From a24d4c906f231f893e56c3b263468dda5f5d9968 Mon Sep 17 00:00:00 2001 From: Florian Date: Mon, 16 Nov 2026 09:48:13 +0100 Subject: [PATCH] fix(api): mint one-time tokens only from the mobile handoff route Better Auth's generate endpoint answered any client with a session cookie, past the origin check and PKCE binding of /mobile-auth/issue. It now refuses client requests, and the handoff route refuses impersonation sessions. --- apps/api/src/auth-postgres.test.ts | 17 +++++++++++ apps/api/src/auth.ts | 6 ++-- apps/api/src/routes/mobile-auth.test.ts | 30 ++++++++++++++++---- apps/api/src/routes/mobile-auth.ts | 5 +++- docs/docs/administration/users-and-access.md | 3 +- docs/docs/developer/mobile-architecture.md | 5 +++- 6 files changed, 56 insertions(+), 10 deletions(-) diff --git a/apps/api/src/auth-postgres.test.ts b/apps/api/src/auth-postgres.test.ts index 31063b71e..c97268a66 100644 --- a/apps/api/src/auth-postgres.test.ts +++ b/apps/api/src/auth-postgres.test.ts @@ -566,6 +566,23 @@ describeDatabase("production authentication on migrated PostgreSQL", () => { ).toMatchObject({ email: targetEmail }); }); + it("mints one-time tokens only from server calls", async () => { + const { cookie } = await verifiedUser("one-time-token@example.test"); + + const direct = await request("/api/auth/one-time-token/generate", undefined, cookie); + expect(direct.statusCode, direct.body).toBe(400); + expect(direct.json()).toMatchObject({ message: "Client requests are disabled" }); + + const generated = await auth.api.generateOneTimeToken({ headers: new Headers({ cookie }) }); + expect(typeof generated.token).toBe("string"); + + const verified = await request("/api/auth/one-time-token/verify", { token: generated.token }); + expect(verified.statusCode, verified.body).toBe(200); + expect( + verified.cookies.some((entry) => entry.name.includes("session_token") && entry.value), + ).toBe(true); + }); + it("refuses reserved .invalid addresses at sign-up without revealing existing placeholders", async () => { // Fixture input: the account an OpenStreetMap sign-in would already own. await fixture.db.insert(user).values({ diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts index 42e91860c..755f9292e 100644 --- a/apps/api/src/auth.ts +++ b/apps/api/src/auth.ts @@ -395,8 +395,10 @@ function createPolicyAuth( // becomes a session in the WebView. Two minutes and single-use because the // token is in flight from the handoff exchange to the WebView, and the only // legitimate holder redeems it immediately. Stored hashed so a database - // read never yields a usable token. - oneTimeToken({ expiresIn: 2, storeToken: "hashed" }), + // read never yields a usable token. Browsers cannot call the generate + // endpoint: only `/mobile-auth/issue` mints a token, server-side, after + // its origin check and with the token bound to a PKCE handoff. + oneTimeToken({ expiresIn: 2, storeToken: "hashed", disableClientRequest: true }), emailHarmony({ allowNormalizedSignin: true }), passkey({ rpID: envString("PASSKEY_RP_ID", "localhost"), diff --git a/apps/api/src/routes/mobile-auth.test.ts b/apps/api/src/routes/mobile-auth.test.ts index 6efe90ff4..f3083be78 100644 --- a/apps/api/src/routes/mobile-auth.test.ts +++ b/apps/api/src/routes/mobile-auth.test.ts @@ -8,9 +8,14 @@ const SECOND_WEB_ORIGIN = "https://maps.openmapx.test"; /** What the mocked Better Auth returns for this request. */ const authState: { - session: { user: { id: string } } | null; + session: { user: { id: string }; session: { impersonatedBy: string | null } } | null; token: string | null; -} = { session: { user: { id: "user-A" } }, token: "ott-value" }; + generated: number; +} = { + session: { user: { id: "user-A" }, session: { impersonatedBy: null } }, + token: "ott-value", + generated: 0, +}; /** What the mocked handoff service returns, and what it was asked. */ const handoff: { @@ -24,8 +29,10 @@ vi.mock("../auth.js", () => ({ auth: { api: { getSession: async () => authState.session, - generateOneTimeToken: async () => - authState.token === null ? null : { token: authState.token }, + generateOneTimeToken: async () => { + authState.generated += 1; + return authState.token === null ? null : { token: authState.token }; + }, }, }, })); @@ -65,8 +72,9 @@ afterAll(async () => { }); beforeEach(() => { - authState.session = { user: { id: "user-A" } }; + authState.session = { user: { id: "user-A" }, session: { impersonatedBy: null } }; authState.token = "ott-value"; + authState.generated = 0; handoff.issue = { ok: true, callbackCode: "code-value", expiresAtMs: 1_700_000_120_000 }; handoff.exchange = { ok: true, oneTimeToken: "ott-value" }; handoff.issued = []; @@ -154,6 +162,18 @@ describe("POST /mobile-auth/issue", () => { expect(handoff.issued).toEqual([]); }); + it("refuses an administrator impersonation session before minting a token", async () => { + authState.session = { user: { id: "user-A" }, session: { impersonatedBy: "admin-1" } }; + + const response = await issue(validIssue); + + expect(response.statusCode).toBe(403); + expect(response.json()).toEqual({ error: "invalid_request" }); + expectMobilePrivacy(response); + expect(authState.generated).toBe(0); + expect(handoff.issued).toEqual([]); + }); + it("refuses a cross-origin caller", async () => { const response = await issue(validIssue, { origin: "https://evil.example" }); diff --git a/apps/api/src/routes/mobile-auth.ts b/apps/api/src/routes/mobile-auth.ts index 502218d82..46b4db016 100644 --- a/apps/api/src/routes/mobile-auth.ts +++ b/apps/api/src/routes/mobile-auth.ts @@ -127,7 +127,9 @@ export const mobileAuthRoute: FastifyPluginAsync = async (fastify) => { * Called by the fixed-origin system-browser page, after a session exists. * * The one-time token is minted here rather than in the browser so it never - * appears in a page the user can be persuaded to read out. + * appears in a page the user can be persuaded to read out. An administrator + * impersonating an account is refused: the token would carry that support + * session onto a device. */ fastify.post<{ Body: IssueBody }>( "/mobile-auth/issue", @@ -146,6 +148,7 @@ export const mobileAuthRoute: FastifyPluginAsync = async (fastify) => { const session = await auth.api.getSession({ headers: fromNodeHeaders(request.headers) }); if (!session) return reply.code(401).send({ error: "authentication_required" }); + if (session.session.impersonatedBy) return reply.code(403).send({ error: "invalid_request" }); const generated = await auth.api.generateOneTimeToken({ headers: fromNodeHeaders(request.headers), diff --git a/docs/docs/administration/users-and-access.md b/docs/docs/administration/users-and-access.md index c5b89d572..53144e179 100644 --- a/docs/docs/administration/users-and-access.md +++ b/docs/docs/administration/users-and-access.md @@ -183,7 +183,8 @@ target user and can expose their personal data. Stop impersonation to return to your administrator session. The list prevents impersonating yourself. An impersonation session cannot change the target's email, passkeys, linked -providers, password or second factor, and cannot delete the account. Use the +providers, password or second factor, cannot delete the account and cannot +sign the mobile app in as the target. Use the dedicated administrator actions for those changes. ### Delete diff --git a/docs/docs/developer/mobile-architecture.md b/docs/docs/developer/mobile-architecture.md index d73bb6ed8..1ec2982b5 100644 --- a/docs/docs/developer/mobile-architecture.md +++ b/docs/docs/developer/mobile-architecture.md @@ -464,7 +464,10 @@ deployment's trusted web origins (`CORS_ORIGIN`); there is no separate mobile origin setting. A native client can forge `Origin`, so this check keeps browsers on other sites out; it does not authenticate the app. An intercepted code cannot be redeemed without its -verifier; concurrent redemptions cannot both succeed. +verifier; concurrent redemptions cannot both succeed. Better Auth's +`/one-time-token/generate` endpoint refuses browser requests, so only `issue` +mints a one-time token, after its origin check and bound to the PKCE handoff. +`issue` also refuses an administrator impersonation session. The page receives the code, state and verifier through the bounded result, exchanges them for a Better Auth one-time token, then verifies that token to set