Skip to content

Commit 4aceae5

Browse files
fix(plugin-auth): an unconfigured auth origin ends on the port the server bound, not the port it was asked for (#32194)
Fixes #31948 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:没有配置认证地址时,认证模块改在服务器真正开始监听之后(`kernel:listening`)再读取端口,并把认证地址改成服务器实际监听的端口。如果启动期间认证实例已经按旧地址建好,就丢弃它,下次使用时按正确地址重建。 - 为什么改:用 `objectstack dev -p 0`,或开发服务器因端口被占自动换端口时,认证地址停在 `http://localhost:0` 或 `http://localhost:3000`,邀请链接、登录和重置密码邮件都指向一个没人监听的端口。 - 风险与回滚:只影响「没有配置认证地址」的开发场景。已配置的地址(包括 `http://localhost`)照原样保留,不受影响。回滚即还原这一个提交。 - 先看:`packages/plugins/plugin-auth/src/auth-plugin.ts` 中 `kernel:listening` 那一段,风险点是用 `applyConfigPatch` 替换 `setRuntimeBaseUrl`,它会丢弃已建好的认证实例;其次看 `auth-plugin.test.ts` 末尾新增的真实启动测试。 - 两分钟验证:`pnpm --filter @objectstack/plugin-auth exec vitest run src/auth-plugin.test.ts -t 'transport bound'`,预期 4 个用例全部通过;把修复还原后,其中 3 个会失败,失败信息是 `localhost:0` 或 `localhost:3000` 与实际端口不符。 - 需要你做的:无,席位落地。 ## What changes With no auth base URL configured, `AuthPlugin` corrected the port from its `kernel:ready` hook by calling `httpServer.getPort()`. The transport opens its socket later, on `kernel:listening`: `HonoServerPlugin` registers that handler in its own `start()`, and the kernel fires `kernel:listening` only after every `kernel:ready` and `kernel:bootstrapped` handler (`packages/core/src/kernel.ts`, phases 3 to 4; the contract text is in `packages/spec/src/contracts/plugin-lifecycle-events.ts`). So on `kernel:ready` the adapter answers the REQUESTED port (`listeningPort || port`): `0` for `--port 0`, and the busy port for a dev server about to shift off it. `if (actualPort)` then skipped the correction for `0`, and the origin stayed `http://localhost:0` or `http://localhost:3000`. The fix stays inside the port-correction region of `auth-plugin.ts`: 1. The existing `kernel:ready` handler now registers the correction as a `kernel:listening` handler. A handler registered during `kernel:ready` is appended after every `start()`-registered `kernel:listening` handler, the transport's `listen` included, so it reads the bound port whichever plugin was used first. No producer change and no new event was needed: the ordering already exists in the kernel's phases. 2. The correction goes through `authManager.applyConfigPatch({ baseUrl })` instead of `setRuntimeBaseUrl`. Measured: on every real boot, something in `kernel:ready` has already built the better-auth instance by `kernel:listening`. `setRuntimeBaseUrl` then logs `called after the auth instance was already created — ignoring` and changes nothing. `applyConfigPatch` discards the built or in-flight instance (its documented contract), so the next caller rebuilds it on the bound origin. 3. The `baseUrlDefaulted` doc comment now says `kernel:listening` where it said `kernel:ready`. Its ruling text is otherwise unchanged: a configured base URL, `http://localhost` included, is kept as written (PR #31946). The configured-versus-defaulted predicate (`baseUrlConfigured`) and the localhost-only guard are unchanged. ## Tests - New top-level `describe` in `auth-plugin.test.ts` (the component's harness file), which boots a real `ObjectKernel` with in-memory SQLite, `ObjectQLPlugin`, the real `HonoServerPlugin({ port: 0 })` (aliased to source) and the real `AuthPlugin`: - no base URL: the origin ends on the bound port; - the `os dev -p 0` shape (`http://localhost:0`, `baseUrlDefaulted: true`) with auth used BEFORE the server: the bound port; - a better-auth instance built from a `kernel:ready` hook (the dev admin seed's position): `instance.options.baseURL` is the bound origin; - CONTROL: a configured `http://localhost` is kept as written, both the console URL and the instance's `baseURL`. - The existing mock-server cases now drive `kernel:listening` after `kernel:ready` and spy on `applyConfigPatch`. Without that, their "not called" controls would pass vacuously. - RED on the unfixed source: 3 of 4 new cases fail (`expected 'http://localhost:3000/_console/login' to be 'http://localhost:44627/_console/login'`, `'http://localhost:0/…'`, and `'http://localhost:0'` for the instance); the control passes. ## Acceptance notes - The same timing defect also covered the other case named in the doc comment, a dev server that shifted off a busy port: `getPort()` answered the busy port on `kernel:ready`, too. This change covers that case on the same path. No separate pin was added, because occupying a fixed port in a test is flaky. - `AuthManager.setRuntimeBaseUrl`'s JSDoc still says it is "typically called from a `kernel:ready` hook where the actual server port is known". Its one caller is the correction this change moves, and nothing else in the workspace calls it now. `auth-manager.ts` is outside this card's file surface, so it is left for its owner. - The CLI's own trusted-origin entry for the base URL is computed from the requested port (`resolveAuthBaseUrl(port, …)` in `serve.ts`). In dev, `http://localhost:*` is trusted alongside it, so nothing is refused, and it is not touched here. - Not driven through the CLI door (`objectstack dev --fresh -p 0`): that needs the whole CLI build closure. The pin boots the same kernel, the same transport plugin and the same auth plugin that `os serve` composes. ## Verification All local readings are on head `56d75889` (after one `git merge origin/main`; the merge touched no `packages/` path). <details><summary>Ablation (fix reverted, pin red, restored)</summary> - Leg 1: `auth-plugin.ts` restored to base `0f7389cc` (on disk: `kernel:listening` hook count 0, `setRuntimeBaseUrl(actualUrl)` count 1). Result: `Tests 3 failed | 1 passed`. Restore: `git checkout HEAD --`, then hash `a1d5bb3e` equal to the HEAD blob, `git diff HEAD` empty. - Leg 2: `node scripts/ablation-replace.mjs` replaced `applyConfigPatch({ baseUrl: actualUrl })` with `setRuntimeBaseUrl(actualUrl)` (anchor 1 to 0, blob `a1d5bb3e` to `26c06211`). Result: `Tests 3 failed | 1 passed`, with the `setRuntimeBaseUrl() called after the auth instance was already created — ignoring` warning on all three legs. The tool then restored the file (blob equal to HEAD). - Neither leg needed a rebuild: the subject is imported from source (relative), and `@objectstack/plugin-hono-server` is aliased to `src/`. </details> <details><summary>Package suite and typecheck</summary> - `pnpm --filter @objectstack/plugin-auth test`: `Test Files 255 passed (255)`, `Tests 4591 passed | 10 skipped (4601)`. - `pnpm --filter @objectstack/plugin-auth typecheck` (after `build`): exit 0, `check:test-typecheck: OK — 10 file(s) / 72 error(s) / 23 pinned signature(s) held`. - File weight: `auth-plugin.test.ts` import time is 16.0–17.7 s with the new imports, against 16.5 s for the base file. The new cases add about 1.6 s of test time. </details> <details><summary>Derived gates</summary> - `node scripts/pm/dispatch-gates.mjs --commands`: 75 commands. Reconciled with `--ran`: `75 derived, 74 run, 1 NOT-MEASURED, 0 UNRUN`. - NOT MEASURED: `pnpm check:dual-build-cjs-loads`, exit 3 `PREREQUISITE NOT MET` (it needs every package's `dist/`). CI runs it. - `node scripts/check-plugin-teardown-shape.mjs --self-test` first exited 3 because the shallow checkout could not reach its pinned fixture commit. After fetching that one commit it passed (`48 cases pass`). - All other derived commands exited 0. - `pnpm lint` (repo-wide, `eslint . --no-inline-config`): finished with no diagnostics. Its exit code was not captured by the background wrapper, so the same eslint on the two changed files was run again with the code captured: exit 0, no output. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_012dn2Ae4fomvXPZ2AioCpY4)_ --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 5430b4a commit 4aceae5

3 files changed

Lines changed: 179 additions & 26 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(plugin-auth): an unconfigured auth origin now ends on the port the HTTP server actually bound
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
With no auth base URL configured (`objectstack dev -p 0`, or a dev server that moved off a busy port), the auth origin used to stay on the requested port, `http://localhost:0` or `http://localhost:3000`, while the server listened on another one. Invite links, sign-in and password-reset mail then pointed at a port nothing served. The port is now read on `kernel:listening`, after the transport has bound it. A better-auth instance that a `kernel:ready` hook had already built on the old origin, such as the development admin seed's, is discarded and rebuilt on the bound origin at its next use. A configured base URL, `http://localhost` included, is still kept exactly as written.

‎packages/plugins/plugin-auth/src/auth-plugin.test.ts‎

Lines changed: 148 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,11 @@ import { AuthPlugin } from './auth-plugin';
55
import type { AuthPluginOptions } from './auth-plugin';
66
import { AuthManager } from './auth-manager';
77
import { invitationAcceptPath } from './invitation-link-action';
8-
import type { PluginContext } from '@objectstack/core';
9-
import { assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/objectql';
8+
import { ObjectKernel } from '@objectstack/core';
9+
import type { Plugin, PluginContext } from '@objectstack/core';
10+
import { ObjectQLPlugin, assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/objectql';
11+
import { SqlDriver } from '@objectstack/driver-sql';
12+
import { HonoServerPlugin } from '@objectstack/plugin-hono-server';
1013
import { bindCatalogFromTables } from './__tests__/security-catalog.testkit.js';
1114
import { SettingsService, brandingSettingsManifest } from '@objectstack/service-settings';
1215

@@ -410,12 +413,13 @@ describe('AuthPlugin', () => {
410413

411414
// Host-defaulted base URL on port 3000, but server will be on 3002
412415
const registeredAuthManager = (mockContext.registerService as any).mock.calls[0][1];
413-
const setRuntimeSpy = vi.spyOn(registeredAuthManager, 'setRuntimeBaseUrl');
416+
const baseUrlPatchSpy = vi.spyOn(registeredAuthManager, 'applyConfigPatch');
414417

415418
await localPlugin.start(mockContext);
416419
await localHookCapture.trigger('kernel:ready');
420+
await localHookCapture.trigger('kernel:listening');
417421

418-
expect(setRuntimeSpy).toHaveBeenCalledWith('http://localhost:3002');
422+
expect(baseUrlPatchSpy).toHaveBeenCalledWith({ baseUrl: 'http://localhost:3002' });
419423
expect(mockContext.logger.info).toHaveBeenCalledWith(
420424
expect.stringContaining('Auth baseUrl auto-updated to http://localhost:3002'),
421425
);
@@ -445,12 +449,13 @@ describe('AuthPlugin', () => {
445449
});
446450

447451
const registeredAuthManager = (mockContext.registerService as any).mock.calls[0][1];
448-
const setRuntimeSpy = vi.spyOn(registeredAuthManager, 'setRuntimeBaseUrl');
452+
const baseUrlPatchSpy = vi.spyOn(registeredAuthManager, 'applyConfigPatch');
449453

450454
await localPlugin.start(mockContext);
451455
await localHookCapture.trigger('kernel:ready');
456+
await localHookCapture.trigger('kernel:listening');
452457

453-
expect(setRuntimeSpy).not.toHaveBeenCalled();
458+
expect(baseUrlPatchSpy).not.toHaveBeenCalled();
454459
});
455460

456461
it('should auto-detect baseUrl when no baseUrl configured (uses default fallback)', async () => {
@@ -477,12 +482,13 @@ describe('AuthPlugin', () => {
477482
});
478483

479484
const registeredAuthManager = (mockContext.registerService as any).mock.calls[0][1];
480-
const setRuntimeSpy = vi.spyOn(registeredAuthManager, 'setRuntimeBaseUrl');
485+
const baseUrlPatchSpy = vi.spyOn(registeredAuthManager, 'applyConfigPatch');
481486

482487
await localPlugin.start(mockContext);
483488
await localHookCapture.trigger('kernel:ready');
489+
await localHookCapture.trigger('kernel:listening');
484490

485-
expect(setRuntimeSpy).toHaveBeenCalledWith('http://localhost:3002');
491+
expect(baseUrlPatchSpy).toHaveBeenCalledWith({ baseUrl: 'http://localhost:3002' });
486492
});
487493

488494
it('should throw error if auth not initialized', async () => {
@@ -2231,14 +2237,14 @@ describe('AuthPlugin', () => {
22312237
* A configured base URL is the deployment's public origin and is kept as
22322238
* written. Only a base URL nobody configured (no `baseUrl` option, or one the
22332239
* host filled from its own loopback fallback and marked `baseUrlDefaulted`)
2234-
* has its port corrected to the one the HTTP server bound on `kernel:ready`.
2240+
* has its port corrected to the one the HTTP server bound, on `kernel:listening`.
22352241
* Behind a proxy (`OS_AUTH_URL=http://localhost`, app on :3000) a corrected
22362242
* origin would send invite links and auth mail to the unpublished port.
22372243
*/
22382244
describe('AuthPlugin base URL port correction honours a configured origin', () => {
22392245
const SECRET = 'test-secret-at-least-32-chars-long';
22402246

2241-
/** Boots the plugin through `kernel:ready` against a server bound to `boundPort`. */
2247+
/** Boots the plugin through `kernel:listening` against a server bound to `boundPort`. */
22422248
async function bootAgainstPort(options: AuthPluginOptions, boundPort: number) {
22432249
const handlers = new Map<string, Array<() => Promise<void>>>();
22442250
const registered = new Map<string, any>();
@@ -2268,42 +2274,164 @@ describe('AuthPlugin base URL port correction honours a configured origin', () =
22682274
const plugin = new AuthPlugin({ secret: SECRET, ...options });
22692275
await plugin.init(ctx);
22702276
const authManager = registered.get('auth') as AuthManager;
2271-
const setRuntimeBaseUrl = vi.spyOn(authManager, 'setRuntimeBaseUrl');
2277+
const baseUrlPatch = vi.spyOn(authManager, 'applyConfigPatch');
22722278
await plugin.start(ctx);
22732279
for (const h of handlers.get('kernel:ready') ?? []) await h();
2274-
return { authManager, setRuntimeBaseUrl };
2280+
// The correction is registered FROM `kernel:ready`, so it is read after.
2281+
for (const h of handlers.get('kernel:listening') ?? []) await h();
2282+
return { authManager, baseUrlPatch };
22752283
}
22762284

22772285
it('keeps a configured http://localhost as written: the invite link carries no bound port', async () => {
2278-
const { authManager, setRuntimeBaseUrl } = await bootAgainstPort({ baseUrl: 'http://localhost' }, 3000);
2286+
const { authManager, baseUrlPatch } = await bootAgainstPort({ baseUrl: 'http://localhost' }, 3000);
22792287

2280-
expect(setRuntimeBaseUrl).not.toHaveBeenCalled();
2288+
expect(baseUrlPatch).not.toHaveBeenCalled();
22812289
expect(authManager.getConsoleUrl(invitationAcceptPath('inv_1')))
22822290
.toBe(`http://localhost/_console${invitationAcceptPath('inv_1')}`);
22832291
expect(authManager.getConsoleUrl('/login')).toBe('http://localhost/_console/login');
22842292
});
22852293

22862294
it('keeps a configured http://localhost:4000 on a server bound to 3000', async () => {
2287-
const { authManager, setRuntimeBaseUrl } = await bootAgainstPort({ baseUrl: 'http://localhost:4000' }, 3000);
2295+
const { authManager, baseUrlPatch } = await bootAgainstPort({ baseUrl: 'http://localhost:4000' }, 3000);
22882296

2289-
expect(setRuntimeBaseUrl).not.toHaveBeenCalled();
2297+
expect(baseUrlPatch).not.toHaveBeenCalled();
22902298
expect(authManager.getConsoleUrl('/login')).toBe('http://localhost:4000/_console/login');
22912299
});
22922300

22932301
it('CONTROL: a host-defaulted base URL is still corrected to the bound port', async () => {
2294-
const { authManager, setRuntimeBaseUrl } = await bootAgainstPort(
2302+
const { authManager, baseUrlPatch } = await bootAgainstPort(
22952303
{ baseUrl: 'http://localhost:0', baseUrlDefaulted: true },
22962304
41303,
22972305
);
22982306

2299-
expect(setRuntimeBaseUrl).toHaveBeenCalledWith('http://localhost:41303');
2307+
expect(baseUrlPatch).toHaveBeenCalledWith({ baseUrl: 'http://localhost:41303' });
23002308
expect(authManager.getConsoleUrl('/login')).toBe('http://localhost:41303/_console/login');
23012309
});
23022310

23032311
it('CONTROL: no base URL at all is still corrected to the bound port', async () => {
2304-
const { authManager, setRuntimeBaseUrl } = await bootAgainstPort({}, 3002);
2312+
const { authManager, baseUrlPatch } = await bootAgainstPort({}, 3002);
23052313

2306-
expect(setRuntimeBaseUrl).toHaveBeenCalledWith('http://localhost:3002');
2314+
expect(baseUrlPatch).toHaveBeenCalledWith({ baseUrl: 'http://localhost:3002' });
23072315
expect(authManager.getConsoleUrl('/login')).toBe('http://localhost:3002/_console/login');
23082316
});
23092317
});
2318+
2319+
/**
2320+
* The port correction above, on a REAL boot: a real kernel, the real
2321+
* `HonoServerPlugin` on `port: 0`, and the real `AuthPlugin`.
2322+
*
2323+
* The transport opens its socket on `kernel:listening`, which fires after every
2324+
* `kernel:ready` handler. Read on `kernel:ready`, `getPort()` answers the port
2325+
* that was REQUESTED (`0` here), never the one that was bound, so an
2326+
* unconfigured auth origin stayed `http://localhost:0` (or the
2327+
* `http://localhost:3000` default) while the server listened elsewhere. The
2328+
* mock-server cases above cannot see that: their `getPort()` answers the bound
2329+
* port from the start.
2330+
*/
2331+
describe('AuthPlugin corrects an unconfigured base URL to the port the transport bound (real boot)', () => {
2332+
const SECRET = 'test-secret-at-least-32-chars-long';
2333+
let kernel: ObjectKernel | undefined;
2334+
2335+
afterEach(async () => {
2336+
try {
2337+
await kernel?.shutdown();
2338+
} catch {
2339+
/* a refused boot leaves the kernel stopped */
2340+
}
2341+
kernel = undefined;
2342+
});
2343+
2344+
/** Publishes an in-memory SQLite driver the way a datasource plugin does. */
2345+
function sqliteDriverPlugin(): Plugin {
2346+
return {
2347+
name: 'test.driver.sqlite',
2348+
type: 'standard',
2349+
version: '1.0.0',
2350+
async init(ctx: PluginContext) {
2351+
ctx.registerService(
2352+
'driver.default',
2353+
new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }),
2354+
);
2355+
},
2356+
};
2357+
}
2358+
2359+
/**
2360+
* Builds the better-auth instance from a `kernel:ready` hook registered after
2361+
* the auth plugin's own, as the development admin seed's sign-up does on
2362+
* `os dev`: the instance then exists before the server listens.
2363+
*/
2364+
function buildsAuthOnReady(): Plugin {
2365+
return {
2366+
name: 'test.builds-auth-on-ready',
2367+
type: 'standard',
2368+
version: '1.0.0',
2369+
dependencies: ['com.objectstack.auth'],
2370+
async init() {},
2371+
async start(ctx: PluginContext) {
2372+
ctx.hook('kernel:ready', async () => {
2373+
await ctx.getService<AuthManager>('auth').getAuthInstance();
2374+
});
2375+
},
2376+
};
2377+
}
2378+
2379+
async function bootOnPortZero(
2380+
options: AuthPluginOptions,
2381+
opts: { authBeforeServer?: boolean; buildAuthOnReady?: boolean } = {},
2382+
) {
2383+
kernel = new ObjectKernel({ logger: { level: 'silent' } });
2384+
await kernel.use(sqliteDriverPlugin());
2385+
await kernel.use(new ObjectQLPlugin());
2386+
const server = new HonoServerPlugin({ port: 0 });
2387+
const auth = new AuthPlugin({ secret: SECRET, ...options });
2388+
if (opts.authBeforeServer) {
2389+
await kernel.use(auth);
2390+
await kernel.use(server);
2391+
} else {
2392+
await kernel.use(server);
2393+
await kernel.use(auth);
2394+
}
2395+
if (opts.buildAuthOnReady) await kernel.use(buildsAuthOnReady());
2396+
await kernel.bootstrap();
2397+
2398+
const boundPort = kernel.getService<{ getPort(): number }>('http-server').getPort();
2399+
// The window is real: the kernel assigned a port, so `0` was never it.
2400+
expect(boundPort).toBeGreaterThan(0);
2401+
return { boundPort, authManager: kernel.getService<AuthManager>('auth') };
2402+
}
2403+
2404+
it('no base URL at all: the auth origin ends on the bound port', async () => {
2405+
const { boundPort, authManager } = await bootOnPortZero({});
2406+
2407+
expect(authManager.getConsoleUrl('/login')).toBe(`http://localhost:${boundPort}/_console/login`);
2408+
}, 30_000);
2409+
2410+
it('the `os dev -p 0` shape (host-defaulted http://localhost:0), auth used before the server: the bound port', async () => {
2411+
const { boundPort, authManager } = await bootOnPortZero(
2412+
{ baseUrl: 'http://localhost:0', baseUrlDefaulted: true },
2413+
{ authBeforeServer: true },
2414+
);
2415+
2416+
expect(authManager.getConsoleUrl('/login')).toBe(`http://localhost:${boundPort}/_console/login`);
2417+
}, 30_000);
2418+
2419+
it('a better-auth instance built on kernel:ready (the dev admin seed) is rebuilt on the bound origin', async () => {
2420+
const { boundPort, authManager } = await bootOnPortZero(
2421+
{ baseUrl: 'http://localhost:0', baseUrlDefaulted: true },
2422+
{ buildAuthOnReady: true },
2423+
);
2424+
2425+
const instance = (await authManager.getAuthInstance()) as unknown as { options: { baseURL?: string } };
2426+
expect(instance.options.baseURL).toBe(`http://localhost:${boundPort}`);
2427+
expect(authManager.getConsoleUrl('/login')).toBe(`http://localhost:${boundPort}/_console/login`);
2428+
}, 30_000);
2429+
2430+
it('CONTROL: a configured http://localhost is kept as written on the same boot', async () => {
2431+
const { authManager } = await bootOnPortZero({ baseUrl: 'http://localhost' }, { buildAuthOnReady: true });
2432+
2433+
const instance = (await authManager.getAuthInstance()) as unknown as { options: { baseURL?: string } };
2434+
expect(instance.options.baseURL).toBe('http://localhost');
2435+
expect(authManager.getConsoleUrl('/login')).toBe('http://localhost/_console/login');
2436+
}, 30_000);
2437+
});

‎packages/plugins/plugin-auth/src/auth-plugin.ts‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,7 @@ export interface AuthPluginOptions extends Partial<AuthConfig> {
409409
* `http://localhost:<port>` itself.
410410
*
411411
* Only such a base URL, or no `baseUrl` at all, has its port corrected on
412-
* `kernel:ready` to the one the HTTP server actually bound (a dev server that
412+
* `kernel:listening` to the one the HTTP server actually bound (a dev server that
413413
* shifted off a busy port, or `--port 0`). A configured `baseUrl` is the
414414
* deployment's public origin and is kept as written, `http://localhost`
415415
* included: behind a proxy that publishes `http://localhost` while the app
@@ -1568,9 +1568,19 @@ export class AuthPlugin implements Plugin {
15681568
// getPort() is optional on IHttpServer; duck-type check for it.
15691569
const serverWithPort = httpServer as IHttpServer & { getPort?: () => number };
15701570
const baseUrlConfigured = !!this.options.baseUrl && this.options.baseUrlDefaulted !== true;
1571-
if (!baseUrlConfigured && this.authManager && typeof serverWithPort.getPort === 'function') {
1572-
const actualPort = serverWithPort.getPort();
1573-
if (actualPort) {
1571+
const authManager = this.authManager;
1572+
if (!baseUrlConfigured && authManager && typeof serverWithPort.getPort === 'function') {
1573+
// Read the port on `kernel:listening`, not here. The transport
1574+
// opens its socket from a `kernel:listening` handler it registers in
1575+
// its own `start()` (HonoServerPlugin), so on `kernel:ready`
1576+
// `getPort()` answers the REQUESTED port — `0` for `--port 0`, the
1577+
// busy port a dev server is about to shift off — never the bound
1578+
// one. A handler registered from this `kernel:ready` hook lands
1579+
// after every `start()`-registered `kernel:listening` handler, so
1580+
// it reads the bound port whichever plugin was used first.
1581+
ctx.hook('kernel:listening', async () => {
1582+
const actualPort = serverWithPort.getPort!();
1583+
if (!actualPort) return;
15741584
const configuredUrl = this.options.baseUrl || 'http://localhost:3000';
15751585
const configuredOrigin = new URL(configuredUrl).origin;
15761586
const actualUrl = `http://localhost:${actualPort}`;
@@ -1581,12 +1591,17 @@ export class AuthPlugin implements Plugin {
15811591
// with a localhost URL, which would break OAuth callback URLs.
15821592
const configuredIsLocalhost = configuredOrigin.startsWith('http://localhost');
15831593
if (configuredIsLocalhost && configuredOrigin !== actualUrl) {
1584-
this.authManager.setRuntimeBaseUrl(actualUrl);
1594+
// A config patch, not `setRuntimeBaseUrl`: by now a
1595+
// `kernel:ready` hook (the development admin seed's sign-up)
1596+
// may have built the better-auth instance, which
1597+
// `setRuntimeBaseUrl` declines to touch. The patch discards
1598+
// that instance, and the next caller builds it on this origin.
1599+
authManager.applyConfigPatch({ baseUrl: actualUrl });
15851600
ctx.logger.info(
15861601
`Auth baseUrl auto-updated to ${actualUrl} (configured: ${configuredUrl})`,
15871602
);
15881603
}
1589-
}
1604+
});
15901605
}
15911606

15921607
// Route registration errors should propagate (server misconfiguration)

0 commit comments

Comments
 (0)