feat: enhance host API authentication handling and add regression tests

This commit is contained in:
duanshuwen
2026-04-23 19:09:30 +08:00
parent 71bcc3b3c5
commit c9617a3777
10 changed files with 471 additions and 127 deletions

View File

@@ -11,6 +11,7 @@ import {
} from './route-utils';
const DEFAULT_HOST_API_PORT = 13210;
const HOST_API_UNAUTHORIZED_CODE = 'HOST_API_UNAUTHORIZED';
type StartHostApiServerOptions = {
ctx: HostApiContext;
@@ -50,21 +51,19 @@ export function startHostApiServer(options: StartHostApiServerOptions): Server {
return;
}
const bearerHeader = req.headers.authorization || '';
const bearerToken = bearerHeader.startsWith('Bearer ')
? bearerHeader.slice('Bearer '.length)
: '';
const token = (
req.headers['x-host-api-token']
|| requestUrl.searchParams.get('token')
|| bearerToken
);
const headerToken = req.headers['x-host-api-token'];
const token = typeof headerToken === 'string'
? headerToken
: Array.isArray(headerToken)
? headerToken[0]
: (requestUrl.searchParams.get('token') || '');
if (token !== hostApiToken) {
sendJsonResponse(res, 401, {
success: false,
ok: false,
error: 'Unauthorized',
code: HOST_API_UNAUTHORIZED_CODE,
error: 'Host API authentication failed',
});
return;
}