@intentrax/sdk 1.6.0 → 1.8.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 (62) hide show
  1. package/README.md +56 -3
  2. package/cli/intentrax.mjs +57 -1
  3. package/index.js +4 -2
  4. package/index.ts +4 -2
  5. package/mcp/README.md +138 -0
  6. package/mcp/canonical.d.ts +12 -0
  7. package/mcp/canonical.mjs +70 -0
  8. package/mcp/cli.d.ts +16 -0
  9. package/mcp/cli.mjs +214 -0
  10. package/mcp/client.d.ts +131 -0
  11. package/mcp/client.mjs +955 -0
  12. package/mcp/commands.d.ts +113 -0
  13. package/mcp/commands.mjs +575 -0
  14. package/mcp/index.d.ts +12 -0
  15. package/mcp/index.mjs +12 -0
  16. package/mcp/proxy.d.ts +47 -0
  17. package/mcp/proxy.mjs +434 -0
  18. package/mcp/receipt-meta.d.ts +59 -0
  19. package/mcp/receipt-meta.mjs +178 -0
  20. package/mcp/tool-manifest.d.ts +74 -0
  21. package/mcp/tool-manifest.mjs +154 -0
  22. package/package.json +19 -1
  23. package/readback/README.md +352 -0
  24. package/readback/bridge.mjs +71 -0
  25. package/readback/cli.mjs +150 -0
  26. package/readback/confirm.mjs +404 -0
  27. package/readback/index.mjs +12 -0
  28. package/readback/recipe-worker.mjs +33 -0
  29. package/readback/recipes/_shared.mjs +126 -0
  30. package/readback/recipes/email-delivery.mjs +136 -0
  31. package/readback/recipes/github-issue.mjs +88 -0
  32. package/readback/recipes/http-json.mjs +109 -0
  33. package/readback/recipes/sql-row.mjs +96 -0
  34. package/readback/recipes/stripe-refund.mjs +73 -0
  35. package/readback/redact.mjs +68 -0
  36. package/sandbox/README.md +255 -0
  37. package/sandbox/authority.mjs +66 -0
  38. package/sandbox/bundle.mjs +93 -0
  39. package/sandbox/canonical.mjs +64 -0
  40. package/sandbox/check-runner.mjs +50 -0
  41. package/sandbox/check-worker.mjs +30 -0
  42. package/sandbox/cli.mjs +376 -0
  43. package/sandbox/effect-verifier.mjs +242 -0
  44. package/sandbox/effects.mjs +80 -0
  45. package/sandbox/envelope.mjs +174 -0
  46. package/sandbox/examples/read-only-check.example.mjs +32 -0
  47. package/sandbox/external-decision.mjs +364 -0
  48. package/sandbox/keys.mjs +179 -0
  49. package/sandbox/model.mjs +170 -0
  50. package/sandbox/run.mjs +324 -0
  51. package/sandbox/time.mjs +18 -0
  52. package/sandbox/verifier.mjs +503 -0
  53. package/scan/README.md +211 -0
  54. package/scan/classify.mjs +276 -0
  55. package/scan/cli.mjs +102 -0
  56. package/scan/configs.mjs +261 -0
  57. package/scan/credentials.mjs +121 -0
  58. package/scan/extract.mjs +323 -0
  59. package/scan/gates.mjs +94 -0
  60. package/scan/report.mjs +58 -0
  61. package/scan/scan.mjs +571 -0
  62. package/scan/text.mjs +186 -0
@@ -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
+ }
@@ -0,0 +1,170 @@
1
+ // Evidence-quality model for the local assurance sandbox.
2
+ //
3
+ // Ported from examples/effect-assurance-demo/src/model.mjs (PRs #449, #477;
4
+ // INTENTRAX_ASSURANCE_GAP_ANALYSIS.md §5). The eight dimensions, the
5
+ // profiles and the §5.4 verdict rule are unchanged. The sandbox adds ONE
6
+ // thing: a verdict ceiling. Every bundle the sandbox can produce is signed by
7
+ // ephemeral local keys that are not trust-bearing, so the strongest verdict a
8
+ // local bundle can ever receive is LOCAL_NON_TRUST_BEARING, never
9
+ // VERIFIED_FOR_SCOPE, whatever key set the user pins.
10
+
11
+ export const DIMENSIONS = Object.freeze([
12
+ "RECORD_INTEGRITY",
13
+ "SIGNER_AUTHENTICITY",
14
+ "AUTHORIZATION",
15
+ "EXECUTION_REPORTED",
16
+ "EXECUTION_ATTESTED",
17
+ "EFFECT_OBSERVED",
18
+ "EFFECT_CONFIRMED",
19
+ "CAUSAL_CHAIN",
20
+ ]);
21
+
22
+ // Optional dimensions (B3, INTENTRAX_EXTERNAL_DECISION_EVIDENCE.md; ported from
23
+ // the demo, PR #481). Not in DIMENSIONS: a report carries one only when the
24
+ // bundle has the evidence it assesses or the relying party requires it, so
25
+ // ordinary sandbox reports keep exactly the eight core dimensions.
26
+ // EXTERNAL_AUTHORIZATION: a third party's signed authorization decision,
27
+ // verified against a relying-party-pinned issuer key set. Provenance is always
28
+ // THIRD_PARTY_ATTESTED; it never stands in for the local AUTHORIZATION.
29
+ export const OPTIONAL_DIMENSIONS = Object.freeze(["EXTERNAL_AUTHORIZATION"]);
30
+
31
+ // §5.2, plus OBSERVED for the EFFECT_OBSERVED dimension.
32
+ export const RESULTS = Object.freeze([
33
+ "VERIFIED",
34
+ "REPORTED",
35
+ "ATTESTED",
36
+ "OBSERVED",
37
+ "CONFIRMED",
38
+ "CONTRADICTED",
39
+ "PENDING",
40
+ "INSUFFICIENT_EVIDENCE",
41
+ "NOT_ASSESSED",
42
+ "NOT_APPLICABLE",
43
+ "FAILED",
44
+ ]);
45
+
46
+ export const PROVENANCE = Object.freeze({
47
+ SELF_REPORTED: "SELF_REPORTED",
48
+ INTENTRAX_DECISION: "INTENTRAX_DECISION",
49
+ ENFORCEMENT_ATTESTED: "ENFORCEMENT_ATTESTED",
50
+ AUTHORITATIVE_SOURCE: "AUTHORITATIVE_SOURCE",
51
+ THIRD_PARTY_ATTESTED: "THIRD_PARTY_ATTESTED",
52
+ VERIFIER_COMPUTED: "VERIFIER_COMPUTED",
53
+ });
54
+
55
+ // Assurance profiles, weakest first. EXECUTION_REPORTED is deliberately never
56
+ // required: a self-report can never satisfy a profile.
57
+ export const PROFILES = Object.freeze({
58
+ DECISION_RECORD: ["RECORD_INTEGRITY", "SIGNER_AUTHENTICITY", "AUTHORIZATION"],
59
+ AUTHORIZED_AND_ATTESTED: ["RECORD_INTEGRITY", "SIGNER_AUTHENTICITY", "AUTHORIZATION", "EXECUTION_ATTESTED"],
60
+ EFFECT_CONFIRMED: ["RECORD_INTEGRITY", "SIGNER_AUTHENTICITY", "AUTHORIZATION", "EFFECT_OBSERVED", "EFFECT_CONFIRMED"],
61
+ CAUSAL_CHAIN: [
62
+ "RECORD_INTEGRITY", "SIGNER_AUTHENTICITY", "AUTHORIZATION", "EFFECT_OBSERVED", "EFFECT_CONFIRMED", "CAUSAL_CHAIN",
63
+ ],
64
+ });
65
+
66
+ export const PROFILE_STRENGTH = Object.freeze({
67
+ DECISION_RECORD: 0,
68
+ AUTHORIZED_AND_ATTESTED: 1,
69
+ EFFECT_CONFIRMED: 2,
70
+ CAUSAL_CHAIN: 3,
71
+ });
72
+
73
+ export function strongerProfile(a, b) {
74
+ return PROFILE_STRENGTH[a] >= PROFILE_STRENGTH[b] ? a : b;
75
+ }
76
+
77
+ export const VERDICTS = Object.freeze({
78
+ VERIFICATION_FAILED: "VERIFICATION_FAILED",
79
+ INTEGRITY_ONLY: "INTEGRITY_ONLY",
80
+ CONFLICTING_EVIDENCE: "CONFLICTING_EVIDENCE",
81
+ PENDING_FINALITY: "PENDING_FINALITY",
82
+ INSUFFICIENT_EVIDENCE: "INSUFFICIENT_EVIDENCE",
83
+ // Sandbox-only. The ceiling for anything signed by local keys: every check
84
+ // that the bundle can carry passed, but no signer is trust-bearing, so this
85
+ // is never production assurance.
86
+ LOCAL_NON_TRUST_BEARING: "LOCAL_NON_TRUST_BEARING",
87
+ VERIFIED_FOR_SCOPE: "VERIFIED_FOR_SCOPE",
88
+ });
89
+
90
+ // Rule precedence, first-matching rule = 0. LOCAL_NON_TRUST_BEARING sits
91
+ // directly below VERIFIED_FOR_SCOPE: the ceiling removes the positive claim
92
+ // but never hides a negative finding (a contradiction stays a contradiction).
93
+ export const VERDICT_PRECEDENCE = Object.freeze({
94
+ VERIFICATION_FAILED: 0,
95
+ INTEGRITY_ONLY: 1,
96
+ CONFLICTING_EVIDENCE: 2,
97
+ PENDING_FINALITY: 3,
98
+ INSUFFICIENT_EVIDENCE: 4,
99
+ LOCAL_NON_TRUST_BEARING: 5,
100
+ VERIFIED_FOR_SCOPE: 6,
101
+ });
102
+
103
+ export const LOCAL_VERDICT_CEILING = VERDICTS.LOCAL_NON_TRUST_BEARING;
104
+
105
+ const WEAK = new Set(["REPORTED", "INSUFFICIENT_EVIDENCE", "NOT_ASSESSED"]);
106
+ const SATISFYING = new Set(["VERIFIED", "ATTESTED", "OBSERVED", "CONFIRMED"]);
107
+
108
+ // §5.4 order, with the V-1 change (CONTRADICTED anywhere -> CONFLICTING_EVIDENCE).
109
+ // `assessments` is { [dimension]: result }.
110
+ // A required dimension that is missing or NOT_APPLICABLE counts as
111
+ // INSUFFICIENT_EVIDENCE (never a bare VALID).
112
+ // `extraRequired`: dimensions the relying party adds to the profile (e.g.
113
+ // EXTERNAL_AUTHORIZATION when it names an external issuer). Additive only: it
114
+ // can make a verdict weaker, never stronger.
115
+ export function deriveVerdict(assessments, profile, { extraRequired = [] } = {}) {
116
+ if (!PROFILES[profile]) {
117
+ throw new Error("unknown assurance profile " + profile);
118
+ }
119
+ const required = [...new Set([...PROFILES[profile], ...extraRequired])];
120
+ const all = Object.values(assessments);
121
+ const req = required.map((d) => assessments[d] ?? "INSUFFICIENT_EVIDENCE");
122
+ if (all.includes("FAILED")) return VERDICTS.VERIFICATION_FAILED;
123
+ if (assessments.SIGNER_AUTHENTICITY !== "VERIFIED") return VERDICTS.INTEGRITY_ONLY;
124
+ // V-1 (honest verdicts): a CONTRADICTED result in ANY dimension, required by
125
+ // the profile or not, is a conflict and never a pass. Mirrors the demo,
126
+ // Go DeriveAssuranceVerdict and the TS SDK deriveAssuranceVerdict.
127
+ if (all.includes("CONTRADICTED")) return VERDICTS.CONFLICTING_EVIDENCE;
128
+ if (req.includes("PENDING")) return VERDICTS.PENDING_FINALITY;
129
+ if (req.some((r) => WEAK.has(r) || !SATISFYING.has(r))) return VERDICTS.INSUFFICIENT_EVIDENCE;
130
+ return VERDICTS.VERIFIED_FOR_SCOPE;
131
+ }
132
+
133
+ // The sandbox ceiling: the weaker of the derived verdict and
134
+ // LOCAL_NON_TRUST_BEARING. Applied unconditionally to every local bundle.
135
+ export function applyLocalCeiling(verdict) {
136
+ if (!Object.prototype.hasOwnProperty.call(VERDICT_PRECEDENCE, verdict)) {
137
+ throw new Error("unknown verdict " + verdict);
138
+ }
139
+ return VERDICT_PRECEDENCE[verdict] > VERDICT_PRECEDENCE[LOCAL_VERDICT_CEILING] ? LOCAL_VERDICT_CEILING : verdict;
140
+ }
141
+
142
+ // Limitations every local sandbox bundle carries.
143
+ export const GLOBAL_LIMITATIONS = Object.freeze([
144
+ {
145
+ code: "LOCAL_KEYS_NOT_TRUST_BEARING",
146
+ text: "Every signature was made by an ephemeral key generated on this machine (environment: local, " +
147
+ "trust_bearing: false). Anyone can generate such keys; this is not production assurance.",
148
+ },
149
+ {
150
+ code: "PREVIEW_FORMAT_NOT_PRODUCTION_AEP",
151
+ text: "The bundle uses the preview effect-assurance format (intentrax.effect_evidence/0.1), not the " +
152
+ "production AEP export; production verifiers, hosted verify and the Verification Mark do not accept it.",
153
+ },
154
+ {
155
+ code: "SIGNING_TIME_SELF_ASSERTED",
156
+ text: "Signing times are asserted by each local signer; there is no trusted timestamp authority.",
157
+ },
158
+ {
159
+ code: "COMPLETENESS_NOT_ESTABLISHED",
160
+ text: "Nothing proves every consequential agent action was routed through Intentrax.",
161
+ },
162
+ {
163
+ code: "EXECUTION_NOT_ATTESTED",
164
+ text: "No trusted in-path enforcement component observed the call; execution is self-reported.",
165
+ },
166
+ {
167
+ code: "NO_REVOCATION_OR_BUDGET_IN_SANDBOX",
168
+ text: "The mandate is minted for this run only; the sandbox has no revocation registry and no budget ledger.",
169
+ },
170
+ ]);
@@ -0,0 +1,324 @@
1
+ // Local assurance sandbox: one consequential action, end to end, in-process.
2
+ //
3
+ // local principal ──signs──▶ mandate (agent may SetState on one resource)
4
+ // local decision service ──signs──▶ ALLOW/DENY, made BEFORE execution
5
+ // executor shim ──signs──▶ execution report (SELF_REPORTED)
6
+ // local effect verifier ──own key, read-only──▶ reads the outcome
7
+ // └─ signs intentrax.effect_evidence/0.1 (CONFIRMED / CONTRADICTED / ...)
8
+ // local decision service ──seals──▶ intentrax.local_assurance_bundle/0.1
9
+ // offline verifier (local key set, no network, no clock)
10
+ // └─ 8 dimensions → §5.4 verdict → capped at LOCAL_NON_TRUST_BEARING
11
+ //
12
+ // Flow ported from examples/effect-assurance-demo (decision-service.mjs,
13
+ // executor.mjs, world.mjs, scenarios.mjs; PRs #449, #477), reduced to one
14
+ // root mandate, one action and one read.
15
+ //
16
+ // Hard boundaries (each enforced by a test in ./test):
17
+ // - keys are generated fresh per run; nothing here reads, derives or
18
+ // requests a production or published sandbox key;
19
+ // - no network: no module here imports a network API; the only code that
20
+ // could touch a network is a developer's own --check module;
21
+ // - the sandbox never calls a developer's write path. With --check it only
22
+ // records the claim that the developer's action ran, then calls the
23
+ // developer's read-only check.
24
+
25
+ import { randomBytes } from "node:crypto";
26
+ import { digest } from "./canonical.mjs";
27
+ import { signEnvelope, verifyEnvelope, envelopeDigest, PAYLOAD_TYPES } from "./envelope.mjs";
28
+ import { evaluate, actionDigest } from "./authority.mjs";
29
+ import { OPERATION, claimedOutcome } from "./effects.mjs";
30
+ import { LocalEffectVerifier, READ_KINDS } from "./effect-verifier.mjs";
31
+ import { assembleBundle } from "./bundle.mjs";
32
+ import { generateLocalSigners, localKeySetDocument, localSigningKeysDocument, loadLocalKeySet, LOCAL_PRINCIPALS, ROLES } from "./keys.mjs";
33
+ import { verifyLocalBundle } from "./verifier.mjs";
34
+
35
+ export const SCENARIOS = Object.freeze({
36
+ confirmed: "The executor applies the authorised change; the independent read confirms it.",
37
+ contradicted:
38
+ "Scenario B: the decision is ALLOW and the executor reports SUCCEEDED, but it never wrote; the independent read contradicts it.",
39
+ });
40
+
41
+ export const SAMPLE_ACTION = Object.freeze({
42
+ description: "Approve a 42.00 refund on order SBX-1042 (synthetic, in-memory)",
43
+ resource: "order:SBX-1042",
44
+ initial_state: Object.freeze({ refund_status: "REQUESTED", refund_amount_cents: 0 }),
45
+ authorised_state: Object.freeze({ refund_status: "APPROVED", refund_amount_cents: 4200 }),
46
+ });
47
+
48
+ const AGENT = "agent:local-sandbox-agent";
49
+ const DECISION_TTL_SECONDS = 300;
50
+ const MANDATE_TTL_SECONDS = 3600;
51
+
52
+ function iso(ms) {
53
+ return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
54
+ }
55
+
56
+ function addSeconds(isoString, seconds) {
57
+ return iso(Date.parse(isoString) + seconds * 1000);
58
+ }
59
+
60
+ // Logical clock: starts at the real time of the run (whole seconds) and
61
+ // advances one step per event, so the record order is unambiguous.
62
+ class LogicalClock {
63
+ #ms;
64
+
65
+ constructor(start) {
66
+ this.#ms = Math.floor(start.getTime() / 1000) * 1000;
67
+ if (!Number.isFinite(this.#ms)) throw new Error("sandbox clock: bad start time");
68
+ }
69
+
70
+ now() {
71
+ return iso(this.#ms);
72
+ }
73
+
74
+ advance(seconds = 1) {
75
+ this.#ms += seconds * 1000;
76
+ return this.now();
77
+ }
78
+ }
79
+
80
+ // In-memory stand-in for the system the sample action changes.
81
+ class SyntheticStore {
82
+ #state = new Map();
83
+ writeCalls = 0;
84
+
85
+ seed(resource, state) {
86
+ this.#state.set(resource, structuredClone(state));
87
+ }
88
+
89
+ write(resource, state) {
90
+ this.writeCalls += 1;
91
+ this.#state.set(resource, { ...(this.#state.get(resource) ?? {}), ...structuredClone(state) });
92
+ }
93
+
94
+ read(resource) {
95
+ return structuredClone(this.#state.get(resource) ?? null);
96
+ }
97
+ }
98
+
99
+ export class ExecutorRefusal extends Error {
100
+ constructor(code) {
101
+ super("executor refused: " + code);
102
+ this.code = code;
103
+ }
104
+ }
105
+
106
+ class LocalDecisionService {
107
+ #clock;
108
+ #signer;
109
+ #policy;
110
+ #mandateEnv;
111
+
112
+ constructor({ clock, signer, policy, mandateEnv }) {
113
+ this.#clock = clock;
114
+ this.#signer = signer;
115
+ this.#policy = policy;
116
+ this.#mandateEnv = mandateEnv;
117
+ }
118
+
119
+ decide(request) {
120
+ const now = this.#clock.now();
121
+ const result = evaluate({
122
+ request,
123
+ mandate: this.#mandateEnv.payload,
124
+ policy: this.#policy,
125
+ policyDigest: digest(this.#policy),
126
+ at: now,
127
+ });
128
+ return signEnvelope(PAYLOAD_TYPES.DECISION, {
129
+ schema_version: PAYLOAD_TYPES.DECISION,
130
+ decision_id: "dec-" + digest(request).slice(7, 23),
131
+ request,
132
+ request_digest: digest(request),
133
+ action_digest: actionDigest(request),
134
+ outcome: result.outcome,
135
+ reasons: result.reasons,
136
+ decided_at: now,
137
+ execute_before: result.outcome === "ALLOW" ? addSeconds(now, DECISION_TTL_SECONDS) : null,
138
+ mandate_id: request.mandate_id,
139
+ mandate_chain_digests: [envelopeDigest(this.#mandateEnv)],
140
+ policy_id: this.#policy.policy_id,
141
+ policy_version: this.#policy.version,
142
+ policy_digest: digest(this.#policy),
143
+ required_assurance_profile: result.required_assurance_profile,
144
+ }, this.#signer);
145
+ }
146
+ }
147
+
148
+ // Executor shim. Modes:
149
+ // "apply" writes the authorised state to the synthetic store
150
+ // "drop-write-report-success" never writes, reports SUCCEEDED (scenario B)
151
+ // "record-external-claim" the developer's action ran outside the sandbox;
152
+ // this report records that claim (no call made)
153
+ class LocalExecutor {
154
+ #clock;
155
+ #signer;
156
+ #pinned;
157
+ #store;
158
+ #used = new Set();
159
+
160
+ constructor({ clock, signer, pinned, store, mode }) {
161
+ this.#clock = clock;
162
+ this.#signer = signer;
163
+ this.#pinned = pinned;
164
+ this.#store = store;
165
+ this.mode = mode;
166
+ this.principal = signer.principal;
167
+ }
168
+
169
+ execute(decisionEnv) {
170
+ const v = verifyEnvelope(decisionEnv, { pinned: this.#pinned });
171
+ if (decisionEnv?.payload_type !== PAYLOAD_TYPES.DECISION || v.integrity !== "VERIFIED" || v.authenticity !== "VERIFIED") {
172
+ throw new ExecutorRefusal("DECISION_NOT_AUTHENTIC");
173
+ }
174
+ const d = decisionEnv.payload;
175
+ if (d.outcome !== "ALLOW") throw new ExecutorRefusal("DECISION_DENIED");
176
+ if (Date.parse(this.#clock.now()) >= Date.parse(d.execute_before)) throw new ExecutorRefusal("DECISION_EXPIRED");
177
+ if (this.#used.has(d.decision_id)) throw new ExecutorRefusal("DECISION_REPLAYED");
178
+ this.#used.add(d.decision_id);
179
+
180
+ const startedAt = this.#clock.now();
181
+ let downstream;
182
+ if (this.mode === "apply") {
183
+ this.#store.write(d.request.resource, d.request.params.state);
184
+ downstream = { system: "sandbox-synthetic-store", call: "write", note: null };
185
+ } else if (this.mode === "drop-write-report-success") {
186
+ downstream = { system: "sandbox-synthetic-store", call: "write", note: null };
187
+ } else if (this.mode === "record-external-claim") {
188
+ downstream = {
189
+ system: "developer-system",
190
+ call: null,
191
+ note: "The action ran outside the sandbox. This report records the claim that it succeeded; the sandbox made no call.",
192
+ };
193
+ } else {
194
+ throw new Error("unknown executor mode " + this.mode);
195
+ }
196
+ this.#clock.advance();
197
+ return signEnvelope(PAYLOAD_TYPES.EXECUTION_REPORT, {
198
+ schema_version: PAYLOAD_TYPES.EXECUTION_REPORT,
199
+ report_id: "rpt-" + d.decision_id.slice(4) + "-1",
200
+ sequence: 1,
201
+ decision_id: d.decision_id,
202
+ decision_digest: envelopeDigest(decisionEnv),
203
+ action_digest: d.action_digest,
204
+ executor_principal: this.principal,
205
+ started_at: startedAt,
206
+ reported_at: this.#clock.now(),
207
+ status: "SUCCEEDED",
208
+ claimed_outcome: claimedOutcome("SUCCEEDED"),
209
+ downstream,
210
+ }, this.#signer);
211
+ }
212
+ }
213
+
214
+ // userCheck: null for the built-in sample, or
215
+ // { read: async (probe) => observedState, expected: {...}, resource: string,
216
+ // checkModule: { file_name, sha256 }, timeoutMs }
217
+ export async function runSandbox({ scenario = "confirmed", userCheck = null, now = new Date() } = {}) {
218
+ if (userCheck && scenario !== "confirmed") {
219
+ throw new Error("--scenario applies to the built-in sample only; it cannot be combined with --check");
220
+ }
221
+ if (!Object.prototype.hasOwnProperty.call(SCENARIOS, scenario)) {
222
+ throw new Error("unknown scenario " + scenario + " (expected: " + Object.keys(SCENARIOS).join(", ") + ")");
223
+ }
224
+ const clock = new LogicalClock(now);
225
+ const runId = randomBytes(8).toString("hex");
226
+ const startedAt = clock.now();
227
+ const signers = generateLocalSigners({ now: startedAt });
228
+ const keySet = localKeySetDocument(signers);
229
+ const pinned = loadLocalKeySet(keySet);
230
+
231
+ const resource = userCheck ? userCheck.resource : SAMPLE_ACTION.resource;
232
+ const state = userCheck ? userCheck.expected : { ...SAMPLE_ACTION.authorised_state };
233
+ const policy = {
234
+ schema_version: "intentrax.policy/0.1",
235
+ policy_id: "local-sandbox-policy",
236
+ version: 1,
237
+ default: "DENY",
238
+ rules: [{ operation: OPERATION, required_profile: "EFFECT_CONFIRMED" }],
239
+ };
240
+ const mandateEnv = signEnvelope(PAYLOAD_TYPES.MANDATE, {
241
+ schema_version: PAYLOAD_TYPES.MANDATE,
242
+ mandate_id: "mnd-local-" + runId,
243
+ issuer: LOCAL_PRINCIPALS.PRINCIPAL,
244
+ subject: AGENT,
245
+ parent_mandate_id: null,
246
+ policy_digest: digest(policy),
247
+ scope: { operations: [OPERATION], resources: [resource] },
248
+ not_before: startedAt,
249
+ expires_at: addSeconds(startedAt, MANDATE_TTL_SECONDS),
250
+ issued_at: startedAt,
251
+ purpose: userCheck ? "Local sandbox: check the outcome of the developer's own action" : "Local sandbox sample action",
252
+ }, signers[ROLES.PRINCIPAL]);
253
+
254
+ const store = new SyntheticStore();
255
+ if (!userCheck) store.seed(SAMPLE_ACTION.resource, SAMPLE_ACTION.initial_state);
256
+
257
+ clock.advance();
258
+ const request = {
259
+ request_id: "req-local-" + runId,
260
+ agent: AGENT,
261
+ mandate_id: mandateEnv.payload.mandate_id,
262
+ operation: OPERATION,
263
+ resource,
264
+ params: { state },
265
+ requested_at: clock.now(),
266
+ };
267
+ const decisionService = new LocalDecisionService({ clock, signer: signers[ROLES.DECISION_SERVICE], policy, mandateEnv });
268
+ const decisionEnv = decisionService.decide(request);
269
+
270
+ clock.advance();
271
+ const executor = new LocalExecutor({
272
+ clock,
273
+ signer: signers[ROLES.EXECUTOR],
274
+ pinned,
275
+ store,
276
+ mode: userCheck ? "record-external-claim" : scenario === "contradicted" ? "drop-write-report-success" : "apply",
277
+ });
278
+ const reportEnv = executor.execute(decisionEnv);
279
+
280
+ clock.advance();
281
+ const effectVerifier = new LocalEffectVerifier({ clock, signer: signers[ROLES.EFFECT_VERIFIER] });
282
+ const reader = userCheck
283
+ ? { kind: READ_KINDS.USER_SUPPLIED_CHECK, read: userCheck.read, checkModule: userCheck.checkModule, timeoutMs: userCheck.timeoutMs }
284
+ : { kind: READ_KINDS.SANDBOX_SYNTHETIC_STORE, read: (probe) => store.read(probe.resource), checkModule: null };
285
+ const { evidence, observation } = await effectVerifier.observe({ decisionEnv, reportEnv, reader });
286
+
287
+ clock.advance();
288
+ const bundle = assembleBundle({
289
+ bundleId: "bnd-local-" + runId,
290
+ policy,
291
+ mandates: [mandateEnv],
292
+ decision: decisionEnv,
293
+ executionReports: [reportEnv],
294
+ effectEvidence: [evidence],
295
+ sourceObservations: [observation],
296
+ sealSigner: signers[ROLES.DECISION_SERVICE],
297
+ sealedAt: clock.now(),
298
+ });
299
+
300
+ // Verify from the serialised bytes, exactly as a third party would.
301
+ const report = verifyLocalBundle(JSON.parse(JSON.stringify(bundle)), { pinned: loadLocalKeySet(JSON.parse(JSON.stringify(keySet))) });
302
+
303
+ return {
304
+ run_id: runId,
305
+ scenario: userCheck ? "user-check" : scenario,
306
+ action: userCheck
307
+ ? { description: "Your action (performed outside the sandbox)", resource, authorised_state: state }
308
+ : { description: SAMPLE_ACTION.description, resource, authorised_state: state },
309
+ facts: {
310
+ decision_outcome: decisionEnv.payload.outcome,
311
+ executor_report_status: reportEnv.payload.status,
312
+ synthetic_store_writes: userCheck ? null : store.writeCalls,
313
+ observed_state: observation.body ? observation.body.state : null,
314
+ read_status: observation.status,
315
+ read_error: observation.error,
316
+ read_kind: observation.read_kind,
317
+ },
318
+ keys: Object.fromEntries(Object.entries(signers).map(([role, s]) => [role, s.key_id])),
319
+ bundle,
320
+ keySet,
321
+ signingKeys: localSigningKeysDocument(signers, startedAt),
322
+ report,
323
+ };
324
+ }
@@ -0,0 +1,18 @@
1
+ // Strict timestamps for the local assurance sandbox verifier.
2
+ //
3
+ // Ported from examples/effect-assurance-demo/src/clock.mjs (#491).
4
+ // RFC 3339 date-time with an EXPLICIT offset (`Z` or `±hh:mm`). Date.parse()
5
+ // alone would accept a timezone-less value in the verifier's local timezone,
6
+ // making a result depend on the machine that verifies, and returns NaN for
7
+ // garbage, which compares false and can silently pass a time check. Everything
8
+ // that verifies a timestamp uses this and treats null as a failure. The
9
+ // sandbox's own producers only ever emit `Z` times.
10
+
11
+ export const RFC3339_WITH_OFFSET = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$/;
12
+
13
+ // Epoch ms, or null unless `v` is an RFC 3339 string with an explicit offset.
14
+ export function isoMs(v) {
15
+ if (typeof v !== "string" || !RFC3339_WITH_OFFSET.test(v)) return null;
16
+ const ms = Date.parse(v);
17
+ return Number.isFinite(ms) ? ms : null;
18
+ }