@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/LICENSE +21 -0
- package/README.md +151 -2
- package/dist/badge.d.ts +17 -0
- package/dist/badge.d.ts.map +1 -0
- package/dist/badge.js +6 -0
- package/dist/badge.js.map +1 -0
- package/dist/client.d.ts +119 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +223 -0
- package/dist/client.js.map +1 -0
- package/dist/crypto.d.ts +60 -0
- package/dist/crypto.d.ts.map +1 -0
- package/dist/crypto.js +286 -0
- package/dist/crypto.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/types.d.ts +169 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +8 -0
- package/dist/types.js.map +1 -0
- package/dist/verify.d.ts +46 -0
- package/dist/verify.d.ts.map +1 -0
- package/dist/verify.js +177 -0
- package/dist/verify.js.map +1 -0
- package/package.json +62 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cinian Studios Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,152 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @chain-receipt/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
JavaScript / TypeScript client for [Chain Receipt](https://chainreceipt.link) — verified AI output receipts. Every AI call through the Chain Receipt proxy returns a signed receipt; this SDK fetches receipts, parses them out of proxy responses, and verifies them **offline** (hash recompute + Ed25519 signature, no network).
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @chain-receipt/sdk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Requires Node 18+ (global `fetch`) or any modern browser. No runtime dependencies beyond `@noble/ed25519`, `@noble/hashes`, and `canonicalize` — no `Buffer`, no `node:crypto`, so the offline verify path runs in browsers as well as Node.
|
|
12
|
+
|
|
13
|
+
## Quickstart
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { ChainReceiptClient } from "@chain-receipt/sdk";
|
|
17
|
+
|
|
18
|
+
const client = new ChainReceiptClient({ apiKey: "crk_test_..." });
|
|
19
|
+
|
|
20
|
+
// 1. Call the proxy — the receipt comes back attached to the answer.
|
|
21
|
+
const { data, receipt } = await client.chatCompletions({
|
|
22
|
+
model: "openai/gpt-6-luna",
|
|
23
|
+
messages: [{ role: "user", content: "Say the word receipt." }],
|
|
24
|
+
max_tokens: 20,
|
|
25
|
+
});
|
|
26
|
+
// data.choices[0].message.content === "receipt"
|
|
27
|
+
// receipt.receipt_id, receipt.receipt_hash, receipt.salts, ...
|
|
28
|
+
|
|
29
|
+
// 2. Fetch the full envelope later.
|
|
30
|
+
const envelope = await client.getReceipt(receipt.receipt_id);
|
|
31
|
+
|
|
32
|
+
// 3. Verify it offline. The public key is fetched once from the
|
|
33
|
+
// public key directory; the crypto itself runs locally.
|
|
34
|
+
const result = await client.verifyReceipt(envelope);
|
|
35
|
+
console.log(result.valid); // true
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
If you already call the proxy with your own `fetch` (or with the OpenAI client pointed at the Chain Receipt base URL), pull the receipt out of the response yourself:
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
import { receiptFromResponse, receiptFromSseEvent } from "@chain-receipt/sdk";
|
|
42
|
+
|
|
43
|
+
// Non-streaming: the response JSON carries ai_receipt at the top level.
|
|
44
|
+
const receipt = receiptFromResponse(await res.json());
|
|
45
|
+
|
|
46
|
+
// Streaming: each SSE `data:` line — the ai_receipt event arrives
|
|
47
|
+
// just before [DONE].
|
|
48
|
+
for (const line of sseLines) {
|
|
49
|
+
const receipt = receiptFromSseEvent(line);
|
|
50
|
+
if (receipt) console.log("receipt:", receipt.receipt_id);
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Verify offline, with a key you already hold
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { verifyReceipt } from "@chain-receipt/sdk";
|
|
58
|
+
|
|
59
|
+
// Public key as base64 (the form in /.well-known/receipt-keys.json),
|
|
60
|
+
// 64-char hex, or raw 32 bytes.
|
|
61
|
+
const result = verifyReceipt(envelope, "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a");
|
|
62
|
+
// { valid: true, hashValid: true, signatureValid: true,
|
|
63
|
+
// receiptHash, recomputedHash, keyId, reasons: [] }
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`verifyReceipt` never throws on a bad receipt, a bad signature, or a bad key — those come back as `valid: false` with `reasons`. It throws only when the envelope has no receipt object at all.
|
|
67
|
+
|
|
68
|
+
## Prove the content, not just the signature
|
|
69
|
+
|
|
70
|
+
The receipt holds salted hashes of your prompt and the provider's response, not the text itself. Recompute them locally — the text never leaves your machine:
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
import { verifyReceiptContent } from "@chain-receipt/sdk";
|
|
74
|
+
|
|
75
|
+
// salts came back once in ai_receipt.salts — keep them with the receipt.
|
|
76
|
+
const ok = verifyReceiptContent(
|
|
77
|
+
envelope.receipt,
|
|
78
|
+
receipt.salts,
|
|
79
|
+
{ messages: [{ role: "user", content: "Say the word receipt." }] },
|
|
80
|
+
providerResponseJson,
|
|
81
|
+
);
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The prompt body is the exact object the commitment hashes: `{messages, tools?, response_format?}` — only the keys present in the request.
|
|
85
|
+
|
|
86
|
+
## List receipts
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
const page = await client.listReceipts({ status: "complete", limit: 50 });
|
|
90
|
+
for (const row of page.data) {
|
|
91
|
+
console.log(row.receipt_id, row.anchor_status, row.verify_url);
|
|
92
|
+
}
|
|
93
|
+
if (page.has_more) {
|
|
94
|
+
const next = await client.listReceipts({ cursor: page.next_cursor });
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Download a public bundle
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
// Public receipts only — no API key needed. A private receipt
|
|
102
|
+
// answers 404 here; use client.getReceipt for your own receipts.
|
|
103
|
+
const envelope = await client.downloadBundle("rcpt_...");
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Server-side verification (Merkle + Bitcoin)
|
|
107
|
+
|
|
108
|
+
The offline check covers hash + signature. The server also checks the Merkle inclusion proof and the Bitcoin anchor state:
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
const server = await client.verifyOnline({ envelope });
|
|
112
|
+
// { valid, checks: { hash, signature, content, merkle, bitcoin },
|
|
113
|
+
// anchor: { status: "confirmed" | "pending" | ... } }
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## React badge
|
|
117
|
+
|
|
118
|
+
```tsx
|
|
119
|
+
import { ReceiptBadge } from "@chain-receipt/sdk/badge";
|
|
120
|
+
|
|
121
|
+
<ReceiptBadge receiptId="rcpt_..." />
|
|
122
|
+
// <a href="https://chainreceipt.link/verify/rcpt_...">✓ Verified by Chain Receipt</a>
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
React is an optional peer dependency (`>=16.8`) — importing the client alone never pulls React in. The badge renders a plain link with no imposed styles; pass `className`, `label`, or `verifyUrl` to control it.
|
|
126
|
+
|
|
127
|
+
## API
|
|
128
|
+
|
|
129
|
+
| Export | What it does |
|
|
130
|
+
| --- | --- |
|
|
131
|
+
| `ChainReceiptClient` | `getReceipt`, `listReceipts`, `downloadBundle`, `chatCompletions`, `verifyReceipt`, `verifyOnline`, `getPublicKey`, `getVerifyUrl` |
|
|
132
|
+
| `receiptFromResponse` | `ai_receipt` block out of a proxy response JSON (or SSE event object) |
|
|
133
|
+
| `receiptFromSseEvent` | Receipt out of one SSE `data:` line |
|
|
134
|
+
| `verifyReceipt` | Offline hash + Ed25519 check (sync with a key, async resolving the key) |
|
|
135
|
+
| `verifyReceiptContent` | Salted prompt/response re-hash check |
|
|
136
|
+
| `verifyAnchorProof` | Merkle inclusion proof from an envelope's anchor block |
|
|
137
|
+
| `fetchPublicKey` | One entry of `/.well-known/receipt-keys.json` |
|
|
138
|
+
| `getVerifyUrl` | Public verify-page URL for a receipt |
|
|
139
|
+
| `ReceiptBadge` | React link to the verify page (`@chain-receipt/sdk/badge`) |
|
|
140
|
+
| Crypto utilities | `canonicalJson`, `receiptHash`, `signReceipt`, `verifyReceiptSignature`, `merkleRoot`, `merkleProof`, `verifyMerkleProof`, `saltedPromptHash`, `saltedResponseHash`, hex/base64 helpers |
|
|
141
|
+
|
|
142
|
+
Errors are `ChainReceiptError` with `.status` (HTTP status) and `.code` (API error code) when available.
|
|
143
|
+
|
|
144
|
+
## Correctness
|
|
145
|
+
|
|
146
|
+
The SDK's crypto is proven against the shared golden vectors in `packages/core/test-vectors/golden.json`: JCS (RFC 8785 §3.2.3), Ed25519 (RFC 8032 test 1), SHA-256 (FIPS 180-4), and the locked Merkle root (leaf `sha256(0x00||hash)`, node `sha256(0x01||L||R)`). Run them with `pnpm test`. Tamper tests flip one byte in the receipt, the signature, the prompt, and the Merkle proof — every one fails verification.
|
|
147
|
+
|
|
148
|
+
## Notes
|
|
149
|
+
|
|
150
|
+
- The SDK never stores or sends provider keys. A provider key is passed per chat call (`X-Provider-Key`) or saved on the portal Keys page.
|
|
151
|
+
- Receipts are hash-only by default: the envelope contains hashes, never your prompt or the answer. Keep the `salts` from `ai_receipt` — without them the content check cannot run, and they are returned exactly once.
|
|
152
|
+
- A genuine receipt is valid before its batch confirms on Bitcoin; `anchor.status` (`pending` → `submitted` → `confirmed`) is reported separately from `valid`.
|
package/dist/badge.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ReactNode } from "react";
|
|
2
|
+
export interface ReceiptBadgeProps {
|
|
3
|
+
/** The receipt id (rcpt_...). */
|
|
4
|
+
receiptId: string;
|
|
5
|
+
/** Full verify URL. Defaults to {baseUrl}/verify/{receiptId}. */
|
|
6
|
+
verifyUrl?: string;
|
|
7
|
+
/** Site base URL. Defaults to https://chainreceipt.link. */
|
|
8
|
+
baseUrl?: string;
|
|
9
|
+
/** Link text. Defaults to "Verified by Chain Receipt". */
|
|
10
|
+
label?: ReactNode;
|
|
11
|
+
/** CSS class for the <a>. */
|
|
12
|
+
className?: string;
|
|
13
|
+
/** Where the link opens. Defaults to a new tab. */
|
|
14
|
+
target?: "_blank" | "_self";
|
|
15
|
+
}
|
|
16
|
+
export declare function ReceiptBadge({ receiptId, verifyUrl, baseUrl, label, className, target, }: ReceiptBadgeProps): import("react").JSX.Element;
|
|
17
|
+
//# sourceMappingURL=badge.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"badge.d.ts","sourceRoot":"","sources":["../src/badge.tsx"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAEvC,MAAM,WAAW,iBAAiB;IAChC,iCAAiC;IACjC,SAAS,EAAE,MAAM,CAAC;IAClB,iEAAiE;IACjE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,4DAA4D;IAC5D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,0DAA0D;IAC1D,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,6BAA6B;IAC7B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,mDAAmD;IACnD,MAAM,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC;CAC7B;AAED,wBAAgB,YAAY,CAAC,EAC3B,SAAS,EACT,SAAS,EACT,OAAqC,EACrC,KAAmC,EACnC,SAAS,EACT,MAAiB,GAClB,EAAE,iBAAiB,+BAcnB"}
|
package/dist/badge.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
export function ReceiptBadge({ receiptId, verifyUrl, baseUrl = "https://chainreceipt.link", label = "Verified by Chain Receipt", className, target = "_blank", }) {
|
|
3
|
+
const href = verifyUrl ?? `${baseUrl.replace(/\/$/, "")}/verify/${receiptId}`;
|
|
4
|
+
return (_jsxs("a", { href: href, className: className, target: target, rel: target === "_blank" ? "noopener noreferrer" : undefined, "data-chain-receipt-badge": receiptId, children: ["\u2713 ", label] }));
|
|
5
|
+
}
|
|
6
|
+
//# sourceMappingURL=badge.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"badge.js","sourceRoot":"","sources":["../src/badge.tsx"],"names":[],"mappings":";AA2BA,MAAM,UAAU,YAAY,CAAC,EAC3B,SAAS,EACT,SAAS,EACT,OAAO,GAAG,2BAA2B,EACrC,KAAK,GAAG,2BAA2B,EACnC,SAAS,EACT,MAAM,GAAG,QAAQ,GACC;IAClB,MAAM,IAAI,GACR,SAAS,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,WAAW,SAAS,EAAE,CAAC;IACnE,OAAO,CACL,aACE,IAAI,EAAE,IAAI,EACV,SAAS,EAAE,SAAS,EACpB,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,SAAS,8BAClC,SAAS,wBAEhC,KAAK,IACN,CACL,CAAC;AACJ,CAAC"}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { fetchPublicKey, getVerifyUrl, verifyReceipt } from "./verify.js";
|
|
2
|
+
import type { AiReceiptSummary, PublicKeyEntry, ReceiptEnvelope, ReceiptListPage, ServerVerifyResult, VerifyResult } from "./types.js";
|
|
3
|
+
export { fetchPublicKey, getVerifyUrl, verifyReceipt };
|
|
4
|
+
/** Error from the Chain Receipt API (or from the network layer).
|
|
5
|
+
* `status` is the HTTP status when one was received; `code` is the
|
|
6
|
+
* API's error code when the body carried one. */
|
|
7
|
+
export declare class ChainReceiptError extends Error {
|
|
8
|
+
status: number | null;
|
|
9
|
+
code: string | null;
|
|
10
|
+
constructor(message: string, status?: number | null, code?: string | null);
|
|
11
|
+
/** Build an error from a failed fetch Response, reading the
|
|
12
|
+
* OpenAI-shaped {error: {message, code}} body when present. */
|
|
13
|
+
static fromResponse(res: Response, path: string): Promise<ChainReceiptError>;
|
|
14
|
+
}
|
|
15
|
+
export interface ChainReceiptClientOptions {
|
|
16
|
+
/** Chain Receipt API key (crk_live_... or crk_test_...). */
|
|
17
|
+
apiKey: string;
|
|
18
|
+
/** API base URL. Defaults to https://chainreceipt.link. */
|
|
19
|
+
baseUrl?: string;
|
|
20
|
+
/** fetch implementation (defaults to the global fetch). Inject a
|
|
21
|
+
* mock in tests or a custom implementation in non-DOM runtimes. */
|
|
22
|
+
fetch?: typeof fetch;
|
|
23
|
+
}
|
|
24
|
+
export interface ListReceiptsParams {
|
|
25
|
+
/** ISO dates. */
|
|
26
|
+
from?: string;
|
|
27
|
+
to?: string;
|
|
28
|
+
/** API key id (key_...) to filter by. */
|
|
29
|
+
apiKeyId?: string;
|
|
30
|
+
status?: "complete" | "incomplete" | "upstream_error";
|
|
31
|
+
/** customer_ref to filter by. */
|
|
32
|
+
ref?: string;
|
|
33
|
+
/** 1–100, default 50. */
|
|
34
|
+
limit?: number;
|
|
35
|
+
/** The seq of the last row seen (from a previous page's
|
|
36
|
+
* next_cursor). */
|
|
37
|
+
cursor?: string;
|
|
38
|
+
}
|
|
39
|
+
export interface ChatCompletionsOptions {
|
|
40
|
+
/** Provider key for this one call (X-Provider-Key). Omit when the
|
|
41
|
+
* org has a provider key saved on the portal Keys page. */
|
|
42
|
+
providerKey?: string;
|
|
43
|
+
signal?: AbortSignal;
|
|
44
|
+
}
|
|
45
|
+
export interface ChatCompletionsResult {
|
|
46
|
+
/** The provider's response JSON, exactly as returned. */
|
|
47
|
+
data: Record<string, unknown>;
|
|
48
|
+
/** The attached receipt summary, or null when the proxy could not
|
|
49
|
+
* sign/store one (the answer is still returned in `data`). */
|
|
50
|
+
receipt: AiReceiptSummary | null;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Parse the `ai_receipt` block out of a proxy chat-completion
|
|
54
|
+
* response. Handles both shapes:
|
|
55
|
+
* - non-streaming: the response JSON carries `ai_receipt` at the top
|
|
56
|
+
* level;
|
|
57
|
+
* - streaming: the `ai_receipt` SSE event, parsed to
|
|
58
|
+
* `{object: "ai_receipt", ai_receipt: {...}}`.
|
|
59
|
+
* Returns null when the response carries no receipt. */
|
|
60
|
+
export declare function receiptFromResponse(response: unknown): AiReceiptSummary | null;
|
|
61
|
+
/** Parse one SSE `data:` line from a streamed proxy response and
|
|
62
|
+
* return its receipt when it is the `ai_receipt` event. Returns
|
|
63
|
+
* null for token events, `[DONE]`, and anything unparseable. */
|
|
64
|
+
export declare function receiptFromSseEvent(dataLine: string): AiReceiptSummary | null;
|
|
65
|
+
export declare class ChainReceiptClient {
|
|
66
|
+
readonly apiKey: string;
|
|
67
|
+
readonly baseUrl: string;
|
|
68
|
+
private readonly fetchFn;
|
|
69
|
+
constructor(options: ChainReceiptClientOptions);
|
|
70
|
+
private request;
|
|
71
|
+
/** The public verify-page URL for a receipt. */
|
|
72
|
+
getVerifyUrl(receiptId: string): string;
|
|
73
|
+
/** Full air/1 envelope for one receipt (GET /v1/receipts/:id).
|
|
74
|
+
* A receipt from another org answers the same 404 as a missing
|
|
75
|
+
* one. */
|
|
76
|
+
getReceipt(receiptId: string): Promise<ReceiptEnvelope>;
|
|
77
|
+
/** The org's receipts, newest first (GET /v1/receipts). */
|
|
78
|
+
listReceipts(params?: ListReceiptsParams): Promise<ReceiptListPage>;
|
|
79
|
+
/** Download a receipt's public bundle (GET /verify/:id/download).
|
|
80
|
+
* No API key needed — but only public receipts can be downloaded
|
|
81
|
+
* this way; a private receipt answers 404, so use getReceipt for
|
|
82
|
+
* your own receipts instead. */
|
|
83
|
+
downloadBundle(receiptId: string): Promise<ReceiptEnvelope>;
|
|
84
|
+
/** The published signing key for a key_id
|
|
85
|
+
* (GET /.well-known/receipt-keys.json). Public, no auth. */
|
|
86
|
+
getPublicKey(keyId: string): Promise<PublicKeyEntry>;
|
|
87
|
+
/** Verify a receipt envelope offline — hash recompute + Ed25519
|
|
88
|
+
* signature, no network when the public key is passed directly.
|
|
89
|
+
* Pass the key (hex/base64/bytes), or omit it to resolve it by
|
|
90
|
+
* the envelope's key_id from the public key directory (one fetch).
|
|
91
|
+
* Accepts an envelope from getReceipt / downloadBundle, or the
|
|
92
|
+
* receipt + hash + signature rebuilt from an ai_receipt summary. */
|
|
93
|
+
verifyReceipt(envelope: ReceiptEnvelope, publicKey?: string | Uint8Array): VerifyResult | Promise<VerifyResult>;
|
|
94
|
+
/** Server-side verification (POST /v1/verify). Public — no API
|
|
95
|
+
* key is sent. Accepts either a full envelope or a receipt id
|
|
96
|
+
* (plus optional prompt/response + salts for the content check).
|
|
97
|
+
* The server also reports the Merkle + Bitcoin anchor checks,
|
|
98
|
+
* which the offline path cannot. */
|
|
99
|
+
verifyOnline(input: {
|
|
100
|
+
envelope: ReceiptEnvelope;
|
|
101
|
+
} | {
|
|
102
|
+
receiptId: string;
|
|
103
|
+
prompt?: unknown;
|
|
104
|
+
response?: unknown;
|
|
105
|
+
salts?: {
|
|
106
|
+
prompt: string;
|
|
107
|
+
response: string;
|
|
108
|
+
};
|
|
109
|
+
}): Promise<ServerVerifyResult>;
|
|
110
|
+
/** Call the OpenAI-compatible proxy (POST
|
|
111
|
+
* /api/v1/chat/completions). The request body is OpenAI-shaped
|
|
112
|
+
* ({model: "openai/gpt-...", messages, ...}); the response is the
|
|
113
|
+
* provider's JSON plus the attached receipt, parsed out for you.
|
|
114
|
+
* Streaming is not handled here — pass stream: true and this
|
|
115
|
+
* throws; stream with your own fetch and pull the receipt from
|
|
116
|
+
* the `ai_receipt` SSE event with receiptFromSseEvent. */
|
|
117
|
+
chatCompletions(body: Record<string, unknown>, options?: ChatCompletionsOptions): Promise<ChatCompletionsResult>;
|
|
118
|
+
}
|
|
119
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,cAAc,EACd,YAAY,EACZ,aAAa,EACd,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EACV,gBAAgB,EAChB,cAAc,EACd,eAAe,EACf,eAAe,EACf,kBAAkB,EAClB,YAAY,EACb,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,aAAa,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AAkB,CAAC;IAoB9B;;;;;;+DAM2D;IACrD,eAAe,CACnB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,OAAO,GAAE,sBAA2B,GACnC,OAAO,CAAC,qBAAqB,CAAC;CAyBlC"}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/* @chain-receipt/sdk — HTTP client (plan step 25).
|
|
2
|
+
Thin wrapper over the live v1 API (apps/web/app/api/v1/*) and the
|
|
3
|
+
public verify surface. The API key is a Chain Receipt key
|
|
4
|
+
(crk_live_... / crk_test_...); provider keys are never stored in
|
|
5
|
+
the SDK — they are passed per chat call in X-Provider-Key, or
|
|
6
|
+
saved on the portal Keys page. */
|
|
7
|
+
import { fetchPublicKey, getVerifyUrl, verifyReceipt, } from "./verify.js";
|
|
8
|
+
export { fetchPublicKey, getVerifyUrl, verifyReceipt };
|
|
9
|
+
/** Error from the Chain Receipt API (or from the network layer).
|
|
10
|
+
* `status` is the HTTP status when one was received; `code` is the
|
|
11
|
+
* API's error code when the body carried one. */
|
|
12
|
+
export class ChainReceiptError extends Error {
|
|
13
|
+
status;
|
|
14
|
+
code;
|
|
15
|
+
constructor(message, status = null, code = null) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = "ChainReceiptError";
|
|
18
|
+
this.status = status;
|
|
19
|
+
this.code = code;
|
|
20
|
+
}
|
|
21
|
+
/** Build an error from a failed fetch Response, reading the
|
|
22
|
+
* OpenAI-shaped {error: {message, code}} body when present. */
|
|
23
|
+
static async fromResponse(res, path) {
|
|
24
|
+
let message = `Chain Receipt API error: ${res.status} ${path}`;
|
|
25
|
+
let code = null;
|
|
26
|
+
try {
|
|
27
|
+
const body = (await res.json());
|
|
28
|
+
if (typeof body.error?.message === "string") {
|
|
29
|
+
message = body.error.message;
|
|
30
|
+
}
|
|
31
|
+
if (typeof body.error?.code === "string") {
|
|
32
|
+
code = body.error.code;
|
|
33
|
+
}
|
|
34
|
+
else if (typeof body.error?.type === "string") {
|
|
35
|
+
code = body.error.type;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
// Non-JSON error body (e.g. the plain-text 404 from the public
|
|
40
|
+
// download route) — keep the status-based message.
|
|
41
|
+
}
|
|
42
|
+
return new ChainReceiptError(message, res.status, code);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Parse the `ai_receipt` block out of a proxy chat-completion
|
|
47
|
+
* response. Handles both shapes:
|
|
48
|
+
* - non-streaming: the response JSON carries `ai_receipt` at the top
|
|
49
|
+
* level;
|
|
50
|
+
* - streaming: the `ai_receipt` SSE event, parsed to
|
|
51
|
+
* `{object: "ai_receipt", ai_receipt: {...}}`.
|
|
52
|
+
* Returns null when the response carries no receipt. */
|
|
53
|
+
export function receiptFromResponse(response) {
|
|
54
|
+
if (typeof response !== "object" || response === null)
|
|
55
|
+
return null;
|
|
56
|
+
const obj = response;
|
|
57
|
+
const block = obj.ai_receipt;
|
|
58
|
+
if (typeof block !== "object" || block === null)
|
|
59
|
+
return null;
|
|
60
|
+
const summary = block;
|
|
61
|
+
if (typeof summary.receipt_id !== "string")
|
|
62
|
+
return null;
|
|
63
|
+
return summary;
|
|
64
|
+
}
|
|
65
|
+
/** Parse one SSE `data:` line from a streamed proxy response and
|
|
66
|
+
* return its receipt when it is the `ai_receipt` event. Returns
|
|
67
|
+
* null for token events, `[DONE]`, and anything unparseable. */
|
|
68
|
+
export function receiptFromSseEvent(dataLine) {
|
|
69
|
+
const line = dataLine.trim();
|
|
70
|
+
if (line === "" || line === "[DONE]")
|
|
71
|
+
return null;
|
|
72
|
+
try {
|
|
73
|
+
return receiptFromResponse(JSON.parse(line));
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
export class ChainReceiptClient {
|
|
80
|
+
apiKey;
|
|
81
|
+
baseUrl;
|
|
82
|
+
fetchFn;
|
|
83
|
+
constructor(options) {
|
|
84
|
+
if (!options.apiKey) {
|
|
85
|
+
throw new Error("ChainReceiptClient: apiKey is required");
|
|
86
|
+
}
|
|
87
|
+
this.apiKey = options.apiKey;
|
|
88
|
+
this.baseUrl = (options.baseUrl ?? "https://chainreceipt.link").replace(/\/$/, "");
|
|
89
|
+
this.fetchFn = options.fetch ?? fetch;
|
|
90
|
+
}
|
|
91
|
+
async request(path, init = {}) {
|
|
92
|
+
const { auth = true, ...rest } = init;
|
|
93
|
+
const headers = new Headers(rest.headers);
|
|
94
|
+
headers.set("Accept", "application/json");
|
|
95
|
+
if (auth)
|
|
96
|
+
headers.set("Authorization", `Bearer ${this.apiKey}`);
|
|
97
|
+
let res;
|
|
98
|
+
try {
|
|
99
|
+
res = await this.fetchFn(`${this.baseUrl}${path}`, {
|
|
100
|
+
...rest,
|
|
101
|
+
headers,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
throw new ChainReceiptError(`network error calling ${path}: ${err instanceof Error ? err.message : String(err)}`, null, "network_error");
|
|
106
|
+
}
|
|
107
|
+
if (!res.ok) {
|
|
108
|
+
throw await ChainReceiptError.fromResponse(res, path);
|
|
109
|
+
}
|
|
110
|
+
return (await res.json());
|
|
111
|
+
}
|
|
112
|
+
/** The public verify-page URL for a receipt. */
|
|
113
|
+
getVerifyUrl(receiptId) {
|
|
114
|
+
return getVerifyUrl(receiptId, this.baseUrl);
|
|
115
|
+
}
|
|
116
|
+
/** Full air/1 envelope for one receipt (GET /v1/receipts/:id).
|
|
117
|
+
* A receipt from another org answers the same 404 as a missing
|
|
118
|
+
* one. */
|
|
119
|
+
getReceipt(receiptId) {
|
|
120
|
+
return this.request(`/api/v1/receipts/${encodeURIComponent(receiptId)}`);
|
|
121
|
+
}
|
|
122
|
+
/** The org's receipts, newest first (GET /v1/receipts). */
|
|
123
|
+
listReceipts(params = {}) {
|
|
124
|
+
const qs = new URLSearchParams();
|
|
125
|
+
if (params.from)
|
|
126
|
+
qs.set("from", params.from);
|
|
127
|
+
if (params.to)
|
|
128
|
+
qs.set("to", params.to);
|
|
129
|
+
if (params.apiKeyId)
|
|
130
|
+
qs.set("api_key", params.apiKeyId);
|
|
131
|
+
if (params.status)
|
|
132
|
+
qs.set("status", params.status);
|
|
133
|
+
if (params.ref)
|
|
134
|
+
qs.set("ref", params.ref);
|
|
135
|
+
if (params.limit !== undefined)
|
|
136
|
+
qs.set("limit", String(params.limit));
|
|
137
|
+
if (params.cursor)
|
|
138
|
+
qs.set("cursor", params.cursor);
|
|
139
|
+
const query = qs.toString();
|
|
140
|
+
return this.request(`/api/v1/receipts${query ? `?${query}` : ""}`);
|
|
141
|
+
}
|
|
142
|
+
/** Download a receipt's public bundle (GET /verify/:id/download).
|
|
143
|
+
* No API key needed — but only public receipts can be downloaded
|
|
144
|
+
* this way; a private receipt answers 404, so use getReceipt for
|
|
145
|
+
* your own receipts instead. */
|
|
146
|
+
async downloadBundle(receiptId) {
|
|
147
|
+
const res = await this.fetchFn(`${this.baseUrl}/verify/${encodeURIComponent(receiptId)}/download`, { headers: { Accept: "application/json" } });
|
|
148
|
+
if (!res.ok) {
|
|
149
|
+
throw await ChainReceiptError.fromResponse(res, `/verify/${receiptId}/download`);
|
|
150
|
+
}
|
|
151
|
+
return (await res.json());
|
|
152
|
+
}
|
|
153
|
+
/** The published signing key for a key_id
|
|
154
|
+
* (GET /.well-known/receipt-keys.json). Public, no auth. */
|
|
155
|
+
getPublicKey(keyId) {
|
|
156
|
+
return fetchPublicKey(keyId, this.baseUrl, this.fetchFn);
|
|
157
|
+
}
|
|
158
|
+
/** Verify a receipt envelope offline — hash recompute + Ed25519
|
|
159
|
+
* signature, no network when the public key is passed directly.
|
|
160
|
+
* Pass the key (hex/base64/bytes), or omit it to resolve it by
|
|
161
|
+
* the envelope's key_id from the public key directory (one fetch).
|
|
162
|
+
* Accepts an envelope from getReceipt / downloadBundle, or the
|
|
163
|
+
* receipt + hash + signature rebuilt from an ai_receipt summary. */
|
|
164
|
+
verifyReceipt(envelope, publicKey) {
|
|
165
|
+
if (publicKey !== undefined)
|
|
166
|
+
return verifyReceipt(envelope, publicKey);
|
|
167
|
+
return verifyReceipt(envelope, {
|
|
168
|
+
fetchFrom: this.baseUrl,
|
|
169
|
+
fetchFn: this.fetchFn,
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
/** Server-side verification (POST /v1/verify). Public — no API
|
|
173
|
+
* key is sent. Accepts either a full envelope or a receipt id
|
|
174
|
+
* (plus optional prompt/response + salts for the content check).
|
|
175
|
+
* The server also reports the Merkle + Bitcoin anchor checks,
|
|
176
|
+
* which the offline path cannot. */
|
|
177
|
+
verifyOnline(input) {
|
|
178
|
+
const body = "envelope" in input
|
|
179
|
+
? input.envelope
|
|
180
|
+
: {
|
|
181
|
+
receipt_id: input.receiptId,
|
|
182
|
+
...(input.prompt !== undefined ? { prompt: input.prompt } : {}),
|
|
183
|
+
...(input.response !== undefined
|
|
184
|
+
? { response: input.response }
|
|
185
|
+
: {}),
|
|
186
|
+
...(input.salts ? { salts: input.salts } : {}),
|
|
187
|
+
};
|
|
188
|
+
return this.request("/api/v1/verify", {
|
|
189
|
+
method: "POST",
|
|
190
|
+
auth: false,
|
|
191
|
+
headers: { "Content-Type": "application/json" },
|
|
192
|
+
body: JSON.stringify(body),
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
/** Call the OpenAI-compatible proxy (POST
|
|
196
|
+
* /api/v1/chat/completions). The request body is OpenAI-shaped
|
|
197
|
+
* ({model: "openai/gpt-...", messages, ...}); the response is the
|
|
198
|
+
* provider's JSON plus the attached receipt, parsed out for you.
|
|
199
|
+
* Streaming is not handled here — pass stream: true and this
|
|
200
|
+
* throws; stream with your own fetch and pull the receipt from
|
|
201
|
+
* the `ai_receipt` SSE event with receiptFromSseEvent. */
|
|
202
|
+
async chatCompletions(body, options = {}) {
|
|
203
|
+
if (body.stream === true) {
|
|
204
|
+
throw new Error("chatCompletions: streaming is not supported by this helper — " +
|
|
205
|
+
"stream with your own fetch and use receiptFromSseEvent on " +
|
|
206
|
+
"the ai_receipt SSE event");
|
|
207
|
+
}
|
|
208
|
+
const headers = new Headers({
|
|
209
|
+
"Content-Type": "application/json",
|
|
210
|
+
});
|
|
211
|
+
if (options.providerKey) {
|
|
212
|
+
headers.set("X-Provider-Key", options.providerKey);
|
|
213
|
+
}
|
|
214
|
+
const data = await this.request("/api/v1/chat/completions", {
|
|
215
|
+
method: "POST",
|
|
216
|
+
headers,
|
|
217
|
+
body: JSON.stringify(body),
|
|
218
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
219
|
+
});
|
|
220
|
+
return { data, receipt: receiptFromResponse(data) };
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;oCAKoC;AACpC,OAAO,EACL,cAAc,EACd,YAAY,EACZ,aAAa,GACd,MAAM,aAAa,CAAC;AAUrB,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,aAAa,EAAE,CAAC;AAEvD;;kDAEkD;AAClD,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IAC1C,MAAM,CAAgB;IACtB,IAAI,CAAgB;IAEpB,YACE,OAAe,EACf,SAAwB,IAAI,EAC5B,OAAsB,IAAI;QAE1B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;QAChC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAED;oEACgE;IAChE,MAAM,CAAC,KAAK,CAAC,YAAY,CACvB,GAAa,EACb,IAAY;QAEZ,IAAI,OAAO,GAAG,4BAA4B,GAAG,CAAC,MAAM,IAAI,IAAI,EAAE,CAAC;Q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KAAK,IAAI,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CACb,+DAA+D;gBAC7D,4DAA4D;gBAC5D,0BAA0B,CAC7B,CAAC;QACJ,CAAC;QACD,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC;YAC1B,cAAc,EAAE,kBAAkB;SACnC,CAAC,CAAC;QACH,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC;YACxB,OAAO,CAAC,GAAG,CAAC,gBAAgB,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC;QACrD,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,OAAO,CAC7B,0BAA0B,EAC1B;YACE,MAAM,EAAE,MAAM;YACd,OAAO;YACP,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;YAC1B,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACtD,CACF,CAAC;QACF,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,mBAAmB,CAAC,IAAI,CAAC,EAAE,CAAC;IACtD,CAAC;CACF"}
|
package/dist/crypto.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { Receipt, Salts } from "./types.js";
|
|
2
|
+
export declare function bytesToHex(bytes: Uint8Array): string;
|
|
3
|
+
export declare function hexToBytes(hex: string): Uint8Array;
|
|
4
|
+
export declare function bytesToBase64(bytes: Uint8Array): string;
|
|
5
|
+
export declare function base64ToBytes(b64: string): Uint8Array;
|
|
6
|
+
/** Canonicalize a JSON value to its RFC 8785 string form. */
|
|
7
|
+
export declare function canonicalJson(value: unknown): string;
|
|
8
|
+
/** Canonical JSON as UTF-8 bytes, ready for hashing. */
|
|
9
|
+
export declare function canonicalJsonBytes(value: unknown): Uint8Array;
|
|
10
|
+
export declare function sha256Bytes(data: Uint8Array): Uint8Array;
|
|
11
|
+
export declare function sha256Hex(data: Uint8Array): string;
|
|
12
|
+
/** "sha256:<hex>" for raw bytes. */
|
|
13
|
+
export declare function sha256Tagged(data: Uint8Array): string;
|
|
14
|
+
/** "sha256:<hex>" for bytes that are ALREADY a digest — tags without
|
|
15
|
+
* re-hashing. */
|
|
16
|
+
export declare function tagHashBytes(digest: Uint8Array): string;
|
|
17
|
+
/** Raw 32 bytes of the hash behind a "sha256:<hex>" tag. */
|
|
18
|
+
export declare function hashBytesFromTag(tag: string): Uint8Array;
|
|
19
|
+
/** 32-byte public key for a 32-byte private seed. */
|
|
20
|
+
export declare function getPublicKey(privateKey: Uint8Array): Uint8Array;
|
|
21
|
+
/** Sign a message (NOT a hash) with a 32-byte private seed. */
|
|
22
|
+
export declare function signMessage(message: Uint8Array, privateKey: Uint8Array): Uint8Array;
|
|
23
|
+
/** Verify a signature over a message with a 32-byte public key. */
|
|
24
|
+
export declare function verifyMessage(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array): boolean;
|
|
25
|
+
/** A signing keypair from a 32-byte seed. */
|
|
26
|
+
export declare function keypairFromSeed(seed: Uint8Array): {
|
|
27
|
+
privateKey: Uint8Array;
|
|
28
|
+
publicKey: Uint8Array;
|
|
29
|
+
};
|
|
30
|
+
/** receipt_hash = sha256(JCS(receipt)). */
|
|
31
|
+
export declare function receiptHash(receipt: Receipt): string;
|
|
32
|
+
/** sha256 of the canonical receipt JSON, as raw bytes (for Merkle
|
|
33
|
+
* leaves — the leaf hash is sha256(0x00 || this)). */
|
|
34
|
+
export declare function receiptHashBytes(receipt: Receipt): Uint8Array;
|
|
35
|
+
/** Sign a receipt: Ed25519 over the 32 raw bytes of its receipt_hash. */
|
|
36
|
+
export declare function signReceipt(receipt: Receipt, privateKey: Uint8Array): string;
|
|
37
|
+
/** Verify a receipt's signature and that its hash matches its content.
|
|
38
|
+
* Returns false (never throws) on any mismatch. */
|
|
39
|
+
export declare function verifyReceiptSignature(receipt: Receipt, signatureB64: string, publicKey: Uint8Array): boolean;
|
|
40
|
+
/** Salted prompt commitment: sha256(salt || JCS(messages + tools +
|
|
41
|
+
* response_format)). */
|
|
42
|
+
export declare function saltedPromptHash(saltB64: string, requestBody: Record<string, unknown>): string;
|
|
43
|
+
/** Salted response commitment: sha256(salt || JCS(provider response)). */
|
|
44
|
+
export declare function saltedResponseHash(saltB64: string, responseJson: unknown): string;
|
|
45
|
+
/** Recompute the content hashes from the original text + salts and
|
|
46
|
+
* compare them to the receipt. This is what the public verify page
|
|
47
|
+
* runs in the browser: the text never leaves the customer's machine. */
|
|
48
|
+
export declare function verifyReceiptContent(receipt: Receipt, salts: Salts, promptBody: Record<string, unknown>, responseJson: unknown): boolean;
|
|
49
|
+
export type MerkleProofStep = {
|
|
50
|
+
side: "L" | "R";
|
|
51
|
+
hash: Uint8Array;
|
|
52
|
+
};
|
|
53
|
+
/** Merkle root of an ordered list of receipt-hash digests. */
|
|
54
|
+
export declare function merkleRoot(hashes: Uint8Array[]): Uint8Array;
|
|
55
|
+
/** Merkle proof for the leaf at `index`. Empty proof for a
|
|
56
|
+
* single-leaf tree. */
|
|
57
|
+
export declare function merkleProof(hashes: Uint8Array[], index: number): MerkleProofStep[];
|
|
58
|
+
/** Recompute the root from a leaf hash and its proof. */
|
|
59
|
+
export declare function verifyMerkleProof(leafHashBytes: Uint8Array, proof: MerkleProofStep[], expectedRoot: Uint8Array): boolean;
|
|
60
|
+
//# sourceMappingURL=crypto.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAWjD,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAIpD;AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CASlD;AAKD,wBAAgB,aAAa,CAAC,KAAK,EAAE,UAAU,GAAG,MA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