@redditech/agent-protocol 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/LICENSE +21 -0
  3. package/README.md +394 -2
  4. package/dist/adl.d.ts +141 -0
  5. package/dist/adl.js +3601 -0
  6. package/dist/agent-stack-fixtures.d.ts +743 -0
  7. package/dist/agent-stack-fixtures.js +1554 -0
  8. package/dist/ai-catalog.d.ts +128 -0
  9. package/dist/ai-catalog.js +373 -0
  10. package/dist/attestation-reputation.d.ts +102 -0
  11. package/dist/attestation-reputation.js +279 -0
  12. package/dist/audd-rail-config.d.ts +102 -0
  13. package/dist/audd-rail-config.js +294 -0
  14. package/dist/browser-wallet-approval.d.ts +293 -0
  15. package/dist/browser-wallet-approval.js +1201 -0
  16. package/dist/discovery-source.d.ts +115 -0
  17. package/dist/discovery-source.js +251 -0
  18. package/dist/evidence-archive.d.ts +73 -0
  19. package/dist/evidence-archive.js +238 -0
  20. package/dist/index.d.ts +23 -0
  21. package/dist/index.js +23 -0
  22. package/dist/mpp-tempo-receipt-shapes.d.ts +201 -0
  23. package/dist/mpp-tempo-receipt-shapes.js +330 -0
  24. package/dist/okf-adapter.d.ts +229 -0
  25. package/dist/okf-adapter.js +556 -0
  26. package/dist/okf-conformance.d.ts +208 -0
  27. package/dist/okf-conformance.js +651 -0
  28. package/dist/okf-instruction-safety.d.ts +192 -0
  29. package/dist/okf-instruction-safety.js +509 -0
  30. package/dist/onboarding-analyser-handoff.d.ts +391 -0
  31. package/dist/onboarding-analyser-handoff.js +959 -0
  32. package/dist/onboarding-state-machine.d.ts +228 -0
  33. package/dist/onboarding-state-machine.js +432 -0
  34. package/dist/payment-records.d.ts +181 -0
  35. package/dist/payment-records.js +599 -0
  36. package/dist/policy.d.ts +33 -0
  37. package/dist/policy.js +45 -0
  38. package/dist/provider-trust.d.ts +113 -0
  39. package/dist/provider-trust.js +346 -0
  40. package/dist/quasar-registry-compatibility.d.ts +113 -0
  41. package/dist/quasar-registry-compatibility.js +214 -0
  42. package/dist/ranking-explainability.d.ts +202 -0
  43. package/dist/ranking-explainability.js +302 -0
  44. package/dist/receipt-v2.d.ts +202 -0
  45. package/dist/receipt-v2.js +418 -0
  46. package/dist/repo-explorer-evidence-manifest.d.ts +387 -0
  47. package/dist/repo-explorer-evidence-manifest.js +1187 -0
  48. package/dist/source-diagnostics.d.ts +84 -0
  49. package/dist/source-diagnostics.js +193 -0
  50. package/dist/source-trust-conformance-matrix.d.ts +207 -0
  51. package/dist/source-trust-conformance-matrix.js +672 -0
  52. package/examples/ard-no-spend-ai-catalog.json +51 -0
  53. package/examples/ard-no-spend-demo.mjs +355 -0
  54. package/examples/interpretation-guide-scenarios.mjs +302 -0
  55. package/package.json +144 -4
@@ -0,0 +1,418 @@
1
+ /**
2
+ * Reddi receipt v2 (#739, #740).
3
+ *
4
+ * `reddi.receipt.v2` is a receipt the provider issues and signs. It names the
5
+ * provider, the model the provider declares it served, the hashes of the
6
+ * request and response, and the transaction the call was paid with. The
7
+ * provider signs those fields with its wallet key, so the receipt can be
8
+ * checked offline against the provider's address.
9
+ *
10
+ * It is the receipt for every paid call in V1 (#776). It also states what was
11
+ * paid: the currency and mint, the listed price, the protocol fee and where it
12
+ * went, and whether the call was paid directly or through escrow. A v1
13
+ * validator rejects a v2 receipt and this module rejects a v1 receipt.
14
+ *
15
+ * The payment fields are the provider's statement. A verifier that needs to
16
+ * rely on them checks the named transaction on chain; this module does not.
17
+ *
18
+ * What a valid signature shows: the holder of the provider key stated these
19
+ * fields. It does not show which model actually ran. "Declared model" is a
20
+ * declaration, not verified execution.
21
+ *
22
+ * Everything here is offline: no network, no clock unless a caller passes one,
23
+ * and no private key is ever accepted. Signing goes through a caller-supplied
24
+ * signer function.
25
+ */
26
+ import { createHash, createPublicKey, verify as edVerify } from 'node:crypto';
27
+ export const REDDI_RECEIPT_V2_VERSION = 'reddi.receipt.v2';
28
+ export const REDDI_RECEIPT_V2_PROOF_TYPE = 'ed25519';
29
+ export const REDDI_RECEIPT_V2_CURRENCIES = ['SOL', 'USDC', 'PYUSD', 'USDG', 'AUDD'];
30
+ const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
31
+ const HASH = /^[0-9a-f]{64}$/;
32
+ const TX_SIGNATURE = /^[1-9A-HJ-NP-Za-km-z]{64,88}$/;
33
+ const ISO_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;
34
+ const ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');
35
+ const RECEIPT_KEYS = ['schemaVersion', 'providerId', 'declaredModel', 'requestHash', 'responseHash', 'payment', 'session', 'jobId', 'issuedAt'];
36
+ const SESSION_KEYS = ['escrow', 'payer', 'network', 'currency', 'mint', 'maxAmount', 'sequence', 'inputTokens', 'outputTokens', 'cumulativeInputTokens', 'cumulativeOutputTokens', 'cumulativeCost', 'previousReceiptHash', 'closed'];
37
+ const SESSION_COUNTS = ['maxAmount', 'sequence', 'inputTokens', 'outputTokens', 'cumulativeInputTokens', 'cumulativeOutputTokens', 'cumulativeCost'];
38
+ const PAYMENT_KEYS = ['network', 'txSignature', 'currency', 'mint', 'amount', 'fee', 'payer', 'settlement', 'metered'];
39
+ const METERED_KEYS = ['inputTokens', 'outputTokens', 'maxAmount', 'refunded'];
40
+ /** Smallest-unit amount: digits only, no leading zero, at most 30 digits. */
41
+ const BASE_UNITS = /^(0|[1-9]\d{0,29})$/;
42
+ const JOB_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/;
43
+ function err(code, path, message) {
44
+ return { code, path, message };
45
+ }
46
+ function isRecord(value) {
47
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
48
+ }
49
+ function onlyKeys(value, allowed) {
50
+ return Object.keys(value).every((key) => allowed.includes(key));
51
+ }
52
+ /** Decodes base58 to bytes, or undefined when the text is not base58. */
53
+ function base58Decode(text) {
54
+ if (text.length === 0 || text.length > 128)
55
+ return undefined;
56
+ const bytes = [];
57
+ for (const char of text) {
58
+ let carry = BASE58_ALPHABET.indexOf(char);
59
+ if (carry < 0)
60
+ return undefined;
61
+ for (let i = 0; i < bytes.length; i += 1) {
62
+ carry += bytes[i] * 58;
63
+ bytes[i] = carry & 0xff;
64
+ carry >>= 8;
65
+ }
66
+ while (carry > 0) {
67
+ bytes.push(carry & 0xff);
68
+ carry >>= 8;
69
+ }
70
+ }
71
+ for (const char of text) {
72
+ if (char !== '1')
73
+ break;
74
+ bytes.push(0);
75
+ }
76
+ return Uint8Array.from(bytes.reverse());
77
+ }
78
+ /** The 32-byte ed25519 public key behind a Solana address, or undefined. */
79
+ function publicKeyBytes(address) {
80
+ if (typeof address !== 'string')
81
+ return undefined;
82
+ const decoded = base58Decode(address);
83
+ return decoded && decoded.length === 32 ? decoded : undefined;
84
+ }
85
+ /** SHA-256 of a body, lowercase hex. Strings are hashed as UTF-8. */
86
+ export function hashReddiReceiptV2Body(body) {
87
+ return createHash('sha256').update(typeof body === 'string' ? Buffer.from(body, 'utf8') : body).digest('hex');
88
+ }
89
+ export function validateReddiReceiptV2(input) {
90
+ if (!isRecord(input))
91
+ return { ok: false, errors: [err('malformed_receipt', '$', 'receipt must be an object')] };
92
+ if (input.schemaVersion !== REDDI_RECEIPT_V2_VERSION) {
93
+ return { ok: false, errors: [err('unsupported_version', '$.schemaVersion', `expected ${REDDI_RECEIPT_V2_VERSION}`)] };
94
+ }
95
+ const errors = [];
96
+ if (!onlyKeys(input, RECEIPT_KEYS))
97
+ errors.push(err('malformed_receipt', '$', 'receipt has fields this version does not define'));
98
+ if (!publicKeyBytes(input.providerId))
99
+ errors.push(err('malformed_receipt', '$.providerId', 'providerId must be a base58 Solana address'));
100
+ if (typeof input.declaredModel !== 'string' || input.declaredModel.length < 1 || input.declaredModel.length > 120 || /[\u0000-\u001f\u007f]/.test(input.declaredModel)) {
101
+ errors.push(err('malformed_receipt', '$.declaredModel', 'declaredModel must be 1 to 120 printable characters'));
102
+ }
103
+ if (typeof input.requestHash !== 'string' || !HASH.test(input.requestHash))
104
+ errors.push(err('malformed_receipt', '$.requestHash', 'requestHash must be lowercase hex SHA-256'));
105
+ if (typeof input.responseHash !== 'string' || !HASH.test(input.responseHash))
106
+ errors.push(err('malformed_receipt', '$.responseHash', 'responseHash must be lowercase hex SHA-256'));
107
+ const payment = input.payment;
108
+ const session = input.session;
109
+ if (session !== undefined)
110
+ validateSession(session, payment, errors);
111
+ if (payment === undefined && session !== undefined) {
112
+ // A session receipt before the settle: the session block states the money.
113
+ }
114
+ else if (!isRecord(payment) || !onlyKeys(payment, PAYMENT_KEYS)) {
115
+ errors.push(err('malformed_receipt', '$.payment', 'payment must be an object with only the fields this version defines'));
116
+ }
117
+ else {
118
+ const isSol = payment.currency === 'SOL';
119
+ if (!REDDI_RECEIPT_V2_CURRENCIES.includes(payment.currency))
120
+ errors.push(err('malformed_receipt', '$.payment.currency', 'currency must be SOL, USDC, PYUSD, USDG or AUDD'));
121
+ else if (isSol && payment.mint !== undefined)
122
+ errors.push(err('malformed_receipt', '$.payment.mint', 'SOL has no mint'));
123
+ else if (!isSol && !publicKeyBytes(payment.mint))
124
+ errors.push(err('malformed_receipt', '$.payment.mint', 'mint must be a base58 address for a token currency'));
125
+ if (typeof payment.amount !== 'string' || !BASE_UNITS.test(payment.amount) || payment.amount === '0')
126
+ errors.push(err('malformed_receipt', '$.payment.amount', 'amount must be a positive whole number of smallest units, as a string'));
127
+ const fee = payment.fee;
128
+ if (!isRecord(fee) || !onlyKeys(fee, ['amount', 'treasury']) || typeof fee.amount !== 'string' || !BASE_UNITS.test(fee.amount)) {
129
+ errors.push(err('malformed_receipt', '$.payment.fee', 'fee must be { amount, treasury? } with amount in smallest units'));
130
+ }
131
+ else {
132
+ if (fee.treasury !== undefined && !publicKeyBytes(fee.treasury))
133
+ errors.push(err('malformed_receipt', '$.payment.fee.treasury', 'treasury must be a base58 address'));
134
+ if (fee.amount !== '0' && fee.treasury === undefined)
135
+ errors.push(err('malformed_receipt', '$.payment.fee.treasury', 'a fee above zero must name the treasury that received it'));
136
+ if (typeof payment.amount === 'string' && BASE_UNITS.test(payment.amount) && BigInt(fee.amount) >= BigInt(payment.amount))
137
+ errors.push(err('malformed_receipt', '$.payment.fee.amount', 'fee must be less than the amount'));
138
+ }
139
+ if (payment.payer !== undefined && !publicKeyBytes(payment.payer))
140
+ errors.push(err('malformed_receipt', '$.payment.payer', 'payer must be a base58 address'));
141
+ if (payment.settlement !== 'direct' && payment.settlement !== 'escrow' && payment.settlement !== 'metered-escrow') {
142
+ errors.push(err('malformed_receipt', '$.payment.settlement', 'settlement must be direct, escrow or metered-escrow'));
143
+ }
144
+ const metered = payment.metered;
145
+ if (payment.settlement === 'metered-escrow') {
146
+ if (!isRecord(metered) || !onlyKeys(metered, METERED_KEYS) || !METERED_KEYS.every((key) => typeof metered[key] === 'string' && BASE_UNITS.test(metered[key]))) {
147
+ errors.push(err('malformed_receipt', '$.payment.metered', 'a metered-escrow payment must state { inputTokens, outputTokens, maxAmount, refunded } as whole numbers'));
148
+ }
149
+ else if (typeof payment.amount === 'string' && BASE_UNITS.test(payment.amount)) {
150
+ const max = BigInt(metered.maxAmount);
151
+ const paid = BigInt(payment.amount);
152
+ if (paid > max)
153
+ errors.push(err('malformed_receipt', '$.payment.amount', 'a metered payment cannot exceed the authorised maximum'));
154
+ else if (BigInt(metered.refunded) !== max - paid)
155
+ errors.push(err('malformed_receipt', '$.payment.metered.refunded', 'refunded must be the maximum less the amount paid'));
156
+ }
157
+ }
158
+ else if (metered !== undefined) {
159
+ errors.push(err('malformed_receipt', '$.payment.metered', 'only a metered-escrow payment states token counts'));
160
+ }
161
+ if (payment.network !== 'solana-devnet' && payment.network !== 'solana-mainnet-beta')
162
+ errors.push(err('malformed_receipt', '$.payment.network', 'network must be solana-devnet or solana-mainnet-beta'));
163
+ if (typeof payment.txSignature !== 'string' || !TX_SIGNATURE.test(payment.txSignature))
164
+ errors.push(err('malformed_receipt', '$.payment.txSignature', 'txSignature must be a base58 transaction signature'));
165
+ }
166
+ if (input.jobId !== undefined && (typeof input.jobId !== 'string' || !JOB_ID.test(input.jobId)))
167
+ errors.push(err('malformed_receipt', '$.jobId', 'jobId must be 1 to 120 characters of letters, digits, dot, underscore, colon or hyphen'));
168
+ if (typeof input.issuedAt !== 'string' || !ISO_UTC.test(input.issuedAt) || Number.isNaN(Date.parse(input.issuedAt))) {
169
+ errors.push(err('malformed_receipt', '$.issuedAt', 'issuedAt must be an ISO 8601 UTC time'));
170
+ }
171
+ return errors.length > 0 ? { ok: false, errors } : { ok: true, receipt: input };
172
+ }
173
+ function validateSession(session, payment, errors) {
174
+ if (!isRecord(session) || !onlyKeys(session, SESSION_KEYS)) {
175
+ errors.push(err('malformed_receipt', '$.session', 'session must be an object with only the fields this version defines'));
176
+ return;
177
+ }
178
+ if (!publicKeyBytes(session.escrow))
179
+ errors.push(err('malformed_receipt', '$.session.escrow', 'escrow must be a base58 address'));
180
+ if (!publicKeyBytes(session.payer))
181
+ errors.push(err('malformed_receipt', '$.session.payer', 'payer must be a base58 address'));
182
+ if (session.network !== 'solana-devnet' && session.network !== 'solana-mainnet-beta')
183
+ errors.push(err('malformed_receipt', '$.session.network', 'network must be solana-devnet or solana-mainnet-beta'));
184
+ if (!REDDI_RECEIPT_V2_CURRENCIES.includes(session.currency))
185
+ errors.push(err('malformed_receipt', '$.session.currency', 'currency must be SOL, USDC, PYUSD, USDG or AUDD'));
186
+ else if (session.currency === 'SOL' ? session.mint !== undefined : !publicKeyBytes(session.mint))
187
+ errors.push(err('malformed_receipt', '$.session.mint', 'mint must be a base58 address for a token currency, and absent for SOL'));
188
+ if (typeof session.closed !== 'boolean')
189
+ errors.push(err('malformed_receipt', '$.session.closed', 'closed must be true or false'));
190
+ if (!SESSION_COUNTS.every((key) => typeof session[key] === 'string' && BASE_UNITS.test(session[key]))) {
191
+ errors.push(err('malformed_receipt', '$.session', 'session amounts and token counts must be whole numbers, as strings'));
192
+ return;
193
+ }
194
+ const n = (key) => BigInt(session[key]);
195
+ const sequence = n('sequence');
196
+ if (sequence < 1n)
197
+ errors.push(err('malformed_receipt', '$.session.sequence', 'sequence starts at 1'));
198
+ if (n('cumulativeCost') > n('maxAmount'))
199
+ errors.push(err('malformed_receipt', '$.session.cumulativeCost', 'cumulative cost cannot exceed the locked maximum'));
200
+ if (n('cumulativeInputTokens') < n('inputTokens') || n('cumulativeOutputTokens') < n('outputTokens'))
201
+ errors.push(err('malformed_receipt', '$.session', 'totals cannot be below this call'));
202
+ if (sequence === 1n) {
203
+ if (session.previousReceiptHash !== undefined)
204
+ errors.push(err('malformed_receipt', '$.session.previousReceiptHash', 'the first call has no previous receipt'));
205
+ if (n('cumulativeInputTokens') !== n('inputTokens') || n('cumulativeOutputTokens') !== n('outputTokens'))
206
+ errors.push(err('malformed_receipt', '$.session', "the first call's totals are its own counts"));
207
+ }
208
+ else if (typeof session.previousReceiptHash !== 'string' || !HASH.test(session.previousReceiptHash)) {
209
+ errors.push(err('malformed_receipt', '$.session.previousReceiptHash', 'every call after the first names the previous receipt by its hash'));
210
+ }
211
+ if (payment === undefined) {
212
+ if (session.closed !== false)
213
+ errors.push(err('malformed_receipt', '$.session.closed', 'a closed session receipt states the payment that settled it'));
214
+ return;
215
+ }
216
+ if (session.closed !== true)
217
+ errors.push(err('malformed_receipt', '$.session.closed', 'only the receipt of the settle states a payment'));
218
+ if (!isRecord(payment))
219
+ return;
220
+ const metered = isRecord(payment.metered) ? payment.metered : undefined;
221
+ const agrees = payment.settlement === 'metered-escrow'
222
+ && payment.network === session.network
223
+ && payment.currency === session.currency
224
+ && payment.mint === session.mint
225
+ && (payment.payer === undefined || payment.payer === session.payer)
226
+ && payment.amount === session.cumulativeCost
227
+ && metered !== undefined
228
+ && metered.inputTokens === session.cumulativeInputTokens
229
+ && metered.outputTokens === session.cumulativeOutputTokens
230
+ && metered.maxAmount === session.maxAmount;
231
+ if (!agrees)
232
+ errors.push(err('malformed_receipt', '$.session', "the settle's payment must be the session's cumulative cost and totals, on the same lock"));
233
+ }
234
+ /**
235
+ * The exact bytes the provider signs: JSON with a fixed field order and no
236
+ * whitespace. The version string is the first field, so a signature for this
237
+ * receipt cannot be replayed as a signature for another kind of message.
238
+ */
239
+ export function canonicalizeReddiReceiptV2(receipt) {
240
+ const p = receipt.payment;
241
+ // A receipt with neither block fails validation; this keeps the shape total for callers that canonicalise first.
242
+ return JSON.stringify({
243
+ schemaVersion: receipt.schemaVersion,
244
+ providerId: receipt.providerId,
245
+ declaredModel: receipt.declaredModel,
246
+ requestHash: receipt.requestHash,
247
+ responseHash: receipt.responseHash,
248
+ ...(p !== undefined ? { payment: {
249
+ network: p.network,
250
+ txSignature: p.txSignature,
251
+ currency: p.currency,
252
+ ...(p.mint !== undefined ? { mint: p.mint } : {}),
253
+ amount: p.amount,
254
+ fee: { amount: p.fee.amount, ...(p.fee.treasury !== undefined ? { treasury: p.fee.treasury } : {}) },
255
+ ...(p.payer !== undefined ? { payer: p.payer } : {}),
256
+ settlement: p.settlement,
257
+ ...(p.metered !== undefined
258
+ ? { metered: { inputTokens: p.metered.inputTokens, outputTokens: p.metered.outputTokens, maxAmount: p.metered.maxAmount, refunded: p.metered.refunded } }
259
+ : {}),
260
+ } } : {}),
261
+ ...(receipt.session !== undefined ? { session: canonicalSession(receipt.session) } : {}),
262
+ ...(receipt.jobId !== undefined ? { jobId: receipt.jobId } : {}),
263
+ issuedAt: receipt.issuedAt,
264
+ });
265
+ }
266
+ function canonicalSession(s) {
267
+ return {
268
+ escrow: s.escrow,
269
+ payer: s.payer,
270
+ network: s.network,
271
+ currency: s.currency,
272
+ ...(s.mint !== undefined ? { mint: s.mint } : {}),
273
+ maxAmount: s.maxAmount,
274
+ sequence: s.sequence,
275
+ inputTokens: s.inputTokens,
276
+ outputTokens: s.outputTokens,
277
+ cumulativeInputTokens: s.cumulativeInputTokens,
278
+ cumulativeOutputTokens: s.cumulativeOutputTokens,
279
+ cumulativeCost: s.cumulativeCost,
280
+ ...(s.previousReceiptHash !== undefined ? { previousReceiptHash: s.previousReceiptHash } : {}),
281
+ closed: s.closed,
282
+ };
283
+ }
284
+ /** SHA-256 of a receipt's canonical bytes, lowercase hex: what the next call of a session names as `previousReceiptHash`. */
285
+ export function hashReddiReceiptV2(receipt) {
286
+ return hashReddiReceiptV2Body(canonicalizeReddiReceiptV2(receipt));
287
+ }
288
+ /** Validates the receipt, asks the signer for a signature, and refuses to return one that does not verify. */
289
+ export async function signReddiReceiptV2(receipt, signer) {
290
+ const valid = validateReddiReceiptV2(receipt);
291
+ if (!valid.ok)
292
+ throw new Error(`invalid_reddi_receipt_v2:${valid.errors.map((e) => `${e.code}:${e.path}`).join(',')}`);
293
+ const signature = await signer(Buffer.from(canonicalizeReddiReceiptV2(valid.receipt), 'utf8'));
294
+ const signed = {
295
+ receipt: valid.receipt,
296
+ proof: { type: REDDI_RECEIPT_V2_PROOF_TYPE, signature: Buffer.from(signature).toString('base64') },
297
+ };
298
+ const check = verifyReddiReceiptV2(signed);
299
+ if (!check.ok)
300
+ throw new Error('provider_receipt_signer_mismatch: the signature does not verify against providerId');
301
+ return signed;
302
+ }
303
+ /**
304
+ * Verifies a signed receipt offline. The signature must verify against the
305
+ * `providerId` inside the receipt, and every field of `expected` that is given
306
+ * must equal the signed value. Pass what you know yourself: the provider you
307
+ * paid, the hashes of the bytes you sent and received, the transaction you paid
308
+ * with. Without `expected`, a pass only says some key signed some statement.
309
+ */
310
+ export function verifyReddiReceiptV2(input, expected = {}) {
311
+ if (!isRecord(input) || !onlyKeys(input, ['receipt', 'proof'])) {
312
+ return { ok: false, errors: [err('malformed_proof', '$', 'expected an object with receipt and proof only')] };
313
+ }
314
+ const valid = validateReddiReceiptV2(input.receipt);
315
+ if (!valid.ok)
316
+ return valid;
317
+ const receipt = valid.receipt;
318
+ const proof = input.proof;
319
+ if (!isRecord(proof) || !onlyKeys(proof, ['type', 'signature']) || proof.type !== REDDI_RECEIPT_V2_PROOF_TYPE || typeof proof.signature !== 'string') {
320
+ return { ok: false, errors: [err('malformed_proof', '$.proof', 'proof must be { type: "ed25519", signature }')] };
321
+ }
322
+ if (!/^[A-Za-z0-9+/]{86}==$/.test(proof.signature)) {
323
+ return { ok: false, errors: [err('malformed_proof', '$.proof.signature', 'signature must be base64 of 64 bytes')] };
324
+ }
325
+ const signature = Buffer.from(proof.signature, 'base64');
326
+ const key = publicKeyBytes(receipt.providerId);
327
+ let verified = false;
328
+ try {
329
+ const publicKey = createPublicKey({ key: Buffer.concat([ED25519_SPKI_PREFIX, Buffer.from(key)]), format: 'der', type: 'spki' });
330
+ verified = signature.length === 64 && edVerify(null, Buffer.from(canonicalizeReddiReceiptV2(receipt), 'utf8'), publicKey, signature);
331
+ }
332
+ catch {
333
+ verified = false;
334
+ }
335
+ if (!verified)
336
+ return { ok: false, errors: [err('signature_invalid', '$.proof.signature', 'signature does not verify against providerId over the canonical receipt')] };
337
+ const errors = [];
338
+ if (expected.providerId !== undefined && expected.providerId !== receipt.providerId)
339
+ errors.push(err('provider_mismatch', '$.receipt.providerId', 'signed by a different provider than expected'));
340
+ if (expected.declaredModel !== undefined && expected.declaredModel !== receipt.declaredModel)
341
+ errors.push(err('declared_model_mismatch', '$.receipt.declaredModel', 'declared model differs from the one expected'));
342
+ if (expected.requestHash !== undefined && expected.requestHash !== receipt.requestHash)
343
+ errors.push(err('request_hash_mismatch', '$.receipt.requestHash', 'request hash differs from the request that was sent'));
344
+ if (expected.responseHash !== undefined && expected.responseHash !== receipt.responseHash)
345
+ errors.push(err('response_hash_mismatch', '$.receipt.responseHash', 'response hash differs from the response that was received'));
346
+ if (expected.session !== undefined) {
347
+ const got = receipt.session;
348
+ if (!got || Object.entries(expected.session).some(([key, value]) => value !== undefined && got[key] !== value))
349
+ errors.push(err('session_mismatch', '$.receipt.session', 'session differs from the session expected'));
350
+ }
351
+ if (expected.payment !== undefined && receipt.payment === undefined) {
352
+ errors.push(err('payment_mismatch', '$.receipt.payment', 'this receipt states no payment yet'));
353
+ }
354
+ else if (expected.payment !== undefined && receipt.payment !== undefined) {
355
+ const want = expected.payment;
356
+ const got = receipt.payment;
357
+ const differs = want.network !== got.network
358
+ || want.txSignature !== got.txSignature
359
+ || (want.currency !== undefined && want.currency !== got.currency)
360
+ || (want.mint !== undefined && want.mint !== got.mint)
361
+ || (want.amount !== undefined && want.amount !== got.amount)
362
+ || (want.payer !== undefined && want.payer !== got.payer)
363
+ || (want.settlement !== undefined && want.settlement !== got.settlement)
364
+ || (want.metered !== undefined && (got.metered === undefined || METERED_KEYS.some((key) => want.metered[key] !== got.metered[key])))
365
+ || (want.fee !== undefined && (want.fee.amount !== got.fee.amount || (want.fee.treasury !== undefined && want.fee.treasury !== got.fee.treasury)));
366
+ if (differs)
367
+ errors.push(err('payment_mismatch', '$.receipt.payment', 'payment differs from the payment that was made'));
368
+ }
369
+ return errors.length > 0 ? { ok: false, errors } : { ok: true, receipt };
370
+ }
371
+ /**
372
+ * Checks a session's receipts as one chain, oldest first: each verifies on its
373
+ * own (pass `expected` for what every receipt must state, for example the
374
+ * provider and the escrow), they share provider, escrow, payer, network,
375
+ * currency, mint and maximum, sequences run 1, 2, 3 with no gap, each names the
376
+ * previous receipt's hash, the totals are the running sums of each call's
377
+ * counts, the cost never goes down, and only the last may be closed. It does
378
+ * not recompute cost from a price: compare `cumulativeCost` with your own
379
+ * count of tokens at the price you were quoted.
380
+ */
381
+ export function verifyReddiReceiptV2Session(chain, expected = {}) {
382
+ if (chain.length === 0)
383
+ return { ok: false, errors: [err('session_chain_broken', '$', 'no receipts')] };
384
+ const receipts = [];
385
+ for (const [index, item] of chain.entries()) {
386
+ const one = verifyReddiReceiptV2(item, { ...(expected.providerId !== undefined ? { providerId: expected.providerId } : {}), ...(expected.declaredModel !== undefined ? { declaredModel: expected.declaredModel } : {}), ...(expected.session !== undefined ? { session: expected.session } : {}) });
387
+ if (!one.ok)
388
+ return { ok: false, errors: one.errors.map((e) => ({ ...e, path: `$[${index}]${e.path.slice(1)}` })) };
389
+ if (!one.receipt.session)
390
+ return { ok: false, errors: [err('session_chain_broken', `$[${index}].receipt.session`, 'not a session receipt')] };
391
+ receipts.push(one.receipt);
392
+ }
393
+ const broken = (index, message) => ({ ok: false, errors: [err('session_chain_broken', `$[${index}].receipt.session`, message)] });
394
+ const first = receipts[0];
395
+ let input = 0n;
396
+ let output = 0n;
397
+ let cost = 0n;
398
+ for (const [index, receipt] of receipts.entries()) {
399
+ const s = receipt.session;
400
+ const f = first.session;
401
+ if (receipt.providerId !== first.providerId || s.escrow !== f.escrow || s.payer !== f.payer || s.network !== f.network || s.currency !== f.currency || s.mint !== f.mint || s.maxAmount !== f.maxAmount)
402
+ return broken(index, 'a different provider, lock or currency than the first receipt');
403
+ if (BigInt(s.sequence) !== BigInt(index + 1))
404
+ return broken(index, `expected sequence ${index + 1}`);
405
+ if (index > 0 && s.previousReceiptHash !== hashReddiReceiptV2(receipts[index - 1]))
406
+ return broken(index, 'does not name the previous receipt');
407
+ input += BigInt(s.inputTokens);
408
+ output += BigInt(s.outputTokens);
409
+ if (BigInt(s.cumulativeInputTokens) !== input || BigInt(s.cumulativeOutputTokens) !== output)
410
+ return broken(index, 'totals are not the sum of the calls');
411
+ if (BigInt(s.cumulativeCost) < cost)
412
+ return broken(index, 'cumulative cost went down');
413
+ cost = BigInt(s.cumulativeCost);
414
+ if (s.closed && index !== receipts.length - 1)
415
+ return broken(index, 'a receipt follows the closing one');
416
+ }
417
+ return { ok: true, receipts, closed: receipts[receipts.length - 1].session.closed };
418
+ }