fix(onebot): hot-reload HTTP server accessToken without re-binding

`HttpServerAdapter.startServer` baked `accessToken` into the
`createServer` callback's closure, then relied on
`bindingSignature` including the token to trigger a
`close()`+`open()` round-trip on every change. Two problems:

  1. The three sibling adapters (`ws-server`, `http-post`,
     `ws-client`) all read `this.config.accessToken` inline at the
     point of use, so the HTTP-server's closure-capture pattern was
     the odd one out.
  2. `server.close()` is asynchronous; the immediately-following
     `server.listen()` on the same port can race with the OS
     releasing it. When it loses, the new listener fails with
     EADDRINUSE (logged via `server.on('error', …)` but not bubbled
     up), the old server is gone, and the operator's `reload` looks
     successful while the endpoint is actually broken — which lines
     up with the "token didn't hot-reload" reports.

Drop the closure capture: `handleRequest` reads
`this.config.path` and `this.config.accessToken` fresh per request
(`reload()` already replaces `this.config` in place via
`structuredClone(next)`). Remove `accessToken` from
`bindingSignature` so a token change no longer triggers a port
re-bind. `host`/`port`/`path` stay in the signature because Node's
`Server.listen()` binds the socket on those.

Four hot-reload tests pin the new contract: token swap, clearing
to empty, setting from empty, and "token-only change returns
`NetworkReloadType.Normal`" (no Reopened/Closed). All four hit a
single OS-assigned port and verify the port is unchanged after
reload — a re-bind would either land on a different port or fail.

core: 613/613 tests pass (+4), typecheck clean.
This commit is contained in:
DrSmoothl committed 2026-05-19 11:16:54 +08:00
1 parent 76b87f6b27
commit d821336943
2 files changed
+162 -7

No files matched your search

@@ -79,11 +79,8 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ }
private startServer(): void {
const expectedPath = normalizePath(this.config.path ?? '/');
const accessToken = this.config.accessToken ?? '';
const server = createServer((req, res) => {
void this.handleRequest(expectedPath, accessToken, req, res);
void this.handleRequest(req, res);
});
this.server = server;
@@ -93,7 +90,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
this.name,
this.config.host ?? '0.0.0.0',
this.config.port,
expectedPath,
normalizePath(this.config.path ?? '/'),
);
});
server.on('error', (err) => {
@@ -103,7 +100,15 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
server.listen(this.config.port, this.config.host ?? '0.0.0.0');
}
private async handleRequest(expectedPath: string, accessToken: string, req: IncomingMessage, res: ServerResponse): Promise<void> {
private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
// Read `path` + `accessToken` fresh from `this.config` on every
// request so config hot-reloads (`reload()` overwrites `this.config`
// in place) take effect on the very next request without
// re-binding the listener. Matches the ws-server / http-post /
// ws-client adapters, which all read `this.config.accessToken`
// inline at the point of use.
const expectedPath = normalizePath(this.config.path ?? '/');
const accessToken = this.config.accessToken ?? '';
const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1');
const incomingPath = parsedUrl.pathname;
@@ -224,7 +229,16 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
}
function bindingSignature(net: HttpServerNetwork): string {
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}#${net.accessToken ?? ''}`;
// `accessToken` deliberately omitted: it's read per-request from
// `this.config`, so a token change doesn't need to re-bind the
// listener. Including it here would cause a `close()` + `listen()`
// round trip on every token edit — a needless port-rebind that, on
// some hosts, races with the OS releasing the port and lands the
// server in a half-broken state where the old token still
// authenticates because the EADDRINUSE-failing new server never
// replaced the old one. `host`/`port`/`path` still gate a restart
// because Node's HTTP `Server.listen()` binds the socket on those.
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}`;
}
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
@@ -0,0 +1,141 @@
// Hot-reload tests for HttpServerAdapter — pins the contract that
// `reload({ accessToken: <new> })` must take effect on the very next
// request without the listener being torn down. Earlier the adapter
// captured `accessToken` into a `startServer()` closure and relied on
// `bindingSignature` to trigger a `close()` + `open()` round-trip on
// token change; that race-prone path is gone and `handleRequest` now
// reads `this.config.accessToken` per request.
import { describe, expect, it, vi, afterEach } from 'vitest';
import http from 'http';
import type { AddressInfo } from 'net';
import { HttpServerAdapter } from '../src/onebot/network/http-server-adapter';
import { NetworkReloadType, type NetworkAdapterContext } from '../src/onebot/network/adapter';
import type { HttpServerNetwork } from '../src/onebot/types';
function fakeCtx(): NetworkAdapterContext {
return {
uin: '10001',
api: {
handle: vi.fn(async () => ({ status: 'ok', retcode: 0, data: { online: true } })),
} as any,
buildLifecycleEvent: vi.fn(() => ({})),
buildHeartbeatEvent: vi.fn(() => ({})),
};
}
function get(port: number, path: string, headers: Record<string, string> = {}): Promise<{ status: number }> {
return new Promise((resolve, reject) => {
const req = http.request(
{ hostname: '127.0.0.1', port, path, method: 'GET', headers },
(res) => {
res.on('data', () => { /* drain */ });
res.on('end', () => resolve({ status: res.statusCode! }));
},
);
req.on('error', reject);
req.end();
});
}
// Wait until the underlying http.Server has bound its port; tests that
// hit the socket too early get ECONNREFUSED on slow CI hosts.
async function waitForListen(adapter: HttpServerAdapter): Promise<number> {
for (let i = 0; i < 50; i++) {
const server = (adapter as any).server as http.Server | null;
const addr = server?.address() as AddressInfo | null | undefined;
if (addr && typeof addr === 'object') return addr.port;
await new Promise((r) => setTimeout(r, 20));
}
throw new Error('http server never started listening');
}
describe('HttpServerAdapter — accessToken hot reload', () => {
let adapter: HttpServerAdapter | null = null;
afterEach(() => {
adapter?.close();
adapter = null;
});
it('a swapped accessToken authorizes the new token on the next request — no listener re-bind', async () => {
const ctx = fakeCtx();
// port=0 → OS-assigned; the swap proves no re-bind happens because
// a re-bind would land on a different port and `waitForListen`
// would diverge from the original.
const config: HttpServerNetwork = {
name: 'hot', port: 0, enabled: true, accessToken: 'tok-1',
messageFormat: 'array', reportSelfMessage: false,
};
adapter = new HttpServerAdapter('hot', config, ctx);
adapter.open();
const portBefore = await waitForListen(adapter);
// Sanity: old token authorizes, anything else 401s.
expect((await get(portBefore, '/', { authorization: 'Bearer tok-1' })).status).toBe(200);
expect((await get(portBefore, '/', { authorization: 'Bearer tok-2' })).status).toBe(401);
// Hot-swap the token.
await adapter.reload({ ...config, accessToken: 'tok-2' });
// Same port (no re-bind) — and the new token must take effect on
// the very next request.
const portAfter = ((adapter as any).server as http.Server).address() as AddressInfo;
expect(portAfter.port).toBe(portBefore);
expect((await get(portBefore, '/', { authorization: 'Bearer tok-1' })).status).toBe(401);
expect((await get(portBefore, '/', { authorization: 'Bearer tok-2' })).status).toBe(200);
});
it('clearing accessToken to empty disables auth on the next request', async () => {
const ctx = fakeCtx();
const config: HttpServerNetwork = {
name: 'hot-clear', port: 0, enabled: true, accessToken: 'tok-1',
messageFormat: 'array', reportSelfMessage: false,
};
adapter = new HttpServerAdapter('hot-clear', config, ctx);
adapter.open();
const port = await waitForListen(adapter);
expect((await get(port, '/')).status).toBe(401); // no token header → 401
await adapter.reload({ ...config, accessToken: '' });
expect((await get(port, '/')).status).toBe(200); // auth disabled
});
it('setting accessToken from empty enforces auth on the next request', async () => {
const ctx = fakeCtx();
const config: HttpServerNetwork = {
name: 'hot-add', port: 0, enabled: true,
messageFormat: 'array', reportSelfMessage: false,
};
adapter = new HttpServerAdapter('hot-add', config, ctx);
adapter.open();
const port = await waitForListen(adapter);
expect((await get(port, '/')).status).toBe(200); // no auth configured
await adapter.reload({ ...config, accessToken: 'tok-new' });
expect((await get(port, '/')).status).toBe(401); // auth now required
expect((await get(port, '/', { authorization: 'Bearer tok-new' })).status).toBe(200);
});
it('changing only accessToken returns NetworkReloadType.Normal — no Reopened/Closed', async () => {
const ctx = fakeCtx();
const config: HttpServerNetwork = {
name: 'hot-type', port: 0, enabled: true, accessToken: 'a',
messageFormat: 'array', reportSelfMessage: false,
};
adapter = new HttpServerAdapter('hot-type', config, ctx);
adapter.open();
await waitForListen(adapter);
const reloadType = await adapter.reload({ ...config, accessToken: 'b' });
// Without re-binding, the adapter reports `Normal` — anything but
// `Reopened` / `Closed` is acceptable; we mostly care that nothing
// touched the listener.
expect(reloadType).toBe(NetworkReloadType.Normal);
});
});