Files
token-circles/worker/test/helpers/software-authenticator.ts
KomediruzeckiandGitHub d07247c26c feat(auth): passkey sign-in and registration (WebAuthn) (#502)
* feat(auth): TOTP two-factor authentication with recovery codes

Second factor for password and Google sign-in. Login now withholds the
session when the account has a confirmed TOTP credential: the browser
gets a 5-minute signed challenge cookie (fm_2fa) and /api/auth/2fa/verify
trades a valid authenticator or recovery code for the real session.

- RFC 6238 TOTP over WebCrypto (SHA-1/6/30 as authenticator apps expect),
  verified against the RFC's reference vectors; constant-time compares;
  last-used-step high-water mark so a code is never accepted twice.
- Secrets encrypted at rest (AES-256-GCM under an HKDF key from
  JWT_SECRET); decrypt failure fails CLOSED - the challenge remains and
  the SHA-256-hashed single-use recovery codes still sign you in.
- Enrollment in Settings: otpauth link + manual key, confirm with a live
  code, ten recovery codes shown exactly once. Disable demands a code.
- Rate limits on verify (10/15min/user), auth_logs twofa events, and the
  Google callback returns with ?twofa=1 so the SPA opens the code step.

* feat(auth): email-code sign-in (passwordless login)

"Email me a code": POST /api/auth/email-code/request mints a 6-digit
code (stored SHA-256-hashed, mailed via the existing template shell)
and answers the same neutral ok whether or not the address has an
account; /verify trades a live code for a session.

- Single active code per user, single use (atomic claim), 10-minute
  TTL, rejection-sampled generation (no modulo bias).
- Layered rate limits mirroring forgot-password: per-IP send flood
  guard, 3 sends/hour/address, 10 verify tries/15 min/address.
- A verified code proves inbox control, so it also resolves the
  pending email_verified flag.
- 2FA accounts still get the authenticator challenge after the code -
  the inbox is one factor, not two. Sessions record provider 'email'
  (labelled in the devices list).
- Frontend: shared EmailCodeLogin step wired into LoginScreen and
  LoginModal ("Email me a sign-in code"), with its own Turnstile
  instance and resend flow.

* feat(auth): passkey sign-in and registration (WebAuthn)

Sign in with a passkey from the login screen, add/remove passkeys in
Settings, and a one-shot post-login nudge to set one up on supported
devices.

Server (@simplewebauthn/server):
- Ceremony state rides a short-lived signed httpOnly cookie
  (fm_webauthn), same construction as the 2FA challenge — stateless
  between options and verify, purpose-bound (reg vs auth), 300s TTL.
- RP identity is the frontend origin (CORS_ORIGIN), never the API host.
- Login requires user verification (device PIN/biometric), so a passkey
  is possession + inherence in one gesture and deliberately does NOT
  trigger the TOTP challenge; sessions carry provider 'passkey'.
- Registration: discoverable credentials (residentKey required),
  attestation 'none', excludeCredentials against existing keys,
  counter + last_used_at maintained on every login.

Tests drive real ceremonies through a software FIDO2 authenticator
(minimal CBOR/COSE + raw-to-DER ECDSA), not mocks.

Frontend: core/webauthn.ts glue (base64url conversions, abort-aware
ceremonies), PasskeySettings card (hidden without WebAuthn),
PasskeyNudge banner, login screen/modal entry points, 'Passkey'
provider label in signed-in devices.

* feat(2fa): QR enrollment and a full-loop e2e spec

- Enroll now shows a QR code of the otpauth URI, rendered locally with
  uqr — the shared secret never leaves the page, so external QR image
  services are not an option. White backing keeps it scannable in dark
  mode. Manual key entry and the open-directly link stay.
- New Playwright spec drives the whole loop through the real UI with a
  dedicated user: enroll (computing codes from the on-screen secret the
  way an authenticator app would), wrong-code rejection, TOTP challenge
  sign-in, recovery-code sign-in, disable via recovery code.
- tests/db.ts: shared local-D1 helpers (sql / sqlRows) so auth specs can
  arrange state the API deliberately refuses to expose.

* fix(2fa): close the review findings on the 2FA lifecycle

Security:
- /2fa/disable now shares the 2fa:<user> attempt bucket with /2fa/verify
  (and clears it on success). It accepts the same factors, so it must not
  hand an attacker a fresh guessing budget; before this, a stolen session
  could brute-force the disable endpoint unmetered.
- Enabling 2FA deletes every OTHER auth session. Sessions that predate
  enrollment got in on one factor — including the intruder the user may
  be enrolling against. Only the enrolling session survives.
- Account deletion now removes totp_credentials and recovery_codes; the
  encrypted secret and code hashes used to outlive the account.

UX / recoverability:
- "Create account" with an existing 2FA-protected email now lands on the
  code challenge instead of a silent reload loop (both login surfaces).
- Recovery codes: a Download button joins Copy (clipboard is unavailable
  in non-secure contexts and the codes are unrecoverable once revealed),
  and Settings warns loudly when 3 or fewer codes remain.
- The challenge's recovery/back controls are real buttons — keyboard and
  assistive-tech reachable; they were onClick-only anchors, invisible to
  the tab order, gating the only path in after a lost phone.
- Backing out of the challenge strips the ?twofa=1 marker, so a reload
  no longer reopens a dead challenge for an expired cookie.

Not addressed here (accepted, low): recovery-code spend before a failed
session write; the two-tab concurrent-setup race (second secret wins).

* fix(email-code): bind verification to the requesting browser; close review findings

The 10^6 code space was defended only by resettable rate-limit windows:
~10 free guesses per code with no captcha on /verify, horizontally
scalable across addresses, plus two denial-of-service handles (fill the
per-address verify bucket to lock an inbox out; fire /request to delete
the code the victim was typing).

Redesign: /request now sets a signed ceremony cookie (fm_logincode, the
fm_2fa construction, TTL = code TTL) naming the one code row that
browser may attempt; /verify accepts nothing without it.

- A third party who triggers codes for someone else's address gets a
  cookie for a code they cannot read — no guessing surface, no way to
  spend the victim's budget. The per-address verify bucket is gone
  (nothing left to lock), the per-IP one stays and clears on success.
- Wrong guesses increment a per-code attempts counter; five misses burn
  the code even if the right value is presented later.
- /request no longer deletes previous unused codes (that was the DoS
  handle); live codes are capped at three, oldest pruned.
- Anti-enumeration hardened: unknown addresses get the same cookie and
  the same code+hash work; the Resend call moved off the response path
  (waitUntil + swallow) — it was a 100-400ms timing oracle and its
  failures turned into 500-for-registered / 200-for-unknown.
- Account deletion removes login_codes rows.
- UI: the code field focuses itself when the verify step appears, and
  the captcha-disabled send button now explains itself (captcha-hint,
  LoginScreen's rule).
- New e2e spec drives the real UI loop, rewriting the minted row's hash
  to a known value via the local-D1 side door (the mailed code is
  unreadable by design); tests/db.ts retries on SQLITE_BUSY so parallel
  specs share the database calmly.

Accepted trade-off: entering the code on a different device than the
one that requested it no longer works (the UI never offered that flow).

* feat(passkeys): conditional autofill, Google-login nudge, e2e; close review findings

Follow-ups:
- Conditional UI: on capable browsers the login screen starts a
  background WebAuthn request so the email field's autofill offers
  saved passkeys — one tap, no button. Aborted before the explicit
  button's modal request and on unmount; quiet on failure (the button
  path reports errors). The email input carries autocomplete
  "username webauthn".
- The Google button now sets the passkey-nudge flag; sessionStorage
  survives the OAuth round-trip in the same tab, so Google sign-ins get
  the post-login "add a passkey?" offer too.
- New Playwright spec runs the whole loop against Chromium's virtual
  authenticator (CDP WebAuthn domain): add in Settings, sign out, sign
  back in with the passkey button. It runs at localhost (not 127.0.0.1)
  because that is the hostname passkeys are bound to.

Review fixes (the blocking one first):
- Registration now requires a FRESH session (10 min) or a re-presented
  password / 2FA code. A credential that skips TOTP and survives
  password resets must cost more than a bare session cookie; the
  post-login nudge is always fresh, so its flow is unchanged. Inline
  confirm field in Settings handles the stale case.
- Registration demands user verification, matching login — a UV-less
  authenticator used to register fine and then fail every sign-in
  forever.
- Replayed registration answers 409, not a raw D1 UNIQUE error string.
- A signature counter that runs backwards logs as
  passkey_counter_regression — the one signal of a cloned credential —
  instead of blending into passkey_failed.
- Registration is rate-limited (20/h) and capped at 10 passkeys per
  account (unbounded rows eventually overflow authenticators'
  excludeCredentials limits and brick the owner's own add button).
- login/options budget raised to 60/15min: conditional UI fires one
  per login-screen load, and offices share IPs.
- rpOrigin no longer falls back to the API host when CORS_ORIGIN and
  APP_ORIGINS are both unset — that minted credentials bound to
  api.<domain> that could never sign in; it now fails closed.
- Account deletion removes webauthn_credentials.
- Ceremony failures log the raw error to the console (browsers blur
  cancel / no-credential / config-mismatch into NotAllowedError; the
  console line is the only diagnostic left).
- Test authenticator tracks its signature counter so specs can sign in
  repeatedly, and can emit UV-less attestations for the negative test.
2026-08-30 18:31:48 +02:00

207 lines
6.8 KiB
TypeScript

/**
* A minimal software FIDO2 authenticator (ES256, attestation "none") so passkey tests can run
* REAL registration and authentication ceremonies against the worker — no mocks, the same bytes
* a platform authenticator would produce.
*/
const enc = new TextEncoder();
export function b64url(data: ArrayBuffer | Uint8Array): string {
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
let s = '';
for (const b of bytes) s += String.fromCharCode(b);
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
// ── Tiny CBOR writer (just what an attestation object needs) ──────────────────
function cborUint(n: number, major: number): Uint8Array {
const m = major << 5;
if (n < 24) return new Uint8Array([m | n]);
if (n < 256) return new Uint8Array([m | 24, n]);
const out = new Uint8Array(3);
out[0] = m | 25;
new DataView(out.buffer).setUint16(1, n);
return out;
}
function concat(...parts: Uint8Array[]): Uint8Array {
const total = parts.reduce((s, p) => s + p.length, 0);
const out = new Uint8Array(total);
let o = 0;
for (const p of parts) {
out.set(p, o);
o += p.length;
}
return out;
}
type CborValue = number | string | Uint8Array | Map<number | string, CborValue>;
function cbor(value: CborValue): Uint8Array {
if (typeof value === 'number') {
if (value >= 0) return cborUint(value, 0);
return cborUint(-value - 1, 1); // negative int
}
if (typeof value === 'string')
return concat(cborUint(enc.encode(value).length, 3), enc.encode(value));
if (value instanceof Uint8Array) return concat(cborUint(value.length, 2), value);
const entries = [...value.entries()];
return concat(cborUint(entries.length, 5), ...entries.flatMap(([k, v]) => [cbor(k), cbor(v)]));
}
// ── ECDSA raw (r||s) -> ASN.1 DER, which is what WebAuthn signatures use ─────
function derEncodeSignature(raw: Uint8Array): Uint8Array {
const derInt = (bytes: Uint8Array): Uint8Array => {
let i = 0;
while (i < bytes.length - 1 && bytes[i] === 0) i++;
let v = bytes.slice(i);
if (v[0]! & 0x80) v = concat(new Uint8Array([0]), v);
return concat(new Uint8Array([0x02, v.length]), v);
};
const r = derInt(raw.slice(0, 32));
const s = derInt(raw.slice(32));
return concat(new Uint8Array([0x30, r.length + s.length]), r, s);
}
async function sha256(data: Uint8Array): Promise<Uint8Array> {
return new Uint8Array(await crypto.subtle.digest('SHA-256', data as BufferSource));
}
export interface SoftwareAuthenticator {
credentialId: Uint8Array;
register(
challengeB64url: string,
origin: string,
rpId: string,
opts?: { userVerified?: boolean }
): Promise<RegistrationResponseJSONish>;
authenticate(
challengeB64url: string,
origin: string,
rpId: string,
opts?: { counter?: number; userVerified?: boolean }
): Promise<AuthenticationResponseJSONish>;
}
export interface RegistrationResponseJSONish {
id: string;
rawId: string;
type: 'public-key';
clientExtensionResults: Record<string, never>;
response: { clientDataJSON: string; attestationObject: string; transports: string[] };
}
export interface AuthenticationResponseJSONish {
id: string;
rawId: string;
type: 'public-key';
clientExtensionResults: Record<string, never>;
response: {
clientDataJSON: string;
authenticatorData: string;
signature: string;
userHandle: string | null;
};
}
export async function createAuthenticator(): Promise<SoftwareAuthenticator> {
const keys = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [
'sign',
'verify',
]);
const rawPub = new Uint8Array(await crypto.subtle.exportKey('raw', keys.publicKey)); // 0x04||x||y
const x = rawPub.slice(1, 33);
const y = rawPub.slice(33, 65);
const credentialId = crypto.getRandomValues(new Uint8Array(32));
// COSE_Key (EC2/ES256): {1: 2, 3: -7, -1: 1, -2: x, -3: y}
const coseKey = cbor(
new Map<number, CborValue>([
[1, 2],
[3, -7],
[-1, 1],
[-2, x],
[-3, y],
])
);
const authDataFor = async (rpId: string, flags: number, counter: number, attested: boolean) => {
const rpIdHash = await sha256(enc.encode(rpId));
const head = new Uint8Array(37);
head.set(rpIdHash, 0);
head[32] = flags;
new DataView(head.buffer).setUint32(33, counter);
if (!attested) return head;
const credLen = new Uint8Array(2);
new DataView(credLen.buffer).setUint16(0, credentialId.length);
return concat(head, new Uint8Array(16), credLen, credentialId, coseKey); // AAGUID = zeros
};
// A real authenticator's signature counter climbs on every use; tracking it here means a
// test can sign in repeatedly without tripping the library's clone detection.
let signCount = 0;
return {
credentialId,
async register(challengeB64url, origin, rpId, opts = {}) {
const clientData = enc.encode(
JSON.stringify({
type: 'webauthn.create',
challenge: challengeB64url,
origin,
crossOrigin: false,
})
);
// UP | AT, plus UV unless the test wants a verification-less authenticator.
const flags = 0x41 | (opts.userVerified === false ? 0 : 0x04);
const authData = await authDataFor(rpId, flags, 0, true);
const attestationObject = cbor(
new Map<string, CborValue>([
['fmt', 'none'],
['attStmt', new Map()],
['authData', authData],
])
);
return {
id: b64url(credentialId),
rawId: b64url(credentialId),
type: 'public-key',
clientExtensionResults: {},
response: {
clientDataJSON: b64url(clientData),
attestationObject: b64url(attestationObject),
transports: ['internal'],
},
};
},
async authenticate(challengeB64url, origin, rpId, opts = {}) {
const clientData = enc.encode(
JSON.stringify({
type: 'webauthn.get',
challenge: challengeB64url,
origin,
crossOrigin: false,
})
);
const flags = 0x01 | (opts.userVerified === false ? 0 : 0x04); // UP, UV unless disabled
const authData = await authDataFor(rpId, flags, opts.counter ?? ++signCount, false);
const toSign = concat(authData, await sha256(clientData));
const rawSig = new Uint8Array(
await crypto.subtle.sign(
{ name: 'ECDSA', hash: 'SHA-256' },
keys.privateKey,
toSign as BufferSource
)
);
return {
id: b64url(credentialId),
rawId: b64url(credentialId),
type: 'public-key',
clientExtensionResults: {},
response: {
clientDataJSON: b64url(clientData),
authenticatorData: b64url(authData),
signature: b64url(derEncodeSignature(rawSig)),
userHandle: null,
},
};
},
};
}