@coderifts/sdk 3.13.1 → 3.13.3

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 (33) hide show
  1. package/dist/cjs/authorize.d.ts +134 -0
  2. package/dist/cjs/authorize.d.ts.map +1 -0
  3. package/dist/cjs/authorize.js +118 -0
  4. package/dist/cjs/authorize.js.map +1 -0
  5. package/dist/cjs/index.d.ts +2 -0
  6. package/dist/cjs/index.d.ts.map +1 -1
  7. package/dist/cjs/index.js +10 -1
  8. package/dist/cjs/index.js.map +1 -1
  9. package/dist/cjs/vendor/receipt-verifier/VENDOR.sha256 +24 -0
  10. package/dist/cjs/vendor/receipt-verifier/arity.js +53 -0
  11. package/dist/cjs/vendor/receipt-verifier/evidence-root.js +188 -0
  12. package/dist/cjs/vendor/receipt-verifier/verified-execution-binding.js +316 -0
  13. package/dist/cjs/vendor/receipt-verifier/verify-evidence.js +410 -0
  14. package/dist/cjs/vendor/receipt-verifier/verify-grant.js +564 -0
  15. package/dist/cjs/vendor/receipt-verifier/verify-prove-transcript.js +72 -0
  16. package/dist/cjs/vendor/receipt-verifier/verify.js +454 -0
  17. package/dist/esm/authorize.d.ts +134 -0
  18. package/dist/esm/authorize.d.ts.map +1 -0
  19. package/dist/esm/authorize.js +114 -0
  20. package/dist/esm/authorize.js.map +1 -0
  21. package/dist/esm/index.d.ts +2 -0
  22. package/dist/esm/index.d.ts.map +1 -1
  23. package/dist/esm/index.js +7 -0
  24. package/dist/esm/index.js.map +1 -1
  25. package/dist/esm/vendor/receipt-verifier/VENDOR.sha256 +24 -0
  26. package/dist/esm/vendor/receipt-verifier/arity.js +53 -0
  27. package/dist/esm/vendor/receipt-verifier/evidence-root.js +188 -0
  28. package/dist/esm/vendor/receipt-verifier/verified-execution-binding.js +316 -0
  29. package/dist/esm/vendor/receipt-verifier/verify-evidence.js +410 -0
  30. package/dist/esm/vendor/receipt-verifier/verify-grant.js +564 -0
  31. package/dist/esm/vendor/receipt-verifier/verify-prove-transcript.js +72 -0
  32. package/dist/esm/vendor/receipt-verifier/verify.js +454 -0
  33. package/package.json +5 -4
@@ -0,0 +1,410 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * THE CANONICAL EVIDENCE VERIFIER — every signature in a prove envelope, not just one.
5
+ *
6
+ * ── WHAT 1423 MEASURED ──────────────────────────────────────────────────────────────────────
7
+ *
8
+ * A recorded artifact is protected by two different things, and they answer different questions:
9
+ *
10
+ * the PIN (sha256) are these the bytes we vendored? → tamper-EVIDENT
11
+ * the SIGNATURES did the named issuers produce them? → AUTHENTIC
12
+ *
13
+ * Conformance checked the pin and exactly one signature (the correlation). So an auditor could
14
+ * flip the last character of `issuance.execution_grant`, recompute the pin, and the profile still
15
+ * graded COVERED — reproduced, both mutations, before this file existed. The pin cannot catch that
16
+ * on its own: whoever edits the bytes also owns the file the hash is written in.
17
+ *
18
+ * capability-demo's `prove --check` already refused both mutations. That is the shape of the bug:
19
+ * not a missing capability anywhere, but TWO verifiers that disagreed about what checking means.
20
+ * So this is a shared core rather than a third implementation — one place to fix, one place to
21
+ * drift from, and consumers that can be tested against each other.
22
+ *
23
+ * ── WHAT IT REFUSES TO DO ───────────────────────────────────────────────────────────────────
24
+ *
25
+ * An ABSENT token is reported ABSENT and never as verified. This matters more than it sounds: a
26
+ * verifier that returns "ok" for an envelope carrying no grant at all would let the strongest
27
+ * possible tamper — deletion — read as a pass. The caller says which slots it requires
28
+ * (`required`), and absence of a required slot is a failure with its own reason.
29
+ *
30
+ * It authenticates SIGNATURES. It does not decide whether the run's claims are true: a correctly
31
+ * signed transcript of a failing run is authentic and still a failure. Callers keep grading.
32
+ */
33
+
34
+ const crypto = require('node:crypto');
35
+
36
+ const { verifyReceipt, keyringFromDocument } = require('./verify.js');
37
+ const { verifyExecutionGrant } = require('./verify-grant.js');
38
+ const { verifyProveTranscript } = require('./verify-prove-transcript.js');
39
+ const {
40
+ ROOT_V, SLOTS, SLOT_NAMES, digestToken, verifyEvidenceRoot, canonicalJson,
41
+ } = require('./evidence-root.js');
42
+
43
+ const CORRELATION_V = 'cr.exec.correlation.v1';
44
+
45
+ /**
46
+ * The version four consumers must agree on. `verifyEvidenceRootBinding` returns it, so "prove,
47
+ * conformance, the guard and the provider all ran the same library" is something a report can
48
+ * SHOW rather than assert. Bump it when a check is added, removed or changed in meaning.
49
+ */
50
+ const LIBRARY_VERSION = 'cr.evidence-verifier.1';
51
+ const US = '\x1f';
52
+
53
+ /** The slots this verifier knows how to authenticate. */
54
+ const SLOT = Object.freeze({
55
+ CHAIN_RECEIPT: 'chain_receipt',
56
+ EXECUTION_GRANT: 'execution_grant',
57
+ TRANSCRIPT_TOKEN: 'transcript_token',
58
+ CORRELATION: 'correlation',
59
+ ATTESTATION: 'atomic_attestation',
60
+ });
61
+
62
+ /** Which keyring signs which slot. Stated as data so a caller can read it, not infer it. */
63
+ const SIGNER = Object.freeze({
64
+ [SLOT.CHAIN_RECEIPT]: 'issuer',
65
+ [SLOT.EXECUTION_GRANT]: 'issuer',
66
+ [SLOT.TRANSCRIPT_TOKEN]: 'executor',
67
+ [SLOT.CORRELATION]: 'executor',
68
+ [SLOT.ATTESTATION]: 'executor',
69
+ });
70
+
71
+ function toKeyring(doc) {
72
+ if (!doc) return null;
73
+ if (doc instanceof Map) return doc;
74
+ return keyringFromDocument(doc);
75
+ }
76
+
77
+ function keyFor(keyring, kid) {
78
+ if (!keyring) return null;
79
+ const entry = keyring instanceof Map ? keyring.get(kid) : keyring[kid];
80
+ if (!entry) return null;
81
+ return entry.publicKey || entry.public_key || entry;
82
+ }
83
+
84
+ /** Rebuilt from the fields, never read back from `correlation_hash`. */
85
+ function correlationPreimage(c) {
86
+ return [CORRELATION_V, c.scope_hash, c.contract_commit, c.contract_path, c.readback_commit]
87
+ .join(US);
88
+ }
89
+
90
+ /**
91
+ * The correlation is a bare Ed25519 signature over a field-joined preimage rather than a token,
92
+ * so it gets its own small verifier here instead of a shape it does not have.
93
+ */
94
+ function verifyCorrelation(c, publicKey) {
95
+ if (!c || c.v !== CORRELATION_V) {
96
+ return { valid: false, status: 'CORRELATION_MALFORMED', reason: 'not_a_correlation' };
97
+ }
98
+ if (!publicKey) {
99
+ return { valid: false, status: 'CORRELATION_UNKNOWN_KEY', reason: 'unknown_kid' };
100
+ }
101
+ const preimage = correlationPreimage(c);
102
+ const expected = `sha256:${crypto.createHash('sha256').update(preimage, 'utf8').digest('hex')}`;
103
+ // The hash is checked BEFORE the signature so a mutated binding field is named as what it is —
104
+ // a field that no longer matches its own digest — rather than as a generic bad signature.
105
+ if (c.correlation_hash && c.correlation_hash !== expected) {
106
+ return { valid: false, status: 'CORRELATION_UNBOUND', reason: 'correlation_hash_mismatch' };
107
+ }
108
+ let ok = false;
109
+ try {
110
+ ok = crypto.verify(
111
+ null, Buffer.from(preimage, 'utf8'), publicKey, Buffer.from(String(c.signature), 'base64url'),
112
+ );
113
+ } catch (_) {
114
+ return { valid: false, status: 'CORRELATION_INVALID_SIGNATURE', reason: 'signature_error' };
115
+ }
116
+ return ok
117
+ ? { valid: true, status: 'CORRELATION_VALID' }
118
+ : { valid: false, status: 'CORRELATION_INVALID_SIGNATURE', reason: 'signature_mismatch' };
119
+ }
120
+
121
+ /** cr.atomic.execution.attestation.v1 | <kid> | b64url(preimage) | <sig> */
122
+ function verifyAtomicAttestationToken(token, keyring) {
123
+ const seg = String(token).split('|');
124
+ if (seg.length !== 4 || seg[0] !== 'cr.atomic.execution.attestation.v1' || seg.some((s) => !s)) {
125
+ return { valid: false, status: 'ATTEST_MALFORMED', reason: 'malformed_structure' };
126
+ }
127
+ const publicKey = keyFor(keyring, seg[1]);
128
+ if (!publicKey) return { valid: false, status: 'ATTEST_UNKNOWN_KEY', reason: 'unknown_kid', kid: seg[1] };
129
+ let preimage;
130
+ try { preimage = Buffer.from(seg[2], 'base64url').toString('utf8'); } catch (_) {
131
+ return { valid: false, status: 'ATTEST_MALFORMED', reason: 'bad_preimage', kid: seg[1] };
132
+ }
133
+ let ok = false;
134
+ try {
135
+ ok = crypto.verify(null, Buffer.from(preimage, 'utf8'), publicKey, Buffer.from(seg[3], 'base64url'));
136
+ } catch (_) {
137
+ return { valid: false, status: 'ATTEST_INVALID_SIGNATURE', reason: 'signature_error', kid: seg[1] };
138
+ }
139
+ return ok
140
+ ? { valid: true, status: 'ATTEST_VALID', kid: seg[1], preimage }
141
+ : { valid: false, status: 'ATTEST_INVALID_SIGNATURE', reason: 'signature_mismatch', kid: seg[1] };
142
+ }
143
+
144
+ /**
145
+ * Authenticate every signed token an artifact carries.
146
+ *
147
+ * @param {object} artifact a cr.prove.artifact.v1 document
148
+ * @param {object} o
149
+ * @param {object|Map} [o.issuerKeys] registry document (or Map) for the CodeRifts issuer
150
+ * @param {object|Map} [o.executorKeys] registry document (or Map) for the executor
151
+ * @param {string[]} [o.required] slots that MUST be present; absence is a failure
152
+ * @param {number} [o.now] clock injection; defaults to each token's own issuance
153
+ * instant, so a recorded artifact is authenticated as of
154
+ * when it was made rather than expiring in the vendor tree
155
+ * @returns {{ok: boolean, slots: object[], failures: string[]}}
156
+ */
157
+ function verifyEvidenceEnvelope(artifact, o = {}) {
158
+ const issuer = toKeyring(o.issuerKeys);
159
+ const executor = toKeyring(o.executorKeys);
160
+ const required = new Set(Array.isArray(o.required) ? o.required : []);
161
+ const slots = [];
162
+ const failures = [];
163
+
164
+ const record = (name, present, result) => {
165
+ const entry = {
166
+ slot: name,
167
+ signer: SIGNER[name],
168
+ present,
169
+ verified: present ? result.valid === true : false,
170
+ status: present ? result.status : 'ABSENT',
171
+ reason: present ? (result.reason || null) : 'not_present_in_envelope',
172
+ kid: present ? (result.kid || null) : null,
173
+ };
174
+ slots.push(entry);
175
+ if (!present && required.has(name)) {
176
+ failures.push(`the ${name} is absent from the envelope, and this profile requires it`);
177
+ } else if (present && !entry.verified) {
178
+ failures.push(`the ${name} signature does not verify (${entry.status}${entry.reason ? `: ${entry.reason}` : ''})`);
179
+ }
180
+ return entry;
181
+ };
182
+
183
+ const iss = artifact && artifact.issuance ? artifact.issuance : null;
184
+
185
+ // ── issuer-signed ────────────────────────────────────────────────────────────────────────
186
+ const grantTok = iss && iss.execution_grant;
187
+ if (grantTok) {
188
+ // now = the grant's own not_before/iat. A RECORDED grant is short-lived by design; judging it
189
+ // against today's clock would report every vendored fixture as expired, which says something
190
+ // about the calendar and nothing about the signature.
191
+ const g = iss.grant || {};
192
+ const at = Number.isFinite(o.now) ? o.now : Date.parse(g.not_before || g.iat || artifact.started_at);
193
+ record(SLOT.EXECUTION_GRANT, true, verifyExecutionGrant(grantTok, {
194
+ ctx: { keyring: issuer, expectedKid: null },
195
+ now: Number.isFinite(at) ? at + 1000 : undefined,
196
+ }));
197
+ } else {
198
+ record(SLOT.EXECUTION_GRANT, false, {});
199
+ }
200
+
201
+ const receiptTok = iss && iss.chain_receipt;
202
+ if (receiptTok) {
203
+ const at = Number.isFinite(o.now) ? o.now : Date.parse(artifact.started_at);
204
+ record(SLOT.CHAIN_RECEIPT, true, verifyReceipt(receiptTok, {
205
+ ctx: { keyring: issuer, expectedKid: null },
206
+ now: Number.isFinite(at) ? at + 1000 : undefined,
207
+ }));
208
+ } else {
209
+ record(SLOT.CHAIN_RECEIPT, false, {});
210
+ }
211
+
212
+ // ── executor-signed ──────────────────────────────────────────────────────────────────────
213
+ if (artifact && artifact.transcript_token) {
214
+ record(SLOT.TRANSCRIPT_TOKEN, true,
215
+ verifyProveTranscript(artifact.transcript_token, { keyring: executor }));
216
+ } else {
217
+ record(SLOT.TRANSCRIPT_TOKEN, false, {});
218
+ }
219
+
220
+ if (artifact && artifact.correlation) {
221
+ const c = artifact.correlation;
222
+ const kid = executor && executor instanceof Map ? [...executor.keys()][0] : null;
223
+ record(SLOT.CORRELATION, true, verifyCorrelation(c, keyFor(executor, kid)));
224
+ } else {
225
+ record(SLOT.CORRELATION, false, {});
226
+ }
227
+
228
+ const att = artifact && artifact.atomic_execution_attestation
229
+ ? artifact.atomic_execution_attestation
230
+ : (artifact && artifact.attestation) || null;
231
+ if (typeof att === 'string' && att.length > 0) {
232
+ record(SLOT.ATTESTATION, true, verifyAtomicAttestationToken(att, executor));
233
+ } else {
234
+ record(SLOT.ATTESTATION, false, {});
235
+ }
236
+
237
+ return { ok: failures.length === 0, slots, failures };
238
+ }
239
+
240
+ /**
241
+ * THE ROOT CHECK — is this set of tokens ONE run?
242
+ *
243
+ * Ten questions, in the order a reader would ask them. Each is answered against something the
244
+ * producer signed, never against a value copied out of the thing being checked.
245
+ *
246
+ * 1 the root's own signature verifies against the executor key
247
+ * 2 every mandatory slot is present in the root (absence is refused, not skipped)
248
+ * 3 every token PRESENT in the envelope has the EXACT byte digest the root recorded
249
+ * 4 every token the root records is present to be checked, or named as unavailable
250
+ * 5 the grant's claims match the root's claims (grant_id, scope, policy)
251
+ * 6 grant.receipt_hash === sha256(the chain_receipt bytes actually carried)
252
+ * 7 grant_id === the consumed jti === the attested jti
253
+ * 8 run_id === the transcript's run_id === the correlation's scope binding
254
+ * 9 the outer artifact's summaries agree with what the tokens say
255
+ * 10 the verifier reports its own version, so four consumers can be shown to run one library
256
+ *
257
+ * @param {object} artifact
258
+ * @param {object} o
259
+ * @param {import('crypto').KeyObject} o.executorKey the key the root and correlation are signed with
260
+ * @param {object} [o.sidecars] tokens the artifact does not carry but the caller holds, by slot
261
+ * name (e.g. provider_readback bytes, atomic_attestation token)
262
+ */
263
+ function verifyEvidenceRootBinding(artifact, o = {}) {
264
+ const failures = [];
265
+ const checks = [];
266
+ const note = (id, ok, detail) => { checks.push({ id, ok, detail }); if (!ok) failures.push(detail); };
267
+
268
+ const root = artifact && artifact.evidence_root;
269
+ if (!root) {
270
+ return {
271
+ ok: false,
272
+ present: false,
273
+ library: LIBRARY_VERSION,
274
+ checks: [],
275
+ failures: ['cross_run_collage: the artifact carries no cr.evidence.root.v1, so nothing binds '
276
+ + 'its tokens to ONE run'],
277
+ };
278
+ }
279
+
280
+ // 1 — the root's own signature.
281
+ const rv = verifyEvidenceRoot(root, o.executorKey);
282
+ note('root_signature', rv.valid,
283
+ rv.valid ? 'the evidence root is signed by the executor key'
284
+ : `the evidence root signature does not verify (${rv.status}: ${rv.reason})`);
285
+ // Everything below reads the root. A root that does not verify is not a source of truth about
286
+ // anything, so the remaining checks are not run rather than run against unsigned values.
287
+ if (!rv.valid) return { ok: false, present: true, library: LIBRARY_VERSION, checks, failures };
288
+
289
+ // The tokens as they travel, by slot. Sidecars are tokens the artifact does not republish but
290
+ // the caller holds — the provider readback is one, and binding it is what stops a readback from
291
+ // another run being paired with this artifact.
292
+ const carried = {
293
+ chain_receipt: artifact.issuance && artifact.issuance.chain_receipt,
294
+ execution_grant: artifact.issuance && artifact.issuance.execution_grant,
295
+ transcript_token: artifact.transcript_token,
296
+ correlation: artifact.correlation || null,
297
+ atomic_attestation: null,
298
+ provider_readback: null,
299
+ ...(o.sidecars || {}),
300
+ };
301
+
302
+ // 2 — mandatory slots. A root that omits a token would make deletion look like "not applicable".
303
+ for (const name of SLOT_NAMES) {
304
+ if (!SLOTS[name].mandatory) continue;
305
+ note(`root_slot_${name}`, root.artifact_digests && root.artifact_digests[name] != null,
306
+ `the root records no digest for the mandatory ${name}`);
307
+ }
308
+
309
+ // 3 & 4 — EXACT BYTES. This is the check the collage fails: a substituted token is authentic and
310
+ // has different bytes, so its digest cannot match whatever it says inside.
311
+ for (const name of SLOT_NAMES) {
312
+ const want = root.artifact_digests ? root.artifact_digests[name] : null;
313
+ const got = digestToken(carried[name]);
314
+ if (want == null && got == null) continue;
315
+ if (want == null) {
316
+ note(`digest_${name}`, false,
317
+ `the envelope carries a ${name} the root does not account for — an extra token is not evidence`);
318
+ continue;
319
+ }
320
+ if (got == null) {
321
+ // Not a failure for an optional slot the caller simply did not supply: it is UNCHECKED, and
322
+ // saying so beats grading a token nobody looked at.
323
+ note(`digest_${name}`, !SLOTS[name].mandatory,
324
+ `the root records a ${name} digest but no such token was supplied to check it`);
325
+ continue;
326
+ }
327
+ note(`digest_${name}`, got === want,
328
+ got === want ? `${name} bytes match the root`
329
+ : `${name} does not match the root's digest — these bytes were not emitted by run ${root.run_id}`);
330
+ }
331
+
332
+ // 5 — the grant's own claims vs the root's.
333
+ const grantBody = (() => {
334
+ const t = carried.execution_grant;
335
+ if (typeof t !== 'string') return null;
336
+ try { return JSON.parse(Buffer.from(t.split('.')[0], 'base64url').toString('utf8')); } catch (_) { return null; }
337
+ })();
338
+ if (grantBody) {
339
+ const gid = grantBody.grant_id || grantBody.jti || null;
340
+ note('claim_grant_id', root.grant_id == null || root.grant_id === gid,
341
+ `the root names grant ${root.grant_id} but the grant it carries is ${gid}`);
342
+ const scope = grantBody.after_payload_hash || grantBody.scope_hash || null;
343
+ note('claim_scope_hash', root.scope_hash == null || root.scope_hash === scope,
344
+ `the root names scope ${root.scope_hash} but the grant scopes ${scope}`);
345
+ note('claim_policy_hash', root.policy_hash == null || grantBody.policy_hash == null
346
+ || root.policy_hash === grantBody.policy_hash,
347
+ 'the root and the grant disagree about policy_hash');
348
+
349
+ // 6 — grant → receipt, by the digest of the receipt actually carried, not by a copied string.
350
+ const rh = grantBody.receipt_hash || grantBody.receipt_digest || null;
351
+ if (rh && typeof carried.chain_receipt === 'string') {
352
+ const actual = digestToken(carried.chain_receipt);
353
+ note('grant_binds_receipt', rh === actual,
354
+ `the grant was issued against receipt ${rh}, but the receipt carried here hashes to ${actual}`);
355
+ }
356
+ }
357
+
358
+ // 7 — one grant, through consume and attestation. Read from the continuity block the producer
359
+ // signed into the transcript, re-derived rather than trusted: the identities must agree with the
360
+ // root's grant_id too, or the root and the chain are describing different executions.
361
+ const ids = (artifact.continuity && artifact.continuity.identities) || {};
362
+ if (root.grant_id != null && ids.issued_jti != null) {
363
+ const oneGrant = ids.issued_jti === root.grant_id
364
+ && ids.consumed_jti === root.grant_id
365
+ && ids.attestation_jti === root.grant_id;
366
+ note('identity_chain', oneGrant,
367
+ `the root names grant ${root.grant_id}, the chain records issued ${ids.issued_jti} / `
368
+ + `consumed ${ids.consumed_jti} / attested ${ids.attestation_jti}`);
369
+ }
370
+
371
+ // 8 — one run, through the transcript and the correlation.
372
+ note('run_id_artifact', artifact.run_id === root.run_id,
373
+ `the artifact says run ${artifact.run_id}, the root says ${root.run_id}`);
374
+ if (carried.correlation && root.scope_hash != null) {
375
+ note('run_id_correlation', carried.correlation.scope_hash === root.scope_hash,
376
+ `the correlation binds scope ${carried.correlation.scope_hash}, the root ${root.scope_hash}`);
377
+ }
378
+ if (root.contract_commit != null && carried.correlation) {
379
+ note('contract_commit', carried.correlation.contract_commit === root.contract_commit,
380
+ `the correlation names commit ${carried.correlation.contract_commit}, the root ${root.contract_commit}`);
381
+ }
382
+
383
+ // 9 — the outer summary vs the tokens. The artifact is a wrapper; a wrapper that disagrees with
384
+ // what it wraps is the thing that is wrong.
385
+ const tv = typeof carried.transcript_token === 'string'
386
+ ? verifyProveTranscript(carried.transcript_token, { keyring: null, publicKey: o.executorKey })
387
+ : null;
388
+ if (tv && tv.valid && tv.payload) {
389
+ const claimed = tv.payload.run_id || tv.payload.deployment_id || null;
390
+ if (claimed && tv.payload.run_id) {
391
+ note('transcript_run_id', tv.payload.run_id === root.run_id,
392
+ `the signed transcript is run ${tv.payload.run_id}, the root says ${root.run_id}`);
393
+ }
394
+ }
395
+
396
+ return { ok: failures.length === 0, present: true, library: LIBRARY_VERSION, checks, failures };
397
+ }
398
+
399
+ module.exports = {
400
+ verifyEvidenceRootBinding,
401
+ LIBRARY_VERSION,
402
+ ROOT_V,
403
+ verifyEvidenceEnvelope,
404
+ verifyCorrelation,
405
+ verifyAtomicAttestationToken,
406
+ correlationPreimage,
407
+ SLOT,
408
+ SIGNER,
409
+ CORRELATION_V,
410
+ };