@chitmark/sdk 0.6.5 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/edge.cjs CHANGED
@@ -1,5 +1,96 @@
1
1
  'use strict';
2
2
 
3
+ // src/attribution.ts
4
+ function attributionEvidence(options, mode) {
5
+ const { request, agentProof, session, piiMode = mode } = options;
6
+ const headers = request.headers;
7
+ const header = typeof headers.get === "function" ? headers.get("chitmark-agent-proof") : Object.entries(headers).find(
8
+ ([name]) => name.toLowerCase() === "chitmark-agent-proof"
9
+ )?.[1];
10
+ let site = options.site;
11
+ if (!site && request.url?.startsWith("https://")) site = new URL(request.url).origin;
12
+ let proof = agentProof;
13
+ if (!proof && typeof header === "string" && header.length <= 2048 && site) {
14
+ try {
15
+ proof = JSON.parse(header);
16
+ } catch {
17
+ }
18
+ }
19
+ return { site, session, piiMode, agentProof: proof };
20
+ }
21
+
22
+ // src/credentials.ts
23
+ var encode = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
24
+ var json = (value) => encode(new TextEncoder().encode(JSON.stringify(value)));
25
+ async function boundedCredential(work, signal) {
26
+ signal.throwIfAborted();
27
+ let abort;
28
+ const aborted = new Promise((_, reject) => {
29
+ abort = () => reject(new Error("Credential deadline exceeded"));
30
+ signal.addEventListener("abort", abort, { once: true });
31
+ });
32
+ try {
33
+ return await Promise.race([work, aborted]);
34
+ } finally {
35
+ signal.removeEventListener("abort", abort);
36
+ }
37
+ }
38
+ function createDPoPCredentialProvider(options) {
39
+ const { privateKey, publicJwk } = options;
40
+ if (publicJwk.d || publicJwk.kty !== "EC" || publicJwk.crv !== "P-256" || !publicJwk.x || !publicJwk.y)
41
+ throw new Error("DPoP requires a public P-256 JWK");
42
+ const jwk = { kty: "EC", crv: "P-256", x: publicJwk.x, y: publicJwk.y };
43
+ let cached;
44
+ let pending;
45
+ const valid = (c) => !!c && typeof c.accessToken === "string" && /^[\w-]+\.[\w-]+\.[\w-]+$/.test(c.accessToken) && [c.expiresAt, c.trustExpiresAt, c.revocationValidUntil].every(
46
+ (v) => Number.isSafeInteger(v) && v > Date.now() / 1e3 + 1
47
+ );
48
+ return {
49
+ async headers({ url, method, signal }) {
50
+ signal.throwIfAborted();
51
+ const target = new URL(url);
52
+ if (target.protocol !== "https:" || target.username || target.password)
53
+ throw new Error("DPoP requires HTTPS");
54
+ if (!valid(cached)) {
55
+ if (!pending) {
56
+ const refreshSignal = AbortSignal.timeout(options.refreshTimeoutMs ?? 500);
57
+ pending = Promise.resolve().then(() => options.load(refreshSignal)).then((c) => {
58
+ if (!valid(c) || refreshSignal.aborted) throw new Error("Stale credential");
59
+ cached = { ...c };
60
+ return cached;
61
+ }).finally(() => {
62
+ pending = void 0;
63
+ });
64
+ }
65
+ await boundedCredential(
66
+ pending,
67
+ AbortSignal.any([signal, AbortSignal.timeout(options.refreshTimeoutMs ?? 500)])
68
+ );
69
+ }
70
+ if (!valid(cached)) throw new Error("Stale credential");
71
+ const credential = cached;
72
+ const token = credential.accessToken;
73
+ const ath = encode(
74
+ new Uint8Array(
75
+ await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token))
76
+ )
77
+ );
78
+ const payload = `${json({ typ: "dpop+jwt", alg: "ES256", jwk })}.${json({ jti: crypto.randomUUID(), iat: Math.floor(Date.now() / 1e3), htm: method.toUpperCase(), htu: `${target.origin}${target.pathname}`, ath })}`;
79
+ const signature = await crypto.subtle.sign(
80
+ { name: "ECDSA", hash: "SHA-256" },
81
+ privateKey,
82
+ new TextEncoder().encode(payload)
83
+ );
84
+ signal.throwIfAborted();
85
+ if (!valid(credential)) throw new Error("Stale credential");
86
+ return {
87
+ Authorization: `DPoP ${token}`,
88
+ DPoP: `${payload}.${encode(new Uint8Array(signature))}`
89
+ };
90
+ }
91
+ };
92
+ }
93
+
3
94
  // src/errors.ts
4
95
  var ChitmarkError = class extends Error {
5
96
  name = "ChitmarkError";
@@ -62,7 +153,7 @@ var DEFAULT_BASE_URLS = {
62
153
  };
63
154
  var DEFAULT_TIMEOUT_MS = 800;
64
155
  var LOCAL_TIMEOUT_MS = 2e3;
65
- var SDK_VERSION = "0.6.5";
156
+ var SDK_VERSION = "0.8.0";
66
157
  function defaultTimeoutMs(baseUrl) {
67
158
  try {
68
159
  const host = new URL(baseUrl).hostname.replace(/^\[|\]$/g, "").toLowerCase();
@@ -125,11 +216,11 @@ function minimizeFormData(formData) {
125
216
  }
126
217
  function bufferToHex(buffer) {
127
218
  const bytes = new Uint8Array(buffer);
128
- let hex = "";
219
+ let hex2 = "";
129
220
  for (const b of bytes) {
130
- hex += b.toString(16).padStart(2, "0");
221
+ hex2 += b.toString(16).padStart(2, "0");
131
222
  }
132
- return hex;
223
+ return hex2;
133
224
  }
134
225
 
135
226
  // src/internal/prepare.ts
@@ -205,6 +296,46 @@ var VerdictTokenError = class extends ChitmarkError {
205
296
  var DEFAULT_JWKS_URL = "https://api.chitmark.com/.well-known/jwks.json";
206
297
  var DEFAULT_LEEWAY_SECONDS = 30;
207
298
  async function verifyVerdictToken(token, options) {
299
+ return verifyReceipt(token, options, "JWT");
300
+ }
301
+ var SENSITIVE_RECEIPT_ACTIONS = [
302
+ "api_key",
303
+ "data_export",
304
+ "session_establish",
305
+ "privilege_elevate",
306
+ "authenticator_replace",
307
+ "recovery_contact_change",
308
+ "session_use",
309
+ "privilege_change",
310
+ "release_deploy",
311
+ "bulk_mutation",
312
+ "commitment_change",
313
+ "agent_effect",
314
+ "agent_escalation",
315
+ "quote_generate",
316
+ "queue_priority"
317
+ ];
318
+ async function verifyActionReceipt(token, options) {
319
+ const claims = await verifyReceipt(
320
+ token,
321
+ {
322
+ ...options,
323
+ aud: options.audience,
324
+ issuer: VERDICT_TOKEN_ISSUER,
325
+ leewaySeconds: 0
326
+ },
327
+ "chitmark-action+jwt"
328
+ );
329
+ const now = Math.floor((options.nowMs ?? Date.now()) / 1e3);
330
+ if (!options.audience || !options.session || !options.tenantId || !options.policy || !/^[a-f0-9]{64}$/.test(options.digest) || !(options.action === "trial_activation" ? options.proof === "none" || options.proof === "pow_severe" : SENSITIVE_RECEIPT_ACTIONS.includes(options.action) && options.proof === "tenant_step_up" && typeof options.subject === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(options.subject) && claims.subject === options.subject) || claims.action !== options.action || options.environment !== "test" && options.environment !== "live" || claims.environment !== options.environment || !options.surface || claims.surface !== options.surface || claims.digest !== options.digest || claims.policy !== options.policy || claims.proof !== options.proof || claims.enforcementMode !== "enforce" || claims.decision !== "allow" || claims.degraded !== false || typeof claims.eventId !== "string" || !claims.eventId || !Number.isSafeInteger(claims.iat) || !Number.isSafeInteger(claims.exp) || claims.iat > now || claims.exp <= now || claims.exp - claims.iat !== 60) {
331
+ throw new VerdictTokenError(
332
+ "wrong_action_binding",
333
+ "Receipt cannot authorize this operation"
334
+ );
335
+ }
336
+ return claims;
337
+ }
338
+ async function verifyReceipt(token, options, expectedType) {
208
339
  const nowMs = options.nowMs ?? Date.now();
209
340
  const leewaySeconds = options.leewaySeconds ?? DEFAULT_LEEWAY_SECONDS;
210
341
  const parts = token.split(".");
@@ -226,10 +357,10 @@ async function verifyVerdictToken(token, options) {
226
357
  `verdictToken must use ES256, got ${String(header["alg"])}`
227
358
  );
228
359
  }
229
- if (header["typ"] !== "JWT") {
360
+ if (header["typ"] !== expectedType) {
230
361
  throw new VerdictTokenError(
231
362
  "wrong_type",
232
- `verdictToken must be a JWT, got ${String(header["typ"])}`
363
+ `verdictToken must have type ${expectedType}, got ${String(header["typ"])}`
233
364
  );
234
365
  }
235
366
  const kid = typeof header["kid"] === "string" ? header["kid"] : "";
@@ -275,6 +406,12 @@ async function verifyVerdictToken(token, options) {
275
406
  if (!jwk) {
276
407
  throw new VerdictTokenError("unknown_kid", `JWKS has no key for kid ${kid}`);
277
408
  }
409
+ if (jwk["kty"] !== "EC" || jwk["crv"] !== "P-256" || jwk["alg"] !== void 0 && jwk["alg"] !== "ES256") {
410
+ throw new VerdictTokenError(
411
+ "wrong_algorithm",
412
+ "Verification requires an ES256 P-256 key"
413
+ );
414
+ }
278
415
  let publicKey;
279
416
  try {
280
417
  publicKey = await crypto.subtle.importKey(
@@ -347,7 +484,27 @@ function decodeBase64UrlBytes(value) {
347
484
 
348
485
  // src/client.ts
349
486
  var Chitmark = class {
487
+ attribution = {
488
+ resolve: (input) => this.request("/v1/attributions/resolve", {
489
+ method: "POST",
490
+ body: attributionEvidence(input, this.piiMode),
491
+ idempotencyKey: input.idempotencyKey
492
+ }),
493
+ get: (id2) => this.request(`/v1/attributions/${encodeURIComponent(id2)}`, { method: "GET" }),
494
+ createLink: (input, idempotencyKey) => this.request("/v1/identity-links", { method: "POST", body: input, idempotencyKey }),
495
+ revokeLink: (id2) => this.request(`/v1/identity-links/${encodeURIComponent(id2)}`, { method: "DELETE" })
496
+ };
497
+ /** Paid access lifecycle. Transport uncertainty must be resumed, never treated as payment. */
498
+ async charge(request) {
499
+ return this.request("/v1/charge", {
500
+ method: "POST",
501
+ body: request,
502
+ idempotencyKey: request.idempotencyKey,
503
+ timeoutMs: Math.max(this.timeoutMs, 15e3)
504
+ });
505
+ }
350
506
  apiKey;
507
+ credentialProvider;
351
508
  baseUrl;
352
509
  timeoutMs;
353
510
  piiMode;
@@ -355,7 +512,7 @@ var Chitmark = class {
355
512
  fetchImpl;
356
513
  clientName;
357
514
  constructor(options) {
358
- if (!options.apiKey) {
515
+ if (!!options.apiKey === !!options.credentialProvider) {
359
516
  throw new ChitmarkError("Chitmark apiKey is required");
360
517
  }
361
518
  if (options.onDegraded && options.onDegraded !== "challenge") {
@@ -364,6 +521,7 @@ var Chitmark = class {
364
521
  );
365
522
  }
366
523
  this.apiKey = options.apiKey;
524
+ this.credentialProvider = options.credentialProvider;
367
525
  this.baseUrl = resolveBaseUrl(options.env, options.baseUrl ?? envBaseUrl());
368
526
  this.timeoutMs = options.timeoutMs ?? defaultTimeoutMs(this.baseUrl);
369
527
  this.piiMode = options.piiMode ?? "hashed";
@@ -456,7 +614,8 @@ var Chitmark = class {
456
614
  /**
457
615
  * Complete a challenge by submitting its solved proof. Clears only the bound
458
616
  * session, once. Does not authorize the action: re-verify with
459
- * `context.challengeId` and proceed only on non-degraded allow.
617
+ * `context.challengeId` for standalone challenges or the original action
618
+ * binding plus the challenge and event IDs for operation-bound challenges.
460
619
  */
461
620
  async completeChallenge(request) {
462
621
  return this.request("/v1/challenge", {
@@ -484,15 +643,35 @@ var Chitmark = class {
484
643
  */
485
644
  async request(path, init) {
486
645
  const controller = new AbortController();
487
- const timer = setTimeout(() => controller.abort(), this.timeoutMs);
646
+ const timeoutMs = init.timeoutMs ?? this.timeoutMs;
647
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
488
648
  try {
489
649
  const headers = {
490
- Authorization: `Bearer ${this.apiKey}`,
650
+ ...this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {},
491
651
  "Content-Type": "application/json",
492
652
  Accept: "application/json",
493
653
  "User-Agent": this.clientName,
494
654
  "X-Chitmark-Client": this.clientName
495
655
  };
656
+ if (this.credentialProvider) {
657
+ try {
658
+ Object.assign(
659
+ headers,
660
+ await boundedCredential(
661
+ this.credentialProvider.headers({
662
+ url: `${this.baseUrl}${path}`,
663
+ method: init.method,
664
+ signal: controller.signal
665
+ }),
666
+ controller.signal
667
+ )
668
+ );
669
+ } catch {
670
+ throw new ChitmarkError("Credential unavailable", { code: "credential" });
671
+ }
672
+ if (!headers.Authorization?.startsWith("DPoP ") || !headers.DPoP)
673
+ throw new ChitmarkError("Invalid DPoP credentials");
674
+ }
496
675
  if (init.idempotencyKey) {
497
676
  headers["Idempotency-Key"] = init.idempotencyKey;
498
677
  }
@@ -500,7 +679,8 @@ var Chitmark = class {
500
679
  method: init.method,
501
680
  headers,
502
681
  body: init.body !== void 0 ? JSON.stringify(init.body) : void 0,
503
- signal: controller.signal
682
+ signal: controller.signal,
683
+ redirect: "error"
504
684
  });
505
685
  const text = await res.text();
506
686
  let parsed = void 0;
@@ -524,7 +704,7 @@ var Chitmark = class {
524
704
  } catch (err) {
525
705
  if (err instanceof ChitmarkApiError) throw err;
526
706
  if (err instanceof Error && err.name === "AbortError") {
527
- throw new ChitmarkError(`Request timed out after ${this.timeoutMs}ms`, {
707
+ throw new ChitmarkError(`Request timed out after ${timeoutMs}ms`, {
528
708
  code: "timeout"
529
709
  });
530
710
  }
@@ -594,6 +774,371 @@ function verdictToHttpStatus(verdict) {
594
774
  return CHITMARK_HTTP_STATUS.ok;
595
775
  }
596
776
 
777
+ // src/action-binding.ts
778
+ var opaqueId = /^[A-Za-z0-9_.:-]{1,128}$/;
779
+ async function trialCreditOperationDigest(operation) {
780
+ const { operationId, target, quota, recipient } = operation;
781
+ if (Object.keys(operation).some(
782
+ (key) => !["operationId", "target", "quota", "recipient"].includes(key)
783
+ ) || typeof operationId !== "string" || !opaqueId.test(operationId) || typeof target !== "string" || !opaqueId.test(target) || !Number.isSafeInteger(quota) || quota < 1 || recipient !== void 0 && (typeof recipient !== "string" || !opaqueId.test(recipient))) {
784
+ throw new TypeError("Invalid trial credit operation");
785
+ }
786
+ const bytes = new TextEncoder().encode(
787
+ JSON.stringify([
788
+ "chitmark-action-v1",
789
+ "trial_activation",
790
+ operationId,
791
+ target,
792
+ quota,
793
+ recipient ?? null
794
+ ])
795
+ );
796
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
797
+ return Array.from(
798
+ new Uint8Array(digest),
799
+ (byte) => byte.toString(16).padStart(2, "0")
800
+ ).join("");
801
+ }
802
+
803
+ // src/evidence.ts
804
+ var EvidenceError = class extends Error {
805
+ constructor(code) {
806
+ super(code);
807
+ this.code = code;
808
+ this.name = "EvidenceError";
809
+ }
810
+ code;
811
+ };
812
+ function evidenceAssert(value, code) {
813
+ if (!value) throw new EvidenceError(code);
814
+ }
815
+ function canonicalEvidence(value) {
816
+ if (value === null || typeof value === "boolean") return JSON.stringify(value);
817
+ if (typeof value === "number") {
818
+ evidenceAssert(
819
+ Number.isSafeInteger(value) && !Object.is(value, -0),
820
+ "noncanonical_number"
821
+ );
822
+ return String(value);
823
+ }
824
+ if (typeof value === "string") {
825
+ evidenceAssert(/^[\x20-\x7e]*$/.test(value), "noncanonical_string");
826
+ return JSON.stringify(value);
827
+ }
828
+ if (Array.isArray(value)) return `[${value.map(canonicalEvidence).join(",")}]`;
829
+ evidenceAssert(
830
+ value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype,
831
+ "noncanonical_object"
832
+ );
833
+ const obj = value;
834
+ return `{${Object.keys(obj).sort().map((key) => `${canonicalEvidence(key)}:${canonicalEvidence(obj[key])}`).join(",")}}`;
835
+ }
836
+ async function evidenceHash(value) {
837
+ return Array.from(
838
+ new Uint8Array(
839
+ await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value))
840
+ ),
841
+ (b) => b.toString(16).padStart(2, "0")
842
+ ).join("");
843
+ }
844
+ var encode2 = (bytes) => btoa(Array.from(bytes, (b) => String.fromCharCode(b)).join("")).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
845
+ var decode = (part) => Uint8Array.from(
846
+ atob(part.replace(/-/g, "+").replace(/_/g, "/")),
847
+ (c) => c.charCodeAt(0)
848
+ );
849
+ function evidenceKeyAt(history, kid, at) {
850
+ const matches = history.filter((key2) => key2.kid === kid);
851
+ evidenceAssert(matches.length === 1, "unknown_trust_root");
852
+ const key = matches[0];
853
+ evidenceAssert(
854
+ key.jwk.kty === "EC" && key.jwk.crv === "P-256" && (!key.jwk.alg || key.jwk.alg === "ES256") && !key.jwk.d,
855
+ "unsupported_key"
856
+ );
857
+ evidenceAssert(
858
+ Number.isSafeInteger(at) && Number.isSafeInteger(key.notBefore) && Number.isSafeInteger(key.notAfter) && key.notBefore <= at && at < key.notAfter,
859
+ "key_outside_validity"
860
+ );
861
+ evidenceAssert(key.revokedAt === void 0, "revoked_key");
862
+ return key;
863
+ }
864
+ async function verifyEvidenceSignature(token, typ, history, at) {
865
+ evidenceAssert(
866
+ typeof token === "string" && token.length <= 8e6 && /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(token),
867
+ "malformed_signature"
868
+ );
869
+ const [h, p, s] = token.split(".");
870
+ let head, payload;
871
+ try {
872
+ head = JSON.parse(
873
+ new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(decode(h))
874
+ );
875
+ payload = JSON.parse(
876
+ new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(decode(p))
877
+ );
878
+ } catch {
879
+ throw new EvidenceError("malformed_signature");
880
+ }
881
+ evidenceAssert(
882
+ head?.alg === "ES256" && head.typ === typ && Object.keys(head).length === 3,
883
+ "unsupported_profile"
884
+ );
885
+ const trusted = evidenceKeyAt(history, head.kid, at);
886
+ const key = await crypto.subtle.importKey(
887
+ "jwk",
888
+ trusted.jwk,
889
+ { name: "ECDSA", namedCurve: "P-256" },
890
+ false,
891
+ ["verify"]
892
+ );
893
+ evidenceAssert(
894
+ await crypto.subtle.verify(
895
+ { name: "ECDSA", hash: "SHA-256" },
896
+ key,
897
+ decode(s),
898
+ new TextEncoder().encode(`${h}.${p}`)
899
+ ),
900
+ "invalid_signature"
901
+ );
902
+ evidenceAssert(
903
+ payload && typeof payload === "object" && !Array.isArray(payload),
904
+ "malformed_payload"
905
+ );
906
+ return payload;
907
+ }
908
+ async function signEvidence(payload, typ, kid, jwk) {
909
+ evidenceAssert(
910
+ jwk.kty === "EC" && jwk.crv === "P-256" && (!jwk.alg || jwk.alg === "ES256"),
911
+ "unsupported_key"
912
+ );
913
+ const input = `${encode2(new TextEncoder().encode(canonicalEvidence({ alg: "ES256", kid, typ })))}.${encode2(new TextEncoder().encode(canonicalEvidence(payload)))}`;
914
+ evidenceAssert(input.length + 87 <= 8e6, "bundle_too_large");
915
+ const key = await crypto.subtle.importKey(
916
+ "jwk",
917
+ jwk,
918
+ { name: "ECDSA", namedCurve: "P-256" },
919
+ false,
920
+ ["sign"]
921
+ );
922
+ return `${input}.${encode2(new Uint8Array(await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, key, new TextEncoder().encode(input))))}`;
923
+ }
924
+ var id = /^[A-Za-z0-9_.:/-]{1,160}$/;
925
+ function validateManifest(value, tenantId) {
926
+ evidenceAssert(
927
+ Object.keys(value).sort().join(",") === "completeness,createdAt,endAt,gaps,issuer,purpose,records,retention,sourceAsOf,startAt,tenantId,timeBasis,version" && Object.keys(value.retention).sort().join(",") === "deleteAfter,exportedCopies,recipient,redaction",
928
+ "unminimized_manifest"
929
+ );
930
+ canonicalEvidence(value);
931
+ evidenceAssert(
932
+ value.version === 1 && value.issuer === "https://portal.chitmark.com" && value.purpose === "historical_evidence" && value.tenantId === tenantId && id.test(tenantId),
933
+ "wrong_bundle_scope"
934
+ );
935
+ evidenceAssert(
936
+ [
937
+ value.startAt,
938
+ value.endAt,
939
+ value.createdAt,
940
+ value.sourceAsOf,
941
+ value.retention.deleteAfter
942
+ ].every(Number.isSafeInteger) && value.startAt < value.endAt && value.endAt <= value.sourceAsOf && value.sourceAsOf <= value.createdAt && value.createdAt < value.retention.deleteAfter,
943
+ "invalid_window"
944
+ );
945
+ evidenceAssert(
946
+ value.completeness === "unknown" && value.timeBasis === "issuer_and_ingestion_clocks_not_independent_time" && value.retention.redaction === "minimized" && value.retention.exportedCopies === "recipient_controlled" && id.test(value.retention.recipient) && Array.isArray(value.gaps) && value.gaps.every((gap) => id.test(gap)),
947
+ "invalid_manifest"
948
+ );
949
+ evidenceAssert(
950
+ Array.isArray(value.records) && value.records.length <= 1e4,
951
+ "record_limit"
952
+ );
953
+ const seen = /* @__PURE__ */ new Set();
954
+ for (const row of value.records) {
955
+ evidenceAssert(
956
+ Object.keys(row).sort().join(",") === "eventId,id,kind,occurredAt,policyRevision,receipt,recordedAt,result,source",
957
+ "unminimized_record"
958
+ );
959
+ evidenceAssert(
960
+ id.test(row.id) && id.test(row.eventId) && ["decision", "execution", "outcome"].includes(row.kind) && id.test(row.result) && (row.policyRevision === null || id.test(row.policyRevision)) && (row.receipt === null || typeof row.receipt === "string" && row.receipt.length <= 8192),
961
+ "invalid_record"
962
+ );
963
+ evidenceAssert(
964
+ Number.isSafeInteger(row.occurredAt) && Number.isSafeInteger(row.recordedAt) && value.startAt <= row.occurredAt && row.occurredAt < value.endAt && row.recordedAt <= value.sourceAsOf && row.recordedAt >= row.occurredAt && row.source === (row.kind === "decision" ? "decision_service" : "customer_report"),
965
+ "invalid_provenance"
966
+ );
967
+ const identity = `${row.kind}:${row.id}`;
968
+ evidenceAssert(!seen.has(identity), "duplicate_record");
969
+ seen.add(identity);
970
+ }
971
+ }
972
+ async function verifyEvidenceBundle(bundle, options) {
973
+ validateManifest(bundle.manifest, options.tenantId);
974
+ evidenceAssert(
975
+ bundle.manifest.retention.recipient === options.recipient,
976
+ "wrong_recipient"
977
+ );
978
+ evidenceAssert(
979
+ options.now < bundle.manifest.retention.deleteAfter && options.now >= bundle.manifest.createdAt,
980
+ "retention_expired"
981
+ );
982
+ const signed = await verifyEvidenceSignature(
983
+ bundle.signature,
984
+ "chitmark-evidence+jwt",
985
+ options.trustedKeys,
986
+ bundle.manifest.createdAt
987
+ );
988
+ evidenceAssert(
989
+ canonicalEvidence(signed) === canonicalEvidence(bundle.manifest),
990
+ "manifest_mismatch"
991
+ );
992
+ const head = JSON.parse(
993
+ new TextDecoder().decode(decode(bundle.signature.split(".")[0]))
994
+ );
995
+ evidenceAssert(
996
+ evidenceKeyAt(options.trustedKeys, head.kid, bundle.manifest.createdAt).compromisedAt === void 0,
997
+ "compromised_bundle_key"
998
+ );
999
+ return {
1000
+ purpose: "historical_evidence",
1001
+ executionAuthorized: false,
1002
+ integrity: "valid",
1003
+ completeness: "unknown",
1004
+ outcomeTruth: "not_established",
1005
+ gaps: bundle.manifest.gaps
1006
+ };
1007
+ }
1008
+ async function verifyHistoricalReceipt(token, options) {
1009
+ evidenceAssert(
1010
+ typeof token === "string" && token.length <= 8192,
1011
+ "malformed_signature"
1012
+ );
1013
+ let claims, head;
1014
+ try {
1015
+ const parts = token.split(".");
1016
+ head = JSON.parse(new TextDecoder().decode(decode(parts[0])));
1017
+ claims = JSON.parse(new TextDecoder().decode(decode(parts[1])));
1018
+ } catch {
1019
+ throw new EvidenceError("malformed_signature");
1020
+ }
1021
+ evidenceAssert(
1022
+ head.typ === "JWT" || head.typ === "chitmark-action+jwt",
1023
+ "unsupported_profile"
1024
+ );
1025
+ evidenceAssert(
1026
+ Number.isSafeInteger(claims.iat) && Number.isSafeInteger(claims.exp) && Number(claims.iat) < Number(claims.exp) && Number(claims.exp) - Number(claims.iat) <= (head.typ === "JWT" ? 300 : 60),
1027
+ "invalid_receipt_time"
1028
+ );
1029
+ const at = Number(claims.iat);
1030
+ evidenceAssert(
1031
+ typeof claims.eventId === "string" && /^[A-Za-z0-9_-]{1,160}$/.test(claims.eventId),
1032
+ "invalid_receipt_context"
1033
+ );
1034
+ const trusted = evidenceKeyAt(options.trustedKeys, String(head.kid), at);
1035
+ claims = await verifyEvidenceSignature(
1036
+ token,
1037
+ String(head.typ),
1038
+ options.trustedKeys,
1039
+ at
1040
+ );
1041
+ evidenceAssert(
1042
+ claims.tid === options.tenantId && claims.sub === options.session && claims.iss === "https://api.chitmark.com",
1043
+ "wrong_receipt_scope"
1044
+ );
1045
+ const witnessed = options.witness && Number.isSafeInteger(options.witness.observedAt) && options.witness.observedAt >= at && options.witness.tokenHash === await evidenceHash(token);
1046
+ const beforeCompromise = witnessed && (trusted.compromisedAt === void 0 || options.witness.observedAt < trusted.compromisedAt);
1047
+ return {
1048
+ purpose: "historical_evidence",
1049
+ executionAuthorized: false,
1050
+ eventId: String(claims.eventId),
1051
+ policyRevision: typeof claims.policy === "string" ? claims.policy : null,
1052
+ timeIntegrity: beforeCompromise ? "independently_checkpointed" : trusted.compromisedAt !== void 0 ? "uncertain_after_compromise" : "self_asserted"
1053
+ };
1054
+ }
1055
+
1056
+ // src/evidence-checkpoint.ts
1057
+ var hex = /^[a-f0-9]{64}$/;
1058
+ function scope(checkpoint, tenantId, now) {
1059
+ evidenceAssert(
1060
+ checkpoint.version === 1 && checkpoint.tenantId === tenantId && /^[A-Za-z0-9_-]{16,128}$/.test(checkpoint.epoch) && Number.isSafeInteger(checkpoint.expiresAt) && now < checkpoint.expiresAt && Number.isSafeInteger(checkpoint.observedAt) && checkpoint.observedAt <= now && checkpoint.observedAt < checkpoint.expiresAt && Number.isSafeInteger(checkpoint.size) && checkpoint.size >= 0 && checkpoint.size <= 1e4 && hex.test(checkpoint.root),
1061
+ "checkpoint_scope_or_expiry"
1062
+ );
1063
+ }
1064
+ var genesis = (cp) => evidenceHash(
1065
+ canonicalEvidence(["chitmark-private-chain-v1", cp.tenantId, cp.epoch, cp.expiresAt])
1066
+ );
1067
+ var evidenceCommitment = (cp, record, salt) => {
1068
+ evidenceAssert(hex.test(salt), "invalid_commitment_salt");
1069
+ return evidenceHash(
1070
+ canonicalEvidence([
1071
+ "chitmark-record-v1",
1072
+ cp.tenantId,
1073
+ cp.epoch,
1074
+ cp.expiresAt,
1075
+ salt,
1076
+ record
1077
+ ])
1078
+ );
1079
+ };
1080
+ var advance = (root, leaf, index) => evidenceHash(canonicalEvidence(["chitmark-append-v1", index, root, leaf]));
1081
+ async function checkpointFromCommitments(input) {
1082
+ evidenceAssert(
1083
+ input.commitments.length <= 1e4 && input.commitments.every((leaf) => hex.test(leaf)),
1084
+ "invalid_commitments"
1085
+ );
1086
+ let root = await genesis(input);
1087
+ for (let index = 0; index < input.commitments.length; index++)
1088
+ root = await advance(root, input.commitments[index], index);
1089
+ const cp = {
1090
+ version: 1,
1091
+ tenantId: input.tenantId,
1092
+ epoch: input.epoch,
1093
+ expiresAt: input.expiresAt,
1094
+ observedAt: input.observedAt,
1095
+ size: input.commitments.length,
1096
+ root
1097
+ };
1098
+ scope(cp, input.tenantId, input.observedAt);
1099
+ return cp;
1100
+ }
1101
+ async function verifyCheckpointAppend(older, newer, appended, options) {
1102
+ scope(older, options.tenantId, options.now);
1103
+ scope(newer, options.tenantId, options.now);
1104
+ if (older.size === 0)
1105
+ evidenceAssert(older.root === await genesis(older), "invalid_empty_checkpoint");
1106
+ evidenceAssert(
1107
+ older.epoch === newer.epoch && older.expiresAt === newer.expiresAt && older.observedAt <= newer.observedAt && older.size <= newer.size,
1108
+ "inconsistent_checkpoint"
1109
+ );
1110
+ if (older.size === newer.size)
1111
+ evidenceAssert(older.root === newer.root, "divergent_history");
1112
+ if (appended === null)
1113
+ return { status: "unavailable", completeness: "unknown" };
1114
+ evidenceAssert(
1115
+ appended.length === newer.size - older.size && appended.every((leaf) => hex.test(leaf)),
1116
+ "invalid_append_proof"
1117
+ );
1118
+ let root = older.root;
1119
+ for (let index = 0; index < appended.length; index++)
1120
+ root = await advance(root, appended[index], older.size + index);
1121
+ evidenceAssert(root === newer.root, "divergent_history");
1122
+ return { status: "consistent", completeness: "unknown" };
1123
+ }
1124
+ async function verifyCheckpointInclusion(checkpoint, proof, options) {
1125
+ scope(checkpoint, options.tenantId, options.now);
1126
+ if (!proof) return { status: "unavailable", completeness: "unknown" };
1127
+ evidenceAssert(
1128
+ Number.isSafeInteger(proof.index) && proof.index >= 0 && proof.index < checkpoint.size && proof.commitments.length === checkpoint.size,
1129
+ "invalid_inclusion_proof"
1130
+ );
1131
+ const rebuilt = await checkpointFromCommitments({
1132
+ ...checkpoint,
1133
+ commitments: proof.commitments
1134
+ });
1135
+ evidenceAssert(
1136
+ rebuilt.root === checkpoint.root && await evidenceCommitment(checkpoint, proof.record, proof.salt) === proof.commitments[proof.index],
1137
+ "changed_record"
1138
+ );
1139
+ return { status: "included", completeness: "unknown" };
1140
+ }
1141
+
597
1142
  // src/edge.ts
598
1143
  var ChitmarkEdge = class extends Chitmark {
599
1144
  /**
@@ -630,16 +1175,34 @@ exports.ChitmarkApiError = ChitmarkApiError;
630
1175
  exports.ChitmarkCore = Chitmark;
631
1176
  exports.ChitmarkEdge = ChitmarkEdge;
632
1177
  exports.ChitmarkError = ChitmarkError;
1178
+ exports.EvidenceError = EvidenceError;
1179
+ exports.SENSITIVE_RECEIPT_ACTIONS = SENSITIVE_RECEIPT_ACTIONS;
633
1180
  exports.VERDICT_TOKEN_ISSUER = VERDICT_TOKEN_ISSUER;
634
1181
  exports.VerdictTokenError = VerdictTokenError;
1182
+ exports.canonicalEvidence = canonicalEvidence;
1183
+ exports.checkpointFromCommitments = checkpointFromCommitments;
1184
+ exports.createDPoPCredentialProvider = createDPoPCredentialProvider;
635
1185
  exports.degradedChallengeVerdict = degradedChallengeVerdict;
636
1186
  exports.enforceDegradedNeverAllow = enforceDegradedNeverAllow;
1187
+ exports.evidenceAssert = evidenceAssert;
1188
+ exports.evidenceCommitment = evidenceCommitment;
1189
+ exports.evidenceHash = evidenceHash;
1190
+ exports.evidenceKeyAt = evidenceKeyAt;
637
1191
  exports.getTrustedClientIp = getTrustedClientIp;
638
1192
  exports.hashEmailSha256 = hashEmailSha256;
639
1193
  exports.isEligibleAllow = isEligibleAllow;
640
1194
  exports.minimizeFormData = minimizeFormData;
1195
+ exports.signEvidence = signEvidence;
1196
+ exports.trialCreditOperationDigest = trialCreditOperationDigest;
641
1197
  exports.truncateIp = truncateIp;
1198
+ exports.validateManifest = validateManifest;
642
1199
  exports.verdictToHttpStatus = verdictToHttpStatus;
1200
+ exports.verifyActionReceipt = verifyActionReceipt;
1201
+ exports.verifyCheckpointAppend = verifyCheckpointAppend;
1202
+ exports.verifyCheckpointInclusion = verifyCheckpointInclusion;
1203
+ exports.verifyEvidenceBundle = verifyEvidenceBundle;
1204
+ exports.verifyEvidenceSignature = verifyEvidenceSignature;
1205
+ exports.verifyHistoricalReceipt = verifyHistoricalReceipt;
643
1206
  exports.verifyVerdictToken = verifyVerdictToken;
644
1207
  //# sourceMappingURL=edge.cjs.map
645
1208
  //# sourceMappingURL=edge.cjs.map