@forestrie/receipt-verify 0.11.0 → 1.0.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,445 @@
1
+ /**
2
+ * Passkey session-key endorsement, payload v2 (devdocs ADR-0064 as amended by
3
+ * ADR-0065 §3; plan-2608-14 1.2).
4
+ *
5
+ * A passkey log root signs ceremonies only; the per-turn user-envelope
6
+ * signer is a separate session key, endorsed by the root via a COSE Sign1 in
7
+ * the ADR-0063 WebAuthn envelope. This module owns both sides of that
8
+ * artifact's byte-exact shape:
9
+ *
10
+ * - build/assemble: the client constructs the TBS, hashes its Sig_structure
11
+ * into the WebAuthn challenge, and attaches the assertion + signature;
12
+ * - verify: given the passkey root as trust anchor, validate the artifact
13
+ * (typed, challenge-bound, fail-closed) and yield the session public key
14
+ * and its validity window.
15
+ *
16
+ * The endorsement rides INSIDE every endorsed leaf (unprotected label
17
+ * `COSE_LABEL_SESSION_KEY_ENDORSEMENT`, -65801) and the chain
18
+ * root → endorsement → session key → leaf → receipt is walked by
19
+ * {@link verifyEndorsedLeaf} (the single offline rung, ADR-0065 §5) and by
20
+ * canopy SCRAPI admission (§4).
21
+ *
22
+ * Domain separation: the protected content type below names payload v2 and
23
+ * the payload is EXACTLY `{"sessionKey": bstr .size 64, "notBefore": uint,
24
+ * "notAfter": uint}` (unix milliseconds, the idtimestamp time domain).
25
+ * Anything else — including a v1 (window-less) artifact — is a verification
26
+ * failure, never a fallback (ADR-0065 §3: v1 is rejected, not grandfathered).
27
+ *
28
+ * The window itself is NOT checked here: the reference time differs per
29
+ * verifier (canopy's clock at admission; the receipted idtimestamp offline).
30
+ * Callers apply {@link checkEndorsementWindow} with the time they hold.
31
+ */
32
+
33
+ import {
34
+ COSE_ALG_ES256_WEBAUTHN,
35
+ coseUnprotectedToMap,
36
+ decodeCborDeterministic,
37
+ decodeCoseSign1,
38
+ encodeCborDeterministic,
39
+ encodeCoseSign1Raw,
40
+ encodeSigStructure,
41
+ verifyCoseSign1WithParsedKey,
42
+ WEBAUTHN_ENVELOPE_LABEL,
43
+ type ParsedVerifyKey,
44
+ } from "@forestrie/encoding";
45
+ import { importEs256PublicKeyFromGrantDataXy64 } from "./decode-trust-root-cbor.js";
46
+
47
+ /**
48
+ * Protected-header content type (label 3) naming the v2 endorsement artifact.
49
+ * Signed via Sig_structure, so both the artifact's type AND its payload
50
+ * version are non-malleable.
51
+ */
52
+ export const SESSION_KEY_ENDORSEMENT_CONTENT_TYPE =
53
+ "application/vnd.forestrie.session-key-endorsement.v2+cbor";
54
+
55
+ /**
56
+ * The retired ADR-0064 v1 content type (payload without a window). Exported
57
+ * only so verifiers and tests can name what is being REJECTED; no code path
58
+ * accepts it.
59
+ */
60
+ export const SESSION_KEY_ENDORSEMENT_V1_CONTENT_TYPE =
61
+ "application/vnd.forestrie.session-key-endorsement+cbor";
62
+
63
+ /** Payload map key holding the endorsed session public key (x‖y, 64 bytes). */
64
+ export const SESSION_KEY_PAYLOAD_KEY = "sessionKey";
65
+ /** Payload map key: window start, unix milliseconds, inclusive. */
66
+ export const NOT_BEFORE_PAYLOAD_KEY = "notBefore";
67
+ /** Payload map key: window end, unix milliseconds, inclusive. */
68
+ export const NOT_AFTER_PAYLOAD_KEY = "notAfter";
69
+
70
+ /** Default client window length: 7 days (ADR-0065 §3). */
71
+ export const DEFAULT_ENDORSEMENT_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
72
+
73
+ /** WebAuthn authenticatorData UV flag bit (WebAuthn L2 §6.1). */
74
+ const AUTH_FLAG_UV = 0x04;
75
+
76
+ /** Validity window of an endorsement, unix milliseconds, both ends inclusive. */
77
+ export interface EndorsementWindow {
78
+ notBefore: number;
79
+ notAfter: number;
80
+ }
81
+
82
+ /** To-be-signed endorsement halves plus the challenge preimage. */
83
+ export interface SessionKeyEndorsementTbs {
84
+ /** Protected header map bytes `{1: -65800, 3: cty(v2), 4: root x}`. */
85
+ protectedBstr: Uint8Array;
86
+ /** Payload bytes: deterministic CBOR `{sessionKey, notBefore, notAfter}`. */
87
+ payloadBstr: Uint8Array;
88
+ /**
89
+ * `Sig_structure` over the halves. The WebAuthn challenge MUST be
90
+ * `base64url(sha256(sigStructureBytes))` (ADR-0063 §3).
91
+ */
92
+ sigStructureBytes: Uint8Array;
93
+ }
94
+
95
+ function isUnixMs(v: unknown): v is number {
96
+ return typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
97
+ }
98
+
99
+ /**
100
+ * Structural window check shared by the builder and the verifier: both ends
101
+ * are unsigned safe integers and the window is non-empty (ADR-0065 §3
102
+ * "malformed windows are rejected": `notAfter ≤ notBefore`).
103
+ */
104
+ function windowWellFormed(w: {
105
+ notBefore: unknown;
106
+ notAfter: unknown;
107
+ }): w is EndorsementWindow {
108
+ return (
109
+ isUnixMs(w.notBefore) && isUnixMs(w.notAfter) && w.notAfter > w.notBefore
110
+ );
111
+ }
112
+
113
+ /**
114
+ * Build the v2 endorsement TBS. The caller hashes `sigStructureBytes` into
115
+ * the `navigator.credentials.get` challenge, then assembles with the assertion.
116
+ *
117
+ * @param input.rootPublicKeyX - Passkey root x coordinate (kid, 32 bytes)
118
+ * @param input.sessionPublicKeyXY - Endorsed session public key x‖y (64 bytes)
119
+ * @param input.notBefore - Window start, unix ms inclusive
120
+ * @param input.notAfter - Window end, unix ms inclusive; must exceed notBefore
121
+ */
122
+ export function buildSessionKeyEndorsementTbs(input: {
123
+ rootPublicKeyX: Uint8Array;
124
+ sessionPublicKeyXY: Uint8Array;
125
+ notBefore: number;
126
+ notAfter: number;
127
+ }): SessionKeyEndorsementTbs {
128
+ if (input.rootPublicKeyX.length !== 32) {
129
+ throw new Error("endorsement kid must be the 32-byte root x coordinate");
130
+ }
131
+ if (input.sessionPublicKeyXY.length !== 64) {
132
+ throw new Error("endorsed session key must be 64 bytes (x||y)");
133
+ }
134
+ if (!windowWellFormed(input)) {
135
+ throw new Error(
136
+ "endorsement window must be unsigned safe-integer unix ms with notAfter > notBefore",
137
+ );
138
+ }
139
+ const protectedBstr = encodeCborDeterministic(
140
+ new Map<number, unknown>([
141
+ [1, COSE_ALG_ES256_WEBAUTHN],
142
+ [3, SESSION_KEY_ENDORSEMENT_CONTENT_TYPE],
143
+ [4, input.rootPublicKeyX],
144
+ ]),
145
+ );
146
+ // Deterministic CBOR sorts the keys (RFC 8949 §4.2.1); insertion order here
147
+ // is irrelevant to the bytes.
148
+ const payloadBstr = encodeCborDeterministic(
149
+ new Map<string, unknown>([
150
+ [SESSION_KEY_PAYLOAD_KEY, input.sessionPublicKeyXY],
151
+ [NOT_BEFORE_PAYLOAD_KEY, input.notBefore],
152
+ [NOT_AFTER_PAYLOAD_KEY, input.notAfter],
153
+ ]),
154
+ );
155
+ const sigStructureBytes = encodeSigStructure(
156
+ protectedBstr,
157
+ new Uint8Array(0),
158
+ payloadBstr,
159
+ );
160
+ return { protectedBstr, payloadBstr, sigStructureBytes };
161
+ }
162
+
163
+ /**
164
+ * Assemble the final endorsement COSE Sign1: the assertion rides in the
165
+ * unprotected header at label -65800 (ADR-0063 §2), the signature is the
166
+ * assertion's, converted to low-s P1363 r‖s by the caller (see
167
+ * delegation-cose `derSignatureToP1363` / low-s normalisation).
168
+ */
169
+ export function assembleSessionKeyEndorsement(input: {
170
+ tbs: SessionKeyEndorsementTbs;
171
+ authenticatorData: Uint8Array;
172
+ clientDataJSON: Uint8Array;
173
+ /** Low-s P1363 r‖s (64 bytes). */
174
+ signature: Uint8Array;
175
+ }): Uint8Array {
176
+ if (input.signature.length !== 64) {
177
+ throw new Error("endorsement signature must be 64-byte P1363 r||s");
178
+ }
179
+ const unprotected = new Map<number, unknown>([
180
+ [WEBAUTHN_ENVELOPE_LABEL, [input.authenticatorData, input.clientDataJSON]],
181
+ ]);
182
+ return encodeCoseSign1Raw(
183
+ input.tbs.protectedBstr,
184
+ unprotected,
185
+ input.tbs.payloadBstr,
186
+ input.signature,
187
+ );
188
+ }
189
+
190
+ /** Verification failure reasons; the first check that broke. */
191
+ export type SessionKeyEndorsementFailureReason =
192
+ | "endorsement_malformed"
193
+ | "wrong_alg"
194
+ | "wrong_content_type"
195
+ | "kid_invalid"
196
+ | "kid_mismatch"
197
+ | "payload_invalid"
198
+ | "window_invalid"
199
+ | "uv_required"
200
+ | "signature_invalid"
201
+ | "session_key_import_failed";
202
+
203
+ /** Verification outcome; failures name the first check that broke. */
204
+ export type SessionKeyEndorsementVerifyResult =
205
+ | ({
206
+ ok: true;
207
+ /** Endorsed session public key, raw x‖y (64 bytes). */
208
+ sessionPublicKeyXY: Uint8Array;
209
+ /** The same key imported for ES256 verify of per-turn leaves. */
210
+ sessionKey: CryptoKey;
211
+ } & EndorsementWindow)
212
+ | { ok: false; reason: SessionKeyEndorsementFailureReason };
213
+
214
+ /** Options for {@link verifySessionKeyEndorsement}. */
215
+ export interface VerifySessionKeyEndorsementOptions {
216
+ /**
217
+ * Require the assertion's UV flag. At admission this is the grant's
218
+ * `GF_REQUIRES_USER_VERIFICATION` (ADR-0065 §4); at DO onboarding, where
219
+ * no grant exists yet, deployment config (ADR-0064 §3). User presence is
220
+ * always required regardless.
221
+ */
222
+ requireUserVerification?: boolean;
223
+ /** Emit JSON warning lines on failure paths (no secrets). */
224
+ logFailures?: boolean;
225
+ /** Included in JSON log lines. */
226
+ logPrefix?: string;
227
+ }
228
+
229
+ function protectedHeaderEntries(
230
+ protectedBstr: Uint8Array,
231
+ ): { alg: unknown; cty: unknown; kid: unknown } | null {
232
+ let decoded: unknown;
233
+ try {
234
+ decoded = decodeCborDeterministic(protectedBstr);
235
+ } catch {
236
+ return null;
237
+ }
238
+ if (decoded instanceof Map) {
239
+ return { alg: decoded.get(1), cty: decoded.get(3), kid: decoded.get(4) };
240
+ }
241
+ if (typeof decoded === "object" && decoded !== null) {
242
+ const obj = decoded as Record<string | number, unknown>;
243
+ return {
244
+ alg: obj[1] ?? obj["1"],
245
+ cty: obj[3] ?? obj["3"],
246
+ kid: obj[4] ?? obj["4"],
247
+ };
248
+ }
249
+ return null;
250
+ }
251
+
252
+ type DecodedPayload =
253
+ | { kind: "ok"; sessionPublicKeyXY: Uint8Array; window: EndorsementWindow }
254
+ | { kind: "payload_invalid" }
255
+ | { kind: "window_invalid" };
256
+
257
+ function toNumberIfInt(v: unknown): unknown {
258
+ // Deterministic decode may surface large ints as bigint; the window is
259
+ // unix ms (< 2^53) so a safe bigint is folded back to a number.
260
+ if (
261
+ typeof v === "bigint" &&
262
+ v >= 0n &&
263
+ v <= BigInt(Number.MAX_SAFE_INTEGER)
264
+ ) {
265
+ return Number(v);
266
+ }
267
+ return v;
268
+ }
269
+
270
+ function decodePayloadV2(payloadBstr: Uint8Array): DecodedPayload {
271
+ let decoded: unknown;
272
+ try {
273
+ decoded = decodeCborDeterministic(payloadBstr);
274
+ } catch {
275
+ return { kind: "payload_invalid" };
276
+ }
277
+ // Exactly three entries, exactly the three labels, exactly these shapes
278
+ // (ADR-0065 §3) — anything else is a failure, never a partial read.
279
+ let entries: [unknown, unknown][];
280
+ if (decoded instanceof Map) {
281
+ entries = [...decoded.entries()];
282
+ } else if (typeof decoded === "object" && decoded !== null) {
283
+ entries = Object.entries(decoded);
284
+ } else {
285
+ return { kind: "payload_invalid" };
286
+ }
287
+ if (entries.length !== 3) return { kind: "payload_invalid" };
288
+ const byKey = new Map<unknown, unknown>(entries);
289
+ const sessionPublicKeyXY = byKey.get(SESSION_KEY_PAYLOAD_KEY);
290
+ if (
291
+ !(sessionPublicKeyXY instanceof Uint8Array) ||
292
+ sessionPublicKeyXY.length !== 64
293
+ ) {
294
+ return { kind: "payload_invalid" };
295
+ }
296
+ const notBefore = toNumberIfInt(byKey.get(NOT_BEFORE_PAYLOAD_KEY));
297
+ const notAfter = toNumberIfInt(byKey.get(NOT_AFTER_PAYLOAD_KEY));
298
+ if (!isUnixMs(notBefore) || !isUnixMs(notAfter)) {
299
+ return { kind: "payload_invalid" };
300
+ }
301
+ const window = { notBefore, notAfter };
302
+ if (!windowWellFormed(window)) return { kind: "window_invalid" };
303
+ return { kind: "ok", sessionPublicKeyXY, window };
304
+ }
305
+
306
+ /** Read the assertion's flags byte from the -65800 envelope, if well-shaped. */
307
+ function envelopeFlags(unprotected: unknown): number | null {
308
+ const envelope = coseUnprotectedToMap(unprotected).get(
309
+ WEBAUTHN_ENVELOPE_LABEL,
310
+ );
311
+ if (!Array.isArray(envelope) || envelope.length !== 2) return null;
312
+ const authenticatorData = envelope[0];
313
+ if (
314
+ !(authenticatorData instanceof Uint8Array) ||
315
+ authenticatorData.length < 37
316
+ ) {
317
+ return null;
318
+ }
319
+ return authenticatorData[32]!;
320
+ }
321
+
322
+ /**
323
+ * Verify a v2 session-key endorsement under the passkey root and yield the
324
+ * endorsed session key plus its window. All the ADR-0063 envelope checks
325
+ * (challenge binding to this artifact's `Sig_structure`, UP flag, ceremony
326
+ * type, low-s, both fail-closed directions) run inside the shared `-65800`
327
+ * verify branch; this function adds the ADR-0064/0065 typing rules on top
328
+ * and reports a missing-UV rejection under its own reason so admission can
329
+ * name it (`endorsement_uv_required`, ADR-0065 §4).
330
+ *
331
+ * @param endorsementCbor - The endorsement COSE Sign1 bytes
332
+ * @param rootKeys - Passkey root trust anchor(s), tried in order. Raw
333
+ * coordinate anchors additionally pin `kid == root x`.
334
+ * @param opts - UV requirement and failure logging
335
+ */
336
+ export async function verifySessionKeyEndorsement(
337
+ endorsementCbor: Uint8Array,
338
+ rootKeys: ParsedVerifyKey | ParsedVerifyKey[],
339
+ opts?: VerifySessionKeyEndorsementOptions,
340
+ ): Promise<SessionKeyEndorsementVerifyResult> {
341
+ const anchors = Array.isArray(rootKeys) ? rootKeys : [rootKeys];
342
+
343
+ const decoded = decodeCoseSign1(endorsementCbor);
344
+ if (!decoded) return { ok: false, reason: "endorsement_malformed" };
345
+
346
+ const header = protectedHeaderEntries(decoded.protectedBstr);
347
+ if (!header) return { ok: false, reason: "endorsement_malformed" };
348
+
349
+ const alg = typeof header.alg === "bigint" ? Number(header.alg) : header.alg;
350
+ if (alg !== COSE_ALG_ES256_WEBAUTHN) {
351
+ return { ok: false, reason: "wrong_alg" };
352
+ }
353
+ if (header.cty !== SESSION_KEY_ENDORSEMENT_CONTENT_TYPE) {
354
+ return { ok: false, reason: "wrong_content_type" };
355
+ }
356
+ if (!(header.kid instanceof Uint8Array) || header.kid.length !== 32) {
357
+ return { ok: false, reason: "kid_invalid" };
358
+ }
359
+
360
+ const payload = decodePayloadV2(decoded.payloadBstr);
361
+ if (payload.kind !== "ok") return { ok: false, reason: payload.kind };
362
+
363
+ if (opts?.requireUserVerification) {
364
+ const flags = envelopeFlags(decoded.unprotected);
365
+ // A malformed envelope is left to the shared branch to reject; only a
366
+ // well-shaped assertion that plainly lacks UV gets the distinct reason.
367
+ if (flags !== null && (flags & AUTH_FLAG_UV) === 0) {
368
+ return { ok: false, reason: "uv_required" };
369
+ }
370
+ }
371
+
372
+ let kidMismatch = false;
373
+ for (const anchor of anchors) {
374
+ // When the anchor exposes raw coordinates, the signed kid must name it —
375
+ // a valid signature under a root whose x is not the kid is evidence of
376
+ // artifact confusion, not authorization (ADR-0064 §2 kid = root x).
377
+ if (!(anchor instanceof CryptoKey)) {
378
+ const x = anchor.x;
379
+ if (
380
+ x.length !== header.kid.length ||
381
+ !x.every((b, i) => b === (header.kid as Uint8Array)[i])
382
+ ) {
383
+ kidMismatch = true;
384
+ continue;
385
+ }
386
+ }
387
+ const sigOk = await verifyCoseSign1WithParsedKey(endorsementCbor, anchor, {
388
+ requireUserVerification: opts?.requireUserVerification,
389
+ logFailures: opts?.logFailures,
390
+ logPrefix: opts?.logPrefix ?? "session-key-endorsement",
391
+ });
392
+ if (!sigOk) continue;
393
+
394
+ let sessionKey: CryptoKey;
395
+ try {
396
+ sessionKey = await importEs256PublicKeyFromGrantDataXy64(
397
+ payload.sessionPublicKeyXY,
398
+ );
399
+ } catch {
400
+ return { ok: false, reason: "session_key_import_failed" };
401
+ }
402
+ return {
403
+ ok: true,
404
+ sessionPublicKeyXY: payload.sessionPublicKeyXY,
405
+ sessionKey,
406
+ ...payload.window,
407
+ };
408
+ }
409
+
410
+ return {
411
+ ok: false,
412
+ reason: kidMismatch ? "kid_mismatch" : "signature_invalid",
413
+ };
414
+ }
415
+
416
+ /** Outcome of {@link checkEndorsementWindow}. */
417
+ export type EndorsementWindowCheck =
418
+ | { ok: true }
419
+ | { ok: false; reason: "endorsement_not_yet_valid" | "endorsement_expired" };
420
+
421
+ /**
422
+ * Is `atMs` inside the endorsement's window? `notBefore ≤ atMs ≤ notAfter`,
423
+ * both inclusive (ADR-0065 §3). `skewMs` (default 0) tolerates a `notBefore`
424
+ * slightly in the future of a wall-clock verifier; offline verifiers
425
+ * comparing against the receipted idtimestamp should leave it at 0 — that
426
+ * comparison is exact and authoritative.
427
+ *
428
+ * Deliberately a pure function of the two numbers so callers can (and must)
429
+ * run it on every request, structurally outside any verified-endorsement
430
+ * cache (ADR-0065 §4).
431
+ */
432
+ export function checkEndorsementWindow(
433
+ window: EndorsementWindow,
434
+ atMs: number,
435
+ opts?: { skewMs?: number },
436
+ ): EndorsementWindowCheck {
437
+ const skew = opts?.skewMs ?? 0;
438
+ if (atMs + skew < window.notBefore) {
439
+ return { ok: false, reason: "endorsement_not_yet_valid" };
440
+ }
441
+ if (atMs > window.notAfter) {
442
+ return { ok: false, reason: "endorsement_expired" };
443
+ }
444
+ return { ok: true };
445
+ }