Public: anyone can read this; the crew can change it.
Passkeys, part 1: a signed-in person adds, uses and removes passkeys, and signs in with one #1677
scout/forge:scout/1617-passkeys-part-1-a-signed-in-person-adds → main 2 commits fork
15 files
changed +1353
−4
README.md +7
| @@ -89,6 +89,13 @@ username and password — which links that key to your account, so the next | ||
| 89 | 89 | connection is instant. `j`/`k` to move, `enter` to open, `esc` to go back, `/` |
| 90 | 90 | to filter, `?` for the keys, `:` for the command palette, `t` for the theme. |
| 91 | 91 | |
| 92 | **Passkeys.** Settings → Passkeys adds, lists and removes WebAuthn passkeys | |
| 93 | (ES256 and RS256; an account may hold several), and the sign-in page offers | |
| 94 | "Sign in with a passkey", which issues the same session a password does. No | |
| 95 | dependency: `src/auth/webauthn.ts` checks challenge, origin, rpId, user | |
| 96 | presence, signature and signCount with WebCrypto and a small CBOR reader. | |
| 97 | Attestation is "none" (never trusted). Sign-up and recovery are not part of it. | |
| 98 | ||
| 92 | 99 | **Milestones.** `:` → *Milestones in a repository* → `owner/name` lists a |
| 93 | 100 | repository's limbs in the order the crew takes ready work (`enter` opens a |
| 94 | 101 | limb's own limbs). A person who administers the repository presses `r` to |
scripts/gate.ts +1
| @@ -201,6 +201,7 @@ export const GATE: readonly string[] = [ | ||
| 201 | 201 | "test/issues.test.ts", |
| 202 | 202 | "test/kernel.test.ts", |
| 203 | 203 | "test/keys.test.ts", |
| 204 | "test/passkeys.test.ts", | |
| 204 | 205 | "test/limb_order.test.ts", |
| 205 | 206 | "test/limbs.test.ts", |
| 206 | 207 | "test/live-pages.test.ts", |
src/actions/passkeys.ts added +215
| @@ -0,0 +1,215 @@ | ||
| 1 | /** | |
| 2 | * Passkeys: a signed-in person adds, lists and removes them, and anyone | |
| 3 | * holding one signs in with it. Each ceremony is two calls — options (which | |
| 4 | * issues a single-use challenge), then the browser's answer — and the answer | |
| 5 | * is only believed against that challenge, this origin and this rpId. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { App } from "../app.ts"; | |
| 9 | import { | |
| 10 | b64urlDecode, | |
| 11 | b64urlEncode, | |
| 12 | verifyAssertion, | |
| 13 | verifyRegistration, | |
| 14 | type Expected, | |
| 15 | type WebauthnError, | |
| 16 | } from "../auth/webauthn.ts"; | |
| 17 | import { | |
| 18 | addPasskey, | |
| 19 | deletePasskey, | |
| 20 | issueChallenge, | |
| 21 | listPasskeys, | |
| 22 | PASSKEYS_MAX, | |
| 23 | passkeyByCredential, | |
| 24 | spendChallenge, | |
| 25 | touchPasskey, | |
| 26 | type Passkey, | |
| 27 | } from "../core/passkeys.ts"; | |
| 28 | import { getUserById, isActive, type User } from "../core/users.ts"; | |
| 29 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 30 | import { requireUser } from "./access.ts"; | |
| 31 | ||
| 32 | /** Where the ceremony is happening: this request's own origin. */ | |
| 33 | export interface Where { | |
| 34 | readonly origin: string; | |
| 35 | readonly rpId: string; | |
| 36 | } | |
| 37 | ||
| 38 | export type PasskeyError = | |
| 39 | | "unauthorized" | |
| 40 | | "invalid" | |
| 41 | | "challenge" | |
| 42 | | "too_many" | |
| 43 | | "exists" | |
| 44 | | "not_found" | |
| 45 | | WebauthnError; | |
| 46 | ||
| 47 | const NAME_MAX = 60; | |
| 48 | ||
| 49 | /** A JSON body field that must be a base64url string of bounded size. */ | |
| 50 | const bytes = (v: unknown): Uint8Array | undefined => b64urlDecode(v); | |
| 51 | ||
| 52 | const expected = (challenge: string, where: Where): Expected => ({ | |
| 53 | challenge, | |
| 54 | origin: where.origin, | |
| 55 | rpId: where.rpId, | |
| 56 | }); | |
| 57 | ||
| 58 | ||
| 59 | /** The options `navigator.credentials.create` takes, plain data. */ | |
| 60 | export function registrationOptions( | |
| 61 | app: App, | |
| 62 | actor: User | undefined, | |
| 63 | where: Where, | |
| 64 | ): Result<unknown, PasskeyError> { | |
| 65 | const user = requireUser(actor); | |
| 66 | if (!user.ok) return err("unauthorized"); | |
| 67 | const have = listPasskeys(app.db, user.value.id); | |
| 68 | if (have.length >= PASSKEYS_MAX) return err("too_many"); | |
| 69 | const challenge = issueChallenge(app.db, "register", user.value.id); | |
| 70 | if (challenge === undefined) return err("too_many"); | |
| 71 | return ok({ | |
| 72 | challenge, | |
| 73 | rp: { id: where.rpId, name: "forge" }, | |
| 74 | user: { | |
| 75 | id: b64urlEncode(new TextEncoder().encode(user.value.id)), | |
| 76 | name: user.value.username, | |
| 77 | displayName: user.value.displayName || user.value.username, | |
| 78 | }, | |
| 79 | pubKeyCredParams: [ | |
| 80 | { type: "public-key", alg: -7 }, | |
| 81 | { type: "public-key", alg: -257 }, | |
| 82 | ], | |
| 83 | excludeCredentials: have.map((p) => ({ | |
| 84 | type: "public-key", | |
| 85 | id: p.credentialId, | |
| 86 | })), | |
| 87 | authenticatorSelection: { | |
| 88 | residentKey: "required", | |
| 89 | userVerification: "preferred", | |
| 90 | }, | |
| 91 | attestation: "none", | |
| 92 | timeout: 120000, | |
| 93 | }); | |
| 94 | } | |
| 95 | ||
| 96 | export async function addPasskeyFrom( | |
| 97 | app: App, | |
| 98 | actor: User | undefined, | |
| 99 | where: Where, | |
| 100 | body: unknown, | |
| 101 | ): Promise<Result<Passkey, PasskeyError>> { | |
| 102 | const user = requireUser(actor); | |
| 103 | if (!user.ok) return err("unauthorized"); | |
| 104 | if (typeof body !== "object" || body === null) return err("invalid"); | |
| 105 | const b = body as Record<string, unknown>; | |
| 106 | const clientDataJSON = bytes(b.clientDataJSON); | |
| 107 | const attestationObject = bytes(b.attestationObject); | |
| 108 | if ( | |
| 109 | typeof b.challenge !== "string" || | |
| 110 | clientDataJSON === undefined || | |
| 111 | attestationObject === undefined | |
| 112 | ) | |
| 113 | return err("invalid"); | |
| 114 | const name = | |
| 115 | typeof b.name === "string" ? b.name.trim().slice(0, NAME_MAX) : ""; | |
| 116 | // Spent first: a failed attempt burns its challenge too. | |
| 117 | if (!spendChallenge(app.db, b.challenge, "register", user.value.id)) | |
| 118 | return err("challenge"); | |
| 119 | if (listPasskeys(app.db, user.value.id).length >= PASSKEYS_MAX) | |
| 120 | return err("too_many"); | |
| 121 | const verified = await verifyRegistration( | |
| 122 | { clientDataJSON, attestationObject }, | |
| 123 | expected(b.challenge, where), | |
| 124 | ); | |
| 125 | if (!verified.ok) return err(verified.error); | |
| 126 | const added = addPasskey(app.db, { | |
| 127 | userId: user.value.id, | |
| 128 | name: name === "" ? "Passkey" : name, | |
| 129 | credentialId: b64urlEncode(verified.value.credentialId), | |
| 130 | key: verified.value.key, | |
| 131 | signCount: verified.value.signCount, | |
| 132 | }); | |
| 133 | if (!added) return err("exists"); | |
| 134 | app.bus.append({ | |
| 135 | kind: "user.passkey_added", | |
| 136 | actorId: user.value.id, | |
| 137 | payload: { name: added.name }, | |
| 138 | }); | |
| 139 | return ok(added); | |
| 140 | } | |
| 141 | ||
| 142 | export function removePasskey( | |
| 143 | app: App, | |
| 144 | actor: User | undefined, | |
| 145 | id: string, | |
| 146 | ): Result<void, PasskeyError> { | |
| 147 | const user = requireUser(actor); | |
| 148 | if (!user.ok) return err("unauthorized"); | |
| 149 | const name = deletePasskey(app.db, user.value.id, id); | |
| 150 | if (name === undefined) return err("not_found"); | |
| 151 | app.bus.append({ | |
| 152 | kind: "user.passkey_removed", | |
| 153 | actorId: user.value.id, | |
| 154 | payload: { name }, | |
| 155 | }); | |
| 156 | return ok(); | |
| 157 | } | |
| 158 | ||
| 159 | /** Sign-in options: no username, the authenticator offers its own passkeys. */ | |
| 160 | export function signinOptions( | |
| 161 | app: App, | |
| 162 | where: Where, | |
| 163 | ): Result<unknown, PasskeyError> { | |
| 164 | const challenge = issueChallenge(app.db, "signin"); | |
| 165 | if (challenge === undefined) return err("too_many"); | |
| 166 | return ok({ | |
| 167 | challenge, | |
| 168 | rpId: where.rpId, | |
| 169 | allowCredentials: [], | |
| 170 | userVerification: "preferred", | |
| 171 | timeout: 120000, | |
| 172 | }); | |
| 173 | } | |
| 174 | ||
| 175 | /** The account a passkey assertion proves, or why not. */ | |
| 176 | export async function signinWithPasskey( | |
| 177 | app: App, | |
| 178 | where: Where, | |
| 179 | body: unknown, | |
| 180 | ): Promise<Result<User, PasskeyError>> { | |
| 181 | if (typeof body !== "object" || body === null) return err("invalid"); | |
| 182 | const b = body as Record<string, unknown>; | |
| 183 | const clientDataJSON = bytes(b.clientDataJSON); | |
| 184 | const authenticatorData = bytes(b.authenticatorData); | |
| 185 | const signature = bytes(b.signature); | |
| 186 | if ( | |
| 187 | typeof b.challenge !== "string" || | |
| 188 | typeof b.id !== "string" || | |
| 189 | clientDataJSON === undefined || | |
| 190 | authenticatorData === undefined || | |
| 191 | signature === undefined | |
| 192 | ) | |
| 193 | return err("invalid"); | |
| 194 | if (!spendChallenge(app.db, b.challenge, "signin")) return err("challenge"); | |
| 195 | const passkey = passkeyByCredential(app.db, b.id); | |
| 196 | if (!passkey) return err("not_found"); | |
| 197 | const verified = await verifyAssertion( | |
| 198 | { clientDataJSON, authenticatorData, signature }, | |
| 199 | expected(b.challenge, where), | |
| 200 | { key: passkey.key, signCount: passkey.signCount }, | |
| 201 | ); | |
| 202 | if (!verified.ok) return err(verified.error); | |
| 203 | if ( | |
| 204 | !touchPasskey( | |
| 205 | app.db, | |
| 206 | passkey.id, | |
| 207 | passkey.signCount, | |
| 208 | verified.value.signCount, | |
| 209 | ) | |
| 210 | ) | |
| 211 | return err("sign_count"); | |
| 212 | const user = getUserById(app.db, passkey.userId); | |
| 213 | if (!user || !isActive(user)) return err("not_found"); | |
| 214 | return ok(user); | |
| 215 | } |
src/auth/webauthn.ts added +313
| @@ -0,0 +1,313 @@ | ||
| 1 | /** | |
| 2 | * WebAuthn, the two ceremonies a relying party needs: registering a passkey | |
| 3 | * and checking an assertion. ES256 and RS256 only, attestation "none" (the | |
| 4 | * attestation statement is never trusted, so it is never read). Plain data | |
| 5 | * in, a Result out; the caller owns challenges, storage and sessions. | |
| 6 | * | |
| 7 | * A passkey's public key is kept as a JWK, so what the database holds is | |
| 8 | * what WebCrypto imports. | |
| 9 | */ | |
| 10 | ||
| 11 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 12 | ||
| 13 | export type PasskeyAlg = "ES256" | "RS256"; | |
| 14 | ||
| 15 | export interface PasskeyKey { | |
| 16 | readonly alg: PasskeyAlg; | |
| 17 | readonly jwk: Record<string, string>; | |
| 18 | } | |
| 19 | ||
| 20 | /** What the browser hands back, base64url strings decoded to bytes. */ | |
| 21 | export interface RegistrationResponse { | |
| 22 | readonly clientDataJSON: Uint8Array; | |
| 23 | readonly attestationObject: Uint8Array; | |
| 24 | } | |
| 25 | export interface AssertionResponse { | |
| 26 | readonly clientDataJSON: Uint8Array; | |
| 27 | readonly authenticatorData: Uint8Array; | |
| 28 | readonly signature: Uint8Array; | |
| 29 | } | |
| 30 | ||
| 31 | /** What the relying party expects the ceremony to have been about. */ | |
| 32 | export interface Expected { | |
| 33 | /** The challenge this ceremony issued, as base64url. */ | |
| 34 | readonly challenge: string; | |
| 35 | /** The page origin, e.g. `https://forge.example`. */ | |
| 36 | readonly origin: string; | |
| 37 | /** The relying party id: the page's hostname. */ | |
| 38 | readonly rpId: string; | |
| 39 | } | |
| 40 | ||
| 41 | export type WebauthnError = | |
| 42 | | "malformed" | |
| 43 | | "wrong_type" | |
| 44 | | "wrong_challenge" | |
| 45 | | "wrong_origin" | |
| 46 | | "wrong_rp" | |
| 47 | | "no_presence" | |
| 48 | | "unsupported_key" | |
| 49 | | "bad_signature" | |
| 50 | | "sign_count"; | |
| 51 | ||
| 52 | const MAX_BYTES = 16 * 1024; | |
| 53 | const FLAG_UP = 0x01; | |
| 54 | const FLAG_AT = 0x40; | |
| 55 | ||
| 56 | // ---- base64url ---- | |
| 57 | ||
| 58 | export function b64urlEncode(bytes: Uint8Array): string { | |
| 59 | return Buffer.from(bytes).toString("base64url"); | |
| 60 | } | |
| 61 | ||
| 62 | /** Strict: only the base64url alphabet, bounded. Undefined when it is not. */ | |
| 63 | export function b64urlDecode(text: unknown): Uint8Array | undefined { | |
| 64 | if (typeof text !== "string" || text.length > MAX_BYTES * 2) return undefined; | |
| 65 | if (!/^[A-Za-z0-9_-]*$/.test(text)) return undefined; | |
| 66 | return new Uint8Array(Buffer.from(text, "base64url")); | |
| 67 | } | |
| 68 | ||
| 69 | // ---- CBOR: the subset an attestation object and a COSE key use ---- | |
| 70 | ||
| 71 | type Cbor = number | bigint | Uint8Array | string | Cbor[] | Map<Cbor, Cbor>; | |
| 72 | ||
| 73 | class Cursor { | |
| 74 | offset = 0; | |
| 75 | constructor(readonly bytes: Uint8Array) {} | |
| 76 | byte(): number { | |
| 77 | const b = this.bytes[this.offset++]; | |
| 78 | if (b === undefined) throw new Error("short"); | |
| 79 | return b; | |
| 80 | } | |
| 81 | take(n: number): Uint8Array { | |
| 82 | if (n < 0 || this.offset + n > this.bytes.length) throw new Error("short"); | |
| 83 | const out = this.bytes.subarray(this.offset, this.offset + n); | |
| 84 | this.offset += n; | |
| 85 | return out; | |
| 86 | } | |
| 87 | } | |
| 88 | ||
| 89 | function cborLength(c: Cursor, info: number): number { | |
| 90 | if (info < 24) return info; | |
| 91 | const width = { 24: 1, 25: 2, 26: 4 }[info]; | |
| 92 | if (width === undefined) throw new Error("length"); | |
| 93 | let n = 0; | |
| 94 | for (const b of c.take(width)) n = n * 256 + b; | |
| 95 | return n; | |
| 96 | } | |
| 97 | ||
| 98 | function cborItem(c: Cursor, depth: number): Cbor { | |
| 99 | if (depth > 8) throw new Error("deep"); | |
| 100 | const head = c.byte(); | |
| 101 | const major = head >> 5; | |
| 102 | const info = head & 31; | |
| 103 | const n = cborLength(c, info); | |
| 104 | switch (major) { | |
| 105 | case 0: | |
| 106 | return n; | |
| 107 | case 1: | |
| 108 | return -1 - n; | |
| 109 | case 2: | |
| 110 | return c.take(n); | |
| 111 | case 3: | |
| 112 | return new TextDecoder("utf-8", { fatal: true }).decode(c.take(n)); | |
| 113 | case 4: { | |
| 114 | if (n > 64) throw new Error("big"); | |
| 115 | return Array.from({ length: n }, () => cborItem(c, depth + 1)); | |
| 116 | } | |
| 117 | case 5: { | |
| 118 | if (n > 64) throw new Error("big"); | |
| 119 | const map = new Map<Cbor, Cbor>(); | |
| 120 | for (let i = 0; i < n; i++) | |
| 121 | map.set(cborItem(c, depth + 1), cborItem(c, depth + 1)); | |
| 122 | return map; | |
| 123 | } | |
| 124 | default: | |
| 125 | throw new Error("unsupported"); | |
| 126 | } | |
| 127 | } | |
| 128 | ||
| 129 | /** One CBOR item and how many bytes it took. */ | |
| 130 | function cborDecode(bytes: Uint8Array): { value: Cbor; used: number } { | |
| 131 | const c = new Cursor(bytes); | |
| 132 | const value = cborItem(c, 0); | |
| 133 | return { value, used: c.offset }; | |
| 134 | } | |
| 135 | ||
| 136 | // ---- COSE key → JWK ---- | |
| 137 | ||
| 138 | function coseKey(bytes: Uint8Array): PasskeyKey | undefined { | |
| 139 | const { value } = cborDecode(bytes); | |
| 140 | if (!(value instanceof Map)) return undefined; | |
| 141 | const bin = (k: number): string | undefined => { | |
| 142 | const v = value.get(k); | |
| 143 | return v instanceof Uint8Array ? b64urlEncode(v) : undefined; | |
| 144 | }; | |
| 145 | const kty = value.get(1); | |
| 146 | const alg = value.get(3); | |
| 147 | if (kty === 2 && alg === -7 && value.get(-1) === 1) { | |
| 148 | const x = bin(-2); | |
| 149 | const y = bin(-3); | |
| 150 | if (x === undefined || y === undefined) return undefined; | |
| 151 | if (b64urlDecode(x)?.length !== 32 || b64urlDecode(y)?.length !== 32) | |
| 152 | return undefined; | |
| 153 | return { alg: "ES256", jwk: { kty: "EC", crv: "P-256", x, y } }; | |
| 154 | } | |
| 155 | if (kty === 3 && alg === -257) { | |
| 156 | const n = bin(-1); | |
| 157 | const e = bin(-2); | |
| 158 | if (n === undefined || e === undefined) return undefined; | |
| 159 | if ((b64urlDecode(n)?.length ?? 0) < 256) return undefined; // 2048 bits | |
| 160 | return { alg: "RS256", jwk: { kty: "RSA", n, e } }; | |
| 161 | } | |
| 162 | return undefined; | |
| 163 | } | |
| 164 | ||
| 165 | // ---- shared checks ---- | |
| 166 | ||
| 167 | async function rpIdHash(rpId: string): Promise<Uint8Array> { | |
| 168 | return new Uint8Array( | |
| 169 | await crypto.subtle.digest("SHA-256", new TextEncoder().encode(rpId)), | |
| 170 | ); | |
| 171 | } | |
| 172 | ||
| 173 | const same = (a: Uint8Array, b: Uint8Array): boolean => | |
| 174 | a.length === b.length && a.every((v, i) => v === b[i]); | |
| 175 | ||
| 176 | /** The client data: its type, challenge and origin are what the page claims. */ | |
| 177 | function checkClientData( | |
| 178 | raw: Uint8Array, | |
| 179 | type: "webauthn.create" | "webauthn.get", | |
| 180 | expected: Expected, | |
| 181 | ): WebauthnError | undefined { | |
| 182 | if (raw.length > MAX_BYTES) return "malformed"; | |
| 183 | let data: unknown; | |
| 184 | try { | |
| 185 | data = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(raw)); | |
| 186 | } catch { | |
| 187 | return "malformed"; | |
| 188 | } | |
| 189 | if (typeof data !== "object" || data === null) return "malformed"; | |
| 190 | const d = data as Record<string, unknown>; | |
| 191 | if (d.type !== type) return "wrong_type"; | |
| 192 | if (d.challenge !== expected.challenge) return "wrong_challenge"; | |
| 193 | if (d.origin !== expected.origin) return "wrong_origin"; | |
| 194 | return undefined; | |
| 195 | } | |
| 196 | ||
| 197 | // ---- registration ---- | |
| 198 | ||
| 199 | export async function verifyRegistration( | |
| 200 | response: RegistrationResponse, | |
| 201 | expected: Expected, | |
| 202 | ): Promise< | |
| 203 | Result< | |
| 204 | { credentialId: Uint8Array; key: PasskeyKey; signCount: number }, | |
| 205 | WebauthnError | |
| 206 | > | |
| 207 | > { | |
| 208 | const bad = checkClientData( | |
| 209 | response.clientDataJSON, | |
| 210 | "webauthn.create", | |
| 211 | expected, | |
| 212 | ); | |
| 213 | if (bad) return err(bad); | |
| 214 | if (response.attestationObject.length > MAX_BYTES) return err("malformed"); | |
| 215 | try { | |
| 216 | const { value } = cborDecode(response.attestationObject); | |
| 217 | const authData = value instanceof Map ? value.get("authData") : undefined; | |
| 218 | if (!(authData instanceof Uint8Array) || authData.length < 55) | |
| 219 | return err("malformed"); | |
| 220 | if (!same(authData.subarray(0, 32), await rpIdHash(expected.rpId))) | |
| 221 | return err("wrong_rp"); | |
| 222 | const flags = authData[32] ?? 0; | |
| 223 | if (!(flags & FLAG_UP)) return err("no_presence"); | |
| 224 | if (!(flags & FLAG_AT)) return err("malformed"); | |
| 225 | const signCount = new DataView( | |
| 226 | authData.buffer, | |
| 227 | authData.byteOffset, | |
| 228 | ).getUint32(33); | |
| 229 | const idLength = (authData[53] ?? 0) * 256 + (authData[54] ?? 0); | |
| 230 | if (idLength < 16 || idLength > 1023 || 55 + idLength > authData.length) | |
| 231 | return err("malformed"); | |
| 232 | const credentialId = authData.slice(55, 55 + idLength); | |
| 233 | const key = coseKey(authData.subarray(55 + idLength)); | |
| 234 | return key === undefined | |
| 235 | ? err("unsupported_key") | |
| 236 | : ok({ credentialId, key, signCount }); | |
| 237 | } catch { | |
| 238 | return err("malformed"); | |
| 239 | } | |
| 240 | } | |
| 241 | ||
| 242 | // ---- assertion ---- | |
| 243 | ||
| 244 | /** An ES256 signature arrives as DER; WebCrypto wants r‖s, 32 bytes each. */ | |
| 245 | function derToRaw(der: Uint8Array): Uint8Array | undefined { | |
| 246 | let i = 0; | |
| 247 | const read = (): number | undefined => der[i++]; | |
| 248 | if (read() !== 0x30) return undefined; | |
| 249 | let seq = read(); | |
| 250 | if (seq === undefined) return undefined; | |
| 251 | if (seq === 0x81) seq = read(); | |
| 252 | if (seq === undefined || i + seq !== der.length) return undefined; | |
| 253 | const out = new Uint8Array(64); | |
| 254 | for (const at of [0, 32]) { | |
| 255 | if (read() !== 0x02) return undefined; | |
| 256 | const len = read(); | |
| 257 | if (len === undefined || i + len > der.length) return undefined; | |
| 258 | let part = der.subarray(i, i + len); | |
| 259 | i += len; | |
| 260 | while (part.length > 32 && part[0] === 0) part = part.subarray(1); | |
| 261 | if (part.length > 32) return undefined; | |
| 262 | out.set(part, at + 32 - part.length); | |
| 263 | } | |
| 264 | return i === der.length ? out : undefined; | |
| 265 | } | |
| 266 | ||
| 267 | export async function verifyAssertion( | |
| 268 | response: AssertionResponse, | |
| 269 | expected: Expected, | |
| 270 | stored: { key: PasskeyKey; signCount: number }, | |
| 271 | ): Promise<Result<{ signCount: number }, WebauthnError>> { | |
| 272 | const bad = checkClientData(response.clientDataJSON, "webauthn.get", expected); | |
| 273 | if (bad) return err(bad); | |
| 274 | const auth = response.authenticatorData; | |
| 275 | if (auth.length < 37 || auth.length > MAX_BYTES) return err("malformed"); | |
| 276 | if (!same(auth.subarray(0, 32), await rpIdHash(expected.rpId))) | |
| 277 | return err("wrong_rp"); | |
| 278 | if (!((auth[32] ?? 0) & FLAG_UP)) return err("no_presence"); | |
| 279 | const signCount = new DataView(auth.buffer, auth.byteOffset).getUint32(33); | |
| 280 | // A counter that stands still or goes back is a cloned authenticator — | |
| 281 | // unless the authenticator has no counter at all (zero, always). | |
| 282 | if ((signCount !== 0 || stored.signCount !== 0) && signCount <= stored.signCount) | |
| 283 | return err("sign_count"); | |
| 284 | const clientHash = new Uint8Array( | |
| 285 | await crypto.subtle.digest("SHA-256", response.clientDataJSON.slice()), | |
| 286 | ); | |
| 287 | const signed = new Uint8Array(auth.length + 32); | |
| 288 | signed.set(auth); | |
| 289 | signed.set(clientHash, auth.length); | |
| 290 | try { | |
| 291 | const es = stored.key.alg === "ES256"; | |
| 292 | const signature = es ? derToRaw(response.signature) : response.signature; | |
| 293 | if (signature === undefined) return err("bad_signature"); | |
| 294 | const key = await crypto.subtle.importKey( | |
| 295 | "jwk", | |
| 296 | stored.key.jwk, | |
| 297 | es | |
| 298 | ? { name: "ECDSA", namedCurve: "P-256" } | |
| 299 | : { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, | |
| 300 | false, | |
| 301 | ["verify"], | |
| 302 | ); | |
| 303 | const valid = await crypto.subtle.verify( | |
| 304 | es ? { name: "ECDSA", hash: "SHA-256" } : "RSASSA-PKCS1-v1_5", | |
| 305 | key, | |
| 306 | signature.slice(), | |
| 307 | signed, | |
| 308 | ); | |
| 309 | return valid ? ok({ signCount }) : err("bad_signature"); | |
| 310 | } catch { | |
| 311 | return err("bad_signature"); | |
| 312 | } | |
| 313 | } |
src/core/passkeys.ts added +177
| @@ -0,0 +1,177 @@ | ||
| 1 | /** | |
| 2 | * Passkeys at rest: an account's WebAuthn credentials, and the single-use | |
| 3 | * challenges that ceremonies are bound to. Pure data — the ceremony itself | |
| 4 | * is `auth/webauthn.ts`, the authority is `actions/passkeys.ts`. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { Database } from "bun:sqlite"; | |
| 8 | import type { PasskeyAlg, PasskeyKey } from "../auth/webauthn.ts"; | |
| 9 | import { id as newId, secret } from "../kernel/id.ts"; | |
| 10 | ||
| 11 | const CHALLENGE_TTL_MS = 5 * 60 * 1000; | |
| 12 | /** Outstanding challenges, forge-wide: a stranger may ask for one. */ | |
| 13 | const CHALLENGES_MAX = 2000; | |
| 14 | export const PASSKEYS_MAX = 20; | |
| 15 | ||
| 16 | export interface Passkey { | |
| 17 | readonly id: string; | |
| 18 | readonly userId: string; | |
| 19 | readonly name: string; | |
| 20 | readonly credentialId: string; | |
| 21 | readonly key: PasskeyKey; | |
| 22 | readonly signCount: number; | |
| 23 | readonly createdAt: string; | |
| 24 | readonly lastUsedAt: string | null; | |
| 25 | } | |
| 26 | ||
| 27 | interface Row { | |
| 28 | id: string; | |
| 29 | user_id: string; | |
| 30 | name: string; | |
| 31 | credential_id: string; | |
| 32 | alg: string; | |
| 33 | jwk: string; | |
| 34 | sign_count: number; | |
| 35 | created_at: string; | |
| 36 | last_used_at: string | null; | |
| 37 | } | |
| 38 | ||
| 39 | const toPasskey = (r: Row): Passkey => ({ | |
| 40 | id: r.id, | |
| 41 | userId: r.user_id, | |
| 42 | name: r.name, | |
| 43 | credentialId: r.credential_id, | |
| 44 | key: { alg: r.alg as PasskeyAlg, jwk: JSON.parse(r.jwk) as Record<string, string> }, | |
| 45 | signCount: r.sign_count, | |
| 46 | createdAt: r.created_at, | |
| 47 | lastUsedAt: r.last_used_at, | |
| 48 | }); | |
| 49 | ||
| 50 | export function listPasskeys(db: Database, userId: string): Passkey[] { | |
| 51 | return db | |
| 52 | .query<Row, [string]>( | |
| 53 | "SELECT * FROM passkey WHERE user_id = ?1 ORDER BY created_at, id", | |
| 54 | ) | |
| 55 | .all(userId) | |
| 56 | .map(toPasskey); | |
| 57 | } | |
| 58 | ||
| 59 | export function passkeyByCredential( | |
| 60 | db: Database, | |
| 61 | credentialId: string, | |
| 62 | ): Passkey | undefined { | |
| 63 | const row = db | |
| 64 | .query<Row, [string]>("SELECT * FROM passkey WHERE credential_id = ?1") | |
| 65 | .get(credentialId); | |
| 66 | return row ? toPasskey(row) : undefined; | |
| 67 | } | |
| 68 | ||
| 69 | /** False when the credential is already registered (here or on another account). */ | |
| 70 | export function addPasskey( | |
| 71 | db: Database, | |
| 72 | input: { | |
| 73 | userId: string; | |
| 74 | name: string; | |
| 75 | credentialId: string; | |
| 76 | key: PasskeyKey; | |
| 77 | signCount: number; | |
| 78 | }, | |
| 79 | ): Passkey | undefined { | |
| 80 | const id = newId(); | |
| 81 | const added = db | |
| 82 | .query( | |
| 83 | `INSERT OR IGNORE INTO passkey (id, user_id, name, credential_id, alg, jwk, sign_count) | |
| 84 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)`, | |
| 85 | ) | |
| 86 | .run( | |
| 87 | id, | |
| 88 | input.userId, | |
| 89 | input.name, | |
| 90 | input.credentialId, | |
| 91 | input.key.alg, | |
| 92 | JSON.stringify(input.key.jwk), | |
| 93 | input.signCount, | |
| 94 | ); | |
| 95 | if (added.changes === 0) return undefined; | |
| 96 | return toPasskey( | |
| 97 | db.query<Row, [string]>("SELECT * FROM passkey WHERE id = ?1").get(id)!, | |
| 98 | ); | |
| 99 | } | |
| 100 | ||
| 101 | /** Remove one of this account's passkeys; its name, or undefined if not theirs. */ | |
| 102 | export function deletePasskey( | |
| 103 | db: Database, | |
| 104 | userId: string, | |
| 105 | id: string, | |
| 106 | ): string | undefined { | |
| 107 | return ( | |
| 108 | db | |
| 109 | .query<{ name: string }, [string, string]>( | |
| 110 | "DELETE FROM passkey WHERE id = ?1 AND user_id = ?2 RETURNING name", | |
| 111 | ) | |
| 112 | .get(id, userId)?.name ?? undefined | |
| 113 | ); | |
| 114 | } | |
| 115 | ||
| 116 | /** | |
| 117 | * Record a use. Only succeeds while the stored counter is still what the | |
| 118 | * assertion was checked against, so two racing assertions cannot both win. | |
| 119 | */ | |
| 120 | export function touchPasskey( | |
| 121 | db: Database, | |
| 122 | id: string, | |
| 123 | was: number, | |
| 124 | signCount: number, | |
| 125 | ): boolean { | |
| 126 | return ( | |
| 127 | db | |
| 128 | .query( | |
| 129 | `UPDATE passkey SET sign_count = ?3, last_used_at = ?4 | |
| 130 | WHERE id = ?1 AND sign_count = ?2`, | |
| 131 | ) | |
| 132 | .run(id, was, signCount, new Date().toISOString()).changes > 0 | |
| 133 | ); | |
| 134 | } | |
| 135 | ||
| 136 | /** A fresh challenge for a ceremony, or undefined when too many are out. */ | |
| 137 | export function issueChallenge( | |
| 138 | db: Database, | |
| 139 | purpose: "register" | "signin", | |
| 140 | userId?: string, | |
| 141 | ): string | undefined { | |
| 142 | const now = new Date(); | |
| 143 | db.query("DELETE FROM passkey_challenge WHERE expires_at <= ?1").run( | |
| 144 | now.toISOString(), | |
| 145 | ); | |
| 146 | const out = db | |
| 147 | .query<{ n: number }, []>("SELECT count(*) AS n FROM passkey_challenge") | |
| 148 | .get()!.n; | |
| 149 | if (out >= CHALLENGES_MAX) return undefined; | |
| 150 | const challenge = secret(); | |
| 151 | db.query( | |
| 152 | "INSERT INTO passkey_challenge (challenge, purpose, user_id, expires_at) VALUES (?1, ?2, ?3, ?4)", | |
| 153 | ).run( | |
| 154 | challenge, | |
| 155 | purpose, | |
| 156 | userId ?? null, | |
| 157 | new Date(now.getTime() + CHALLENGE_TTL_MS).toISOString(), | |
| 158 | ); | |
| 159 | return challenge; | |
| 160 | } | |
| 161 | ||
| 162 | /** Spend a challenge: true once, for the purpose and person it was issued to. */ | |
| 163 | export function spendChallenge( | |
| 164 | db: Database, | |
| 165 | challenge: string, | |
| 166 | purpose: "register" | "signin", | |
| 167 | userId?: string, | |
| 168 | ): boolean { | |
| 169 | const row = db | |
| 170 | .query<{ expires_at: string }, [string, string, string | null]>( | |
| 171 | `DELETE FROM passkey_challenge | |
| 172 | WHERE challenge = ?1 AND purpose = ?2 AND user_id IS ?3 | |
| 173 | RETURNING expires_at`, | |
| 174 | ) | |
| 175 | .get(challenge, purpose, userId ?? null); | |
| 176 | return row !== null && row.expires_at > new Date().toISOString(); | |
| 177 | } |
src/core/schema.ts +25
| @@ -1639,6 +1639,31 @@ export const migrations: readonly string[] = [ | ||
| 1639 | 1639 | ALTER TABLE run ADD COLUMN variant_group TEXT; |
| 1640 | 1640 | CREATE INDEX pull_variant_group ON pull(variant_group) WHERE variant_group IS NOT NULL; |
| 1641 | 1641 | `, |
| 1642 | ||
| 1643 | // Passkeys (#1617): a WebAuthn credential belongs to one account, and an | |
| 1644 | // account may hold several. The public key is a JWK; the private half | |
| 1645 | // never leaves the authenticator. A challenge is issued, then spent once | |
| 1646 | // (deleted on use) or left to expire. | |
| 1647 | ` | |
| 1648 | CREATE TABLE passkey ( | |
| 1649 | id TEXT PRIMARY KEY, | |
| 1650 | user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE, | |
| 1651 | name TEXT NOT NULL, | |
| 1652 | credential_id TEXT NOT NULL UNIQUE, | |
| 1653 | alg TEXT NOT NULL, | |
| 1654 | jwk TEXT NOT NULL, | |
| 1655 | sign_count INTEGER NOT NULL DEFAULT 0, | |
| 1656 | created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), | |
| 1657 | last_used_at TEXT | |
| 1658 | ); | |
| 1659 | CREATE INDEX passkey_user ON passkey(user_id); | |
| 1660 | CREATE TABLE passkey_challenge ( | |
| 1661 | challenge TEXT PRIMARY KEY, | |
| 1662 | purpose TEXT NOT NULL, | |
| 1663 | user_id TEXT, | |
| 1664 | expires_at TEXT NOT NULL | |
| 1665 | ); | |
| 1666 | `, | |
| 1642 | 1667 | ]; |
| 1643 | 1668 | |
| 1644 | 1669 | /** |
src/http/server.ts +14
| @@ -35,6 +35,14 @@ import { | ||
| 35 | 35 | import { canRead, canWrite, getRepo, getRepoById } from "../core/repos.ts"; |
| 36 | 36 | import { trackPullHead } from "../core/pulls.ts"; |
| 37 | 37 | import { createRepo } from "../actions/repos.ts"; |
| 38 | import { | |
| 39 | passkeyDelete, | |
| 40 | passkeyRegister, | |
| 41 | passkeyRegisterOptions, | |
| 42 | passkeysPage, | |
| 43 | passkeySignin, | |
| 44 | passkeySigninOptions, | |
| 45 | } from "../web/pages/passkeys.ts"; | |
| 38 | 46 | import { sessionOf } from "../core/sessions.ts"; |
| 39 | 47 | import { scopeAllows, verifyToken } from "../core/tokens.ts"; |
| 40 | 48 | import { forgeHost } from "../core/commit_identity.ts"; |
| @@ -565,6 +573,8 @@ export function buildRouter(): Router<Handler> { | ||
| 565 | 573 | router.add("POST", "/front", frontUpdate); |
| 566 | 574 | router.add("GET", "/signin", signinPage); |
| 567 | 575 | router.add("POST", "/signin", signinSubmit); |
| 576 | router.add("POST", "/signin/passkey/options", passkeySigninOptions); | |
| 577 | router.add("POST", "/signin/passkey", passkeySignin); | |
| 568 | 578 | router.add("GET", "/signup", signupPage); |
| 569 | 579 | router.add("GET", "/verify", verifyPage); |
| 570 | 580 | router.add("POST", "/signup", signupSubmit); |
| @@ -811,6 +821,10 @@ export function buildRouter(): Router<Handler> { | ||
| 811 | 821 | browseContributeSubmit, |
| 812 | 822 | ); |
| 813 | 823 | |
| 824 | router.add("GET", "/settings/passkeys", passkeysPage); | |
| 825 | router.add("POST", "/settings/passkeys/options", passkeyRegisterOptions); | |
| 826 | router.add("POST", "/settings/passkeys", passkeyRegister); | |
| 827 | router.add("POST", "/settings/passkeys/:id/delete", passkeyDelete); | |
| 814 | 828 | router.add("GET", "/settings/keys", keysPage); |
| 815 | 829 | router.add("POST", "/settings/keys", keyCreate); |
| 816 | 830 | router.add("POST", "/settings/keys/:id/delete", keyDelete); |
src/web/layout.ts +2
| @@ -200,6 +200,7 @@ function userMenu(ctx: Ctx, user: User, signOut: MenuItem): Html { | ||
| 200 | 200 | { label: "Settings", href: "/settings", icon: "settings" }, |
| 201 | 201 | { label: "Access tokens", href: "/settings/tokens", icon: "key" }, |
| 202 | 202 | { label: "SSH keys", href: "/settings/keys", icon: "lock" }, |
| 203 | { label: "Passkeys", href: "/settings/passkeys", icon: "key" }, | |
| 203 | 204 | { label: "Origins", href: "/settings/origins", icon: "globe" }, |
| 204 | 205 | ...(user.isAdmin |
| 205 | 206 | ? [{ label: "Crew", href: "/settings/crew", icon: "bot" as const }] |
| @@ -274,6 +275,7 @@ const STATIC_PALETTE: PaletteItem[] = [ | ||
| 274 | 275 | { t: "Account settings", h: "/settings", c: "Settings" }, |
| 275 | 276 | { t: "Access tokens", h: "/settings/tokens", c: "Settings" }, |
| 276 | 277 | { t: "SSH keys", h: "/settings/keys", c: "Settings" }, |
| 278 | { t: "Passkeys", h: "/settings/passkeys", c: "Settings" }, | |
| 277 | 279 | { t: "Origins", h: "/settings/origins", c: "Settings" }, |
| 278 | 280 | ]; |
| 279 | 281 |
src/web/pages/account.ts +3 −1
| @@ -54,7 +54,7 @@ import { | ||
| 54 | 54 | } from "../ui.ts"; |
| 55 | 55 | import { everydayLine } from "./everyday.ts"; |
| 56 | 56 | |
| 57 | type Section = "profile" | "password" | "tokens" | "keys"; | |
| 57 | type Section = "profile" | "password" | "tokens" | "keys" | "passkeys"; | |
| 58 | 58 | |
| 59 | 59 | // The section list lives beside the newest page that joins it, so adding one |
| 60 | 60 | // cannot leave the others pointing at a nav that has forgotten it. |
| @@ -68,11 +68,13 @@ export function accountShell( | ||
| 68 | 68 | title: string, |
| 69 | 69 | body: Html, |
| 70 | 70 | status = 200, |
| 71 | scriptJs?: string, | |
| 71 | 72 | ): Response { |
| 72 | 73 | return page( |
| 73 | 74 | { |
| 74 | 75 | ctx, |
| 75 | 76 | title, |
| 77 | ...(scriptJs === undefined ? {} : { scriptJs }), | |
| 76 | 78 | body: html`<div class="page-head"><h1>${title}</h1></div> |
| 77 | 79 | ${settingsLayout(sections(ctx, current), body, "Account settings")}`, |
| 78 | 80 | }, |
src/web/pages/origins.ts +7
| @@ -73,6 +73,7 @@ export type AccountSection = | ||
| 73 | 73 | | "password" |
| 74 | 74 | | "tokens" |
| 75 | 75 | | "keys" |
| 76 | | "passkeys" | |
| 76 | 77 | | "origins" |
| 77 | 78 | | "crew" |
| 78 | 79 | | "accounts" |
| @@ -170,6 +171,12 @@ export function accountSections( | ||
| 170 | 171 | icon: "lock", |
| 171 | 172 | current: current === "keys", |
| 172 | 173 | }, |
| 174 | { | |
| 175 | label: "Passkeys", | |
| 176 | href: "/settings/passkeys", | |
| 177 | icon: "key", | |
| 178 | current: current === "passkeys", | |
| 179 | }, | |
| 173 | 180 | { |
| 174 | 181 | label: "Origins", |
| 175 | 182 | href: "/settings/origins", |
src/web/pages/passkeys.ts added +209
| @@ -0,0 +1,209 @@ | ||
| 1 | /** | |
| 2 | * Passkeys on the web: the settings page that lists, adds and removes them, | |
| 3 | * and the JSON endpoints the page's script and the sign-in page talk to. | |
| 4 | * Every route is same-origin (`crossOrigin`), every body bounded and parsed | |
| 5 | * before the action sees it, every error a short sentence. | |
| 6 | */ | |
| 7 | ||
| 8 | import { | |
| 9 | addPasskeyFrom, | |
| 10 | registrationOptions, | |
| 11 | removePasskey, | |
| 12 | signinOptions, | |
| 13 | signinWithPasskey, | |
| 14 | type PasskeyError, | |
| 15 | type Where, | |
| 16 | } from "../../actions/passkeys.ts"; | |
| 17 | import { listPasskeys } from "../../core/passkeys.ts"; | |
| 18 | import { createSession } from "../../core/sessions.ts"; | |
| 19 | import { scopeAllows } from "../../core/tokens.ts"; | |
| 20 | import { crossOrigin, type Ctx } from "../../http/context.ts"; | |
| 21 | import { readBounded, STRANGER_MAX } from "../../http/limits.ts"; | |
| 22 | import { json } from "../../http/respond.ts"; | |
| 23 | import { signInFirst } from "../chrome.ts"; | |
| 24 | import { html } from "../html.ts"; | |
| 25 | import { flashTo } from "../layout.ts"; | |
| 26 | import { PASSKEY_JS } from "../passkey-client.ts"; | |
| 27 | import { badge, card, confirmAction, empty, time } from "../ui.ts"; | |
| 28 | import { readForm } from "../form.ts"; | |
| 29 | import { accountShell } from "./account.ts"; | |
| 30 | import { safeNext, sessionCookie } from "./site.ts"; | |
| 31 | ||
| 32 | const MESSAGES: Partial<Record<PasskeyError, string>> = { | |
| 33 | unauthorized: "Sign in first.", | |
| 34 | invalid: "That request was not understood.", | |
| 35 | challenge: "That attempt expired. Try again.", | |
| 36 | too_many: "Too many passkeys or attempts right now. Try again shortly.", | |
| 37 | exists: "That passkey is already registered.", | |
| 38 | not_found: "That passkey is not registered here.", | |
| 39 | unsupported_key: "This passkey uses a key type forge does not support.", | |
| 40 | }; | |
| 41 | ||
| 42 | const REFUSED = "That passkey could not be verified."; | |
| 43 | ||
| 44 | const whereOf = (ctx: Ctx): Where => ({ | |
| 45 | origin: ctx.url.origin, | |
| 46 | rpId: ctx.url.hostname, | |
| 47 | }); | |
| 48 | ||
| 49 | /** A same-origin JSON body, bounded; a Response when it must be refused. */ | |
| 50 | async function readJson(ctx: Ctx, signedIn: boolean): Promise<unknown> { | |
| 51 | if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) | |
| 52 | return json({ error: "Forbidden." }, 403); | |
| 53 | if (signedIn && (ctx.auth.scope === undefined || !scopeAllows(ctx.auth.scope, "rw"))) | |
| 54 | return json({ error: "Forbidden." }, 403); | |
| 55 | const raw = await readBounded(ctx.request, STRANGER_MAX); | |
| 56 | if (raw === "too_large") return json({ error: "Too large." }, 413); | |
| 57 | if (raw.byteLength === 0) return {}; | |
| 58 | try { | |
| 59 | return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(raw)); | |
| 60 | } catch { | |
| 61 | return json({ error: MESSAGES.invalid }, 400); | |
| 62 | } | |
| 63 | } | |
| 64 | ||
| 65 | const refusal = (error: PasskeyError): Response => | |
| 66 | json( | |
| 67 | { error: MESSAGES[error] ?? REFUSED }, | |
| 68 | error === "unauthorized" ? 401 : error === "too_many" ? 429 : 400, | |
| 69 | ); | |
| 70 | ||
| 71 | // GET /settings/passkeys | |
| 72 | export function passkeysPage(ctx: Ctx): Response { | |
| 73 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 74 | const keys = listPasskeys(ctx.app.db, ctx.auth.user.id); | |
| 75 | const body = html`<p class="muted small mb"> | |
| 76 | A passkey signs you in with your device's unlock — fingerprint, face or | |
| 77 | PIN — and no password. Add one for each device or security key you use. | |
| 78 | </p> | |
| 79 | ${keys.length === 0 | |
| 80 | ? empty({ | |
| 81 | icon: "key", | |
| 82 | title: "No passkeys yet", | |
| 83 | note: "Add one and the sign-in page offers it.", | |
| 84 | }) | |
| 85 | : card( | |
| 86 | html`<div class="table-scroll"> | |
| 87 | <table class="table"> | |
| 88 | <thead> | |
| 89 | <tr> | |
| 90 | <th>Name</th> | |
| 91 | <th>Added</th> | |
| 92 | <th>Last used</th> | |
| 93 | <th></th> | |
| 94 | </tr> | |
| 95 | </thead> | |
| 96 | <tbody> | |
| 97 | ${keys.map( | |
| 98 | (k) => | |
| 99 | html`<tr> | |
| 100 | <td> | |
| 101 | <strong>${k.name}</strong> | |
| 102 | ${badge(k.key.alg, { variant: "secondary" })} | |
| 103 | </td> | |
| 104 | <td class="muted">${time(k.createdAt)}</td> | |
| 105 | <td class="muted"> | |
| 106 | ${k.lastUsedAt ? time(k.lastUsedAt) : "never"} | |
| 107 | </td> | |
| 108 | <td> | |
| 109 | ${confirmAction({ | |
| 110 | action: `/settings/passkeys/${k.id}/delete`, | |
| 111 | verb: "Remove", | |
| 112 | size: "sm", | |
| 113 | })} | |
| 114 | </td> | |
| 115 | </tr>`, | |
| 116 | )} | |
| 117 | </tbody> | |
| 118 | </table> | |
| 119 | </div>`, | |
| 120 | { pad: false }, | |
| 121 | )} | |
| 122 | ${card( | |
| 123 | html`<div class="form-actions"> | |
| 124 | <input | |
| 125 | class="input" | |
| 126 | id="passkey-name" | |
| 127 | maxlength="60" | |
| 128 | placeholder="Name, e.g. Laptop" | |
| 129 | aria-label="Passkey name" | |
| 130 | /> | |
| 131 | <button | |
| 132 | type="button" | |
| 133 | class="btn btn-primary" | |
| 134 | data-passkey="add" | |
| 135 | data-prefix="/settings/passkeys" | |
| 136 | hidden | |
| 137 | > | |
| 138 | Add a passkey | |
| 139 | </button> | |
| 140 | </div> | |
| 141 | <p class="muted small" id="passkey-note" role="status"></p> | |
| 142 | <noscript | |
| 143 | ><p class="muted small">Adding a passkey needs JavaScript.</p></noscript | |
| 144 | >`, | |
| 145 | { head: html`<h3>New passkey</h3>` }, | |
| 146 | )}`; | |
| 147 | return accountShell(ctx, "passkeys", "Passkeys", body, 200, PASSKEY_JS); | |
| 148 | } | |
| 149 | ||
| 150 | // POST /settings/passkeys/options | |
| 151 | export async function passkeyRegisterOptions(ctx: Ctx): Promise<Response> { | |
| 152 | if (!ctx.auth.user) return json({ error: MESSAGES.unauthorized }, 401); | |
| 153 | const body = await readJson(ctx, true); | |
| 154 | if (body instanceof Response) return body; | |
| 155 | const made = registrationOptions(ctx.app, ctx.auth.user, whereOf(ctx)); | |
| 156 | return made.ok ? json(made.value) : refusal(made.error); | |
| 157 | } | |
| 158 | ||
| 159 | // POST /settings/passkeys | |
| 160 | export async function passkeyRegister(ctx: Ctx): Promise<Response> { | |
| 161 | if (!ctx.auth.user) return json({ error: MESSAGES.unauthorized }, 401); | |
| 162 | const body = await readJson(ctx, true); | |
| 163 | if (body instanceof Response) return body; | |
| 164 | const added = await addPasskeyFrom(ctx.app, ctx.auth.user, whereOf(ctx), body); | |
| 165 | return added.ok ? json({ ok: true, name: added.value.name }) : refusal(added.error); | |
| 166 | } | |
| 167 | ||
| 168 | // POST /settings/passkeys/:id/delete | |
| 169 | export async function passkeyDelete(ctx: Ctx): Promise<Response> { | |
| 170 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 171 | const form = await readForm(ctx, "rw"); | |
| 172 | if (form instanceof Response) return form; | |
| 173 | const removed = removePasskey(ctx.app, ctx.auth.user, ctx.params.id ?? ""); | |
| 174 | return flashTo(ctx, "/settings/passkeys", { | |
| 175 | ...(removed.ok | |
| 176 | ? { message: "Passkey removed." } | |
| 177 | : { tone: "danger" as const, message: "No such passkey." }), | |
| 178 | }); | |
| 179 | } | |
| 180 | ||
| 181 | // POST /signin/passkey/options | |
| 182 | export async function passkeySigninOptions(ctx: Ctx): Promise<Response> { | |
| 183 | const body = await readJson(ctx, false); | |
| 184 | if (body instanceof Response) return body; | |
| 185 | const made = signinOptions(ctx.app, whereOf(ctx)); | |
| 186 | return made.ok ? json(made.value) : refusal(made.error); | |
| 187 | } | |
| 188 | ||
| 189 | // POST /signin/passkey — the same session a password makes | |
| 190 | export async function passkeySignin(ctx: Ctx): Promise<Response> { | |
| 191 | const body = await readJson(ctx, false); | |
| 192 | if (body instanceof Response) return body; | |
| 193 | const proven = await signinWithPasskey(ctx.app, whereOf(ctx), body); | |
| 194 | if (!proven.ok) | |
| 195 | return json({ error: MESSAGES[proven.error] ?? REFUSED }, proven.error === "too_many" ? 429 : 401); | |
| 196 | const session = createSession(ctx.app.db, proven.value.id); | |
| 197 | const next = | |
| 198 | typeof body === "object" && body !== null | |
| 199 | ? safeNext(String((body as { next?: unknown }).next ?? "")) | |
| 200 | : undefined; | |
| 201 | return json({ ok: true, next: next ?? "/" }, 200, { | |
| 202 | "set-cookie": sessionCookie( | |
| 203 | session.token, | |
| 204 | session.expiresAt, | |
| 205 | ctx.url, | |
| 206 | ctx.app.config.url, | |
| 207 | ), | |
| 208 | }); | |
| 209 | } |
src/web/pages/site.ts +26 −2
| @@ -25,6 +25,7 @@ import { | ||
| 25 | 25 | listReposVisibleTo, |
| 26 | 26 | type Repo, |
| 27 | 27 | } from "../../core/repos.ts"; |
| 28 | import { PASSKEY_JS } from "../passkey-client.ts"; | |
| 28 | 29 | import { createSession } from "../../core/sessions.ts"; |
| 29 | 30 | import { hasAnyUser, verifyPassword, type User } from "../../core/users.ts"; |
| 30 | 31 | import { isThemeName } from "../../design/themes.ts"; |
| @@ -75,7 +76,7 @@ export function sessionCookie( | ||
| 75 | 76 | * protocol-relative `//evil.example` is a redirect off-site wearing a path's |
| 76 | 77 | * clothes, so it is refused with everything else that isn't a plain path. |
| 77 | 78 | */ |
| 78 | function safeNext(raw: string | null): string | undefined { | |
| 79 | export function safeNext(raw: string | null): string | undefined { | |
| 79 | 80 | if (raw === null || raw === "") return undefined; |
| 80 | 81 | if (!raw.startsWith("/") || raw.startsWith("//")) return undefined; |
| 81 | 82 | if (raw.includes("\\") || /[\n\r]/.test(raw)) return undefined; |
| @@ -411,6 +412,22 @@ function authForm( | ||
| 411 | 412 | admin. |
| 412 | 413 | </p>`, |
| 413 | 414 | )} |
| 415 | ${when( | |
| 416 | kind === "signin", | |
| 417 | () => html`<p class="mb"> | |
| 418 | <button | |
| 419 | type="button" | |
| 420 | class="btn" | |
| 421 | data-passkey="signin" | |
| 422 | data-prefix="/signin/passkey" | |
| 423 | data-next="${next ?? ""}" | |
| 424 | hidden | |
| 425 | > | |
| 426 | Sign in with a passkey | |
| 427 | </button> | |
| 428 | <span class="muted small" id="passkey-note" role="status"></span> | |
| 429 | </p>`, | |
| 430 | )} | |
| 414 | 431 | <div class="form-actions"> |
| 415 | 432 | ${btn(kind === "signin" ? "Sign in" : "Create account", { |
| 416 | 433 | variant: "primary", |
| @@ -446,7 +463,12 @@ function authForm( | ||
| 446 | 463 | } |
| 447 | 464 | |
| 448 | 465 | export function signinPage(ctx: Ctx): Response { |
| 449 | return page({ ctx, title: "Sign in", body: authForm(ctx, "signin") }); | |
| 466 | return page({ | |
| 467 | ctx, | |
| 468 | title: "Sign in", | |
| 469 | scriptJs: PASSKEY_JS, | |
| 470 | body: authForm(ctx, "signin"), | |
| 471 | }); | |
| 450 | 472 | } |
| 451 | 473 | |
| 452 | 474 | export function signupPage(ctx: Ctx): Response { |
| @@ -494,6 +516,7 @@ export async function signinSubmit(ctx: Ctx): Promise<Response> { | ||
| 494 | 516 | { |
| 495 | 517 | ctx, |
| 496 | 518 | title: "Sign in", |
| 519 | scriptJs: PASSKEY_JS, | |
| 497 | 520 | body: authForm(ctx, "signin", { |
| 498 | 521 | values: { username }, |
| 499 | 522 | errors: { |
| @@ -516,6 +539,7 @@ export async function signinSubmit(ctx: Ctx): Promise<Response> { | ||
| 516 | 539 | { |
| 517 | 540 | ctx, |
| 518 | 541 | title: "Sign in", |
| 542 | scriptJs: PASSKEY_JS, | |
| 519 | 543 | body: authForm(ctx, "signin", { |
| 520 | 544 | values: { username }, |
| 521 | 545 | errors: { |
src/web/passkey-client.ts added +55
| @@ -0,0 +1,55 @@ | ||
| 1 | /** | |
| 2 | * The browser half of passkeys, as one static string for a nonce'd <script> | |
| 3 | * (`scriptJs`). It only moves bytes between `navigator.credentials` and the | |
| 4 | * JSON endpoints; every decision is the server's. A button with | |
| 5 | * `data-passkey="add"` registers one (name from `#passkey-name`), one with | |
| 6 | * `data-passkey="signin"` signs in. Without WebAuthn the buttons stay hidden. | |
| 7 | */ | |
| 8 | ||
| 9 | export const PASSKEY_JS = `(() => { | |
| 10 | const buttons = document.querySelectorAll("[data-passkey]"); | |
| 11 | if (!window.PublicKeyCredential || !navigator.credentials) return; | |
| 12 | const bytes = (s) => { | |
| 13 | const p = s.replace(/-/g, "+").replace(/_/g, "/"); | |
| 14 | return Uint8Array.from(atob(p + "=".repeat((4 - (p.length % 4)) % 4)), (c) => c.charCodeAt(0)); | |
| 15 | }; | |
| 16 | const text = (b) => btoa(String.fromCharCode(...new Uint8Array(b))).replace(/\\+/g, "-").replace(/\\//g, "_").replace(/=+$/, ""); | |
| 17 | const post = async (url, body) => { | |
| 18 | const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify(body || {}) }); | |
| 19 | const data = await r.json().catch(() => ({})); | |
| 20 | if (!r.ok) throw new Error(data.error || "That did not work."); | |
| 21 | return data; | |
| 22 | }; | |
| 23 | for (const button of buttons) { | |
| 24 | button.hidden = false; | |
| 25 | button.addEventListener("click", async () => { | |
| 26 | const note = document.getElementById("passkey-note"); | |
| 27 | const say = (m) => { if (note) note.textContent = m; }; | |
| 28 | button.disabled = true; | |
| 29 | say(""); | |
| 30 | try { | |
| 31 | const kind = button.dataset.passkey; | |
| 32 | const prefix = button.dataset.prefix; | |
| 33 | const options = await post(prefix + "/options"); | |
| 34 | if (kind === "add") { | |
| 35 | const credential = await navigator.credentials.create({ publicKey: { | |
| 36 | ...options, challenge: bytes(options.challenge), user: { ...options.user, id: bytes(options.user.id) }, | |
| 37 | excludeCredentials: options.excludeCredentials.map((c) => ({ ...c, id: bytes(c.id) })) } }); | |
| 38 | const nameField = document.getElementById("passkey-name"); | |
| 39 | await post(prefix, { challenge: options.challenge, name: nameField ? nameField.value : "", | |
| 40 | clientDataJSON: text(credential.response.clientDataJSON), attestationObject: text(credential.response.attestationObject) }); | |
| 41 | location.reload(); | |
| 42 | } else { | |
| 43 | const credential = await navigator.credentials.get({ publicKey: { ...options, challenge: bytes(options.challenge) } }); | |
| 44 | const done = await post(prefix, { challenge: options.challenge, id: credential.id, | |
| 45 | clientDataJSON: text(credential.response.clientDataJSON), authenticatorData: text(credential.response.authenticatorData), | |
| 46 | signature: text(credential.response.signature), next: button.dataset.next || "" }); | |
| 47 | location.assign(done.next || "/"); | |
| 48 | } | |
| 49 | } catch (e) { | |
| 50 | say(e && e.name === "NotAllowedError" ? "Cancelled." : (e && e.message) || "That did not work."); | |
| 51 | button.disabled = false; | |
| 52 | } | |
| 53 | }); | |
| 54 | } | |
| 55 | })();`; |
test/asks-bulk.test.ts −1
| @@ -684,7 +684,6 @@ describe("acting on many asks at once", () => { | ||
| 684 | 684 | expect(res.status).toBe(200); |
| 685 | 685 | const text = await res.text(); |
| 686 | 686 | expect(text).toContain('id="live-on-you"'); |
| 687 | expect(text).toContain('id="asks-link"'); | |
| 688 | 687 | expect(text).not.toContain("Card one"); |
| 689 | 688 | expect(getIssueById(app.db, a.id)!.state).toBe("closed"); |
| 690 | 689 | // The undo link rides on the card, and is the same one after a refresh. |
test/passkeys.test.ts added +299
| @@ -0,0 +1,299 @@ | ||
| 1 | /** | |
| 2 | * Passkeys: a software authenticator registers, signs in and is removed over | |
| 3 | * the real routes; a wrong origin, a replayed challenge, a counter that goes | |
| 4 | * backwards, a forged signature and a cross-origin post are each refused. | |
| 5 | */ | |
| 6 | ||
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { signUp } from "../src/actions/users.ts"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { b64urlDecode, b64urlEncode } from "../src/auth/webauthn.ts"; | |
| 14 | import { listPasskeys } from "../src/core/passkeys.ts"; | |
| 15 | import { createSession } from "../src/core/sessions.ts"; | |
| 16 | import type { User } from "../src/core/users.ts"; | |
| 17 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 18 | ||
| 19 | // ---- a software authenticator ---- | |
| 20 | ||
| 21 | const enc = new TextEncoder(); | |
| 22 | ||
| 23 | function cbor(v: unknown): number[] { | |
| 24 | const head = (major: number, n: number): number[] => | |
| 25 | n < 24 ? [(major << 5) | n] : n < 256 ? [(major << 5) | 24, n] : [(major << 5) | 25, n >> 8, n & 255]; | |
| 26 | if (typeof v === "number") return v >= 0 ? head(0, v) : head(1, -1 - v); | |
| 27 | if (typeof v === "string") { | |
| 28 | const b = [...enc.encode(v)]; | |
| 29 | return [...head(3, b.length), ...b]; | |
| 30 | } | |
| 31 | if (v instanceof Uint8Array) return [...head(2, v.length), ...v]; | |
| 32 | const entries = [...(v as Map<unknown, unknown>)]; | |
| 33 | return [...head(5, entries.length), ...entries.flatMap(([k, x]) => [...cbor(k), ...cbor(x)])]; | |
| 34 | } | |
| 35 | ||
| 36 | const sha = async (b: Uint8Array): Promise<Uint8Array> => | |
| 37 | new Uint8Array(await crypto.subtle.digest("SHA-256", b.slice())); | |
| 38 | ||
| 39 | const derInt = (b: Uint8Array): number[] => { | |
| 40 | let i = 0; | |
| 41 | while (i < b.length - 1 && b[i] === 0) i++; | |
| 42 | const v = [...b.subarray(i)]; | |
| 43 | if ((v[0] ?? 0) & 0x80) v.unshift(0); | |
| 44 | return [2, v.length, ...v]; | |
| 45 | }; | |
| 46 | const toDer = (raw: Uint8Array): Uint8Array => { | |
| 47 | const body = [...derInt(raw.subarray(0, 32)), ...derInt(raw.subarray(32))]; | |
| 48 | return new Uint8Array([0x30, body.length, ...body]); | |
| 49 | }; | |
| 50 | ||
| 51 | class Authenticator { | |
| 52 | readonly credentialId = crypto.getRandomValues(new Uint8Array(32)); | |
| 53 | count = 0; | |
| 54 | private constructor( | |
| 55 | readonly alg: "ES256" | "RS256", | |
| 56 | private readonly pair: CryptoKeyPair, | |
| 57 | private readonly cose: Map<number, unknown>, | |
| 58 | ) {} | |
| 59 | ||
| 60 | static async make(alg: "ES256" | "RS256"): Promise<Authenticator> { | |
| 61 | if (alg === "ES256") { | |
| 62 | const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]); | |
| 63 | const jwk = await crypto.subtle.exportKey("jwk", pair.publicKey); | |
| 64 | return new Authenticator(alg, pair, new Map<number, unknown>([ | |
| 65 | [1, 2], [3, -7], [-1, 1], [-2, b64urlDecode(jwk.x)], [-3, b64urlDecode(jwk.y)], | |
| 66 | ])); | |
| 67 | } | |
| 68 | const pair = await crypto.subtle.generateKey( | |
| 69 | { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, | |
| 70 | true, ["sign", "verify"], | |
| 71 | ); | |
| 72 | const jwk = await crypto.subtle.exportKey("jwk", pair.publicKey); | |
| 73 | return new Authenticator(alg, pair, new Map<number, unknown>([ | |
| 74 | [1, 3], [3, -257], [-1, b64urlDecode(jwk.n)], [-2, b64urlDecode(jwk.e)], | |
| 75 | ])); | |
| 76 | } | |
| 77 | ||
| 78 | private async authData(rpId: string, count: number, attested: boolean): Promise<Uint8Array> { | |
| 79 | const head = [...(await sha(enc.encode(rpId))), attested ? 0x41 : 0x01, count >>> 24, (count >> 16) & 255, (count >> 8) & 255, count & 255]; | |
| 80 | if (!attested) return new Uint8Array(head); | |
| 81 | return new Uint8Array([ | |
| 82 | ...head, ...new Uint8Array(16), 0, this.credentialId.length, ...this.credentialId, ...cbor(this.cose), | |
| 83 | ]); | |
| 84 | } | |
| 85 | ||
| 86 | async create(o: { challenge: string }, origin: string, rpId: string) { | |
| 87 | const clientDataJSON = enc.encode(JSON.stringify({ type: "webauthn.create", challenge: o.challenge, origin })); | |
| 88 | const authData = await this.authData(rpId, 0, true); | |
| 89 | const attestationObject = new Uint8Array(cbor(new Map<unknown, unknown>([["fmt", "none"], ["attStmt", new Map()], ["authData", authData]]))); | |
| 90 | return { clientDataJSON: b64urlEncode(clientDataJSON), attestationObject: b64urlEncode(attestationObject) }; | |
| 91 | } | |
| 92 | ||
| 93 | async get(o: { challenge: string }, origin: string, rpId: string, count = ++this.count) { | |
| 94 | const clientDataJSON = enc.encode(JSON.stringify({ type: "webauthn.get", challenge: o.challenge, origin })); | |
| 95 | const authenticatorData = await this.authData(rpId, count, false); | |
| 96 | const signed = new Uint8Array([...authenticatorData, ...(await sha(clientDataJSON))]); | |
| 97 | const es = this.alg === "ES256"; | |
| 98 | const raw = new Uint8Array( | |
| 99 | await crypto.subtle.sign(es ? { name: "ECDSA", hash: "SHA-256" } : "RSASSA-PKCS1-v1_5", this.pair.privateKey, signed), | |
| 100 | ); | |
| 101 | return { | |
| 102 | id: b64urlEncode(this.credentialId), | |
| 103 | clientDataJSON: b64urlEncode(clientDataJSON), | |
| 104 | authenticatorData: b64urlEncode(authenticatorData), | |
| 105 | signature: b64urlEncode(es ? toDer(raw) : raw), | |
| 106 | }; | |
| 107 | } | |
| 108 | } | |
| 109 | ||
| 110 | // ---- the forge ---- | |
| 111 | ||
| 112 | describe("passkeys", () => { | |
| 113 | let dataDir: string; | |
| 114 | let app: App; | |
| 115 | let servers: Servers; | |
| 116 | let base: string; | |
| 117 | let origin: string; | |
| 118 | let rpId: string; | |
| 119 | let alice: User; | |
| 120 | let bob: User; | |
| 121 | let cookie: string; | |
| 122 | let bobCookie: string; | |
| 123 | ||
| 124 | const post = (path: string, body: unknown, headers: Record<string, string> = {}) => | |
| 125 | fetch(base + path, { | |
| 126 | method: "POST", | |
| 127 | redirect: "manual", | |
| 128 | headers: { "content-type": "application/json", ...headers }, | |
| 129 | body: JSON.stringify(body), | |
| 130 | }); | |
| 131 | const signedIn = (c: string) => ({ cookie: `forge_session=${c}` }); | |
| 132 | ||
| 133 | async function register(a: Authenticator, name = "Laptop", c = cookie) { | |
| 134 | const options = (await (await post("/settings/passkeys/options", {}, signedIn(c))).json()) as { challenge: string }; | |
| 135 | const response = await a.create(options, origin, rpId); | |
| 136 | return post("/settings/passkeys", { challenge: options.challenge, name, ...response }, signedIn(c)); | |
| 137 | } | |
| 138 | async function signinOptions() { | |
| 139 | return (await (await post("/signin/passkey/options", {})).json()) as { challenge: string }; | |
| 140 | } | |
| 141 | ||
| 142 | beforeAll(async () => { | |
| 143 | dataDir = await mkdtemp(join(tmpdir(), "forge-passkeys-")); | |
| 144 | app = createApp({ dataDir, port: 0 }); | |
| 145 | servers = await serve(app); | |
| 146 | base = servers.url; | |
| 147 | const url = new URL(base); | |
| 148 | origin = url.origin; | |
| 149 | rpId = url.hostname; | |
| 150 | const a = await signUp(app, { username: "alice", email: "[email protected]", password: "a-long-passphrase" }); | |
| 151 | const b = await signUp(app, { username: "bob", email: "[email protected]", password: "a-long-passphrase" }); | |
| 152 | if (!a.ok || !b.ok) throw new Error("signup failed"); | |
| 153 | alice = a.value; | |
| 154 | bob = b.value; | |
| 155 | cookie = createSession(app.db, alice.id).token; | |
| 156 | bobCookie = createSession(app.db, bob.id).token; | |
| 157 | }); | |
| 158 | ||
| 159 | afterAll(async () => { | |
| 160 | await servers.stop(); | |
| 161 | await rm(dataDir, { recursive: true, force: true }); | |
| 162 | }); | |
| 163 | ||
| 164 | test("registers, lists, signs in with the same session a password makes, and removes", async () => { | |
| 165 | const a = await Authenticator.make("ES256"); | |
| 166 | expect((await register(a)).status).toBe(200); | |
| 167 | expect(listPasskeys(app.db, alice.id).map((p) => p.name)).toEqual(["Laptop"]); | |
| 168 | ||
| 169 | const page = await fetch(`${base}/settings/passkeys`, { headers: signedIn(cookie) }); | |
| 170 | expect(page.status).toBe(200); | |
| 171 | expect(await page.text()).toContain("Laptop"); | |
| 172 | ||
| 173 | const options = await signinOptions(); | |
| 174 | const res = await post("/signin/passkey", { challenge: options.challenge, next: "/explore", ...(await a.get(options, origin, rpId)) }); | |
| 175 | expect(res.status).toBe(200); | |
| 176 | expect(await res.json()).toEqual({ ok: true, next: "/explore" }); | |
| 177 | const set = res.headers.get("set-cookie") ?? ""; | |
| 178 | expect(set).toContain("forge_session="); | |
| 179 | expect(set).toContain("HttpOnly"); | |
| 180 | const token = /forge_session=([^;]+)/.exec(set)![1]!; | |
| 181 | const mine = await fetch(`${base}/settings/passkeys`, { headers: signedIn(token) }); | |
| 182 | expect(mine.status).toBe(200); | |
| 183 | expect(await mine.text()).toContain("Laptop"); | |
| 184 | ||
| 185 | const id = listPasskeys(app.db, alice.id)[0]!.id; | |
| 186 | const gone = await fetch(`${base}/settings/passkeys/${id}/delete`, { method: "POST", redirect: "manual", headers: signedIn(cookie) }); | |
| 187 | expect(gone.status).toBe(303); | |
| 188 | expect(listPasskeys(app.db, alice.id)).toEqual([]); | |
| 189 | const again = await signinOptions(); | |
| 190 | const after = await post("/signin/passkey", { challenge: again.challenge, ...(await a.get(again, origin, rpId)) }); | |
| 191 | expect(after.status).toBe(401); | |
| 192 | }); | |
| 193 | ||
| 194 | test("RS256 registers and signs in; one account holds several", async () => { | |
| 195 | const es = await Authenticator.make("ES256"); | |
| 196 | const rs = await Authenticator.make("RS256"); | |
| 197 | expect((await register(es, "Phone")).status).toBe(200); | |
| 198 | expect((await register(rs, "Key")).status).toBe(200); | |
| 199 | expect(listPasskeys(app.db, alice.id).map((p) => p.key.alg).sort()).toEqual(["ES256", "RS256"]); | |
| 200 | const options = await signinOptions(); | |
| 201 | const res = await post("/signin/passkey", { challenge: options.challenge, ...(await rs.get(options, origin, rpId)) }); | |
| 202 | expect(res.status).toBe(200); | |
| 203 | }); | |
| 204 | ||
| 205 | test("a wrong origin is refused, at registration and at sign-in", async () => { | |
| 206 | const a = await Authenticator.make("ES256"); | |
| 207 | const reg = (await (await post("/settings/passkeys/options", {}, signedIn(cookie))).json()) as { challenge: string }; | |
| 208 | const bad = await post("/settings/passkeys", { challenge: reg.challenge, name: "x", ...(await a.create(reg, "https://evil.example", rpId)) }, signedIn(cookie)); | |
| 209 | expect(bad.status).toBe(400); | |
| 210 | ||
| 211 | expect((await register(a, "Real")).status).toBe(200); | |
| 212 | const options = await signinOptions(); | |
| 213 | const res = await post("/signin/passkey", { challenge: options.challenge, ...(await a.get(options, "https://evil.example", rpId)) }); | |
| 214 | expect(res.status).toBe(401); | |
| 215 | expect(res.headers.get("set-cookie")).toBeNull(); | |
| 216 | }); | |
| 217 | ||
| 218 | test("a wrong rpId is refused", async () => { | |
| 219 | const a = await Authenticator.make("ES256"); | |
| 220 | await register(a, "Rp"); | |
| 221 | const options = await signinOptions(); | |
| 222 | const res = await post("/signin/passkey", { challenge: options.challenge, ...(await a.get(options, origin, "other.example")) }); | |
| 223 | expect(res.status).toBe(401); | |
| 224 | }); | |
| 225 | ||
| 226 | test("a replayed challenge is refused", async () => { | |
| 227 | const a = await Authenticator.make("ES256"); | |
| 228 | await register(a, "Replay"); | |
| 229 | const options = await signinOptions(); | |
| 230 | const body = { challenge: options.challenge, ...(await a.get(options, origin, rpId)) }; | |
| 231 | expect((await post("/signin/passkey", body)).status).toBe(200); | |
| 232 | expect((await post("/signin/passkey", body)).status).toBe(401); | |
| 233 | // And a challenge that was never issued. | |
| 234 | const forged = await a.get({ challenge: "AAAA" }, origin, rpId); | |
| 235 | expect((await post("/signin/passkey", { challenge: "AAAA", ...forged })).status).toBe(401); | |
| 236 | }); | |
| 237 | ||
| 238 | test("a signCount that goes backwards, or stands still, is refused", async () => { | |
| 239 | const a = await Authenticator.make("ES256"); | |
| 240 | await register(a, "Count"); | |
| 241 | let options = await signinOptions(); | |
| 242 | expect((await post("/signin/passkey", { challenge: options.challenge, ...(await a.get(options, origin, rpId, 5)) })).status).toBe(200); | |
| 243 | for (const count of [4, 5]) { | |
| 244 | options = await signinOptions(); | |
| 245 | const res = await post("/signin/passkey", { challenge: options.challenge, ...(await a.get(options, origin, rpId, count)) }); | |
| 246 | expect(res.status).toBe(401); | |
| 247 | } | |
| 248 | options = await signinOptions(); | |
| 249 | expect((await post("/signin/passkey", { challenge: options.challenge, ...(await a.get(options, origin, rpId, 6)) })).status).toBe(200); | |
| 250 | }); | |
| 251 | ||
| 252 | test("a signature from another key is refused", async () => { | |
| 253 | const a = await Authenticator.make("ES256"); | |
| 254 | const impostor = await Authenticator.make("ES256"); | |
| 255 | await register(a, "Real key"); | |
| 256 | const options = await signinOptions(); | |
| 257 | const forged = await impostor.get(options, origin, rpId); | |
| 258 | const res = await post("/signin/passkey", { challenge: options.challenge, ...forged, id: b64urlEncode(a.credentialId) }); | |
| 259 | expect(res.status).toBe(401); | |
| 260 | }); | |
| 261 | ||
| 262 | test("a challenge is for one purpose and one person", async () => { | |
| 263 | const a = await Authenticator.make("ES256"); | |
| 264 | const options = (await (await post("/settings/passkeys/options", {}, signedIn(cookie))).json()) as { challenge: string }; | |
| 265 | const response = await a.create(options, origin, rpId); | |
| 266 | const res = await post("/settings/passkeys", { challenge: options.challenge, name: "Stolen", ...response }, signedIn(bobCookie)); | |
| 267 | expect(res.status).toBe(400); | |
| 268 | expect(listPasskeys(app.db, bob.id)).toEqual([]); | |
| 269 | }); | |
| 270 | ||
| 271 | test("another account cannot remove it, and a stranger cannot add", async () => { | |
| 272 | const a = await Authenticator.make("ES256"); | |
| 273 | await register(a, "Mine"); | |
| 274 | const id = listPasskeys(app.db, alice.id).find((p) => p.name === "Mine")!.id; | |
| 275 | await fetch(`${base}/settings/passkeys/${id}/delete`, { method: "POST", redirect: "manual", headers: signedIn(bobCookie) }); | |
| 276 | expect(listPasskeys(app.db, alice.id).some((p) => p.id === id)).toBe(true); | |
| 277 | expect((await post("/settings/passkeys/options", {})).status).toBe(401); | |
| 278 | expect((await post("/settings/passkeys", {})).status).toBe(401); | |
| 279 | }); | |
| 280 | ||
| 281 | test("a cross-origin post is refused", async () => { | |
| 282 | const evil = { origin: "https://evil.example" }; | |
| 283 | expect((await post("/signin/passkey/options", {}, evil)).status).toBe(403); | |
| 284 | expect((await post("/signin/passkey", {}, evil)).status).toBe(403); | |
| 285 | expect((await post("/settings/passkeys/options", {}, { ...evil, ...signedIn(cookie) })).status).toBe(403); | |
| 286 | }); | |
| 287 | ||
| 288 | test("garbage bodies are refused, not crashed on", async () => { | |
| 289 | expect((await post("/signin/passkey", { challenge: 1, id: [] })).status).toBe(401); | |
| 290 | expect((await post("/signin/passkey", "nope")).status).toBe(401); | |
| 291 | const raw = await fetch(`${base}/signin/passkey`, { method: "POST", body: "{not json" }); | |
| 292 | expect(raw.status).toBe(400); | |
| 293 | }); | |
| 294 | ||
| 295 | test("the sign-in page offers a passkey", async () => { | |
| 296 | const html = await (await fetch(`${base}/signin`)).text(); | |
| 297 | expect(html).toContain('data-passkey="signin"'); | |
| 298 | }); | |
| 299 | }); |
new above
offline