@chain-receipt/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/verify.js ADDED
@@ -0,0 +1,177 @@
1
+ /* Offline receipt verification (plan step 25).
2
+ verifyReceipt runs entirely locally: it recomputes the receipt
3
+ hash from the receipt object (RFC 8785 JCS + SHA-256) and checks
4
+ the Ed25519 signature against a public key — no network call, so
5
+ it works in a browser, in a test, or on a downloaded bundle.
6
+ The public key comes from the caller (hex, base64, or raw bytes)
7
+ or from the public key directory at /.well-known/receipt-keys.json
8
+ via fetchPublicKey — retired keys stay listed there so old
9
+ receipts keep verifying. */
10
+ import { base64ToBytes, bytesToBase64, hashBytesFromTag, hexToBytes, receiptHash, verifyMerkleProof as verifyMerkleProofCrypto, verifyReceiptContent as verifyContentCrypto, verifyReceiptSignature, } from "./crypto.js";
11
+ export const DEFAULT_BASE_URL = "https://chainreceipt.link";
12
+ /** The public verify-page URL for a receipt. */
13
+ export function getVerifyUrl(receiptId, baseUrl = DEFAULT_BASE_URL) {
14
+ return `${baseUrl.replace(/\/$/, "")}/verify/${receiptId}`;
15
+ }
16
+ /** Accept a public key as a 64-char hex string, a base64 string
17
+ * (44 chars, the form in /.well-known/receipt-keys.json), or raw
18
+ * 32 bytes. Throws on anything else. */
19
+ export function parsePublicKey(input) {
20
+ if (input instanceof Uint8Array) {
21
+ if (input.length !== 32) {
22
+ throw new Error(`public key must be 32 bytes, got ${input.length}`);
23
+ }
24
+ return input;
25
+ }
26
+ if (/^[0-9a-fA-F]{64}$/.test(input))
27
+ return hexToBytes(input);
28
+ const bytes = base64ToBytes(input);
29
+ if (bytes.length !== 32) {
30
+ throw new Error(`public key must decode to 32 bytes, got ${bytes.length}`);
31
+ }
32
+ return bytes;
33
+ }
34
+ /** Fetch the public signing-key directory and return the entry for
35
+ * `keyId`. Throws when the key is not listed. The directory is
36
+ * public and needs no auth. */
37
+ export async function fetchPublicKey(keyId, baseUrl = DEFAULT_BASE_URL, fetchFn = fetch) {
38
+ const url = `${baseUrl.replace(/\/$/, "")}/.well-known/receipt-keys.json`;
39
+ const res = await fetchFn(url, {
40
+ headers: { Accept: "application/json" },
41
+ });
42
+ if (!res.ok) {
43
+ throw new Error(`failed to fetch signing keys (${res.status} ${url})`);
44
+ }
45
+ const doc = (await res.json());
46
+ const entry = (doc.keys ?? []).find((k) => k.key_id === keyId);
47
+ if (!entry) {
48
+ throw new Error(`signing key ${keyId} is not published`);
49
+ }
50
+ return entry;
51
+ }
52
+ export function verifyReceipt(envelope, publicKey) {
53
+ if (typeof envelope !== "object" ||
54
+ envelope === null ||
55
+ typeof envelope.receipt !== "object" ||
56
+ envelope.receipt === null) {
57
+ throw new Error("verifyReceipt: envelope.receipt is missing");
58
+ }
59
+ const env = envelope;
60
+ const keyId = env.signature?.key_id ?? null;
61
+ const check = (key) => {
62
+ const reasons = [];
63
+ let hashValid = false;
64
+ let recomputedHash = "";
65
+ try {
66
+ recomputedHash = receiptHash(env.receipt);
67
+ hashValid = recomputedHash === env.receipt_hash;
68
+ if (!hashValid)
69
+ reasons.push("receipt_hash does not recompute");
70
+ }
71
+ catch (err) {
72
+ reasons.push(`receipt hash failed: ${err instanceof Error ? err.message : String(err)}`);
73
+ }
74
+ let signatureValid = false;
75
+ try {
76
+ const sigValue = env.signature?.value;
77
+ if (typeof sigValue !== "string" || sigValue.length === 0) {
78
+ reasons.push("envelope has no signature value");
79
+ }
80
+ else {
81
+ signatureValid = verifyReceiptSignature(env.receipt, sigValue, key);
82
+ if (!signatureValid)
83
+ reasons.push("signature does not verify");
84
+ }
85
+ }
86
+ catch {
87
+ reasons.push("signature check failed");
88
+ }
89
+ return {
90
+ valid: hashValid && signatureValid,
91
+ hashValid,
92
+ signatureValid,
93
+ receiptHash: typeof env.receipt_hash === "string" ? env.receipt_hash : "",
94
+ recomputedHash,
95
+ keyId,
96
+ reasons,
97
+ };
98
+ };
99
+ if (typeof publicKey === "string" || publicKey instanceof Uint8Array) {
100
+ let key;
101
+ try {
102
+ key = parsePublicKey(publicKey);
103
+ }
104
+ catch (err) {
105
+ return {
106
+ valid: false,
107
+ hashValid: false,
108
+ signatureValid: false,
109
+ receiptHash: typeof env.receipt_hash === "string" ? env.receipt_hash : "",
110
+ recomputedHash: "",
111
+ keyId,
112
+ reasons: [
113
+ `unusable public key: ${err instanceof Error ? err.message : String(err)}`,
114
+ ],
115
+ };
116
+ }
117
+ return check(key);
118
+ }
119
+ // No key passed: resolve it from the public directory by key_id.
120
+ const baseUrl = publicKey?.fetchFrom ?? DEFAULT_BASE_URL;
121
+ const fetchFn = publicKey?.fetchFn ?? fetch;
122
+ if (!keyId) {
123
+ return Promise.resolve({
124
+ valid: false,
125
+ hashValid: false,
126
+ signatureValid: false,
127
+ receiptHash: typeof env.receipt_hash === "string" ? env.receipt_hash : "",
128
+ recomputedHash: "",
129
+ keyId,
130
+ reasons: ["envelope has no signature key_id to resolve"],
131
+ });
132
+ }
133
+ return fetchPublicKey(keyId, baseUrl, fetchFn).then((entry) => check(parsePublicKey(entry.public_key)), (err) => ({
134
+ valid: false,
135
+ hashValid: false,
136
+ signatureValid: false,
137
+ receiptHash: typeof env.receipt_hash === "string" ? env.receipt_hash : "",
138
+ recomputedHash: "",
139
+ keyId,
140
+ reasons: [
141
+ `could not fetch public key ${keyId}: ${err instanceof Error ? err.message : String(err)}`,
142
+ ],
143
+ }));
144
+ }
145
+ /** Recompute the content hashes from the original prompt/response +
146
+ * salts and compare them to the receipt's commitments. The text
147
+ * never leaves the caller's machine. `promptBody` is the exact
148
+ * object the prompt commitment hashes: {messages, tools?,
149
+ * response_format?} — only the keys present in the request. */
150
+ export function verifyReceiptContent(receipt, salts, promptBody, responseJson) {
151
+ try {
152
+ return verifyContentCrypto(receipt, salts, promptBody, responseJson);
153
+ }
154
+ catch {
155
+ return false;
156
+ }
157
+ }
158
+ /** Verify a Merkle inclusion proof from an envelope's anchor block.
159
+ * `proof` steps carry "sha256:<hex>" hashes (the envelope form);
160
+ * `leafHash` and `root` accept the same tag form. */
161
+ export function verifyAnchorProof(leafHash, proof, root) {
162
+ try {
163
+ const steps = proof.map((step) => ({
164
+ side: step.side,
165
+ hash: hashBytesFromTag(step.hash),
166
+ }));
167
+ return verifyMerkleProofCrypto(hashBytesFromTag(leafHash), steps, hashBytesFromTag(root));
168
+ }
169
+ catch {
170
+ return false;
171
+ }
172
+ }
173
+ /** The base64 form of a public key (handy for logging/comparing). */
174
+ export function publicKeyToBase64(key) {
175
+ return bytesToBase64(key);
176
+ }
177
+ //# sourceMappingURL=verify.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify.js","sourceRoot":"","sources":["../src/verify.ts"],"names":[],"mappings":"AAAA;;;;;;;;8BAQ8B;AAC9B,OAAO,EACL,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,UAAU,EACV,WAAW,EACX,iBAAiB,IAAI,uBAAuB,EAC5C,oBAAoB,IAAI,mBAAmB,EAC3C,sBAAsB,GAEvB,MAAM,aAAa,CAAC;AAWrB,MAAM,CAAC,MAAM,gBAAgB,GAAG,2BAA2B,CAAC;AAE5D,gDAAgD;AAChD,MAAM,UAAU,YAAY,CAC1B,SAAiB,EACjB,UAAkB,gBAAgB;IAElC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,WAAW,SAAS,EAAE,CAAC;AAC7D,CAAC;AAED;;yCAEyC;AACzC,MAAM,UAAU,cAAc,CAC5B,KAA0B;IAE1B,IAAI,KAAK,YAAY,UAAU,EAAE,CAAC;QAChC,IAAI,KAAK,CAAC,MAAM,KAAK,EAAE,EAAE,CAAC;YACxB,MAAM,IAAI,KAAK,CACb,oCAAoC,KAAK,CAAC,MAAM,EAAE,CACnD,CAAC;QACJ,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,mBAAmB,CAAC,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,UAAU,CAAC,KAAK,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ChB,KAA0C,EAC1C,IAAY;IAEZ,IAAI,CAAC;QACH,MAAM,KAAK,GAAsB,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;YACpD,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,IAAI,EAAE,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC;SAClC,CAAC,CAAC,CAAC;QACJ,OAAO,uBAAuB,CAC5B,gBAAgB,CAAC,QAAQ,CAAC,EAC1B,KAAK,EACL,gBAAgB,CAAC,IAAI,CAAC,CACvB,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED,qEAAqE;AACrE,MAAM,UAAU,iBAAiB,CAAC,GAAe;IAC/C,OAAO,aAAa,CAAC,GAAG,CAAC,CAAC;AAC5B,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
+ "bugs": {
3
+ "url": "https://github.com/CinianStudios/chain-receipt/issues"
4
+ },
5
+ "dependencies": {
6
+ "@noble/ed25519": "^2.0.0",
7
+ "@noble/hashes": "^1.0.0",
8
+ "canonicalize": "^2.0.0"
9
+ },
10
+ "description": "Chain Receipt — verified AI output receipts (JavaScript/TypeScript client SDK)",
11
+ "devDependencies": {
12
+ "@types/react": "^19.0.0",
13
+ "@types/react-dom": "^19.0.0",
14
+ "react": "^19.0.0",
15
+ "react-dom": "^19.0.0",
16
+ "typescript": "^5.0.0",
17
+ "vitest": "^3.0.0"
18
+ },
19
+ "exports": {
20
+ ".": {
21
+ "default": "./dist/index.js",
22
+ "import": "./dist/index.js",
23
+ "types": "./dist/index.d.ts"
24
+ },
25
+ "./badge": {
26
+ "default": "./dist/badge.js",
27
+ "import": "./dist/badge.js",
28
+ "types": "./dist/badge.d.ts"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "homepage": "https://chainreceipt.link/docs",
37
+ "license": "MIT",
38
+ "main": "./dist/index.js",
39
+ "module": "./dist/index.js",
2
40
  "name": "@chain-receipt/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
41
+ "peerDependencies": {
42
+ "react": ">=16.8"
43
+ },
44
+ "peerDependenciesMeta": {
45
+ "react": {
46
+ "optional": true
47
+ }
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "repository": {
53
+ "type": "git",
54
+ "url": "https://github.com/CinianStudios/chain-receipt.git"
55
+ },
56
+ "type": "module",
57
+ "types": "./dist/index.d.ts",
58
+ "version": "0.1.0",
59
+ "scripts": {
60
+ "build": "tsc -p tsconfig.build.json",
61
+ "lint": "eslint src",
62
+ "test": "vitest run --passWithNoTests",
63
+ "typecheck": "tsc --noEmit"
64
+ }
6
65
  }