mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 08:02:12 +00:00
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:
1 parent
d2d79b70a2
commit
0b3280c604
28 files changed
+1976
-197
No files matched your search
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
});
|
||||
Reference in new issue
Block a user