@intentrax/sdk 1.3.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,376 @@
1
+ #!/usr/bin/env node
2
+ // `intentrax sandbox`: the local assurance sandbox CLI.
3
+ //
4
+ // intentrax sandbox [--scenario confirmed|contradicted] [--dir <project>] [--json]
5
+ // intentrax sandbox --check ./my-check.mjs [--check-timeout-ms 30000] [--dir <project>] [--json]
6
+ // intentrax sandbox verify <bundle.json> [--keys <local-key-set.json>] [--json]
7
+ // [--issuer-keys <pinned-external-issuers.json>] [--require-external-issuer <issuer>]...
8
+ //
9
+ // Everything runs in-process with ephemeral local keys. Output files go to
10
+ // <project>/.intentrax/local/, which is gitignored. Nothing is sent anywhere.
11
+ //
12
+ // `intentrax sandbox ...` (cli/intentrax.mjs) dispatches here; from a repository
13
+ // checkout, `node sdk/typescript/sandbox/cli.mjs [args]` runs the same thing.
14
+
15
+ import { readFileSync, writeFileSync, mkdirSync, realpathSync } from "node:fs";
16
+ import { basename, join, relative, resolve, isAbsolute } from "node:path";
17
+ import { fileURLToPath, pathToFileURL } from "node:url";
18
+ import { sha256Hex, isCanonicalizable } from "./canonical.mjs";
19
+ import { runSandbox, SCENARIOS, SAMPLE_ACTION } from "./run.mjs";
20
+ import { verifyLocalBundle } from "./verifier.mjs";
21
+ import { loadLocalKeySet, LocalKeySetError } from "./keys.mjs";
22
+ import { loadPinnedIssuerKeySet, IssuerKeySetError } from "./external-decision.mjs";
23
+ import { describeCheck, runCheckWorker } from "./check-runner.mjs";
24
+ import { VERDICTS } from "./model.mjs";
25
+
26
+ export const LOCAL_DIR = join(".intentrax", "local");
27
+
28
+ export const BANNER = Object.freeze([
29
+ "==============================================================================",
30
+ " INTENTRAX LOCAL SANDBOX: NOT PRODUCTION ASSURANCE",
31
+ " Signed with ephemeral keys generated on this machine",
32
+ " (environment: local, trust_bearing: false). No production or published key",
33
+ " was read or used, and nothing was sent over the network. Production",
34
+ " verifiers, hosted verify and the Verification Mark reject local bundles.",
35
+ "==============================================================================",
36
+ ]);
37
+
38
+ export const EXIT_CODES = Object.freeze({
39
+ [VERDICTS.LOCAL_NON_TRUST_BEARING]: 0,
40
+ [VERDICTS.PENDING_FINALITY]: 10,
41
+ [VERDICTS.INSUFFICIENT_EVIDENCE]: 11,
42
+ [VERDICTS.CONFLICTING_EVIDENCE]: 12,
43
+ [VERDICTS.INTEGRITY_ONLY]: 13,
44
+ [VERDICTS.VERIFICATION_FAILED]: 14,
45
+ });
46
+ export const USAGE_EXIT_CODE = 64;
47
+ // Loading a --check module (in its worker) is bounded separately from the
48
+ // read itself, which --check-timeout-ms bounds.
49
+ const CHECK_LOAD_TIMEOUT_MS = 15000;
50
+
51
+ class UsageError extends Error {}
52
+
53
+ function exitCodeFor(verdict) {
54
+ if (!Object.prototype.hasOwnProperty.call(EXIT_CODES, verdict)) {
55
+ // VERIFIED_FOR_SCOPE is unreachable here by construction; refuse loudly.
56
+ throw new Error("sandbox verifier produced a verdict above its ceiling: " + verdict);
57
+ }
58
+ return EXIT_CODES[verdict];
59
+ }
60
+
61
+ function parseArgs(args) {
62
+ const opts = {
63
+ scenario: null, check: null, checkTimeoutMs: 30000, dir: null, json: false, keys: null, help: false, positional: [],
64
+ issuerKeys: null, requireExternalIssuer: [],
65
+ };
66
+ for (let i = 0; i < args.length; i += 1) {
67
+ const a = args[i];
68
+ const value = () => {
69
+ const v = args[i + 1];
70
+ if (v === undefined || v.startsWith("--")) throw new UsageError(a + " requires a value");
71
+ i += 1;
72
+ return v;
73
+ };
74
+ if (a === "--help" || a === "-h") opts.help = true;
75
+ else if (a === "--json") opts.json = true;
76
+ else if (a === "--scenario") opts.scenario = value();
77
+ else if (a === "--check") opts.check = value();
78
+ else if (a === "--check-timeout-ms") {
79
+ const n = Number(value());
80
+ if (!Number.isSafeInteger(n) || n < 1 || n > 600000) throw new UsageError("--check-timeout-ms must be an integer from 1 to 600000");
81
+ opts.checkTimeoutMs = n;
82
+ } else if (a === "--dir") opts.dir = value();
83
+ else if (a === "--keys") opts.keys = value();
84
+ else if (a === "--issuer-keys") opts.issuerKeys = value();
85
+ else if (a === "--require-external-issuer") opts.requireExternalIssuer.push(value());
86
+ else if (a.startsWith("--")) throw new UsageError("unknown option " + a);
87
+ else opts.positional.push(a);
88
+ }
89
+ return opts;
90
+ }
91
+
92
+ // Load a developer's read-only check module.
93
+ // export const expected = { status: "closed" }; // required: the state your action should produce
94
+ // export const resource = "ticket:1234"; // optional label for what is checked
95
+ // export default async function check({ resource, fields }) { return { status: ... }; }
96
+ export async function loadUserCheck(path, { cwd, timeoutMs }) {
97
+ const abs = isAbsolute(path) ? path : resolve(cwd, path);
98
+ let source;
99
+ try {
100
+ source = readFileSync(abs);
101
+ } catch {
102
+ throw new UsageError("--check: cannot read " + path);
103
+ }
104
+ // The module is loaded and run only inside a worker thread (check-runner.mjs).
105
+ const href = pathToFileURL(abs).href;
106
+ let mod;
107
+ try {
108
+ mod = await describeCheck(href, CHECK_LOAD_TIMEOUT_MS);
109
+ } catch (err) {
110
+ throw new UsageError("--check: cannot load " + path + ": " + (err && err.message ? err.message : err));
111
+ }
112
+ if (!mod.has_check) throw new UsageError("--check: module must export a default async function (or `check`) returning the observed state");
113
+ const read = (probe, { signal } = {}) => runCheckWorker({ href, mode: "read", probe, signal });
114
+ const expected = mod.expected;
115
+ if (expected === null || typeof expected !== "object" || Array.isArray(expected) || Object.keys(expected).length === 0
116
+ || !isCanonicalizable(expected)) {
117
+ throw new UsageError("--check: module must export `expected`, a non-empty plain object of JSON values (integers only) " +
118
+ "describing the state your action should produce");
119
+ }
120
+ const resource = mod.resource === null ? "user:" + basename(abs) : mod.resource;
121
+ if (typeof resource !== "string" || resource.length === 0 || resource.length > 200 || resource.endsWith("*")) {
122
+ throw new UsageError("--check: `resource` must be a non-empty string (max 200 chars, no trailing *)");
123
+ }
124
+ return {
125
+ read,
126
+ expected: JSON.parse(JSON.stringify(expected)),
127
+ resource,
128
+ checkModule: { file_name: basename(abs), sha256: sha256Hex(source) },
129
+ timeoutMs,
130
+ };
131
+ }
132
+
133
+ function writeJson(path, value, mode = 0o644) {
134
+ writeFileSync(path, JSON.stringify(value, null, 2) + "\n", { mode });
135
+ }
136
+
137
+ // Everything goes under <project>/.intentrax/local/, which ignores itself.
138
+ export function writeRunArtifacts(projectDir, result) {
139
+ const localDir = join(projectDir, LOCAL_DIR);
140
+ const runDir = join(localDir, "runs", result.bundle.bundle_id);
141
+ mkdirSync(runDir, { recursive: true });
142
+ writeFileSync(join(localDir, ".gitignore"), "# Intentrax local sandbox: ephemeral keys and local-only bundles. Never commit.\n*\n");
143
+ writeJson(join(localDir, "sandbox-signing-keys.json"), result.signingKeys, 0o600);
144
+ const paths = {
145
+ local_dir: localDir,
146
+ signing_keys: join(localDir, "sandbox-signing-keys.json"),
147
+ bundle: join(runDir, "bundle.json"),
148
+ key_set: join(runDir, "local-key-set.json"),
149
+ report: join(runDir, "verification-report.json"),
150
+ };
151
+ writeJson(paths.bundle, result.bundle);
152
+ writeJson(paths.key_set, result.keySet);
153
+ writeJson(paths.report, result.report);
154
+ return paths;
155
+ }
156
+
157
+ function pad(s, n) {
158
+ return (s + " ".repeat(n)).slice(0, Math.max(n, s.length));
159
+ }
160
+
161
+ function renderAssessments(report, out) {
162
+ for (const a of report.assessments) {
163
+ const prov = a.provenance ? " [" + a.provenance + "]" : "";
164
+ const why = a.reasons.length ? " " + a.reasons.slice(0, 3).join(", ") : "";
165
+ out(" " + pad(a.dimension, 22) + " " + pad(a.result, 22) + prov + why);
166
+ }
167
+ }
168
+
169
+ function renderVerdict(report, out) {
170
+ out("");
171
+ out("Verdict: " + report.verdict + " (profile " + report.assurance_profile + ")");
172
+ if (report.verdict !== report.uncapped_verdict) {
173
+ out(" Uncapped verdict " + report.uncapped_verdict + ", capped at " + report.verdict_ceiling +
174
+ " because every signer is a local, non-trust-bearing key.");
175
+ }
176
+ const result = (dim) => report.assessments.find((a) => a.dimension === dim)?.result;
177
+ if (report.verdict === VERDICTS.CONFLICTING_EVIDENCE && result("EFFECT_CONFIRMED") === "CONTRADICTED") {
178
+ out(" The signed decision said ALLOW and the executor reported success, but the independent read");
179
+ out(" disagrees with the authorised effect. A decision record alone would not have shown this.");
180
+ }
181
+ if (report.verdict === VERDICTS.CONFLICTING_EVIDENCE && result("EXTERNAL_AUTHORIZATION") === "CONTRADICTED") {
182
+ out(" A genuinely signed, bound external authorization decision DENIED this action while the local");
183
+ out(" decision said ALLOW. The external decision is evidence, not trust; the conflict is reported as such.");
184
+ }
185
+ out("");
186
+ out("Limitations:");
187
+ for (const l of report.limitations) out(" - " + l.code + ": " + l.text);
188
+ }
189
+
190
+ function rel(cwd, p) {
191
+ const r = relative(cwd, p);
192
+ return r && !r.startsWith("..") && !isAbsolute(r) ? r : p;
193
+ }
194
+
195
+ function usage(invokedAs) {
196
+ return [
197
+ "Usage:",
198
+ " " + invokedAs + " [--scenario confirmed|contradicted] [--dir <project>] [--json]",
199
+ " " + invokedAs + " --check ./my-check.mjs [--check-timeout-ms 30000] [--dir <project>] [--json]",
200
+ " " + invokedAs + " verify <bundle.json> [--keys <local-key-set.json>] [--json]",
201
+ " [--issuer-keys <pinned-external-issuers.json>] [--require-external-issuer <issuer>]...",
202
+ "",
203
+ "Scenarios (built-in sample action, " + SAMPLE_ACTION.description + "):",
204
+ ...Object.entries(SCENARIOS).map(([k, v]) => " " + pad(k, 13) + v),
205
+ "",
206
+ "--check runs YOUR read-only check after your action: export `expected` (the state the action",
207
+ "should produce) and a default async function returning the observed state. The sandbox never",
208
+ "calls your write path. A check you wrote is labelled SELF_REPORTED, not an authoritative read.",
209
+ "",
210
+ "verify --issuer-keys assesses third-party signed authorization decisions a bundle carries",
211
+ "(EXTERNAL_AUTHORIZATION, THIRD_PARTY_ATTESTED) against an issuer key set YOU pinned; nothing is",
212
+ "fetched. --require-external-issuer makes that issuer's decision required. Evidence, never trust.",
213
+ "",
214
+ "Exit codes: 0 LOCAL_NON_TRUST_BEARING · 10 PENDING_FINALITY · 11 INSUFFICIENT_EVIDENCE ·",
215
+ "12 CONFLICTING_EVIDENCE · 13 INTEGRITY_ONLY · 14 VERIFICATION_FAILED · 64 usage",
216
+ ].join("\n");
217
+ }
218
+
219
+ async function runCommand(opts, { out, cwd, now, invokedAs }) {
220
+ if (opts.positional.length) throw new UsageError("unexpected argument " + opts.positional[0]);
221
+ if (opts.keys) throw new UsageError("--keys applies to `verify` only");
222
+ if (opts.issuerKeys || opts.requireExternalIssuer.length) {
223
+ throw new UsageError("--issuer-keys and --require-external-issuer apply to `verify` only");
224
+ }
225
+ if (opts.check && opts.scenario) throw new UsageError("--scenario applies to the built-in sample only; it cannot be combined with --check");
226
+ const scenario = opts.scenario ?? "confirmed";
227
+ if (!Object.prototype.hasOwnProperty.call(SCENARIOS, scenario)) {
228
+ throw new UsageError("unknown --scenario " + scenario + " (expected: " + Object.keys(SCENARIOS).join(", ") + ")");
229
+ }
230
+ const userCheck = opts.check ? await loadUserCheck(opts.check, { cwd, timeoutMs: opts.checkTimeoutMs }) : null;
231
+ const result = await runSandbox({ scenario, userCheck, now: now ?? new Date() });
232
+ const projectDir = opts.dir ? resolve(cwd, opts.dir) : cwd;
233
+ const paths = writeRunArtifacts(projectDir, result);
234
+ const report = result.report;
235
+ const reverify = invokedAs + " verify " + rel(cwd, paths.bundle) + " --keys " + rel(cwd, paths.key_set);
236
+
237
+ if (opts.json) {
238
+ out(JSON.stringify({
239
+ banner: BANNER.filter((l) => !l.startsWith("=")).map((l) => l.trim()).join(" "),
240
+ environment: "local",
241
+ trust_bearing: false,
242
+ production_assurance: false,
243
+ run_id: result.run_id,
244
+ scenario: result.scenario,
245
+ action: result.action,
246
+ facts: result.facts,
247
+ keys: result.keys,
248
+ files: Object.fromEntries(Object.entries(paths).map(([k, v]) => [k, rel(cwd, v)])),
249
+ reverify,
250
+ report,
251
+ }, null, 2));
252
+ return exitCodeFor(report.verdict);
253
+ }
254
+
255
+ const f = result.facts;
256
+ const effect = report.assessments.find((a) => a.dimension === "EFFECT_CONFIRMED");
257
+ const observed = report.assessments.find((a) => a.dimension === "EFFECT_OBSERVED");
258
+ BANNER.forEach((l) => out(l));
259
+ out("");
260
+ out("Scenario: " + result.scenario + (result.scenario === "user-check" ? "" : " (" + SCENARIOS[result.scenario] + ")"));
261
+ out("Action: " + result.action.description);
262
+ out(" SetState " + result.action.resource + " -> " + JSON.stringify(result.action.authorised_state));
263
+ out("");
264
+ out(" 1. Decision " + f.decision_outcome + ", signed before execution by " + result.keys.DECISION_SERVICE);
265
+ out(" 2. Executor report " + f.executor_report_status + " (self-reported by " + result.keys.EXECUTOR + ")" +
266
+ (f.synthetic_store_writes === null ? "; the sandbox did not call your system" : "; writes reaching the store: " + f.synthetic_store_writes));
267
+ out(" 3. Independent read " + (f.read_status === "OK" ? JSON.stringify(f.observed_state) : f.read_status + (f.read_error ? " (" + f.read_error + ")" : "")));
268
+ out(" read by " + result.keys.EFFECT_VERIFIER + " via " +
269
+ (f.read_kind === "USER_SUPPLIED_CHECK" ? "your check module (provenance SELF_REPORTED: you wrote the check)"
270
+ : "the sandbox's synthetic store (provenance THIRD_PARTY_ATTESTED by the local effect-verifier key)"));
271
+ out(" EFFECT_CONFIRMED = " + effect.result + " EFFECT_OBSERVED = " + observed.result);
272
+ out(" 4. Sealed bundle " + rel(cwd, paths.bundle));
273
+ out(" 5. Offline verify 8 dimensions, local key set " + rel(cwd, paths.key_set));
274
+ renderAssessments(report, out);
275
+ renderVerdict(report, out);
276
+ out("");
277
+ out("Re-verify offline: " + reverify);
278
+ out("Ephemeral private keys: " + rel(cwd, paths.signing_keys) + " (gitignored; not trust-bearing)");
279
+ return exitCodeFor(report.verdict);
280
+ }
281
+
282
+ function verifyCommand(opts, { out, cwd }) {
283
+ const [bundlePath, ...extra] = opts.positional;
284
+ if (!bundlePath || extra.length) throw new UsageError("verify requires exactly one bundle path");
285
+ if (opts.check || opts.scenario || opts.dir) {
286
+ throw new UsageError("verify takes only <bundle.json>, --keys, --issuer-keys, --require-external-issuer and --json");
287
+ }
288
+ let bundle;
289
+ try {
290
+ bundle = JSON.parse(readFileSync(resolve(cwd, bundlePath), "utf8"));
291
+ } catch {
292
+ throw new UsageError("cannot read bundle JSON from " + bundlePath);
293
+ }
294
+ let pinned = null;
295
+ if (opts.keys) {
296
+ let doc;
297
+ try {
298
+ doc = JSON.parse(readFileSync(resolve(cwd, opts.keys), "utf8"));
299
+ } catch {
300
+ throw new UsageError("cannot read key set JSON from " + opts.keys);
301
+ }
302
+ try {
303
+ pinned = loadLocalKeySet(doc);
304
+ } catch (err) {
305
+ if (err instanceof LocalKeySetError) throw new UsageError("--keys: " + err.message);
306
+ throw err;
307
+ }
308
+ }
309
+ let issuerKeys = null;
310
+ if (opts.issuerKeys) {
311
+ let doc;
312
+ try {
313
+ doc = JSON.parse(readFileSync(resolve(cwd, opts.issuerKeys), "utf8"));
314
+ } catch {
315
+ throw new UsageError("cannot read issuer key set JSON from " + opts.issuerKeys);
316
+ }
317
+ try {
318
+ issuerKeys = loadPinnedIssuerKeySet(doc);
319
+ } catch (err) {
320
+ if (err instanceof IssuerKeySetError) throw new UsageError("--issuer-keys: " + err.message);
321
+ throw err;
322
+ }
323
+ }
324
+ const report = verifyLocalBundle(bundle, { pinned, issuerKeys, externalAuthorizationIssuers: opts.requireExternalIssuer });
325
+ if (opts.json) {
326
+ out(JSON.stringify(report, null, 2));
327
+ return exitCodeFor(report.verdict);
328
+ }
329
+ BANNER.forEach((l) => out(l));
330
+ out("");
331
+ out("Bundle: " + bundlePath + (pinned ? "" : " (no --keys: signer authenticity cannot be assessed)"));
332
+ renderAssessments(report, out);
333
+ renderVerdict(report, out);
334
+ return exitCodeFor(report.verdict);
335
+ }
336
+
337
+ export async function sandboxMain(argv, {
338
+ stdout = process.stdout,
339
+ stderr = process.stderr,
340
+ cwd = process.cwd(),
341
+ now = null,
342
+ invokedAs = "intentrax sandbox",
343
+ } = {}) {
344
+ const out = (line) => stdout.write(line + "\n");
345
+ const err = (line) => stderr.write(line + "\n");
346
+ try {
347
+ const isVerify = argv[0] === "verify";
348
+ const opts = parseArgs(isVerify ? argv.slice(1) : argv);
349
+ if (opts.help) {
350
+ out(usage(invokedAs));
351
+ return 0;
352
+ }
353
+ return isVerify ? verifyCommand(opts, { out, cwd }) : await runCommand(opts, { out, cwd, now, invokedAs });
354
+ } catch (e) {
355
+ if (e instanceof UsageError || (e && /--scenario|unknown scenario/.test(e.message))) {
356
+ err("intentrax sandbox: " + e.message);
357
+ err(usage(invokedAs));
358
+ return USAGE_EXIT_CODE;
359
+ }
360
+ throw e;
361
+ }
362
+ }
363
+
364
+ function invokedDirectly() {
365
+ if (!process.argv[1]) return false;
366
+ try {
367
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
368
+ } catch {
369
+ return false;
370
+ }
371
+ }
372
+
373
+ if (invokedDirectly()) {
374
+ const self = rel(process.cwd(), fileURLToPath(import.meta.url));
375
+ process.exitCode = await sandboxMain(process.argv.slice(2), { invokedAs: "node " + JSON.stringify(self) });
376
+ }
@@ -0,0 +1,242 @@
1
+ // Local effect verifier: the sandbox's independent, read-only outcome check.
2
+ //
3
+ // Adapted from examples/effect-assurance-demo/src/effect-verifier.mjs (PRs
4
+ // #449, #477). As in the demo, the check reads the system with its OWN key and
5
+ // principal (never the executor's), compares the observed state with the
6
+ // state the signed decision authorised, and signs an
7
+ // `intentrax.effect_evidence/0.1` object. `assessEffect` is a pure function
8
+ // shared with the offline verifier, which recomputes every conclusion from the
9
+ // bundled observation and refuses evidence whose signed fields disagree.
10
+ //
11
+ // What differs from the demo, and is labelled in every bundle:
12
+ // - There is no source-signed receipt or authenticated channel. The read is
13
+ // either the sandbox's synthetic store (source_authentication
14
+ // LOCAL_EFFECT_VERIFIER_READ, provenance THIRD_PARTY_ATTESTED: attested by
15
+ // the local effect-verifier key, distinct from the executor key) or a
16
+ // check module the developer wrote (USER_SUPPLIED_CHECK, provenance
17
+ // SELF_REPORTED: the party whose action is checked also wrote the check).
18
+ // Neither is an Intentrax-pulled authoritative read.
19
+ // - The sandbox never calls a developer's write path. A user check is
20
+ // read-only by contract only; the sandbox cannot enforce that.
21
+
22
+ import { digest, canonicalJson, isCanonicalizable } from "./canonical.mjs";
23
+ import { signEnvelope, envelopeDigest, PAYLOAD_TYPES } from "./envelope.mjs";
24
+ import { effectFor, claimedOutcome, expectedStateDigest, OUTCOMES } from "./effects.mjs";
25
+ import { isoMs } from "./time.mjs";
26
+
27
+ export const RETRIEVAL_METHOD = "LOCAL_SANDBOX_PULL";
28
+
29
+ export const READ_KINDS = Object.freeze({
30
+ SANDBOX_SYNTHETIC_STORE: "SANDBOX_SYNTHETIC_STORE",
31
+ USER_SUPPLIED_CHECK: "USER_SUPPLIED_CHECK",
32
+ });
33
+
34
+ const SOURCE_AUTHENTICATION = Object.freeze({
35
+ SANDBOX_SYNTHETIC_STORE: "LOCAL_EFFECT_VERIFIER_READ",
36
+ USER_SUPPLIED_CHECK: "USER_SUPPLIED_CHECK",
37
+ });
38
+
39
+ const READ_LIMITATIONS = Object.freeze({
40
+ SANDBOX_SYNTHETIC_STORE: ["SOURCE_RESPONSE_NOT_THIRD_PARTY_SIGNED", "SYNTHETIC_SOURCE"],
41
+ USER_SUPPLIED_CHECK: ["USER_SUPPLIED_CHECK_NOT_INDEPENDENT", "USER_CHECK_READ_ONLY_BY_CONTRACT_ONLY"],
42
+ });
43
+
44
+ export function sourceAuthenticationFor(readKind) {
45
+ return Object.prototype.hasOwnProperty.call(SOURCE_AUTHENTICATION, readKind) ? SOURCE_AUTHENTICATION[readKind] : "NONE";
46
+ }
47
+
48
+
49
+ export function assessEffect({
50
+ request,
51
+ report,
52
+ retrievalMethod,
53
+ retrievalPrincipal,
54
+ expectedRetrievalPrincipal = null,
55
+ observation,
56
+ observedAt,
57
+ }) {
58
+ const eff = effectFor(request.operation);
59
+ const outcome = claimedOutcome(report.status);
60
+ const reasons = [];
61
+ const limitations = [];
62
+ let expected = null;
63
+ try {
64
+ expected = outcome && outcome !== OUTCOMES.PENDING ? expectedStateDigest(request, outcome) : null;
65
+ } catch {
66
+ expected = null;
67
+ }
68
+ const out = {
69
+ claimed_outcome: outcome,
70
+ expected_state_digest: expected,
71
+ observed_state_digest: null,
72
+ evidence_digest: null,
73
+ source_authentication: "NONE",
74
+ finality: "UNKNOWN",
75
+ max_age_seconds: eff.max_age_seconds,
76
+ };
77
+
78
+ if (retrievalMethod !== RETRIEVAL_METHOD) reasons.push("READ_NOT_PERFORMED_BY_SANDBOX_EFFECT_VERIFIER");
79
+ if (retrievalPrincipal === report.executor_principal) reasons.push("RETRIEVAL_NOT_INDEPENDENT_OF_EXECUTOR");
80
+ if (expectedRetrievalPrincipal !== null && retrievalPrincipal !== expectedRetrievalPrincipal) {
81
+ reasons.push("RETRIEVAL_PRINCIPAL_IS_NOT_THE_EFFECT_VERIFIER");
82
+ }
83
+
84
+ if (!observation) {
85
+ reasons.push("OBSERVATION_MISSING");
86
+ } else {
87
+ out.evidence_digest = isCanonicalizable(observation.body) ? digest(observation.body) : null;
88
+ if (canonicalJson(observation.request) !== canonicalJson(eff.probe(request))) {
89
+ reasons.push("PROBE_DOES_NOT_TARGET_CLAIMED_EFFECT");
90
+ }
91
+ out.source_authentication = sourceAuthenticationFor(observation.read_kind);
92
+ if (out.source_authentication === "NONE") reasons.push("READ_KIND_UNKNOWN");
93
+ else limitations.push(...READ_LIMITATIONS[observation.read_kind]);
94
+ if (observation.status !== "OK") reasons.push("SOURCE_READ_FAILED:" + observation.status);
95
+ const bound = observation.status === "OK" && eff.bound(request, observation.body);
96
+ if (observation.status === "OK" && !bound) reasons.push("OBSERVATION_NOT_BOUND_TO_DECISION");
97
+ if (bound) {
98
+ const problems = eff.observationProblems(request, observation.body);
99
+ if (problems.length) {
100
+ reasons.push(...problems);
101
+ } else {
102
+ out.observed_state_digest = digest(eff.observed(request, observation.body));
103
+ out.finality = eff.finality(observation.body);
104
+ }
105
+ }
106
+ }
107
+
108
+ // Strict timestamps (explicit offset; #491 parity): a timezone-less or
109
+ // unparseable time fails closed.
110
+ const reportedMs = isoMs(report.reported_at);
111
+ const observedMs = isoMs(observedAt);
112
+ const age = reportedMs === null || observedMs === null ? null : (observedMs - reportedMs) / 1000;
113
+ if (age === null) reasons.push("OBSERVATION_TIME_INVALID");
114
+ else if (age < 0) reasons.push("OBSERVATION_PREDATES_EXECUTION_REPORT");
115
+ else if (age > eff.max_age_seconds) reasons.push("OBSERVATION_STALE");
116
+
117
+ out.observed_result = reasons.length ? "INSUFFICIENT_EVIDENCE" : "OBSERVED";
118
+ if (reasons.length) {
119
+ out.result = "INSUFFICIENT_EVIDENCE";
120
+ } else if (outcome === null) {
121
+ reasons.push("REPORT_STATUS_UNRECOGNISED");
122
+ out.result = "INSUFFICIENT_EVIDENCE";
123
+ } else if (outcome === OUTCOMES.PENDING || out.finality !== "FINAL") {
124
+ out.result = "PENDING";
125
+ } else if (expected === null) {
126
+ reasons.push("EXPECTATION_NOT_DERIVABLE_FROM_DECISION");
127
+ out.result = "INSUFFICIENT_EVIDENCE";
128
+ } else {
129
+ out.result = expected === out.observed_state_digest ? "CONFIRMED" : "CONTRADICTED";
130
+ }
131
+ if (out.result === "CONTRADICTED") reasons.push("OBSERVED_STATE_DIFFERS_FROM_AUTHORISED_EFFECT");
132
+ if (out.result === "PENDING") reasons.push(outcome === OUTCOMES.PENDING ? "EXECUTION_NOT_FINAL" : "SOURCE_STATE_NOT_FINAL");
133
+ if (out.result === "CONFIRMED") limitations.push("EFFECT_NOT_ATTRIBUTED_TO_THIS_EXECUTION");
134
+ out.reasons = reasons;
135
+ out.limitations = limitations;
136
+ return out;
137
+ }
138
+
139
+ // Run a read with a timeout. Never throws: failures become an observation
140
+ // status, so a broken check yields INSUFFICIENT_EVIDENCE, not CONFIRMED.
141
+ // On timeout the read's AbortSignal fires; a user check (run in a worker
142
+ // thread, see check-runner.mjs) is then terminated, so its outstanding
143
+ // sockets or timers cannot keep the CLI alive.
144
+ async function performRead(read, probe, timeoutMs) {
145
+ const controller = new AbortController();
146
+ let timer;
147
+ try {
148
+ const value = await Promise.race([
149
+ // A copy, so a check that mutates its argument cannot alter the recorded probe.
150
+ Promise.resolve().then(() => read(structuredClone(probe), { signal: controller.signal })),
151
+ new Promise((_, reject) => {
152
+ timer = setTimeout(() => {
153
+ const timeout = Object.assign(new Error("timeout"), { sandboxTimeout: true });
154
+ controller.abort(timeout);
155
+ reject(timeout);
156
+ }, timeoutMs);
157
+ }),
158
+ ]);
159
+ if (!isCanonicalizable(value)) {
160
+ return { status: "CHECK_RESULT_NOT_CANONICAL_JSON", state: null, error: "result must be plain JSON data with integer numbers" };
161
+ }
162
+ return { status: "OK", state: value, error: null };
163
+ } catch (err) {
164
+ if (err && err.sandboxTimeout) return { status: "CHECK_TIMED_OUT", state: null, error: "no result within " + timeoutMs + " ms" };
165
+ return { status: "CHECK_THREW", state: null, error: String(err && err.message ? err.message : err).slice(0, 200) };
166
+ } finally {
167
+ clearTimeout(timer);
168
+ }
169
+ }
170
+
171
+ export class LocalEffectVerifier {
172
+ #clock;
173
+ #signer;
174
+ #seq = 0;
175
+
176
+ constructor({ clock, signer }) {
177
+ this.#clock = clock;
178
+ this.#signer = signer;
179
+ this.principal = signer.principal;
180
+ }
181
+
182
+ // reader: { kind: READ_KINDS.*, read: async (probe) => observedState,
183
+ // checkModule: { file_name, sha256 } | null, timeoutMs }
184
+ async observe({ decisionEnv, reportEnv, reader }) {
185
+ const d = decisionEnv.payload;
186
+ const r = reportEnv.payload;
187
+ const req = d.request;
188
+ const eff = effectFor(req.operation);
189
+ this.#seq += 1;
190
+ const probe = eff.probe(req);
191
+ const result = await performRead(reader.read, probe, reader.timeoutMs ?? 30000);
192
+ const observedAt = this.#clock.now();
193
+ const observation = {
194
+ observation_id: "obs-" + d.decision_id.slice(4) + "-" + this.#seq,
195
+ read_kind: reader.kind,
196
+ retrieved_by: this.principal,
197
+ check_module: reader.checkModule ?? null,
198
+ request: probe,
199
+ status: result.status,
200
+ error: result.error,
201
+ body: result.status === "OK" ? { resource: req.resource, state: result.state } : null,
202
+ };
203
+ const a = assessEffect({
204
+ request: req,
205
+ report: r,
206
+ retrievalMethod: RETRIEVAL_METHOD,
207
+ retrievalPrincipal: this.principal,
208
+ observation,
209
+ observedAt,
210
+ });
211
+ const payload = {
212
+ schema_version: PAYLOAD_TYPES.EFFECT_EVIDENCE,
213
+ evidence_id: "evd-" + d.decision_id.slice(4) + "-" + this.#seq,
214
+ decision_id: d.decision_id,
215
+ decision_digest: envelopeDigest(decisionEnv),
216
+ execution_report_digest: envelopeDigest(reportEnv),
217
+ claimed_effect: { operation: req.operation, resource: req.resource, outcome: a.claimed_outcome },
218
+ retrieval_method: RETRIEVAL_METHOD,
219
+ retrieval_principal_ref: this.principal,
220
+ read_kind: reader.kind,
221
+ observed_at: observedAt,
222
+ attested_at: this.#clock.now(),
223
+ resource_id: req.resource,
224
+ expected_state_digest: a.expected_state_digest,
225
+ observed_state_digest: a.observed_state_digest,
226
+ result: a.result,
227
+ reasons: a.reasons,
228
+ evidence_digest: a.evidence_digest,
229
+ observation_id: observation.observation_id,
230
+ observation_digest: digest(observation),
231
+ source_authentication: a.source_authentication,
232
+ freshness: {
233
+ max_age_seconds: a.max_age_seconds,
234
+ finality: a.finality,
235
+ consistency_model: eff.consistency_model,
236
+ },
237
+ coverage_boundary: eff.coverage_boundary,
238
+ limitations: a.limitations,
239
+ };
240
+ return { evidence: signEnvelope(PAYLOAD_TYPES.EFFECT_EVIDENCE, payload, this.#signer), observation, assessment: a };
241
+ }
242
+ }