Dough Git

commit

Let native apps sign in with a one-time code and PKCE

commit
d6c74783018d8a8d87fdee2b6ff77437cf609397
author
Clove Twilight <[email protected]>
date
2026-11-02 16:58
/plural/auth/sso/login?app=<S256 challenge> starts the same SSO flow; its
callback redirects to gay.doughmination.plural://auth?code=... with a
single-use code that expires after 60 seconds, never the JWT. The app swaps
code + verifier at POST /plural/auth/app/token for the usual token. Without
'app' the website's flow is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

diff --git a/src/system/routes/auth.ts b/src/system/routes/auth.ts
index 34bbe88..4c86a30 100644
--- a/src/system/routes/auth.ts
+++ b/src/system/routes/auth.ts
@@ -13,6 +13,15 @@
  *                              session, mint a JWT and hand the browser back to
  *                              the frontend with the token in the URL fragment.
  *   POST /auth/logout        — end the session here and at the SSO.
+ *   POST /auth/app/token     — a native app swaps its one-time code and PKCE
+ *                              verifier for the same JWT (see below).
+ *
+ * Native apps (the Plural Android app) start the same flow with
+ * /auth/sso/login?app=<S256 PKCE challenge>. Their callback never carries the
+ * JWT: it redirects to gay.doughmination.plural://auth?code=<one-time code>,
+ * and the app redeems that code within a minute at /auth/app/token with the
+ * verifier only it holds (services/app_codes.ts). Without `app` the flow is
+ * exactly the website's, unchanged.
  *
  * /auth/pocketid/login and /auth/pocketid/callback remain as aliases: the
  * published @doughmination/react-api client still builds the old login URL.
@@ -32,8 +41,10 @@ import {
   beginLogin,
   completeLogin,
   endSessionUrl,
+  isAppLogin,
   revokeRefreshToken,
 } from "../services/oidc";
+import { APP_CODE, PKCE_CHALLENGE, PKCE_VERIFIER, saveAppCode, takeAppCode } from "../services/app_codes";
 import { createSsoSession, endSsoSession } from "../services/sso_sessions";
 import { ssoPostLoginUrl, ssoLoginErrorUrl, ACCESS_TOKEN_EXPIRE_MINUTES } from "../config";
 import { createAccessToken, decodeAccessToken } from "../security";
@@ -64,8 +75,11 @@ function safeReturnPath(raw: string | undefined): string {
   return raw;
 }
 
-function loginError(c: Context<Env>, message: string) {
-  const url = new URL(ssoLoginErrorUrl());
+/** Where an app-started login lands; the Plural Android app handles this scheme. */
+const APP_REDIRECT = "gay.doughmination.plural://auth";
+
+function loginError(c: Context<Env>, message: string, app = false) {
+  const url = new URL(app ? APP_REDIRECT : ssoLoginErrorUrl());
   url.searchParams.set("error", message);
   return c.redirect(url.toString(), 302);
 }
@@ -73,30 +87,37 @@ function loginError(c: Context<Env>, message: string) {
 /** Start the SSO login: 302 to the provider's authorization endpoint. */
 async function login(c: Context<Env>) {
   const from = safeReturnPath(c.req.query("from"));
-  const authUrl = await beginLogin(from);
+  const app = c.req.query("app");
+  if (app !== undefined && !PKCE_CHALLENGE.test(app)) {
+    return c.json({ detail: "'app' must be an S256 PKCE challenge." }, 400);
+  }
+  const authUrl = await beginLogin(from, app);
   return c.redirect(authUrl, 302);
 }
 
 /** The SSO redirects the browser back here after the user authenticates. */
 async function callback(c: Context<Env>) {
+  const code = c.req.query("code");
+  const state = c.req.query("state");
+  // Errors go back to whoever started the login: the app or the website.
+  const app = await isAppLogin(state);
+
   const errorParam = c.req.query("error");
   if (errorParam === "access_denied") {
-    return loginError(c, "Your SSO account isn't allowed to use this site.");
+    return loginError(c, "Your SSO account isn't allowed to use this site.", app);
   }
-  if (errorParam) return loginError(c, errorParam);
+  if (errorParam) return loginError(c, errorParam, app);
 
-  const code = c.req.query("code");
-  const state = c.req.query("state");
-  if (!code || !state) return loginError(c, "missing_code");
+  if (!code || !state) return loginError(c, "missing_code", app);
 
   let result;
   try {
     result = await completeLogin(code, state, c.req.query("iss"));
   } catch (err) {
-    return loginError(c, err instanceof Error ? err.message : "Login failed. Please try again.");
+    return loginError(c, err instanceof Error ? err.message : "Login failed. Please try again.", app);
   }
 
-  const { identity, tokens, from } = result;
+  const { identity, tokens, from, appChallenge } = result;
 
   let user: User;
   try {
@@ -108,7 +129,7 @@ async function callback(c: Context<Env>) {
       displayName: identity.displayName,
     });
   } catch (err) {
-    return loginError(c, err instanceof Error ? err.message : "Could not sign you in.");
+    return loginError(c, err instanceof Error ? err.message : "Could not sign you in.", app);
   }
 
   const expiresAt = Date.now() + ACCESS_TOKEN_EXPIRE_MINUTES * 60 * 1000;
@@ -125,6 +146,13 @@ async function callback(c: Context<Env>) {
     avatar_url: user.avatar_url ?? null,
   });
 
+  // An app gets a one-time code, never the token: any app can claim a custom
+  // scheme, but only the one holding the PKCE verifier can redeem the code.
+  if (appChallenge) {
+    const appCode = await saveAppCode(token, appChallenge);
+    return c.redirect(`${APP_REDIRECT}?code=${encodeURIComponent(appCode)}`, 302);
+  }
+
   // Token goes in the fragment so it never lands in a server access log or the
   // Referer header; the frontend callback page reads it from location.hash.
   const dest = new URL(ssoPostLoginUrl());
@@ -137,6 +165,23 @@ authRoutes.get("/auth/sso/callback", callback);
 authRoutes.get("/auth/pocketid/login", login);
 authRoutes.get("/auth/pocketid/callback", callback);
 
+/** A native app redeems its one-time code (and PKCE verifier) for the JWT. */
+authRoutes.post("/auth/app/token", async (c) => {
+  const body = (await c.req.json().catch(() => ({}))) as { code?: unknown; verifier?: unknown };
+  const code = typeof body.code === "string" ? body.code : "";
+  const verifier = typeof body.verifier === "string" ? body.verifier : "";
+  if (!APP_CODE.test(code) || !PKCE_VERIFIER.test(verifier)) {
+    return c.json({ detail: "Body must include 'code' and a PKCE 'verifier'." }, 422);
+  }
+
+  const token = await takeAppCode(code, verifier);
+  c.header("Cache-Control", "no-store");
+  if (!token) {
+    return c.json({ detail: "That sign-in code is invalid or has expired. Please sign in again." }, 400);
+  }
+  return c.json({ access_token: token, token_type: "bearer" });
+});
+
 /**
  * End the caller's session. Accepts an expired or already-revoked token so a
  * stale tab can still sign out cleanly; returns the SSO URL the browser should
diff --git a/src/system/services/app_codes.ts b/src/system/services/app_codes.ts
new file mode 100644
index 0000000..da2f71b
--- /dev/null
+++ b/src/system/services/app_codes.ts
@@ -0,0 +1,69 @@
+/**
+ * Copyright (c) 2026 Clove Twilight
+ * Licensed under the ESAL-2.0 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+/**
+ * One-time sign-in codes for native apps.
+ *
+ * A browser can be handed its JWT in a URL fragment, but an app's redirect URI
+ * (a custom scheme) can be claimed by any other app on the phone. So an
+ * app-started login ends with a short-lived, single-use code instead, and the
+ * app swaps it at POST /v2/plural/auth/app/token together with the PKCE
+ * verifier only it holds. Anyone else who catches the redirect gets a useless
+ * code: without the verifier it can't be redeemed, and once redeemed (or after
+ * a minute) it's gone.
+ */
+
+import { rt } from "../runtime";
+import { constantTimeStringEqual, randomUrlToken, sha256Base64Url } from "../security";
+
+/** How long an app has to redeem its code. */
+export const APP_CODE_TTL_SECONDS = 60;
+
+/** An S256 PKCE challenge: base64url of a SHA-256 digest, 43 characters. */
+export const PKCE_CHALLENGE = /^[A-Za-z0-9_-]{43}$/;
+
+/** A code from saveAppCode: 32 random bytes, base64url. */
+export const APP_CODE = /^[A-Za-z0-9_-]{43}$/;
+
+/** RFC 7636 verifier: 43–128 unreserved characters. */
+export const PKCE_VERIFIER = /^[A-Za-z0-9._~-]{43,128}$/;
+
+interface StoredAppCode {
+  token: string;
+  challenge: string;
+  expiresAt: number;
+}
+
+function codeKey(code: string): string {
+  return `app_code:${code}`;
+}
+
+/** Park a freshly minted JWT behind a one-time code bound to the app's challenge. */
+export async function saveAppCode(token: string, challenge: string): Promise<string> {
+  const code = randomUrlToken(32);
+  await rt().store.put(codeKey(code), {
+    token,
+    challenge,
+    expiresAt: Date.now() + APP_CODE_TTL_SECONDS * 1000,
+  } satisfies StoredAppCode);
+  return code;
+}
+
+/**
+ * The JWT for a code, exactly once. The code is consumed on the first attempt,
+ * right or wrong, so a guessed verifier can't be retried. Null when the code is
+ * unknown, already used, expired, or the verifier doesn't match.
+ */
+export async function takeAppCode(code: string, verifier: string): Promise<string | null> {
+  const key = codeKey(code);
+  const stored = await rt().store.get<StoredAppCode | null>(key, null);
+  if (!stored) return null;
+  await rt().store.delete(key);
+
+  if (Date.now() > stored.expiresAt) return null;
+  const challenge = await sha256Base64Url(verifier);
+  return constantTimeStringEqual(challenge, stored.challenge) ? stored.token : null;
+}
diff --git a/src/system/services/oidc.ts b/src/system/services/oidc.ts
index 482b3ae..a2e39e8 100644
--- a/src/system/services/oidc.ts
+++ b/src/system/services/oidc.ts
@@ -113,6 +113,8 @@ interface StoredState {
   verifier: string;
   from: string;
   createdAt: number;
+  /** Set when a native app started this login: the app's own S256 PKCE challenge. */
+  appChallenge?: string;
 }
 
 function stateKey(state: string): string {
@@ -121,9 +123,10 @@ function stateKey(state: string): string {
 
 /**
  * Build the authorization redirect URL and persist the matching PKCE verifier.
- * `from` is the app path to return the user to after login.
+ * `from` is the app path to return the user to after login. `appChallenge` is
+ * set when a native app started the login (see routes/auth.ts).
  */
-export async function beginLogin(from: string): Promise<string> {
+export async function beginLogin(from: string, appChallenge?: string): Promise<string> {
   assertConfigured();
   const doc = await discover();
 
@@ -135,6 +138,7 @@ export async function beginLogin(from: string): Promise<string> {
     verifier,
     from: from || "/",
     createdAt: Date.now(),
+    ...(appChallenge ? { appChallenge } : {}),
   } satisfies StoredState);
 
   const authUrl = new URL(doc.authorization_endpoint);
@@ -153,6 +157,19 @@ export interface CallbackResult {
   tokens: SsoTokens;
   /** The original app path to return the user to. */
   from: string;
+  /** The native app's PKCE challenge, when an app started this login. */
+  appChallenge?: string;
+}
+
+/**
+ * Whether a pending login was started by a native app, without consuming it.
+ * Lets a callback that fails before the code exchange (the SSO refusing the
+ * account, say) still send the person back to the app rather than the website.
+ */
+export async function isAppLogin(state: string | undefined): Promise<boolean> {
+  if (!state) return false;
+  const stored = await rt().store.get<StoredState | null>(stateKey(state), null);
+  return Boolean(stored?.appChallenge);
 }
 
 /** Thrown when the SSO definitively refuses a grant (as opposed to being unreachable). */
@@ -275,6 +292,7 @@ export async function completeLogin(code: string, state: string, iss: string | u
       idToken: typeof tokens.id_token === "string" ? tokens.id_token : null,
     },
     from: stored.from || "/",
+    ...(stored.appChallenge ? { appChallenge: stored.appChallenge } : {}),
   };
 }