chore(release): v1.32.11 — native web-handoff login for self-hosted iOS

Self-hosters can sign in to the iOS app through their own domain, so the
password manager files credentials under the right site and passkeys run in
the correct origin. The app opens the instance's own web login inside an
ASWebAuthenticationSession; after an interactive login the server mints a
single-use, PKCE-locked handoff code on a compiled-in custom scheme, which the
app exchanges for the standard native token bundle. The token pair never rides
a URL — only the opaque code does.

Three endpoints mirror the OIDC native handoff and share its mint/consume core,
now extracted to native-handoff.ts (the OIDC leg keeps working unchanged, as
the default flow):

  - GET  /api/auth/native/login    validates the PKCE challenge, sets a
                                   short-lived encrypted state cookie, and
                                   redirects to /auth/login?flow=native.
  - GET  /api/auth/native/complete validates the web session, enforces the
                                   freshness binding, mints the code, and
                                   redirects to healthlog://login-callback.
  - POST /api/auth/native/token    exchanges the code under the cookie-less
                                   native transport gate for the native bundle.

The freshness binding refuses any session older than the flow start, so a
pre-existing browser session can never silently complete a handoff. The start
time is stamped from the database clock (SELECT now()) to stay comparable to
Session.createdAt with no app/DB skew, and createdAt is read through a
dedicated projection so the comparison cannot be silently dropped. A flow
discriminator on the handoff row (migration 0268) makes an OIDC code
non-redeemable at the web-login route and vice versa.

The callback scheme is a compile-time constant with no redirect_uri parameter,
requireAdmin and requireFreshMfa stay cookie-only, and the exchange mints no
wider scope than password login. The state cookie is AES-256-GCM with a fresh
IV. Adds the flow=native login-page banner in all six locales and the three
routes to the OpenAPI contract.
This commit is contained in:
Marc-André Bombeck committed 2026-07-24 02:28:51 +02:00
1 parent d2d79b70a2
commit 0b3280c604
28 files changed
+1976 -197

No files matched your search

@@ -0,0 +1,111 @@
/**
* Structural invariants for the native web-handoff surface (iOS #65).
*
* These are tripwires, not proofs — they assert the load-bearing constructions
* the red-team relied on stay in place: no `redirect_uri` parameter, one
* compile-time callback constant, a trailing-slash public-path entry, the
* cookie-only admin / step-up boundaries, and that the new routes never resolve
* a Bearer token or mint an ApiToken.
*/
import { describe, it, expect } from "vitest";
import { readFileSync } from "node:fs";
import { join } from "node:path";
const SRC = join(process.cwd(), "src");
const read = (rel: string) => readFileSync(join(SRC, rel), "utf8");
/**
* Strip block + line comments so an invariant asserts against CODE, not against
* a doc comment that legitimately names the thing it forbids (e.g. "there is no
* `redirect_uri` parameter").
*/
function code(rel: string): string {
return read(rel)
.replace(/\/\*[\s\S]*?\*\//g, "")
.replace(/(^|[^:])\/\/.*$/gm, "$1");
}
const ROUTE_FILES = [
"app/api/auth/native/login/route.ts",
"app/api/auth/native/complete/route.ts",
"app/api/auth/native/token/route.ts",
];
describe("T6 — open redirect / redirect_uri removed by construction", () => {
it("no new route or handoff module references a redirect_uri parameter", () => {
const files = [
...ROUTE_FILES,
"lib/auth/native-web-handoff.ts",
"lib/auth/native-handoff.ts",
];
// Comments legitimately state "there is no redirect_uri parameter"; the
// invariant is that no CODE reads or builds one.
for (const rel of files) {
expect(code(rel)).not.toMatch(/redirect_uri/);
}
});
it("the callback scheme is a single compile-time constant", () => {
// Defined exactly once, as a string literal, with no interpolation.
const mod = read("lib/auth/native-web-handoff.ts");
expect(mod).toMatch(
/NATIVE_WEB_HANDOFF_REDIRECT_URI\s*=\s*"healthlog:\/\/login-callback"/,
);
// The routes build the Location only through the helper, never a bespoke
// scheme string in code (doc comments naming the scheme are fine).
for (const rel of ROUTE_FILES) {
expect(code(rel)).not.toMatch(/"healthlog:\/\//);
}
});
});
describe("A4 — public-path allowlist carries the trailing slash", () => {
it("proxy admits exactly /api/auth/native/ (slash), never the bare prefix", () => {
const proxy = read("proxy.ts");
expect(proxy).toMatch(/"\/api\/auth\/native\/"/);
// The slashless literal must not appear as its own allowlist entry.
expect(proxy).not.toMatch(/"\/api\/auth\/native"(?!\/)/);
});
});
describe("T12 — the new routes resolve no Bearer and mint no ApiToken", () => {
it("no native route resolves a Bearer token or hand-rolls a tokenHash lookup", () => {
for (const rel of ROUTE_FILES) {
const src = read(rel);
expect(src).not.toMatch(/resolveBearerToken/);
expect(src).not.toMatch(/apiToken\.findUnique/);
}
});
it("no native route creates an ApiToken", () => {
for (const rel of ROUTE_FILES) {
const src = read(rel);
expect(src).not.toMatch(/apiToken\.create\(|issueApiToken\(/);
}
});
});
describe("T11/T13 — cookie-only boundaries and no bundle-in-browser", () => {
it("the token route never sets a cookie itself", () => {
// The bundle rides the JSON body; a Set-Cookie here would be the browser leak.
expect(read("app/api/auth/native/token/route.ts")).not.toMatch(
/cookies\.set|Set-Cookie/,
);
});
it("requireAdmin and requireFreshMfa remain cookie-only (getSession)", () => {
const handler = read("lib/api-handler.ts");
// Both resolve via getSession() (cookie-only) — restated as a tripwire so a
// future edit that threads a Bearer into either trips this test.
const requireAdmin = handler.slice(
handler.indexOf("export async function requireAdmin"),
handler.indexOf("export async function requireAdmin") + 400,
);
expect(requireAdmin).toMatch(/getSession\(\)/);
const requireFresh = handler.slice(
handler.indexOf("export async function requireFreshMfa"),
handler.indexOf("export async function requireFreshMfa") + 400,
);
expect(requireFresh).toMatch(/getSession\(\)/);
});
});
@@ -0,0 +1,193 @@
/**
* GET /api/auth/native/complete — the freshness-bound code mint (iOS #65).
*
* The load-bearing test is the mandatory-refusal one (red-team A3): a STALE
* session (createdAt < startedAt) is refused with a specific reason AND mints no
* code / row. This file is the mutation-check target for the freshness gate
* (flip the comparison in the route → the stale-refusal case goes RED).
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
process.env.ENCRYPTION_KEY = "0".repeat(64);
vi.mock("@/lib/api-handler", () => ({ apiHandler: (fn: unknown) => fn }));
vi.mock("@/lib/rate-limit", () => ({
checkAuthSurfaceRateLimit: vi.fn(),
}));
const validateSessionWithCreatedAt = vi.fn();
vi.mock("@/lib/auth/session", () => ({
validateSessionWithCreatedAt: (v: unknown) => validateSessionWithCreatedAt(v),
SESSION_COOKIE_NAME: "healthlog_session",
}));
// Keep the real shared core (buildHandoffCallbackUrl is used by
// native-web-handoff) but stub the mint so we can assert called / not-called.
vi.mock("@/lib/auth/native-handoff", async (importActual) => {
const actual =
await importActual<typeof import("@/lib/auth/native-handoff")>();
return { ...actual, mintNativeHandoff: vi.fn() };
});
vi.mock("@/lib/db", () => ({
prisma: { session: { delete: vi.fn().mockResolvedValue({}) } },
}));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
import { GET } from "../route";
import { checkAuthSurfaceRateLimit } from "@/lib/rate-limit";
import { mintNativeHandoff } from "@/lib/auth/native-handoff";
import { prisma } from "@/lib/db";
import {
NATIVE_HANDOFF_STATE_COOKIE,
encodeNativeHandoffState,
} from "@/lib/auth/native-web-handoff";
const STARTED_AT = new Date("2026-07-24T10:00:00.000Z");
/** Build a request carrying a valid encrypted state cookie + a session cookie. */
function makeRequest(opts: {
withState?: boolean;
stateValue?: string;
withSession?: boolean;
}): NextRequest {
const r = new NextRequest("http://localhost/api/auth/native/complete");
if (opts.stateValue !== undefined) {
r.cookies.set(NATIVE_HANDOFF_STATE_COOKIE, opts.stateValue);
} else if (opts.withState !== false) {
r.cookies.set(
NATIVE_HANDOFF_STATE_COOKIE,
encodeNativeHandoffState({
appCodeChallenge: "a".repeat(43),
startedAt: STARTED_AT.toISOString(),
}),
);
}
if (opts.withSession !== false) {
r.cookies.set("healthlog_session", "hls_sessionsecret");
}
return r;
}
function sessionCreatedAt(createdAt: Date) {
return {
session: {
id: "sess-1",
createdAt,
expiresAt: new Date(Date.now() + 1000000),
},
user: { id: "user-1", username: "alice" },
};
}
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(checkAuthSurfaceRateLimit).mockResolvedValue({
allowed: true,
ip: "1.2.3.4",
} as never);
vi.mocked(mintNativeHandoff).mockResolvedValue({
code: "hlh_" + "z".repeat(43),
handoffId: "ho-1",
});
});
describe("GET /api/auth/native/complete", () => {
it("fresh session → mints a web_login code and redirects to the scheme", async () => {
// createdAt AFTER startedAt: the user authenticated inside this flow.
validateSessionWithCreatedAt.mockResolvedValue(
sessionCreatedAt(new Date(STARTED_AT.getTime() + 1000)),
);
const res = await GET(makeRequest({}));
const location = res.headers.get("location")!;
expect(location.startsWith("healthlog://login-callback?code=hlh_")).toBe(
true,
);
// The token pair never rides the URL — only the code.
expect(location).not.toContain("token");
expect(location).not.toContain("refresh");
expect(mintNativeHandoff).toHaveBeenCalledWith(
expect.objectContaining({
userId: "user-1",
appCodeChallenge: "a".repeat(43),
flow: "web_login",
}),
);
// State cookie deleted + scaffold session destroyed + session cookie cleared.
expect(res.cookies.get(NATIVE_HANDOFF_STATE_COOKIE)?.value).toBe("");
expect(prisma.session.delete).toHaveBeenCalledWith({
where: { id: "sess-1" },
});
expect(res.cookies.get("healthlog_session")?.value).toBe("");
});
it("A3 — STALE session (createdAt < startedAt) is REFUSED and mints nothing", async () => {
validateSessionWithCreatedAt.mockResolvedValue(
sessionCreatedAt(new Date(STARTED_AT.getTime() - 1000)),
);
const res = await GET(makeRequest({}));
expect(res.headers.get("location")).toBe(
"healthlog://login-callback?error=stale_session",
);
// No code minted, no scaffold session destroyed.
expect(mintNativeHandoff).not.toHaveBeenCalled();
expect(prisma.session.delete).not.toHaveBeenCalled();
// The single-use state cookie is still cleared on the failure branch.
expect(res.cookies.get(NATIVE_HANDOFF_STATE_COOKIE)?.value).toBe("");
});
it("no state cookie → invalid_state, no mint", async () => {
validateSessionWithCreatedAt.mockResolvedValue(
sessionCreatedAt(new Date(STARTED_AT.getTime() + 1000)),
);
const res = await GET(makeRequest({ withState: false }));
expect(res.headers.get("location")).toBe(
"healthlog://login-callback?error=invalid_state",
);
expect(mintNativeHandoff).not.toHaveBeenCalled();
});
it("tampered / garbage state cookie → invalid_state (auth tag fails)", async () => {
validateSessionWithCreatedAt.mockResolvedValue(
sessionCreatedAt(new Date(STARTED_AT.getTime() + 1000)),
);
const res = await GET(makeRequest({ stateValue: "v1.not-a-real-blob" }));
expect(res.headers.get("location")).toBe(
"healthlog://login-callback?error=invalid_state",
);
expect(mintNativeHandoff).not.toHaveBeenCalled();
});
it("no valid session → no_session, no mint", async () => {
validateSessionWithCreatedAt.mockResolvedValue(null);
const res = await GET(makeRequest({ withSession: false }));
expect(res.headers.get("location")).toBe(
"healthlog://login-callback?error=no_session",
);
expect(mintNativeHandoff).not.toHaveBeenCalled();
});
it("rate-limited → scheme error, no mint", async () => {
vi.mocked(checkAuthSurfaceRateLimit).mockResolvedValue({
allowed: false,
ip: "1.2.3.4",
} as never);
const res = await GET(makeRequest({}));
expect(res.headers.get("location")).toBe(
"healthlog://login-callback?error=rate_limited",
);
expect(mintNativeHandoff).not.toHaveBeenCalled();
});
});
+152
View File
@@ -0,0 +1,152 @@
/**
* GET /api/auth/native/complete
*
* Completion leg of the first-party web-handoff login (iOS #65). After the user
* signs in on the instance's own web login page (inside the app's
* `ASWebAuthenticationSession`), the page navigates the browser here as a
* top-level GET. This endpoint validates the web session, enforces the FRESHNESS
* BINDING, mints a single-use handoff code, and redirects to the compiled-in
* custom scheme carrying ONLY the opaque code.
*
* Security-critical invariants:
* - `userId` is resolved SOLELY from the DB-validated session cookie — the
* request carries no identity field; the app challenge lives in the
* tamper-authenticated state cookie.
* - FRESHNESS: `session.createdAt >= state.startedAt`. The session completing the
* flow must have been minted AFTER the flow started — i.e. the user actually
* authenticated inside this ASWebAuthenticationSession. A pre-existing browser
* session can NEVER silently complete a handoff. Both timestamps are DB-clock
* values, so there is no app/DB skew (red-team A1). `createdAt` is read from a
* dedicated projection (`validateSessionWithCreatedAt`) so the comparison can
* never be silently dropped (red-team A3).
* - The token pair NEVER rides the URL — only the opaque code does.
* - Every failure redirects to `healthlog://login-callback?error=<reason>` and
* deletes the state cookie; no code or row is minted on any failure branch.
*/
import { NextRequest, NextResponse } from "next/server";
import { apiHandler } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { checkAuthSurfaceRateLimit } from "@/lib/rate-limit";
import { prisma } from "@/lib/db";
import { auditLog } from "@/lib/auth/audit";
import { shouldEmitSecureCookie } from "@/lib/auth/secure-cookie";
import {
validateSessionWithCreatedAt,
SESSION_COOKIE_NAME,
} from "@/lib/auth/session";
import { mintNativeHandoff } from "@/lib/auth/native-handoff";
import {
NATIVE_HANDOFF_STATE_COOKIE,
NATIVE_HANDOFF_STATE_COOKIE_PATH,
buildWebHandoffCallbackUrl,
decodeNativeHandoffState,
type NativeHandoffErrorReason,
} from "@/lib/auth/native-web-handoff";
export const dynamic = "force-dynamic";
/**
* The state cookie is path-scoped to `/api/auth/native`; RFC 6265 keys cookies
* by name+domain+path, so the delete must repeat that path or it silently
* targets `/` and leaves the single-use blob alive.
*/
function deleteStateCookie(response: NextResponse): void {
response.cookies.delete({
name: NATIVE_HANDOFF_STATE_COOKIE,
path: NATIVE_HANDOFF_STATE_COOKIE_PATH,
});
}
export const GET = apiHandler(async (req: NextRequest) => {
annotate({ action: { name: "auth.native.complete" } });
// Every failure — and success — deletes the single-use state cookie.
const fail = (reason: NativeHandoffErrorReason): NextResponse => {
const response = NextResponse.redirect(
buildWebHandoffCallbackUrl({ error: reason }),
);
deleteStateCookie(response);
return response;
};
const rl = await checkAuthSurfaceRateLimit(
req,
"auth:native:complete",
20,
15 * 60 * 1000,
);
const ip = rl.ip ?? "unknown";
if (!rl.allowed) {
annotate({ meta: { reason: "rate_limited" } });
return fail("rate_limited");
}
// (1) The encrypted, tamper-authenticated state cookie. A missing, forged, or
// tampered blob (AES-256-GCM auth tag) fails to decode → no mint.
const state = decodeNativeHandoffState(
req.cookies.get(NATIVE_HANDOFF_STATE_COOKIE)?.value,
);
if (!state) {
annotate({ meta: { reason: "invalid_state" } });
return fail("invalid_state");
}
// (2) A genuinely authenticated web session — validated against the database
// (row + expiry), never "a cookie is present". Projects `createdAt` so the
// freshness comparison below is structurally always available.
const authed = await validateSessionWithCreatedAt(
req.cookies.get(SESSION_COOKIE_NAME)?.value,
);
if (!authed) {
annotate({ meta: { reason: "no_session" } });
return fail("no_session");
}
// (3) FRESHNESS BINDING. The session must have been minted AFTER the flow
// started. A stale (pre-existing) session is refused and mints NOTHING.
const startedAt = new Date(state.startedAt);
if (authed.session.createdAt.getTime() < startedAt.getTime()) {
annotate({ meta: { reason: "stale_session" } });
return fail("stale_session");
}
// (4) Mint the single-use, PKCE-locked, flow-tagged handoff code. `userId` is
// the server-resolved session identity; the app's S256 challenge (from the
// tamper-authenticated cookie) locks the code to the app instance that
// started the flow.
const ua = req.headers.get("user-agent");
const { code } = await mintNativeHandoff({
userId: authed.user.id,
appCodeChallenge: state.appCodeChallenge,
flow: "web_login",
ipAddress: ip,
userAgent: ua,
});
await auditLog("auth.native.handoff_minted", {
userId: authed.user.id,
ipAddress: ip,
});
annotate({ action: { name: "auth.native.handoff_minted" } });
const response = NextResponse.redirect(buildWebHandoffCallbackUrl({ code }));
deleteStateCookie(response);
// (5) Destroy the scaffold web session (design §2.6, recommended). The flow's
// product is the native bundle; the browser sheet's residual login is not
// something the user asked for, and the freshness rule already makes a
// retained session worthless for any FUTURE flow. Best-effort — a delete
// hiccup never fails the handoff.
await prisma.session
.delete({ where: { id: authed.session.id } })
.catch(() => {});
response.cookies.set(SESSION_COOKIE_NAME, "", {
httpOnly: true,
secure: shouldEmitSecureCookie(),
sameSite: "lax",
maxAge: 0,
path: "/",
});
return response;
});
@@ -0,0 +1,95 @@
/**
* GET /api/auth/native/login — authorize entry (iOS #65).
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
process.env.ENCRYPTION_KEY = "0".repeat(64);
vi.mock("@/lib/api-handler", () => ({ apiHandler: (fn: unknown) => fn }));
vi.mock("@/lib/rate-limit", () => ({
checkAuthSurfaceRateLimit: vi.fn(),
}));
// Only `$queryRaw` (the DB clock) is used here; return a fixed instant.
// Hoisted so the mock factory (also hoisted) can reference it.
const { DB_NOW } = vi.hoisted(() => ({
DB_NOW: new Date("2026-07-24T10:00:00.000Z"),
}));
vi.mock("@/lib/db", () => ({
prisma: { $queryRaw: vi.fn().mockResolvedValue([{ now: DB_NOW }]) },
}));
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
import { GET } from "../route";
import { checkAuthSurfaceRateLimit } from "@/lib/rate-limit";
import { prisma } from "@/lib/db";
import {
NATIVE_HANDOFF_STATE_COOKIE,
decodeNativeHandoffState,
} from "@/lib/auth/native-web-handoff";
const VALID_CHALLENGE = "a".repeat(43);
function req(query = `code_challenge=${VALID_CHALLENGE}`): NextRequest {
return new NextRequest(`http://localhost/api/auth/native/login?${query}`);
}
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(checkAuthSurfaceRateLimit).mockResolvedValue({
allowed: true,
ip: "1.2.3.4",
} as never);
});
describe("GET /api/auth/native/login", () => {
it("valid challenge → 302 to the web login page with flow=native + state cookie", async () => {
const res = await GET(req());
const location = res.headers.get("location")!;
expect(location).toContain("/auth/login?flow=native");
// No custom scheme on the success path.
expect(location.startsWith("healthlog://")).toBe(false);
const cookie = res.cookies.get(NATIVE_HANDOFF_STATE_COOKIE);
expect(cookie?.value).toBeTruthy();
expect(cookie?.path).toBe("/api/auth/native");
expect(cookie?.httpOnly).toBe(true);
// The state round-trips: challenge bound, startedAt is the DB clock.
const state = decodeNativeHandoffState(cookie!.value);
expect(state?.appCodeChallenge).toBe(VALID_CHALLENGE);
expect(state?.startedAt).toBe(DB_NOW.toISOString());
});
it("invalid (short) challenge → scheme error, no state cookie", async () => {
const res = await GET(req("code_challenge=tooshort"));
expect(res.headers.get("location")).toBe(
"healthlog://login-callback?error=invalid_request",
);
expect(res.cookies.get(NATIVE_HANDOFF_STATE_COOKIE)?.value).toBeFalsy();
// No DB clock read on the reject path.
expect(prisma.$queryRaw).not.toHaveBeenCalled();
});
it("missing challenge → scheme error", async () => {
const res = await GET(req(""));
expect(res.headers.get("location")).toBe(
"healthlog://login-callback?error=invalid_request",
);
});
it("rate-limited → scheme error, no state cookie, no DB write", async () => {
vi.mocked(checkAuthSurfaceRateLimit).mockResolvedValue({
allowed: false,
ip: "1.2.3.4",
} as never);
const res = await GET(req());
expect(res.headers.get("location")).toBe(
"healthlog://login-callback?error=rate_limited",
);
expect(prisma.$queryRaw).not.toHaveBeenCalled();
});
});
+82
View File
@@ -0,0 +1,82 @@
/**
* GET /api/auth/native/login
*
* Authorize entry for the first-party web-handoff login (iOS #65). The iOS app,
* on a self-hosted domain, opens this URL inside an `ASWebAuthenticationSession`
* with its PKCE `code_challenge`. This endpoint validates the challenge, folds
* it plus a DB-clock `startedAt` into an AES-256-GCM state cookie, and redirects
* to the instance's own web login at `/auth/login?flow=native` so the login runs
* in the real web origin (fixing password autofill + passkeys for self-hosters).
*
* Pre-auth surface: writes NO database rows (anonymous flooding costs the caller
* a cookie in their own jar). Every error branch redirects to the compiled-in
* custom scheme with a machine-readable `error=<reason>` — an error redirect
* carries no code or session, so it leaks nothing.
*/
import { NextRequest, NextResponse } from "next/server";
import { apiHandler } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { checkAuthSurfaceRateLimit } from "@/lib/rate-limit";
import { isValidChallenge } from "@/lib/mcp/oauth/pkce";
import { shouldEmitSecureCookie } from "@/lib/auth/secure-cookie";
import {
NATIVE_HANDOFF_STATE_COOKIE,
NATIVE_HANDOFF_STATE_COOKIE_PATH,
NATIVE_HANDOFF_STATE_TTL_MS,
buildWebHandoffCallbackUrl,
encodeNativeHandoffState,
nativeHandoffDbNow,
type NativeHandoffErrorReason,
} from "@/lib/auth/native-web-handoff";
export const dynamic = "force-dynamic";
export const GET = apiHandler(async (req: NextRequest) => {
annotate({ action: { name: "auth.native.login" } });
// The whole route is a native start — every failure redirects to the scheme.
const loginError = (reason: NativeHandoffErrorReason): NextResponse =>
NextResponse.redirect(buildWebHandoffCallbackUrl({ error: reason }));
const rl = await checkAuthSurfaceRateLimit(
req,
"auth:native:login",
10,
15 * 60 * 1000,
);
if (!rl.allowed) return loginError("rate_limited");
// A native start MUST carry a valid S256 challenge (43–128 chars). `plain` is
// structurally unsupported — the exchange only ever verifies S256.
const appCodeChallenge = req.nextUrl.searchParams.get("code_challenge");
if (!isValidChallenge(appCodeChallenge)) {
annotate({ meta: { reason: "invalid_native_request" } });
return loginError("invalid_request");
}
// Stamp `startedAt` from the DB clock so it is directly comparable to
// `Session.createdAt` (also DB-side) at completion, with no app/DB skew.
const startedAt = await nativeHandoffDbNow();
const response = NextResponse.redirect(
new URL("/auth/login?flow=native", req.url),
);
response.cookies.set(
NATIVE_HANDOFF_STATE_COOKIE,
encodeNativeHandoffState({
appCodeChallenge,
startedAt: startedAt.toISOString(),
}),
{
httpOnly: true,
secure: shouldEmitSecureCookie(),
// The completion is a top-level GET navigated by the page after login;
// Lax carries the cookie on that same-site top-level navigation.
sameSite: "lax",
maxAge: Math.floor(NATIVE_HANDOFF_STATE_TTL_MS / 1000),
// Only the completion endpoint ever reads it — the delete repeats this path.
path: NATIVE_HANDOFF_STATE_COOKIE_PATH,
},
);
return response;
});
@@ -0,0 +1,236 @@
/**
* POST /api/auth/native/token — web-handoff exchange (iOS #65).
*
* Mirrors the OIDC native-token route tests, with the `web_login` flow gate.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest, NextResponse } from "next/server";
vi.mock("@/lib/api-handler", () => ({ apiHandler: (fn: unknown) => fn }));
vi.mock("@/lib/db", () => ({
prisma: { user: { findUnique: vi.fn() } },
}));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/rate-limit", () => ({
checkAuthSurfaceRateLimit: vi.fn(),
rateLimitHeaders: vi.fn(() => ({})),
}));
vi.mock("@/lib/auth/native-client", () => ({
isCookielessNativeCaller: vi.fn(() => true),
}));
vi.mock("@/lib/auth/native-handoff", () => ({
consumeNativeHandoff: vi.fn(),
stampIssuedRefreshToken: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/auth/login-response", () => ({
finishLogin: vi.fn(),
}));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
import { POST } from "../route";
import { prisma } from "@/lib/db";
import { checkAuthSurfaceRateLimit } from "@/lib/rate-limit";
import { isCookielessNativeCaller } from "@/lib/auth/native-client";
import {
consumeNativeHandoff,
stampIssuedRefreshToken,
} from "@/lib/auth/native-handoff";
import { finishLogin } from "@/lib/auth/login-response";
import { auditLog } from "@/lib/auth/audit";
const VALID_BODY = {
code: "hlh_" + "a".repeat(43),
codeVerifier: "a".repeat(43),
};
function makeRequest(
body: unknown = VALID_BODY,
headers: Record<string, string> = {},
): NextRequest {
return new NextRequest("http://localhost/api/auth/native/token", {
method: "POST",
headers: {
"content-type": "application/json",
"x-client-type": "native",
...headers,
},
body: typeof body === "string" ? body : JSON.stringify(body),
});
}
function nativeBundleResponse() {
return NextResponse.json({
data: {
user: { id: "user-1", username: "alice" },
token: "hlk_access",
tokenExpiresAt: new Date().toISOString(),
refreshToken: "hlr_refresh",
refreshTokenExpiresAt: new Date().toISOString(),
},
error: null,
});
}
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(checkAuthSurfaceRateLimit).mockResolvedValue({
allowed: true,
ip: "1.2.3.4",
} as never);
vi.mocked(isCookielessNativeCaller).mockReturnValue(true);
});
describe("POST /api/auth/native/token", () => {
it("429 when rate-limited (before any state is touched)", async () => {
vi.mocked(checkAuthSurfaceRateLimit).mockResolvedValue({
allowed: false,
ip: "1.2.3.4",
} as never);
const res = await POST(makeRequest());
expect(res.status).toBe(429);
expect(consumeNativeHandoff).not.toHaveBeenCalled();
});
it("401 and never consumes when the transport is not cookie-less native", async () => {
vi.mocked(isCookielessNativeCaller).mockReturnValue(false);
const res = await POST(makeRequest());
expect(res.status).toBe(401);
expect(consumeNativeHandoff).not.toHaveBeenCalled();
});
it("401 when the caller presents no native marker (browser UA path)", async () => {
// isCookielessNativeCaller true, but no x-client-type / native UA →
// isNativeClientRequest false → rejected before any state.
const res = await POST(makeRequest(VALID_BODY, { "x-client-type": "web" }));
expect(res.status).toBe(401);
expect(consumeNativeHandoff).not.toHaveBeenCalled();
});
it("422 on a malformed body", async () => {
const res = await POST(makeRequest({ code: "nope", codeVerifier: "x" }));
expect(res.status).toBe(422);
expect(consumeNativeHandoff).not.toHaveBeenCalled();
});
it("consumes with the web_login flow gate", async () => {
vi.mocked(consumeNativeHandoff).mockResolvedValue({
status: "not_found",
} as never);
await POST(makeRequest());
expect(consumeNativeHandoff).toHaveBeenCalledWith(
VALID_BODY.code,
VALID_BODY.codeVerifier,
"web_login",
);
});
it("returns ONE identical generic 401 across every invalid-code class", async () => {
const statuses = [
{ status: "not_found" },
{ status: "replayed", userId: "user-1" },
{ status: "expired" },
{ status: "pkce_mismatch" },
{ status: "race_lost" },
] as const;
const bodies: string[] = [];
for (const s of statuses) {
vi.mocked(consumeNativeHandoff).mockResolvedValue(s as never);
const res = await POST(makeRequest());
expect(res.status).toBe(401);
bodies.push(await res.text());
}
vi.mocked(consumeNativeHandoff).mockResolvedValue({
status: "ok",
userId: "user-1",
handoffId: "ho-1",
} as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue(null as never);
const res = await POST(makeRequest());
expect(res.status).toBe(401);
bodies.push(await res.text());
expect(new Set(bodies).size).toBe(1);
});
it("does not mint on the deleted-user branch", async () => {
vi.mocked(consumeNativeHandoff).mockResolvedValue({
status: "ok",
userId: "user-1",
handoffId: "ho-1",
} as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue(null as never);
await POST(makeRequest());
expect(finishLogin).not.toHaveBeenCalled();
});
it("200 on success: mints via the web_handoff source, stamps, audits, no mfaVerified", async () => {
vi.mocked(consumeNativeHandoff).mockResolvedValue({
status: "ok",
userId: "user-1",
handoffId: "ho-1",
} as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
id: "user-1",
username: "alice",
onboardingCompletedAt: new Date(),
} as never);
vi.mocked(finishLogin).mockResolvedValue(nativeBundleResponse());
const res = await POST(makeRequest());
expect(res.status).toBe(200);
const finishArg = vi.mocked(finishLogin).mock.calls[0][0];
expect(finishArg.source).toBe("login.web_handoff");
// Never set — the handoff login can't satisfy step-up.
expect(finishArg.mfaVerified).toBeUndefined();
expect(stampIssuedRefreshToken).toHaveBeenCalledWith("ho-1", "hlr_refresh");
expect(auditLog).toHaveBeenCalledWith(
"auth.login",
expect.objectContaining({
userId: "user-1",
details: { transport: "native", method: "web_handoff" },
}),
);
const body = await res.json();
expect(body.data.refreshToken).toBe("hlr_refresh");
});
it("is NOT blocked by OIDC_ONLY", async () => {
const prev = process.env.OIDC_ONLY;
process.env.OIDC_ONLY = "true";
try {
vi.mocked(consumeNativeHandoff).mockResolvedValue({
status: "ok",
userId: "user-1",
handoffId: "ho-1",
} as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
id: "user-1",
username: "alice",
onboardingCompletedAt: new Date(),
} as never);
vi.mocked(finishLogin).mockResolvedValue(nativeBundleResponse());
const res = await POST(makeRequest());
expect(res.status).toBe(200);
} finally {
if (prev === undefined) delete process.env.OIDC_ONLY;
else process.env.OIDC_ONLY = prev;
}
});
});
+160
View File
@@ -0,0 +1,160 @@
/**
* POST /api/auth/native/token
*
* The cookie-less native leg of the first-party web-handoff login (iOS #65). The
* app presents the one-time handoff code it received on
* `healthlog://login-callback?code=` plus its PKCE `codeVerifier`; on success it
* receives the SAME native token bundle password login issues
* (`{ token, tokenExpiresAt, refreshToken, refreshTokenExpiresAt }`).
*
* Byte-for-byte the posture of `POST /api/auth/oidc/native/token`, with the
* `flow: "web_login"` gate on the shared consume:
* - It IS the credential mint: no session or Bearer is required to reach it.
* - The transport gate (`isCookielessNativeCaller` + `isNativeClientRequest`)
* makes the endpoint structurally incapable of minting a web session or handing
* a 60-day refresh token into a browser context.
* - `userId` is derived SOLELY from the server-side handoff row.
* - A single generic 401 covers not-found / expired / used / PKCE-mismatch /
* cross-flow / deleted-user so a code-guesser learns nothing.
* - `mfaVerifiedAt` is never set — a Bearer transport can never satisfy
* `requireFreshMfa` step-up.
*/
import { NextRequest } from "next/server";
import { apiError, safeJson } from "@/lib/api-response";
import { apiHandler } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import { ensureDbCompatibility } from "@/lib/db-compat";
import { checkAuthSurfaceRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
import { isCookielessNativeCaller } from "@/lib/auth/native-client";
import { isNativeClientRequest } from "@/lib/auth/issue-token";
import { finishLogin } from "@/lib/auth/login-response";
import {
consumeNativeHandoff,
stampIssuedRefreshToken,
} from "@/lib/auth/native-handoff";
import { nativeHandoffTokenSchema } from "@/lib/validations/native-handoff";
export const dynamic = "force-dynamic";
/** The single generic rejection for every invalid-code class. */
function invalidCode() {
return apiError("Invalid or expired code", 401);
}
export const POST = apiHandler(async (request: NextRequest) => {
annotate({ action: { name: "auth.native.token" } });
// (1) Rate limit — the MFA-verify surface's posture, incl. the
// trust-violation collapse semantics.
const rl = await checkAuthSurfaceRateLimit(
request,
"auth:native:token",
10,
15 * 60 * 1000,
);
const ip = rl.ip ?? "unknown";
if (!rl.allowed) {
return apiError("Too many attempts. Please try again later.", 429, {
headers: rateLimitHeaders(rl),
});
}
// (2) Transport gate — this endpoint only ever hands a native token bundle. A
// browser (Mozilla UA or an inbound session cookie) is rejected, AND the
// caller must present an explicit native marker, so the cookie branch of
// `finishLogin` is structurally unreachable.
if (
!isCookielessNativeCaller(request.headers) ||
!isNativeClientRequest(request.headers)
) {
annotate({ action: { name: "auth.native.token.wrong_transport" } });
return invalidCode();
}
await ensureDbCompatibility();
// (3) Body — bounded, then the exact wire contract.
const { data: body, error: jsonError } = await safeJson(request, {
maxBytes: 16 * 1024,
});
if (jsonError) return jsonError;
const parsed = nativeHandoffTokenSchema.safeParse(body);
if (!parsed.success) {
return apiError("Invalid request", 422);
}
const { code, codeVerifier } = parsed.data;
// (4) Lookup + flow check + replay/expiry/PKCE + atomic single-use consume.
// The `web_login` flow gate rejects an OIDC-minted code as `not_found`.
const result = await consumeNativeHandoff(code, codeVerifier, "web_login");
if (result.status !== "ok") {
switch (result.status) {
case "not_found":
annotate({ action: { name: "auth.native.token.not_found" } });
break;
case "replayed":
annotate({
action: { name: "auth.native.handoff_replay" },
meta: { revoked_issued_pair: result.revokedIssuedPair },
});
break;
case "expired":
annotate({ action: { name: "auth.native.token.expired" } });
break;
case "pkce_mismatch":
annotate({ action: { name: "auth.native.pkce_failed" } });
break;
case "race_lost":
annotate({ action: { name: "auth.native.token.race_lost" } });
break;
}
return invalidCode();
}
// (5) Load the user (may have been deleted mid-flight).
const user = await prisma.user.findUnique({
where: { id: result.userId },
select: { id: true, username: true, onboardingCompletedAt: true },
});
if (!user) {
annotate({ action: { name: "auth.native.token.user_missing" } });
return invalidCode();
}
// (6) Mint the native bundle. Step (2) guarantees the cookie-less-native
// branch of `finishLogin` (24h access + 60d rotating refresh). `mfaVerified`
// is deliberately unset — the handoff login can never satisfy step-up.
const ua = request.headers.get("user-agent");
const response = await finishLogin({
user,
request,
ip,
userAgent: ua,
source: "login.web_handoff",
});
// (7) Stamp the issued refresh token's hash for replay-containment reach-back,
// then audit. Best-effort — the code is already single-use-consumed.
try {
const bundle = (await response.clone().json()) as {
data?: { refreshToken?: unknown };
};
const refreshToken = bundle.data?.refreshToken;
if (typeof refreshToken === "string") {
await stampIssuedRefreshToken(result.handoffId, refreshToken);
}
} catch {
// Non-fatal — see comment above.
}
await auditLog("auth.login", {
userId: user.id,
ipAddress: ip,
details: { transport: "native", method: "web_handoff" },
});
return response;
});