@intellectual-frontiers/crypto 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,548 @@
1
+ // Spec: 0001-crypto FR-008
2
+ /**
3
+ * WebAuthn (Web Authentication Level 3) for a relying party, pure and with no outside package (commons 0014-webauthn): the options a
4
+ * browser's `navigator.credentials.create()` and `.get()` take, and the verification of what they answer, in the JSON shapes of the
5
+ * Level 3 `toJSON()` methods (every binary field as base64url). Registration checks the client data (`webauthn.create`, the challenge,
6
+ * the origin), the attestation object (CBOR: `fmt` `none`, or `packed` with no more than self-attestation's trust), the authenticator
7
+ * data (the SHA-256 of the RP ID, user presence and user verification, the attested credential) and the credential's COSE key (ES256 or
8
+ * EdDSA). Authentication checks the client data (`webauthn.get`), the authenticator data, the signature over the authenticator data and
9
+ * the SHA-256 of the client data by the stored key, and that the signature counter went up. Every refusal is a plain sentence, never an
10
+ * exception: what a browser sends is input from outside.
11
+ *
12
+ * The kernel has no randomness and no store: the caller makes each challenge (16 or more random bytes, base64url), keeps it until the
13
+ * answer comes, and keeps the credential (`credentialId`, `publicKey`, `alg`, `signCount`) that registration gives back.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { registrationOptions, verifyRegistration } from "./webauthn.ts";
18
+ * const options = registrationOptions({
19
+ * rpId: "example.com",
20
+ * rpName: "Example",
21
+ * user: { id: "dXNlci0x", name: "ada", displayName: "Ada" },
22
+ * challenge: "q83vEjRWeJq83vEjRWeJqw",
23
+ * });
24
+ * // send `options` to the browser; then, with what it answers:
25
+ * // const r = await verifyRegistration({ response, expectedChallenge: options.challenge, expectedOrigin: "https://example.com", rpId: "example.com" });
26
+ * ```
27
+ *
28
+ * @limits
29
+ * Attestation is not judged: commons asks for `none`, accepts `none`, and accepts `packed` with self-attestation (its signature checked) or
30
+ * with a certificate chain that is not checked, so that every credential has the trust of `none`; any other format is refused. Only ES256
31
+ * and EdDSA keys (see `cose.ts`). Extensions are read past, not interpreted; `topOrigin` is not checked, and a `crossOrigin` ceremony is
32
+ * refused.
33
+ *
34
+ * @module
35
+ */
36
+ import { fromBase64Url, toBase64Url } from "@intellectual-frontiers/formats/base64";
37
+ import { type CborKey, type CborValue, decodeCbor, decodeCborItem, formatCborError, isMap } from "@intellectual-frontiers/formats/cbor";
38
+ import { ALGORITHMS, type CoseKey, EDDSA, ES256, parseCoseKey, verifyCose } from "./cose.ts";
39
+ import {
40
+ array,
41
+ boolean,
42
+ formatDecodeError,
43
+ integer,
44
+ json,
45
+ literal,
46
+ nullable,
47
+ object,
48
+ record,
49
+ string,
50
+ unknownValue,
51
+ err,
52
+ ok,
53
+ type Result,
54
+ } from "@intellectual-frontiers/core";
55
+
56
+ /** A relying party as the options name it. */
57
+ export type PublicKeyCredentialRpEntity = { readonly id?: string; readonly name: string };
58
+
59
+ /** A user account as the options name it (`id` base64url, at most 64 bytes). */
60
+ export type PublicKeyCredentialUserEntityJSON = { readonly id: string; readonly name: string; readonly displayName: string };
61
+
62
+ /** An algorithm offered for a new credential. */
63
+ export type PublicKeyCredentialParameters = { readonly type: "public-key"; readonly alg: number };
64
+
65
+ /** A credential named by its id (base64url). */
66
+ export type PublicKeyCredentialDescriptorJSON = {
67
+ readonly type: "public-key";
68
+ readonly id: string;
69
+ readonly transports?: readonly string[];
70
+ };
71
+
72
+ /** What kind of authenticator is wanted. */
73
+ export type AuthenticatorSelectionCriteria = {
74
+ readonly authenticatorAttachment?: "platform" | "cross-platform";
75
+ readonly residentKey?: "discouraged" | "preferred" | "required";
76
+ readonly requireResidentKey?: boolean;
77
+ readonly userVerification?: "required" | "preferred" | "discouraged";
78
+ };
79
+
80
+ /** The options of `navigator.credentials.create({ publicKey })` as JSON (`PublicKeyCredential.parseCreationOptionsFromJSON` takes it). */
81
+ export type PublicKeyCredentialCreationOptionsJSON = {
82
+ readonly rp: PublicKeyCredentialRpEntity;
83
+ readonly user: PublicKeyCredentialUserEntityJSON;
84
+ readonly challenge: string;
85
+ readonly pubKeyCredParams: readonly PublicKeyCredentialParameters[];
86
+ readonly timeout?: number;
87
+ readonly excludeCredentials?: readonly PublicKeyCredentialDescriptorJSON[];
88
+ readonly authenticatorSelection?: AuthenticatorSelectionCriteria;
89
+ readonly hints?: readonly string[];
90
+ readonly attestation?: "none" | "indirect" | "direct" | "enterprise";
91
+ readonly attestationFormats?: readonly string[];
92
+ readonly extensions?: Readonly<Record<string, unknown>>;
93
+ };
94
+
95
+ /** The options of `navigator.credentials.get({ publicKey })` as JSON (`PublicKeyCredential.parseRequestOptionsFromJSON` takes it). */
96
+ export type PublicKeyCredentialRequestOptionsJSON = {
97
+ readonly challenge: string;
98
+ readonly timeout?: number;
99
+ readonly rpId?: string;
100
+ readonly allowCredentials?: readonly PublicKeyCredentialDescriptorJSON[];
101
+ readonly userVerification?: "required" | "preferred" | "discouraged";
102
+ readonly hints?: readonly string[];
103
+ readonly extensions?: Readonly<Record<string, unknown>>;
104
+ };
105
+
106
+ /** An authenticator's answer to `create()`, as `AuthenticatorAttestationResponse.toJSON()` gives it. */
107
+ export type AuthenticatorAttestationResponseJSON = {
108
+ readonly clientDataJSON: string;
109
+ readonly attestationObject: string;
110
+ readonly authenticatorData?: string;
111
+ readonly transports?: readonly string[];
112
+ readonly publicKey?: string;
113
+ readonly publicKeyAlgorithm?: number;
114
+ };
115
+
116
+ /** A new credential, as `PublicKeyCredential.toJSON()` gives it after `create()`. */
117
+ export type RegistrationResponseJSON = {
118
+ readonly id: string;
119
+ readonly rawId: string;
120
+ readonly response: AuthenticatorAttestationResponseJSON;
121
+ readonly authenticatorAttachment?: string | null;
122
+ readonly clientExtensionResults: Readonly<Record<string, unknown>>;
123
+ readonly type: "public-key";
124
+ };
125
+
126
+ /** An authenticator's answer to `get()`, as `AuthenticatorAssertionResponse.toJSON()` gives it. */
127
+ export type AuthenticatorAssertionResponseJSON = {
128
+ readonly clientDataJSON: string;
129
+ readonly authenticatorData: string;
130
+ readonly signature: string;
131
+ readonly userHandle?: string | null;
132
+ };
133
+
134
+ /** An assertion, as `PublicKeyCredential.toJSON()` gives it after `get()`. */
135
+ export type AuthenticationResponseJSON = {
136
+ readonly id: string;
137
+ readonly rawId: string;
138
+ readonly response: AuthenticatorAssertionResponseJSON;
139
+ readonly authenticatorAttachment?: string | null;
140
+ readonly clientExtensionResults: Readonly<Record<string, unknown>>;
141
+ readonly type: "public-key";
142
+ };
143
+
144
+ /** A credential as the relying party keeps it: its id and COSE public key (base64url), its algorithm and its last signature counter. */
145
+ export type StoredCredential = { readonly id: string; readonly publicKey: string; readonly alg: number; readonly signCount: number };
146
+
147
+ /** What a verified registration gives the relying party to keep. */
148
+ export type VerifiedRegistration = {
149
+ /** The credential's id, base64url. */
150
+ readonly credentialId: string;
151
+ /** The credential's public key as its CBOR `COSE_Key`, base64url. */
152
+ readonly publicKey: string;
153
+ /** Its COSE algorithm: -7 (ES256) or -8 (EdDSA). */
154
+ readonly alg: number;
155
+ readonly signCount: number;
156
+ readonly userVerified: boolean;
157
+ /** Whether the credential is backed up (synced, a passkey): the BS flag. */
158
+ readonly backedUp: boolean;
159
+ /** Whether it may be backed up: the BE flag. */
160
+ readonly backupEligible: boolean;
161
+ /** The authenticator's AAGUID, as a UUID (all zeros under attestation `none`). */
162
+ readonly aaguid: string;
163
+ /** The attestation format the authenticator used (`none` or `packed`). */
164
+ readonly fmt: string;
165
+ readonly transports?: string[];
166
+ };
167
+
168
+ /** What a verified authentication gives: the counter to keep, and the flags. */
169
+ export type VerifiedAuthentication = {
170
+ readonly signCount: number;
171
+ readonly userVerified: boolean;
172
+ readonly backedUp: boolean;
173
+ };
174
+
175
+ /** The default time a ceremony may take: five minutes, within what Level 3 recommends where user verification is required. */
176
+ export const DEFAULT_TIMEOUT_MS = 300_000;
177
+
178
+ function bytesOfB64u(text: unknown, what: string): Result<Uint8Array, string> {
179
+ if (typeof text !== "string") return err(`${what} is not a string`);
180
+ const r = fromBase64Url(text);
181
+ return r.kind === "ok" ? r : err(`${what} is not base64url`);
182
+ }
183
+
184
+ function checkedChallenge(challenge: string): void {
185
+ const r = fromBase64Url(challenge);
186
+ if (r.kind === "err" || r.value.length < 16) throw new RangeError("WebAuthn: a challenge is at least 16 random bytes, as base64url");
187
+ }
188
+
189
+ function descriptors(ids: readonly string[]): readonly PublicKeyCredentialDescriptorJSON[] {
190
+ return ids.map((id) => {
191
+ if (fromBase64Url(id).kind === "err") throw new RangeError(`WebAuthn: the credential id ${id} is not base64url`);
192
+ return { type: "public-key", id };
193
+ });
194
+ }
195
+
196
+ /**
197
+ * The options for registering a credential: ES256 and EdDSA offered, a discoverable credential preferred, user verification required, no
198
+ * attestation asked for, and the credentials the user already has excluded. A challenge shorter than 16 bytes or a user id longer than 64
199
+ * is a programming error and throws a `RangeError`.
200
+ */
201
+ export function registrationOptions(o: {
202
+ readonly rpId: string;
203
+ readonly rpName: string;
204
+ readonly user: { readonly id: string; readonly name: string; readonly displayName: string };
205
+ readonly challenge: string;
206
+ readonly excludeCredentials?: readonly string[];
207
+ readonly timeoutMs?: number;
208
+ }): PublicKeyCredentialCreationOptionsJSON {
209
+ checkedChallenge(o.challenge);
210
+ const uid = fromBase64Url(o.user.id);
211
+ if (uid.kind === "err" || uid.value.length === 0 || uid.value.length > 64)
212
+ throw new RangeError("WebAuthn: a user id is 1 to 64 bytes, as base64url");
213
+ return {
214
+ rp: { id: o.rpId, name: o.rpName },
215
+ user: { id: o.user.id, name: o.user.name, displayName: o.user.displayName },
216
+ challenge: o.challenge,
217
+ pubKeyCredParams: ALGORITHMS.map((alg) => ({ type: "public-key", alg })),
218
+ timeout: o.timeoutMs ?? DEFAULT_TIMEOUT_MS,
219
+ excludeCredentials: descriptors(o.excludeCredentials ?? []),
220
+ authenticatorSelection: { residentKey: "preferred", requireResidentKey: false, userVerification: "required" },
221
+ attestation: "none",
222
+ };
223
+ }
224
+
225
+ /** The options for authenticating: user verification required, and the credentials allowed where the user is known (none for a passkey's discoverable sign-in). */
226
+ export function authenticationOptions(o: {
227
+ readonly rpId: string;
228
+ readonly challenge: string;
229
+ readonly allowCredentials?: readonly string[];
230
+ readonly timeoutMs?: number;
231
+ }): PublicKeyCredentialRequestOptionsJSON {
232
+ checkedChallenge(o.challenge);
233
+ const base = { challenge: o.challenge, timeout: o.timeoutMs ?? DEFAULT_TIMEOUT_MS, rpId: o.rpId, userVerification: "required" } as const;
234
+ return o.allowCredentials === undefined ? base : { ...base, allowCredentials: descriptors(o.allowCredentials) };
235
+ }
236
+
237
+ /** The flags of authenticator data (WebAuthn §6.1). */
238
+ export const FLAGS = { up: 0x01, uv: 0x04, be: 0x08, bs: 0x10, at: 0x40, ed: 0x80 } as const;
239
+
240
+ /** Authenticator data as read (WebAuthn §6.1). */
241
+ export type AuthenticatorData = {
242
+ readonly rpIdHash: Uint8Array;
243
+ readonly flags: number;
244
+ readonly userPresent: boolean;
245
+ readonly userVerified: boolean;
246
+ readonly backupEligible: boolean;
247
+ readonly backedUp: boolean;
248
+ readonly signCount: number;
249
+ /** The attested credential data, where the AT flag says it is there. */
250
+ readonly attested?: { readonly aaguid: Uint8Array; readonly credentialId: Uint8Array; readonly publicKey: Uint8Array };
251
+ /** The extension outputs, where the ED flag says they are there. */
252
+ readonly extensions?: ReadonlyMap<CborKey, CborValue>;
253
+ };
254
+
255
+ /** Authenticator data read: the RP ID hash, the flags, the counter, the attested credential (its COSE key's bytes as given) and extensions; every byte accounted for. */
256
+ export function parseAuthenticatorData(bytes: Uint8Array): Result<AuthenticatorData, string> {
257
+ if (bytes.length < 37) return err(`the authenticator data is ${bytes.length} bytes, fewer than 37`);
258
+ const flags = bytes[32] ?? 0;
259
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
260
+ const signCount = view.getUint32(33);
261
+ let at = 37;
262
+ let attested: AuthenticatorData["attested"];
263
+ if (flags & FLAGS.at) {
264
+ if (bytes.length < at + 18) return err("the authenticator data ends inside its attested credential data");
265
+ const aaguid = bytes.slice(at, at + 16);
266
+ const idLength = view.getUint16(at + 16);
267
+ at += 18;
268
+ if (idLength > 1023) return err(`a credential id of ${idLength} bytes (at most 1023)`);
269
+ if (bytes.length < at + idLength) return err("the authenticator data ends inside the credential id");
270
+ const credentialId = bytes.slice(at, at + idLength);
271
+ at += idLength;
272
+ const key = decodeCborItem(bytes, at);
273
+ if (key.kind === "err") return err(`the credential public key is not CBOR (${formatCborError(key.error)})`);
274
+ const publicKey = bytes.slice(at, key.value.end);
275
+ at = key.value.end;
276
+ attested = { aaguid, credentialId, publicKey };
277
+ }
278
+ let extensions: ReadonlyMap<CborKey, CborValue> | undefined;
279
+ if (flags & FLAGS.ed) {
280
+ const ext = decodeCborItem(bytes, at);
281
+ if (ext.kind === "err") return err(`the extensions are not CBOR (${formatCborError(ext.error)})`);
282
+ if (!isMap(ext.value.value)) return err("the extensions are not a CBOR map");
283
+ extensions = ext.value.value;
284
+ at = ext.value.end;
285
+ }
286
+ if (at !== bytes.length) return err(`${bytes.length - at} bytes after the authenticator data that its flags do not account for`);
287
+ return ok({
288
+ rpIdHash: bytes.slice(0, 32),
289
+ flags,
290
+ userPresent: (flags & FLAGS.up) !== 0,
291
+ userVerified: (flags & FLAGS.uv) !== 0,
292
+ backupEligible: (flags & FLAGS.be) !== 0,
293
+ backedUp: (flags & FLAGS.bs) !== 0,
294
+ signCount,
295
+ ...(attested === undefined ? {} : { attested }),
296
+ ...(extensions === undefined ? {} : { extensions }),
297
+ });
298
+ }
299
+
300
+ /** Client data as read (WebAuthn §5.8.1). */
301
+ export type ClientData = {
302
+ readonly type: string;
303
+ readonly challenge: string;
304
+ readonly origin: string;
305
+ readonly crossOrigin?: boolean;
306
+ readonly topOrigin?: string;
307
+ };
308
+
309
+ const clientData = object({ type: string, challenge: string, origin: string }, { crossOrigin: boolean, topOrigin: string });
310
+
311
+ /** Client data JSON (its bytes, UTF-8) read. */
312
+ export function parseClientData(bytes: Uint8Array): Result<ClientData, string> {
313
+ let text: string;
314
+ try {
315
+ text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
316
+ } catch {
317
+ return err("the client data is not UTF-8");
318
+ }
319
+ const r = json(text, clientData);
320
+ return r.kind === "ok" ? r : err(`the client data is not WebAuthn's (${formatDecodeError(r.error)})`);
321
+ }
322
+
323
+ function sameBytes(a: Uint8Array, b: Uint8Array): boolean {
324
+ if (a.length !== b.length) return false;
325
+ let d = 0;
326
+ for (let i = 0; i < a.length; i++) d |= (a[i] ?? 0) ^ (b[i] ?? 0);
327
+ return d === 0;
328
+ }
329
+
330
+ async function digest(b: Uint8Array): Promise<Uint8Array> {
331
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", new Uint8Array(b)));
332
+ }
333
+
334
+ function concatBytes(a: Uint8Array, b: Uint8Array): Uint8Array {
335
+ const out = new Uint8Array(a.length + b.length);
336
+ out.set(a, 0);
337
+ out.set(b, a.length);
338
+ return out;
339
+ }
340
+
341
+ type Ceremony = {
342
+ readonly clientDataJSON: unknown;
343
+ readonly expectedChallenge: string;
344
+ readonly expectedOrigin: string | readonly string[];
345
+ };
346
+
347
+ /** The client data checked for its type, challenge, origin and cross-origin flag; its bytes, to hash. */
348
+ function checkClientData(type: "webauthn.create" | "webauthn.get", c: Ceremony): Result<Uint8Array, string> {
349
+ const raw = bytesOfB64u(c.clientDataJSON, "clientDataJSON");
350
+ if (raw.kind === "err") return raw;
351
+ const cd = parseClientData(raw.value);
352
+ if (cd.kind === "err") return cd;
353
+ if (cd.value.type !== type) return err(`the client data's type is ${cd.value.type}, not ${type}`);
354
+ const got = fromBase64Url(cd.value.challenge);
355
+ const want = fromBase64Url(c.expectedChallenge);
356
+ if (got.kind === "err" || want.kind === "err" || !sameBytes(got.value, want.value))
357
+ return err("the challenge is not the one this ceremony issued");
358
+ const origins: readonly string[] = typeof c.expectedOrigin === "string" ? [c.expectedOrigin] : c.expectedOrigin;
359
+ if (!origins.includes(cd.value.origin)) return err(`the origin ${cd.value.origin} is not one expected`);
360
+ if (cd.value.crossOrigin === true) return err("the ceremony ran in a cross-origin frame");
361
+ return ok(raw.value);
362
+ }
363
+
364
+ /** The authenticator data checked for the RP ID's hash, user presence and user verification, and the backup flags' consistency. */
365
+ async function checkAuthenticatorData(data: AuthenticatorData, rpId: string): Promise<Result<void, string>> {
366
+ if (!sameBytes(data.rpIdHash, await digest(new TextEncoder().encode(rpId))))
367
+ return err(`the authenticator data is not for the RP ID ${rpId}`);
368
+ if (!data.userPresent) return err("the user was not present (the UP flag is not set)");
369
+ if (!data.userVerified) return err("the user was not verified (the UV flag is not set)");
370
+ if (data.backedUp && !data.backupEligible) return err("the credential says it is backed up but not eligible to be (BS without BE)");
371
+ return ok(undefined);
372
+ }
373
+
374
+ function uuidOf(b: Uint8Array): string {
375
+ const h = [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
376
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
377
+ }
378
+
379
+ function algOfCose(key: CoseKey): number {
380
+ return key.kty === "EC2" ? ES256 : EDDSA;
381
+ }
382
+
383
+ /** The attestation statement checked: `none` empty; `packed` with self-attestation verified by the credential's own key, or with `x5c` taken at the trust of `none`. */
384
+ async function checkAttestation(
385
+ fmt: string,
386
+ stmt: CborValue,
387
+ key: CoseKey,
388
+ authData: Uint8Array,
389
+ clientDataHash: Uint8Array,
390
+ ): Promise<Result<void, string>> {
391
+ if (!isMap(stmt)) return err("the attestation statement is not a CBOR map");
392
+ if (fmt === "none") return stmt.size === 0 ? ok(undefined) : err("an attestation of format none with a statement");
393
+ if (fmt !== "packed") return err(`the attestation format ${fmt} is not accepted (commons asks for none, and accepts none and packed)`);
394
+ const alg = stmt.get("alg");
395
+ const sig = stmt.get("sig");
396
+ if (typeof alg !== "number" || !(sig instanceof Uint8Array)) return err("a packed attestation statement without alg and sig");
397
+ if (stmt.has("x5c")) return ok(undefined); // a certificate chain: not judged, the credential has the trust of none
398
+ if (alg !== algOfCose(key)) return err("a packed self-attestation whose algorithm is not the credential's");
399
+ const v = await verifyCose(key, sig, concatBytes(authData, clientDataHash));
400
+ if (v.kind === "err") return err(`the packed self-attestation cannot be checked (${v.error})`);
401
+ return v.value ? ok(undefined) : err("the packed self-attestation's signature does not verify");
402
+ }
403
+
404
+ /**
405
+ * A registration verified (WebAuthn §7.1): the client data, the attestation object, the authenticator data and the credential's key; what
406
+ * to keep, or why it is refused.
407
+ */
408
+ export async function verifyRegistration(o: {
409
+ readonly response: RegistrationResponseJSON;
410
+ readonly expectedChallenge: string;
411
+ readonly expectedOrigin: string | readonly string[];
412
+ readonly rpId: string;
413
+ }): Promise<Result<VerifiedRegistration, string>> {
414
+ const r = o.response;
415
+ if (r.type !== "public-key") return err("the credential is not of type public-key");
416
+ const rawId = bytesOfB64u(r.rawId, "rawId");
417
+ if (rawId.kind === "err") return rawId;
418
+ if (r.id !== r.rawId) return err("the credential's id and rawId differ");
419
+ const clientDataJSON = checkClientData("webauthn.create", {
420
+ clientDataJSON: r.response.clientDataJSON,
421
+ expectedChallenge: o.expectedChallenge,
422
+ expectedOrigin: o.expectedOrigin,
423
+ });
424
+ if (clientDataJSON.kind === "err") return clientDataJSON;
425
+ const attObjBytes = bytesOfB64u(r.response.attestationObject, "attestationObject");
426
+ if (attObjBytes.kind === "err") return attObjBytes;
427
+ const attObj = decodeCbor(attObjBytes.value);
428
+ if (attObj.kind === "err") return err(`the attestation object is not CBOR (${formatCborError(attObj.error)})`);
429
+ if (!isMap(attObj.value)) return err("the attestation object is not a CBOR map");
430
+ const fmt = attObj.value.get("fmt");
431
+ const authBytes = attObj.value.get("authData");
432
+ const stmt = attObj.value.get("attStmt");
433
+ if (typeof fmt !== "string" || !(authBytes instanceof Uint8Array) || stmt === undefined)
434
+ return err("the attestation object lacks fmt, attStmt or authData");
435
+ const data = parseAuthenticatorData(authBytes);
436
+ if (data.kind === "err") return data;
437
+ const checked = await checkAuthenticatorData(data.value, o.rpId);
438
+ if (checked.kind === "err") return checked;
439
+ const attested = data.value.attested;
440
+ if (attested === undefined) return err("the authenticator data holds no attested credential (the AT flag is not set)");
441
+ if (!sameBytes(attested.credentialId, rawId.value))
442
+ return err("the credential id in the authenticator data is not the credential's rawId");
443
+ const key = parseCoseKey(attested.publicKey);
444
+ if (key.kind === "err") return key;
445
+ const clientDataHash = await digest(clientDataJSON.value);
446
+ const att = await checkAttestation(fmt, stmt, key.value, authBytes, clientDataHash);
447
+ if (att.kind === "err") return att;
448
+ const transports = Array.isArray(r.response.transports)
449
+ ? r.response.transports.filter((t): t is string => typeof t === "string")
450
+ : undefined;
451
+ return ok({
452
+ credentialId: toBase64Url(rawId.value),
453
+ publicKey: toBase64Url(attested.publicKey),
454
+ alg: algOfCose(key.value),
455
+ signCount: data.value.signCount,
456
+ userVerified: data.value.userVerified,
457
+ backedUp: data.value.backedUp,
458
+ backupEligible: data.value.backupEligible,
459
+ aaguid: uuidOf(attested.aaguid),
460
+ fmt,
461
+ ...(transports === undefined ? {} : { transports }),
462
+ });
463
+ }
464
+
465
+ /**
466
+ * An authentication verified (WebAuthn §7.2) against the credential kept at registration: the client data, the authenticator data, the
467
+ * signature and the counter; the counter and flags to keep, or why it is refused.
468
+ */
469
+ export async function verifyAuthentication(o: {
470
+ readonly response: AuthenticationResponseJSON;
471
+ readonly expectedChallenge: string;
472
+ readonly expectedOrigin: string | readonly string[];
473
+ readonly rpId: string;
474
+ readonly credential: StoredCredential;
475
+ }): Promise<Result<VerifiedAuthentication, string>> {
476
+ const r = o.response;
477
+ if (r.type !== "public-key") return err("the credential is not of type public-key");
478
+ const rawId = bytesOfB64u(r.rawId, "rawId");
479
+ if (rawId.kind === "err") return rawId;
480
+ if (r.id !== r.rawId) return err("the credential's id and rawId differ");
481
+ const storedId = bytesOfB64u(o.credential.id, "the stored credential's id");
482
+ if (storedId.kind === "err") return storedId;
483
+ if (!sameBytes(rawId.value, storedId.value)) return err("the assertion is by another credential than the one given");
484
+ const clientDataJSON = checkClientData("webauthn.get", {
485
+ clientDataJSON: r.response.clientDataJSON,
486
+ expectedChallenge: o.expectedChallenge,
487
+ expectedOrigin: o.expectedOrigin,
488
+ });
489
+ if (clientDataJSON.kind === "err") return clientDataJSON;
490
+ const authBytes = bytesOfB64u(r.response.authenticatorData, "authenticatorData");
491
+ if (authBytes.kind === "err") return authBytes;
492
+ const data = parseAuthenticatorData(authBytes.value);
493
+ if (data.kind === "err") return data;
494
+ const checked = await checkAuthenticatorData(data.value, o.rpId);
495
+ if (checked.kind === "err") return checked;
496
+ const keyBytes = bytesOfB64u(o.credential.publicKey, "the stored public key");
497
+ if (keyBytes.kind === "err") return keyBytes;
498
+ const key = parseCoseKey(keyBytes.value);
499
+ if (key.kind === "err") return err(`the stored public key cannot be used (${key.error})`);
500
+ if (algOfCose(key.value) !== o.credential.alg) return err("the stored algorithm is not the stored key's");
501
+ const signature = bytesOfB64u(r.response.signature, "signature");
502
+ if (signature.kind === "err") return signature;
503
+ const signed = concatBytes(authBytes.value, await digest(clientDataJSON.value));
504
+ const v = await verifyCose(key.value, signature.value, signed);
505
+ if (v.kind === "err") return v;
506
+ if (!v.value) return err("the signature does not verify");
507
+ const now = data.value.signCount;
508
+ const before = o.credential.signCount;
509
+ if ((now !== 0 || before !== 0) && now <= before)
510
+ return err(`the signature counter went from ${before} to ${now}, not up: the authenticator may be cloned`);
511
+ return ok({ signCount: now, userVerified: data.value.userVerified, backedUp: data.value.backedUp });
512
+ }
513
+
514
+ const kind = literal("public-key");
515
+ const extensionResults = record(unknownValue);
516
+
517
+ /** JSON from a browser read as a `RegistrationResponseJSON`, or why it is not one: the boundary before `verifyRegistration`. */
518
+ export function parseRegistrationResponse(input: unknown): Result<RegistrationResponseJSON, string> {
519
+ const d = object(
520
+ {
521
+ id: string,
522
+ rawId: string,
523
+ type: kind,
524
+ response: object(
525
+ { clientDataJSON: string, attestationObject: string },
526
+ { authenticatorData: string, transports: array(string), publicKey: string, publicKeyAlgorithm: integer },
527
+ ),
528
+ },
529
+ { authenticatorAttachment: nullable(string), clientExtensionResults: extensionResults },
530
+ )(input);
531
+ if (d.kind === "err") return err(`not a registration response (${formatDecodeError(d.error)})`);
532
+ return ok({ ...d.value, clientExtensionResults: d.value.clientExtensionResults ?? {} });
533
+ }
534
+
535
+ /** JSON from a browser read as an `AuthenticationResponseJSON`, or why it is not one: the boundary before `verifyAuthentication`. */
536
+ export function parseAuthenticationResponse(input: unknown): Result<AuthenticationResponseJSON, string> {
537
+ const d = object(
538
+ {
539
+ id: string,
540
+ rawId: string,
541
+ type: kind,
542
+ response: object({ clientDataJSON: string, authenticatorData: string, signature: string }, { userHandle: nullable(string) }),
543
+ },
544
+ { authenticatorAttachment: nullable(string), clientExtensionResults: extensionResults },
545
+ )(input);
546
+ if (d.kind === "err") return err(`not an authentication response (${formatDecodeError(d.error)})`);
547
+ return ok({ ...d.value, clientExtensionResults: d.value.clientExtensionResults ?? {} });
548
+ }