Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions apps/api/src/auth-postgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
6 changes: 4 additions & 2 deletions apps/api/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
30 changes: 25 additions & 5 deletions apps/api/src/routes/mobile-auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand All @@ -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 };
},
},
},
}));
Expand Down Expand Up @@ -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 = [];
Expand Down Expand Up @@ -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" });

Expand Down
5 changes: 4 additions & 1 deletion apps/api/src/routes/mobile-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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),
Expand Down
3 changes: 2 additions & 1 deletion docs/docs/administration/users-and-access.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion docs/docs/developer/mobile-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading