@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentrax/sdk",
3
- "version": "1.3.0",
3
+ "version": "1.7.0",
4
4
  "description": "Intentrax deterministic public SDK for proof verification and API-wrapper execution.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -32,6 +32,9 @@
32
32
  "http.ts",
33
33
  "http.d.ts",
34
34
  "README.md",
35
+ "sandbox/*.mjs",
36
+ "sandbox/examples",
37
+ "sandbox/README.md",
35
38
  "trust"
36
39
  ],
37
40
  "keywords": [
@@ -0,0 +1,255 @@
1
+ # Intentrax local assurance sandbox (preview)
2
+
3
+ > **Not production assurance.** Everything here is signed with ephemeral keys
4
+ > generated on your machine (`environment: "local"`, `trust_bearing: false`).
5
+ > A local bundle can never verify as a production proof: the production
6
+ > `verify-proof`, the Go offline verifier, hosted verify and the Verification
7
+ > Mark do not accept it.
8
+
9
+ The sandbox runs one consequential action through the whole Intentrax
10
+ assurance flow, in-process, with no account, no API key and no network:
11
+
12
+ 1. a **signed decision** (ALLOW/DENY), made before execution;
13
+ 2. an **executor report** (a self-report: "I did it");
14
+ 3. an **independent read-only check** of the outcome, signed by a different
15
+ key from the executor's;
16
+ 4. a **sealed bundle** binding all of it by digests;
17
+ 5. **offline verification**: eight per-dimension assessments and the §5.4
18
+ verdict rule, capped at `LOCAL_NON_TRUST_BEARING`.
19
+
20
+ The point it demonstrates is the one a decision record alone cannot show: an
21
+ action can be authorised and reported as successful, yet not have happened.
22
+
23
+ Not to be confused with the **published sandbox** (`trust/sandbox-key-set.json`,
24
+ the sample proofs in `examples/sandbox/`, and the `SANDBOX_NON_TRUST_BEARING`
25
+ status of `verify-proof`). Those are production-format AEPs signed by
26
+ Intentrax-published, non-trust-bearing keys. The local sandbox never uses
27
+ those keys; it generates its own on your machine.
28
+
29
+ Design: `docs/architecture/INTENTRAX_APORT_COMPETITIVE_ASSESSMENT.md` §4.3 and
30
+ `docs/architecture/INTENTRAX_WAY_FORWARD_ADOPTION_AND_ASSURANCE.md` (P0 items
31
+ A1 and B1). The verifier semantics are ported from
32
+ `examples/effect-assurance-demo` (PRs #449, #477); see "Relationship to the
33
+ demo" below.
34
+
35
+ ## Run it
36
+
37
+ The sandbox is a subcommand of the SDK CLI (`@intentrax/sdk` 1.7.0 and later):
38
+
39
+ ```bash
40
+ npx @intentrax/sdk sandbox # sample action, outcome confirmed
41
+ npx @intentrax/sdk sandbox --scenario contradicted # ALLOW + "SUCCEEDED" + read says otherwise
42
+ npx @intentrax/sdk sandbox --check ./my-check.mjs # check the outcome of YOUR action
43
+ npx @intentrax/sdk sandbox verify <bundle.json> --keys <local-key-set.json>
44
+ ```
45
+
46
+ The packaged example check is at
47
+ `node_modules/@intentrax/sdk/sandbox/examples/read-only-check.example.mjs`. From
48
+ a checkout of this repository, `node sdk/typescript/sandbox/cli.mjs` runs the
49
+ same CLI.
50
+
51
+ Add `--json` for machine-readable output, and `--dir <project>` to write
52
+ somewhere other than the current directory.
53
+
54
+ | Command | Verdict | Exit |
55
+ | --- | --- | --- |
56
+ | `sandbox` | `LOCAL_NON_TRUST_BEARING` (uncapped: `VERIFIED_FOR_SCOPE`), `EFFECT_CONFIRMED = CONFIRMED` | 0 |
57
+ | `sandbox --scenario contradicted` | `CONFLICTING_EVIDENCE`, `EFFECT_CONFIRMED = CONTRADICTED` | 12 |
58
+ | `sandbox --check` (read matches `expected`) | `LOCAL_NON_TRUST_BEARING`, `EFFECT_CONFIRMED = CONFIRMED` | 0 |
59
+ | `sandbox --check` (read differs) | `CONFLICTING_EVIDENCE` | 12 |
60
+ | `sandbox --check` (check throws, times out, returns non-JSON) | `INSUFFICIENT_EVIDENCE` | 11 |
61
+ | `sandbox verify` without `--keys` | `INTEGRITY_ONLY` | 13 |
62
+
63
+ Exit codes: `0` LOCAL_NON_TRUST_BEARING · `10` PENDING_FINALITY · `11`
64
+ INSUFFICIENT_EVIDENCE · `12` CONFLICTING_EVIDENCE · `13` INTEGRITY_ONLY · `14`
65
+ VERIFICATION_FAILED · `64` usage. `VERIFIED_FOR_SCOPE` is never returned.
66
+
67
+ ## Check the outcome of your own action (`--check`)
68
+
69
+ Write a small module that **reads** the state your agent's action should have
70
+ produced. Run your action first, then the sandbox:
71
+
72
+ ```js
73
+ // my-check.mjs
74
+ export const resource = "ticket:1234"; // optional label
75
+ export const expected = { status: "closed" }; // required: what the action should have set
76
+ export default async function check({ resource, fields }) {
77
+ const ticket = await myReadOnlyClient.getTicket(1234); // a READ, never a write
78
+ return { status: ticket.status };
79
+ }
80
+ ```
81
+
82
+ The sandbox authorises `SetState ticket:1234 -> {"status":"closed"}`, records
83
+ that your action reports success, calls `check()` once with its own local
84
+ effect-verifier key, compares only the fields named in `expected`, and shows
85
+ `EFFECT_CONFIRMED` = `CONFIRMED` or `CONTRADICTED`.
86
+
87
+ - The read must be an object containing **every** field named in `expected`.
88
+ A missing field is not treated as `null`, so `{}` can never confirm
89
+ `expected = { deleted_at: null }`. A missing field, or a read that is not an
90
+ object, gives `INSUFFICIENT_EVIDENCE`.
91
+ - Your module is loaded and called only inside a worker thread, never on the
92
+ sandbox's own thread. The worker is terminated once it answers, or when
93
+ `--check-timeout-ms` (default 30000) runs out. So a check that hangs or
94
+ leaves sockets or timers open still ends with exit 11
95
+ (`INSUFFICIENT_EVIDENCE`, `CHECK_TIMED_OUT`). Return plain data only: the
96
+ result crosses the thread boundary by structured clone. A full example is in
97
+ [`examples/read-only-check.example.mjs`](examples/read-only-check.example.mjs).
98
+
99
+ How the read is labelled, honestly:
100
+
101
+ | Read | `source_authentication` | Provenance | Why |
102
+ | --- | --- | --- | --- |
103
+ | Built-in sample (synthetic store) | `LOCAL_EFFECT_VERIFIER_READ` | `THIRD_PARTY_ATTESTED` | Read and signed by the local effect-verifier key, distinct from the executor key. Still a local key. |
104
+ | Your `--check` module | `USER_SUPPLIED_CHECK` | `SELF_REPORTED` | You wrote both the action and the check. It is not an Intentrax-pulled authoritative read. |
105
+
106
+ The bundle records the check module's file name and SHA-256, not its path.
107
+
108
+ ## What gets written
109
+
110
+ Everything goes under `<project>/.intentrax/local/`, which contains its own
111
+ `.gitignore` (`*`), so nothing is committed by accident:
112
+
113
+ ```
114
+ .intentrax/local/
115
+ .gitignore # "*"
116
+ sandbox-signing-keys.json # this run's ephemeral PRIVATE keys (mode 0600); regenerated every run
117
+ runs/<bundle_id>/
118
+ bundle.json # intentrax.local_assurance_bundle/0.1
119
+ local-key-set.json # the run's PUBLIC keys, to re-verify the bundle
120
+ verification-report.json # the eight assessments and the verdict
121
+ ```
122
+
123
+ ## External authorization decisions (`verify --issuer-keys`)
124
+
125
+ A bundle may also carry another system's signed authorization decision. The
126
+ sandbox treats it as **evidence, never trust**. This is the verifier side of
127
+ B3 (`docs/architecture/INTENTRAX_EXTERNAL_DECISION_EVIDENCE.md`), ported from
128
+ the demo (PR #481). The sandbox never issues, fetches or adds external
129
+ decisions itself. `sandbox verify` assesses them when a bundle carries them:
130
+
131
+ ```bash
132
+ node sdk/typescript/sandbox/cli.mjs verify bundle.json --keys local-key-set.json \
133
+ --issuer-keys pinned-external-issuers.json [--require-external-issuer <issuer>]...
134
+ ```
135
+
136
+ - Each decision sits in an optional, sealed `external_decisions` array of
137
+ `intentrax.external_decision_evidence/0.1` wrappers. The wrappers keep the
138
+ issuer's original bytes verbatim. Bundles the sandbox makes never have this
139
+ field, so their bytes and seals are unchanged.
140
+ - Signatures are checked **only** against the issuer key set you pin
141
+ (`intentrax.local.sandbox_pinned_external_issuers/0.1`; same shape as the
142
+ demo's file). Nothing is fetched: no JWKS, no revocation list, no network.
143
+ The loader fails closed on an unknown schema or profile, a non-Ed25519 or
144
+ malformed key, a duplicate issuer or kid, or a missing, malformed or
145
+ inverted `valid_from`/`valid_until`/`revoked_at`.
146
+ - The result is an extra dimension, `EXTERNAL_AUTHORIZATION`, with provenance
147
+ `THIRD_PARTY_ATTESTED`. It appears only when the bundle carries external
148
+ decisions or you name an issuer, so ordinary reports keep eight
149
+ dimensions. It never changes `AUTHORIZATION`.
150
+ - Binding: the decision must name the same tool, target and parameters
151
+ digest, be issued before the action, and still be in force when it runs.
152
+ Otherwise the result is `UNBOUND_EXTERNAL_DECISION:*` or
153
+ `EXTERNAL_DECISION_EXPIRED` (`INSUFFICIENT_EVIDENCE`).
154
+ - Conflict: an external DENY against a local ALLOW is `CONTRADICTED`, so the
155
+ verdict is `CONFLICTING_EVIDENCE` (exit 12), required or not.
156
+ - Non-required by default: a missing or unverifiable external decision does
157
+ not change the verdict. `--require-external-issuer` makes the dimension
158
+ required, and only that issuer's decision satisfies it.
159
+ - **The ceiling still applies.** A genuinely signed, bound and required
160
+ external ALLOW still gives `LOCAL_NON_TRUST_BEARING`, never
161
+ `VERIFIED_FOR_SCOPE`.
162
+ - Format profile `intentrax.ext_profile.ed25519_jcs_oap_shaped/0.1`: an
163
+ Ed25519-over-JCS decision shaped like an OAP decision, plus an
164
+ `action_binding` extension. Interoperability with real APort/OAP decisions
165
+ is **UNVERIFIED** (never tested against a genuine signed APort decision),
166
+ and no APort compatibility is claimed.
167
+ - Documented limit: someone holding the local decision-service key can strip
168
+ `external_decisions` and reseal. Completeness is not established, and the
169
+ verifier cannot know about evidence it was never shown.
170
+
171
+ ## Invariants (each is a test in `test/invariants.test.mjs`)
172
+
173
+ 1. Fresh Ed25519 keys per run, under `.intentrax/local/`, each labelled
174
+ `environment: "local"`, `trust_bearing: false`. The key-set loader refuses
175
+ anything else, including the production and published sandbox key sets.
176
+ 2. The sandbox never reads, derives or requests a production or published
177
+ sandbox key, and makes no network call. Checked three ways: a static scan
178
+ of the runtime modules' imports, a run with file-read and network spies,
179
+ and a run under the Node permission model with no read access to `trust/`.
180
+ The only code that could touch a network is your own `--check` module.
181
+ 3. The verdict is capped at `LOCAL_NON_TRUST_BEARING`, also when you pin the
182
+ run's key set, and also if a key map claiming `trust_bearing: true` is
183
+ forced past the loader. The cap removes the positive claim only; a
184
+ contradiction, missing evidence or a failed check is reported as is.
185
+ 4. `trust/production-key-set.json` (and `trust/sandbox-key-set.json`) are
186
+ hash-pinned and unchanged.
187
+ 5. `intentrax verify-proof` with the built-in production key set rejects a
188
+ local bundle (fails closed), and rejects a local key set passed as
189
+ `--trusted-keys`.
190
+ 6. Human and JSON output carry the "not production assurance" banner.
191
+
192
+ ## Limitations (read before showing this to anyone)
193
+
194
+ 1. **Not trust-bearing.** Anyone can generate local keys and sign whatever
195
+ they like. A local bundle shows the verification mechanics and the shape
196
+ of the evidence, not that anything is true.
197
+ 2. **Preview format.** The bundle is the effect-assurance preview format
198
+ (`intentrax.effect_evidence/0.1` inside
199
+ `intentrax.local_assurance_bundle/0.1`), not the production AEP export.
200
+ Format parity with production is not claimed.
201
+ 3. **Your check is yours.** A `--check` read is `SELF_REPORTED`: it is only as
202
+ independent and correct as the code you wrote, and it is read-only by
203
+ contract only. The sandbox cannot stop a check from writing.
204
+ 4. **The sandbox does not run your action.** With `--check`, the executor
205
+ report records the claim that your action ran; the sandbox makes no call
206
+ to your system other than your check function.
207
+ 5. **No attribution.** A confirmed state may pre-date the action; nothing
208
+ links it to this execution (`EFFECT_NOT_ATTRIBUTED_TO_THIS_EXECUTION`).
209
+ 6. **Reads are treated as final.** Eventual consistency and asynchronous
210
+ operations are not modelled; the demo's PENDING/FINAL handling is not
211
+ exercised here.
212
+ 7. **Partial coverage.** Only the fields named in `expected` are compared.
213
+ 8. **One mandate, no delegation, no budget, no revocation registry.** The
214
+ demo's delegation, aggregate-budget and revocation scenarios are not part
215
+ of the sandbox.
216
+ 9. **Execution is not attested** (`EXECUTION_ATTESTED = NOT_ASSESSED`), and
217
+ completeness is not established: nothing proves every action went through
218
+ Intentrax.
219
+ 10. **Times are self-asserted** by local signers, on a logical clock that
220
+ starts at the real time of the run.
221
+ The verifier accepts only RFC 3339 times with an explicit offset (`Z` or
222
+ `±hh:mm`): a timezone-less or unparseable time fails closed, so a result
223
+ never depends on the verifying machine's timezone.
224
+ 11. **Shared evaluator.** The verifier re-runs the same mandate/policy
225
+ evaluator as the local decision service.
226
+ 12. **The bundle holds the raw read.** That makes offline recomputation
227
+ possible. Do not point a check at data you would not keep in a local
228
+ file.
229
+
230
+ ## Relationship to the demo
231
+
232
+ Ported (not imported) from `examples/effect-assurance-demo`, PRs #449 and
233
+ #477: `canonical.mjs` (unchanged), `model.mjs` (unchanged rule plus the local
234
+ ceiling), `envelope.mjs` (sandbox signing domain, no revocation),
235
+ `verifier.mjs` (single mandate, no budget), `effect-verifier.mjs` (local
236
+ reads instead of source receipts), `bundle.mjs` (sealed
237
+ `environment`/`trust_bearing` labels), and the decision service and executor
238
+ flow (`run.mjs`). Each file names its source. Scenario B of the demo is
239
+ `--scenario contradicted` here.
240
+
241
+ From PR #481 (B3), the verifier side only: `external-decision.mjs` (no
242
+ issuing, no ingestion), the optional `EXTERNAL_AUTHORIZATION` dimension,
243
+ `deriveVerdict(..., { extraRequired })`, the optional sealed
244
+ `external_decisions` component, and the `SEAL_COMPONENT_SET_MISMATCH` check.
245
+ Scenario J of the demo is `test/external-decision.test.mjs` here (rows J1 to
246
+ J9, with the local ceiling applied). The test-only issuer is in
247
+ `test-fixtures/external-issuer.mjs`.
248
+
249
+ ## Release status
250
+
251
+ Shipped in `@intentrax/sdk` 1.7.0: `cli/intentrax.mjs` dispatches `sandbox`
252
+ to `sandbox/cli.mjs`, and the package `files` include `sandbox/*.mjs`,
253
+ `sandbox/examples` and this README (not the tests or fixtures). The npm
254
+ release goes through staged trusted publishing; the owner approves it with
255
+ `npm stage approve`.
@@ -0,0 +1,66 @@
1
+ // Mandate + policy evaluation for the local assurance sandbox.
2
+ //
3
+ // Trimmed port of examples/effect-assurance-demo/src/authority.mjs (PRs #449,
4
+ // #477). The sandbox issues one root mandate per run, with no delegation and
5
+ // no budget, so the delegation-subset and budget-ledger logic is not carried
6
+ // over. The evaluator is shared by the local decision service (to decide) and
7
+ // the offline verifier (to re-evaluate); sharing it is a stated limitation.
8
+ //
9
+ // Shapes:
10
+ // mandate payload (intentrax.mandate/0.1)
11
+ // { schema_version, mandate_id, issuer, subject, parent_mandate_id: null,
12
+ // policy_digest, scope: { operations[], resources[] }, not_before,
13
+ // expires_at, issued_at, purpose }
14
+ // policy (intentrax.policy/0.1)
15
+ // { schema_version, policy_id, version, default: "DENY", rules: [{ operation, required_profile }] }
16
+
17
+ import { digest } from "./canonical.mjs";
18
+ import { isoMs } from "./time.mjs";
19
+
20
+ export function resourceMatches(pattern, resource) {
21
+ if (pattern.endsWith("*")) return resource.startsWith(pattern.slice(0, -1));
22
+ return pattern === resource;
23
+ }
24
+
25
+ // Evaluate `request` against one root `mandate` at time `at`.
26
+ export function evaluate({ request, mandate, policy, policyDigest, at }) {
27
+ const reasons = [];
28
+ const add = (r) => {
29
+ if (!reasons.includes(r)) reasons.push(r);
30
+ };
31
+ if (!mandate) {
32
+ return { outcome: "DENY", reasons: ["NO_MANDATE"], required_assurance_profile: "DECISION_RECORD" };
33
+ }
34
+ if (mandate.parent_mandate_id !== null) add("CHAIN_ROOT_HAS_PARENT");
35
+ if (mandate.policy_digest !== policyDigest) add("MANDATE_POLICY_MISMATCH");
36
+ // Strict timestamps (explicit offset; #491 parity). An unparseable decision
37
+ // time or mandate bound fails closed instead of comparing false (NaN).
38
+ const atMs = isoMs(at);
39
+ if (atMs === null) add("DECISION_TIME_INVALID");
40
+ const notBefore = isoMs(mandate.not_before);
41
+ const expiresAt = isoMs(mandate.expires_at);
42
+ if (notBefore === null || expiresAt === null) {
43
+ add("MANDATE_TIME_INVALID");
44
+ } else if (atMs !== null) {
45
+ if (atMs < notBefore) add("MANDATE_NOT_YET_VALID");
46
+ if (atMs >= expiresAt) add("MANDATE_EXPIRED");
47
+ }
48
+ if (request.mandate_id !== mandate.mandate_id) add("REQUEST_MANDATE_MISMATCH");
49
+ if (request.agent !== mandate.subject) add("AGENT_NOT_MANDATE_SUBJECT");
50
+ if (!mandate.scope.operations.includes(request.operation)) add("MANDATE_OPERATION_NOT_PERMITTED");
51
+ if (!mandate.scope.resources.some((p) => resourceMatches(p, request.resource))) add("MANDATE_RESOURCE_NOT_PERMITTED");
52
+
53
+ const rule = policy.rules.find((r) => r.operation === request.operation);
54
+ if (!rule) add("POLICY_NO_MATCHING_RULE");
55
+
56
+ const outcome = reasons.length ? "DENY" : "ALLOW";
57
+ return {
58
+ outcome,
59
+ reasons,
60
+ required_assurance_profile: outcome === "ALLOW" ? rule.required_profile : "DECISION_RECORD",
61
+ };
62
+ }
63
+
64
+ export function actionDigest(request) {
65
+ return digest({ operation: request.operation, resource: request.resource, params: request.params });
66
+ }
@@ -0,0 +1,93 @@
1
+ // Local assurance bundle (`intentrax.local_assurance_bundle/0.1`).
2
+ //
3
+ // Adapted from examples/effect-assurance-demo/src/bundle.mjs (PRs #449,
4
+ // #477). Every component is signed by the party that produced it and
5
+ // cross-bound by digests; the local decision-service seal lists the digest of
6
+ // every component. The sandbox adds two sealed top-level labels,
7
+ // `environment: "local"` and `trust_bearing: false`, so a local bundle cannot
8
+ // be relabelled without breaking the seal. There is no budget ledger.
9
+
10
+ import { digest } from "./canonical.mjs";
11
+ import { signEnvelope, envelopeDigest, PAYLOAD_TYPES } from "./envelope.mjs";
12
+ import { LOCAL_ENVIRONMENT } from "./keys.mjs";
13
+
14
+ export const BUNDLE_SCHEMA = "intentrax.local_assurance_bundle/0.1";
15
+
16
+ export const BUNDLE_FIELDS = Object.freeze([
17
+ "assurance_profile",
18
+ "bundle_id",
19
+ "decision",
20
+ "effect_evidence",
21
+ "environment",
22
+ "execution_reports",
23
+ "mandates",
24
+ "policy",
25
+ "schema_version",
26
+ "seal",
27
+ "source_observations",
28
+ "trust_bearing",
29
+ ]);
30
+
31
+ // Optional field (B3, ported from the demo, PR #481): third-party signed
32
+ // authorization decisions, wrapped as `intentrax.external_decision_evidence/0.1`.
33
+ // The sandbox never adds it to the bundles it makes, so their seal components
34
+ // (and bytes) are unchanged; `sandbox verify` assesses it when present.
35
+ export const OPTIONAL_BUNDLE_FIELDS = Object.freeze(["external_decisions"]);
36
+
37
+ export function sealComponents(bundle) {
38
+ const comps = {
39
+ policy: digest(bundle.policy),
40
+ mandates: bundle.mandates.map(envelopeDigest),
41
+ decision: envelopeDigest(bundle.decision),
42
+ execution_reports: bundle.execution_reports.map(envelopeDigest),
43
+ effect_evidence: bundle.effect_evidence.map(envelopeDigest),
44
+ source_observations: bundle.source_observations.map((o) => digest(o)),
45
+ };
46
+ if (Object.prototype.hasOwnProperty.call(bundle, "external_decisions")) {
47
+ comps.external_decisions = bundle.external_decisions.map((x) => digest(x));
48
+ }
49
+ return comps;
50
+ }
51
+
52
+ export function assembleBundle({
53
+ bundleId,
54
+ policy,
55
+ mandates,
56
+ decision,
57
+ executionReports = [],
58
+ effectEvidence = [],
59
+ sourceObservations = [],
60
+ sealSigner,
61
+ sealedAt,
62
+ }) {
63
+ const bundle = {
64
+ schema_version: BUNDLE_SCHEMA,
65
+ bundle_id: bundleId,
66
+ environment: LOCAL_ENVIRONMENT,
67
+ trust_bearing: false,
68
+ assurance_profile: decision.payload.required_assurance_profile,
69
+ policy,
70
+ mandates,
71
+ decision,
72
+ execution_reports: executionReports,
73
+ effect_evidence: effectEvidence,
74
+ source_observations: sourceObservations,
75
+ };
76
+ return resealBundle(bundle, { sealSigner, sealedAt });
77
+ }
78
+
79
+ // (Re)compute and sign the seal over the bundle as it stands.
80
+ export function resealBundle(bundle, { sealSigner, sealedAt }) {
81
+ const { seal: _old, ...rest } = bundle;
82
+ const seal = signEnvelope(PAYLOAD_TYPES.BUNDLE_SEAL, {
83
+ schema_version: PAYLOAD_TYPES.BUNDLE_SEAL,
84
+ bundle_id: rest.bundle_id,
85
+ bundle_schema_version: rest.schema_version,
86
+ environment: rest.environment,
87
+ trust_bearing: rest.trust_bearing,
88
+ assurance_profile: rest.assurance_profile,
89
+ sealed_at: sealedAt,
90
+ components: sealComponents(rest),
91
+ }, sealSigner);
92
+ return { ...rest, seal };
93
+ }
@@ -0,0 +1,64 @@
1
+ // Canonical JSON + digests for the local assurance sandbox.
2
+ //
3
+ // Ported from examples/effect-assurance-demo/src/canonical.mjs (PRs #449,
4
+ // #477) without behavioural change. Same rule as `canonicalJson` in
5
+ // sdk/typescript/index.ts: object keys sorted by UTF-16 code unit, no
6
+ // whitespace, strings via JSON.stringify, integers only (no floats, NaN or
7
+ // Infinity), `undefined` rejected. Every signature and digest in the sandbox
8
+ // is computed over these bytes.
9
+
10
+ import { createHash } from "node:crypto";
11
+
12
+ export function canonicalJson(value) {
13
+ if (value === null) {
14
+ return "null";
15
+ }
16
+ if (Array.isArray(value)) {
17
+ return "[" + value.map((item) => canonicalJson(item)).join(",") + "]";
18
+ }
19
+ if (typeof value === "string") {
20
+ return JSON.stringify(value);
21
+ }
22
+ if (typeof value === "boolean") {
23
+ return value ? "true" : "false";
24
+ }
25
+ if (typeof value === "number") {
26
+ if (!Number.isSafeInteger(value)) {
27
+ throw new Error("canonical_json: only safe integers are allowed");
28
+ }
29
+ return String(value);
30
+ }
31
+ if (typeof value === "object") {
32
+ const proto = Object.getPrototypeOf(value);
33
+ if (proto !== Object.prototype && proto !== null) {
34
+ throw new Error("canonical_json: only plain objects are allowed");
35
+ }
36
+ return "{" + Object.keys(value).sort().map((key) => {
37
+ const member = value[key];
38
+ if (member === undefined) {
39
+ throw new Error("canonical_json: undefined member " + key);
40
+ }
41
+ return JSON.stringify(key) + ":" + canonicalJson(member);
42
+ }).join(",") + "}";
43
+ }
44
+ throw new Error("canonical_json: unsupported value of type " + typeof value);
45
+ }
46
+
47
+ export function sha256Hex(data) {
48
+ return createHash("sha256").update(data).digest("hex");
49
+ }
50
+
51
+ // digest(value) -> "sha256:<hex>" over the canonical JSON bytes.
52
+ export function digest(value) {
53
+ return "sha256:" + sha256Hex(Buffer.from(canonicalJson(value), "utf8"));
54
+ }
55
+
56
+ // True when `value` can be represented in canonical JSON.
57
+ export function isCanonicalizable(value) {
58
+ try {
59
+ canonicalJson(value);
60
+ return true;
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
@@ -0,0 +1,50 @@
1
+ // Runs a developer's `--check` module in a worker thread.
2
+ //
3
+ // The sandbox never executes user check code on its own thread: both reading
4
+ // the module's exports ("describe") and calling the check ("read") happen in
5
+ // a worker that is terminated as soon as it answers, fails, or the caller's
6
+ // AbortSignal fires (the read timeout). Sockets, timers or a promise that
7
+ // never settles inside a check therefore cannot keep the CLI alive.
8
+ //
9
+ // The worker side is check-worker.mjs. Values cross the boundary by
10
+ // structured clone, so a check can only return data (functions and other
11
+ // non-cloneable values are an error).
12
+
13
+ import { Worker } from "node:worker_threads";
14
+
15
+ export function runCheckWorker({ href, mode, probe = null, signal = null }) {
16
+ return new Promise((resolve, reject) => {
17
+ if (signal && signal.aborted) {
18
+ reject(signal.reason);
19
+ return;
20
+ }
21
+ const worker = new Worker(new URL("./check-worker.mjs", import.meta.url), {
22
+ workerData: { href, mode, probe },
23
+ });
24
+ let settled = false;
25
+ const onAbort = () => finish(() => reject(signal.reason));
26
+ function finish(settle) {
27
+ if (settled) return;
28
+ settled = true;
29
+ if (signal) signal.removeEventListener("abort", onAbort);
30
+ // Terminate unconditionally: the check may have left handles open.
31
+ worker.terminate().catch(() => {});
32
+ settle();
33
+ }
34
+ worker.once("message", (m) => finish(() => (m && m.ok ? resolve(m.value) : reject(new Error(m && m.error ? m.error : "check failed")))));
35
+ worker.once("error", (err) => finish(() => reject(err)));
36
+ worker.once("exit", (code) => finish(() => reject(new Error("check worker exited with code " + code))));
37
+ if (signal) signal.addEventListener("abort", onAbort, { once: true });
38
+ });
39
+ }
40
+
41
+ // Read a check module's exports without running its code on this thread.
42
+ export async function describeCheck(href, timeoutMs) {
43
+ const controller = new AbortController();
44
+ const timer = setTimeout(() => controller.abort(new Error("loading the check module took longer than " + timeoutMs + " ms")), timeoutMs);
45
+ try {
46
+ return await runCheckWorker({ href, mode: "describe", signal: controller.signal });
47
+ } finally {
48
+ clearTimeout(timer);
49
+ }
50
+ }
@@ -0,0 +1,30 @@
1
+ // Worker side of check-runner.mjs: imports the developer's check module and
2
+ // either describes its exports or calls its check once with the probe. The
3
+ // parent terminates this worker as soon as it posts, so nothing the check
4
+ // leaves behind outlives the answer.
5
+
6
+ import { parentPort, workerData } from "node:worker_threads";
7
+
8
+ const { href, mode, probe } = workerData;
9
+
10
+ try {
11
+ const mod = await import(href);
12
+ const check = typeof mod.default === "function" ? mod.default : typeof mod.check === "function" ? mod.check : null;
13
+ if (mode === "describe") {
14
+ parentPort.postMessage({
15
+ ok: true,
16
+ value: {
17
+ has_check: check !== null,
18
+ expected: mod.expected === undefined ? null : mod.expected,
19
+ resource: mod.resource === undefined ? null : mod.resource,
20
+ },
21
+ });
22
+ } else if (check === null) {
23
+ parentPort.postMessage({ ok: false, error: "module exports no check function" });
24
+ } else {
25
+ const value = await check(probe);
26
+ parentPort.postMessage({ ok: true, value: value === undefined ? null : value });
27
+ }
28
+ } catch (err) {
29
+ parentPort.postMessage({ ok: false, error: String(err && err.message ? err.message : err).slice(0, 200) });
30
+ }