@eyeoverthink/sva-gate 0.0.0-stage → 1.0.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 +201 -0
- package/README.md +131 -2
- package/bin/sva-gate.js +153 -0
- package/package.json +61 -4
- package/src/index.d.ts +96 -0
- package/src/index.js +46 -0
- package/src/lib/binder-induction.js +204 -0
- package/src/lib/judge-verify.js +190 -0
- package/src/lib/membrane-core.js +130 -0
- package/src/lib/sentinel.js +88 -0
- package/src/lib/stream-guard.js +166 -0
- package/src/mcp-server.js +264 -0
- package/src/membrane.js +3 -0
- package/src/receipt.js +341 -0
package/src/receipt.js
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
// Zero-dependency SVA-ER/1, IETF AER-1 v0.4, and OPEG/1 minting & verification engine (Node 22+ node:crypto).
|
|
2
|
+
// Follows specs/SVA-ER-1.md, specs/OPEG-1.md, and draft-zambo-aer1-26 (kit 1.6.1) strictly fail-closed.
|
|
3
|
+
|
|
4
|
+
import crypto from 'node:crypto';
|
|
5
|
+
|
|
6
|
+
const HEX64 = /^[0-9a-f]{64}$/i;
|
|
7
|
+
const HEX128 = /^[0-9a-f]{128}$/i;
|
|
8
|
+
const STRICT_B64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
|
9
|
+
const RFC3339 = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?([Zz]|[+-](\d{2}):(\d{2}))$/;
|
|
10
|
+
const AER1_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
11
|
+
const AER1_NIL_UUID = '00000000-0000-0000-0000-000000000000';
|
|
12
|
+
const AER1_HASH = /^sha256:[0-9a-f]{64}$/;
|
|
13
|
+
const AER1_PROV = /^(EXECUTED BY [A-Z0-9][A-Z0-9 ._-]*|OBSERVED VIA GATEWAY|LOGGED BY AGENT)$/;
|
|
14
|
+
const UTF8_FATAL = new TextDecoder('utf-8', { fatal: true });
|
|
15
|
+
|
|
16
|
+
export function canonical(value) {
|
|
17
|
+
if (value === undefined) return 'null';
|
|
18
|
+
if (value === null || typeof value !== 'object') {
|
|
19
|
+
if (typeof value === 'number' && !Number.isFinite(value)) return 'null';
|
|
20
|
+
return JSON.stringify(value);
|
|
21
|
+
}
|
|
22
|
+
if (typeof value.toJSON === 'function') return canonical(value.toJSON());
|
|
23
|
+
if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';
|
|
24
|
+
const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort();
|
|
25
|
+
return '{' + keys.map((k) => JSON.stringify(k) + ':' + canonical(value[k])).join(',') + '}';
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function sha256Hex(data) {
|
|
29
|
+
return crypto.createHash('sha256').update(data).digest('hex');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const merkleLeaf = (h) => crypto.createHash('sha256').update(Buffer.from([0x00])).update(String(h), 'utf8').digest('hex');
|
|
33
|
+
const merkleNode = (l, r) => crypto.createHash('sha256').update(Buffer.from([0x01])).update(String(l), 'utf8').update(String(r), 'utf8').digest('hex');
|
|
34
|
+
|
|
35
|
+
export function isValidRfc3339(s) {
|
|
36
|
+
if (typeof s !== 'string') return false;
|
|
37
|
+
const m = RFC3339.exec(s);
|
|
38
|
+
if (!m) return false;
|
|
39
|
+
const y = Number(m[1]), mo = Number(m[2]), d = Number(m[3]);
|
|
40
|
+
const hh = Number(m[4]), mm = Number(m[5]), ss = Number(m[6]);
|
|
41
|
+
if (mo < 1 || mo > 12 || hh > 23 || mm > 59 || ss > 60) return false;
|
|
42
|
+
const leap = (y % 4 === 0 && y % 100 !== 0) || (y % 400 === 0);
|
|
43
|
+
const maxDay = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][mo - 1];
|
|
44
|
+
if (d < 1 || d > maxDay) return false;
|
|
45
|
+
if (m[8] !== undefined && (Number(m[8]) > 23 || Number(m[9]) > 59)) return false;
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function generateEd25519Keypair() {
|
|
50
|
+
const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
|
|
51
|
+
const pubJwk = publicKey.export({ format: 'jwk' });
|
|
52
|
+
const privJwk = privateKey.export({ format: 'jwk' });
|
|
53
|
+
const publicKeyHex = Buffer.from(pubJwk.x, 'base64url').toString('hex');
|
|
54
|
+
const seedHex = Buffer.from(privJwk.d, 'base64url').toString('hex');
|
|
55
|
+
const h = sha256Hex(Buffer.from(publicKeyHex, 'hex')).slice(0, 16);
|
|
56
|
+
const fxId = `fx-${h.slice(0, 4)}-${h.slice(4, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}`;
|
|
57
|
+
return { publicKeyHex, seedHex, fxId, privateKey, publicKey };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function keypairFromSeedHex(seedHex) {
|
|
61
|
+
if (!HEX64.test(String(seedHex || ''))) throw new Error('Ed25519 seedHex must be 64 hex chars (32 bytes)');
|
|
62
|
+
const pkcs8Prefix = Buffer.from('302e020100300506032b657004220420', 'hex');
|
|
63
|
+
const der = Buffer.concat([pkcs8Prefix, Buffer.from(seedHex, 'hex')]);
|
|
64
|
+
const privateKey = crypto.createPrivateKey({ key: der, format: 'der', type: 'pkcs8' });
|
|
65
|
+
const publicKey = crypto.createPublicKey(privateKey);
|
|
66
|
+
const pubJwk = publicKey.export({ format: 'jwk' });
|
|
67
|
+
const publicKeyHex = Buffer.from(pubJwk.x, 'base64url').toString('hex');
|
|
68
|
+
const h = sha256Hex(Buffer.from(publicKeyHex, 'hex')).slice(0, 16);
|
|
69
|
+
const fxId = `fx-${h.slice(0, 4)}-${h.slice(4, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}`;
|
|
70
|
+
return { publicKeyHex, seedHex: seedHex.toLowerCase(), fxId, privateKey, publicKey };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function ed25519Sign(privateKey, msg) {
|
|
74
|
+
return crypto.sign(null, Buffer.from(msg, 'utf8'), privateKey).toString('hex');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function ed25519Verify(pubHex, msg, sigHex) {
|
|
78
|
+
try {
|
|
79
|
+
if (!HEX64.test(String(pubHex || '')) || !HEX128.test(String(sigHex || ''))) return false;
|
|
80
|
+
const key = crypto.createPublicKey({
|
|
81
|
+
key: { kty: 'OKP', crv: 'Ed25519', x: Buffer.from(pubHex, 'hex').toString('base64url') },
|
|
82
|
+
format: 'jwk',
|
|
83
|
+
});
|
|
84
|
+
return crypto.verify(null, Buffer.from(msg, 'utf8'), key, Buffer.from(sigHex, 'hex'));
|
|
85
|
+
} catch { return false; }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function buildMerkle(hashes) {
|
|
89
|
+
const levels = [hashes.map(merkleLeaf)];
|
|
90
|
+
while (levels[levels.length - 1].length > 1) {
|
|
91
|
+
const prev = levels[levels.length - 1];
|
|
92
|
+
const next = [];
|
|
93
|
+
for (let i = 0; i < prev.length; i += 2) {
|
|
94
|
+
next.push(i + 1 < prev.length ? merkleNode(prev[i], prev[i + 1]) : prev[i]);
|
|
95
|
+
}
|
|
96
|
+
levels.push(next);
|
|
97
|
+
}
|
|
98
|
+
const root = levels[levels.length - 1][0];
|
|
99
|
+
const proofOf = (seq) => {
|
|
100
|
+
let idx = seq - 1;
|
|
101
|
+
const steps = [];
|
|
102
|
+
for (let lvl = 0; lvl < levels.length - 1; lvl++) {
|
|
103
|
+
const row = levels[lvl];
|
|
104
|
+
if (idx % 2 === 0 && idx + 1 === row.length) {
|
|
105
|
+
idx = Math.floor(idx / 2);
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
steps.push({ hash: idx % 2 === 0 ? row[idx + 1] : row[idx - 1], left: idx % 2 === 1 });
|
|
109
|
+
idx = Math.floor(idx / 2);
|
|
110
|
+
}
|
|
111
|
+
return steps;
|
|
112
|
+
};
|
|
113
|
+
return { root, proofOf };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function expectedSteps(seq, size) {
|
|
117
|
+
if (!Number.isInteger(seq) || !Number.isInteger(size) || seq < 1 || size < 1 || seq > size) return null;
|
|
118
|
+
const steps = [];
|
|
119
|
+
let idx = seq - 1, len = size;
|
|
120
|
+
while (len > 1) {
|
|
121
|
+
if (idx % 2 === 0 && idx + 1 === len) { idx = Math.floor(idx / 2); len = Math.ceil(len / 2); continue; }
|
|
122
|
+
steps.push(idx % 2 === 1);
|
|
123
|
+
idx = Math.floor(idx / 2);
|
|
124
|
+
len = Math.ceil(len / 2);
|
|
125
|
+
}
|
|
126
|
+
return steps;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function verifyMerkle({ leaf, seq, size, root, path: steps }) {
|
|
130
|
+
if (!HEX64.test(String(leaf || '')) || !HEX64.test(String(root || '')) || !Array.isArray(steps)) return false;
|
|
131
|
+
const exp = expectedSteps(seq, size);
|
|
132
|
+
if (!exp || exp.length !== steps.length) return false;
|
|
133
|
+
let h = merkleLeaf(leaf);
|
|
134
|
+
for (let i = 0; i < steps.length; i++) {
|
|
135
|
+
const s = steps[i];
|
|
136
|
+
if (!s || !HEX64.test(String(s.hash || '')) || Boolean(s.left) !== exp[i]) return false;
|
|
137
|
+
h = s.left ? merkleNode(s.hash, h) : merkleNode(h, s.hash);
|
|
138
|
+
}
|
|
139
|
+
return h === root;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Mint a conformant SVA-ER/1 receipt + OPEG/1 S4_COMMIT envelope for any sanitized result object.
|
|
144
|
+
*/
|
|
145
|
+
export function mintSvaEr1({
|
|
146
|
+
agencyName = 'sva-gate',
|
|
147
|
+
missionId = `ms_${crypto.randomBytes(6).toString('hex')}`,
|
|
148
|
+
rSan,
|
|
149
|
+
events = [],
|
|
150
|
+
clockStatus = 'unattested',
|
|
151
|
+
issuedAt = new Date().toISOString(),
|
|
152
|
+
keypair = null,
|
|
153
|
+
seedHex = null,
|
|
154
|
+
} = {}) {
|
|
155
|
+
if (!rSan || typeof rSan !== 'object' || Array.isArray(rSan)) {
|
|
156
|
+
throw new Error('mintSvaEr1 requires rSan to be a plain JSON object');
|
|
157
|
+
}
|
|
158
|
+
if (!['attested', 'drift', 'unattested'].includes(clockStatus)) {
|
|
159
|
+
throw new Error('clockStatus must be attested, drift, or unattested');
|
|
160
|
+
}
|
|
161
|
+
if (!isValidRfc3339(issuedAt)) throw new Error('issuedAt must be a valid RFC 3339 timestamp');
|
|
162
|
+
|
|
163
|
+
const kp = keypair || (seedHex ? keypairFromSeedHex(seedHex) : generateEd25519Keypair());
|
|
164
|
+
const deliverable = canonical(rSan);
|
|
165
|
+
const delivSha = sha256Hex(deliverable);
|
|
166
|
+
|
|
167
|
+
const rows = [];
|
|
168
|
+
let prev = '0'.repeat(64);
|
|
169
|
+
for (const ev of events) {
|
|
170
|
+
const seq = rows.length + 1;
|
|
171
|
+
const core = {
|
|
172
|
+
seq,
|
|
173
|
+
ts: isValidRfc3339(ev.ts) ? ev.ts : issuedAt,
|
|
174
|
+
kind: String(ev.kind || 'tool.call'),
|
|
175
|
+
actor: String(ev.actor || kp.fxId),
|
|
176
|
+
data: { missionId, ...(ev.data && typeof ev.data === 'object' ? ev.data : {}) },
|
|
177
|
+
prev,
|
|
178
|
+
};
|
|
179
|
+
const ehash = sha256Hex(canonical(core));
|
|
180
|
+
rows.push({ ...core, hash: ehash, sig: ed25519Sign(kp.privateKey, ehash), signer: kp.publicKeyHex });
|
|
181
|
+
prev = ehash;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const compCore = {
|
|
185
|
+
seq: rows.length + 1,
|
|
186
|
+
ts: issuedAt,
|
|
187
|
+
kind: 'mission.complete',
|
|
188
|
+
actor: kp.fxId,
|
|
189
|
+
data: { id: missionId, resultHash: delivSha },
|
|
190
|
+
prev,
|
|
191
|
+
};
|
|
192
|
+
const compHash = sha256Hex(canonical(compCore));
|
|
193
|
+
rows.push({ ...compCore, hash: compHash, sig: ed25519Sign(kp.privateKey, compHash), signer: kp.publicKeyHex });
|
|
194
|
+
|
|
195
|
+
const { root, proofOf } = buildMerkle(rows.map((r) => r.hash));
|
|
196
|
+
const statement = {
|
|
197
|
+
type: 'sva-er.statement',
|
|
198
|
+
missionId,
|
|
199
|
+
deliverableSha256: delivSha,
|
|
200
|
+
merkleRoot: root,
|
|
201
|
+
merkle: 'rfc6962-sha256',
|
|
202
|
+
size: rows.length,
|
|
203
|
+
entries: rows.length,
|
|
204
|
+
clock: { status: clockStatus, issuedAt, maxSkewSec: 300 },
|
|
205
|
+
};
|
|
206
|
+
const statementSig = ed25519Sign(kp.privateKey, canonical(statement));
|
|
207
|
+
const receipt = {
|
|
208
|
+
spec: 'sva-er/1',
|
|
209
|
+
agency: { name: agencyName, publicKey: kp.publicKeyHex },
|
|
210
|
+
statement,
|
|
211
|
+
statementSig,
|
|
212
|
+
entries: rows.map((r) => ({ ...r, proof: proofOf(r.seq) })),
|
|
213
|
+
};
|
|
214
|
+
const opegEnvelope = {
|
|
215
|
+
spec: 'opeg/1',
|
|
216
|
+
state: 'S4_COMMIT',
|
|
217
|
+
mode: 'EXECUTE_AND_RECEIVE',
|
|
218
|
+
receiptFormat: 'sva-er/1',
|
|
219
|
+
sourcePriority: ['runtime_receipt', 'sanitized_output', 'model_narrative'],
|
|
220
|
+
sanitizer: { status: 'SUCCESS', rSan, rSanSha256: delivSha },
|
|
221
|
+
receipt,
|
|
222
|
+
};
|
|
223
|
+
return { receipt, deliverable, opegEnvelope, publicKeyHex: kp.publicKeyHex, fxId: kp.fxId };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function evaluateSvaEr1({ receipt, deliverable = null }) {
|
|
227
|
+
const malformed = { ok: false, outcome: 'rejected_malformed', deliverable: 'not_checked', clock: 'verification_failed' };
|
|
228
|
+
const failed = (delivState = 'not_checked', clockState = 'verification_failed') => ({
|
|
229
|
+
ok: false, outcome: 'verification_failed', deliverable: delivState, clock: clockState,
|
|
230
|
+
});
|
|
231
|
+
if (!receipt || receipt.spec !== 'sva-er/1') return malformed;
|
|
232
|
+
const pub = receipt.agency?.publicKey;
|
|
233
|
+
const st = receipt.statement;
|
|
234
|
+
if (!HEX64.test(String(pub || '')) || !st || typeof st !== 'object' || Array.isArray(st) || !Array.isArray(receipt.entries)) return malformed;
|
|
235
|
+
if (st.type !== 'sva-er.statement' || typeof st.missionId !== 'string' || st.missionId.length === 0) return malformed;
|
|
236
|
+
if (!HEX64.test(String(st.deliverableSha256 || '')) || !HEX64.test(String(st.merkleRoot || ''))) return malformed;
|
|
237
|
+
if (st.merkle !== 'rfc6962-sha256' || !Number.isSafeInteger(st.size) || st.size < 1 || !Number.isSafeInteger(st.entries) || st.entries < 1) return malformed;
|
|
238
|
+
if (!st.clock || typeof st.clock !== 'object' || !['attested', 'drift', 'unattested'].includes(st.clock.status) || !isValidRfc3339(st.clock.issuedAt)) return malformed;
|
|
239
|
+
const clockState = st.clock.status;
|
|
240
|
+
if (!ed25519Verify(pub, canonical(st), receipt.statementSig)) return failed('not_checked', clockState);
|
|
241
|
+
if (receipt.entries.length !== st.entries) return failed('not_checked', clockState);
|
|
242
|
+
|
|
243
|
+
const seen = new Set();
|
|
244
|
+
let hasComplete = false;
|
|
245
|
+
for (const e of receipt.entries) {
|
|
246
|
+
if (!e || !Number.isSafeInteger(e.seq) || e.seq < 1 || e.seq > st.size || seen.has(e.seq)) return failed('not_checked', clockState);
|
|
247
|
+
seen.add(e.seq);
|
|
248
|
+
const recomputed = sha256Hex(canonical({ seq: e.seq, ts: e.ts, kind: e.kind, actor: e.actor, data: e.data, prev: e.prev }));
|
|
249
|
+
if (recomputed !== e.hash) return failed('not_checked', clockState);
|
|
250
|
+
if (e.signer !== pub || !ed25519Verify(pub, e.hash, e.sig)) return failed('not_checked', clockState);
|
|
251
|
+
if (!verifyMerkle({ leaf: e.hash, seq: e.seq, size: st.size, root: st.merkleRoot, path: e.proof })) return failed('not_checked', clockState);
|
|
252
|
+
if (e.data?.id !== st.missionId && e.data?.missionId !== st.missionId) return failed('not_checked', clockState);
|
|
253
|
+
if (e.kind === 'mission.complete') {
|
|
254
|
+
if (e.data?.resultHash !== st.deliverableSha256) return failed('not_checked', clockState);
|
|
255
|
+
hasComplete = true;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (!hasComplete) return failed('not_checked', clockState);
|
|
259
|
+
let delivState = 'not_checked';
|
|
260
|
+
if (deliverable != null) {
|
|
261
|
+
const delivStr = typeof deliverable === 'string' ? deliverable : canonical(deliverable);
|
|
262
|
+
if (sha256Hex(delivStr) !== st.deliverableSha256) return failed('verification_failed', clockState);
|
|
263
|
+
delivState = 'verified';
|
|
264
|
+
}
|
|
265
|
+
return { ok: true, outcome: 'verified', deliverable: delivState, clock: clockState };
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export function evaluateAer1V04(r) {
|
|
269
|
+
const fail = (reason) => ({ ok: false, outcome: 'verification_failed', clockAttestation: 'absent', issuerKeyBinding: 'absent', reason });
|
|
270
|
+
if (!r || typeof r !== 'object' || Array.isArray(r)) return fail('not an object');
|
|
271
|
+
if (typeof r.id !== 'string' || !AER1_UUID.test(r.id) || r.id === AER1_NIL_UUID) return fail('invalid id');
|
|
272
|
+
if (r.receipt_schema_version !== '0.4') return fail('expected schema version 0.4');
|
|
273
|
+
if (!isValidRfc3339(r.created_at)) return fail('invalid created_at');
|
|
274
|
+
if (!r.tool || typeof r.tool !== 'object' || !['name', 'version', 'scope'].every((k) => typeof r.tool[k] === 'string' && r.tool[k].length > 0)) return fail('invalid tool');
|
|
275
|
+
if (typeof r.provenance_class !== 'string' || !AER1_PROV.test(r.provenance_class)) return fail('invalid provenance_class');
|
|
276
|
+
if (r.verification_status !== 'verified') return fail('verification_status must be verified');
|
|
277
|
+
if (typeof r.canonical_bytes !== 'string' || !STRICT_B64.test(r.canonical_bytes)) return fail('invalid canonical_bytes');
|
|
278
|
+
if (typeof r.output_hash !== 'string' || !AER1_HASH.test(r.output_hash)) return fail('invalid output_hash');
|
|
279
|
+
if (typeof r.metadata_hash !== 'string' || !AER1_HASH.test(r.metadata_hash)) return fail('invalid metadata_hash');
|
|
280
|
+
let rawBytes;
|
|
281
|
+
try { rawBytes = Buffer.from(r.canonical_bytes, 'base64'); } catch { return fail('bad base64'); }
|
|
282
|
+
if ('sha256:' + sha256Hex(rawBytes) !== r.output_hash) return fail('output_hash mismatch');
|
|
283
|
+
let payload;
|
|
284
|
+
try { payload = JSON.parse(UTF8_FATAL.decode(rawBytes)); } catch { return fail('canonical_bytes not strict UTF-8 JSON'); }
|
|
285
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return fail('payload not object');
|
|
286
|
+
if (payload.receipt_schema_version !== r.receipt_schema_version) return fail('version agreement mismatch');
|
|
287
|
+
if (payload.issuer_claims?.provenance_class !== r.provenance_class) return fail('provenance binding mismatch');
|
|
288
|
+
const metaBlock = {
|
|
289
|
+
created_at: r.created_at,
|
|
290
|
+
id: r.id,
|
|
291
|
+
output_hash: r.output_hash,
|
|
292
|
+
provenance_class: r.provenance_class,
|
|
293
|
+
receipt_schema_version: r.receipt_schema_version,
|
|
294
|
+
tool: { name: r.tool.name, scope: r.tool.scope, version: r.tool.version },
|
|
295
|
+
};
|
|
296
|
+
if ('sha256:' + sha256Hex(Buffer.from(canonical(metaBlock), 'utf8')) !== r.metadata_hash) return fail('metadata_hash mismatch');
|
|
297
|
+
return { ok: true, outcome: 'verified', clockAttestation: 'absent', issuerKeyBinding: 'absent', payload };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export function verifyAnyReceipt(receipt, { deliverable = null } = {}) {
|
|
301
|
+
if (receipt && receipt.spec === 'sva-er/1') {
|
|
302
|
+
return { format: 'sva-er/1', ...evaluateSvaEr1({ receipt, deliverable }) };
|
|
303
|
+
}
|
|
304
|
+
if (receipt && receipt.receipt_schema_version === '0.4') {
|
|
305
|
+
const res = evaluateAer1V04(receipt);
|
|
306
|
+
const { payload, ...summary } = res;
|
|
307
|
+
return { format: 'aer-1', ...summary, ...(payload ? { outputs: payload.outputs } : {}) };
|
|
308
|
+
}
|
|
309
|
+
return { format: 'unknown', ok: false, outcome: 'rejected_malformed', reason: 'Unrecognized receipt format (expected sva-er/1 or aer-1 v0.4)' };
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
export function evaluateOpeg1(doc) {
|
|
313
|
+
const blocked = (reason, receiptFormat = doc?.receiptFormat ?? 'sva-er/1', receiptOutcome = null) => ({
|
|
314
|
+
ok: false, gate: 'blocked', receiptFormat, reason, receiptOutcome,
|
|
315
|
+
});
|
|
316
|
+
if (!doc || doc.spec !== 'opeg/1' || doc.state !== 'S4_COMMIT') return blocked('invalid spec/state');
|
|
317
|
+
if (doc.mode !== 'EXECUTE_AND_RECEIVE') return blocked('forbidden mode (DIRECT_INFERENCE blocked)');
|
|
318
|
+
if (!Array.isArray(doc.sourcePriority) || doc.sourcePriority[0] !== 'runtime_receipt') return blocked('sourcePriority must start with runtime_receipt');
|
|
319
|
+
const san = doc.sanitizer;
|
|
320
|
+
if (!san || san.status !== 'SUCCESS' || !san.rSan || typeof san.rSan !== 'object' || Array.isArray(san.rSan)) return blocked('invalid sanitizer');
|
|
321
|
+
const rSanCanon = canonical(san.rSan);
|
|
322
|
+
if (sha256Hex(rSanCanon) !== san.rSanSha256) return blocked('rSanSha256 mismatch');
|
|
323
|
+
const fmt = doc.receiptFormat ?? 'sva-er/1';
|
|
324
|
+
if (fmt === 'sva-er/1') {
|
|
325
|
+
const er = evaluateSvaEr1({ receipt: doc.receipt, deliverable: rSanCanon });
|
|
326
|
+
if (er.ok !== true || er.outcome !== 'verified' || er.deliverable !== 'verified') return blocked('sva-er/1 receipt failed', fmt, er);
|
|
327
|
+
return { ok: true, gate: 'pass', receiptFormat: fmt, receiptOutcome: er };
|
|
328
|
+
}
|
|
329
|
+
if (fmt === 'aer-1') {
|
|
330
|
+
const aer = evaluateAer1V04(doc.receipt);
|
|
331
|
+
const receiptOutcome = { outcome: aer.outcome, clockAttestation: aer.clockAttestation, issuerKeyBinding: aer.issuerKeyBinding };
|
|
332
|
+
if (!aer.ok) return blocked(aer.reason, fmt, receiptOutcome);
|
|
333
|
+
const outputs = aer.payload?.outputs;
|
|
334
|
+
const directOk = outputs !== undefined && sha256Hex(canonical(outputs)) === san.rSanSha256;
|
|
335
|
+
const explicit = outputs?.rSanSha256;
|
|
336
|
+
const explicitOk = explicit === san.rSanSha256 || explicit === 'sha256:' + san.rSanSha256;
|
|
337
|
+
if (!directOk && !explicitOk) return blocked('aer-1 outputs binding mismatch', fmt, receiptOutcome);
|
|
338
|
+
return { ok: true, gate: 'pass', receiptFormat: fmt, receiptOutcome };
|
|
339
|
+
}
|
|
340
|
+
return blocked(`unsupported receiptFormat: ${fmt}`, fmt);
|
|
341
|
+
}
|