@peac/protocol 0.10.9 → 0.10.11

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.
Files changed (45) hide show
  1. package/LICENSE +1 -1
  2. package/dist/discovery.d.ts.map +1 -1
  3. package/dist/index.cjs +2694 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.mjs +2612 -0
  6. package/dist/index.mjs.map +1 -0
  7. package/dist/verification-report.d.ts.map +1 -1
  8. package/dist/verifier-types.d.ts +42 -2
  9. package/dist/verifier-types.d.ts.map +1 -1
  10. package/dist/verify-local.cjs +164 -0
  11. package/dist/verify-local.cjs.map +1 -0
  12. package/dist/verify-local.d.ts +15 -0
  13. package/dist/verify-local.d.ts.map +1 -1
  14. package/dist/verify-local.mjs +160 -0
  15. package/dist/verify-local.mjs.map +1 -0
  16. package/dist/verify.d.ts.map +1 -1
  17. package/package.json +20 -13
  18. package/dist/crypto-utils.js +0 -21
  19. package/dist/crypto-utils.js.map +0 -1
  20. package/dist/discovery.js +0 -405
  21. package/dist/discovery.js.map +0 -1
  22. package/dist/headers.js +0 -110
  23. package/dist/headers.js.map +0 -1
  24. package/dist/index.js +0 -44
  25. package/dist/index.js.map +0 -1
  26. package/dist/issue.js +0 -198
  27. package/dist/issue.js.map +0 -1
  28. package/dist/pointer-fetch.js +0 -305
  29. package/dist/pointer-fetch.js.map +0 -1
  30. package/dist/ssrf-safe-fetch.js +0 -671
  31. package/dist/ssrf-safe-fetch.js.map +0 -1
  32. package/dist/telemetry.js +0 -43
  33. package/dist/telemetry.js.map +0 -1
  34. package/dist/transport-profiles.js +0 -424
  35. package/dist/transport-profiles.js.map +0 -1
  36. package/dist/verification-report.js +0 -322
  37. package/dist/verification-report.js.map +0 -1
  38. package/dist/verifier-core.js +0 -578
  39. package/dist/verifier-core.js.map +0 -1
  40. package/dist/verifier-types.js +0 -161
  41. package/dist/verifier-types.js.map +0 -1
  42. package/dist/verify-local.js +0 -230
  43. package/dist/verify-local.js.map +0 -1
  44. package/dist/verify.js +0 -213
  45. package/dist/verify.js.map +0 -1
package/dist/index.mjs ADDED
@@ -0,0 +1,2612 @@
1
+ import { uuidv7 } from 'uuidv7';
2
+ import { sign, decode, verify, sha256Hex, computeJwkThumbprint, jwkToPublicKeyBytes, base64urlDecode } from '@peac/crypto';
3
+ export { base64urlDecode, base64urlEncode, computeJwkThumbprint, generateKeypair, jwkToPublicKeyBytes, sha256Bytes, sha256Hex, verify } from '@peac/crypto';
4
+ import { ZodError } from 'zod';
5
+ import { isValidPurposeToken, isCanonicalPurpose, isValidPurposeReason, isValidWorkflowContext, createWorkflowContextInvalidError, hasValidDagSemantics, createWorkflowDagInvalidError, WORKFLOW_EXTENSION_KEY, ReceiptClaims, createEvidenceNotJsonError, validateSubjectSnapshot, parseReceiptClaims, PEAC_RECEIPT_HEADER, PEAC_PURPOSE_HEADER, parsePurposeHeader, PEAC_PURPOSE_APPLIED_HEADER, PEAC_PURPOSE_REASON_HEADER, PEAC_ISSUER_CONFIG_MAX_BYTES, PEAC_ISSUER_CONFIG_PATH, PEAC_POLICY_MAX_BYTES, PEAC_POLICY_PATH, PEAC_POLICY_FALLBACK_PATH } from '@peac/schema';
6
+ import { createHash } from 'crypto';
7
+ import { VERIFIER_LIMITS, VERIFIER_NETWORK, VERIFIER_POLICY_VERSION, VERIFICATION_REPORT_VERSION, WIRE_TYPE } from '@peac/kernel';
8
+
9
+ // src/issue.ts
10
+ function fireTelemetryHook(fn, input) {
11
+ if (!fn) return;
12
+ try {
13
+ const result = fn(input);
14
+ if (result && typeof result.catch === "function") {
15
+ result.catch(() => {
16
+ });
17
+ }
18
+ } catch {
19
+ }
20
+ }
21
+ function hashReceipt(jws) {
22
+ const hash = createHash("sha256").update(jws).digest("hex");
23
+ return `sha256:${hash.slice(0, 16)}`;
24
+ }
25
+
26
+ // src/issue.ts
27
+ var IssueError = class extends Error {
28
+ /** Structured error details */
29
+ peacError;
30
+ constructor(peacError) {
31
+ const details = peacError.details;
32
+ super(details?.message ?? peacError.code);
33
+ this.name = "IssueError";
34
+ this.peacError = peacError;
35
+ }
36
+ };
37
+ async function issue(options) {
38
+ if (!options.iss.startsWith("https://")) {
39
+ throw new Error("Issuer URL must start with https://");
40
+ }
41
+ if (!options.aud.startsWith("https://")) {
42
+ throw new Error("Audience URL must start with https://");
43
+ }
44
+ if (options.subject && !options.subject.startsWith("https://")) {
45
+ throw new Error("Subject URI must start with https://");
46
+ }
47
+ if (!/^[A-Z]{3}$/.test(options.cur)) {
48
+ throw new Error("Currency must be ISO 4217 uppercase (e.g., USD)");
49
+ }
50
+ if (!Number.isInteger(options.amt) || options.amt < 0) {
51
+ throw new Error("Amount must be a non-negative integer");
52
+ }
53
+ if (options.exp !== void 0) {
54
+ if (!Number.isInteger(options.exp) || options.exp < 0) {
55
+ throw new Error("Expiry must be a non-negative integer");
56
+ }
57
+ }
58
+ let purposeDeclared;
59
+ if (options.purpose !== void 0) {
60
+ const rawPurposes = Array.isArray(options.purpose) ? options.purpose : [options.purpose];
61
+ const invalidTokens = [];
62
+ for (const token of rawPurposes) {
63
+ if (!isValidPurposeToken(token)) {
64
+ invalidTokens.push(token);
65
+ }
66
+ }
67
+ if (invalidTokens.length > 0) {
68
+ throw new Error(`Invalid purpose tokens: ${invalidTokens.join(", ")}`);
69
+ }
70
+ if (rawPurposes.includes("undeclared")) {
71
+ throw new Error("Explicit 'undeclared' is not a valid purpose token (internal-only)");
72
+ }
73
+ purposeDeclared = rawPurposes;
74
+ }
75
+ if (options.purpose_enforced !== void 0) {
76
+ if (!isCanonicalPurpose(options.purpose_enforced)) {
77
+ throw new Error(
78
+ `purpose_enforced must be a canonical purpose, got: ${options.purpose_enforced}`
79
+ );
80
+ }
81
+ }
82
+ if (options.purpose_reason !== void 0) {
83
+ if (!isValidPurposeReason(options.purpose_reason)) {
84
+ throw new Error(`Invalid purpose_reason: ${options.purpose_reason}`);
85
+ }
86
+ }
87
+ if (options.workflow_context !== void 0) {
88
+ if (!isValidWorkflowContext(options.workflow_context)) {
89
+ throw new IssueError(
90
+ createWorkflowContextInvalidError("Does not conform to WorkflowContextSchema")
91
+ );
92
+ }
93
+ if (!hasValidDagSemantics(options.workflow_context)) {
94
+ const ctx = options.workflow_context;
95
+ const isSelfParent = ctx.parent_step_ids.includes(ctx.step_id);
96
+ const hasDuplicates = new Set(ctx.parent_step_ids).size !== ctx.parent_step_ids.length;
97
+ const reason = isSelfParent ? "self_parent" : hasDuplicates ? "duplicate_parent" : "cycle";
98
+ throw new IssueError(createWorkflowDagInvalidError(reason));
99
+ }
100
+ }
101
+ const rid = uuidv7();
102
+ const iat = Math.floor(Date.now() / 1e3);
103
+ const claims = {
104
+ iss: options.iss,
105
+ aud: options.aud,
106
+ iat,
107
+ rid,
108
+ amt: options.amt,
109
+ cur: options.cur,
110
+ payment: {
111
+ rail: options.rail,
112
+ reference: options.reference,
113
+ amount: options.amt,
114
+ currency: options.cur,
115
+ asset: options.asset ?? options.cur,
116
+ // Default asset to currency for backward compatibility
117
+ env: options.env ?? "test",
118
+ // Default to test environment for backward compatibility
119
+ evidence: options.evidence ?? {},
120
+ // Default to empty object for backward compatibility
121
+ ...options.network && { network: options.network },
122
+ ...options.facilitator_ref && { facilitator_ref: options.facilitator_ref },
123
+ ...options.idempotency_key && { idempotency_key: options.idempotency_key },
124
+ ...options.metadata && { metadata: options.metadata }
125
+ },
126
+ ...options.exp && { exp: options.exp },
127
+ ...options.subject && { subject: { uri: options.subject } },
128
+ // Build extensions (merge user-provided ext with workflow_context)
129
+ ...(options.ext || options.workflow_context) && {
130
+ ext: {
131
+ ...options.ext,
132
+ ...options.workflow_context && {
133
+ [WORKFLOW_EXTENSION_KEY]: options.workflow_context
134
+ }
135
+ }
136
+ },
137
+ // Purpose claims (v0.9.24+)
138
+ ...purposeDeclared && { purpose_declared: purposeDeclared },
139
+ ...options.purpose_enforced && { purpose_enforced: options.purpose_enforced },
140
+ ...options.purpose_reason && { purpose_reason: options.purpose_reason }
141
+ };
142
+ try {
143
+ ReceiptClaims.parse(claims);
144
+ } catch (err) {
145
+ if (err instanceof ZodError) {
146
+ const evidenceIssue = err.issues.find(
147
+ (issue2) => issue2.path.some((p) => p === "evidence" || p === "payment")
148
+ );
149
+ if (evidenceIssue && evidenceIssue.path.includes("evidence")) {
150
+ const peacError = createEvidenceNotJsonError(evidenceIssue.message, evidenceIssue.path);
151
+ throw new IssueError(peacError);
152
+ }
153
+ }
154
+ throw err;
155
+ }
156
+ const validatedSnapshot = validateSubjectSnapshot(options.subject_snapshot);
157
+ const startTime = performance.now();
158
+ const jws = await sign(claims, options.privateKey, options.kid);
159
+ fireTelemetryHook(options.telemetry?.onReceiptIssued, {
160
+ receiptHash: hashReceipt(jws),
161
+ issuer: options.iss,
162
+ kid: options.kid,
163
+ durationMs: performance.now() - startTime
164
+ });
165
+ return {
166
+ jws,
167
+ ...validatedSnapshot && { subject_snapshot: validatedSnapshot }
168
+ };
169
+ }
170
+ async function issueJws(options) {
171
+ const result = await issue(options);
172
+ return result.jws;
173
+ }
174
+ var jwksCache = /* @__PURE__ */ new Map();
175
+ var CACHE_TTL_MS = 5 * 60 * 1e3;
176
+ async function fetchJWKS(issuerUrl) {
177
+ if (!issuerUrl.startsWith("https://")) {
178
+ throw new Error("Issuer URL must be https://");
179
+ }
180
+ const discoveryUrl = `${issuerUrl}/.well-known/peac.txt`;
181
+ try {
182
+ const discoveryResp = await fetch(discoveryUrl, {
183
+ headers: { Accept: "text/plain" },
184
+ // Timeout after 5 seconds
185
+ signal: AbortSignal.timeout(5e3)
186
+ });
187
+ if (!discoveryResp.ok) {
188
+ throw new Error(`Discovery fetch failed: ${discoveryResp.status}`);
189
+ }
190
+ const discoveryText = await discoveryResp.text();
191
+ const jwksLine = discoveryText.split("\n").find((line) => line.startsWith("jwks:"));
192
+ if (!jwksLine) {
193
+ throw new Error("No jwks field in discovery");
194
+ }
195
+ const jwksUrl = jwksLine.replace("jwks:", "").trim();
196
+ if (!jwksUrl.startsWith("https://")) {
197
+ throw new Error("JWKS URL must be https://");
198
+ }
199
+ const jwksResp = await fetch(jwksUrl, {
200
+ headers: { Accept: "application/json" },
201
+ signal: AbortSignal.timeout(5e3)
202
+ });
203
+ if (!jwksResp.ok) {
204
+ throw new Error(`JWKS fetch failed: ${jwksResp.status}`);
205
+ }
206
+ const jwks = await jwksResp.json();
207
+ return jwks;
208
+ } catch (err) {
209
+ throw new Error(`JWKS fetch failed: ${err instanceof Error ? err.message : String(err)}`, {
210
+ cause: err
211
+ });
212
+ }
213
+ }
214
+ async function getJWKS(issuerUrl) {
215
+ const now = Date.now();
216
+ const cached = jwksCache.get(issuerUrl);
217
+ if (cached && cached.expiresAt > now) {
218
+ return { jwks: cached.keys, fromCache: true };
219
+ }
220
+ const jwks = await fetchJWKS(issuerUrl);
221
+ jwksCache.set(issuerUrl, {
222
+ keys: jwks,
223
+ expiresAt: now + CACHE_TTL_MS
224
+ });
225
+ return { jwks, fromCache: false };
226
+ }
227
+ function jwkToPublicKey(jwk) {
228
+ if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519") {
229
+ throw new Error("Only Ed25519 keys (OKP/Ed25519) are supported");
230
+ }
231
+ const xBytes = Buffer.from(jwk.x, "base64url");
232
+ if (xBytes.length !== 32) {
233
+ throw new Error("Ed25519 public key must be 32 bytes");
234
+ }
235
+ return new Uint8Array(xBytes);
236
+ }
237
+ async function verifyReceipt(optionsOrJws) {
238
+ const receiptJws = typeof optionsOrJws === "string" ? optionsOrJws : optionsOrJws.receiptJws;
239
+ const inputSnapshot = typeof optionsOrJws === "string" ? void 0 : optionsOrJws.subject_snapshot;
240
+ const telemetry = typeof optionsOrJws === "string" ? void 0 : optionsOrJws.telemetry;
241
+ const startTime = performance.now();
242
+ let jwksFetchTime;
243
+ try {
244
+ const { header, payload } = decode(receiptJws);
245
+ ReceiptClaims.parse(payload);
246
+ if (payload.exp && payload.exp < Math.floor(Date.now() / 1e3)) {
247
+ const durationMs = performance.now() - startTime;
248
+ fireTelemetryHook(telemetry?.onReceiptVerified, {
249
+ receiptHash: hashReceipt(receiptJws),
250
+ valid: false,
251
+ reasonCode: "expired",
252
+ issuer: payload.iss,
253
+ kid: header.kid,
254
+ durationMs
255
+ });
256
+ return {
257
+ ok: false,
258
+ reason: "expired",
259
+ details: `Receipt expired at ${new Date(payload.exp * 1e3).toISOString()}`
260
+ };
261
+ }
262
+ const jwksFetchStart = performance.now();
263
+ const { jwks, fromCache } = await getJWKS(payload.iss);
264
+ if (!fromCache) {
265
+ jwksFetchTime = performance.now() - jwksFetchStart;
266
+ }
267
+ const jwk = jwks.keys.find((k) => k.kid === header.kid);
268
+ if (!jwk) {
269
+ const durationMs = performance.now() - startTime;
270
+ fireTelemetryHook(telemetry?.onReceiptVerified, {
271
+ receiptHash: hashReceipt(receiptJws),
272
+ valid: false,
273
+ reasonCode: "unknown_key",
274
+ issuer: payload.iss,
275
+ kid: header.kid,
276
+ durationMs
277
+ });
278
+ return {
279
+ ok: false,
280
+ reason: "unknown_key",
281
+ details: `No key found with kid=${header.kid}`
282
+ };
283
+ }
284
+ const publicKey = jwkToPublicKey(jwk);
285
+ const result = await verify(receiptJws, publicKey);
286
+ if (!result.valid) {
287
+ const durationMs = performance.now() - startTime;
288
+ fireTelemetryHook(telemetry?.onReceiptVerified, {
289
+ receiptHash: hashReceipt(receiptJws),
290
+ valid: false,
291
+ reasonCode: "invalid_signature",
292
+ issuer: payload.iss,
293
+ kid: header.kid,
294
+ durationMs
295
+ });
296
+ return {
297
+ ok: false,
298
+ reason: "invalid_signature",
299
+ details: "Ed25519 signature verification failed"
300
+ };
301
+ }
302
+ const validatedSnapshot = validateSubjectSnapshot(inputSnapshot);
303
+ const verifyTime = performance.now() - startTime;
304
+ fireTelemetryHook(telemetry?.onReceiptVerified, {
305
+ receiptHash: hashReceipt(receiptJws),
306
+ valid: true,
307
+ issuer: payload.iss,
308
+ kid: header.kid,
309
+ durationMs: verifyTime
310
+ });
311
+ return {
312
+ ok: true,
313
+ claims: payload,
314
+ ...validatedSnapshot && { subject_snapshot: validatedSnapshot },
315
+ perf: {
316
+ verify_ms: verifyTime,
317
+ ...jwksFetchTime && { jwks_fetch_ms: jwksFetchTime }
318
+ }
319
+ };
320
+ } catch (err) {
321
+ const durationMs = performance.now() - startTime;
322
+ fireTelemetryHook(telemetry?.onReceiptVerified, {
323
+ receiptHash: hashReceipt(receiptJws),
324
+ valid: false,
325
+ reasonCode: "verification_error",
326
+ durationMs
327
+ });
328
+ return {
329
+ ok: false,
330
+ reason: "verification_error",
331
+ details: err instanceof Error ? err.message : String(err)
332
+ };
333
+ }
334
+ }
335
+ function isCryptoError(err) {
336
+ return err !== null && typeof err === "object" && "name" in err && err.name === "CryptoError" && "code" in err && typeof err.code === "string" && err.code.startsWith("CRYPTO_") && "message" in err && typeof err.message === "string";
337
+ }
338
+ var FORMAT_ERROR_CODES = /* @__PURE__ */ new Set([
339
+ "CRYPTO_INVALID_JWS_FORMAT",
340
+ "CRYPTO_INVALID_TYP",
341
+ "CRYPTO_INVALID_ALG",
342
+ "CRYPTO_INVALID_KEY_LENGTH"
343
+ ]);
344
+ var MAX_PARSE_ISSUES = 25;
345
+ function sanitizeParseIssues(issues) {
346
+ if (!Array.isArray(issues)) return void 0;
347
+ return issues.slice(0, MAX_PARSE_ISSUES).map((issue2) => ({
348
+ path: Array.isArray(issue2?.path) ? issue2.path.join(".") : "",
349
+ message: typeof issue2?.message === "string" ? issue2.message : String(issue2)
350
+ }));
351
+ }
352
+ async function verifyLocal(jws, publicKey, options = {}) {
353
+ const { issuer, audience, subjectUri, rid, requireExp = false, maxClockSkew = 300 } = options;
354
+ const now = options.now ?? Math.floor(Date.now() / 1e3);
355
+ try {
356
+ const result = await verify(jws, publicKey);
357
+ if (!result.valid) {
358
+ return {
359
+ valid: false,
360
+ code: "E_INVALID_SIGNATURE",
361
+ message: "Ed25519 signature verification failed"
362
+ };
363
+ }
364
+ const pr = parseReceiptClaims(result.payload);
365
+ if (!pr.ok) {
366
+ return {
367
+ valid: false,
368
+ code: "E_INVALID_FORMAT",
369
+ message: `Receipt schema validation failed: ${pr.error.message}`,
370
+ details: { parse_code: pr.error.code, issues: sanitizeParseIssues(pr.error.issues) }
371
+ };
372
+ }
373
+ if (issuer !== void 0 && pr.claims.iss !== issuer) {
374
+ return {
375
+ valid: false,
376
+ code: "E_INVALID_ISSUER",
377
+ message: `Issuer mismatch: expected "${issuer}", got "${pr.claims.iss}"`
378
+ };
379
+ }
380
+ if (audience !== void 0 && pr.claims.aud !== audience) {
381
+ return {
382
+ valid: false,
383
+ code: "E_INVALID_AUDIENCE",
384
+ message: `Audience mismatch: expected "${audience}", got "${pr.claims.aud}"`
385
+ };
386
+ }
387
+ if (rid !== void 0 && pr.claims.rid !== rid) {
388
+ return {
389
+ valid: false,
390
+ code: "E_INVALID_RECEIPT_ID",
391
+ message: `Receipt ID mismatch: expected "${rid}", got "${pr.claims.rid}"`
392
+ };
393
+ }
394
+ if (requireExp && pr.claims.exp === void 0) {
395
+ return {
396
+ valid: false,
397
+ code: "E_MISSING_EXP",
398
+ message: "Receipt missing required exp claim"
399
+ };
400
+ }
401
+ if (pr.claims.iat > now + maxClockSkew) {
402
+ return {
403
+ valid: false,
404
+ code: "E_NOT_YET_VALID",
405
+ message: `Receipt not yet valid: issued at ${new Date(pr.claims.iat * 1e3).toISOString()}, now is ${new Date(now * 1e3).toISOString()}`
406
+ };
407
+ }
408
+ if (pr.claims.exp !== void 0 && pr.claims.exp < now - maxClockSkew) {
409
+ return {
410
+ valid: false,
411
+ code: "E_EXPIRED",
412
+ message: `Receipt expired at ${new Date(pr.claims.exp * 1e3).toISOString()}`
413
+ };
414
+ }
415
+ if (pr.variant === "commerce") {
416
+ const claims = pr.claims;
417
+ if (subjectUri !== void 0 && claims.subject?.uri !== subjectUri) {
418
+ return {
419
+ valid: false,
420
+ code: "E_INVALID_SUBJECT",
421
+ message: `Subject mismatch: expected "${subjectUri}", got "${claims.subject?.uri ?? "undefined"}"`
422
+ };
423
+ }
424
+ return {
425
+ valid: true,
426
+ variant: "commerce",
427
+ claims,
428
+ kid: result.header.kid,
429
+ policy_binding: "unavailable"
430
+ };
431
+ } else {
432
+ const claims = pr.claims;
433
+ if (subjectUri !== void 0 && claims.sub !== subjectUri) {
434
+ return {
435
+ valid: false,
436
+ code: "E_INVALID_SUBJECT",
437
+ message: `Subject mismatch: expected "${subjectUri}", got "${claims.sub ?? "undefined"}"`
438
+ };
439
+ }
440
+ return {
441
+ valid: true,
442
+ variant: "attestation",
443
+ claims,
444
+ kid: result.header.kid,
445
+ policy_binding: "unavailable"
446
+ };
447
+ }
448
+ } catch (err) {
449
+ if (isCryptoError(err)) {
450
+ if (FORMAT_ERROR_CODES.has(err.code)) {
451
+ return {
452
+ valid: false,
453
+ code: "E_INVALID_FORMAT",
454
+ message: err.message
455
+ };
456
+ }
457
+ if (err.code === "CRYPTO_INVALID_SIGNATURE") {
458
+ return {
459
+ valid: false,
460
+ code: "E_INVALID_SIGNATURE",
461
+ message: err.message
462
+ };
463
+ }
464
+ }
465
+ if (err !== null && typeof err === "object" && "name" in err && err.name === "SyntaxError") {
466
+ const syntaxMessage = "message" in err && typeof err.message === "string" ? err.message : "Invalid JSON";
467
+ return {
468
+ valid: false,
469
+ code: "E_INVALID_FORMAT",
470
+ message: `Invalid receipt payload: ${syntaxMessage}`
471
+ };
472
+ }
473
+ const message = err instanceof Error ? err.message : String(err);
474
+ return {
475
+ valid: false,
476
+ code: "E_INTERNAL",
477
+ message: `Unexpected verification error: ${message}`
478
+ };
479
+ }
480
+ }
481
+ function isCommerceResult(r) {
482
+ return r.valid === true && r.variant === "commerce";
483
+ }
484
+ function isAttestationResult(r) {
485
+ return r.valid === true && r.variant === "attestation";
486
+ }
487
+ function setReceiptHeader(headers, receiptJws) {
488
+ headers.set(PEAC_RECEIPT_HEADER, receiptJws);
489
+ }
490
+ function getReceiptHeader(headers) {
491
+ return headers.get(PEAC_RECEIPT_HEADER);
492
+ }
493
+ function setVaryHeader(headers) {
494
+ const existing = headers.get("Vary");
495
+ if (existing) {
496
+ const varies = existing.split(",").map((v) => v.trim());
497
+ if (!varies.includes(PEAC_RECEIPT_HEADER)) {
498
+ headers.set("Vary", `${existing}, ${PEAC_RECEIPT_HEADER}`);
499
+ }
500
+ } else {
501
+ headers.set("Vary", PEAC_RECEIPT_HEADER);
502
+ }
503
+ }
504
+ function getPurposeHeader(headers) {
505
+ const value = headers.get(PEAC_PURPOSE_HEADER);
506
+ if (!value) {
507
+ return [];
508
+ }
509
+ return parsePurposeHeader(value);
510
+ }
511
+ function setPurposeAppliedHeader(headers, purpose) {
512
+ headers.set(PEAC_PURPOSE_APPLIED_HEADER, purpose);
513
+ }
514
+ function setPurposeReasonHeader(headers, reason) {
515
+ headers.set(PEAC_PURPOSE_REASON_HEADER, reason);
516
+ }
517
+ function setVaryPurposeHeader(headers) {
518
+ const existing = headers.get("Vary");
519
+ if (existing) {
520
+ const varies = existing.split(",").map((v) => v.trim());
521
+ if (!varies.includes(PEAC_PURPOSE_HEADER)) {
522
+ headers.set("Vary", `${existing}, ${PEAC_PURPOSE_HEADER}`);
523
+ }
524
+ } else {
525
+ headers.set("Vary", PEAC_PURPOSE_HEADER);
526
+ }
527
+ }
528
+ function parseIssuerConfig(json) {
529
+ let config;
530
+ if (typeof json === "string") {
531
+ const bytes = new TextEncoder().encode(json).length;
532
+ if (bytes > PEAC_ISSUER_CONFIG_MAX_BYTES) {
533
+ throw new Error(`Issuer config exceeds ${PEAC_ISSUER_CONFIG_MAX_BYTES} bytes (got ${bytes})`);
534
+ }
535
+ try {
536
+ config = JSON.parse(json);
537
+ } catch {
538
+ throw new Error("Issuer config is not valid JSON");
539
+ }
540
+ } else {
541
+ config = json;
542
+ }
543
+ if (typeof config !== "object" || config === null) {
544
+ throw new Error("Issuer config must be an object");
545
+ }
546
+ const obj = config;
547
+ if (typeof obj.version !== "string" || !obj.version) {
548
+ throw new Error("Missing required field: version");
549
+ }
550
+ if (typeof obj.issuer !== "string" || !obj.issuer) {
551
+ throw new Error("Missing required field: issuer");
552
+ }
553
+ if (typeof obj.jwks_uri !== "string" || !obj.jwks_uri) {
554
+ throw new Error("Missing required field: jwks_uri");
555
+ }
556
+ if (!obj.issuer.startsWith("https://")) {
557
+ throw new Error("issuer must be an HTTPS URL");
558
+ }
559
+ if (!obj.jwks_uri.startsWith("https://")) {
560
+ throw new Error("jwks_uri must be an HTTPS URL");
561
+ }
562
+ if (obj.verify_endpoint !== void 0) {
563
+ if (typeof obj.verify_endpoint !== "string") {
564
+ throw new Error("verify_endpoint must be a string");
565
+ }
566
+ if (!obj.verify_endpoint.startsWith("https://")) {
567
+ throw new Error("verify_endpoint must be an HTTPS URL");
568
+ }
569
+ }
570
+ if (obj.receipt_versions !== void 0) {
571
+ if (!Array.isArray(obj.receipt_versions)) {
572
+ throw new Error("receipt_versions must be an array");
573
+ }
574
+ }
575
+ if (obj.algorithms !== void 0) {
576
+ if (!Array.isArray(obj.algorithms)) {
577
+ throw new Error("algorithms must be an array");
578
+ }
579
+ }
580
+ if (obj.payment_rails !== void 0) {
581
+ if (!Array.isArray(obj.payment_rails)) {
582
+ throw new Error("payment_rails must be an array");
583
+ }
584
+ }
585
+ return {
586
+ version: obj.version,
587
+ issuer: obj.issuer,
588
+ jwks_uri: obj.jwks_uri,
589
+ verify_endpoint: obj.verify_endpoint,
590
+ receipt_versions: obj.receipt_versions,
591
+ algorithms: obj.algorithms,
592
+ payment_rails: obj.payment_rails,
593
+ security_contact: obj.security_contact
594
+ };
595
+ }
596
+ async function fetchIssuerConfig(issuerUrl) {
597
+ if (!issuerUrl.startsWith("https://")) {
598
+ throw new Error("Issuer URL must be https://");
599
+ }
600
+ const baseUrl = issuerUrl.replace(/\/$/, "");
601
+ const configUrl = `${baseUrl}${PEAC_ISSUER_CONFIG_PATH}`;
602
+ try {
603
+ const resp = await fetch(configUrl, {
604
+ headers: { Accept: "application/json" },
605
+ signal: AbortSignal.timeout(1e4)
606
+ });
607
+ if (!resp.ok) {
608
+ throw new Error(`Issuer config fetch failed: ${resp.status}`);
609
+ }
610
+ const text = await resp.text();
611
+ const config = parseIssuerConfig(text);
612
+ const normalizedExpected = baseUrl.replace(/\/$/, "");
613
+ const normalizedActual = config.issuer.replace(/\/$/, "");
614
+ if (normalizedActual !== normalizedExpected) {
615
+ throw new Error(`Issuer mismatch: expected ${normalizedExpected}, got ${normalizedActual}`);
616
+ }
617
+ return config;
618
+ } catch (err) {
619
+ throw new Error(
620
+ `Failed to fetch issuer config from ${issuerUrl}: ${err instanceof Error ? err.message : String(err)}`,
621
+ { cause: err }
622
+ );
623
+ }
624
+ }
625
+ function isJsonContent(text, contentType) {
626
+ if (contentType?.includes("application/json")) {
627
+ return true;
628
+ }
629
+ const firstChar = text.trimStart()[0];
630
+ return firstChar === "{";
631
+ }
632
+ function parsePolicyManifest(text, contentType) {
633
+ const bytes = new TextEncoder().encode(text).length;
634
+ if (bytes > PEAC_POLICY_MAX_BYTES) {
635
+ throw new Error(`Policy manifest exceeds ${PEAC_POLICY_MAX_BYTES} bytes (got ${bytes})`);
636
+ }
637
+ let manifest;
638
+ if (isJsonContent(text, contentType)) {
639
+ try {
640
+ manifest = JSON.parse(text);
641
+ } catch {
642
+ throw new Error("Policy manifest is not valid JSON");
643
+ }
644
+ } else {
645
+ manifest = parseSimpleYaml(text);
646
+ }
647
+ if (typeof manifest.version !== "string" || !manifest.version) {
648
+ throw new Error("Missing required field: version");
649
+ }
650
+ if (!manifest.version.startsWith("peac-policy/")) {
651
+ throw new Error(
652
+ `Invalid version format: "${manifest.version}". Must start with "peac-policy/" (e.g., "peac-policy/0.1")`
653
+ );
654
+ }
655
+ if (manifest.usage !== "open" && manifest.usage !== "conditional") {
656
+ throw new Error('Missing or invalid field: usage (must be "open" or "conditional")');
657
+ }
658
+ return {
659
+ version: manifest.version,
660
+ usage: manifest.usage,
661
+ purposes: manifest.purposes,
662
+ receipts: manifest.receipts,
663
+ attribution: manifest.attribution,
664
+ rate_limit: manifest.rate_limit,
665
+ daily_limit: manifest.daily_limit,
666
+ negotiate: manifest.negotiate,
667
+ contact: manifest.contact,
668
+ license: manifest.license,
669
+ price: manifest.price,
670
+ currency: manifest.currency,
671
+ payment_methods: manifest.payment_methods,
672
+ payment_endpoint: manifest.payment_endpoint
673
+ };
674
+ }
675
+ function parseSimpleYaml(text) {
676
+ const lines = text.split("\n");
677
+ const result = {};
678
+ if (text.includes("<<:")) {
679
+ throw new Error("YAML merge keys are not allowed");
680
+ }
681
+ if (text.includes("&") || text.includes("*")) {
682
+ throw new Error("YAML anchors and aliases are not allowed");
683
+ }
684
+ if (/!\w+/.test(text)) {
685
+ throw new Error("YAML custom tags are not allowed");
686
+ }
687
+ const docSeparators = text.match(/^---$/gm);
688
+ if (docSeparators && docSeparators.length > 1) {
689
+ throw new Error("Multi-document YAML is not allowed");
690
+ }
691
+ for (const line of lines) {
692
+ const trimmed = line.trim();
693
+ if (!trimmed || trimmed.startsWith("#") || trimmed === "---") {
694
+ continue;
695
+ }
696
+ const colonIndex = trimmed.indexOf(":");
697
+ if (colonIndex === -1) continue;
698
+ const key = trimmed.slice(0, colonIndex).trim();
699
+ let value = trimmed.slice(colonIndex + 1).trim();
700
+ if (value === "") {
701
+ value = void 0;
702
+ } else if (typeof value === "string") {
703
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
704
+ value = value.slice(1, -1);
705
+ } else if (value.startsWith("[") && value.endsWith("]")) {
706
+ const inner = value.slice(1, -1);
707
+ value = inner.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
708
+ } else if (/^-?\d+(\.\d+)?$/.test(value)) {
709
+ value = parseFloat(value);
710
+ } else if (value === "true") {
711
+ value = true;
712
+ } else if (value === "false") {
713
+ value = false;
714
+ }
715
+ }
716
+ if (value !== void 0) {
717
+ result[key] = value;
718
+ }
719
+ }
720
+ return result;
721
+ }
722
+ async function fetchPolicyManifest(baseUrl) {
723
+ if (!baseUrl.startsWith("https://") && !baseUrl.startsWith("http://localhost")) {
724
+ throw new Error("Base URL must be https://");
725
+ }
726
+ const normalizedBase = baseUrl.replace(/\/$/, "");
727
+ const primaryUrl = `${normalizedBase}${PEAC_POLICY_PATH}`;
728
+ const fallbackUrl = `${normalizedBase}${PEAC_POLICY_FALLBACK_PATH}`;
729
+ try {
730
+ const resp = await fetch(primaryUrl, {
731
+ headers: { Accept: "text/plain, application/json" },
732
+ signal: AbortSignal.timeout(5e3)
733
+ });
734
+ if (resp.ok) {
735
+ const text = await resp.text();
736
+ const contentType = resp.headers.get("content-type") || void 0;
737
+ return parsePolicyManifest(text, contentType);
738
+ }
739
+ if (resp.status === 404) {
740
+ const fallbackResp = await fetch(fallbackUrl, {
741
+ headers: { Accept: "text/plain, application/json" },
742
+ signal: AbortSignal.timeout(5e3)
743
+ });
744
+ if (fallbackResp.ok) {
745
+ const text = await fallbackResp.text();
746
+ const contentType = fallbackResp.headers.get("content-type") || void 0;
747
+ return parsePolicyManifest(text, contentType);
748
+ }
749
+ throw new Error("Policy manifest not found at primary or fallback location");
750
+ }
751
+ throw new Error(`Policy manifest fetch failed: ${resp.status}`);
752
+ } catch (err) {
753
+ throw new Error(
754
+ `Failed to fetch policy manifest from ${baseUrl}: ${err instanceof Error ? err.message : String(err)}`,
755
+ { cause: err }
756
+ );
757
+ }
758
+ }
759
+ function parseDiscovery(text) {
760
+ const bytes = new TextEncoder().encode(text).length;
761
+ if (bytes > 2e3) {
762
+ throw new Error(`Discovery manifest exceeds 2000 bytes (got ${bytes})`);
763
+ }
764
+ const lines = text.trim().split("\n");
765
+ if (lines.length > 20) {
766
+ throw new Error(`Discovery manifest exceeds 20 lines (got ${lines.length})`);
767
+ }
768
+ const discovery = {};
769
+ for (const line of lines) {
770
+ const trimmed = line.trim();
771
+ if (!trimmed || trimmed.startsWith("#")) {
772
+ continue;
773
+ }
774
+ if (trimmed.includes(":")) {
775
+ const [key, ...valueParts] = trimmed.split(":");
776
+ const value = valueParts.join(":").trim();
777
+ switch (key.trim()) {
778
+ case "version":
779
+ discovery.version = value;
780
+ break;
781
+ case "issuer":
782
+ discovery.issuer = value;
783
+ break;
784
+ case "verify":
785
+ discovery.verify_endpoint = value;
786
+ break;
787
+ case "jwks":
788
+ discovery.jwks_uri = value;
789
+ break;
790
+ case "security":
791
+ discovery.security_contact = value;
792
+ break;
793
+ }
794
+ }
795
+ }
796
+ if (!discovery.version) throw new Error("Missing required field: version");
797
+ if (!discovery.issuer) throw new Error("Missing required field: issuer");
798
+ if (!discovery.verify_endpoint) throw new Error("Missing required field: verify");
799
+ if (!discovery.jwks_uri) throw new Error("Missing required field: jwks");
800
+ return discovery;
801
+ }
802
+ async function fetchDiscovery(issuerUrl) {
803
+ if (!issuerUrl.startsWith("https://")) {
804
+ throw new Error("Issuer URL must be https://");
805
+ }
806
+ const discoveryUrl = `${issuerUrl}/.well-known/peac.txt`;
807
+ try {
808
+ const resp = await fetch(discoveryUrl, {
809
+ headers: { Accept: "text/plain" },
810
+ signal: AbortSignal.timeout(5e3)
811
+ });
812
+ if (!resp.ok) {
813
+ throw new Error(`Discovery fetch failed: ${resp.status}`);
814
+ }
815
+ const text = await resp.text();
816
+ return parseDiscovery(text);
817
+ } catch (err) {
818
+ throw new Error(
819
+ `Failed to fetch discovery from ${issuerUrl}: ${err instanceof Error ? err.message : String(err)}`,
820
+ { cause: err }
821
+ );
822
+ }
823
+ }
824
+ var DEFAULT_VERIFIER_LIMITS = {
825
+ max_receipt_bytes: VERIFIER_LIMITS.maxReceiptBytes,
826
+ max_jwks_bytes: VERIFIER_LIMITS.maxJwksBytes,
827
+ max_jwks_keys: VERIFIER_LIMITS.maxJwksKeys,
828
+ max_redirects: VERIFIER_LIMITS.maxRedirects,
829
+ fetch_timeout_ms: VERIFIER_LIMITS.fetchTimeoutMs,
830
+ max_extension_bytes: VERIFIER_LIMITS.maxExtensionBytes
831
+ };
832
+ var DEFAULT_NETWORK_SECURITY = {
833
+ https_only: VERIFIER_NETWORK.httpsOnly,
834
+ block_private_ips: VERIFIER_NETWORK.blockPrivateIps,
835
+ allow_redirects: VERIFIER_NETWORK.allowRedirects,
836
+ allow_cross_origin_redirects: true,
837
+ // Allow for CDN compatibility
838
+ dns_failure_behavior: "block"
839
+ // Fail-closed by default
840
+ };
841
+ function createDefaultPolicy(mode) {
842
+ return {
843
+ policy_version: VERIFIER_POLICY_VERSION,
844
+ mode,
845
+ limits: { ...DEFAULT_VERIFIER_LIMITS },
846
+ network: { ...DEFAULT_NETWORK_SECURITY }
847
+ };
848
+ }
849
+ var CHECK_IDS = [
850
+ "jws.parse",
851
+ "limits.receipt_bytes",
852
+ "jws.protected_header",
853
+ "claims.schema_unverified",
854
+ "issuer.trust_policy",
855
+ "issuer.discovery",
856
+ "key.resolve",
857
+ "jws.signature",
858
+ "claims.time_window",
859
+ "extensions.limits",
860
+ "transport.profile_binding",
861
+ "policy.binding"
862
+ ];
863
+ var NON_DETERMINISTIC_ARTIFACT_KEYS = [
864
+ "issuer_jwks_digest"
865
+ ];
866
+ function createDigest(hexValue) {
867
+ return {
868
+ alg: "sha-256",
869
+ value: hexValue.toLowerCase()
870
+ };
871
+ }
872
+ function createEmptyReport(policy) {
873
+ return {
874
+ report_version: VERIFICATION_REPORT_VERSION,
875
+ policy
876
+ };
877
+ }
878
+ function ssrfErrorToReasonCode(ssrfReason, fetchType) {
879
+ const prefix = fetchType === "key" ? "key_fetch" : "pointer_fetch";
880
+ switch (ssrfReason) {
881
+ case "not_https":
882
+ case "private_ip":
883
+ case "loopback":
884
+ case "link_local":
885
+ case "cross_origin_redirect":
886
+ case "dns_failure":
887
+ return `${prefix}_blocked`;
888
+ case "timeout":
889
+ return `${prefix}_timeout`;
890
+ case "response_too_large":
891
+ return fetchType === "pointer" ? "pointer_fetch_too_large" : "jwks_too_large";
892
+ case "jwks_too_many_keys":
893
+ return "jwks_too_many_keys";
894
+ case "too_many_redirects":
895
+ case "scheme_downgrade":
896
+ case "network_error":
897
+ case "invalid_url":
898
+ default:
899
+ return `${prefix}_failed`;
900
+ }
901
+ }
902
+ function reasonCodeToSeverity(reason) {
903
+ if (reason === "ok") return "info";
904
+ return "error";
905
+ }
906
+ function reasonCodeToErrorCode(reason) {
907
+ const mapping = {
908
+ ok: "",
909
+ receipt_too_large: "E_VERIFY_RECEIPT_TOO_LARGE",
910
+ malformed_receipt: "E_VERIFY_MALFORMED_RECEIPT",
911
+ signature_invalid: "E_VERIFY_SIGNATURE_INVALID",
912
+ issuer_not_allowed: "E_VERIFY_ISSUER_NOT_ALLOWED",
913
+ key_not_found: "E_VERIFY_KEY_NOT_FOUND",
914
+ key_fetch_blocked: "E_VERIFY_KEY_FETCH_BLOCKED",
915
+ key_fetch_failed: "E_VERIFY_KEY_FETCH_FAILED",
916
+ key_fetch_timeout: "E_VERIFY_KEY_FETCH_TIMEOUT",
917
+ pointer_fetch_blocked: "E_VERIFY_POINTER_FETCH_BLOCKED",
918
+ pointer_fetch_failed: "E_VERIFY_POINTER_FETCH_FAILED",
919
+ pointer_fetch_timeout: "E_VERIFY_POINTER_FETCH_TIMEOUT",
920
+ pointer_fetch_too_large: "E_VERIFY_POINTER_FETCH_TOO_LARGE",
921
+ pointer_digest_mismatch: "E_VERIFY_POINTER_DIGEST_MISMATCH",
922
+ jwks_too_large: "E_VERIFY_JWKS_TOO_LARGE",
923
+ jwks_too_many_keys: "E_VERIFY_JWKS_TOO_MANY_KEYS",
924
+ expired: "E_VERIFY_EXPIRED",
925
+ not_yet_valid: "E_VERIFY_NOT_YET_VALID",
926
+ audience_mismatch: "E_VERIFY_AUDIENCE_MISMATCH",
927
+ schema_invalid: "E_VERIFY_SCHEMA_INVALID",
928
+ policy_violation: "E_VERIFY_POLICY_VIOLATION",
929
+ extension_too_large: "E_VERIFY_EXTENSION_TOO_LARGE",
930
+ invalid_transport: "E_VERIFY_INVALID_TRANSPORT"
931
+ };
932
+ return mapping[reason] || "E_VERIFY_POLICY_VIOLATION";
933
+ }
934
+ var cachedCapabilities = null;
935
+ function getSSRFCapabilities() {
936
+ if (cachedCapabilities) {
937
+ return cachedCapabilities;
938
+ }
939
+ cachedCapabilities = detectCapabilities();
940
+ return cachedCapabilities;
941
+ }
942
+ function detectCapabilities() {
943
+ if (typeof process !== "undefined" && process.versions?.node) {
944
+ return {
945
+ runtime: "node",
946
+ dnsPreResolution: true,
947
+ ipBlocking: true,
948
+ networkIsolation: false,
949
+ protectionLevel: "full",
950
+ notes: [
951
+ "Full SSRF protection available via Node.js dns module",
952
+ "DNS resolution checked before HTTP connection",
953
+ "All RFC 1918 private ranges blocked"
954
+ ]
955
+ };
956
+ }
957
+ if (typeof process !== "undefined" && process.versions?.bun) {
958
+ return {
959
+ runtime: "bun",
960
+ dnsPreResolution: true,
961
+ ipBlocking: true,
962
+ networkIsolation: false,
963
+ protectionLevel: "full",
964
+ notes: [
965
+ "Full SSRF protection available via Bun dns compatibility",
966
+ "DNS resolution checked before HTTP connection"
967
+ ]
968
+ };
969
+ }
970
+ if (typeof globalThis !== "undefined" && "Deno" in globalThis) {
971
+ return {
972
+ runtime: "deno",
973
+ dnsPreResolution: false,
974
+ ipBlocking: false,
975
+ networkIsolation: false,
976
+ protectionLevel: "partial",
977
+ notes: [
978
+ "DNS pre-resolution not available in Deno by default",
979
+ "SSRF protection limited to URL validation and response limits",
980
+ "Consider using Deno.connect with hostname resolution for enhanced protection"
981
+ ]
982
+ };
983
+ }
984
+ if (typeof globalThis !== "undefined" && typeof globalThis.caches !== "undefined" && typeof globalThis.HTMLRewriter !== "undefined") {
985
+ return {
986
+ runtime: "cloudflare-workers",
987
+ dnsPreResolution: false,
988
+ ipBlocking: false,
989
+ networkIsolation: true,
990
+ protectionLevel: "partial",
991
+ notes: [
992
+ "Cloudflare Workers provide network-level isolation",
993
+ "DNS pre-resolution not available in Workers runtime",
994
+ "CF network blocks many SSRF vectors at infrastructure level",
995
+ "SSRF protection supplemented by URL validation and response limits"
996
+ ]
997
+ };
998
+ }
999
+ const g = globalThis;
1000
+ if (typeof g.window !== "undefined" || typeof g.document !== "undefined") {
1001
+ return {
1002
+ runtime: "browser",
1003
+ dnsPreResolution: false,
1004
+ ipBlocking: false,
1005
+ networkIsolation: false,
1006
+ protectionLevel: "minimal",
1007
+ notes: [
1008
+ "Browser environment detected; DNS pre-resolution not available",
1009
+ "SSRF protection limited to URL scheme validation",
1010
+ "Consider validating URLs server-side before browser fetch",
1011
+ "Same-origin policy provides some protection against SSRF"
1012
+ ]
1013
+ };
1014
+ }
1015
+ return {
1016
+ runtime: "edge-generic",
1017
+ dnsPreResolution: false,
1018
+ ipBlocking: false,
1019
+ networkIsolation: false,
1020
+ protectionLevel: "partial",
1021
+ notes: [
1022
+ "Edge runtime detected; DNS pre-resolution may not be available",
1023
+ "SSRF protection limited to URL validation and response limits",
1024
+ "Verify runtime provides additional network-level protections"
1025
+ ]
1026
+ };
1027
+ }
1028
+ function resetSSRFCapabilitiesCache() {
1029
+ cachedCapabilities = null;
1030
+ }
1031
+ function parseIPv4(ip) {
1032
+ const parts = ip.split(".");
1033
+ if (parts.length !== 4) return null;
1034
+ const octets = [];
1035
+ for (const part of parts) {
1036
+ const num = parseInt(part, 10);
1037
+ if (isNaN(num) || num < 0 || num > 255) return null;
1038
+ octets.push(num);
1039
+ }
1040
+ return { octets };
1041
+ }
1042
+ function isInCIDR(ip, cidr) {
1043
+ const [rangeStr, maskStr] = cidr.split("/");
1044
+ const range = parseIPv4(rangeStr);
1045
+ if (!range) return false;
1046
+ const maskBits = parseInt(maskStr, 10);
1047
+ if (isNaN(maskBits) || maskBits < 0 || maskBits > 32) return false;
1048
+ const ipNum = ip.octets[0] << 24 | ip.octets[1] << 16 | ip.octets[2] << 8 | ip.octets[3];
1049
+ const rangeNum = range.octets[0] << 24 | range.octets[1] << 16 | range.octets[2] << 8 | range.octets[3];
1050
+ const mask = maskBits === 0 ? 0 : ~((1 << 32 - maskBits) - 1);
1051
+ return (ipNum & mask) === (rangeNum & mask);
1052
+ }
1053
+ function isIPv6Loopback(ip) {
1054
+ const normalized = ip.toLowerCase().replace(/^::ffff:/, "");
1055
+ return normalized === "::1" || normalized === "0:0:0:0:0:0:0:1";
1056
+ }
1057
+ function isIPv6LinkLocal(ip) {
1058
+ const normalized = ip.toLowerCase();
1059
+ return normalized.startsWith("fe8") || normalized.startsWith("fe9") || normalized.startsWith("fea") || normalized.startsWith("feb");
1060
+ }
1061
+ function isBlockedIP(ip) {
1062
+ const ipv4Match = ip.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);
1063
+ const effectiveIP = ipv4Match ? ipv4Match[1] : ip;
1064
+ const ipv4 = parseIPv4(effectiveIP);
1065
+ if (ipv4) {
1066
+ if (isInCIDR(ipv4, "10.0.0.0/8") || isInCIDR(ipv4, "172.16.0.0/12") || isInCIDR(ipv4, "192.168.0.0/16")) {
1067
+ return { blocked: true, reason: "private_ip" };
1068
+ }
1069
+ if (isInCIDR(ipv4, "127.0.0.0/8")) {
1070
+ return { blocked: true, reason: "loopback" };
1071
+ }
1072
+ if (isInCIDR(ipv4, "169.254.0.0/16")) {
1073
+ return { blocked: true, reason: "link_local" };
1074
+ }
1075
+ return { blocked: false };
1076
+ }
1077
+ if (isIPv6Loopback(ip)) {
1078
+ return { blocked: true, reason: "loopback" };
1079
+ }
1080
+ if (isIPv6LinkLocal(ip)) {
1081
+ return { blocked: true, reason: "link_local" };
1082
+ }
1083
+ return { blocked: false };
1084
+ }
1085
+ async function resolveHostname(hostname) {
1086
+ if (typeof process !== "undefined" && process.versions?.node) {
1087
+ try {
1088
+ const dns = await import('dns');
1089
+ const { promisify } = await import('util');
1090
+ const resolve4 = promisify(dns.resolve4);
1091
+ const resolve6 = promisify(dns.resolve6);
1092
+ const results = [];
1093
+ let ipv4Error = null;
1094
+ let ipv6Error = null;
1095
+ try {
1096
+ const ipv4 = await resolve4(hostname);
1097
+ results.push(...ipv4);
1098
+ } catch (err) {
1099
+ ipv4Error = err;
1100
+ }
1101
+ try {
1102
+ const ipv6 = await resolve6(hostname);
1103
+ results.push(...ipv6);
1104
+ } catch (err) {
1105
+ ipv6Error = err;
1106
+ }
1107
+ if (results.length > 0) {
1108
+ return { ok: true, ips: results, browser: false };
1109
+ }
1110
+ if (ipv4Error && ipv6Error) {
1111
+ return {
1112
+ ok: false,
1113
+ message: `DNS resolution failed for ${hostname}: ${ipv4Error.message}`
1114
+ };
1115
+ }
1116
+ return { ok: true, ips: [], browser: false };
1117
+ } catch (err) {
1118
+ return {
1119
+ ok: false,
1120
+ message: `DNS resolution error: ${err instanceof Error ? err.message : String(err)}`
1121
+ };
1122
+ }
1123
+ }
1124
+ return { ok: true, ips: [], browser: true };
1125
+ }
1126
+ async function ssrfSafeFetch(url, options = {}) {
1127
+ const {
1128
+ timeoutMs = VERIFIER_LIMITS.fetchTimeoutMs,
1129
+ maxBytes = VERIFIER_LIMITS.maxResponseBytes,
1130
+ maxRedirects = 0,
1131
+ allowRedirects = VERIFIER_NETWORK.allowRedirects,
1132
+ allowCrossOriginRedirects = true,
1133
+ // Default: allow for CDN compatibility
1134
+ dnsFailureBehavior = "block",
1135
+ // Default: fail-closed for security
1136
+ headers = {}
1137
+ } = options;
1138
+ let parsedUrl;
1139
+ try {
1140
+ parsedUrl = new URL(url);
1141
+ } catch {
1142
+ return {
1143
+ ok: false,
1144
+ reason: "invalid_url",
1145
+ message: `Invalid URL: ${url}`,
1146
+ blockedUrl: url
1147
+ };
1148
+ }
1149
+ if (parsedUrl.protocol !== "https:") {
1150
+ return {
1151
+ ok: false,
1152
+ reason: "not_https",
1153
+ message: `URL must use HTTPS: ${url}`,
1154
+ blockedUrl: url
1155
+ };
1156
+ }
1157
+ const dnsResult = await resolveHostname(parsedUrl.hostname);
1158
+ if (!dnsResult.ok) {
1159
+ if (dnsFailureBehavior === "block") {
1160
+ return {
1161
+ ok: false,
1162
+ reason: "dns_failure",
1163
+ message: `DNS resolution blocked: ${dnsResult.message}`,
1164
+ blockedUrl: url
1165
+ };
1166
+ }
1167
+ return {
1168
+ ok: false,
1169
+ reason: "network_error",
1170
+ message: dnsResult.message,
1171
+ blockedUrl: url
1172
+ };
1173
+ }
1174
+ if (!dnsResult.browser) {
1175
+ for (const ip of dnsResult.ips) {
1176
+ const blockResult = isBlockedIP(ip);
1177
+ if (blockResult.blocked) {
1178
+ return {
1179
+ ok: false,
1180
+ reason: blockResult.reason,
1181
+ message: `Blocked ${blockResult.reason} address: ${ip} for ${url}`,
1182
+ blockedUrl: url
1183
+ };
1184
+ }
1185
+ }
1186
+ }
1187
+ let redirectCount = 0;
1188
+ let currentUrl = url;
1189
+ const originalOrigin = parsedUrl.origin;
1190
+ while (true) {
1191
+ try {
1192
+ const controller = new AbortController();
1193
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
1194
+ const response = await fetch(currentUrl, {
1195
+ headers: {
1196
+ Accept: "application/json, text/plain",
1197
+ ...headers
1198
+ },
1199
+ signal: controller.signal,
1200
+ redirect: "manual"
1201
+ // Handle redirects manually for security
1202
+ });
1203
+ clearTimeout(timeoutId);
1204
+ if (response.status >= 300 && response.status < 400) {
1205
+ const location = response.headers.get("location");
1206
+ if (!location) {
1207
+ return {
1208
+ ok: false,
1209
+ reason: "network_error",
1210
+ message: `Redirect without Location header from ${currentUrl}`
1211
+ };
1212
+ }
1213
+ if (!allowRedirects) {
1214
+ return {
1215
+ ok: false,
1216
+ reason: "too_many_redirects",
1217
+ message: `Redirects not allowed: ${currentUrl} -> ${location}`,
1218
+ blockedUrl: location
1219
+ };
1220
+ }
1221
+ redirectCount++;
1222
+ if (redirectCount > maxRedirects) {
1223
+ return {
1224
+ ok: false,
1225
+ reason: "too_many_redirects",
1226
+ message: `Too many redirects (${redirectCount} > ${maxRedirects})`,
1227
+ blockedUrl: location
1228
+ };
1229
+ }
1230
+ let redirectUrl;
1231
+ try {
1232
+ redirectUrl = new URL(location, currentUrl);
1233
+ } catch {
1234
+ return {
1235
+ ok: false,
1236
+ reason: "invalid_url",
1237
+ message: `Invalid redirect URL: ${location}`,
1238
+ blockedUrl: location
1239
+ };
1240
+ }
1241
+ if (redirectUrl.protocol !== "https:") {
1242
+ return {
1243
+ ok: false,
1244
+ reason: "scheme_downgrade",
1245
+ message: `HTTPS to HTTP downgrade not allowed: ${currentUrl} -> ${redirectUrl.href}`,
1246
+ blockedUrl: redirectUrl.href
1247
+ };
1248
+ }
1249
+ if (redirectUrl.origin !== originalOrigin && !allowCrossOriginRedirects) {
1250
+ return {
1251
+ ok: false,
1252
+ reason: "cross_origin_redirect",
1253
+ message: `Cross-origin redirect not allowed: ${originalOrigin} -> ${redirectUrl.origin}`,
1254
+ blockedUrl: redirectUrl.href
1255
+ };
1256
+ }
1257
+ const redirectDnsResult = await resolveHostname(redirectUrl.hostname);
1258
+ if (!redirectDnsResult.ok) {
1259
+ if (dnsFailureBehavior === "block") {
1260
+ return {
1261
+ ok: false,
1262
+ reason: "dns_failure",
1263
+ message: `Redirect DNS resolution blocked: ${redirectDnsResult.message}`,
1264
+ blockedUrl: redirectUrl.href
1265
+ };
1266
+ }
1267
+ return {
1268
+ ok: false,
1269
+ reason: "network_error",
1270
+ message: redirectDnsResult.message,
1271
+ blockedUrl: redirectUrl.href
1272
+ };
1273
+ }
1274
+ if (!redirectDnsResult.browser) {
1275
+ for (const ip of redirectDnsResult.ips) {
1276
+ const blockResult = isBlockedIP(ip);
1277
+ if (blockResult.blocked) {
1278
+ return {
1279
+ ok: false,
1280
+ reason: blockResult.reason,
1281
+ message: `Redirect to blocked ${blockResult.reason} address: ${ip}`,
1282
+ blockedUrl: redirectUrl.href
1283
+ };
1284
+ }
1285
+ }
1286
+ }
1287
+ currentUrl = redirectUrl.href;
1288
+ continue;
1289
+ }
1290
+ const contentLength = response.headers.get("content-length");
1291
+ if (contentLength && parseInt(contentLength, 10) > maxBytes) {
1292
+ return {
1293
+ ok: false,
1294
+ reason: "response_too_large",
1295
+ message: `Response too large: ${contentLength} bytes > ${maxBytes} max`
1296
+ };
1297
+ }
1298
+ const reader = response.body?.getReader();
1299
+ if (!reader) {
1300
+ const body2 = await response.text();
1301
+ if (body2.length > maxBytes) {
1302
+ return {
1303
+ ok: false,
1304
+ reason: "response_too_large",
1305
+ message: `Response too large: ${body2.length} bytes > ${maxBytes} max`
1306
+ };
1307
+ }
1308
+ const rawBytes2 = new TextEncoder().encode(body2);
1309
+ return {
1310
+ ok: true,
1311
+ status: response.status,
1312
+ body: body2,
1313
+ rawBytes: rawBytes2,
1314
+ contentType: response.headers.get("content-type") ?? void 0
1315
+ };
1316
+ }
1317
+ const chunks = [];
1318
+ let totalSize = 0;
1319
+ while (true) {
1320
+ const { done, value } = await reader.read();
1321
+ if (done) break;
1322
+ totalSize += value.length;
1323
+ if (totalSize > maxBytes) {
1324
+ reader.cancel();
1325
+ return {
1326
+ ok: false,
1327
+ reason: "response_too_large",
1328
+ message: `Response too large: ${totalSize} bytes > ${maxBytes} max`
1329
+ };
1330
+ }
1331
+ chunks.push(value);
1332
+ }
1333
+ const rawBytes = chunks.reduce((acc, chunk) => {
1334
+ const result = new Uint8Array(acc.length + chunk.length);
1335
+ result.set(acc);
1336
+ result.set(chunk, acc.length);
1337
+ return result;
1338
+ }, new Uint8Array());
1339
+ const body = new TextDecoder().decode(rawBytes);
1340
+ return {
1341
+ ok: true,
1342
+ status: response.status,
1343
+ body,
1344
+ rawBytes,
1345
+ contentType: response.headers.get("content-type") ?? void 0
1346
+ };
1347
+ } catch (err) {
1348
+ if (err instanceof Error) {
1349
+ if (err.name === "AbortError" || err.message.includes("timeout")) {
1350
+ return {
1351
+ ok: false,
1352
+ reason: "timeout",
1353
+ message: `Fetch timeout after ${timeoutMs}ms: ${currentUrl}`
1354
+ };
1355
+ }
1356
+ }
1357
+ return {
1358
+ ok: false,
1359
+ reason: "network_error",
1360
+ message: `Network error: ${err instanceof Error ? err.message : String(err)}`
1361
+ };
1362
+ }
1363
+ }
1364
+ }
1365
+ async function fetchJWKSSafe(jwksUrl, options) {
1366
+ return ssrfSafeFetch(jwksUrl, {
1367
+ ...options,
1368
+ maxBytes: VERIFIER_LIMITS.maxJwksBytes,
1369
+ headers: {
1370
+ Accept: "application/json",
1371
+ ...options?.headers
1372
+ }
1373
+ });
1374
+ }
1375
+ async function fetchPointerSafe(pointerUrl, options) {
1376
+ return ssrfSafeFetch(pointerUrl, {
1377
+ ...options,
1378
+ maxBytes: VERIFIER_LIMITS.maxReceiptBytes,
1379
+ headers: {
1380
+ Accept: "application/jose, application/json",
1381
+ ...options?.headers
1382
+ }
1383
+ });
1384
+ }
1385
+ var VerificationReportBuilder = class {
1386
+ state;
1387
+ constructor(policy) {
1388
+ this.state = {
1389
+ policy,
1390
+ checks: /* @__PURE__ */ new Map(),
1391
+ shortCircuited: false
1392
+ };
1393
+ }
1394
+ /**
1395
+ * Set the input descriptor with pre-computed digest
1396
+ *
1397
+ * Use this when you've already computed the SHA-256 hash.
1398
+ *
1399
+ * @param digestHex - SHA-256 digest as lowercase hex (64 chars)
1400
+ * @param type - Input type
1401
+ */
1402
+ setInputWithDigest(digestHex, type = "receipt_jws") {
1403
+ this.state.receiptDigestHex = digestHex;
1404
+ this.state.input = {
1405
+ type,
1406
+ receipt_digest: createDigest(digestHex)
1407
+ };
1408
+ return this;
1409
+ }
1410
+ /**
1411
+ * Set the input descriptor (async - computes SHA-256)
1412
+ *
1413
+ * @param receiptBytes - Raw receipt bytes
1414
+ * @param type - Input type
1415
+ */
1416
+ async setInputAsync(receiptBytes, type = "receipt_jws") {
1417
+ const digestHex = await sha256Hex(receiptBytes);
1418
+ return this.setInputWithDigest(digestHex, type);
1419
+ }
1420
+ /**
1421
+ * Add a check result
1422
+ *
1423
+ * Checks can be added in any order; they will be sorted in build().
1424
+ * If a previous check failed, subsequent checks should be marked as skip.
1425
+ */
1426
+ addCheck(id, status, detail, errorCode) {
1427
+ const check = { id, status };
1428
+ if (detail && Object.keys(detail).length > 0) {
1429
+ check.detail = detail;
1430
+ }
1431
+ if (errorCode) {
1432
+ check.error_code = errorCode;
1433
+ }
1434
+ this.state.checks.set(id, check);
1435
+ if (status === "fail" && !this.state.shortCircuited) {
1436
+ this.state.shortCircuited = true;
1437
+ this.state.failedAtCheck = id;
1438
+ }
1439
+ return this;
1440
+ }
1441
+ /**
1442
+ * Add a passing check
1443
+ */
1444
+ pass(id, detail) {
1445
+ return this.addCheck(id, "pass", detail);
1446
+ }
1447
+ /**
1448
+ * Add a failing check
1449
+ */
1450
+ fail(id, errorCode, detail) {
1451
+ return this.addCheck(id, "fail", detail, errorCode);
1452
+ }
1453
+ /**
1454
+ * Add a skipped check
1455
+ */
1456
+ skip(id, detail) {
1457
+ return this.addCheck(id, "skip", detail);
1458
+ }
1459
+ /**
1460
+ * Set the final result
1461
+ */
1462
+ setResult(valid, reason, options) {
1463
+ this.state.result = {
1464
+ valid,
1465
+ reason,
1466
+ severity: reasonCodeToSeverity(reason),
1467
+ receipt_type: options?.receiptType ?? WIRE_TYPE,
1468
+ // Wire 0.1: always 'unavailable' (DD-49). Wire 0.2 will set this via options.
1469
+ policy_binding: "unavailable",
1470
+ ...options?.issuer && { issuer: options.issuer },
1471
+ ...options?.kid && { kid: options.kid }
1472
+ };
1473
+ return this;
1474
+ }
1475
+ /**
1476
+ * Set success result
1477
+ */
1478
+ success(issuer, kid) {
1479
+ return this.setResult(true, "ok", { issuer, kid });
1480
+ }
1481
+ /**
1482
+ * Set failure result
1483
+ */
1484
+ failure(reason, issuer, kid) {
1485
+ return this.setResult(false, reason, { issuer, kid });
1486
+ }
1487
+ /**
1488
+ * Add artifacts
1489
+ */
1490
+ addArtifact(key, value) {
1491
+ if (!this.state.artifacts) {
1492
+ this.state.artifacts = {};
1493
+ }
1494
+ this.state.artifacts[key] = value;
1495
+ return this;
1496
+ }
1497
+ /**
1498
+ * Set metadata (non-deterministic fields)
1499
+ */
1500
+ setMeta(meta) {
1501
+ this.state.meta = meta;
1502
+ return this;
1503
+ }
1504
+ /**
1505
+ * Add current timestamp to meta
1506
+ */
1507
+ addTimestamp() {
1508
+ if (!this.state.meta) {
1509
+ this.state.meta = {};
1510
+ }
1511
+ this.state.meta.generated_at = (/* @__PURE__ */ new Date()).toISOString();
1512
+ return this;
1513
+ }
1514
+ /**
1515
+ * Build the final report
1516
+ *
1517
+ * Ensures all checks are present (shape-stable).
1518
+ * Missing checks after a failure are marked as 'skip'.
1519
+ * Missing checks before a failure (or in success) are marked as 'pass'.
1520
+ */
1521
+ build() {
1522
+ if (!this.state.input) {
1523
+ throw new Error("Input is required. Call setInputWithDigest() or setInputAsync() first.");
1524
+ }
1525
+ if (!this.state.result) {
1526
+ throw new Error("Result is required. Call setResult() or success()/failure() first.");
1527
+ }
1528
+ const checks = [];
1529
+ const failedIndex = this.state.failedAtCheck ? CHECK_IDS.indexOf(this.state.failedAtCheck) : -1;
1530
+ for (let i = 0; i < CHECK_IDS.length; i++) {
1531
+ const checkId = CHECK_IDS[i];
1532
+ const existing = this.state.checks.get(checkId);
1533
+ if (existing) {
1534
+ checks.push(existing);
1535
+ } else if (this.state.shortCircuited && i > failedIndex) {
1536
+ checks.push({ id: checkId, status: "skip", detail: { reason: "short_circuit" } });
1537
+ } else {
1538
+ if (checkId === "transport.profile_binding") {
1539
+ checks.push({ id: checkId, status: "skip", detail: { reason: "not_applicable" } });
1540
+ } else if (checkId === "policy.binding") {
1541
+ checks.push({
1542
+ id: checkId,
1543
+ status: "skip",
1544
+ detail: { reason: "wire_01_no_policy_digest" }
1545
+ });
1546
+ } else {
1547
+ checks.push({ id: checkId, status: "skip", detail: { reason: "not_executed" } });
1548
+ }
1549
+ }
1550
+ }
1551
+ const report = {
1552
+ report_version: VERIFICATION_REPORT_VERSION,
1553
+ input: this.state.input,
1554
+ policy: this.state.policy,
1555
+ result: this.state.result,
1556
+ checks
1557
+ };
1558
+ if (this.state.artifacts && Object.keys(this.state.artifacts).length > 0) {
1559
+ report.artifacts = this.state.artifacts;
1560
+ }
1561
+ if (this.state.meta) {
1562
+ report.meta = this.state.meta;
1563
+ }
1564
+ return report;
1565
+ }
1566
+ /**
1567
+ * Build in deterministic mode (excludes meta and non-deterministic artifacts)
1568
+ *
1569
+ * Deterministic mode ensures that the same inputs and policy always produce
1570
+ * the same report output, regardless of cache state or timing.
1571
+ *
1572
+ * Excludes:
1573
+ * - `meta`: Contains timestamps and verifier info
1574
+ * - Non-deterministic artifacts: `issuer_jwks_digest` (depends on cache state)
1575
+ *
1576
+ * @returns Report without meta and with only deterministic artifacts
1577
+ */
1578
+ buildDeterministic() {
1579
+ const report = this.build();
1580
+ const { meta: _meta, ...deterministic } = report;
1581
+ if (deterministic.artifacts) {
1582
+ const filteredArtifacts = { ...deterministic.artifacts };
1583
+ for (const key of NON_DETERMINISTIC_ARTIFACT_KEYS) {
1584
+ delete filteredArtifacts[key];
1585
+ }
1586
+ if (Object.keys(filteredArtifacts).length === 0) {
1587
+ delete deterministic.artifacts;
1588
+ } else {
1589
+ deterministic.artifacts = filteredArtifacts;
1590
+ }
1591
+ }
1592
+ return deterministic;
1593
+ }
1594
+ };
1595
+ function createReportBuilder(policy) {
1596
+ return new VerificationReportBuilder(policy);
1597
+ }
1598
+ async function computeReceiptDigest(receiptBytes) {
1599
+ const bytes = typeof receiptBytes === "string" ? new TextEncoder().encode(receiptBytes) : receiptBytes;
1600
+ return sha256Hex(bytes);
1601
+ }
1602
+ async function buildFailureReport(policy, receiptBytes, reason, failedCheckId, errorCode, detail, options) {
1603
+ const bytes = typeof receiptBytes === "string" ? new TextEncoder().encode(receiptBytes) : receiptBytes;
1604
+ const digestHex = await sha256Hex(bytes);
1605
+ const builder = createReportBuilder(policy).setInputWithDigest(digestHex).failure(reason, options?.issuer, options?.kid);
1606
+ const failedIndex = CHECK_IDS.indexOf(failedCheckId);
1607
+ for (let i = 0; i < CHECK_IDS.length; i++) {
1608
+ const checkId = CHECK_IDS[i];
1609
+ if (i < failedIndex) {
1610
+ builder.pass(checkId);
1611
+ } else if (i === failedIndex) {
1612
+ builder.fail(checkId, errorCode ?? reasonCodeToErrorCode(reason), detail);
1613
+ }
1614
+ }
1615
+ if (options?.meta) {
1616
+ builder.setMeta(options.meta);
1617
+ }
1618
+ return builder.build();
1619
+ }
1620
+ async function buildSuccessReport(policy, receiptBytes, issuer, kid, checkDetails, options) {
1621
+ const bytes = typeof receiptBytes === "string" ? new TextEncoder().encode(receiptBytes) : receiptBytes;
1622
+ const digestHex = await sha256Hex(bytes);
1623
+ const builder = createReportBuilder(policy).setInputWithDigest(digestHex).success(issuer, kid);
1624
+ for (const checkId of CHECK_IDS) {
1625
+ if (checkId === "issuer.discovery" && policy.mode === "offline_only") {
1626
+ builder.skip(checkId, { reason: "offline_mode" });
1627
+ continue;
1628
+ }
1629
+ if (checkId === "transport.profile_binding") {
1630
+ if (checkDetails?.[checkId]) {
1631
+ builder.pass(checkId, checkDetails[checkId]);
1632
+ }
1633
+ continue;
1634
+ }
1635
+ if (checkId === "policy.binding") {
1636
+ continue;
1637
+ }
1638
+ builder.pass(checkId, checkDetails?.[checkId]);
1639
+ }
1640
+ if (options?.artifacts) {
1641
+ for (const [key, value] of Object.entries(options.artifacts)) {
1642
+ builder.addArtifact(key, value);
1643
+ }
1644
+ }
1645
+ if (options?.meta) {
1646
+ builder.setMeta(options.meta);
1647
+ }
1648
+ return builder.build();
1649
+ }
1650
+
1651
+ // src/verifier-core.ts
1652
+ var jwksCache2 = /* @__PURE__ */ new Map();
1653
+ var CACHE_TTL_MS2 = 5 * 60 * 1e3;
1654
+ function normalizeIssuer(issuer) {
1655
+ try {
1656
+ const url = new URL(issuer);
1657
+ if (url.port && url.port !== "443") {
1658
+ return `${url.protocol}//${url.hostname}:${url.port}`;
1659
+ }
1660
+ return `${url.protocol}//${url.hostname}`;
1661
+ } catch {
1662
+ return issuer;
1663
+ }
1664
+ }
1665
+ function isIssuerAllowed(issuer, allowlist) {
1666
+ if (!allowlist || allowlist.length === 0) {
1667
+ return true;
1668
+ }
1669
+ const normalized = normalizeIssuer(issuer);
1670
+ return allowlist.some((allowed) => normalizeIssuer(allowed) === normalized);
1671
+ }
1672
+ function findPinnedKey(issuer, kid, pinnedKeys) {
1673
+ if (!pinnedKeys || pinnedKeys.length === 0) {
1674
+ return void 0;
1675
+ }
1676
+ const normalizedIssuer = normalizeIssuer(issuer);
1677
+ return pinnedKeys.find((pk) => normalizeIssuer(pk.issuer) === normalizedIssuer && pk.kid === kid);
1678
+ }
1679
+ async function fetchIssuerConfig2(issuerOrigin) {
1680
+ const configUrl = `${issuerOrigin}/.well-known/peac-issuer.json`;
1681
+ const result = await ssrfSafeFetch(configUrl, {
1682
+ maxBytes: 65536,
1683
+ // 64 KB
1684
+ headers: { Accept: "application/json" }
1685
+ });
1686
+ if (!result.ok) {
1687
+ return null;
1688
+ }
1689
+ try {
1690
+ return JSON.parse(result.body);
1691
+ } catch {
1692
+ return null;
1693
+ }
1694
+ }
1695
+ async function fetchIssuerJWKS(issuerOrigin) {
1696
+ const now = Date.now();
1697
+ const cached = jwksCache2.get(issuerOrigin);
1698
+ if (cached && cached.expiresAt > now) {
1699
+ return { jwks: cached.jwks, fromCache: true };
1700
+ }
1701
+ const config = await fetchIssuerConfig2(issuerOrigin);
1702
+ if (!config?.jwks_uri) {
1703
+ const fallbackUrl = `${issuerOrigin}/.well-known/jwks.json`;
1704
+ const result2 = await fetchJWKSSafe(fallbackUrl);
1705
+ if (!result2.ok) {
1706
+ return { error: result2 };
1707
+ }
1708
+ try {
1709
+ const jwks = JSON.parse(result2.body);
1710
+ jwksCache2.set(issuerOrigin, { jwks, expiresAt: now + CACHE_TTL_MS2 });
1711
+ return { jwks, fromCache: false, rawBytes: result2.rawBytes };
1712
+ } catch {
1713
+ return {
1714
+ error: {
1715
+ ok: false,
1716
+ reason: "network_error",
1717
+ message: "Invalid JWKS JSON"
1718
+ }
1719
+ };
1720
+ }
1721
+ }
1722
+ const result = await fetchJWKSSafe(config.jwks_uri);
1723
+ if (!result.ok) {
1724
+ return { error: result };
1725
+ }
1726
+ try {
1727
+ const jwks = JSON.parse(result.body);
1728
+ if (jwks.keys.length > VERIFIER_LIMITS.maxJwksKeys) {
1729
+ return {
1730
+ error: {
1731
+ ok: false,
1732
+ reason: "jwks_too_many_keys",
1733
+ message: `JWKS has too many keys: ${jwks.keys.length} > ${VERIFIER_LIMITS.maxJwksKeys}`
1734
+ }
1735
+ };
1736
+ }
1737
+ jwksCache2.set(issuerOrigin, { jwks, expiresAt: now + CACHE_TTL_MS2 });
1738
+ return { jwks, fromCache: false, rawBytes: result.rawBytes };
1739
+ } catch {
1740
+ return {
1741
+ error: {
1742
+ ok: false,
1743
+ reason: "network_error",
1744
+ message: "Invalid JWKS JSON"
1745
+ }
1746
+ };
1747
+ }
1748
+ }
1749
+ async function verifyReceiptCore(options) {
1750
+ const {
1751
+ receipt,
1752
+ policy = createDefaultPolicy("offline_preferred"),
1753
+ referenceTime,
1754
+ includeMeta = false
1755
+ } = options;
1756
+ const receiptJws = typeof receipt === "string" ? receipt : new TextDecoder().decode(receipt);
1757
+ const receiptBytes = typeof receipt === "string" ? new TextEncoder().encode(receipt) : receipt;
1758
+ const receiptDigestHex = await sha256Hex(receiptBytes);
1759
+ const builder = createReportBuilder(policy);
1760
+ builder.setInputWithDigest(receiptDigestHex);
1761
+ const nowSeconds = referenceTime ?? Math.floor(Date.now() / 1e3);
1762
+ let issuer;
1763
+ let kid;
1764
+ let parsedClaims;
1765
+ let header;
1766
+ let payload;
1767
+ try {
1768
+ const decoded = decode(receiptJws);
1769
+ header = decoded.header;
1770
+ payload = decoded.payload;
1771
+ builder.pass("jws.parse");
1772
+ } catch (err) {
1773
+ builder.fail("jws.parse", "E_VERIFY_MALFORMED_RECEIPT", {
1774
+ error: err instanceof Error ? err.message : String(err)
1775
+ });
1776
+ builder.failure("malformed_receipt");
1777
+ return { valid: false, report: includeMeta ? builder.addTimestamp().build() : builder.build() };
1778
+ }
1779
+ if (receiptBytes.length > policy.limits.max_receipt_bytes) {
1780
+ builder.fail("limits.receipt_bytes", "E_VERIFY_RECEIPT_TOO_LARGE", {
1781
+ size: receiptBytes.length,
1782
+ limit: policy.limits.max_receipt_bytes
1783
+ });
1784
+ builder.failure("receipt_too_large");
1785
+ return { valid: false, report: includeMeta ? builder.addTimestamp().build() : builder.build() };
1786
+ }
1787
+ builder.pass("limits.receipt_bytes", { size: receiptBytes.length });
1788
+ if (header.alg !== "EdDSA") {
1789
+ builder.fail("jws.protected_header", "E_VERIFY_MALFORMED_RECEIPT", {
1790
+ expected_alg: "EdDSA",
1791
+ actual_alg: header.alg
1792
+ });
1793
+ builder.failure("malformed_receipt");
1794
+ return { valid: false, report: includeMeta ? builder.addTimestamp().build() : builder.build() };
1795
+ }
1796
+ if (header.typ !== WIRE_TYPE) {
1797
+ builder.fail("jws.protected_header", "E_VERIFY_MALFORMED_RECEIPT", {
1798
+ expected_typ: WIRE_TYPE,
1799
+ actual_typ: header.typ
1800
+ });
1801
+ builder.failure("malformed_receipt");
1802
+ return { valid: false, report: includeMeta ? builder.addTimestamp().build() : builder.build() };
1803
+ }
1804
+ if (!header.kid) {
1805
+ builder.fail("jws.protected_header", "E_VERIFY_MALFORMED_RECEIPT", {
1806
+ error: "Missing kid in protected header"
1807
+ });
1808
+ builder.failure("malformed_receipt");
1809
+ return { valid: false, report: includeMeta ? builder.addTimestamp().build() : builder.build() };
1810
+ }
1811
+ kid = header.kid;
1812
+ builder.pass("jws.protected_header", { alg: header.alg, typ: header.typ, kid: header.kid });
1813
+ try {
1814
+ ReceiptClaims.parse(payload);
1815
+ issuer = payload.iss;
1816
+ builder.pass("claims.schema_unverified");
1817
+ } catch (err) {
1818
+ builder.fail("claims.schema_unverified", "E_VERIFY_SCHEMA_INVALID", {
1819
+ error: err instanceof Error ? err.message : String(err)
1820
+ });
1821
+ builder.failure("schema_invalid");
1822
+ return { valid: false, report: includeMeta ? builder.addTimestamp().build() : builder.build() };
1823
+ }
1824
+ const normalizedIssuer = normalizeIssuer(issuer);
1825
+ if (!isIssuerAllowed(issuer, policy.issuer_allowlist)) {
1826
+ builder.fail("issuer.trust_policy", "E_VERIFY_ISSUER_NOT_ALLOWED", {
1827
+ issuer: normalizedIssuer,
1828
+ allowlist: policy.issuer_allowlist
1829
+ });
1830
+ builder.failure("issuer_not_allowed", normalizedIssuer, kid);
1831
+ return { valid: false, report: includeMeta ? builder.addTimestamp().build() : builder.build() };
1832
+ }
1833
+ builder.pass("issuer.trust_policy", { issuer: normalizedIssuer });
1834
+ let publicKey;
1835
+ let keySource;
1836
+ let keyThumbprint;
1837
+ let jwksRawBytes;
1838
+ const pinnedKey = findPinnedKey(issuer, kid, policy.pinned_keys);
1839
+ if (pinnedKey) {
1840
+ builder.skip("issuer.discovery", { reason: "pinned_key_available" });
1841
+ if (pinnedKey.jwk) {
1842
+ const actualThumbprint = await computeJwkThumbprint(pinnedKey.jwk);
1843
+ if (actualThumbprint !== pinnedKey.jwk_thumbprint_sha256) {
1844
+ builder.fail("key.resolve", "E_VERIFY_POLICY_VIOLATION", {
1845
+ error: "Pinned JWK thumbprint does not match declared thumbprint",
1846
+ expected: pinnedKey.jwk_thumbprint_sha256,
1847
+ actual: actualThumbprint
1848
+ });
1849
+ builder.failure("policy_violation", normalizedIssuer, kid);
1850
+ return {
1851
+ valid: false,
1852
+ report: includeMeta ? builder.addTimestamp().build() : builder.build()
1853
+ };
1854
+ }
1855
+ publicKey = jwkToPublicKeyBytes(pinnedKey.jwk);
1856
+ keySource = "pinned_keys";
1857
+ keyThumbprint = actualThumbprint;
1858
+ builder.pass("key.resolve", {
1859
+ source: keySource,
1860
+ kid,
1861
+ thumbprint_verified: true,
1862
+ offline: true
1863
+ });
1864
+ } else if (pinnedKey.public_key) {
1865
+ try {
1866
+ publicKey = base64urlDecode(pinnedKey.public_key);
1867
+ if (publicKey.length !== 32) {
1868
+ throw new Error(`Expected 32 bytes, got ${publicKey.length}`);
1869
+ }
1870
+ keySource = "pinned_keys";
1871
+ keyThumbprint = pinnedKey.jwk_thumbprint_sha256;
1872
+ builder.pass("key.resolve", {
1873
+ source: keySource,
1874
+ kid,
1875
+ offline: true,
1876
+ thumbprint_verified: false
1877
+ });
1878
+ } catch (err) {
1879
+ builder.fail("key.resolve", "E_VERIFY_KEY_NOT_FOUND", {
1880
+ error: `Invalid pinned public_key: ${err instanceof Error ? err.message : String(err)}`
1881
+ });
1882
+ builder.failure("key_not_found", normalizedIssuer, kid);
1883
+ return {
1884
+ valid: false,
1885
+ report: includeMeta ? builder.addTimestamp().build() : builder.build()
1886
+ };
1887
+ }
1888
+ } else if (policy.mode === "offline_only") {
1889
+ builder.fail("key.resolve", "E_VERIFY_KEY_NOT_FOUND", {
1890
+ error: "Offline mode requires key material (jwk or public_key) in pinned_keys"
1891
+ });
1892
+ builder.failure("key_not_found", normalizedIssuer, kid);
1893
+ return {
1894
+ valid: false,
1895
+ report: includeMeta ? builder.addTimestamp().build() : builder.build()
1896
+ };
1897
+ } else {
1898
+ const jwksResult = await fetchIssuerJWKS(normalizedIssuer);
1899
+ if ("error" in jwksResult) {
1900
+ const reason = ssrfErrorToReasonCode(jwksResult.error.reason, "key");
1901
+ builder.fail("issuer.discovery", reasonCodeToErrorCode(reason), {
1902
+ error: jwksResult.error.message,
1903
+ url: jwksResult.error.blockedUrl
1904
+ });
1905
+ builder.failure(reason, normalizedIssuer, kid);
1906
+ return {
1907
+ valid: false,
1908
+ report: includeMeta ? builder.addTimestamp().build() : builder.build()
1909
+ };
1910
+ }
1911
+ if (jwksResult.rawBytes) {
1912
+ jwksRawBytes = jwksResult.rawBytes;
1913
+ }
1914
+ builder.pass("issuer.discovery", {
1915
+ from_cache: jwksResult.fromCache,
1916
+ keys_count: jwksResult.jwks.keys.length
1917
+ });
1918
+ const jwk = jwksResult.jwks.keys.find((k) => k.kid === kid);
1919
+ if (!jwk) {
1920
+ builder.fail("key.resolve", "E_VERIFY_KEY_NOT_FOUND", {
1921
+ kid,
1922
+ available_kids: jwksResult.jwks.keys.map((k) => k.kid)
1923
+ });
1924
+ builder.failure("key_not_found", normalizedIssuer, kid);
1925
+ return {
1926
+ valid: false,
1927
+ report: includeMeta ? builder.addTimestamp().build() : builder.build()
1928
+ };
1929
+ }
1930
+ const actualThumbprint = await computeJwkThumbprint(jwk);
1931
+ if (actualThumbprint !== pinnedKey.jwk_thumbprint_sha256) {
1932
+ builder.fail("key.resolve", "E_VERIFY_POLICY_VIOLATION", {
1933
+ error: "JWK thumbprint does not match pinned key",
1934
+ expected: pinnedKey.jwk_thumbprint_sha256,
1935
+ actual: actualThumbprint
1936
+ });
1937
+ builder.failure("policy_violation", normalizedIssuer, kid);
1938
+ return {
1939
+ valid: false,
1940
+ report: includeMeta ? builder.addTimestamp().build() : builder.build()
1941
+ };
1942
+ }
1943
+ publicKey = jwkToPublicKeyBytes(jwk);
1944
+ keySource = "pinned_keys";
1945
+ keyThumbprint = actualThumbprint;
1946
+ builder.pass("key.resolve", { source: keySource, kid, thumbprint_verified: true });
1947
+ }
1948
+ } else {
1949
+ if (policy.mode === "offline_only") {
1950
+ builder.fail("issuer.discovery", "E_VERIFY_KEY_NOT_FOUND", {
1951
+ error: "Offline mode requires pinned keys"
1952
+ });
1953
+ builder.failure("key_not_found", normalizedIssuer, kid);
1954
+ return {
1955
+ valid: false,
1956
+ report: includeMeta ? builder.addTimestamp().build() : builder.build()
1957
+ };
1958
+ }
1959
+ const jwksResult = await fetchIssuerJWKS(normalizedIssuer);
1960
+ if ("error" in jwksResult) {
1961
+ const reason = ssrfErrorToReasonCode(jwksResult.error.reason, "key");
1962
+ builder.fail("issuer.discovery", reasonCodeToErrorCode(reason), {
1963
+ error: jwksResult.error.message,
1964
+ url: jwksResult.error.blockedUrl
1965
+ });
1966
+ builder.failure(reason, normalizedIssuer, kid);
1967
+ return {
1968
+ valid: false,
1969
+ report: includeMeta ? builder.addTimestamp().build() : builder.build()
1970
+ };
1971
+ }
1972
+ if (jwksResult.rawBytes) {
1973
+ jwksRawBytes = jwksResult.rawBytes;
1974
+ }
1975
+ builder.pass("issuer.discovery", {
1976
+ from_cache: jwksResult.fromCache,
1977
+ keys_count: jwksResult.jwks.keys.length
1978
+ });
1979
+ const jwk = jwksResult.jwks.keys.find((k) => k.kid === kid);
1980
+ if (!jwk) {
1981
+ builder.fail("key.resolve", "E_VERIFY_KEY_NOT_FOUND", {
1982
+ kid,
1983
+ available_kids: jwksResult.jwks.keys.map((k) => k.kid)
1984
+ });
1985
+ builder.failure("key_not_found", normalizedIssuer, kid);
1986
+ return {
1987
+ valid: false,
1988
+ report: includeMeta ? builder.addTimestamp().build() : builder.build()
1989
+ };
1990
+ }
1991
+ publicKey = jwkToPublicKeyBytes(jwk);
1992
+ keySource = "jwks_discovery";
1993
+ keyThumbprint = await computeJwkThumbprint(jwk);
1994
+ builder.pass("key.resolve", { source: keySource, kid, thumbprint: keyThumbprint });
1995
+ }
1996
+ try {
1997
+ const result = await verify(receiptJws, publicKey);
1998
+ if (!result.valid) {
1999
+ builder.fail("jws.signature", "E_VERIFY_SIGNATURE_INVALID", {
2000
+ error: "Ed25519 signature verification failed"
2001
+ });
2002
+ builder.failure("signature_invalid", normalizedIssuer, kid);
2003
+ return {
2004
+ valid: false,
2005
+ report: includeMeta ? builder.addTimestamp().build() : builder.build()
2006
+ };
2007
+ }
2008
+ parsedClaims = result.payload;
2009
+ builder.pass("jws.signature");
2010
+ } catch (err) {
2011
+ builder.fail("jws.signature", "E_VERIFY_SIGNATURE_INVALID", {
2012
+ error: err instanceof Error ? err.message : String(err)
2013
+ });
2014
+ builder.failure("signature_invalid", normalizedIssuer, kid);
2015
+ return { valid: false, report: includeMeta ? builder.addTimestamp().build() : builder.build() };
2016
+ }
2017
+ const iatTolerance = 60;
2018
+ if (parsedClaims.iat > nowSeconds + iatTolerance) {
2019
+ builder.fail("claims.time_window", "E_VERIFY_NOT_YET_VALID", {
2020
+ error: "Receipt issued in the future",
2021
+ iat: parsedClaims.iat,
2022
+ now: nowSeconds,
2023
+ tolerance: iatTolerance
2024
+ });
2025
+ builder.failure("not_yet_valid", normalizedIssuer, kid);
2026
+ return { valid: false, report: includeMeta ? builder.addTimestamp().build() : builder.build() };
2027
+ }
2028
+ if (parsedClaims.exp) {
2029
+ if (parsedClaims.exp < nowSeconds) {
2030
+ builder.fail("claims.time_window", "E_VERIFY_EXPIRED", {
2031
+ error: "Receipt expired",
2032
+ exp: parsedClaims.exp,
2033
+ now: nowSeconds
2034
+ });
2035
+ builder.failure("expired", normalizedIssuer, kid);
2036
+ return {
2037
+ valid: false,
2038
+ report: includeMeta ? builder.addTimestamp().build() : builder.build()
2039
+ };
2040
+ }
2041
+ }
2042
+ builder.pass("claims.time_window", {
2043
+ iat: parsedClaims.iat,
2044
+ exp: parsedClaims.exp,
2045
+ now: nowSeconds
2046
+ });
2047
+ if (parsedClaims.ext) {
2048
+ for (const [extKey, extValue] of Object.entries(parsedClaims.ext)) {
2049
+ if (extValue !== void 0) {
2050
+ const extJson = JSON.stringify(extValue);
2051
+ if (extJson.length > policy.limits.max_extension_bytes) {
2052
+ builder.fail("extensions.limits", "E_VERIFY_EXTENSION_TOO_LARGE", {
2053
+ extension: extKey,
2054
+ size: extJson.length,
2055
+ limit: policy.limits.max_extension_bytes
2056
+ });
2057
+ builder.failure("extension_too_large", normalizedIssuer, kid);
2058
+ return {
2059
+ valid: false,
2060
+ report: includeMeta ? builder.addTimestamp().build() : builder.build()
2061
+ };
2062
+ }
2063
+ }
2064
+ }
2065
+ }
2066
+ builder.pass("extensions.limits");
2067
+ builder.success(normalizedIssuer, kid);
2068
+ const artifactKeySource = keySource === "pinned_keys" ? "pinned" : "jwks_fetch";
2069
+ builder.addArtifact("issuer_key_source", artifactKeySource);
2070
+ if (keyThumbprint) {
2071
+ builder.addArtifact("issuer_key_thumbprint", keyThumbprint);
2072
+ }
2073
+ if (jwksRawBytes) {
2074
+ const jwksDigestHex = await sha256Hex(jwksRawBytes);
2075
+ builder.addArtifact("issuer_jwks_digest", createDigest(jwksDigestHex));
2076
+ }
2077
+ const report = includeMeta ? builder.addTimestamp().build() : builder.build();
2078
+ return {
2079
+ valid: true,
2080
+ report,
2081
+ claims: parsedClaims
2082
+ };
2083
+ }
2084
+ function clearJWKSCache() {
2085
+ jwksCache2.clear();
2086
+ }
2087
+ function getJWKSCacheSize() {
2088
+ return jwksCache2.size;
2089
+ }
2090
+
2091
+ // src/transport-profiles.ts
2092
+ function parseHeaderProfile(headerValue) {
2093
+ if (headerValue === void 0 || headerValue === "") {
2094
+ return {
2095
+ ok: false,
2096
+ reason: "invalid_transport",
2097
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2098
+ message: "PEAC-Receipt header is missing"
2099
+ };
2100
+ }
2101
+ if (Array.isArray(headerValue)) {
2102
+ return {
2103
+ ok: false,
2104
+ reason: "invalid_transport",
2105
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2106
+ message: "Multiple PEAC-Receipt headers are not allowed"
2107
+ };
2108
+ }
2109
+ if (headerValue.includes(",")) {
2110
+ const parts = headerValue.split(".");
2111
+ if (parts.length !== 3 || parts.some((p) => p.includes(","))) {
2112
+ return {
2113
+ ok: false,
2114
+ reason: "invalid_transport",
2115
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2116
+ message: "Comma-separated PEAC-Receipt values are not allowed"
2117
+ };
2118
+ }
2119
+ }
2120
+ const segments = headerValue.split(".");
2121
+ if (segments.length !== 3) {
2122
+ return {
2123
+ ok: false,
2124
+ reason: "malformed_receipt",
2125
+ errorCode: "E_VERIFY_MALFORMED_RECEIPT",
2126
+ message: `Invalid JWS compact serialization: expected 3 segments, got ${segments.length}`
2127
+ };
2128
+ }
2129
+ const base64urlRegex = /^[A-Za-z0-9_-]*$/;
2130
+ for (let i = 0; i < segments.length; i++) {
2131
+ const segment = segments[i];
2132
+ if (segment.length === 0) {
2133
+ return {
2134
+ ok: false,
2135
+ reason: "malformed_receipt",
2136
+ errorCode: "E_VERIFY_MALFORMED_RECEIPT",
2137
+ message: `Invalid JWS compact serialization: segment ${i + 1} is empty`
2138
+ };
2139
+ }
2140
+ if (!base64urlRegex.test(segment)) {
2141
+ return {
2142
+ ok: false,
2143
+ reason: "malformed_receipt",
2144
+ errorCode: "E_VERIFY_MALFORMED_RECEIPT",
2145
+ message: `Invalid JWS compact serialization: segment ${i + 1} contains invalid characters`
2146
+ };
2147
+ }
2148
+ }
2149
+ return {
2150
+ ok: true,
2151
+ result: {
2152
+ profile: "header",
2153
+ receipt: headerValue
2154
+ }
2155
+ };
2156
+ }
2157
+ function parsePointerProfile(headerValue) {
2158
+ if (headerValue === void 0 || headerValue === "") {
2159
+ return {
2160
+ ok: false,
2161
+ reason: "invalid_transport",
2162
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2163
+ message: "PEAC-Receipt-Pointer header is missing"
2164
+ };
2165
+ }
2166
+ if (Array.isArray(headerValue)) {
2167
+ return {
2168
+ ok: false,
2169
+ reason: "invalid_transport",
2170
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2171
+ message: "Multiple PEAC-Receipt-Pointer headers are not allowed"
2172
+ };
2173
+ }
2174
+ const parseResult = parseSimpleDictionary(headerValue);
2175
+ if (parseResult.duplicates.length > 0) {
2176
+ return {
2177
+ ok: false,
2178
+ reason: "invalid_transport",
2179
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2180
+ message: `PEAC-Receipt-Pointer has duplicate parameter: ${parseResult.duplicates[0]}`
2181
+ };
2182
+ }
2183
+ const ALLOWED_KEYS = /* @__PURE__ */ new Set(["sha256", "url"]);
2184
+ const unknownKeys = parseResult.keys.filter((k) => !ALLOWED_KEYS.has(k) && !k.startsWith("ext_"));
2185
+ if (unknownKeys.length > 0) {
2186
+ return {
2187
+ ok: false,
2188
+ reason: "invalid_transport",
2189
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2190
+ message: `PEAC-Receipt-Pointer has unknown parameter: ${unknownKeys[0]}`
2191
+ };
2192
+ }
2193
+ const params = parseResult.params;
2194
+ if (!params.sha256) {
2195
+ return {
2196
+ ok: false,
2197
+ reason: "invalid_transport",
2198
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2199
+ message: "PEAC-Receipt-Pointer missing sha256 parameter"
2200
+ };
2201
+ }
2202
+ if (!params.url) {
2203
+ return {
2204
+ ok: false,
2205
+ reason: "invalid_transport",
2206
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2207
+ message: "PEAC-Receipt-Pointer missing url parameter"
2208
+ };
2209
+ }
2210
+ const hexRegex = /^[0-9a-f]{64}$/;
2211
+ if (!hexRegex.test(params.sha256)) {
2212
+ return {
2213
+ ok: false,
2214
+ reason: "invalid_transport",
2215
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2216
+ message: "PEAC-Receipt-Pointer sha256 must be 64 lowercase hex characters"
2217
+ };
2218
+ }
2219
+ try {
2220
+ const url = new URL(params.url);
2221
+ if (url.protocol !== "https:") {
2222
+ return {
2223
+ ok: false,
2224
+ reason: "pointer_fetch_blocked",
2225
+ errorCode: "E_VERIFY_POINTER_FETCH_BLOCKED",
2226
+ message: "Pointer URL must use HTTPS"
2227
+ };
2228
+ }
2229
+ } catch {
2230
+ return {
2231
+ ok: false,
2232
+ reason: "invalid_transport",
2233
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2234
+ message: "PEAC-Receipt-Pointer url is not a valid URL"
2235
+ };
2236
+ }
2237
+ const extensions = {};
2238
+ for (const key of parseResult.keys) {
2239
+ if (key.startsWith("ext_")) {
2240
+ extensions[key] = params[key];
2241
+ }
2242
+ }
2243
+ return {
2244
+ ok: true,
2245
+ result: {
2246
+ profile: "pointer",
2247
+ digestAlg: "sha256",
2248
+ digestValue: params.sha256,
2249
+ url: params.url,
2250
+ ...Object.keys(extensions).length > 0 && { extensions }
2251
+ }
2252
+ };
2253
+ }
2254
+ function parseSimpleDictionary(input) {
2255
+ const params = {};
2256
+ const duplicates = [];
2257
+ const keys = [];
2258
+ let i = 0;
2259
+ const len = input.length;
2260
+ while (i < len) {
2261
+ while (i < len && (input[i] === " " || input[i] === "," || input[i] === " ")) {
2262
+ i++;
2263
+ }
2264
+ if (i >= len) break;
2265
+ const keyStart = i;
2266
+ while (i < len && /\w/.test(input[i])) {
2267
+ i++;
2268
+ }
2269
+ const key = input.slice(keyStart, i);
2270
+ if (!key) break;
2271
+ while (i < len && input[i] === " ") i++;
2272
+ if (i >= len || input[i] !== "=") break;
2273
+ i++;
2274
+ while (i < len && input[i] === " ") i++;
2275
+ let value;
2276
+ if (input[i] === '"') {
2277
+ i++;
2278
+ const valueStart = i;
2279
+ while (i < len && input[i] !== '"') {
2280
+ i++;
2281
+ }
2282
+ value = input.slice(valueStart, i);
2283
+ if (i < len) i++;
2284
+ } else {
2285
+ const valueStart = i;
2286
+ while (i < len && input[i] !== "," && input[i] !== " " && input[i] !== " ") {
2287
+ i++;
2288
+ }
2289
+ value = input.slice(valueStart, i);
2290
+ }
2291
+ keys.push(key);
2292
+ if (key in params) {
2293
+ duplicates.push(key);
2294
+ }
2295
+ params[key] = value;
2296
+ }
2297
+ return { params, duplicates, keys };
2298
+ }
2299
+ function parseBodyProfile(body) {
2300
+ if (body === null || typeof body !== "object") {
2301
+ return {
2302
+ ok: false,
2303
+ reason: "invalid_transport",
2304
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2305
+ message: "Body must be a JSON object"
2306
+ };
2307
+ }
2308
+ const obj = body;
2309
+ if ("peac_receipts" in obj) {
2310
+ if (!Array.isArray(obj.peac_receipts)) {
2311
+ return {
2312
+ ok: false,
2313
+ reason: "invalid_transport",
2314
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2315
+ message: "peac_receipts must be an array"
2316
+ };
2317
+ }
2318
+ const receipts = [];
2319
+ for (let i = 0; i < obj.peac_receipts.length; i++) {
2320
+ const receipt = obj.peac_receipts[i];
2321
+ if (typeof receipt !== "string") {
2322
+ return {
2323
+ ok: false,
2324
+ reason: "invalid_transport",
2325
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2326
+ message: `peac_receipts[${i}] must be a string`
2327
+ };
2328
+ }
2329
+ receipts.push(receipt);
2330
+ }
2331
+ if (receipts.length === 0) {
2332
+ return {
2333
+ ok: false,
2334
+ reason: "invalid_transport",
2335
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2336
+ message: "peac_receipts array is empty"
2337
+ };
2338
+ }
2339
+ return {
2340
+ ok: true,
2341
+ result: {
2342
+ profile: "body",
2343
+ receipts
2344
+ }
2345
+ };
2346
+ }
2347
+ if ("peac_receipt" in obj) {
2348
+ if (typeof obj.peac_receipt !== "string") {
2349
+ return {
2350
+ ok: false,
2351
+ reason: "invalid_transport",
2352
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2353
+ message: "peac_receipt must be a string"
2354
+ };
2355
+ }
2356
+ if (obj.peac_receipt.length === 0) {
2357
+ return {
2358
+ ok: false,
2359
+ reason: "invalid_transport",
2360
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2361
+ message: "peac_receipt is empty"
2362
+ };
2363
+ }
2364
+ return {
2365
+ ok: true,
2366
+ result: {
2367
+ profile: "body",
2368
+ receipts: [obj.peac_receipt]
2369
+ }
2370
+ };
2371
+ }
2372
+ return {
2373
+ ok: false,
2374
+ reason: "invalid_transport",
2375
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2376
+ message: "Body must contain peac_receipt or peac_receipts"
2377
+ };
2378
+ }
2379
+ function parseTransportProfile(context) {
2380
+ const peacReceipt = context.headers["peac-receipt"] ?? context.headers["PEAC-Receipt"];
2381
+ const peacPointer = context.headers["peac-receipt-pointer"] ?? context.headers["PEAC-Receipt-Pointer"];
2382
+ if (peacReceipt !== void 0) {
2383
+ return parseHeaderProfile(peacReceipt);
2384
+ }
2385
+ if (peacPointer !== void 0) {
2386
+ return parsePointerProfile(peacPointer);
2387
+ }
2388
+ if (context.body !== void 0) {
2389
+ return parseBodyProfile(context.body);
2390
+ }
2391
+ return {
2392
+ ok: false,
2393
+ reason: "invalid_transport",
2394
+ errorCode: "E_VERIFY_INVALID_TRANSPORT",
2395
+ message: "No transport profile detected (missing PEAC-Receipt, PEAC-Receipt-Pointer, or body receipt)"
2396
+ };
2397
+ }
2398
+ function mapSsrfError(ssrfError) {
2399
+ const reason = ssrfError.reason;
2400
+ switch (reason) {
2401
+ case "not_https":
2402
+ case "private_ip":
2403
+ case "loopback":
2404
+ case "link_local":
2405
+ case "dns_failure":
2406
+ case "cross_origin_redirect":
2407
+ return {
2408
+ ok: false,
2409
+ reason: "pointer_fetch_blocked",
2410
+ errorCode: "E_VERIFY_POINTER_FETCH_BLOCKED",
2411
+ message: ssrfError.message
2412
+ };
2413
+ case "timeout":
2414
+ return {
2415
+ ok: false,
2416
+ reason: "pointer_fetch_timeout",
2417
+ errorCode: "E_VERIFY_POINTER_FETCH_TIMEOUT",
2418
+ message: ssrfError.message
2419
+ };
2420
+ case "response_too_large":
2421
+ return {
2422
+ ok: false,
2423
+ reason: "pointer_fetch_too_large",
2424
+ errorCode: "E_VERIFY_POINTER_FETCH_TOO_LARGE",
2425
+ message: ssrfError.message
2426
+ };
2427
+ default:
2428
+ return {
2429
+ ok: false,
2430
+ reason: "pointer_fetch_failed",
2431
+ errorCode: "E_VERIFY_POINTER_FETCH_FAILED",
2432
+ message: ssrfError.message
2433
+ };
2434
+ }
2435
+ }
2436
+ async function fetchPointerWithDigest(options) {
2437
+ const { url, expectedDigest, fetchOptions = {} } = options;
2438
+ const hexRegex = /^[0-9a-f]{64}$/;
2439
+ if (!hexRegex.test(expectedDigest)) {
2440
+ return {
2441
+ ok: false,
2442
+ reason: "pointer_fetch_failed",
2443
+ errorCode: "E_VERIFY_POINTER_FETCH_FAILED",
2444
+ message: "Invalid expected digest: must be 64 lowercase hex characters"
2445
+ };
2446
+ }
2447
+ try {
2448
+ const parsedUrl = new URL(url);
2449
+ if (parsedUrl.protocol !== "https:") {
2450
+ return {
2451
+ ok: false,
2452
+ reason: "pointer_fetch_blocked",
2453
+ errorCode: "E_VERIFY_POINTER_FETCH_BLOCKED",
2454
+ message: "Pointer URL must use HTTPS"
2455
+ };
2456
+ }
2457
+ } catch {
2458
+ return {
2459
+ ok: false,
2460
+ reason: "pointer_fetch_failed",
2461
+ errorCode: "E_VERIFY_POINTER_FETCH_FAILED",
2462
+ message: "Invalid pointer URL"
2463
+ };
2464
+ }
2465
+ const fetchResult = await ssrfSafeFetch(url, {
2466
+ ...fetchOptions,
2467
+ maxBytes: VERIFIER_LIMITS.maxReceiptBytes,
2468
+ allowRedirects: false,
2469
+ // Pointer URL must be direct - no redirects
2470
+ timeoutMs: fetchOptions?.timeoutMs ?? VERIFIER_LIMITS.fetchTimeoutMs,
2471
+ headers: {
2472
+ Accept: "application/jose, application/json, text/plain",
2473
+ ...fetchOptions.headers
2474
+ }
2475
+ });
2476
+ if (!fetchResult.ok) {
2477
+ return mapSsrfError(fetchResult);
2478
+ }
2479
+ const receipt = fetchResult.body;
2480
+ const contentType = fetchResult.contentType;
2481
+ const expectedContentTypes = ["application/jose", "application/json", "text/plain"];
2482
+ const contentTypeWarning = contentType && !expectedContentTypes.some((expected) => contentType.startsWith(expected)) ? `Unexpected Content-Type: ${contentType}; expected application/jose, application/json, or text/plain` : void 0;
2483
+ if (!receipt || receipt.trim().length === 0) {
2484
+ return {
2485
+ ok: false,
2486
+ reason: "malformed_receipt",
2487
+ errorCode: "E_VERIFY_MALFORMED_RECEIPT",
2488
+ message: "Pointer target returned empty content"
2489
+ };
2490
+ }
2491
+ const jwsValidation = validateJwsCompactStructure(receipt);
2492
+ if (!jwsValidation.valid) {
2493
+ return {
2494
+ ok: false,
2495
+ reason: "malformed_receipt",
2496
+ errorCode: "E_VERIFY_MALFORMED_RECEIPT",
2497
+ message: jwsValidation.message
2498
+ };
2499
+ }
2500
+ const actualDigest = await sha256Hex(receipt);
2501
+ if (actualDigest !== expectedDigest) {
2502
+ return {
2503
+ ok: false,
2504
+ reason: "pointer_digest_mismatch",
2505
+ errorCode: "E_VERIFY_POINTER_DIGEST_MISMATCH",
2506
+ message: "Fetched receipt digest does not match expected digest",
2507
+ actualDigest,
2508
+ expectedDigest
2509
+ };
2510
+ }
2511
+ return {
2512
+ ok: true,
2513
+ receipt,
2514
+ actualDigest,
2515
+ digestMatched: true,
2516
+ contentType: fetchResult.contentType,
2517
+ ...contentTypeWarning && { contentTypeWarning }
2518
+ };
2519
+ }
2520
+ function validateJwsCompactStructure(value) {
2521
+ const segments = value.split(".");
2522
+ if (segments.length !== 3) {
2523
+ return {
2524
+ valid: false,
2525
+ message: `Invalid JWS compact serialization: expected 3 segments, got ${segments.length}`
2526
+ };
2527
+ }
2528
+ const base64urlRegex = /^[A-Za-z0-9_-]+$/;
2529
+ for (let i = 0; i < segments.length; i++) {
2530
+ const segment = segments[i];
2531
+ if (segment.length === 0) {
2532
+ return {
2533
+ valid: false,
2534
+ message: `Invalid JWS compact serialization: segment ${i + 1} is empty`
2535
+ };
2536
+ }
2537
+ if (!base64urlRegex.test(segment)) {
2538
+ return {
2539
+ valid: false,
2540
+ message: `Invalid JWS compact serialization: segment ${i + 1} contains invalid characters`
2541
+ };
2542
+ }
2543
+ }
2544
+ return { valid: true };
2545
+ }
2546
+ function parsePointerHeader(input) {
2547
+ const params = {};
2548
+ let i = 0;
2549
+ const len = input.length;
2550
+ while (i < len) {
2551
+ while (i < len && (input[i] === " " || input[i] === "," || input[i] === " ")) {
2552
+ i++;
2553
+ }
2554
+ if (i >= len) break;
2555
+ const keyStart = i;
2556
+ while (i < len && /\w/.test(input[i])) {
2557
+ i++;
2558
+ }
2559
+ const key = input.slice(keyStart, i);
2560
+ if (!key) break;
2561
+ while (i < len && input[i] === " ") i++;
2562
+ if (i >= len || input[i] !== "=") break;
2563
+ i++;
2564
+ while (i < len && input[i] === " ") i++;
2565
+ let value;
2566
+ if (input[i] === '"') {
2567
+ i++;
2568
+ const valueStart = i;
2569
+ while (i < len && input[i] !== '"') {
2570
+ i++;
2571
+ }
2572
+ value = input.slice(valueStart, i);
2573
+ if (i < len) i++;
2574
+ } else {
2575
+ const valueStart = i;
2576
+ while (i < len && input[i] !== "," && input[i] !== " " && input[i] !== " ") {
2577
+ i++;
2578
+ }
2579
+ value = input.slice(valueStart, i);
2580
+ }
2581
+ params[key] = value;
2582
+ }
2583
+ return params;
2584
+ }
2585
+ async function verifyAndFetchPointer(pointerHeader, fetchOptions) {
2586
+ const params = parsePointerHeader(pointerHeader);
2587
+ if (!params.sha256) {
2588
+ return {
2589
+ ok: false,
2590
+ reason: "pointer_fetch_failed",
2591
+ errorCode: "E_VERIFY_POINTER_FETCH_FAILED",
2592
+ message: "PEAC-Receipt-Pointer missing sha256 parameter"
2593
+ };
2594
+ }
2595
+ if (!params.url) {
2596
+ return {
2597
+ ok: false,
2598
+ reason: "pointer_fetch_failed",
2599
+ errorCode: "E_VERIFY_POINTER_FETCH_FAILED",
2600
+ message: "PEAC-Receipt-Pointer missing url parameter"
2601
+ };
2602
+ }
2603
+ return fetchPointerWithDigest({
2604
+ url: params.url,
2605
+ expectedDigest: params.sha256,
2606
+ fetchOptions
2607
+ });
2608
+ }
2609
+
2610
+ export { CHECK_IDS, DEFAULT_NETWORK_SECURITY, DEFAULT_VERIFIER_LIMITS, IssueError, NON_DETERMINISTIC_ARTIFACT_KEYS, VerificationReportBuilder, buildFailureReport, buildSuccessReport, clearJWKSCache, computeReceiptDigest, createDefaultPolicy, createDigest, createEmptyReport, createReportBuilder, fetchDiscovery, fetchIssuerConfig, fetchJWKSSafe, fetchPointerSafe, fetchPointerWithDigest, fetchPolicyManifest, getJWKSCacheSize, getPurposeHeader, getReceiptHeader, getSSRFCapabilities, isAttestationResult, isBlockedIP, isCommerceResult, issue, issueJws, parseBodyProfile, parseDiscovery, parseHeaderProfile, parseIssuerConfig, parsePointerProfile, parsePolicyManifest, parseTransportProfile, reasonCodeToErrorCode, reasonCodeToSeverity, resetSSRFCapabilitiesCache, setPurposeAppliedHeader, setPurposeReasonHeader, setReceiptHeader, setVaryHeader, setVaryPurposeHeader, ssrfErrorToReasonCode, ssrfSafeFetch, verifyAndFetchPointer, verifyLocal, verifyReceipt, verifyReceiptCore };
2611
+ //# sourceMappingURL=index.mjs.map
2612
+ //# sourceMappingURL=index.mjs.map