From c6bb0250dae665d540644802841b7b65230778c0 Mon Sep 17 00:00:00 2001 From: rigwig Date: Fri, 4 Sep 2026 23:50:40 -0400 Subject: [PATCH 1/2] feat(auth): native-app sign-in handoff via one-time code Native clients can't read the session cookie out of the system browser, so today an app has to embed a web view for the OIDC flow and scrape the cookie. That rules out passkeys (WebKit doesn't expose WebAuthn to embedded views for third-party origins) and is the embedded-OAuth pattern Google discourages. Add an opt-in handoff, disabled unless NATIVE_APP_SCHEMES is set: - a native app opens the normal login page with a returnTo on one of its registered URL schemes, e.g. /login?returnTo=jetpilot://auth; - after sign-in, /oidc/callback redirects there with a single-use code (5 minutes, kept in memory like activeConnections) and clears the browser session so nothing is left behind in the system browser; - POST /auth/exchange { code } establishes a regular session cookie. Native returnTo URLs are only honoured on the plain sign-in path; the device-adoption path (deviceId) is unchanged. Co-Authored-By: Claude Fable 5.1 --- .env.example | 5 ++ README.md | 8 +++ src/index.ts | 3 ++ src/native-auth.ts | 89 +++++++++++++++++++++++++++++++++ src/oidc.ts | 9 ++++ test/native-auth.test.ts | 104 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 218 insertions(+) create mode 100644 src/native-auth.ts create mode 100644 test/native-auth.test.ts diff --git a/.env.example b/.env.example index a7a246a..389df60 100644 --- a/.env.example +++ b/.env.example @@ -35,6 +35,11 @@ CORS_ORIGINS=https://app.jetkvm.com,http://localhost:5173 # Allowed account emails, split by comma (leave empty to allow all) ALLOWED_IDENTITIES= +# URL schemes of native apps that may sign in through the system browser, split by comma +# (e.g. jetpilot). The app opens /login?returnTo=://..., receives a one-time code on +# that URL after sign-in, and exchanges it at POST /auth/exchange. Leave empty to disable. +NATIVE_APP_SCHEMES= + # Real IP Header for the reverse proxy (e.g. X-Real-IP), leave empty if not needed REAL_IP_HEADER= diff --git a/README.md b/README.md index 0c431eb..776917f 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,14 @@ docker compose up -d The app will be available on port 3000. Configure a reverse proxy (nginx, Caddy, etc.) for TLS termination. +### Native app sign-in + +Native clients can't read the session cookie out of the system browser, so `NATIVE_APP_SCHEMES` lets an app on a registered URL scheme (e.g. `jetpilot`) sign in through the normal login page: + +1. The app opens `${APP_HOSTNAME}/login?returnTo=jetpilot://auth` in the system browser (passkeys and password managers work there). +2. After sign-in, `/oidc/callback` redirects to `jetpilot://auth?code=…` with a single-use code valid for five minutes, and clears the browser session. +3. The app calls `POST /auth/exchange` with `{ "code": "…" }` and stores the `session` / `session.sig` cookies from the response. + ### Updating ```bash diff --git a/src/index.ts b/src/index.ts index b6fdecb..f180570 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,6 +7,7 @@ import 'dotenv/config'; import * as Devices from "./devices"; import * as OIDC from "./oidc"; +import * as NativeAuth from "./native-auth"; import * as Webrtc from "./webrtc"; import * as Releases from "./releases"; @@ -47,6 +48,7 @@ declare global { ICE_SERVERS: string; ALLOWED_IDENTITIES?: string; + NATIVE_APP_SCHEMES?: string; } } } @@ -137,6 +139,7 @@ app.post( app.post("/oidc/google", OIDC.Google); app.get("/oidc/callback_o", OIDC.Callback); +app.post("/auth/exchange", NativeAuth.Exchange); app.get("/oidc/callback", (req, res) => { /* * We set the session cookie in the /oidc/google route as a part of 302 redirect to the OIDC login page diff --git a/src/native-auth.ts b/src/native-auth.ts new file mode 100644 index 0000000..67017bc --- /dev/null +++ b/src/native-auth.ts @@ -0,0 +1,89 @@ +import express from "express"; +import * as crypto from "crypto"; +import { LRUCache } from "lru-cache"; +import { UnauthorizedError, UnprocessableEntityError } from "./errors"; + +/** + * Native-app sign-in handoff. + * + * The normal flow leaves the signed-in session as a cookie in whichever + * browser ran the OIDC dance. A native app can't read cookies out of the + * system browser, so today it has to embed a web view and scrape the cookie — + * which also rules out passkeys (WebKit doesn't expose WebAuthn to embedded + * views for third-party origins) and is the kind of embedded OAuth Google + * discourages. + * + * With this handoff a native app opens the regular login page in the system + * browser with a `returnTo` on one of its registered URL schemes + * (NATIVE_APP_SCHEMES). After sign-in, /oidc/callback redirects there with a + * short-lived, single-use `code`, and the app exchanges it at + * POST /auth/exchange for an ordinary session cookie. + */ + +const NATIVE_APP_SCHEMES = new Set( + (process.env.NATIVE_APP_SCHEMES ?? "") + .split(",") + .map(scheme => scheme.trim().toLowerCase().replace(/:$/, "")) + .filter(Boolean), +); + +export const NATIVE_AUTH_CODE_TTL_MS = 5 * 60 * 1000; + +export interface PendingNativeSession { + id_token: string; +} + +// In-memory like `activeConnections`: codes are only meaningful for the +// instance that issued them, and they live for five minutes at most. +const pendingSessions = new LRUCache({ + max: 10_000, + ttl: NATIVE_AUTH_CODE_TTL_MS, +}); + +/** True when `returnTo` is a URL on one of the registered native-app schemes. */ +export function isNativeReturnTo(returnTo: unknown): returnTo is string { + if (typeof returnTo !== "string" || NATIVE_APP_SCHEMES.size === 0) return false; + let url: URL; + try { + url = new URL(returnTo); + } catch { + return false; + } + const scheme = url.protocol.replace(/:$/, "").toLowerCase(); + if (scheme === "http" || scheme === "https") return false; + return NATIVE_APP_SCHEMES.has(scheme); +} + +export function issueNativeAuthCode(session: PendingNativeSession): string { + const code = crypto.randomBytes(32).toString("base64url"); + pendingSessions.set(code, session); + return code; +} + +/** Returns the session for a code and invalidates the code. */ +export function redeemNativeAuthCode(code: string): PendingNativeSession | undefined { + const session = pendingSessions.get(code); + if (session) pendingSessions.delete(code); + return session; +} + +export function nativeRedirectUrl(returnTo: string, code: string): string { + const url = new URL(returnTo); + url.searchParams.set("code", code); + return url.toString(); +} + +/** POST /auth/exchange { code } → session cookie for the native app. */ +export const Exchange = async (req: express.Request, res: express.Response) => { + const { code } = (req.body ?? {}) as { code?: unknown }; + if (typeof code !== "string" || !code) { + throw new UnprocessableEntityError("Missing code in body"); + } + + const pending = redeemNativeAuthCode(code); + if (!pending) + throw new UnauthorizedError("Invalid or expired code", "invalid_auth_code"); + + req.session = { id_token: pending.id_token }; + return res.json({ ok: true }); +}; diff --git a/src/oidc.ts b/src/oidc.ts index 7908e76..2747df0 100644 --- a/src/oidc.ts +++ b/src/oidc.ts @@ -3,6 +3,7 @@ import express from "express"; import { prisma } from "./db"; import { BadRequestError, UnauthorizedError } from "./errors"; import { isIdentityAllowed } from "./auth"; +import { isNativeReturnTo, issueNativeAuthCode, nativeRedirectUrl } from "./native-auth"; import * as crypto from "crypto"; const API_HOSTNAME = process.env.API_HOSTNAME; @@ -165,5 +166,13 @@ export const Callback = async (req: express.Request, res: express.Response) => { url.searchParams.append("clientId", process.env.GOOGLE_CLIENT_ID); return res.redirect(url.toString()); } + + if (isNativeReturnTo(returnTo)) { + // Hand the session to the native app through a one-time code, and leave + // no session behind in the browser that ran the sign-in. + const code = issueNativeAuthCode({ id_token: tokenSet.id_token }); + req.session = null; + return res.redirect(nativeRedirectUrl(returnTo, code)); + } return res.redirect(returnTo); }; diff --git a/test/native-auth.test.ts b/test/native-auth.test.ts new file mode 100644 index 0000000..2f9408b --- /dev/null +++ b/test/native-auth.test.ts @@ -0,0 +1,104 @@ +import { describe, it, expect, beforeAll, vi } from "vitest"; +import { Request, Response } from "express"; + +type NativeAuth = typeof import("../src/native-auth"); + +// The scheme allowlist is read once at import, like ALLOWED_IDENTITIES. +async function loadWithSchemes(schemes: string | undefined): Promise { + vi.resetModules(); + if (schemes === undefined) delete process.env.NATIVE_APP_SCHEMES; + else process.env.NATIVE_APP_SCHEMES = schemes; + return import("../src/native-auth"); +} + +function mockResponse() { + return { json: vi.fn(), redirect: vi.fn() } as unknown as Response & { + json: ReturnType; + }; +} + +describe("isNativeReturnTo", () => { + let nativeAuth: NativeAuth; + beforeAll(async () => { + nativeAuth = await loadWithSchemes("jetpilot, MyApp:"); + }); + + it("accepts URLs on a registered scheme, case-insensitively", () => { + expect(nativeAuth.isNativeReturnTo("jetpilot://auth")).toBe(true); + expect(nativeAuth.isNativeReturnTo("JetPilot://auth/done?x=1")).toBe(true); + expect(nativeAuth.isNativeReturnTo("myapp://signed-in")).toBe(true); + }); + + it("rejects web URLs, unregistered schemes, and garbage", () => { + expect(nativeAuth.isNativeReturnTo("https://app.jetkvm.com/devices")).toBe(false); + expect(nativeAuth.isNativeReturnTo("http://jetpilot/auth")).toBe(false); + expect(nativeAuth.isNativeReturnTo("otherapp://auth")).toBe(false); + expect(nativeAuth.isNativeReturnTo("javascript:alert(1)")).toBe(false); + expect(nativeAuth.isNativeReturnTo("not a url")).toBe(false); + expect(nativeAuth.isNativeReturnTo(undefined)).toBe(false); + expect(nativeAuth.isNativeReturnTo(null)).toBe(false); + }); + + it("is disabled when NATIVE_APP_SCHEMES is unset", async () => { + const disabled = await loadWithSchemes(undefined); + expect(disabled.isNativeReturnTo("jetpilot://auth")).toBe(false); + }); +}); + +describe("native auth codes", () => { + let nativeAuth: NativeAuth; + beforeAll(async () => { + nativeAuth = await loadWithSchemes("jetpilot"); + }); + + it("are single-use", () => { + const code = nativeAuth.issueNativeAuthCode({ id_token: "token-1" }); + expect(code.length).toBeGreaterThanOrEqual(43); + expect(nativeAuth.redeemNativeAuthCode(code)).toEqual({ id_token: "token-1" }); + expect(nativeAuth.redeemNativeAuthCode(code)).toBeUndefined(); + expect(nativeAuth.redeemNativeAuthCode("nope")).toBeUndefined(); + }); + + it("are appended to the app's returnTo as `code`", () => { + const url = new URL( + nativeAuth.nativeRedirectUrl("jetpilot://auth?from=cloud", "abc"), + ); + expect(url.protocol).toBe("jetpilot:"); + expect(url.searchParams.get("from")).toBe("cloud"); + expect(url.searchParams.get("code")).toBe("abc"); + }); +}); + +describe("POST /auth/exchange", () => { + let nativeAuth: NativeAuth; + beforeAll(async () => { + nativeAuth = await loadWithSchemes("jetpilot"); + }); + + it("requires a code", async () => { + const req = { body: {}, session: null } as unknown as Request; + // Compared by status: vi.resetModules() gives the error classes a new identity. + await expect(nativeAuth.Exchange(req, mockResponse())).rejects.toMatchObject({ + status: 422, + }); + }); + + it("rejects unknown or already-used codes", async () => { + const code = nativeAuth.issueNativeAuthCode({ id_token: "token-2" }); + nativeAuth.redeemNativeAuthCode(code); + const req = { body: { code }, session: null } as unknown as Request; + await expect(nativeAuth.Exchange(req, mockResponse())).rejects.toMatchObject({ + status: 401, + code: "invalid_auth_code", + }); + }); + + it("establishes a session for a valid code", async () => { + const code = nativeAuth.issueNativeAuthCode({ id_token: "token-3" }); + const req = { body: { code }, session: null } as unknown as Request; + const res = mockResponse(); + await nativeAuth.Exchange(req, res); + expect(req.session).toEqual({ id_token: "token-3" }); + expect(res.json).toHaveBeenCalledWith({ ok: true }); + }); +}); From 0bdc4f8df3deb6f4da3f2738bcc40e6c38c316cc Mon Sep 17 00:00:00 2001 From: rigwig Date: Sat, 28 Nov 2026 18:27:40 -0500 Subject: [PATCH 2/2] feat(auth): bind native auth codes to the app and restrict the exchange A URL scheme identifies a redirect target, not an app, so a code delivered to another app that registered the same scheme could be redeemed by it. Bind the code to the app that started sign-in, as in PKCE (RFC 7636): the app's returnTo carries `code_challenge` (base64url SHA-256 of a verifier it keeps), and POST /auth/exchange needs the matching `code_verifier`. A wrong verifier leaves the code in place, so an interceptor cannot burn it either. /auth/exchange now only accepts JSON bodies without an Origin header, checked before the code is looked at, so a web page cannot use a form post to sign a visitor's browser in to another session. Co-Authored-By: Claude Fable 5.2 --- .env.example | 5 +- README.md | 6 +- src/native-auth.ts | 85 ++++++++++++++++++++++-- src/oidc.ts | 14 +++- test/native-auth.test.ts | 137 ++++++++++++++++++++++++++++++++++----- 5 files changed, 218 insertions(+), 29 deletions(-) diff --git a/.env.example b/.env.example index e745faf..8bd9cc9 100644 --- a/.env.example +++ b/.env.example @@ -36,8 +36,9 @@ CORS_ORIGINS=https://app.jetkvm.com,http://localhost:5173 ALLOWED_IDENTITIES= # URL schemes of native apps that may sign in through the system browser, split by comma -# (e.g. jetpilot). The app opens /login?returnTo=://..., receives a one-time code on -# that URL after sign-in, and exchanges it at POST /auth/exchange. Leave empty to disable. +# (e.g. jetpilot). The app opens /login?returnTo=://...?code_challenge=..., receives a +# one-time code on that URL after sign-in, and exchanges it with its code verifier at +# POST /auth/exchange. Leave empty to disable. NATIVE_APP_SCHEMES= # Real IP Header for the reverse proxy (e.g. X-Real-IP), leave empty if not needed diff --git a/README.md b/README.md index 6a2a033..dbdb9e0 100644 --- a/README.md +++ b/README.md @@ -91,9 +91,11 @@ The app will be available on port 3000. Configure a reverse proxy (nginx, Caddy, Native clients can't read the session cookie out of the system browser, so `NATIVE_APP_SCHEMES` lets an app on a registered URL scheme (e.g. `jetpilot`) sign in through the normal login page: -1. The app opens `${APP_HOSTNAME}/login?returnTo=jetpilot://auth` in the system browser (passkeys and password managers work there). +1. The app makes a random code verifier (43 to 128 URL-safe characters) and opens `${APP_HOSTNAME}/login?returnTo=…` in the system browser (passkeys and password managers work there), where `returnTo` is the URL-encoded `jetpilot://auth?code_challenge=`. 2. After sign-in, `/oidc/callback` redirects to `jetpilot://auth?code=…` with a single-use code valid for five minutes, and clears the browser session. -3. The app calls `POST /auth/exchange` with `{ "code": "…" }` and stores the `session` / `session.sig` cookies from the response. +3. The app calls `POST /auth/exchange` with the JSON body `{ "code": "…", "code_verifier": "…" }` and stores the `session` / `session.sig` cookies from the response. + +A URL scheme can be registered by more than one app, so the verifier is what ties the code to the app that started sign-in (as in PKCE, RFC 7636). `/auth/exchange` only accepts JSON requests without an `Origin` header, which keeps web pages from using it. ### Updating diff --git a/src/native-auth.ts b/src/native-auth.ts index 67017bc..d90f0d1 100644 --- a/src/native-auth.ts +++ b/src/native-auth.ts @@ -1,7 +1,12 @@ import express from "express"; import * as crypto from "crypto"; import { LRUCache } from "lru-cache"; -import { UnauthorizedError, UnprocessableEntityError } from "./errors"; +import { + BadRequestError, + ForbiddenError, + UnauthorizedError, + UnprocessableEntityError, +} from "./errors"; /** * Native-app sign-in handoff. @@ -18,6 +23,12 @@ import { UnauthorizedError, UnprocessableEntityError } from "./errors"; * (NATIVE_APP_SCHEMES). After sign-in, /oidc/callback redirects there with a * short-lived, single-use `code`, and the app exchanges it at * POST /auth/exchange for an ordinary session cookie. + * + * A URL scheme identifies a redirect target, not an app: another app on the + * device can register the same scheme and receive the redirect. So the code + * is bound to the app that started sign-in, as in PKCE (RFC 7636): the app + * puts `code_challenge` (the base64url SHA-256 of a random verifier it keeps) + * in its `returnTo`, and must present the verifier to redeem the code. */ const NATIVE_APP_SCHEMES = new Set( @@ -31,6 +42,34 @@ export const NATIVE_AUTH_CODE_TTL_MS = 5 * 60 * 1000; export interface PendingNativeSession { id_token: string; + /** base64url(SHA-256(verifier)), from the app's `returnTo`. */ + code_challenge: string; +} + +// A SHA-256 digest in unpadded base64url is always 43 characters. +const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/; +// RFC 7636 section 4.1: 43 to 128 unreserved characters. +const CODE_VERIFIER_PATTERN = /^[A-Za-z0-9._~-]{43,128}$/; + +/** + * The `code_challenge` query parameter of a native `returnTo`; throws when it + * is missing or not a base64url SHA-256 digest. + */ +export function nativeCodeChallenge(returnTo: string): string { + const challenge = new URL(returnTo).searchParams.get("code_challenge"); + if (!challenge || !CODE_CHALLENGE_PATTERN.test(challenge)) { + throw new BadRequestError( + "returnTo needs a code_challenge (base64url SHA-256 of the code verifier)", + "missing_code_challenge", + ); + } + return challenge; +} + +function matchesChallenge(verifier: string, challenge: string): boolean { + const expected = Buffer.from(challenge, "base64url"); + const actual = crypto.createHash("sha256").update(verifier).digest(); + return expected.length === actual.length && crypto.timingSafeEqual(expected, actual); } // In-memory like `activeConnections`: codes are only meaningful for the @@ -60,27 +99,59 @@ export function issueNativeAuthCode(session: PendingNativeSession): string { return code; } -/** Returns the session for a code and invalidates the code. */ -export function redeemNativeAuthCode(code: string): PendingNativeSession | undefined { +/** + * Returns the session for a code and invalidates the code, provided the + * verifier matches the challenge the code was issued for. A wrong verifier + * leaves the code in place, so whoever intercepted a code cannot burn it + * before the app that owns it redeems it. + */ +export function redeemNativeAuthCode( + code: string, + verifier: string, +): PendingNativeSession | undefined { const session = pendingSessions.get(code); - if (session) pendingSessions.delete(code); + if (!session || !matchesChallenge(verifier, session.code_challenge)) return undefined; + pendingSessions.delete(code); return session; } export function nativeRedirectUrl(returnTo: string, code: string): string { const url = new URL(returnTo); + // The app already knows its challenge; only the code goes back. + url.searchParams.delete("code_challenge"); url.searchParams.set("code", code); return url.toString(); } -/** POST /auth/exchange { code } → session cookie for the native app. */ +/** + * POST /auth/exchange { code, code_verifier } → session cookie for the native app. + * + * Only for native clients: the body must be JSON (which a cross-site form + * cannot send) and the request must not come from a browser page (which + * always sends Origin on a POST), so a web page cannot sign a visitor's + * browser in to somebody else's session. Both are checked before the code is + * looked at. + */ export const Exchange = async (req: express.Request, res: express.Response) => { - const { code } = (req.body ?? {}) as { code?: unknown }; + if (!req.is("application/json")) { + throw new BadRequestError("Body must be application/json", "invalid_content_type"); + } + if (req.headers.origin) { + throw new ForbiddenError("This endpoint is for native apps"); + } + + const { code, code_verifier } = (req.body ?? {}) as { + code?: unknown; + code_verifier?: unknown; + }; if (typeof code !== "string" || !code) { throw new UnprocessableEntityError("Missing code in body"); } + if (typeof code_verifier !== "string" || !CODE_VERIFIER_PATTERN.test(code_verifier)) { + throw new UnprocessableEntityError("Missing or malformed code_verifier in body"); + } - const pending = redeemNativeAuthCode(code); + const pending = redeemNativeAuthCode(code, code_verifier); if (!pending) throw new UnauthorizedError("Invalid or expired code", "invalid_auth_code"); diff --git a/src/oidc.ts b/src/oidc.ts index 2747df0..5142a15 100644 --- a/src/oidc.ts +++ b/src/oidc.ts @@ -3,7 +3,12 @@ import express from "express"; import { prisma } from "./db"; import { BadRequestError, UnauthorizedError } from "./errors"; import { isIdentityAllowed } from "./auth"; -import { isNativeReturnTo, issueNativeAuthCode, nativeRedirectUrl } from "./native-auth"; +import { + isNativeReturnTo, + issueNativeAuthCode, + nativeCodeChallenge, + nativeRedirectUrl, +} from "./native-auth"; import * as crypto from "crypto"; const API_HOSTNAME = process.env.API_HOSTNAME; @@ -170,8 +175,13 @@ export const Callback = async (req: express.Request, res: express.Response) => { if (isNativeReturnTo(returnTo)) { // Hand the session to the native app through a one-time code, and leave // no session behind in the browser that ran the sign-in. - const code = issueNativeAuthCode({ id_token: tokenSet.id_token }); + // The session never stays in the browser, even when the app's returnTo + // turns out to lack a challenge. req.session = null; + const code = issueNativeAuthCode({ + id_token: tokenSet.id_token, + code_challenge: nativeCodeChallenge(returnTo), + }); return res.redirect(nativeRedirectUrl(returnTo, code)); } return res.redirect(returnTo); diff --git a/test/native-auth.test.ts b/test/native-auth.test.ts index 2f9408b..682315e 100644 --- a/test/native-auth.test.ts +++ b/test/native-auth.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, beforeAll, vi } from "vitest"; import { Request, Response } from "express"; +import { createHash } from "crypto"; type NativeAuth = typeof import("../src/native-auth"); @@ -11,6 +12,24 @@ async function loadWithSchemes(schemes: string | undefined): Promise return import("../src/native-auth"); } +const VERIFIER = "v".repeat(43); +const CHALLENGE = createHash("sha256").update(VERIFIER).digest("base64url"); +const OTHER_VERIFIER = "w".repeat(43); + +// A request as a native HTTP client sends it: JSON, no Origin header. +function exchangeRequest( + body: unknown, + opts: { contentType?: string; origin?: string } = {}, +): Request { + const contentType = opts.contentType ?? "application/json"; + return { + body, + session: null, + headers: { "content-type": contentType, origin: opts.origin }, + is: (type: string) => (contentType.startsWith(type) ? type : false), + } as unknown as Request; +} + function mockResponse() { return { json: vi.fn(), redirect: vi.fn() } as unknown as Response & { json: ReturnType; @@ -52,20 +71,58 @@ describe("native auth codes", () => { }); it("are single-use", () => { - const code = nativeAuth.issueNativeAuthCode({ id_token: "token-1" }); + const pending = { id_token: "token-1", code_challenge: CHALLENGE }; + const code = nativeAuth.issueNativeAuthCode(pending); expect(code.length).toBeGreaterThanOrEqual(43); - expect(nativeAuth.redeemNativeAuthCode(code)).toEqual({ id_token: "token-1" }); - expect(nativeAuth.redeemNativeAuthCode(code)).toBeUndefined(); - expect(nativeAuth.redeemNativeAuthCode("nope")).toBeUndefined(); + expect(nativeAuth.redeemNativeAuthCode(code, VERIFIER)).toEqual(pending); + expect(nativeAuth.redeemNativeAuthCode(code, VERIFIER)).toBeUndefined(); + expect(nativeAuth.redeemNativeAuthCode("nope", VERIFIER)).toBeUndefined(); + }); + + it("are only redeemed with the verifier behind their challenge, and survive a wrong one", () => { + const pending = { id_token: "token-1b", code_challenge: CHALLENGE }; + const code = nativeAuth.issueNativeAuthCode(pending); + // Whoever intercepts the redirect has the code but not the verifier... + expect(nativeAuth.redeemNativeAuthCode(code, OTHER_VERIFIER)).toBeUndefined(); + // ...and their attempt does not burn the code for the app that owns it. + expect(nativeAuth.redeemNativeAuthCode(code, VERIFIER)).toEqual(pending); }); - it("are appended to the app's returnTo as `code`", () => { + it("are appended to the app's returnTo as `code`, without the challenge", () => { const url = new URL( - nativeAuth.nativeRedirectUrl("jetpilot://auth?from=cloud", "abc"), + nativeAuth.nativeRedirectUrl( + `jetpilot://auth?from=cloud&code_challenge=${CHALLENGE}`, + "abc", + ), ); expect(url.protocol).toBe("jetpilot:"); expect(url.searchParams.get("from")).toBe("cloud"); expect(url.searchParams.get("code")).toBe("abc"); + expect(url.searchParams.has("code_challenge")).toBe(false); + }); +}); + +describe("nativeCodeChallenge", () => { + let nativeAuth: NativeAuth; + beforeAll(async () => { + nativeAuth = await loadWithSchemes("jetpilot"); + }); + + it("reads the challenge from the returnTo", () => { + expect( + nativeAuth.nativeCodeChallenge(`jetpilot://auth?code_challenge=${CHALLENGE}`), + ).toBe(CHALLENGE); + }); + + it.each([ + ["no challenge", "jetpilot://auth"], + ["an empty challenge", "jetpilot://auth?code_challenge="], + ["a challenge that is not a SHA-256 digest", "jetpilot://auth?code_challenge=abc"], + ["a plain verifier in place of its digest", `jetpilot://auth?code_challenge=${"v".repeat(64)}`], + ])("rejects %s", (_label, returnTo) => { + expect(() => nativeAuth.nativeCodeChallenge(returnTo)).toThrowError( + expect.objectContaining({ status: 400, code: "missing_code_challenge" }), + ); }); }); @@ -75,27 +132,75 @@ describe("POST /auth/exchange", () => { nativeAuth = await loadWithSchemes("jetpilot"); }); - it("requires a code", async () => { - const req = { body: {}, session: null } as unknown as Request; + const issue = (id_token: string) => + nativeAuth.issueNativeAuthCode({ id_token, code_challenge: CHALLENGE }); + + it("requires a code and a verifier", async () => { // Compared by status: vi.resetModules() gives the error classes a new identity. - await expect(nativeAuth.Exchange(req, mockResponse())).rejects.toMatchObject({ - status: 422, - }); + await expect( + nativeAuth.Exchange(exchangeRequest({}), mockResponse()), + ).rejects.toMatchObject({ status: 422 }); + await expect( + nativeAuth.Exchange(exchangeRequest({ code: issue("token-2a") }), mockResponse()), + ).rejects.toMatchObject({ status: 422 }); + await expect( + nativeAuth.Exchange( + exchangeRequest({ code: issue("token-2b"), code_verifier: "too short" }), + mockResponse(), + ), + ).rejects.toMatchObject({ status: 422 }); }); it("rejects unknown or already-used codes", async () => { - const code = nativeAuth.issueNativeAuthCode({ id_token: "token-2" }); - nativeAuth.redeemNativeAuthCode(code); - const req = { body: { code }, session: null } as unknown as Request; + const code = issue("token-2"); + nativeAuth.redeemNativeAuthCode(code, VERIFIER); + const req = exchangeRequest({ code, code_verifier: VERIFIER }); await expect(nativeAuth.Exchange(req, mockResponse())).rejects.toMatchObject({ status: 401, code: "invalid_auth_code", }); }); + it("rejects a code presented with the wrong verifier, and leaves it redeemable", async () => { + const code = issue("token-2c"); + const stolen = exchangeRequest({ code, code_verifier: OTHER_VERIFIER }); + await expect(nativeAuth.Exchange(stolen, mockResponse())).rejects.toMatchObject({ + status: 401, + code: "invalid_auth_code", + }); + expect(stolen.session).toBeNull(); + + const req = exchangeRequest({ code, code_verifier: VERIFIER }); + await nativeAuth.Exchange(req, mockResponse()); + expect(req.session).toEqual({ id_token: "token-2c" }); + }); + + it("rejects form posts and browser requests before looking at the code", async () => { + const code = issue("token-2d"); + const body = { code, code_verifier: VERIFIER }; + + const form = exchangeRequest(body, { + contentType: "application/x-www-form-urlencoded", + }); + await expect(nativeAuth.Exchange(form, mockResponse())).rejects.toMatchObject({ + status: 400, + code: "invalid_content_type", + }); + + const browser = exchangeRequest(body, { origin: "https://evil.example" }); + await expect(nativeAuth.Exchange(browser, mockResponse())).rejects.toMatchObject({ + status: 403, + }); + + // Neither attempt consumed the code. + const req = exchangeRequest(body); + await nativeAuth.Exchange(req, mockResponse()); + expect(req.session).toEqual({ id_token: "token-2d" }); + }); + it("establishes a session for a valid code", async () => { - const code = nativeAuth.issueNativeAuthCode({ id_token: "token-3" }); - const req = { body: { code }, session: null } as unknown as Request; + const code = issue("token-3"); + const req = exchangeRequest({ code, code_verifier: VERIFIER }); const res = mockResponse(); await nativeAuth.Exchange(req, res); expect(req.session).toEqual({ id_token: "token-3" });