@prson/login-verifier 0.0.0-stage → 0.2.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.
package/dist/index.js ADDED
@@ -0,0 +1,624 @@
1
+ /**
2
+ * @prson/login-verifier — Node.js verifier for SD-JWT-VC presentations.
3
+ *
4
+ * Enforces the five rules in `../../SECURITY.md §7`. Built on top of
5
+ * `jose` for JWS verification + a hand-written SD-JWT splitter that
6
+ * mirrors the Dart implementation at
7
+ * mobile-app/prson_app/lib/core/utils/sd_jwt_present.dart.
8
+ *
9
+ * Pure-function. No state beyond an in-memory JWKS cache (1-hour TTL).
10
+ */
11
+ import { createHash, createPublicKey, createVerify } from "node:crypto";
12
+ import { importJWK, jwtVerify } from "jose";
13
+ import { checkCredentialStatus } from "./status.js";
14
+ export { checkCredentialStatus, clearStatusCache } from "./status.js";
15
+ export { NOTIFY_HANDLE, readNotifyHandle, sendNotification, } from "./notify.js";
16
+ export { canonicalJson, verdictDisclosureDigest, verifyVerdict, VERDICT_SCOPE_V1, VERDICT_SCOPE_V2, } from "./verdict.js";
17
+ const DEFAULT_TRUSTED_ISSUER = "did:web:app.prson.net";
18
+ const DEFAULT_JWKS_URI = "https://app.prson.net/.well-known/jwt-vc-issuer";
19
+ const DEFAULT_ACCEPTED_VCTS = [
20
+ "https://app.prson.net/credentials/verified-human/v1",
21
+ "https://app.prson.net/credentials/verified-identity/v1",
22
+ ];
23
+ const DEFAULT_MAX_KB_AGE_SECONDS = 60;
24
+ const DEFAULT_JWKS_CACHE_TTL_MS = 60 * 60 * 1000;
25
+ export async function verifyPresentation(presentation, opts) {
26
+ if (typeof presentation !== "string" || presentation.length === 0) {
27
+ return { ok: false, reason: "malformed", detail: "empty" };
28
+ }
29
+ const parts = presentation.split("~");
30
+ if (parts.length < 2)
31
+ return { ok: false, reason: "malformed", detail: "no tildes" };
32
+ const jws = parts[0];
33
+ const tail = parts.slice(1);
34
+ const last = tail[tail.length - 1];
35
+ let kbJwt;
36
+ let discTokens;
37
+ if (!last)
38
+ return { ok: false, reason: "kb_missing" };
39
+ if (last.includes(".")) {
40
+ kbJwt = last;
41
+ discTokens = tail.slice(0, -1);
42
+ }
43
+ else if (last === "") {
44
+ return { ok: false, reason: "kb_missing" };
45
+ }
46
+ else {
47
+ // No KB-JWT slot was reserved — disclosed-only presentation; we
48
+ // require KB for any login use case.
49
+ return { ok: false, reason: "kb_missing" };
50
+ }
51
+ // ── 1. Parse + verify the issuer JWS ──────────────────────────────
52
+ const [hB64, pB64, sigB64] = jws.split(".");
53
+ if (!hB64 || !pB64 || !sigB64) {
54
+ return { ok: false, reason: "malformed", detail: "jws shape" };
55
+ }
56
+ let header;
57
+ let payload;
58
+ try {
59
+ header = JSON.parse(b64uToString(hB64));
60
+ payload = JSON.parse(b64uToString(pB64));
61
+ }
62
+ catch {
63
+ return { ok: false, reason: "malformed", detail: "json" };
64
+ }
65
+ // SD-JWT VC media type (draft-ietf-oauth-sd-jwt-vc): dc+sd-jwt, or the older vc+sd-jwt.
66
+ if (header.typ !== "dc+sd-jwt" && header.typ !== "vc+sd-jwt") {
67
+ return { ok: false, reason: "typ_not_accepted", detail: String(header.typ) };
68
+ }
69
+ const trustedIssuer = opts.trustedIssuer ?? DEFAULT_TRUSTED_ISSUER;
70
+ if (payload.iss !== trustedIssuer) {
71
+ return {
72
+ ok: false,
73
+ reason: "issuer_key_resolve_failed",
74
+ detail: `iss=${String(payload.iss)} expected=${trustedIssuer}`,
75
+ };
76
+ }
77
+ const accepted = opts.acceptedVcts ?? DEFAULT_ACCEPTED_VCTS;
78
+ if (typeof payload.vct !== "string" || !accepted.includes(payload.vct)) {
79
+ return { ok: false, reason: "vct_not_accepted", detail: String(payload.vct) };
80
+ }
81
+ const nowSec = Math.floor(Date.now() / 1000);
82
+ // Prson always sets an expiry; a credential without one is not Prson's.
83
+ if (typeof payload.exp !== "number") {
84
+ return { ok: false, reason: "malformed", detail: "no exp" };
85
+ }
86
+ if (payload.exp < nowSec) {
87
+ return { ok: false, reason: "vc_expired" };
88
+ }
89
+ if (typeof payload.nbf === "number" && payload.nbf > nowSec + 30) {
90
+ return { ok: false, reason: "vc_not_yet_valid" };
91
+ }
92
+ if (!header.kid)
93
+ return { ok: false, reason: "issuer_key_resolve_failed", detail: "no kid" };
94
+ const issuerJwk = await resolveIssuerJwk(header.kid, opts);
95
+ if (!issuerJwk)
96
+ return { ok: false, reason: "issuer_key_resolve_failed", detail: "unknown kid" };
97
+ try {
98
+ // jose's `jwtVerify` does header.alg lookup against the imported
99
+ // key + JOSE-compliant signature verification + signing-input bytes.
100
+ // Disabling iat/exp because we already validated `exp` above.
101
+ await jwtVerify(jws, await importJWK(issuerJwk, "RS256"), {
102
+ algorithms: ["RS256"],
103
+ issuer: trustedIssuer,
104
+ currentDate: new Date(nowSec * 1000),
105
+ });
106
+ }
107
+ catch (e) {
108
+ return { ok: false, reason: "issuer_sig_invalid", detail: e.message };
109
+ }
110
+ // ── 1b. Not revoked (the issuer's Token Status List) ──────────────
111
+ const status = await checkCredentialStatus(payload, {
112
+ resolveKey: async (kid) => (await resolveIssuerJwk(kid, opts)),
113
+ onUnavailable: opts.status?.onUnavailable,
114
+ cacheSeconds: opts.status?.cacheSeconds,
115
+ });
116
+ if (!status.ok)
117
+ return { ok: false, reason: status.reason, detail: status.detail };
118
+ // ── 2. Verify every Disclosure digest is bound by the JWS's _sd ───
119
+ const sdSet = collectSdDigests(payload);
120
+ const disclosed = [];
121
+ for (const t of discTokens) {
122
+ if (!t)
123
+ continue;
124
+ const digest = sha256B64u(t);
125
+ if (!sdSet.has(digest)) {
126
+ return { ok: false, reason: "disclosure_unmatched", detail: digest };
127
+ }
128
+ let arr;
129
+ try {
130
+ arr = JSON.parse(b64uToString(t));
131
+ }
132
+ catch {
133
+ return { ok: false, reason: "malformed", detail: "disclosure json" };
134
+ }
135
+ if (Array.isArray(arr) && arr.length === 3 && typeof arr[1] === "string") {
136
+ disclosed.push({ name: arr[1], value: arr[2] });
137
+ }
138
+ }
139
+ // ── 3. Verify the KB-JWT ──────────────────────────────────────────
140
+ const cnf = payload.cnf?.jwk;
141
+ if (!cnf || cnf.kty !== "OKP" || cnf.crv !== "Ed25519" || typeof cnf.x !== "string") {
142
+ return { ok: false, reason: "kb_missing", detail: "no cnf.jwk OKP/Ed25519" };
143
+ }
144
+ const [kbH, kbP, kbS] = kbJwt.split(".");
145
+ if (!kbH || !kbP || !kbS) {
146
+ return { ok: false, reason: "kb_sig_invalid", detail: "kb shape" };
147
+ }
148
+ let kbHeader;
149
+ let kbPayload;
150
+ try {
151
+ kbHeader = JSON.parse(b64uToString(kbH));
152
+ kbPayload = JSON.parse(b64uToString(kbP));
153
+ }
154
+ catch {
155
+ return { ok: false, reason: "kb_sig_invalid", detail: "kb json" };
156
+ }
157
+ if (kbHeader.alg !== "EdDSA" || kbHeader.typ !== "kb+jwt") {
158
+ return { ok: false, reason: "kb_sig_invalid", detail: "kb header" };
159
+ }
160
+ if (kbPayload.aud !== opts.expectedAudience) {
161
+ return { ok: false, reason: "aud_mismatch", detail: String(kbPayload.aud) };
162
+ }
163
+ if (kbPayload.nonce !== opts.expectedNonce) {
164
+ return { ok: false, reason: "nonce_mismatch" };
165
+ }
166
+ if (typeof kbPayload.iat !== "number")
167
+ return { ok: false, reason: "kb_iat_stale" };
168
+ const maxAge = opts.maxKbJwtAgeSeconds ?? DEFAULT_MAX_KB_AGE_SECONDS;
169
+ if (Math.abs(nowSec - kbPayload.iat) > maxAge) {
170
+ return { ok: false, reason: "kb_iat_stale", detail: `iat skew=${nowSec - kbPayload.iat}s` };
171
+ }
172
+ const presentationPrefix = `${jws}~${discTokens.join("~")}~`;
173
+ if (kbPayload.sd_hash !== sha256B64u(presentationPrefix)) {
174
+ return { ok: false, reason: "sd_hash_mismatch" };
175
+ }
176
+ // KB-JWT signature against cnf.jwk.
177
+ try {
178
+ await jwtVerify(kbJwt, await importJWK(cnf, "EdDSA"), { algorithms: ["EdDSA"] });
179
+ }
180
+ catch (e) {
181
+ return { ok: false, reason: "kb_sig_invalid", detail: e.message };
182
+ }
183
+ // ── 4. Build the verified claims map ──────────────────────────────
184
+ const claims = {};
185
+ for (const [k, v] of Object.entries(payload)) {
186
+ if (k === "_sd" || k === "_sd_alg" || k === "cnf")
187
+ continue;
188
+ if (k === "iss" || k === "vct" || k === "iat" || k === "exp" || k === "nbf")
189
+ continue;
190
+ claims[k] = v;
191
+ }
192
+ for (const d of disclosed)
193
+ claims[d.name] = d.value;
194
+ return {
195
+ ok: true,
196
+ prsonId: cnf.x,
197
+ claims,
198
+ cnf: { jwk: { kty: "OKP", crv: "Ed25519", x: cnf.x } },
199
+ credential: {
200
+ vct: payload.vct,
201
+ iss: payload.iss,
202
+ kid: header.kid,
203
+ iat: typeof payload.iat === "number" ? payload.iat : 0,
204
+ expiresAt: typeof payload.exp === "number" ? payload.exp * 1000 : 0,
205
+ },
206
+ disclosedClaimNames: disclosed.map((d) => d.name),
207
+ };
208
+ }
209
+ // ── Predicate (fragment) verification ────────────────────────────────
210
+ //
211
+ // Predicates are signed boolean assertions about a verified Prson
212
+ // property — "age >= 18", "balance >= 5000 EUR", "doc not expired".
213
+ // They are minted on-demand by `signPropertyFragment` in three shapes,
214
+ // and the helpers below verify each. The shapes are deliberately tiny
215
+ // next to a full login presentation (no KB-JWT, no nonce, no audience)
216
+ // because a fragment is a transferable factual claim, not a sign-in
217
+ // proof — its anti-replay is the short TTL + the propertyHash binding.
218
+ const DEFAULT_PREDICATE_VCT = "https://app.prson.net/credentials/predicate/v1";
219
+ /** The VC Data Model `type` of a predicate fact in the vc+jwt format. */
220
+ const PREDICATE_VC_TYPE = "PrsonPredicateCredential";
221
+ /**
222
+ * Verify a Prson-native signed fragment. The signature is RSA-SHA256
223
+ * over the colon-delimited canonical string
224
+ * `${propertyHash}:${fragmentId}:${value}:${identityId}:${signedAt}:${expiresAt}`
225
+ * — identical bytes to what the server signed in
226
+ * `functions/utils/predicateFormatters.js#formatNative`.
227
+ */
228
+ export async function verifySignedFragment(fragment, opts = {}) {
229
+ if (!fragment ||
230
+ typeof fragment.signature !== "string" ||
231
+ typeof fragment.propertyHash !== "string" ||
232
+ typeof fragment.fragmentId !== "string" ||
233
+ typeof fragment.identityId !== "string" ||
234
+ typeof fragment.signedAt !== "string" ||
235
+ typeof fragment.expiresAt !== "string" ||
236
+ typeof fragment.kid !== "string") {
237
+ return { ok: false, reason: "malformed", detail: "missing required fields" };
238
+ }
239
+ const now = (opts.now ?? new Date()).getTime();
240
+ if (new Date(fragment.expiresAt).getTime() <= now) {
241
+ return { ok: false, reason: "expired" };
242
+ }
243
+ // Audience-scoped (pairwise) fragments are domain-bound: the verifier
244
+ // must declare its own host and it must match what the issuer bound.
245
+ if (fragment.audience != null) {
246
+ const expected = (opts.expectedAudience ?? "").trim().toLowerCase();
247
+ if (!expected || expected !== String(fragment.audience).toLowerCase()) {
248
+ return {
249
+ ok: false,
250
+ reason: "audience_mismatch",
251
+ detail: `fragment bound to '${fragment.audience}', expectedAudience='${expected || "(unset)"}'`,
252
+ };
253
+ }
254
+ }
255
+ const jwk = await resolveIssuerJwk(fragment.kid, opts);
256
+ if (!jwk)
257
+ return { ok: false, reason: "issuer_key_resolve_failed", detail: fragment.kid };
258
+ let pem;
259
+ try {
260
+ pem = createPublicKey({ key: jwk, format: "jwk" });
261
+ }
262
+ catch (e) {
263
+ return { ok: false, reason: "issuer_key_resolve_failed", detail: e.message };
264
+ }
265
+ const base = `${fragment.propertyHash}:${fragment.fragmentId}:${fragment.value}:${fragment.identityId}:${fragment.signedAt}:${fragment.expiresAt}`;
266
+ const dataToSign = fragment.audience != null ? `${base}:aud:${fragment.audience}` : base;
267
+ const verifier = createVerify("RSA-SHA256");
268
+ verifier.update(dataToSign);
269
+ verifier.end();
270
+ let sigBytes;
271
+ try {
272
+ sigBytes = Buffer.from(fragment.signature, "base64");
273
+ }
274
+ catch (e) {
275
+ return { ok: false, reason: "malformed", detail: `signature b64: ${e.message}` };
276
+ }
277
+ if (!verifier.verify(pem, sigBytes)) {
278
+ return { ok: false, reason: "issuer_sig_invalid" };
279
+ }
280
+ return {
281
+ ok: true,
282
+ format: "native",
283
+ fragmentId: fragment.fragmentId,
284
+ value: fragment.value,
285
+ propertyHash: fragment.propertyHash,
286
+ propertyType: fragment.propertyType,
287
+ identityId: fragment.identityId,
288
+ signedAt: fragment.signedAt,
289
+ expiresAt: fragment.expiresAt,
290
+ // Not returned: the native signature doesn't cover the description, so a
291
+ // holder could change it. Label the fact from `fragmentId`.
292
+ kid: fragment.kid,
293
+ };
294
+ }
295
+ /**
296
+ * Verify a JWT-shaped signed fragment. Detects the variant from the
297
+ * JWS `typ` header:
298
+ *
299
+ * * `vc+jwt` — plain W3C VC Data Model 2.0 JWS. The predicate sits
300
+ * in `credentialSubject`.
301
+ * * `sd-jwt` — IETF SD-JWT-VC. The disclosure (joined by `~`) is
302
+ * hashed and matched against `_sd[0]`.
303
+ *
304
+ * Anything else fails with `unsupported_format`.
305
+ */
306
+ export async function verifyFragmentCredential(credential, opts = {}) {
307
+ if (typeof credential !== "string" || credential.length === 0) {
308
+ return { ok: false, reason: "malformed", detail: "empty" };
309
+ }
310
+ const accepted = opts.acceptedPredicateVcts ?? [DEFAULT_PREDICATE_VCT];
311
+ // SD-JWT-VC compact form ends with `~`; split it off before treating
312
+ // the head as a JWS.
313
+ const tildeIdx = credential.indexOf("~");
314
+ const jws = tildeIdx < 0 ? credential : credential.slice(0, tildeIdx);
315
+ const discTokens = tildeIdx < 0
316
+ ? []
317
+ : credential
318
+ .slice(tildeIdx + 1)
319
+ .split("~")
320
+ .filter((s) => s.length > 0);
321
+ const [hB64, pB64, sigB64] = jws.split(".");
322
+ if (!hB64 || !pB64 || !sigB64) {
323
+ return { ok: false, reason: "malformed", detail: "jws shape" };
324
+ }
325
+ let header;
326
+ let payload;
327
+ try {
328
+ header = JSON.parse(b64uToString(hB64));
329
+ payload = JSON.parse(b64uToString(pB64));
330
+ }
331
+ catch (e) {
332
+ return { ok: false, reason: "malformed", detail: `json: ${e.message}` };
333
+ }
334
+ // vc+jwt: a VC Data Model 2.0 credential secured with JOSE, typed by its
335
+ // `type`; vc+sd-jwt: an SD-JWT VC (typ dc+sd-jwt), typed by its `vct`.
336
+ let format;
337
+ if (header.typ === "vc+jwt") {
338
+ format = "vc+jwt";
339
+ const ctx = payload["@context"];
340
+ const types = payload.type;
341
+ if (!Array.isArray(ctx) || ctx[0] !== "https://www.w3.org/ns/credentials/v2") {
342
+ return { ok: false, reason: "malformed", detail: "@context" };
343
+ }
344
+ if (!Array.isArray(types) || !types.includes("VerifiableCredential") || !types.includes(PREDICATE_VC_TYPE)) {
345
+ return { ok: false, reason: "vct_not_accepted", detail: `type=${JSON.stringify(types)}` };
346
+ }
347
+ }
348
+ else if (header.typ === "dc+sd-jwt") {
349
+ format = "vc+sd-jwt";
350
+ if (typeof payload.vct !== "string" || !accepted.includes(payload.vct)) {
351
+ return { ok: false, reason: "vct_not_accepted", detail: String(payload.vct) };
352
+ }
353
+ }
354
+ else {
355
+ return { ok: false, reason: "unsupported_format", detail: String(header.typ) };
356
+ }
357
+ const trustedIssuer = opts.trustedIssuer ?? DEFAULT_TRUSTED_ISSUER;
358
+ if (payload.iss !== trustedIssuer) {
359
+ return { ok: false, reason: "issuer_key_resolve_failed", detail: `iss=${String(payload.iss)}` };
360
+ }
361
+ const nowSec = Math.floor((opts.now ?? new Date()).getTime() / 1000);
362
+ // Prson always sets an expiry; a credential without one is not Prson's.
363
+ if (typeof payload.exp !== "number") {
364
+ return { ok: false, reason: "malformed", detail: "no exp" };
365
+ }
366
+ if (payload.exp < nowSec) {
367
+ return { ok: false, reason: "expired" };
368
+ }
369
+ // Audience-scoped credentials are bound to one relying party, the same rule
370
+ // as verifySignedFragment: a fact minted for another site never verifies here.
371
+ if (payload.aud != null) {
372
+ const expected = (opts.expectedAudience ?? "").trim().toLowerCase();
373
+ const bound = (Array.isArray(payload.aud) ? payload.aud : [payload.aud]).map((a) => String(a).toLowerCase());
374
+ if (!expected || !bound.includes(expected)) {
375
+ return {
376
+ ok: false,
377
+ reason: "audience_mismatch",
378
+ detail: `credential bound to '${bound.join(",")}', expectedAudience='${expected || "(unset)"}'`,
379
+ };
380
+ }
381
+ }
382
+ if (!header.kid)
383
+ return { ok: false, reason: "issuer_key_resolve_failed", detail: "no kid" };
384
+ const issuerJwk = await resolveIssuerJwk(header.kid, opts);
385
+ if (!issuerJwk)
386
+ return { ok: false, reason: "issuer_key_resolve_failed", detail: "unknown kid" };
387
+ try {
388
+ await jwtVerify(jws, await importJWK(issuerJwk, "RS256"), {
389
+ algorithms: ["RS256"],
390
+ issuer: trustedIssuer,
391
+ currentDate: new Date(nowSec * 1000),
392
+ });
393
+ }
394
+ catch (e) {
395
+ return { ok: false, reason: "issuer_sig_invalid", detail: e.message };
396
+ }
397
+ // Pull the predicate value out of whichever slot the format uses.
398
+ let fragmentId;
399
+ let value;
400
+ if (format === "vc+jwt") {
401
+ const subj = payload.credentialSubject;
402
+ if (!subj || typeof subj.fragmentId !== "string") {
403
+ return { ok: false, reason: "malformed", detail: "credentialSubject" };
404
+ }
405
+ fragmentId = subj.fragmentId;
406
+ value = subj.value;
407
+ const propertyHash = String(subj.propertyHash ?? "");
408
+ const propertyType = String(subj.propertyType ?? "");
409
+ const identityId = String(subj.id ?? payload.sub ?? "");
410
+ return {
411
+ ok: true,
412
+ format,
413
+ fragmentId,
414
+ value,
415
+ propertyHash,
416
+ propertyType,
417
+ identityId,
418
+ signedAt: typeof payload.iat === "number" ? new Date(payload.iat * 1000).toISOString() : "",
419
+ expiresAt: typeof payload.exp === "number" ? new Date(payload.exp * 1000).toISOString() : "",
420
+ description: typeof subj.description === "string" ? subj.description : undefined,
421
+ kid: header.kid,
422
+ };
423
+ }
424
+ // SD-JWT-VC: rehash the disclosure(s), match against `_sd`, and pull
425
+ // [salt, name, value] out of the matched disclosure for the result.
426
+ const sdSet = collectSdDigests(payload);
427
+ if (discTokens.length === 0) {
428
+ return { ok: false, reason: "malformed", detail: "no disclosure" };
429
+ }
430
+ let matched = null;
431
+ for (const t of discTokens) {
432
+ const digest = sha256B64u(t);
433
+ if (!sdSet.has(digest)) {
434
+ return { ok: false, reason: "malformed", detail: `unmatched disclosure ${digest}` };
435
+ }
436
+ try {
437
+ const arr = JSON.parse(b64uToString(t));
438
+ if (Array.isArray(arr) && arr.length === 3 && typeof arr[1] === "string") {
439
+ matched = { name: arr[1], val: arr[2] };
440
+ }
441
+ }
442
+ catch {
443
+ return { ok: false, reason: "malformed", detail: "disclosure json" };
444
+ }
445
+ }
446
+ if (!matched) {
447
+ return { ok: false, reason: "malformed", detail: "no parseable disclosure" };
448
+ }
449
+ return {
450
+ ok: true,
451
+ format,
452
+ fragmentId: matched.name,
453
+ value: matched.val,
454
+ propertyHash: String(payload.propertyHash ?? ""),
455
+ propertyType: String(payload.propertyType ?? ""),
456
+ identityId: String(payload.sub ?? ""),
457
+ signedAt: typeof payload.iat === "number" ? new Date(payload.iat * 1000).toISOString() : "",
458
+ expiresAt: typeof payload.exp === "number" ? new Date(payload.exp * 1000).toISOString() : "",
459
+ description: typeof payload.description === "string" ? payload.description : undefined,
460
+ kid: header.kid,
461
+ };
462
+ }
463
+ /**
464
+ * Resolve a Prson notary issuer JWK by `kid` against the published
465
+ * JWKS. Exposed separately so verifiers can pre-warm the cache.
466
+ */
467
+ export async function resolveIssuerKey(kid, opts = {}) {
468
+ return resolveIssuerJwk(kid, opts);
469
+ }
470
+ // ── Internals ─────────────────────────────────────────────────────────
471
+ const jwksCache = new Map();
472
+ const JWKS_REFETCH_MIN_MS = 60_000;
473
+ async function resolveIssuerJwk(kid, opts) {
474
+ const uri = opts.jwksUri ?? DEFAULT_JWKS_URI;
475
+ const ttl = opts.jwksCacheTtlMs ?? DEFAULT_JWKS_CACHE_TTL_MS;
476
+ const cached = jwksCache.get(uri);
477
+ // A kid we don't know yet usually means Prson just rotated its key: look
478
+ // again, but at most once a minute (so unknown kids can't hammer the JWKS).
479
+ const fresh = cached && Date.now() - cached.fetchedAt < ttl;
480
+ if (fresh && (cached.keys[kid] || Date.now() - cached.fetchedAt < JWKS_REFETCH_MIN_MS)) {
481
+ return cached.keys[kid] ?? null;
482
+ }
483
+ const fetchImpl = (opts.fetch ?? globalThis.fetch);
484
+ const res = await fetchImpl(uri);
485
+ if (!res.ok)
486
+ return null;
487
+ const body = (await res.json());
488
+ const keys = body.jwks?.keys ?? body.keys ?? [];
489
+ const map = {};
490
+ for (const k of keys) {
491
+ const id = k.kid;
492
+ if (id)
493
+ map[id] = k;
494
+ }
495
+ jwksCache.set(uri, { fetchedAt: Date.now(), keys: map });
496
+ return map[kid] ?? null;
497
+ }
498
+ function collectSdDigests(payload, out = new Set()) {
499
+ if (!payload || typeof payload !== "object")
500
+ return out;
501
+ if (Array.isArray(payload)) {
502
+ for (const v of payload)
503
+ collectSdDigests(v, out);
504
+ return out;
505
+ }
506
+ for (const [k, v] of Object.entries(payload)) {
507
+ if (k === "_sd" && Array.isArray(v)) {
508
+ for (const d of v)
509
+ if (typeof d === "string")
510
+ out.add(d);
511
+ }
512
+ else if (typeof v === "object") {
513
+ collectSdDigests(v, out);
514
+ }
515
+ }
516
+ return out;
517
+ }
518
+ function sha256B64u(input) {
519
+ return createHash("sha256").update(input, "ascii").digest("base64url");
520
+ }
521
+ function b64uToString(s) {
522
+ return Buffer.from(s, "base64url").toString("utf8");
523
+ }
524
+ /**
525
+ * Sorted-keys JSON canonicalisation — byte-identical port of the
526
+ * server's `functions/utils/signatureUtils.js#canonicalStringify`,
527
+ * which is what the notary signed.
528
+ */
529
+ function canonicalStringify(obj) {
530
+ if (obj === null || obj === undefined)
531
+ return "null";
532
+ if (typeof obj === "boolean" || typeof obj === "number")
533
+ return obj.toString();
534
+ if (typeof obj === "string")
535
+ return JSON.stringify(obj);
536
+ if (Array.isArray(obj))
537
+ return "[" + obj.map(canonicalStringify).join(",") + "]";
538
+ if (typeof obj === "object") {
539
+ const rec = obj;
540
+ const keys = Object.keys(rec).sort();
541
+ return ("{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalStringify(rec[k])).join(",") + "}");
542
+ }
543
+ return JSON.stringify(obj);
544
+ }
545
+ /**
546
+ * Verify a unique-human-id credential. Checks, in order: shape, scope,
547
+ * audience binding (must equal YOUR host — pass `expectedAudience`),
548
+ * expiry, the binding to this sign-in (`expectedNonce`, `expectedCnfX`),
549
+ * and the notary RSA-SHA256 signature against the published
550
+ * JWKS (kid-pinned). On success, `uniqueIdHash` is safe to use as the
551
+ * per-domain uniqueness key.
552
+ */
553
+ export async function verifyUniqueHumanId(credential, opts = {}) {
554
+ const env = credential?.envelope;
555
+ if (!env ||
556
+ typeof credential.signature !== "string" ||
557
+ typeof credential.kid !== "string" ||
558
+ typeof env.uniqueIdHash !== "string" ||
559
+ typeof env.audience !== "string" ||
560
+ typeof env.signedAt !== "string" ||
561
+ typeof env.expiresAt !== "string") {
562
+ return { ok: false, reason: "malformed", detail: "missing required fields" };
563
+ }
564
+ if (env.scope !== "prson-unique-human/1") {
565
+ return { ok: false, reason: "unsupported_format", detail: `scope ${String(env.scope)}` };
566
+ }
567
+ // The envelope names the bare host; accept it as "shop.example.com" or as
568
+ // "https://shop.example.com" (the form verifyPresentation takes), so one
569
+ // value works for both checks. Nothing else is stripped: a path, port or
570
+ // other scheme still mismatches.
571
+ const expected = (opts.expectedAudience ?? "").trim().toLowerCase().replace(/^https:\/\//, "").replace(/\/$/, "");
572
+ if (!expected || expected !== env.audience.toLowerCase()) {
573
+ return {
574
+ ok: false,
575
+ reason: "audience_mismatch",
576
+ detail: `bound to '${env.audience}', expectedAudience='${expected || "(unset)"}'`,
577
+ };
578
+ }
579
+ const now = (opts.now ?? new Date()).getTime();
580
+ if (new Date(env.expiresAt).getTime() <= now) {
581
+ return { ok: false, reason: "expired" };
582
+ }
583
+ // Binding to this sign-in (nonce + the wallet's sign-in key): without it
584
+ // the envelope is a bearer token anyone who copies it can replay.
585
+ const envNonce = typeof env.nonce === "string" ? env.nonce : null;
586
+ const envCnfX = typeof env.cnf?.jwk?.x === "string" ? env.cnf.jwk.x : null;
587
+ if (!opts.allowUnbound) {
588
+ if (!opts.expectedNonce || !opts.expectedCnfX) {
589
+ return { ok: false, reason: "binding_required", detail: "pass expectedNonce and expectedCnfX (the presentation's prsonId)" };
590
+ }
591
+ if (envNonce === null || envCnfX === null)
592
+ return { ok: false, reason: "unbound" };
593
+ }
594
+ if (envNonce !== null && opts.expectedNonce !== undefined && envNonce !== opts.expectedNonce) {
595
+ return { ok: false, reason: "nonce_mismatch" };
596
+ }
597
+ if (envCnfX !== null && opts.expectedCnfX !== undefined && envCnfX !== opts.expectedCnfX) {
598
+ return { ok: false, reason: "cnf_mismatch" };
599
+ }
600
+ const jwk = await resolveIssuerJwk(credential.kid, opts);
601
+ if (!jwk)
602
+ return { ok: false, reason: "issuer_key_resolve_failed", detail: credential.kid };
603
+ let pem;
604
+ try {
605
+ pem = createPublicKey({ key: jwk, format: "jwk" });
606
+ }
607
+ catch (e) {
608
+ return { ok: false, reason: "issuer_key_resolve_failed", detail: e.message };
609
+ }
610
+ const verifier = createVerify("RSA-SHA256");
611
+ verifier.update(canonicalStringify(env));
612
+ verifier.end();
613
+ let sigBytes;
614
+ try {
615
+ sigBytes = Buffer.from(credential.signature, "base64");
616
+ }
617
+ catch (e) {
618
+ return { ok: false, reason: "malformed", detail: `signature b64: ${e.message}` };
619
+ }
620
+ if (!verifier.verify(pem, sigBytes)) {
621
+ return { ok: false, reason: "issuer_sig_invalid" };
622
+ }
623
+ return { ok: true, uniqueIdHash: env.uniqueIdHash, envelope: env, kid: credential.kid };
624
+ }
@@ -0,0 +1,48 @@
1
+ /** `nh_` and 32 random bytes, base64url. */
2
+ export declare const NOTIFY_HANDLE: RegExp;
3
+ /**
4
+ * The handle from what your page posted: the SignInResult (or its
5
+ * `notifications`), or the handle itself. null when there's none or it is
6
+ * malformed.
7
+ */
8
+ export declare function readNotifyHandle(value: unknown): string | null;
9
+ export type SendNotificationOptions = {
10
+ /** An API key with notify:write. */
11
+ apiKey: string;
12
+ handle: string;
13
+ /** Plain text, up to 60 characters. Shown after your domain: "{domain}: {title}". */
14
+ title: string;
15
+ /** Plain text, up to 180 characters. */
16
+ body: string;
17
+ /** Optional https link on exactly the domain the person signed in to; the app asks before opening it. */
18
+ url?: string;
19
+ /** Default https://api.prson.net. */
20
+ apiBase?: string;
21
+ fetch?: (input: string, init: {
22
+ method: string;
23
+ headers: Record<string, string>;
24
+ body: string;
25
+ }) => Promise<{
26
+ status: number;
27
+ json(): Promise<unknown>;
28
+ }>;
29
+ };
30
+ export type SendNotificationResult = {
31
+ ok: true;
32
+ id: string;
33
+ status: number;
34
+ }
35
+ /**
36
+ * `revoked` (410): the person turned your notifications off; delete the
37
+ * handle and don't send again. Others: `error` is the API's code
38
+ * (handle_rate_limited, domain_not_registered, insufficient_balance…).
39
+ */
40
+ | {
41
+ ok: false;
42
+ status: number;
43
+ error: string;
44
+ message?: string;
45
+ revoked: boolean;
46
+ };
47
+ /** POST /v1/notify. Never throws for an API refusal; network errors propagate. */
48
+ export declare function sendNotification(opts: SendNotificationOptions): Promise<SendNotificationResult>;