@calimero-network/mero-js 35.3.0 → 35.5.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.
@@ -0,0 +1,475 @@
1
+ /**
2
+ * Checking a pipeline run's receipt as core's `calimero-client` does (`Client::verify_app_cluster`,
3
+ * `attest::verify_receipt_key`, `Client::verify_receipt`): the receipt is signed by the answering
4
+ * node's receipt key, and that key is one every replica's quote attests, bound to the cluster and
5
+ * node the entry node names. A quote of the unbound `receipt-key.v2` form is never accepted. A
6
+ * version 2 receipt also proves each job's report: its job key signed what the proof says, and a
7
+ * job node's quote under the client's policy binds that key, node, cluster and cluster identity.
8
+ */
9
+ import { concat, fromHex, hex } from '../crypto/internal.js';
10
+ import { governanceCanonical, receiptKeyBinding } from '../recovery/backup-files.js';
11
+ import { jcs } from '../package/pack.js';
12
+ import { verifyQuoteBinding } from '../runtime/attestation.js';
13
+ import { buf } from './recovery-key.js';
14
+ const PIPELINE_RECEIPT_DOMAIN = 'calimero.pipeline.receipt.v1\0';
15
+ const utf8 = (s) => new TextEncoder().encode(s);
16
+ const fail = (path, what) => {
17
+ throw new Error(`the receipt's ${path} ${what}`);
18
+ };
19
+ const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
20
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
21
+ const str = (v, p) => typeof v === 'string' || fail(p, 'is not a string');
22
+ const bool = (v, p) => typeof v === 'boolean' || fail(p, 'is not a boolean');
23
+ const any = () => undefined;
24
+ const obj = (v, p) => isObject(v) || fail(p, 'is not an object');
25
+ const uint = (max) => (v, p) => (typeof v === 'number' && Number.isInteger(v) && v >= 0 && v <= max) || fail(p, 'is not an unsigned integer in range');
26
+ const u32 = uint(0xffffffff);
27
+ const u64 = (v, p) => (typeof v === 'number' && Number.isInteger(v) && v >= 0 && v < 2 ** 64) || fail(p, 'is not an unsigned integer in range'); // 2^64 itself is not a u64
28
+ const list = (item) => (v, p) => {
29
+ if (!Array.isArray(v))
30
+ fail(p, 'is not an array');
31
+ v.forEach((x, i) => item(x, `${p}[${i}]`));
32
+ };
33
+ const map = (value) => (v, p) => {
34
+ if (!isObject(v))
35
+ fail(p, 'is not an object');
36
+ for (const [k, x] of Object.entries(v))
37
+ value(x, `${p}.${k}`);
38
+ };
39
+ // `optional` fields are Options (null reads as absent); `defaulted` ones may be absent but never null;
40
+ // an `open` struct allows other fields, as a serde type without `deny_unknown_fields`.
41
+ const struct = (required, optional = {}, defaulted = {}, open = false) => (v, p) => {
42
+ if (!isObject(v))
43
+ return fail(p, 'is not an object');
44
+ for (const k of Object.keys(v)) {
45
+ if (!open && !hasOwn(required, k) && !hasOwn(optional, k) && !hasOwn(defaulted, k))
46
+ fail(`${p}.${k}`, 'is not a known field');
47
+ }
48
+ for (const [k, check] of Object.entries(required)) {
49
+ if (!hasOwn(v, k))
50
+ fail(`${p}.${k}`, 'is missing');
51
+ check(v[k], `${p}.${k}`);
52
+ }
53
+ for (const [k, check] of Object.entries(optional)) {
54
+ if (hasOwn(v, k) && v[k] !== null)
55
+ check(v[k], `${p}.${k}`);
56
+ }
57
+ for (const [k, check] of Object.entries(defaulted)) {
58
+ if (hasOwn(v, k))
59
+ check(v[k], `${p}.${k}`);
60
+ }
61
+ };
62
+ const fileRef = struct({ id: str, size: u64, sha256: str });
63
+ const jobOutput = struct({ id: str, size: u64, sha256: str, segments: list(str) });
64
+ const jobEvidence = struct({ resultSha256: str, segments: list(list(str)) }, { log: jobOutput }, { message: str });
65
+ const attestationDoc = struct({
66
+ quote: str,
67
+ transportKey: str,
68
+ appHash: str,
69
+ nonce: str,
70
+ release: struct({ version: str, profile: str }, {}, {}, true),
71
+ cluster: str,
72
+ node: u64,
73
+ mock: bool,
74
+ }, { receiptKey: str, governance: obj, kms: obj, jobKey: str, clusterIdentity: str }, {}, true);
75
+ const stepRun = struct({
76
+ run: str,
77
+ step: str,
78
+ index: u32,
79
+ outcome: str,
80
+ attempt: u32,
81
+ outputs: list(fileRef),
82
+ usage: struct({ cpuMicros: str, gibMicros: str, fuel: str }),
83
+ }, { node: u64, jobKey: str, assignmentDigest: str, reportSha256: str, signature: str, job: jobEvidence });
84
+ const cachedRun = struct({ index: u32, cached: bool, cacheKey: str });
85
+ // Core's `RunEntry` is untagged: a cached run first, else a step run proof.
86
+ const runEntry = (v, p) => {
87
+ try {
88
+ cachedRun(v, p);
89
+ }
90
+ catch {
91
+ stepRun(v, p);
92
+ }
93
+ };
94
+ const pipelineReceipt = struct({
95
+ version: u32,
96
+ cluster: str,
97
+ app: str,
98
+ run: str,
99
+ pipeline: str,
100
+ release: str,
101
+ pipelineHash: str,
102
+ modules: map(str),
103
+ inputs: map(list(fileRef)),
104
+ params: map(any),
105
+ state: str,
106
+ startTsMs: u64,
107
+ endTsMs: u64,
108
+ steps: map(struct({ status: str, runs: list(runEntry) }, { reason: str })),
109
+ }, { costSoFar: str }, { jobAttestations: map(attestationDoc) });
110
+ /** Hex as core's `hex::decode` reads it (either case), of exactly `bytes` bytes: no trimming, nothing else. */
111
+ function strictHex(value, label, bytes) {
112
+ if (typeof value !== 'string' || value.length !== bytes * 2 || !/^[0-9a-fA-F]*$/.test(value)) {
113
+ throw new Error(`${label} is not ${bytes} bytes of hex`);
114
+ }
115
+ return fromHex(value, label, bytes);
116
+ }
117
+ /** A node id: a non-negative safe integer, as a JSON number. */
118
+ function nodeId(value, label) {
119
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)
120
+ throw new Error(`${label} is not a node id`);
121
+ return value;
122
+ }
123
+ /**
124
+ * Checks a receipt-key attestation as core's `verify_receipt_key` does: its quote binds the key, the
125
+ * governance and the `cluster` and `node` the caller asked for (never the document's own fields, which
126
+ * nothing signs). Answers the key and the governance rebuilt from its canonical fields.
127
+ */
128
+ export async function verifyReceiptKey(doc, nonce, cluster, node, policy) {
129
+ if (typeof doc.quote !== 'string')
130
+ throw new Error('the attestation carries no quote');
131
+ if (!doc.receiptKey)
132
+ throw new Error('the attestation names no receipt key');
133
+ if (!isObject(doc.governance))
134
+ throw new Error('the attestation names no governance');
135
+ const key = strictHex(doc.receiptKey, 'the receipt key', 32);
136
+ const suffix = fromHex(await receiptKeyBinding(key, doc.governance, cluster, node), 'binding', 32);
137
+ await verifyQuoteBinding(doc, nonce, suffix, policy, 'receipt key');
138
+ return { key, governance: JSON.parse(new TextDecoder().decode(governanceCanonical(doc.governance))) };
139
+ }
140
+ /**
141
+ * Verifies every replica of `app` (core's `Client::verify_app_cluster`): each one's quote over a fresh
142
+ * nonce, held to `policy`, binding its receipt key, the cluster's governance, and the cluster and node
143
+ * id the entry node names. Any replica error, a node id that differs from the document's, or replicas
144
+ * that attest other governance fails the whole check.
145
+ */
146
+ export async function verifyAppCluster(client, app, policy) {
147
+ const nonce = crypto.getRandomValues(new Uint8Array(32));
148
+ const answer = await client.apps.attestation({ app, nonce: hex(nonce) });
149
+ if (!isObject(answer) || typeof answer.cluster !== 'string' || !Array.isArray(answer.replicas)) {
150
+ throw new Error('the node answered a malformed attestation');
151
+ }
152
+ const cluster = answer.cluster;
153
+ const keys = new Map();
154
+ let governance;
155
+ for (const replica of answer.replicas) {
156
+ if (!isObject(replica))
157
+ throw new Error('a replica entry is not an object');
158
+ const node = nodeId(replica.node, 'a replica');
159
+ if (hasOwn(replica, 'error'))
160
+ throw new Error(`replica ${node} gave no attestation: ${String(replica.error)}`);
161
+ const doc = replica.attestation;
162
+ if (!isObject(doc))
163
+ throw new Error(`replica ${node} gave neither an attestation nor an error`);
164
+ if (nodeId(doc.node, `replica ${node}'s document`) !== node)
165
+ throw new Error(`replica ${node} answered as node ${String(doc.node)}`);
166
+ let attested;
167
+ try {
168
+ attested = await verifyReceiptKey(doc, nonce, cluster, node, policy);
169
+ }
170
+ catch (error) {
171
+ throw new Error(`replica ${node}: ${error instanceof Error ? error.message : String(error)}`);
172
+ }
173
+ // verifyReceiptKey answers the governance rebuilt from its canonical bytes, so equal JSON is equal rules.
174
+ if (governance && JSON.stringify(governance) !== JSON.stringify(attested.governance)) {
175
+ throw new Error(`replica ${node} attests other governance`);
176
+ }
177
+ governance = attested.governance;
178
+ keys.set(node, attested.key);
179
+ }
180
+ if (!governance)
181
+ throw new Error(`no replica of ${app} attested`);
182
+ return { keys, governance, cluster };
183
+ }
184
+ /** The receipt's canonical JSON (RFC 8785); any finite number is allowed, as core canonicalizes every number as f64. */
185
+ const canonicalReceipt = (receipt) => jcs(receipt, true);
186
+ /** The bytes a receipt's signature covers (core's `receipt_message`): the domain, then the canonical JSON. */
187
+ export const receiptMessage = (receipt) => concat(utf8(PIPELINE_RECEIPT_DOMAIN), utf8(canonicalReceipt(receipt)));
188
+ /**
189
+ * Whether `answer` is signed by `key` (core's `verify_pipeline_receipt`). Answers the receipt as parsed
190
+ * from the canonical bytes that were verified, checked against core's receipt schema.
191
+ */
192
+ export async function verifyReceiptSignature(answer, key) {
193
+ if (!isObject(answer))
194
+ throw new Error('the receipt answer is not an object');
195
+ const unknown = Object.keys(answer).find((k) => !['receipt', 'node', 'signature'].includes(k));
196
+ if (unknown !== undefined)
197
+ throw new Error(`the receipt answer's ${unknown} is not a known field`);
198
+ const signature = strictHex(answer.signature, 'the signature', 64);
199
+ const canonical = canonicalReceipt(answer.receipt);
200
+ const publicKey = await crypto.subtle.importKey('raw', buf(key), { name: 'Ed25519' }, false, ['verify']);
201
+ if (!(await crypto.subtle.verify('Ed25519', publicKey, buf(signature), buf(concat(utf8(PIPELINE_RECEIPT_DOMAIN), utf8(canonical)))))) {
202
+ throw new Error('the receipt is not signed by that key');
203
+ }
204
+ const receipt = JSON.parse(canonical);
205
+ pipelineReceipt(receipt, 'receipt');
206
+ return receipt;
207
+ }
208
+ const JOB_REPORT_DOMAIN = 'calimero.compute.report.v1\0';
209
+ const JOB_REPORT_LOG_DOMAIN = 'calimero.compute.report.log.v1\0';
210
+ const JOB_KEY_DOMAIN = 'calimero.tee-attest.job-key.v1';
211
+ const RECEIPT_VERSION_JOBS = 2;
212
+ const JOB_FAIL_REASONS = ['fuel', 'memory', 'trap', 'app-error', 'integrity', 'cancelled'];
213
+ const LEADER_FAIL_REASONS = ['lost', 'refused', 'timeout', 'quota', 'not-granted', 'too-large'];
214
+ const U64_MAX = 2n ** 64n - 1n;
215
+ const sha256 = async (bytes) => new Uint8Array(await crypto.subtle.digest('SHA-256', buf(bytes)));
216
+ const u32be = (n) => {
217
+ const out = new Uint8Array(4);
218
+ new DataView(out.buffer).setUint32(0, n, false);
219
+ return out;
220
+ };
221
+ const u64be = (n) => {
222
+ const big = BigInt(n);
223
+ if (big < 0n || big > U64_MAX)
224
+ throw new Error('a number is past 2^64-1');
225
+ const out = new Uint8Array(8);
226
+ new DataView(out.buffer).setBigUint64(0, big, false);
227
+ return out;
228
+ };
229
+ const prefixed = (text) => {
230
+ const bytes = utf8(text);
231
+ return concat(u32be(bytes.length), bytes);
232
+ };
233
+ /** The 32 bytes of a hash spelled as the wire spells it: 64 lowercase hex digits (core's `hash_bytes`). */
234
+ function hashBytes(text) {
235
+ if (typeof text !== 'string' || !/^[0-9a-f]{64}$/.test(text))
236
+ throw new Error('a hash is 64 lowercase hex digits');
237
+ return fromHex(text, 'hash', 32);
238
+ }
239
+ /** A decimal `u64` as the receipt spells usage: digits only. */
240
+ function decimal(text) {
241
+ if (!/^[0-9]+$/.test(text))
242
+ throw new Error(`${JSON.stringify(text)} is not a decimal integer`);
243
+ const n = BigInt(text);
244
+ if (n > U64_MAX)
245
+ throw new Error(`${JSON.stringify(text)} is not a decimal integer`);
246
+ return n;
247
+ }
248
+ function outputBytes(o) {
249
+ return concat(hashBytes(o.id), u64be(o.size), hashBytes(o.sha256), u32be(o.segments.length), ...o.segments.map(hashBytes));
250
+ }
251
+ /**
252
+ * The bytes a job node signs for one report (core's `report_message`): the domain, the assignment digest,
253
+ * the length-prefixed app, run, reason and message, the result's hash, the outputs, the usage, then the
254
+ * log after its own domain; integers big-endian, hashes as their 32 bytes.
255
+ */
256
+ export function reportMessage(f) {
257
+ return concat(utf8(JOB_REPORT_DOMAIN), hashBytes(f.assignment), prefixed(f.app), prefixed(f.run), u32be(f.attempt), new Uint8Array([f.reason === null ? 0 : 1]), prefixed(f.reason ?? ''), prefixed(f.message), hashBytes(f.resultSha256), u32be(f.outputs.length), ...f.outputs.map(outputBytes), ...f.usage.map((n) => u64be(decimal(n))), ...(f.log ? [utf8(JOB_REPORT_LOG_DOMAIN), outputBytes(f.log)] : []));
258
+ }
259
+ /**
260
+ * What a job-node attestation's quote binds after the nonce (core's `job_key_binding`): both keys, the
261
+ * release and cluster (length-prefixed), the node id, and the cluster identity when there is one. Hex.
262
+ */
263
+ export async function jobKeyBinding(transportKey, jobKey, release, cluster, node, clusterIdentity) {
264
+ return hex(await sha256(concat(utf8(JOB_KEY_DOMAIN), transportKey, jobKey, prefixed(release), prefixed(cluster), u64be(node), clusterIdentity ?? new Uint8Array(0))));
265
+ }
266
+ /** The reason a job signed for `outcome`: `{ reason }` (`null` when done), or `null` for an end only the leader gives. */
267
+ function signedReason(outcome, reported) {
268
+ if (outcome === 'done')
269
+ return { reason: null };
270
+ if (outcome === 'cancelled')
271
+ return reported ? { reason: 'cancelled' } : null;
272
+ const bad = () => new Error(`the outcome ${JSON.stringify(outcome)} is not one a run ends with`);
273
+ if (!outcome.startsWith('failed:'))
274
+ throw bad();
275
+ const reason = outcome.slice('failed:'.length);
276
+ if (JOB_FAIL_REASONS.includes(reason))
277
+ return { reason };
278
+ if (!LEADER_FAIL_REASONS.includes(reason))
279
+ throw bad();
280
+ return null;
281
+ }
282
+ // The Ed25519 group order: an S at or above it is a malleated signature, refused as verify_strict does.
283
+ const L = 2n ** 252n + 27742317777372353535851937790883648493n;
284
+ // The Ed25519 points of order dividing 8, for `verify_strict`'s refusal of a small-order key or R.
285
+ const P = 2n ** 255n - 19n;
286
+ const D = (((P - 121665n) % P) * modPow(121666n, P - 2n)) % P;
287
+ function modPow(base, exp) {
288
+ let result = 1n;
289
+ base %= P;
290
+ for (; exp > 0n; exp >>= 1n, base = (base * base) % P)
291
+ if (exp & 1n)
292
+ result = (result * base) % P;
293
+ return result;
294
+ }
295
+ function isSmallOrder(encoded) {
296
+ let y = 0n;
297
+ for (let i = 31; i >= 0; i--)
298
+ y = (y << 8n) | BigInt(encoded[i] & (i === 31 ? 0x7f : 0xff));
299
+ y %= P;
300
+ const sign = (encoded[31] >> 7) & 1;
301
+ const y2 = (y * y) % P;
302
+ const x2 = (((y2 - 1n + P) % P) * modPow((D * y2 + 1n) % P, P - 2n)) % P;
303
+ let x = modPow(x2, (P + 3n) / 8n);
304
+ if ((x * x) % P !== x2)
305
+ x = (x * modPow(2n, (P - 1n) / 4n)) % P;
306
+ if ((x * x) % P !== x2)
307
+ return false;
308
+ if (Number(x & 1n) !== sign)
309
+ x = (P - x) % P;
310
+ let pt = [x, y];
311
+ for (let i = 0; i < 3; i++) {
312
+ const [x1, y1] = pt;
313
+ const k = (D * x1 * x1 * y1 * y1) % P;
314
+ pt = [(2n * x1 * y1 * modPow((1n + k) % P, P - 2n)) % P, ((y1 * y1 + x1 * x1) * modPow((1n - k + P) % P, P - 2n)) % P];
315
+ }
316
+ return pt[0] === 0n && pt[1] === 1n;
317
+ }
318
+ /** Ed25519 as core's `verify_strict` reads it: a non-canonical S and a small-order key or R are refused as well as a bad signature. */
319
+ async function verifyStrict(key, message, signature) {
320
+ let s = 0n;
321
+ for (let i = 63; i >= 32; i--)
322
+ s = (s << 8n) | BigInt(signature[i]);
323
+ if (s >= L || isSmallOrder(key) || isSmallOrder(signature.slice(0, 32)))
324
+ return false;
325
+ const publicKey = await crypto.subtle.importKey('raw', buf(key), { name: 'Ed25519' }, false, ['verify']);
326
+ return crypto.subtle.verify('Ed25519', publicKey, buf(signature), buf(message));
327
+ }
328
+ /**
329
+ * Checks one step run's proof (core's `check_proof`): it is the run the receipt's run, step and index
330
+ * name, and either the leader ended it (no report, outputs or usage) or its job node signed a report that
331
+ * says exactly what the proof says. Answers the job key and node of a signed one.
332
+ */
333
+ async function checkProof(receipt, step, p) {
334
+ const expected = `${receipt.run}.${step}.${p.index}`;
335
+ if (p.run !== expected || p.step !== step)
336
+ throw new Error(`the proof of ${p.run} is listed as ${expected}`);
337
+ const reported = p.signature != null;
338
+ const signed = signedReason(p.outcome, reported);
339
+ if (!signed) {
340
+ const zero = [p.usage.cpuMicros, p.usage.gibMicros, p.usage.fuel].every((n) => n === '0');
341
+ if (reported || p.reportSha256 != null || p.job != null || p.outputs.length > 0 || !zero) {
342
+ throw new Error(`${p.run} ended ${p.outcome} by the leader, yet names a report, outputs or usage`);
343
+ }
344
+ return null;
345
+ }
346
+ const missing = (what) => new Error(`${p.run} ended ${p.outcome} but its proof has no ${what}`);
347
+ if (p.node == null)
348
+ throw missing('job node');
349
+ if (p.jobKey == null)
350
+ throw missing('job key');
351
+ if (p.assignmentDigest == null)
352
+ throw missing('assignment digest');
353
+ if (p.reportSha256 == null)
354
+ throw missing('report hash');
355
+ if (p.signature == null)
356
+ throw missing('report signature');
357
+ if (p.job == null)
358
+ throw missing('job evidence (it ended before receipts carried it)');
359
+ const job = p.job;
360
+ if (job.segments.length !== p.outputs.length) {
361
+ throw new Error(`${p.run}: the job evidence lists segments for ${job.segments.length} outputs, the proof ${p.outputs.length}`);
362
+ }
363
+ const outputs = p.outputs.map((o, i) => ({ id: o.id, size: o.size, sha256: o.sha256, segments: job.segments[i] }));
364
+ let message;
365
+ try {
366
+ message = reportMessage({
367
+ assignment: p.assignmentDigest,
368
+ app: receipt.app,
369
+ run: p.run,
370
+ attempt: p.attempt,
371
+ reason: signed.reason,
372
+ message: job.message ?? '',
373
+ resultSha256: job.resultSha256,
374
+ outputs,
375
+ usage: [p.usage.cpuMicros, p.usage.gibMicros, p.usage.fuel],
376
+ log: job.log,
377
+ });
378
+ }
379
+ catch (error) {
380
+ throw new Error(`${p.run}: ${error instanceof Error ? error.message : String(error)}`);
381
+ }
382
+ if (hex(await sha256(message)) !== p.reportSha256)
383
+ throw new Error(`${p.run}: the report hash is not that of what the proof says`);
384
+ const key = hashBytes(p.jobKey);
385
+ if (!/^[0-9a-fA-F]{128}$/.test(p.signature))
386
+ throw new Error(`${p.run}: the report signature is not 64 bytes of hex`);
387
+ if (!(await verifyStrict(key, message, fromHex(p.signature, 'signature', 64)))) {
388
+ throw new Error(`${p.run}: the job key did not sign what the proof says`);
389
+ }
390
+ return { key: p.jobKey, node: p.node };
391
+ }
392
+ /**
393
+ * Checks every step run's proof of a version 2 receipt (core's `verify_job_reports`), each step's runs
394
+ * listed once in index order, and answers each job key that signed a report with the node it ran on; a
395
+ * key named on two nodes is refused. Whose key each is (its attestation) is for the caller to verify.
396
+ * What a job signed is proven; the rest (step and run states, cached runs, and the node and key a
397
+ * leader-ended run names) is the signing replica's word.
398
+ */
399
+ export async function verifyJobReports(receipt) {
400
+ if (receipt.version !== RECEIPT_VERSION_JOBS) {
401
+ throw new Error(`the receipt is version ${receipt.version}; only version ${RECEIPT_VERSION_JOBS} carries what each job signed`);
402
+ }
403
+ const keys = new Map();
404
+ for (const [step, s] of Object.entries(receipt.steps)) {
405
+ for (const [i, entry] of s.runs.entries()) {
406
+ if (entry.index !== i)
407
+ throw new Error(`step ${step} lists run ${entry.index} where run ${i} belongs`);
408
+ if ('cached' in entry) {
409
+ if (!entry.cached)
410
+ throw new Error(`step ${step} run ${i} is listed as not cached`);
411
+ continue;
412
+ }
413
+ const proved = await checkProof(receipt, step, entry);
414
+ if (proved && (keys.get(proved.key) ?? proved.node) !== proved.node)
415
+ throw new Error(`job key ${proved.key} is named on two nodes`);
416
+ if (proved)
417
+ keys.set(proved.key, proved.node);
418
+ }
419
+ }
420
+ return keys;
421
+ }
422
+ /**
423
+ * Checks that `receipt` carries the attestation of job key `key`: a job node's quote, under `policy`,
424
+ * binding that key to node `node` of `cluster` taking work from the cluster identity the receipt names.
425
+ */
426
+ async function verifyJobAttestation(receipt, cluster, key, node, policy) {
427
+ const doc = receipt.jobAttestations && hasOwn(receipt.jobAttestations, key) ? receipt.jobAttestations[key] : undefined;
428
+ if (!doc)
429
+ throw new Error('the receipt carries no attestation for it');
430
+ if (doc.jobKey !== key)
431
+ throw new Error("its attestation is another key's");
432
+ if (doc.node !== node || doc.cluster !== cluster) {
433
+ throw new Error(`it is attested as node ${doc.node} of cluster ${doc.cluster}, not node ${node} of ${cluster}`);
434
+ }
435
+ if (doc.clusterIdentity !== receipt.cluster)
436
+ throw new Error('its job node takes work from another cluster identity');
437
+ let nonce;
438
+ try {
439
+ nonce = hashBytes(doc.nonce);
440
+ }
441
+ catch {
442
+ throw new Error("its attestation's nonce is not 32 bytes of hex");
443
+ }
444
+ const binding = await jobKeyBinding(strictHex(doc.transportKey, 'the transport key', 32), fromHex(key, 'the job key', 32), doc.release.version, doc.cluster, doc.node, strictHex(doc.clusterIdentity, 'the cluster identity', 32));
445
+ await verifyQuoteBinding(doc, nonce, fromHex(binding, 'binding', 32), policy, 'job key');
446
+ }
447
+ /**
448
+ * Checks that the node that answered holds a receipt key attested under `policy` ({@link verifyAppCluster})
449
+ * and signed `answer` with it, that the receipt is for `app` and `run`, that every job report it names is
450
+ * signed by its job key ({@link verifyJobReports}), and that each such key is a job node's of the attested
451
+ * cluster and the receipt's cluster identity, under `policy`. A version 1 receipt is refused. Answers the receipt.
452
+ */
453
+ export async function verifyPipelineReceipt(client, app, run, answer, policy) {
454
+ const { keys, cluster } = await verifyAppCluster(client, app, policy);
455
+ if (!isObject(answer))
456
+ throw new Error('the receipt answer is not an object');
457
+ const node = nodeId(answer.node, 'the receipt answer');
458
+ const key = keys.get(node);
459
+ if (!key)
460
+ throw new Error(`node ${node} is not an attested replica of ${app}`);
461
+ const receipt = await verifyReceiptSignature(answer, key);
462
+ if (receipt.app !== app)
463
+ throw new Error(`the receipt is for app ${receipt.app}, not ${app}`);
464
+ if (receipt.run !== run)
465
+ throw new Error(`the receipt is for run ${receipt.run}, not ${run}`);
466
+ for (const [jobKey, jobNode] of await verifyJobReports(receipt)) {
467
+ try {
468
+ await verifyJobAttestation(receipt, cluster, jobKey, jobNode, policy);
469
+ }
470
+ catch (error) {
471
+ throw new Error(`job key ${jobKey}: ${error instanceof Error ? error.message : String(error)}`);
472
+ }
473
+ }
474
+ return receipt;
475
+ }