Files
CatoandClaude Fable 5.1 2077bfc207 feat(auth,docs): developer page for "Sign in with OrangeCat"; passkeys (#1185)
* feat(docs): developer page for "Sign in with OrangeCat" + round-trip script

Step D9 of ADR-0009. OrangeCat has been a real OpenID Connect provider
since June and five relying parties sign people in through it, but a site
that wanted the button had the standard and nothing else.

/docs/sign-in-with-orangecat: what you get (one identity keyed by sub,
passwords optional, people can disconnect you), self-service registration
with its rules, the Auth.js config Solon/Heidi/Loki run and the by-hand
authorize/token/userinfo/refresh calls, button wording (prompt=create,
login_hint), sessions and what invalid_grant means, and every scope with
its consent-screen wording. Every URL, scope and lifetime is derived from
the provider's own config (snippets.ts), and a unit test pins the snippets
to the discovery document, so the page cannot quote an endpoint the server
does not serve.

scripts/oauth/sign-in-roundtrip.mjs registers a client, opens the sign-in,
catches the code on loopback, exchanges it with PKCE, checks iss/aud/nonce,
reads userinfo, refreshes, and proves the spent token is refused — the
same steps any relying party takes, runnable before writing a line.

Linked from /docs. ADR-0009 status updated: D1–D4 shipped, relying parties
now honour revocation (solon#203, heidi#145).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QDMxjTqKNLXETMYYuapMa3

* fix(docs): userinfo snippet uses a shell variable for the token

gitleaks (curl-auth-header) reads 'Bearer THE_ACCESS_TOKEN' as a leaked
token; $ACCESS_TOKEN is what a person would paste anyway.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QDMxjTqKNLXETMYYuapMa3

* chore(security): allowlist the docs bearer-token placeholder for gitleaks

The developer page's userinfo example used 'Bearer THE_ACCESS_TOKEN', which
gitleaks' curl-auth-header rule reads as a leak. The tree now uses a shell
variable; the placeholder in history is allowlisted instead of rewriting it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QDMxjTqKNLXETMYYuapMa3

* feat(auth): passkeys — add/list/remove in settings, sign in with a passkey

Step D5 of ADR-0009. The self-hosted auth server (GoTrue) supports WebAuthn
passkeys and the browser client already carries the ceremony; what was
missing was the UI, the wrapper, and the switch.

- Settings → Security → Passkeys: the person's passkeys with name, date and
  last use; "Add a passkey" (browser prompt, then named); remove.
- /auth: "Sign in with a passkey" beside the emailed code — nothing typed.
- Both are hidden until the auth server reports passkeys_enabled: true
  (lib/auth/passkeys-availability reads GoTrue's public settings, cached
  five minutes, fails closed). A button that cannot work is a dead end.
- docs/operations/passkeys.md is the switch: GOTRUE_PASSKEY_ENABLED and the
  relying-party id/origins, with why the id is orangecat.ch and not the
  API host. scripts/auth/passkeys-e2e.mjs drives add → sign in → remove
  with Chromium's virtual authenticator and exits 2 while the switch is off.

services/supabase/auth/passkeys.ts wraps registerPasskey / passkey.list /
update / delete / signInWithPasskey in the auth service's shape; a passkey
is named in a second call and a failed rename still returns a working key.
Unit tests cover the availability parser and the wrappers.

Also: the two CLI scripts under scripts/ carry the no-console pragma their
siblings use.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QDMxjTqKNLXETMYYuapMa3

* fix(scripts): throwaway inbox password from crypto.randomBytes

CodeQL (js/insecure-randomness) flags Math.random() for a password, even
a disposable one; the real generator costs nothing.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QDMxjTqKNLXETMYYuapMa3

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-29 02:45:52 -07:00

162 lines
5.9 KiB
JavaScript

#!/usr/bin/env node
/* eslint-disable no-console -- a CLI talks through stdout */
/**
* Passkeys, end to end, against a real deployment — with Chromium's virtual
* authenticator standing in for a fingerprint reader.
*
* BASE=https://orangecat.ch node scripts/auth/passkeys-e2e.mjs
*
* Steps (the same three docs/operations/passkeys.md asks a person to do):
* 1. sign in with an emailed code (a throwaway mail.tm inbox);
* 2. Settings → Security → Passkeys → Add a passkey → listed;
* 3. sign out; /auth → Sign in with a passkey → signed in with nothing typed;
* 4. remove the passkey → the list is empty again.
*
* Needs `playwright` (a devDependency) and a Chromium. Exit 0 = every step
* answered as the runbook says. Skips with exit 2 when the server reports
* passkeys_enabled: false — that is the box switch, not a bug.
*/
import crypto from 'node:crypto';
import { chromium } from 'playwright';
const BASE = (process.env.BASE ?? 'https://orangecat.ch').replace(/\/$/, '');
const log = (...a) => console.log(new Date().toISOString().slice(11, 19), ...a);
const available = await (await fetch(`${BASE}/api/auth/passkeys/available`)).json();
if (available?.data?.available !== true) {
log(
'passkeys are switched off at the auth server — nothing to test (see docs/operations/passkeys.md)'
);
process.exit(2);
}
// Throwaway inbox for the code sign-in.
const MT = 'https://api.mail.tm';
async function mt(path, init = {}, token) {
const r = await fetch(MT + path, {
...init,
headers: {
'content-type': 'application/json',
...(token ? { authorization: `Bearer ${token}` } : {}),
},
});
if (!r.ok) {
throw new Error(`mail.tm ${path} ${r.status}`);
}
return r.json();
}
const domain = (await mt('/domains'))['hydra:member'][0].domain;
const address = `oc-passkey-${Date.now().toString(36)}@${domain}`;
const password = 'Pw-' + crypto.randomBytes(12).toString('base64url');
await mt('/accounts', { method: 'POST', body: JSON.stringify({ address, password }) });
const { token: mtToken } = await mt('/token', {
method: 'POST',
body: JSON.stringify({ address, password }),
});
async function waitForCode(after) {
for (let i = 0; i < 60; i++) {
const list = (await mt('/messages', {}, mtToken))['hydra:member'].filter(
m => new Date(m.createdAt).getTime() > after
);
if (list.length) {
const full = await mt(`/messages/${list[0].id}`, {}, mtToken);
const m = (full.text || '').match(/\b(\d{6})\b/);
if (m) {
return m[1];
}
}
await new Promise(r => setTimeout(r, 2000));
}
throw new Error('no code email');
}
const browser = await chromium.launch({
executablePath: process.env.CHROMIUM || undefined,
args: process.env.CHROMIUM_ARGS ? process.env.CHROMIUM_ARGS.split(' ') : [],
proxy: process.env.HTTPS_PROXY
? { server: process.env.HTTPS_PROXY, bypass: 'localhost' }
: undefined,
});
const context = await browser.newContext({ viewport: { width: 1280, height: 900 } });
const page = await context.newPage();
page.setDefaultTimeout(45_000);
// The virtual authenticator: a platform authenticator with resident keys and
// user verification, i.e. what Touch ID or Windows Hello look like to a page.
const cdp = await context.newCDPSession(page);
await cdp.send('WebAuthn.enable');
const { authenticatorId } = await cdp.send('WebAuthn.addVirtualAuthenticator', {
options: {
protocol: 'ctap2',
transport: 'internal',
hasResidentKey: true,
hasUserVerification: true,
isUserVerified: true,
automaticPresenceSimulation: true,
},
});
try {
// 1. Code sign-in.
await page.goto(`${BASE}/auth`, { waitUntil: 'domcontentloaded' });
const sentAt = Date.now();
const toggle = page.getByRole('button', { name: /code instead/i });
await toggle.waitFor();
for (
let i = 0;
i < 10 &&
!(await page
.locator('#code-email')
.isVisible()
.catch(() => false));
i++
) {
await toggle.click();
await page.waitForTimeout(1000);
}
await page.locator('#code-email').fill(address);
await page.getByRole('button', { name: 'Email me a code' }).click();
await page.locator('#code-digits').waitFor();
await page.fill('#code-digits', await waitForCode(sentAt - 1000));
await page.getByRole('button', { name: 'Continue' }).click();
await page.waitForURL(u => !new URL(u).pathname.startsWith('/auth'), { timeout: 60_000 });
log('signed in with a code');
// 2. Add a passkey.
await page.goto(`${BASE}/settings`, { waitUntil: 'domcontentloaded' });
await page.getByRole('button', { name: 'Add a passkey' }).click();
await page.getByLabel('Passkey name').fill('Virtual authenticator');
await page.getByRole('button', { name: 'Create passkey' }).click();
await page.getByText('Virtual authenticator').waitFor();
const creds = await cdp.send('WebAuthn.getCredentials', { authenticatorId });
if (creds.credentials.length !== 1) {
throw new Error(`expected 1 credential, got ${creds.credentials.length}`);
}
log('passkey created and listed');
// 3. Sign out, sign in with the passkey.
await page.goto(`${BASE}/auth/signout`, { waitUntil: 'domcontentloaded' }).catch(() => {});
await context.clearCookies();
await page.goto(`${BASE}/auth`, { waitUntil: 'domcontentloaded' });
await page.getByRole('button', { name: 'Sign in with a passkey' }).click();
await page.waitForURL(u => !new URL(u).pathname.startsWith('/auth'), { timeout: 60_000 });
log('signed in with the passkey, nothing typed');
// 4. Remove it.
await page.goto(`${BASE}/settings`, { waitUntil: 'domcontentloaded' });
page.once('dialog', d => d.accept());
await page
.getByRole('button', { name: /Remove passkey/ })
.first()
.click();
await page.getByText('No passkeys yet').waitFor();
log('passkey removed');
log('PASS');
} catch (e) {
await page.screenshot({ path: 'passkeys-e2e-fail.png', fullPage: true }).catch(() => {});
log('FAIL', e.message, page.url());
process.exitCode = 1;
} finally {
await browser.close();
}