@agent-blueprint-protocol/verifier 0.7.1 → 0.8.1

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.
@@ -1,316 +0,0 @@
1
- // Self-check battery — the corpus-independent anchors:
2
- // RFC 8785 Appendix B transcribed first-hand from the RFC (2026-08-23), the
3
- // RFC's §3.2.2→§3.2.4 canonicalization sample, the §3.2.3 sort-order fixture,
4
- // the integer-window matrix (mis-round lexeme included), the b64url strict/
5
- // lenient matrices, and Ed25519 key acceptance. Exit 0 = all pass; exit 1 +
6
- // a list = any failure.
7
- //
8
- // These run inside `verifier.agreement` (a divergence in either
9
- // implementation must surface — RFC table ↔ TS emit ↔ native stringify).
10
- import { number } from "./canonical.js";
11
- import { decode } from "./decode.js";
12
- import { encode } from "./canonical.js";
13
- import * as b64 from "./b64url.js";
14
- import { member, memberString } from "./corpus.js";
15
- import { verify as sigVerify, toCompact, signingInput, usableEd25519Key } from "./signature.js";
16
- import { readFileSync } from "node:fs";
17
- import { join } from "node:path";
18
- import { createPrivateKey, createPublicKey, sign as cryptoSign, verify as cryptoVerify } from "node:crypto";
19
- const failures = [];
20
- let checks = 0;
21
- function check(name, got, want) {
22
- checks++;
23
- if (got !== want)
24
- failures.push(`${name}: got ${String(got)} want ${String(want)}`);
25
- }
26
- // ---- RFC 8785 Appendix B (transcribed from the RFC, verbatim) -------------------
27
- const APPENDIX_B = [
28
- ["0000000000000000", "0"],
29
- ["8000000000000000", "0"], // minus zero
30
- ["0000000000000001", "5e-324"],
31
- ["8000000000000001", "-5e-324"],
32
- ["7fefffffffffffff", "1.7976931348623157e+308"],
33
- ["ffefffffffffffff", "-1.7976931348623157e+308"],
34
- ["4340000000000000", "9007199254740992"],
35
- ["c340000000000000", "-9007199254740992"],
36
- ["4430000000000000", "295147905179352830000"],
37
- ["7fffffffffffffff", null], // NaN — must error
38
- ["7ff0000000000000", null], // Infinity — must error
39
- ["44b52d02c7e14af5", "9.999999999999997e+22"],
40
- ["44b52d02c7e14af6", "1e+23"],
41
- ["44b52d02c7e14af7", "1.0000000000000001e+23"],
42
- ["444b1ae4d6e2ef4e", "999999999999999700000"],
43
- ["444b1ae4d6e2ef4f", "999999999999999900000"],
44
- ["444b1ae4d6e2ef50", "1e+21"],
45
- ["3eb0c6f7a0b5ed8c", "9.999999999999997e-7"],
46
- ["3eb0c6f7a0b5ed8d", "0.000001"],
47
- ["41b3de4355555553", "333333333.3333332"],
48
- ["41b3de4355555554", "333333333.33333325"],
49
- ["41b3de4355555555", "333333333.3333333"],
50
- ["41b3de4355555556", "333333333.3333334"],
51
- ["41b3de4355555557", "333333333.33333343"],
52
- ["becbf647612f3696", "-0.0000033333333333333333"],
53
- ["43143ff3c1cb0959", "1424953923781206.2"], // round to even
54
- ];
55
- for (const [hex, expected] of APPENDIX_B) {
56
- const buffer = Buffer.alloc(8);
57
- buffer.writeBigUInt64BE(BigInt("0x" + hex));
58
- const value = buffer.readDoubleBE();
59
- if (expected === null) {
60
- let errored = false;
61
- try {
62
- number(value);
63
- }
64
- catch {
65
- errored = true;
66
- }
67
- check(`appendix-b ${hex} errors`, errored, true);
68
- continue;
69
- }
70
- check(`appendix-b ${hex}`, number(value), expected);
71
- // Three-way: native stringify must agree with the RFC table too.
72
- check(`appendix-b ${hex} native`, JSON.stringify(value), expected);
73
- }
74
- // ---- RFC 8785 §3.2.2 → §3.2.4 sample --------------------------------------------
75
- const sampleInput = `{
76
- "numbers": [333333333.33333329, 1E30, 4.50,
77
- 2e-3, 0.000000000000000000000000001],
78
- "string": "\\u20ac$\\u000F\\u000aA'\\u0042\\u0022\\u005c\\\\\\"\\/",
79
- "literals": [null, true, false]
80
- }`;
81
- const sampleCanonical = '{"literals":[null,true,false],"numbers":[333333333.3333333,1e+30,4.5,0.002,1e-27],' +
82
- '"string":"€$\\u000f\\nA\'B\\"\\\\\\\\\\"/"}';
83
- const sampleHex = "7b226c69746572616c73223a5b6e756c6c2c747275652c66616c73655d2c226e756d62" +
84
- "657273223a5b3333333333333333332e333333333333332c31652b33302c342e352c" +
85
- "302e3030322c31652d32375d2c22737472696e67223a22e282ac245c75303030665c6e" +
86
- "4127425c225c5c5c5c5c222f227d";
87
- const sampleDecoded = decode(sampleInput);
88
- check("§3.2.2 sample decodes", sampleDecoded.ok, true);
89
- if (sampleDecoded.ok) {
90
- const sampleEncoded = encode(sampleDecoded.v);
91
- check("§3.2.3 canonical output", sampleEncoded.ok && sampleEncoded.v, sampleCanonical);
92
- check("§3.2.4 hex bytes", sampleEncoded.ok && Buffer.from(sampleEncoded.v, "utf8").toString("hex"), sampleHex);
93
- }
94
- // ---- RFC 8785 §3.2.3 sort-order fixture ------------------------------------------
95
- const sortInput = `{
96
- "\\u20ac": "Euro Sign",
97
- "\\r": "Carriage Return",
98
- "\\ufb33": "Hebrew Letter Dalet With Dagesh",
99
- "1": "One",
100
- "\\ud83d\\ude00": "Emoji: Grinning Face",
101
- "\\u0080": "Control",
102
- "\\u00f6": "Latin Small Letter O With Diaeresis"
103
- }`;
104
- const expectedOrder = [
105
- "Carriage Return", // \r
106
- "One", // 1
107
- "Control", // U+0080
108
- "Latin Small Letter O With Diaeresis", // U+00F6
109
- "Euro Sign", // U+20AC
110
- "Emoji: Grinning Face", // U+1F600
111
- "Hebrew Letter Dalet With Dagesh", // U+FB33
112
- ];
113
- const sortDecoded = decode(sortInput);
114
- check("§3.2.3 fixture decodes", sortDecoded.ok, true);
115
- if (sortDecoded.ok) {
116
- // Sorting happens at ENCODE (decode preserves member order) — assert the
117
- // canonical output's key order: \r < 1 < U+0080 < U+00F6 < U+20AC <
118
- // U+1F600 < U+FB33 (UTF-16 code units).
119
- const encoded = encode(sortDecoded.v);
120
- check("§3.2.3 encode succeeds", encoded.ok, true);
121
- if (encoded.ok) {
122
- // Extract values by splitting on '":"' boundaries of the flat object.
123
- const valuesInOrder = [];
124
- const body = encoded.v.slice(1, -1);
125
- for (const pair of body.split(",")) {
126
- const value = pair.slice(pair.indexOf('":') + 2);
127
- valuesInOrder.push(JSON.parse(value));
128
- }
129
- check("§3.2.3 order values", JSON.stringify(valuesInOrder), JSON.stringify(expectedOrder));
130
- }
131
- }
132
- // ---- integer-window matrix -------------------------------------------------------
133
- // [lexeme, expected] — expected is "ok:<tag>:<number-string>" or the deny code.
134
- const WINDOW = [
135
- ["9007199254740992", "ok:float:9007199254740992"],
136
- ["-9007199254740992", "ok:float:-9007199254740992"],
137
- ["9007199254740993", "number_not_double_expressible"],
138
- ["-9007199254740993", "number_not_double_expressible"],
139
- ["9007199254740994", "ok:float:9007199254740994"],
140
- ["295147905179352830000", "ok:float:295147905179352830000"],
141
- ["999999999999999700000", "ok:float:999999999999999700000"],
142
- ["999999999999999900000", "ok:float:999999999999999900000"],
143
- ["295147905179352825856", "number_not_double_expressible"],
144
- ["73639773945516200000", "ok:float:73639773945516200000"], // mis-round bits 440FEFA841F21479
145
- ["1000000000000000000000", "number_not_double_expressible"], // 1e21: canonical is exponential
146
- ["18446744073709551616", "number_not_double_expressible"],
147
- ["1e400", "invalid_number"],
148
- ["-1e400", "invalid_number"],
149
- ["1e-400", "ok:float:0"], // underflow admits as 0 (Float.parse parity)
150
- ["999999999999999999999999999999999999", "number_not_double_expressible"],
151
- ];
152
- for (const [lexeme, expected] of WINDOW) {
153
- const decoded = decode(lexeme);
154
- let got;
155
- if (!decoded.ok)
156
- got = decoded.e;
157
- else if (decoded.v.t === "float")
158
- got = "ok:float:" + number(decoded.v.v);
159
- else if (decoded.v.t === "int")
160
- got = `ok:int:${decoded.v.v}`;
161
- else
162
- got = "ok:other";
163
- check(`window ${lexeme}`, got, expected);
164
- }
165
- // ---- b64url matrices -------------------------------------------------------------
166
- function strict(input) {
167
- const decoded = b64.decodeStrict(input);
168
- return decoded.ok ? "ok:" + decoded.v.toString("latin1") : decoded.e;
169
- }
170
- check("b64 strict valid", strict("QQ"), "ok:A");
171
- check("b64 strict empty", strict(""), "ok:");
172
- check("b64 strict padded", strict("QQ=="), "base64url_padded");
173
- check("b64 strict interior pad", strict("Q=Q"), "base64url_padded");
174
- check("b64 strict bad char", strict("!!!"), "base64url_invalid");
175
- check("b64 strict impossible length", strict("A"), "base64url_invalid");
176
- check("b64 strict nonzero pad bits", strict("Qc"), "base64url_invalid"); // 0x41+0x07 → re-encode differs
177
- check("b64 strict canonical pair", strict("QUJD"), "ok:ABC");
178
- function lenient(input) {
179
- const decoded = b64.decodeLenient(input);
180
- return decoded.ok ? "ok:" + decoded.v.toString("latin1") : decoded.e;
181
- }
182
- check("b64 lenient unpadded", lenient("QQ"), "ok:A");
183
- check("b64 lenient padded", lenient("QQ=="), "ok:A"); // stdlib accepts padding
184
- check("b64 lenient bad char", lenient("!!!"), "lenient_invalid");
185
- // ---- Ed25519 key acceptance ---------------------------------------------------------
186
- // Small-order / non-canonical / off-curve encodings — the libsodium
187
- // ge25519_has_small_order list (provider constants) plus the y ∈ {1, p−1}
188
- // pair an independent review found slipping through the twin's root==0 branch.
189
- const UNUSABLE_HEX = [
190
- "0100000000000000000000000000000000000000000000000000000000000000", // identity (order 1)
191
- "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", // order-2 point
192
- "0000000000000000000000000000000000000000000000000000000000000000", // y = 0
193
- "0000000000000000000000000000000000000000000000000000000000000080", // y = 0, sign set
194
- "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
195
- "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
196
- "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
197
- "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",
198
- "0100000000000000000000000000000000000000000000000000000000000080", // identity, sign set
199
- "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", // y ≥ p
200
- "d7f0980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", // off-curve
201
- ];
202
- for (const hex of UNUSABLE_HEX) {
203
- check(`ed25519 unusable ${hex.slice(0, 8)}…`, usableEd25519Key(Buffer.from(hex, "hex")), false);
204
- }
205
- // The RFC 8032 §7.1 TEST 1 public key — a legitimate main-subgroup point.
206
- check("ed25519 RFC8032 TEST1 pubkey usable", usableEd25519Key(Buffer.from("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", "hex")), true);
207
- // ---- Standard-JOSE cross-check: the stored JWS vectors ----------------------------
208
- {
209
- const vectorsBytes = readFileSync(join(import.meta.dirname, "testdata", "jose-vectors.json"));
210
- const vectors = decode(vectorsBytes);
211
- check("jose vectors decode", vectors.ok, true);
212
- if (!vectors.ok || vectors.v.t !== "obj") {
213
- check("jose vectors shape", false, true);
214
- }
215
- else {
216
- const kat = member(vectors.v, "rfc8032_test1");
217
- const seedHex = memberString(kat, "seed_hex");
218
- const pubHex = memberString(kat, "public_key_hex");
219
- const sigHex = memberString(kat, "signature_hex");
220
- // Seed import via PKCS#8 DER wrap; derived public key must equal the
221
- // RFC's published literal (KAT 1).
222
- const seed = Buffer.from(seedHex, "hex");
223
- const der = Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), seed]);
224
- const privateKey = createPrivateKey({ key: der, format: "der", type: "pkcs8" });
225
- const derivedJwk = createPublicKey(privateKey).export({ format: "jwk" });
226
- check("jose RFC8032 seed derives published pub", Buffer.from(derivedJwk.x, "base64url").toString("hex"), pubHex);
227
- // node's Ed25519 reproduces the RFC's published signature over the
228
- // empty TEST 1 message (KAT 2), and verifies it.
229
- const message = Buffer.from(memberString(kat, "message_hex") ?? "", "hex");
230
- const resigned = cryptoSign(null, message, privateKey);
231
- check("jose RFC8032 signature reproduced", resigned.toString("hex"), sigHex);
232
- check("jose RFC8032 verify", cryptoVerify(null, message, createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: derivedJwk.x }, format: "jwk" }), Buffer.from(sigHex, "hex")), true);
233
- // The stored entries verify through the TS twin, match their compact
234
- // forms, and reconstruct per RFC 7515 App F with stock crypto.
235
- const publicKeyB64 = memberString(vectors.v, "public_key");
236
- const stockKey = createPublicKey({
237
- key: { kty: "OKP", crv: "Ed25519", x: publicKeyB64 },
238
- format: "jwk",
239
- });
240
- const keys = [{ keyId: "test-key", key: Buffer.from(publicKeyB64, "base64url") }];
241
- const entries = member(vectors.v, "entries");
242
- check("jose entries present", entries.t === "arr" && entries.v.length >= 2, true);
243
- for (const wrapped of entries.t === "arr" ? entries.v : []) {
244
- const entry = member(wrapped, "entry");
245
- const compact = memberString(wrapped, "compact");
246
- const purpose = memberString(member(entry, "signed_attributes"), "purpose");
247
- const verified = sigVerify(entry, keys);
248
- check(`jose entry verifies (${purpose})`, verified.ok && verified.v === "verified", true);
249
- const mine = toCompact(entry);
250
- check("jose compact matches", mine.ok ? mine.v : "err", compact);
251
- const input = signingInput(entry);
252
- check("jose signing input ok", input.ok, true);
253
- if (input.ok) {
254
- check("jose standard-reconstruction verify", cryptoVerify(null, Buffer.from(input.v, "utf8"), stockKey, Buffer.from(compact.split(".")[2], "base64url")), true);
255
- }
256
- }
257
- // Tamper tripwire: a flipped signature byte must fail verification.
258
- const firstEntry = (entries.t === "arr" ? entries.v : [])[0];
259
- const tampered = flipSignatureByte(member(firstEntry, "entry"));
260
- const tamperedResult = sigVerify(tampered, keys);
261
- check("jose tampered signature denied", !tamperedResult.ok && tamperedResult.e === "signature_not_verified", true);
262
- }
263
- }
264
- function flipSignatureByte(entry) {
265
- const signature = memberString(entry, "signature");
266
- const flipped = signature.slice(0, 10) + (signature[10] === "A" ? "B" : "A") + signature.slice(11);
267
- return {
268
- t: "obj",
269
- // flipSignatureByte walks signature entries (objects) only.
270
- v: entry.v.map(([k, v]) => k === "signature" ? [k, { t: "str", v: flipped }] : [k, v]),
271
- };
272
- }
273
- // ---- bounds-algebra obligation meet (the corpus-invisible direction) ---------------
274
- //
275
- // The frozen corpus never varies an obligation bound across sources (all
276
- // five intersect cases carry identical values), so meet-direction errors are
277
- // invisible to corpus agreement. These vectors pin it: obligation families
278
- // (authority_trait/approval_trait/effect_impact_ceiling) meet at the
279
- // STRICTEST value (max lattice index), fixed and
280
- // verified against the live Elixir (both deny protected_bound_clamp_denied).
281
- {
282
- const boundsAlgebra = await import("./bounds_algebra.js");
283
- const base = (over) => Object.assign({
284
- approval_trait: "none",
285
- authority_trait: "none",
286
- classification_ceiling: { ordinal: "public", markers: [] },
287
- disclosure_ceiling: "summary",
288
- effect_impact_ceiling: "ordinary",
289
- max_attempts: 3,
290
- max_concurrency: 2,
291
- max_depth: 8,
292
- max_descendants: 64,
293
- max_elapsed_ms: 60000,
294
- max_fan_out: 4,
295
- max_tokens: 100000,
296
- max_cost: { amount: 1000, currency: "USD" },
297
- }, over);
298
- const widenedAuthority = base({ authority_trait: "external_authority_required" });
299
- const widenedApproval = base({ approval_trait: "human_required" });
300
- const r1 = boundsAlgebra.intersect(base({}), base({}), widenedAuthority, "deny");
301
- check("obligation meet: authority widening denied", r1.ok ? "ok" : r1.e, "protected_bound_clamp_denied");
302
- const r2 = boundsAlgebra.intersect(base({}), base({}), widenedApproval, "deny");
303
- check("obligation meet: approval widening denied", r2.ok ? "ok" : r2.e, "protected_bound_clamp_denied");
304
- const r3 = boundsAlgebra.intersect(base({}), base({}), widenedAuthority, "acknowledge");
305
- check("obligation meet: acknowledged clamp emitted", r3.ok ? `clamps=${r3.v.clamps.length}` : r3.e, "clamps=1");
306
- }
307
- // ---- summary --------------------------------------------------------------------
308
- if (failures.length > 0) {
309
- process.stderr.write(`self-checks FAILED (${failures.length}/${checks}):\n`);
310
- for (const failure of failures)
311
- process.stderr.write(" " + failure + "\n");
312
- process.exitCode = 1;
313
- }
314
- else {
315
- process.stdout.write(`self-checks ok (${checks})\n`);
316
- }