@agent-blueprint-protocol/verifier 0.7.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 (78) hide show
  1. package/CHANGELOG.md +891 -0
  2. package/LICENSE +190 -0
  3. package/NOTICE +4 -0
  4. package/README.md +199 -0
  5. package/dist/corpus/cases/base64url-decode.json +1 -0
  6. package/dist/corpus/cases/blueprint-decode.json +1 -0
  7. package/dist/corpus/cases/bounds-new.json +1 -0
  8. package/dist/corpus/cases/bounds_algebra-intersect.json +1 -0
  9. package/dist/corpus/cases/canonicalization-encode.json +1 -0
  10. package/dist/corpus/cases/compatibility-verify.json +1 -0
  11. package/dist/corpus/cases/deployment-decode.json +1 -0
  12. package/dist/corpus/cases/digest-tagged.json +1 -0
  13. package/dist/corpus/cases/extension-resolve.json +1 -0
  14. package/dist/corpus/cases/federation-decode.json +1 -0
  15. package/dist/corpus/cases/federation-verify_commitment.json +1 -0
  16. package/dist/corpus/cases/json-decode.json +1 -0
  17. package/dist/corpus/cases/negotiation-negotiate.json +1 -0
  18. package/dist/corpus/cases/portability-scan.json +1 -0
  19. package/dist/corpus/cases/schema-validate_instance.json +1 -0
  20. package/dist/corpus/cases/signature-verify.json +1 -0
  21. package/dist/corpus/index.json +1 -0
  22. package/dist/corpus/schemas/estate-contract.schema.json +1 -0
  23. package/dist/corpus/schemas/object.schema.json +1 -0
  24. package/dist/corpus/vectors/blueprint-golden.json +1 -0
  25. package/dist/corpus/vectors/deployment-golden.json +1 -0
  26. package/dist/corpus/vectors/rfc8785-numbers.json +1 -0
  27. package/dist/kit/cli.mjs +24 -0
  28. package/dist/verifier/b64url.d.ts +16 -0
  29. package/dist/verifier/b64url.js +36 -0
  30. package/dist/verifier/blueprint.d.ts +56 -0
  31. package/dist/verifier/blueprint.js +795 -0
  32. package/dist/verifier/bounds.d.ts +19 -0
  33. package/dist/verifier/bounds.js +45 -0
  34. package/dist/verifier/bounds_algebra.d.ts +27 -0
  35. package/dist/verifier/bounds_algebra.js +282 -0
  36. package/dist/verifier/canonical.d.ts +17 -0
  37. package/dist/verifier/canonical.js +160 -0
  38. package/dist/verifier/cli.d.ts +1 -0
  39. package/dist/verifier/cli.js +149 -0
  40. package/dist/verifier/compatibility.d.ts +22 -0
  41. package/dist/verifier/compatibility.js +112 -0
  42. package/dist/verifier/corpus.d.ts +42 -0
  43. package/dist/verifier/corpus.js +672 -0
  44. package/dist/verifier/decode.d.ts +16 -0
  45. package/dist/verifier/decode.js +457 -0
  46. package/dist/verifier/deployment.d.ts +49 -0
  47. package/dist/verifier/deployment.js +830 -0
  48. package/dist/verifier/digest.d.ts +23 -0
  49. package/dist/verifier/digest.js +58 -0
  50. package/dist/verifier/extension.d.ts +11 -0
  51. package/dist/verifier/extension.js +75 -0
  52. package/dist/verifier/federation.d.ts +76 -0
  53. package/dist/verifier/federation.js +817 -0
  54. package/dist/verifier/negotiation.d.ts +29 -0
  55. package/dist/verifier/negotiation.js +324 -0
  56. package/dist/verifier/portability.d.ts +12 -0
  57. package/dist/verifier/portability.js +184 -0
  58. package/dist/verifier/predicate.d.ts +10 -0
  59. package/dist/verifier/predicate.js +172 -0
  60. package/dist/verifier/registry.d.ts +16 -0
  61. package/dist/verifier/registry.js +120 -0
  62. package/dist/verifier/registry_engine.d.ts +42 -0
  63. package/dist/verifier/registry_engine.js +220 -0
  64. package/dist/verifier/report.d.ts +13 -0
  65. package/dist/verifier/report.js +29 -0
  66. package/dist/verifier/run_corpus.d.ts +1 -0
  67. package/dist/verifier/run_corpus.js +81 -0
  68. package/dist/verifier/runner.d.ts +20 -0
  69. package/dist/verifier/runner.js +778 -0
  70. package/dist/verifier/schema.d.ts +20 -0
  71. package/dist/verifier/schema.js +623 -0
  72. package/dist/verifier/self_checks.d.ts +1 -0
  73. package/dist/verifier/self_checks.js +316 -0
  74. package/dist/verifier/signature.d.ts +23 -0
  75. package/dist/verifier/signature.js +226 -0
  76. package/dist/verifier/value.d.ts +44 -0
  77. package/dist/verifier/value.js +77 -0
  78. package/package.json +42 -0
@@ -0,0 +1,316 @@
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
+ }
@@ -0,0 +1,23 @@
1
+ import type { Value } from "./value.ts";
2
+ export interface PublicKey {
3
+ keyId: string;
4
+ key: Buffer;
5
+ }
6
+ type VerifyResult = {
7
+ ok: true;
8
+ v: "verified";
9
+ } | {
10
+ ok: false;
11
+ e: string;
12
+ };
13
+ export declare function verify(entry: Value, keys: PublicKey[]): VerifyResult;
14
+ export declare function signingInput(entry: Value): {
15
+ ok: true;
16
+ v: string;
17
+ } | VerifyResult;
18
+ export declare function toCompact(entry: Value): {
19
+ ok: true;
20
+ v: string;
21
+ } | VerifyResult;
22
+ export declare function usableEd25519Key(encoding: Buffer): boolean;
23
+ export {};
@@ -0,0 +1,226 @@
1
+ // Detached JWS verification — the mirror of AgentBlueprintProtocol.Signature:
2
+ // RFC 7515 compact + RFC 7797 b64=false unencoded detached payload, Ed25519
3
+ // via node:crypto (one-shot verify arg order on node ≥ 24 is
4
+ // (algorithm, data, key, signature) — probed on v25.9.0), and the
5
+ // small-order / off-curve public-key rejection the twin added after the
6
+ // found live (:crypto AND OpenSSL both accept small-order keys
7
+ // with all-zero signatures — a universal forgery).
8
+ //
9
+ // Attestations (verify_attestation) are not mirrored: no corpus surface
10
+ // dispatches them and the kind registry is empty by design.
11
+ import { createPublicKey, verify as cryptoVerify } from "node:crypto";
12
+ import * as b64 from "./b64url.js";
13
+ import { encode } from "./canonical.js";
14
+ import * as digest from "./digest.js";
15
+ import { member, memberString } from "./corpus.js";
16
+ const PURPOSES = new Set(["blueprint", "deployment", "federation-envelope"]);
17
+ const CREATED_AT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
18
+ function malformed() {
19
+ return { ok: false, e: "signature_malformed" };
20
+ }
21
+ export function verify(entry, keys) {
22
+ const parts = parseParts(entry);
23
+ if (!parts.ok)
24
+ return parts;
25
+ const input = parts.v.headerB64 + "." + parts.v.payload;
26
+ return check(input, parts.v.signature, parts.v.keyId, keys);
27
+ }
28
+ export function signingInput(entry) {
29
+ const parts = parseParts(entry);
30
+ if (!parts.ok)
31
+ return parts;
32
+ return { ok: true, v: parts.v.headerB64 + "." + parts.v.payload };
33
+ }
34
+ // RFC 7515 detached compact: BASE64URL(JCS(protected)) .. BASE64URL(sig),
35
+ // empty payload segment (Appendix F).
36
+ export function toCompact(entry) {
37
+ const parts = parseParts(entry);
38
+ if (!parts.ok)
39
+ return parts;
40
+ return { ok: true, v: parts.v.headerB64 + "." + "." + b64.encode(parts.v.signature) };
41
+ }
42
+ function parseParts(entry) {
43
+ if (entry.t !== "obj")
44
+ return malformed();
45
+ const names = entry.v.map(([k]) => k).sort();
46
+ if (names.length !== 3 ||
47
+ names[0] !== "protected" ||
48
+ names[1] !== "signature" ||
49
+ names[2] !== "signed_attributes") {
50
+ return malformed();
51
+ }
52
+ const header = member(entry, "protected");
53
+ const attrs = member(entry, "signed_attributes");
54
+ // Header: exactly {alg, b64, crit, kid}; alg must be EdDSA (the twin's one
55
+ // algorithm-unsupported denial in the header), b64 exactly false, crit
56
+ // exactly ["b64"], kid a non-empty string.
57
+ if (header.t !== "obj")
58
+ return malformed();
59
+ const headerNames = header.v.map(([k]) => k).sort();
60
+ if (headerNames.length !== 4 || headerNames.join() !== "alg,b64,crit,kid") {
61
+ return malformed();
62
+ }
63
+ const alg = member(header, "alg");
64
+ if (alg !== null && alg.t === "str" && alg.v !== "EdDSA") {
65
+ return { ok: false, e: "signature_algorithm_unsupported" };
66
+ }
67
+ if (alg === null || alg.t !== "str")
68
+ return malformed();
69
+ const b64Flag = member(header, "b64");
70
+ if (b64Flag === null || b64Flag.t !== "bool" || b64Flag.v !== false)
71
+ return malformed();
72
+ const crit = member(header, "crit");
73
+ if (crit === null ||
74
+ crit.t !== "arr" ||
75
+ crit.v.length !== 1 ||
76
+ crit.v[0].t !== "str" ||
77
+ crit.v[0].v !== "b64") {
78
+ return malformed();
79
+ }
80
+ const kid = member(header, "kid");
81
+ if (kid === null || kid.t !== "str" || kid.v === "")
82
+ return malformed();
83
+ // Attributes: exactly the five closed members.
84
+ if (attrs.t !== "obj")
85
+ return malformed();
86
+ const attrNames = attrs.v.map(([k]) => k).sort();
87
+ if (attrNames.length !== 5 ||
88
+ attrNames.join() !== "algorithm,content_digest,created_at,key_id,purpose") {
89
+ return malformed();
90
+ }
91
+ const algorithm = member(attrs, "algorithm");
92
+ if (algorithm !== null && algorithm.t === "str" && algorithm.v !== "Ed25519") {
93
+ return { ok: false, e: "signature_algorithm_unsupported" };
94
+ }
95
+ if (algorithm === null || algorithm.t !== "str")
96
+ return malformed();
97
+ const contentDigest = memberString(attrs, "content_digest");
98
+ if (contentDigest === null || !digest.fromTagged(contentDigest).ok)
99
+ return malformed();
100
+ const createdAt = memberString(attrs, "created_at");
101
+ if (createdAt === null || !CREATED_AT.test(createdAt) || !validZFormDate(createdAt)) {
102
+ return malformed();
103
+ }
104
+ const keyId = memberString(attrs, "key_id");
105
+ if (keyId === null || keyId === "" || keyId.includes("."))
106
+ return malformed();
107
+ const purpose = memberString(attrs, "purpose");
108
+ if (purpose === null || !PURPOSES.has(purpose))
109
+ return malformed();
110
+ if (kid.v !== keyId)
111
+ return malformed();
112
+ const signatureBody = member(entry, "signature");
113
+ if (signatureBody === null || signatureBody.t !== "str")
114
+ return malformed();
115
+ const decodedSignature = b64.decodeStrict(signatureBody.v);
116
+ if (!decodedSignature.ok || decodedSignature.v.length !== 64)
117
+ return malformed();
118
+ const headerJson = encode(header);
119
+ const attrsJson = encode(attrs);
120
+ if (!headerJson.ok || !attrsJson.ok)
121
+ return malformed();
122
+ return {
123
+ ok: true,
124
+ v: {
125
+ headerB64: b64.encode(Buffer.from(headerJson.v, "utf8")),
126
+ payload: attrsJson.v,
127
+ signature: decodedSignature.v,
128
+ keyId,
129
+ },
130
+ };
131
+ }
132
+ // DateTime.from_iso8601's field validation for the Z whole-second form:
133
+ // regex passes still fail on impossible dates (2026-02-31).
134
+ function validZFormDate(stamped) {
135
+ const year = Number(stamped.slice(0, 4));
136
+ const month = Number(stamped.slice(5, 7));
137
+ const day = Number(stamped.slice(8, 10));
138
+ const hour = Number(stamped.slice(11, 13));
139
+ const minute = Number(stamped.slice(14, 16));
140
+ const second = Number(stamped.slice(17, 19));
141
+ if (month < 1 || month > 12 || day < 1 || hour > 23 || minute > 59 || second > 59) {
142
+ return false;
143
+ }
144
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
145
+ const lengths = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
146
+ return day <= lengths[month - 1];
147
+ }
148
+ function check(input, signature, keyId, keys) {
149
+ const candidates = keys.filter((key) => key.keyId === keyId);
150
+ if (candidates.length === 0)
151
+ return { ok: false, e: "signature_key_unsupported" };
152
+ const usable = candidates.filter((key) => key.key.length === 32 && usableEd25519Key(key.key));
153
+ if (usable.length === 0)
154
+ return { ok: false, e: "signature_algorithm_unsupported" };
155
+ const inputBytes = Buffer.from(input, "utf8");
156
+ for (const key of usable) {
157
+ if (cryptoVerify(null, inputBytes, keyObject(key.key), signature)) {
158
+ return { ok: true, v: "verified" };
159
+ }
160
+ }
161
+ return { ok: false, e: "signature_not_verified" };
162
+ }
163
+ const keyObjectCache = new Map();
164
+ function keyObject(raw) {
165
+ const x = raw.toString("base64url");
166
+ const cached = keyObjectCache.get(x);
167
+ if (cached !== undefined)
168
+ return cached;
169
+ const key = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x }, format: "jwk" });
170
+ keyObjectCache.set(x, key);
171
+ return key;
172
+ }
173
+ // ---- small-order / off-curve rejection (RFC 8032 §5.1 algebra in BigInt) --------
174
+ const ED_P = 2n ** 255n - 19n;
175
+ const ED_D = 37095705934669439343338083508754565189542113879843219016388785533085940283555n;
176
+ const ED_SQRT_M1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n;
177
+ function modPow(base, exponent) {
178
+ let result = 1n;
179
+ let b = base % ED_P;
180
+ let e = exponent;
181
+ while (e > 0n) {
182
+ if (e & 1n)
183
+ result = (result * b) % ED_P;
184
+ b = (b * b) % ED_P;
185
+ e >>= 1n;
186
+ }
187
+ return result;
188
+ }
189
+ export function usableEd25519Key(encoding) {
190
+ if (encoding.length !== 32)
191
+ return false;
192
+ const yRaw = encoding.readBigUInt64LE(0) | (encoding.readBigUInt64LE(8) << 64n) |
193
+ (encoding.readBigUInt64LE(16) << 128n) | (encoding.readBigUInt64LE(24) << 192n);
194
+ // RFC 8032 5.1.2: bit 255 carries the sign of x; the low 255 bits are y.
195
+ const signX = ((yRaw >> 255n) & 1n) === 1n;
196
+ const y = yRaw & ((1n << 255n) - 1n);
197
+ if (y >= ED_P)
198
+ return false; // non-canonical y
199
+ const yy = (y * y) % ED_P;
200
+ const denominator = (ED_D * yy + 1n) % ED_P;
201
+ const x2 = ((yy - 1n) * modPow(denominator, ED_P - 2n)) % ED_P;
202
+ // p = 2^255 - 19 is 5 mod 8: sqrt is a^((p+3)/8), corrected by sqrt(-1)
203
+ // when z^2 = -a. (a^((p+1)/4) is INVALID for this p.)
204
+ const z = modPow(x2, (ED_P + 3n) / 8n);
205
+ let root;
206
+ if ((z * z - x2) % ED_P === 0n)
207
+ root = z;
208
+ else if ((z * z + x2) % ED_P === 0n)
209
+ root = (z * ED_SQRT_M1) % ED_P;
210
+ else
211
+ root = null;
212
+ if (root === null)
213
+ return false; // not on the curve
214
+ // root == 0 happens iff y ∈ {1, p−1} — the identity (order 1) and the
215
+ // order-2 point: non-canonical when sign-set, small-order when sign-clear;
216
+ // both reject (mirrors the Elixir fix found by this mirror's torsion battery).
217
+ if (root === 0n)
218
+ return false;
219
+ const rootOdd = root % 2n === 1n;
220
+ const x = signX === rootOdd ? root : ED_P - root;
221
+ return !smallOrder(x, y);
222
+ }
223
+ function smallOrder(x, y) {
224
+ const ySqrtM1 = (y * ED_SQRT_M1) % ED_P;
225
+ return x === 0n || y === 0n || ySqrtM1 === x || ySqrtM1 === ED_P - x;
226
+ }
@@ -0,0 +1,44 @@
1
+ export type Value = {
2
+ t: "null";
3
+ } | {
4
+ t: "bool";
5
+ v: boolean;
6
+ } | {
7
+ t: "int";
8
+ v: number;
9
+ } | {
10
+ t: "float";
11
+ v: number;
12
+ } | {
13
+ t: "str";
14
+ v: string;
15
+ } | {
16
+ t: "arr";
17
+ v: Value[];
18
+ } | {
19
+ t: "obj";
20
+ v: [string, Value][];
21
+ };
22
+ export type Result<T> = {
23
+ ok: true;
24
+ v: T;
25
+ } | {
26
+ ok: false;
27
+ e: string;
28
+ };
29
+ export declare const ok: <T>(v: T) => Result<T>;
30
+ export declare const err: (e: string) => Result<never>;
31
+ export declare const nil: Value;
32
+ export declare const bool: (v: boolean) => Value;
33
+ export declare const int: (v: number) => Value;
34
+ export declare const float: (v: number) => Value;
35
+ export declare const str: (v: string) => Value;
36
+ export declare const arr: (v: Value[]) => Value;
37
+ export declare const obj: (v: [string, Value][]) => Value;
38
+ export declare const IJSON_MAX = 9007199254740991;
39
+ export declare function sameValue(a: Value, b: Value): boolean;
40
+ export type Plain = null | boolean | number | string | Plain[] | {
41
+ [k: string]: Plain;
42
+ };
43
+ export declare function toPlain(v: Value): Plain;
44
+ export declare function fromPlain(p: Plain): Value;