@intentrax/sdk 1.6.0 → 1.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.
@@ -0,0 +1,364 @@
1
+ // External decision evidence for the local assurance sandbox (B3), VERIFIER
2
+ // SIDE ONLY.
3
+ //
4
+ // Ported from examples/effect-assurance-demo/src/external-decision.mjs (PR
5
+ // #481; docs/architecture/INTENTRAX_EXTERNAL_DECISION_EVIDENCE.md). The
6
+ // sandbox never issues or ingests external decisions itself: a bundle may
7
+ // carry them (`external_decisions`), and `sandbox verify` assesses them.
8
+ //
9
+ // A third party's signed authorization decision is EVIDENCE, never trust:
10
+ // - the original decision bytes are kept verbatim inside an
11
+ // `intentrax.external_decision_evidence/0.1` wrapper, sealed with the bundle;
12
+ // - the signature is checked ONLY against an issuer key set the relying party
13
+ // pinned out of band. This module has no network code at all: it never
14
+ // fetches a key set, a JWKS or a revocation list;
15
+ // - the result is its own optional dimension, EXTERNAL_AUTHORIZATION, with
16
+ // provenance THIRD_PARTY_ATTESTED. It never changes AUTHORIZATION;
17
+ // - the decision must bind the same tool, target, parameters digest and time
18
+ // window as the local decision, otherwise UNBOUND_EXTERNAL_DECISION;
19
+ // - an external DENY against a local ALLOW is CONTRADICTED.
20
+ // - the sandbox ceiling still applies: a bundle with a genuinely signed,
21
+ // bound, required external decision is still LOCAL_NON_TRUST_BEARING.
22
+ //
23
+ // Format profile: a generic Ed25519-over-JCS decision SHAPED LIKE an Open
24
+ // Agent Passport (OAP) decision, plus one profile extension (`action_binding`).
25
+ // Interoperability with genuine APort/OAP decisions is UNVERIFIED: this has
26
+ // never been run against a real signed APort decision. No APort compatibility
27
+ // is claimed.
28
+
29
+ import { verify as edVerify } from "node:crypto";
30
+ import { canonicalJson, digest, sha256Hex } from "./canonical.mjs";
31
+ import { publicKeyFromRaw } from "./keys.mjs";
32
+ import { actionDigest } from "./authority.mjs";
33
+ import { PROVENANCE } from "./model.mjs";
34
+ import { isoMs } from "./time.mjs";
35
+
36
+ export const EXTERNAL_EVIDENCE_SCHEMA = "intentrax.external_decision_evidence/0.1";
37
+
38
+ // The relying party's pinned issuer key set, as the sandbox reads it. Same
39
+ // document shape as the demo's `intentrax.demo.pinned_external_issuers/0.1`,
40
+ // under a sandbox schema id. Kept separate from the local key set: external
41
+ // issuers never sign Intentrax records, and local keys never sign external
42
+ // decisions.
43
+ export const ISSUER_KEY_SET_SCHEMA = "intentrax.local.sandbox_pinned_external_issuers/0.1";
44
+
45
+ // Profile id. Deliberately NOT named "oap" or "aport": it is our reading of the
46
+ // published shape, not a tested implementation of it.
47
+ export const PROFILE_ED25519_JCS_OAP_SHAPED = "intentrax.ext_profile.ed25519_jcs_oap_shaped/0.1";
48
+ export const SUPPORTED_PROFILES = Object.freeze([PROFILE_ED25519_JCS_OAP_SHAPED]);
49
+
50
+ export const WRAPPER_FIELDS = Object.freeze([
51
+ "bound_to",
52
+ "decision_bytes_b64",
53
+ "decision_digest",
54
+ "evidence_id",
55
+ "ingested_at",
56
+ "issuer",
57
+ "issuer_key_set_digest",
58
+ "kid",
59
+ "profile",
60
+ "schema_version",
61
+ ]);
62
+
63
+ // Fields the profile requires in the decision object (OAP prose field list,
64
+ // 2026-10-12, not decision-schema.json, which cannot be satisfied as published).
65
+ const REQUIRED_STRINGS = ["decision_id", "policy_id", "agent_id", "owner_id", "assurance_level", "passport_digest", "kid"];
66
+
67
+ export class IssuerKeySetError extends Error {}
68
+
69
+ function isObj(v) {
70
+ return v !== null && typeof v === "object" && !Array.isArray(v);
71
+ }
72
+
73
+ // Strict timestamps (RFC 3339 with an explicit offset): the shared parser in
74
+ // time.mjs, used everywhere the verifier compares a time.
75
+
76
+ // Parse a pinned issuer key set. Fails closed on anything malformed, including
77
+ // a missing, malformed or inverted validity window (Date.parse() of a bad
78
+ // value is NaN, every NaN comparison is false, and the signing-time checks
79
+ // would otherwise silently pass). The returned digest is what wrappers record
80
+ // as `issuer_key_set_digest`.
81
+ export function loadPinnedIssuerKeySet(doc) {
82
+ const fail = (msg) => {
83
+ throw new IssuerKeySetError("pinned issuer key set: " + msg);
84
+ };
85
+ if (!isObj(doc) || doc.schema_version !== ISSUER_KEY_SET_SCHEMA || !Array.isArray(doc.issuers)) {
86
+ fail("unsupported or malformed document (expected schema_version " + ISSUER_KEY_SET_SCHEMA + ")");
87
+ }
88
+ const byIssuer = new Map();
89
+ const kidOwner = new Map();
90
+ for (const entry of doc.issuers) {
91
+ if (!isObj(entry) || typeof entry.issuer !== "string" || !entry.issuer || byIssuer.has(entry.issuer)) {
92
+ fail("missing or duplicate issuer");
93
+ }
94
+ if (!SUPPORTED_PROFILES.includes(entry.profile) || !Array.isArray(entry.keys) || entry.keys.length === 0) {
95
+ fail("bad profile/keys for " + entry.issuer);
96
+ }
97
+ const keys = new Map();
98
+ for (const k of entry.keys) {
99
+ if (!isObj(k) || k.alg !== "Ed25519" || typeof k.kid !== "string" || !k.kid || kidOwner.has(k.kid)) {
100
+ fail("bad alg or duplicate kid " + (isObj(k) ? k.kid : k));
101
+ }
102
+ const from = isoMs(k.valid_from);
103
+ const until = isoMs(k.valid_until);
104
+ if (from === null || until === null || from >= until) {
105
+ fail("missing or invalid validity window for " + k.kid);
106
+ }
107
+ if (k.revoked_at !== undefined && isoMs(k.revoked_at) === null) {
108
+ fail("invalid revoked_at for " + k.kid);
109
+ }
110
+ let publicKey;
111
+ try {
112
+ publicKey = publicKeyFromRaw(k.public_key);
113
+ } catch {
114
+ fail("bad public key for " + k.kid);
115
+ }
116
+ keys.set(k.kid, Object.freeze({ ...k, publicKey }));
117
+ kidOwner.set(k.kid, entry.issuer);
118
+ }
119
+ byIssuer.set(entry.issuer, { profile: entry.profile, keys });
120
+ }
121
+ let setDigest;
122
+ try {
123
+ setDigest = digest(doc);
124
+ } catch {
125
+ fail("not canonicalizable");
126
+ }
127
+ return Object.freeze({ digest: setDigest, byIssuer, kidOwner });
128
+ }
129
+
130
+ // The profile's binding extension, derived from a local decision request.
131
+ export function actionBindingFor({ operation, resource, params }) {
132
+ return { tool: operation, target: resource, parameters_digest: digest(params) };
133
+ }
134
+
135
+ // Signed message: RFC 8785 JCS of the decision object WITHOUT its `signature`
136
+ // member. OAP says only "signature over JCS-canonicalized decision payload";
137
+ // which members that payload excludes is not specified (UNVERIFIED).
138
+ export function externalSigningBytes(decisionWithoutSignature) {
139
+ return Buffer.from(canonicalJson(decisionWithoutSignature), "utf8");
140
+ }
141
+
142
+ function decodeBytes(wrapper) {
143
+ const s = wrapper.decision_bytes_b64;
144
+ if (typeof s !== "string") return null;
145
+ const bytes = Buffer.from(s, "base64");
146
+ return bytes.toString("base64") === s ? bytes : null;
147
+ }
148
+
149
+ // Record-integrity checks on the wrapper (shape, digest of the carried bytes,
150
+ // and that the wrapper names THIS local decision). Returns reason codes.
151
+ export function wrapperIntegrityReasons(wrapper, d, i) {
152
+ const where = ":" + i;
153
+ if (!isObj(wrapper) || Object.keys(wrapper).sort().join(",") !== WRAPPER_FIELDS.join(",")
154
+ || wrapper.schema_version !== EXTERNAL_EVIDENCE_SCHEMA || !isObj(wrapper.bound_to)) {
155
+ return ["EXTERNAL_EVIDENCE_MALFORMED" + where];
156
+ }
157
+ const reasons = [];
158
+ const bytes = decodeBytes(wrapper);
159
+ if (!bytes || "sha256:" + sha256Hex(bytes) !== wrapper.decision_digest) {
160
+ reasons.push("EXTERNAL_DECISION_DIGEST_MISMATCH" + where);
161
+ }
162
+ if (wrapper.bound_to.intentrax_decision_id !== d.decision_id || wrapper.bound_to.action_digest !== actionDigest(d.request)) {
163
+ reasons.push("EXTERNAL_EVIDENCE_BINDING_MISMATCH" + where);
164
+ }
165
+ return reasons;
166
+ }
167
+
168
+ // ---- verification ---------------------------------------------------------
169
+
170
+ export const EXTERNAL_LIMITATION_TEXT = Object.freeze({
171
+ EXTERNAL_ISSUER_POLICY_UNKNOWN:
172
+ "Intentrax cannot re-evaluate the external issuer's policy; the decision shows what the issuer concluded, not that it was right.",
173
+ EXTERNAL_ISSUER_REVOCATION_NOT_REQUERIED:
174
+ "Passport or key suspension/revocation after issuance is not re-queried offline; only the pinned key set's validity window is applied.",
175
+ EXTERNAL_AGENT_IDENTITY_NOT_MAPPED:
176
+ "The issuer's agent_id/owner_id are not mapped to the sandbox agent; the binding covers tool, target, parameters and time only.",
177
+ EXTERNAL_PROFILE_INTEROP_UNVERIFIED:
178
+ "The OAP-shaped profile follows the published OAP text; it has not been tested against a genuine signed APort decision. No APort compatibility is claimed.",
179
+ EXTERNAL_SIGNING_TIME_SELF_ASSERTED:
180
+ "The external decision's created_at is asserted by its issuer; key validity and expiry are judged against it.",
181
+ ISSUER_KEY_SET_CHANGED_SINCE_INGESTION:
182
+ "The relying party's pinned issuer key set differs from the one recorded at ingestion; the verifier used its own pinned set.",
183
+ });
184
+
185
+ const BASE_LIMITATIONS = [
186
+ "EXTERNAL_ISSUER_POLICY_UNKNOWN",
187
+ "EXTERNAL_ISSUER_REVOCATION_NOT_REQUERIED",
188
+ "EXTERNAL_AGENT_IDENTITY_NOT_MAPPED",
189
+ "EXTERNAL_PROFILE_INTEROP_UNVERIFIED",
190
+ "EXTERNAL_SIGNING_TIME_SELF_ASSERTED",
191
+ ];
192
+
193
+ const SIG_RE = /^ed25519:[A-Za-z0-9+/]+={0,2}$/;
194
+
195
+ // Assess one wrapped decision. Never throws.
196
+ // ctx: { d (local decision payload), reports, effectConfirmed, issuerKeys }
197
+ function assessOne(wrapper, ctx) {
198
+ const { d, reports, effectConfirmed, issuerKeys } = ctx;
199
+ const out = {
200
+ evidence_id: wrapper.evidence_id,
201
+ issuer: wrapper.issuer,
202
+ kid: wrapper.kid,
203
+ profile: wrapper.profile,
204
+ result: "INSUFFICIENT_EVIDENCE",
205
+ reasons: [],
206
+ signature: "NOT_CHECKED",
207
+ bound: null,
208
+ outcome: null,
209
+ created_at: null,
210
+ expires_at: null,
211
+ key_set_digest_matches: issuerKeys ? wrapper.issuer_key_set_digest === issuerKeys.digest : null,
212
+ };
213
+ const done = (result, ...reasons) => {
214
+ out.result = result;
215
+ out.reasons.push(...reasons);
216
+ return out;
217
+ };
218
+
219
+ if (!SUPPORTED_PROFILES.includes(wrapper.profile)) return done("INSUFFICIENT_EVIDENCE", "UNSUPPORTED_EXTERNAL_PROFILE");
220
+ let decision;
221
+ try {
222
+ decision = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(decodeBytes(wrapper)));
223
+ } catch {
224
+ return done("FAILED", "EXTERNAL_DECISION_MALFORMED");
225
+ }
226
+ if (!isObj(decision)) return done("FAILED", "EXTERNAL_DECISION_MALFORMED");
227
+ if (decision.kid !== wrapper.kid) return done("FAILED", "EXTERNAL_KID_MISMATCH");
228
+
229
+ // -- signature, against the pinned issuer key set only --
230
+ if (!issuerKeys) return done("NOT_ASSESSED", "NO_PINNED_ISSUER_KEY_SET");
231
+ const owner = issuerKeys.kidOwner.get(wrapper.kid);
232
+ if (owner === undefined) return done("INSUFFICIENT_EVIDENCE", "EXTERNAL_ISSUER_KEY_NOT_PINNED");
233
+ if (owner !== wrapper.issuer) return done("INSUFFICIENT_EVIDENCE", "KID_PINNED_FOR_DIFFERENT_ISSUER");
234
+ const pinnedIssuer = issuerKeys.byIssuer.get(owner);
235
+ if (pinnedIssuer.profile !== wrapper.profile) return done("INSUFFICIENT_EVIDENCE", "PROFILE_NOT_PINNED_FOR_ISSUER");
236
+ const key = pinnedIssuer.keys.get(wrapper.kid);
237
+ const { signature, ...unsigned } = decision;
238
+ if (typeof signature !== "string" || !SIG_RE.test(signature)) return done("FAILED", "EXTERNAL_SIGNATURE_MALFORMED");
239
+ const sig = Buffer.from(signature.slice("ed25519:".length), "base64");
240
+ let message;
241
+ try {
242
+ message = externalSigningBytes(unsigned);
243
+ } catch {
244
+ // The sandbox's JCS covers integers only; a decision with other numbers
245
+ // cannot be checked here (RFC 8785 number serialization not implemented).
246
+ return done("INSUFFICIENT_EVIDENCE", "EXTERNAL_DECISION_NOT_CANONICALIZABLE");
247
+ }
248
+ let valid = false;
249
+ try {
250
+ valid = sig.length === 64 && edVerify(null, message, key.publicKey, sig);
251
+ } catch {
252
+ valid = false;
253
+ }
254
+ if (!valid) {
255
+ out.signature = "INVALID";
256
+ return done("FAILED", "EXTERNAL_SIGNATURE_INVALID_FOR_PINNED_KEY");
257
+ }
258
+ out.signature = "VALID_PINNED_KEY";
259
+
260
+ // -- shape (profile) --
261
+ const bad = REQUIRED_STRINGS.filter((f) => typeof decision[f] !== "string");
262
+ if (typeof decision.allow !== "boolean") bad.push("allow");
263
+ if (!Array.isArray(decision.reasons) || !decision.reasons.length || !decision.reasons.every((r) => isObj(r) && typeof r.code === "string")) {
264
+ bad.push("reasons");
265
+ }
266
+ const created = isoMs(decision.created_at);
267
+ if (created === null) bad.push("created_at");
268
+ if (!Number.isSafeInteger(decision.expires_in) || decision.expires_in < 0) bad.push("expires_in");
269
+ if (bad.length) return done("INSUFFICIENT_EVIDENCE", ...bad.map((f) => "EXTERNAL_DECISION_SHAPE_INVALID:" + f));
270
+ out.outcome = decision.allow ? "ALLOW" : "DENY";
271
+ out.created_at = decision.created_at;
272
+ const expires = created + decision.expires_in * 1000;
273
+ out.expires_at = new Date(expires).toISOString().replace(/\.\d{3}Z$/, "Z");
274
+
275
+ // -- key validity at the (self-asserted) signing time --
276
+ if (created < isoMs(key.valid_from) || created >= isoMs(key.valid_until)) {
277
+ return done("INSUFFICIENT_EVIDENCE", "EXTERNAL_KEY_NOT_VALID_AT_SIGNING_TIME");
278
+ }
279
+ if (key.revoked_at !== undefined && created >= isoMs(key.revoked_at)) {
280
+ return done("INSUFFICIENT_EVIDENCE", "EXTERNAL_KEY_REVOKED_AT_SIGNING_TIME");
281
+ }
282
+
283
+ // -- binding: same tool, target, parameters digest, time window --
284
+ const unbound = [];
285
+ const b = decision.action_binding;
286
+ if (!isObj(b)) {
287
+ unbound.push("UNBOUND_EXTERNAL_DECISION:NO_ACTION_BINDING");
288
+ } else {
289
+ if (b.tool !== d.request.operation) unbound.push("UNBOUND_EXTERNAL_DECISION:tool");
290
+ if (b.target !== d.request.resource) unbound.push("UNBOUND_EXTERNAL_DECISION:target");
291
+ if (b.parameters_digest !== digest(d.request.params)) unbound.push("UNBOUND_EXTERNAL_DECISION:parameters_digest");
292
+ }
293
+ // The action happens at the first execution start, or (no execution) at the
294
+ // local decision. The external decision must precede it...
295
+ // Strict (explicit offset), and no `??` fallback: a report whose
296
+ // started_at is missing or unparseable fails closed instead of silently
297
+ // using the decision time (demo #490/#491 parity).
298
+ const actionAt = isoMs(reports.length ? reports[0].started_at : d.decided_at);
299
+ if (actionAt === null || created > actionAt) unbound.push("UNBOUND_EXTERNAL_DECISION:issued_after_action");
300
+ out.bound = unbound.length === 0;
301
+ if (unbound.length) return done("INSUFFICIENT_EVIDENCE", ...unbound);
302
+ // ...and still be in force when it happens.
303
+ if (actionAt >= expires) return done("INSUFFICIENT_EVIDENCE", "EXTERNAL_DECISION_EXPIRED");
304
+
305
+ // -- conflict rules --
306
+ if (out.outcome === "DENY" && d.outcome === "ALLOW") {
307
+ return done("CONTRADICTED", "EXTERNAL_DENY_INTENTRAX_ALLOW",
308
+ ...(reports.length ? ["EXECUTED_DESPITE_EXTERNAL_DENY"] : []));
309
+ }
310
+ // Informational cross-checks: the external decision is genuine and bound,
311
+ // so the dimension stays VERIFIED, but the report says what happened next.
312
+ if (out.outcome === "ALLOW" && d.outcome === "DENY") out.reasons.push("EXTERNAL_ALLOW_INTENTRAX_DENY");
313
+ if (out.outcome === "ALLOW" && effectConfirmed === "CONTRADICTED") out.reasons.push("EXTERNAL_ALLOW_BUT_EFFECT_CONTRADICTED");
314
+ out.result = "VERIFIED";
315
+ return out;
316
+ }
317
+
318
+ // Assess every wrapped decision and aggregate into one EXTERNAL_AUTHORIZATION
319
+ // assessment body: { result, provenance, reasons, limitations, evidence_digests, detail }.
320
+ // authorizationIssuers: issuers the relying party's assurance profile names.
321
+ // Empty = EXTERNAL_AUTHORIZATION is informational (non-required) and any
322
+ // pinned issuer's VERIFIED decision counts as VERIFIED.
323
+ export function assessExternalAuthorization({
324
+ wrappers, d, reports, effectConfirmed, issuerKeys, authorizationIssuers = [],
325
+ }) {
326
+ const per = wrappers.map((w) => assessOne(w, { d, reports, effectConfirmed, issuerKeys }));
327
+ const limitations = [...BASE_LIMITATIONS];
328
+ if (per.some((p) => p.key_set_digest_matches === false)) limitations.push("ISSUER_KEY_SET_CHANGED_SINCE_INGESTION");
329
+ const reasons = [...new Set(per.flatMap((p) => p.reasons))];
330
+ const results = per.map((p) => p.result);
331
+ let result;
332
+ if (!per.length) {
333
+ result = "INSUFFICIENT_EVIDENCE";
334
+ reasons.push("NO_EXTERNAL_DECISION_IN_BUNDLE");
335
+ } else if (results.includes("FAILED")) {
336
+ result = "FAILED";
337
+ } else if (results.includes("CONTRADICTED")) {
338
+ result = "CONTRADICTED";
339
+ } else {
340
+ const eligible = per.filter((p) => p.result === "VERIFIED"
341
+ && (!authorizationIssuers.length || authorizationIssuers.includes(p.issuer)));
342
+ if (eligible.length) {
343
+ result = "VERIFIED";
344
+ } else if (results.includes("VERIFIED")) {
345
+ result = "INSUFFICIENT_EVIDENCE";
346
+ reasons.push("EXTERNAL_ISSUER_NOT_NAMED_BY_PROFILE");
347
+ } else {
348
+ result = results.every((r) => r === "NOT_ASSESSED") ? "NOT_ASSESSED" : "INSUFFICIENT_EVIDENCE";
349
+ }
350
+ }
351
+ return {
352
+ result,
353
+ provenance: PROVENANCE.THIRD_PARTY_ATTESTED,
354
+ reasons,
355
+ limitations,
356
+ evidence_digests: wrappers.map((w) => w.decision_digest),
357
+ detail: {
358
+ substitutes_for_authorization: false,
359
+ profile_names_issuers: authorizationIssuers,
360
+ pinned_issuer_key_set_digest: issuerKeys ? issuerKeys.digest : null,
361
+ decisions: per,
362
+ },
363
+ };
364
+ }
@@ -0,0 +1,179 @@
1
+ // Ephemeral local signing keys for the assurance sandbox.
2
+ //
3
+ // Adapted from examples/effect-assurance-demo/src/keys.mjs (PRs #449, #477).
4
+ // The demo derives its keys from public strings; the sandbox instead generates
5
+ // fresh random Ed25519 keys on every run. Every key is labelled
6
+ // `environment: "local"` and `trust_bearing: false`, and the loader refuses
7
+ // any key set that is not labelled exactly that way.
8
+ //
9
+ // Separation from production, by construction:
10
+ // - this module never opens, derives from, or requests any production or
11
+ // published sandbox key (it has no file path, URL or seed for one);
12
+ // - the local key set has its own schema, which production verifiers
13
+ // (`verify-proof`, the Go offline verifier, hosted verify) do not parse;
14
+ // - production key sets never contain `environment: "local"` keys.
15
+
16
+ import { createPublicKey, generateKeyPairSync } from "node:crypto";
17
+ import { sha256Hex } from "./canonical.mjs";
18
+ import { isoMs } from "./time.mjs";
19
+
20
+ export const LOCAL_ENVIRONMENT = "local";
21
+ export const LOCAL_KEY_SET_SCHEMA = "intentrax.local.sandbox_key_set/0.1";
22
+ export const LOCAL_SIGNING_KEYS_SCHEMA = "intentrax.local.sandbox_signing_keys/0.1";
23
+ export const LOCAL_KEY_VALIDITY_SECONDS = 24 * 60 * 60;
24
+
25
+ export const ROLES = Object.freeze({
26
+ PRINCIPAL: "PRINCIPAL", // the local "organisation" issuing the root mandate
27
+ DECISION_SERVICE: "DECISION_SERVICE", // local decision + bundle seal
28
+ EXECUTOR: "EXECUTOR", // the executor shim (self-report only)
29
+ EFFECT_VERIFIER: "EFFECT_VERIFIER", // the sandbox's independent read-only check
30
+ });
31
+
32
+ // The identity each local key speaks for.
33
+ export const LOCAL_PRINCIPALS = Object.freeze({
34
+ PRINCIPAL: "local:sandbox-principal",
35
+ DECISION_SERVICE: "local:sandbox-decision-service",
36
+ EXECUTOR: "local:sandbox-executor",
37
+ EFFECT_VERIFIER: "local:sandbox-effect-verifier",
38
+ });
39
+
40
+ const WARNING =
41
+ "LOCAL SANDBOX ONLY. These keys were generated on this machine for one sandbox run. They are not " +
42
+ "trust-bearing, are not published by Intentrax, and must never be added to a production key set.";
43
+
44
+ function rawPublicKey(publicKey) {
45
+ const spki = publicKey.export({ format: "der", type: "spki" });
46
+ return spki.subarray(spki.length - 32);
47
+ }
48
+
49
+ export function publicKeyFromRaw(b64) {
50
+ const raw = Buffer.from(String(b64), "base64url");
51
+ if (raw.length !== 32) {
52
+ throw new Error("ed25519 public key must be 32 bytes");
53
+ }
54
+ const spki = Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), raw]);
55
+ return createPublicKey({ key: spki, format: "der", type: "spki" });
56
+ }
57
+
58
+ function iso(ms) {
59
+ return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
60
+ }
61
+
62
+ // Generate one fresh Ed25519 key per role. Returns signers (holding private
63
+ // keys, in memory) and the PUBLIC local key set a verifier pins.
64
+ export function generateLocalSigners({ now }) {
65
+ const validFrom = iso(Date.parse(now));
66
+ const validUntil = iso(Date.parse(now) + LOCAL_KEY_VALIDITY_SECONDS * 1000);
67
+ const signers = {};
68
+ for (const role of Object.values(ROLES)) {
69
+ const { privateKey, publicKey } = generateKeyPairSync("ed25519");
70
+ const publicKeyB64 = Buffer.from(rawPublicKey(publicKey)).toString("base64url");
71
+ const keyId = "local-" + role.toLowerCase().replace(/_/g, "-") + "-" + sha256Hex(publicKeyB64).slice(0, 12);
72
+ signers[role] = Object.freeze({
73
+ key_id: keyId,
74
+ role,
75
+ principal: LOCAL_PRINCIPALS[role],
76
+ privateKey,
77
+ publicKey,
78
+ public_key: publicKeyB64,
79
+ valid_from: validFrom,
80
+ valid_until: validUntil,
81
+ environment: LOCAL_ENVIRONMENT,
82
+ trust_bearing: false,
83
+ });
84
+ }
85
+ return Object.freeze(signers);
86
+ }
87
+
88
+ function keyEntry(signer) {
89
+ return {
90
+ key_id: signer.key_id,
91
+ alg: "Ed25519",
92
+ role: signer.role,
93
+ principal: signer.principal,
94
+ public_key: signer.public_key,
95
+ valid_from: signer.valid_from,
96
+ valid_until: signer.valid_until,
97
+ environment: LOCAL_ENVIRONMENT,
98
+ trust_bearing: false,
99
+ };
100
+ }
101
+
102
+ // The public key set for one run. Safe to share; useful only for
103
+ // re-verifying that run's bundle locally.
104
+ export function localKeySetDocument(signers) {
105
+ return {
106
+ schema_version: LOCAL_KEY_SET_SCHEMA,
107
+ environment: LOCAL_ENVIRONMENT,
108
+ trust_bearing: false,
109
+ warning: WARNING,
110
+ keys: Object.values(signers).map(keyEntry),
111
+ };
112
+ }
113
+
114
+ // The private key material for one run (written under .intentrax/local/,
115
+ // which is gitignored). Never needed for verification.
116
+ export function localSigningKeysDocument(signers, generatedAt) {
117
+ return {
118
+ schema_version: LOCAL_SIGNING_KEYS_SCHEMA,
119
+ environment: LOCAL_ENVIRONMENT,
120
+ trust_bearing: false,
121
+ generated_at: generatedAt,
122
+ warning: WARNING + " Private keys: do not commit or share.",
123
+ keys: Object.values(signers).map((s) => ({
124
+ ...keyEntry(s),
125
+ private_key_pkcs8: s.privateKey.export({ format: "der", type: "pkcs8" }).toString("base64url"),
126
+ })),
127
+ };
128
+ }
129
+
130
+ export class LocalKeySetError extends Error {}
131
+
132
+ // Parse a local key set into the lookup the verifier uses. Fails closed on
133
+ // anything that is not an explicitly local, explicitly non-trust-bearing set,
134
+ // so a production or published key set can never be used here, and a local
135
+ // key can never be relabelled as trust-bearing.
136
+ export function loadLocalKeySet(doc) {
137
+ if (!doc || typeof doc !== "object" || doc.schema_version !== LOCAL_KEY_SET_SCHEMA) {
138
+ throw new LocalKeySetError(
139
+ "not a local sandbox key set (expected schema_version " + LOCAL_KEY_SET_SCHEMA + "); " +
140
+ "production and published key sets cannot be used with the sandbox verifier",
141
+ );
142
+ }
143
+ if (doc.environment !== LOCAL_ENVIRONMENT || doc.trust_bearing !== false) {
144
+ throw new LocalKeySetError("local key set must declare environment \"local\" and trust_bearing false");
145
+ }
146
+ if (!Array.isArray(doc.keys) || doc.keys.length === 0) {
147
+ throw new LocalKeySetError("local key set has no keys");
148
+ }
149
+ const byId = new Map();
150
+ for (const entry of doc.keys) {
151
+ if (!entry || typeof entry !== "object") {
152
+ throw new LocalKeySetError("local key set: malformed key entry");
153
+ }
154
+ if (entry.environment !== LOCAL_ENVIRONMENT || entry.trust_bearing !== false) {
155
+ throw new LocalKeySetError("local key set: key " + entry.key_id + " is not labelled environment local / trust_bearing false");
156
+ }
157
+ if (byId.has(entry.key_id)) {
158
+ throw new LocalKeySetError("local key set: duplicate key_id " + entry.key_id);
159
+ }
160
+ if (entry.alg !== "Ed25519" || !Object.values(ROLES).includes(entry.role)) {
161
+ throw new LocalKeySetError("local key set: bad alg/role for " + entry.key_id);
162
+ }
163
+ // Strict, explicit-offset, non-inverted window (#491 parity): a NaN bound
164
+ // would compare false and silently pass the signing-time check.
165
+ const from = isoMs(entry.valid_from);
166
+ const until = isoMs(entry.valid_until);
167
+ if (from === null || until === null || from >= until) {
168
+ throw new LocalKeySetError("local key set: bad validity window for " + entry.key_id);
169
+ }
170
+ let publicKey;
171
+ try {
172
+ publicKey = publicKeyFromRaw(entry.public_key);
173
+ } catch {
174
+ throw new LocalKeySetError("local key set: bad public key for " + entry.key_id);
175
+ }
176
+ byId.set(entry.key_id, Object.freeze({ ...entry, publicKey }));
177
+ }
178
+ return byId;
179
+ }