diff --git a/.env.example b/.env.example index 0ad2520..8bd9cc9 100644 --- a/.env.example +++ b/.env.example @@ -35,6 +35,12 @@ 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=://...?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 REAL_IP_HEADER= diff --git a/README.md b/README.md index d8b7acd..dbdb9e0 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,16 @@ 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 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 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 ```bash diff --git a/src/index.ts b/src/index.ts index 5d677e9..9985562 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"; @@ -50,6 +51,7 @@ declare global { ALLOWED_IDENTITIES?: string; RELEASE_SYNC_TOKEN?: string; + NATIVE_APP_SCHEMES?: string; } } } @@ -151,6 +153,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..d90f0d1 --- /dev/null +++ b/src/native-auth.ts @@ -0,0 +1,160 @@ +import express from "express"; +import * as crypto from "crypto"; +import { LRUCache } from "lru-cache"; +import { + BadRequestError, + ForbiddenError, + 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. + * + * 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( + (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; + /** 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 +// 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, 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 || !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, 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) => { + 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, code_verifier); + 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..5142a15 100644 --- a/src/oidc.ts +++ b/src/oidc.ts @@ -3,6 +3,12 @@ import express from "express"; import { prisma } from "./db"; import { BadRequestError, UnauthorizedError } from "./errors"; import { isIdentityAllowed } from "./auth"; +import { + isNativeReturnTo, + issueNativeAuthCode, + nativeCodeChallenge, + nativeRedirectUrl, +} from "./native-auth"; import * as crypto from "crypto"; const API_HOSTNAME = process.env.API_HOSTNAME; @@ -165,5 +171,18 @@ 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. + // 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 new file mode 100644 index 0000000..682315e --- /dev/null +++ b/test/native-auth.test.ts @@ -0,0 +1,209 @@ +import { describe, it, expect, beforeAll, vi } from "vitest"; +import { Request, Response } from "express"; +import { createHash } from "crypto"; + +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"); +} + +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; + }; +} + +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 pending = { id_token: "token-1", code_challenge: CHALLENGE }; + const code = nativeAuth.issueNativeAuthCode(pending); + expect(code.length).toBeGreaterThanOrEqual(43); + 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`, without the challenge", () => { + const url = new URL( + 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" }), + ); + }); +}); + +describe("POST /auth/exchange", () => { + let nativeAuth: NativeAuth; + beforeAll(async () => { + nativeAuth = await loadWithSchemes("jetpilot"); + }); + + 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(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 = 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 = 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" }); + expect(res.json).toHaveBeenCalledWith({ ok: true }); + }); +});