@coreguard/agent-commerce 0.1.1 → 0.1.3
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/README.md +275 -11
- package/aer1.mjs +258 -0
- package/anchor.mjs +278 -0
- package/bin/mcp.mjs +0 -0
- package/composition.mjs +150 -0
- package/consumption-store.mjs +114 -38
- package/control-plane-cli.mjs +246 -0
- package/control-plane-http.mjs +275 -0
- package/control-plane.mjs +923 -0
- package/decision.mjs +152 -0
- package/firewall.mjs +1 -1
- package/identity.mjs +205 -0
- package/index.d.ts +848 -1
- package/index.mjs +189 -3
- package/mcp.mjs +476 -21
- package/outcomes-bridge.mjs +169 -0
- package/outcomes.mjs +220 -0
- package/package.json +42 -14
- package/profile-ref.mjs +130 -0
- package/reference.mjs +350 -0
- package/risk-cli.mjs +10 -2
- package/risk.mjs +49 -2
- package/spend.mjs +291 -0
- package/trust.mjs +322 -0
package/README.md
CHANGED
|
@@ -10,9 +10,10 @@ bytes approved, and for verifying any executed trace against that receipt.
|
|
|
10
10
|
- **Fail-closed execution verification** — a consent plus an executed trace
|
|
11
11
|
yields a verdict with named drift classes (AGR/1 taxonomy); incomplete or
|
|
12
12
|
ambiguous evidence is never treated as a pass.
|
|
13
|
-
- **stdio MCP server** (JSON-RPC 2.0) exposing
|
|
14
|
-
deterministic, zero keys
|
|
15
|
-
|
|
13
|
+
- **stdio MCP server** (JSON-RPC 2.0, protocol `2025-06-18`) exposing ten tools,
|
|
14
|
+
all offline, all deterministic, zero keys.
|
|
15
|
+
|
|
16
|
+
MIT. Node ≥ 18. No network calls, no stored credentials, no wall clock.
|
|
16
17
|
|
|
17
18
|
## MCP client configuration
|
|
18
19
|
|
|
@@ -27,17 +28,280 @@ bytes approved, and for verifying any executed trace against that receipt.
|
|
|
27
28
|
}
|
|
28
29
|
```
|
|
29
30
|
|
|
30
|
-
|
|
31
|
-
|
|
31
|
+
Per client, the same stdio command in each one's own file:
|
|
32
|
+
|
|
33
|
+
- **Claude Code** — `claude mcp add coreguard-agent-commerce -- npx -y @coreguard/agent-commerce`
|
|
34
|
+
- **Claude Desktop** — the `mcpServers` block above in `claude_desktop_config.json`
|
|
35
|
+
- **Cursor** — the same block in `.cursor/mcp.json`
|
|
36
|
+
- **VS Code (Copilot MCP)** — `{"servers": {"coreguard-agent-commerce": {"type": "stdio", "command": "npx", "args": ["-y", "@coreguard/agent-commerce"]}}}` in `.vscode/mcp.json`
|
|
37
|
+
- **Codex CLI** — `[mcp_servers.coreguard]` with `command = "npx"` and `args = ["-y", "@coreguard/agent-commerce"]` in `config.toml`
|
|
38
|
+
- **Gemini CLI / Zed / Windsurf** — stdio server entry, same command
|
|
39
|
+
|
|
40
|
+
What "supported" means here: the transport and schemas are what the CI harness
|
|
41
|
+
exercises against a real spawned child process. No third-party client has been
|
|
42
|
+
launched by us yet — the status vocabulary and the append-only run log are in
|
|
43
|
+
`docs/agent-commerce-mcp-compatibility.md`. Do not read the list above as a test
|
|
44
|
+
report.
|
|
45
|
+
|
|
46
|
+
## Tools
|
|
47
|
+
|
|
48
|
+
Every tool declares `inputSchema` and `outputSchema`, and returns
|
|
49
|
+
`structuredContent` next to the JSON text content. All ten are offline and
|
|
50
|
+
deterministic. Every tool accepts optional `callerContext` (object) which is echoed
|
|
51
|
+
in `structuredContent.callerContext` and never used as a cryptographic input.
|
|
52
|
+
|
|
53
|
+
### `coreguard_authorize`
|
|
54
|
+
|
|
55
|
+
Binds an approval as a CGCR/1 consent receipt.
|
|
56
|
+
|
|
57
|
+
| Input | Type | Required | Meaning |
|
|
58
|
+
|---|---|---|---|
|
|
59
|
+
| `intent` | object | yes | CGEP/1 intent: merchant, items, total, `credentialRef`, validity window, `singleUse` |
|
|
60
|
+
| `policy` | object | yes | CGEP/1 policy: value limit, target / recipient / selector allowlists |
|
|
61
|
+
| `declaredTrace` | object | yes | the exact submit-order payload the approval covers |
|
|
62
|
+
| `nowSeconds` | string (digits) | yes | pinned approval epoch; a number is rejected, the wall clock is never read |
|
|
63
|
+
|
|
64
|
+
Output: `{ spec: "CGCR/1", receipt, … }` — the commitments are re-derivable by
|
|
65
|
+
anyone holding the record.
|
|
66
|
+
|
|
67
|
+
### `coreguard_verify_consent`
|
|
68
|
+
|
|
69
|
+
Recomputes every commitment against the record's own approved bytes.
|
|
70
|
+
|
|
71
|
+
| Input | Type | Required |
|
|
72
|
+
|---|---|---|
|
|
73
|
+
| `consent` | object | yes — a record returned by `coreguard_authorize` |
|
|
74
|
+
|
|
75
|
+
Output: an integrity verdict; any tampered byte fails closed rather than throwing.
|
|
76
|
+
|
|
77
|
+
### `coreguard_verify_execution`
|
|
78
|
+
|
|
79
|
+
Compares an executed order to the receipt.
|
|
80
|
+
|
|
81
|
+
| Input | Type | Required | Meaning |
|
|
82
|
+
|---|---|---|---|
|
|
83
|
+
| `consent` | object | yes | CGCR/1 record |
|
|
84
|
+
| `trace` | object | yes | the executed order as observed |
|
|
85
|
+
|
|
86
|
+
Output: `{ spec, verdict, risk, consumed, consumedLedger }`.
|
|
87
|
+
|
|
88
|
+
- `verdict` = `VERIFIED` only on an exact re-derivation with no drift class fired.
|
|
89
|
+
- `verdict` = `INVALID` otherwise, with the drifted fields named in
|
|
90
|
+
`risk.violations[].code` (`VALUE_ESCALATION`, `ITEM_MUTATION`,
|
|
91
|
+
`TARGET_MISMATCH`, `RECIPIENT_MISMATCH`, `POLICY_VIOLATION`, …).
|
|
92
|
+
- `consumed` becomes `true` after the first verified execution of a single-use
|
|
93
|
+
consent. **The ledger is process-local** (durable anchoring is `NOT_BUILT`), so
|
|
94
|
+
this is not replay protection across processes or hosts.
|
|
95
|
+
|
|
96
|
+
### `coreguard_assess_risk`
|
|
97
|
+
|
|
98
|
+
Deterministic AGR/1 classification of one executed order against one approval.
|
|
99
|
+
|
|
100
|
+
| Input | Type | Required | Meaning |
|
|
101
|
+
|---|---|---|---|
|
|
102
|
+
| `intent` | object | yes | the approved order |
|
|
103
|
+
| `policy` | object | yes | the committed policy |
|
|
104
|
+
| `trace` | object | yes | the executed order |
|
|
105
|
+
| `consumed` | boolean | no | whether the authorization was already consumed (default `false`) |
|
|
106
|
+
|
|
107
|
+
Output: `{ classification, violations[], … }`. A rule-based conformance
|
|
108
|
+
classification, **not** a probabilistic fraud score.
|
|
109
|
+
|
|
110
|
+
### `coreguard_inspect_identity`
|
|
111
|
+
|
|
112
|
+
Inspects CG-ID/1 identity split (recordId/contentDigest/anchor facts), with optional comparison.
|
|
113
|
+
|
|
114
|
+
| Input | Type | Required | Meaning |
|
|
115
|
+
|---|---|---|---|
|
|
116
|
+
| `issuer` | string | yes | identity issuer |
|
|
117
|
+
| `scope` | string | yes | identity scope |
|
|
118
|
+
| `subject` | string | yes | identity subject |
|
|
119
|
+
| `contentDigest` | string | yes | 64-char lowercase hex digest (no `0x` prefix) |
|
|
120
|
+
| `anchor` | object | no | `{ kind, locator }` anchor reference |
|
|
121
|
+
| `other` | object | no | another identity object for comparison |
|
|
122
|
+
|
|
123
|
+
Output: `{ identity, anchorFacts, comparison? }`.
|
|
124
|
+
|
|
125
|
+
### `coreguard_build_attestation`
|
|
126
|
+
|
|
127
|
+
Builds a CGXA/1 offline execution attestation. No broadcast; no chain/network contact.
|
|
128
|
+
|
|
129
|
+
| Input | Type | Required | Meaning |
|
|
130
|
+
|---|---|---|---|
|
|
131
|
+
| `consent` | object | yes | CGCR/1 consent record |
|
|
132
|
+
| `executedTrace` | object | yes | executed trace observed by caller |
|
|
133
|
+
| `adapterId` | string | yes | CGXA adapter id |
|
|
134
|
+
| `nowSeconds` | integer or digit string | yes | pinned epoch; never wall clock |
|
|
135
|
+
|
|
136
|
+
Output: `{ spec, attestation, attestationId }`.
|
|
137
|
+
|
|
138
|
+
### `coreguard_verify_attestation`
|
|
139
|
+
|
|
140
|
+
Verifies a CGXA/1 attestation against consent and executed trace. Offline, fail-closed.
|
|
141
|
+
|
|
142
|
+
| Input | Type | Required |
|
|
143
|
+
|---|---|---|
|
|
144
|
+
| `attestation` | object | yes |
|
|
145
|
+
| `attestationId` | string | yes |
|
|
146
|
+
| `consent` | object | yes |
|
|
147
|
+
| `executedTrace` | object | yes |
|
|
148
|
+
|
|
149
|
+
Output: attestation verification result including `decision` (e.g. `VERIFIED`/refused) and boundary details.
|
|
150
|
+
|
|
151
|
+
### `coreguard_decide_outcome`
|
|
152
|
+
|
|
153
|
+
Maps a verification report to CG-OUT/1 outcome and authorization decision.
|
|
154
|
+
|
|
155
|
+
| Input | Type | Required | Meaning |
|
|
156
|
+
|---|---|---|---|
|
|
157
|
+
| `report` | object | yes | verification report / bridge-compatible report |
|
|
158
|
+
| `receiptId` | string | no | receipt id for optional profile reference |
|
|
159
|
+
|
|
160
|
+
Output: `{ outcome, decision, profileReference? }`. `ABSENT`/`NOT_CHECKED` never render as BLOCK; `VERIFIED ≠ SAFE`.
|
|
161
|
+
|
|
162
|
+
### `coreguard_profile_reference`
|
|
163
|
+
|
|
164
|
+
Creates or parses a CG-OUT/1 profile reference.
|
|
165
|
+
|
|
166
|
+
| Input | Type | Required | Meaning |
|
|
167
|
+
|---|---|---|---|
|
|
168
|
+
| `action` | string | yes | `make` or `parse` |
|
|
169
|
+
| `receiptId` | string | for make | receipt id |
|
|
170
|
+
| `reference` | object/string | for parse | reference to parse |
|
|
171
|
+
|
|
172
|
+
Output: `{ action, profileReference? , parsed? }`.
|
|
173
|
+
|
|
174
|
+
### `coreguard_consumption_status`
|
|
175
|
+
|
|
176
|
+
Checks/consumes/releases a receiptId in a consumption ledger.
|
|
177
|
+
|
|
178
|
+
| Input | Type | Required | Meaning |
|
|
179
|
+
|---|---|---|---|
|
|
180
|
+
| `receiptId` | string | yes | receipt/consent key |
|
|
181
|
+
| `action` | string | no | `check` (default), `consume`, or `release` |
|
|
182
|
+
| `storePath` | string | no | AC-CS/1 file-backed store path; defaults to `COREGUARD_CONSUMPTION_STORE` when set |
|
|
183
|
+
|
|
184
|
+
Output: `{ receiptId, action, consumed, ledger, boundary }`.
|
|
185
|
+
|
|
186
|
+
**Boundary:** the default ledger is **process-local** to this MCP server process. With `storePath` (or `COREGUARD_CONSUMPTION_STORE`), the AC-CS/1 store is used: lock-guarded and atomic across processes **on one host**. Cross-host reconciliation is CG-SPEND/1 log merge (`spend.mjs`), not this file. **NOT_BUILT:** a distributed/global register, consensus, HA replication, on-chain anchoring.
|
|
187
|
+
|
|
188
|
+
## Errors
|
|
189
|
+
|
|
190
|
+
Failures are tool results, never exceptions and never a process exit:
|
|
191
|
+
|
|
192
|
+
```
|
|
193
|
+
MISSING_ARGUMENT: nowSeconds is required
|
|
194
|
+
INVALID_ARGUMENT: nowSeconds must be a pinned unix-seconds string (digits only), not a number and never the wall clock
|
|
195
|
+
UNKNOWN_TOOL: unknown tool: coreguard_nope
|
|
196
|
+
TOOL_ERROR: <message from the engine>
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
and machine-readable as `structuredContent: { ok: false, error: { code, detail } }`.
|
|
200
|
+
Codes are exported from `mcp.mjs` as `ERROR_CODES`. JSON-RPC level errors stay
|
|
201
|
+
separate (`-32700` parse, `-32600` invalid request, `-32601` method not found); a
|
|
202
|
+
bad line never terminates the server.
|
|
203
|
+
|
|
204
|
+
## Try it without a client
|
|
205
|
+
|
|
206
|
+
```bash
|
|
207
|
+
# Runnable demo (approve → refuse → verify → malformed)
|
|
208
|
+
node examples/agent-commerce-mcp/run.mjs
|
|
209
|
+
|
|
210
|
+
# Runtime smoke check (real stdio MCP child, publish/MCPRush readiness evidence)
|
|
211
|
+
node scripts/agent-commerce-mcp-smoke.mjs
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
The demo ends in `PASS (8/8)`. The smoke check ends in `11/11 PASS` and exits non-zero on any failure.
|
|
215
|
+
Expected demo output: `examples/agent-commerce-mcp/README.md`.
|
|
216
|
+
|
|
217
|
+
```bash
|
|
218
|
+
# Control plane: policies, approvals, spend caps, revocation, audit chain (HTTP, offline)
|
|
219
|
+
node examples/agent-commerce-control-plane/run.mjs
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
## Policy & Evidence Control Plane (CGCP/1)
|
|
223
|
+
|
|
224
|
+
Beyond the per-order check, a team needs the operational layer: which agents exist,
|
|
225
|
+
which policy each runs under, what was approved, what was executed, what was
|
|
226
|
+
verified, what has been spent, and what was revoked. CGCP/1 is that layer, in this
|
|
227
|
+
package and self-hosted.
|
|
228
|
+
|
|
229
|
+
```js
|
|
230
|
+
import { createControlPlane } from "@coreguard/agent-commerce/control-plane.mjs";
|
|
231
|
+
|
|
232
|
+
const cp = createControlPlane({ storePath: "./control-plane.json" });
|
|
233
|
+
cp.upsertPolicy({ id: "p1", spendLimitMinor: "5000", dailyLimitMinor: "20000",
|
|
234
|
+
requireApprovalAboveMinor: "2000", allowMerchants: ["merchant-a"] });
|
|
235
|
+
cp.upsertAgent({ id: "a1", policyId: "p1" });
|
|
236
|
+
|
|
237
|
+
cp.evaluate({ agentId: "a1", merchant: "merchant-a", amountMinor: "2500" });
|
|
238
|
+
// { allowed: false, reasons: ["APPROVAL_REQUIRED"], ... }
|
|
239
|
+
const ap = cp.requestApproval({ agentId: "a1", policyId: "p1", merchant: "merchant-a", amountMinor: "2500" });
|
|
240
|
+
cp.decideApproval(ap.id, { decision: "approved", decidedBy: "ops@example" });
|
|
241
|
+
cp.commitExecution({ agentId: "a1", merchant: "merchant-a", amountMinor: "2500", approvalId: ap.id });
|
|
242
|
+
|
|
243
|
+
cp.verifyLedger(); // { ok: true, chain: { ok: true, length, headHash } }
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
- Immutable policy versions (an upsert appends, never rewrites history).
|
|
247
|
+
- Per-transaction, trailing-24h and lifetime spend caps; merchant/address allow+deny lists.
|
|
248
|
+
- Approvals bound to one order (agent, policy, merchant, address, amount) with expiry.
|
|
249
|
+
- Commits re-evaluate, so a revocation or a limit breach between authorise and commit is refused.
|
|
250
|
+
- Append-only hash-chained audit with `verifyAuditChain()`; tamper detection names the first broken entry.
|
|
251
|
+
- Lock-guarded single-host store; authenticated HTTP API (`control-plane-http.mjs`) and CLI (`control-plane-cli.mjs`).
|
|
252
|
+
|
|
253
|
+
```text
|
|
254
|
+
node packages/agent-commerce/control-plane-cli.mjs serve --port 8787
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
**NOT_BUILT:** multi-tenant isolation, RBAC/SSO/SCIM, distributed HA/consensus, KMS/HSM,
|
|
258
|
+
managed SLA, payment custody. One host, one API key, one JSON store. Architecture:
|
|
259
|
+
`docs/control-plane-architecture.md`; operations: `docs/control-plane-runbook.md`.
|
|
260
|
+
|
|
261
|
+
## SDK, without MCP
|
|
262
|
+
|
|
263
|
+
```js
|
|
264
|
+
import { createConsent, verifyExecution } from "@coreguard/agent-commerce";
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
The MCP tools are thin wrappers over these functions; nothing is added or hidden
|
|
268
|
+
by going through MCP.
|
|
32
269
|
|
|
33
270
|
## Boundaries (standing)
|
|
34
271
|
|
|
35
272
|
- Synthetic demo data is the caller's; nothing here contacts any commerce
|
|
36
|
-
platform or payment network, and no contact/integration/endorsement is
|
|
37
|
-
|
|
38
|
-
- **VERIFIED ≠ SAFE** — a verdict states that commitments re-derive; it is not
|
|
39
|
-
|
|
40
|
-
- Single-use consumption is process-local; durable
|
|
41
|
-
-
|
|
273
|
+
platform or payment network, and no contact/integration/endorsement is claimed
|
|
274
|
+
with any provider.
|
|
275
|
+
- **VERIFIED ≠ SAFE** — a verdict states that commitments re-derive; it is not a
|
|
276
|
+
guarantee of any broader outcome.
|
|
277
|
+
- Single-use consumption is process-local by default; the AC-CS/1 store makes it durable and atomic across processes on one host. Cross-host reconciliation is CG-SPEND/1 log merge; a global/on-chain register is `NOT_BUILT`.
|
|
278
|
+
- The executed trace is caller-supplied. Fetching it from a chain or a PSP is an
|
|
279
|
+
integration this package does not contain.
|
|
280
|
+
- No third-party security review, no certification. Marketplace grades are
|
|
281
|
+
automated heuristics, not audits — see
|
|
282
|
+
`docs/agent-commerce-mcp-security.md`.
|
|
283
|
+
- `serverInfo.version` is read from this package's `package.json`; CI fails if
|
|
284
|
+
they diverge.
|
|
42
285
|
|
|
43
286
|
License: MIT.
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
## Release readiness / MCPRush evidence
|
|
290
|
+
|
|
291
|
+
- **Release notes:** `docs/releases/0.1.3.md`
|
|
292
|
+
- **Publish readiness checklist:** `docs/releases/0.1.3-publish-readiness.md`
|
|
293
|
+
- **Security & threat model:** `docs/agent-commerce-mcp-security.md`
|
|
294
|
+
- **Client compatibility matrix + run log:** `docs/agent-commerce-mcp-compatibility.md`
|
|
295
|
+
- **Runtime smoke (real stdio):** `node scripts/agent-commerce-mcp-smoke.mjs`
|
|
296
|
+
- **60s demo script:** `docs/agent-commerce-mcp-demo-60s.md`
|
|
297
|
+
- **MCP contract tests:** `node --test test/integrations/agent-commerce-mcp.test.mjs`
|
|
298
|
+
- **Control plane architecture / runbook:** `docs/control-plane-architecture.md` · `docs/control-plane-runbook.md`
|
|
299
|
+
- **Control plane demo (HTTP, offline):** `node examples/agent-commerce-control-plane/run.mjs`
|
|
300
|
+
|
|
301
|
+
## Honest boundaries (read before integrating)
|
|
302
|
+
|
|
303
|
+
- **`VERIFIED ≠ SAFE`** — verification means the observed execution matches the approved/committed bytes under the checked rules; it is not a blanket safety or fraud guarantee.
|
|
304
|
+
- **Offline / no external contacts** — this package does not contact commerce platforms, payment networks, wallets, or PSPs.
|
|
305
|
+
- **Single-use consumption scope** — process-local by default; AC-CS/1 gives a lock-guarded file ledger across processes on one host; CG-SPEND/1 merges logs across hosts; a global register and on-chain anchoring are `NOT_BUILT`.
|
|
306
|
+
- **Caller-supplied observed trace** — execution verification checks the trace you provide against the consent; it does not independently fetch or prove external payment/network truth.
|
|
307
|
+
- **No fake "Tested" claims** — client compatibility is marked CONFIG-DOCUMENTED until a real run is recorded in the compatibility run log.
|
package/aer1.mjs
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CoreGuard AER-1 record parser (CG-AER1/1) — the receipt format we did not write.
|
|
3
|
+
*
|
|
4
|
+
* AER-1 (draft-zambo-aer1-26) commits a canonical payload and keeps the receipt
|
|
5
|
+
* id OUTSIDE that commitment. Two independent things follow from that design,
|
|
6
|
+
* and a verifier that merges them will be wrong about one of them:
|
|
7
|
+
*
|
|
8
|
+
* digest what these bytes ARE — recomputed here, never taken on trust
|
|
9
|
+
* id a label the payload does not cover — bindable only against
|
|
10
|
+
* something external: an expected id, or resolution of the id to a
|
|
11
|
+
* record whose own committed digest must agree
|
|
12
|
+
*
|
|
13
|
+
* With neither, the id is `unverified`: not matched, not refuted. That is a
|
|
14
|
+
* fact about the evidence, and this module reports it as one.
|
|
15
|
+
*
|
|
16
|
+
* BOUNDARY (standing, load-bearing):
|
|
17
|
+
* - No network. Resolution is supplied by the caller; this module never goes
|
|
18
|
+
* looking, so "unresolvable" here means the caller could not resolve it.
|
|
19
|
+
* - No clock. `created_at` is read as a claim, never as ordering.
|
|
20
|
+
* - A supported-version check is explicit: an AER-1 schema this build does
|
|
21
|
+
* not implement is reported NOT_CHECKED with the version named, never
|
|
22
|
+
* failed, because a verifier that never judged a record may not convict it.
|
|
23
|
+
* - `verdict: "pass"` means the structural and commitment checks passed. It
|
|
24
|
+
* says nothing about whether the recorded work was correct.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { createHash } from "node:crypto";
|
|
28
|
+
import { decideOutcome } from "./outcomes.mjs";
|
|
29
|
+
|
|
30
|
+
export const AER1_PARSER_VERSION = "CG-AER1/1";
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Receipt schema versions this parser implements. Draft -26 publishes schema
|
|
34
|
+
* 0.3 as current; 0.1 and 0.2 are accepted because their committed payload
|
|
35
|
+
* shape is a subset. Anything else is NOT_CHECKED with the version named.
|
|
36
|
+
*/
|
|
37
|
+
export const SUPPORTED_RECEIPT_SCHEMAS = Object.freeze(["0.1", "0.2", "0.3"]);
|
|
38
|
+
|
|
39
|
+
const DIGEST_RE = /^sha256:[0-9a-f]{64}$/;
|
|
40
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
41
|
+
const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");
|
|
42
|
+
|
|
43
|
+
const check = (name, ok, detail) => (detail === undefined ? { name, ok } : { name, ok, detail });
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* parseAer1Record(record, { expectedId, resolvedRecord })
|
|
47
|
+
*
|
|
48
|
+
* record the AER-1 artifact as published (outer envelope)
|
|
49
|
+
* expectedId an id the caller independently expects (string)
|
|
50
|
+
* resolvedRecord the record `record.id` resolved to — { id, output_hash }
|
|
51
|
+
*
|
|
52
|
+
* Returns frozen facts plus one verdict. Nothing here throws on a malformed
|
|
53
|
+
* artifact: a caller handing us garbage is evidence, not a program defect.
|
|
54
|
+
*/
|
|
55
|
+
export function parseAer1Record(record, { expectedId, resolvedRecord } = {}) {
|
|
56
|
+
if (!isObject(record)) {
|
|
57
|
+
const structure = [check("artifact is an object", false)];
|
|
58
|
+
return freeze({
|
|
59
|
+
parserVersion: AER1_PARSER_VERSION,
|
|
60
|
+
version: null,
|
|
61
|
+
supportedVersion: false,
|
|
62
|
+
structure,
|
|
63
|
+
structureOk: false,
|
|
64
|
+
digest: { claimed: null, computed: null, ok: false, byteLength: null, byteLengthClaimed: null },
|
|
65
|
+
id: { present: false, state: "unverified", verdict: "absent", expected: null, resolved: null },
|
|
66
|
+
verdict: "fail",
|
|
67
|
+
code: "STRUCTURE_INVALID",
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const version = typeof record.receipt_schema_version === "string" ? record.receipt_schema_version : null;
|
|
72
|
+
const supportedVersion = version !== null && SUPPORTED_RECEIPT_SCHEMAS.includes(version);
|
|
73
|
+
|
|
74
|
+
const structure = [];
|
|
75
|
+
const idPresent = typeof record.id === "string" && record.id.length > 0;
|
|
76
|
+
const claimed = typeof record.output_hash === "string" ? record.output_hash : null;
|
|
77
|
+
const encoded = typeof record.canonical_bytes === "string" ? record.canonical_bytes : null;
|
|
78
|
+
|
|
79
|
+
structure.push(check("id is present (outer envelope)", idPresent));
|
|
80
|
+
structure.push(check("output_hash is sha256:<64 hex>", claimed !== null && DIGEST_RE.test(claimed)));
|
|
81
|
+
structure.push(check("canonical_bytes is base64 text", encoded !== null && encoded.length > 0));
|
|
82
|
+
|
|
83
|
+
let computed = null;
|
|
84
|
+
let byteLength = null;
|
|
85
|
+
let payload = null;
|
|
86
|
+
let payloadParses = false;
|
|
87
|
+
|
|
88
|
+
if (encoded !== null && encoded.length > 0) {
|
|
89
|
+
const bytes = Buffer.from(encoded, "base64");
|
|
90
|
+
computed = sha256(bytes);
|
|
91
|
+
byteLength = bytes.length;
|
|
92
|
+
try {
|
|
93
|
+
payload = JSON.parse(bytes.toString("utf8"));
|
|
94
|
+
payloadParses = isObject(payload);
|
|
95
|
+
} catch {
|
|
96
|
+
payloadParses = false;
|
|
97
|
+
}
|
|
98
|
+
structure.push(check("canonical_bytes decode to a byte string", byteLength > 0));
|
|
99
|
+
structure.push(check("canonical_bytes parse to a JSON object", payloadParses));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const byteLengthClaimed =
|
|
103
|
+
typeof record.canonical_byte_length === "number" ? record.canonical_byte_length : null;
|
|
104
|
+
if (byteLengthClaimed !== null) {
|
|
105
|
+
structure.push(
|
|
106
|
+
check("canonical_byte_length matches the decoded bytes", byteLength === byteLengthClaimed, {
|
|
107
|
+
claimed: byteLengthClaimed,
|
|
108
|
+
actual: byteLength,
|
|
109
|
+
}),
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const digestOk = computed !== null && claimed !== null && `sha256:${computed}` === claimed;
|
|
114
|
+
structure.push(check("output_hash matches the recomputed digest", digestOk));
|
|
115
|
+
|
|
116
|
+
// The id must NOT be inside the commitment. If it is, the artifact's own
|
|
117
|
+
// claim ("the label is outside the signed payload") is false.
|
|
118
|
+
if (payloadParses) {
|
|
119
|
+
structure.push(check("committed payload does not carry the id", !("id" in payload)));
|
|
120
|
+
structure.push(
|
|
121
|
+
check(
|
|
122
|
+
"committed payload carries receipt_schema_version",
|
|
123
|
+
payload.receipt_schema_version === undefined || payload.receipt_schema_version === version,
|
|
124
|
+
),
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const structureOk = structure.every((c) => c.ok);
|
|
129
|
+
|
|
130
|
+
const id = bindId({ idPresent, record, expectedId, resolvedRecord });
|
|
131
|
+
|
|
132
|
+
const verdict = structureOk && id.verdict !== "mismatched" && id.state !== "absent" ? "pass" : "fail";
|
|
133
|
+
const code =
|
|
134
|
+
verdict === "pass"
|
|
135
|
+
? null
|
|
136
|
+
: id.verdict === "mismatched"
|
|
137
|
+
? "RECEIPT_ID_MISMATCH"
|
|
138
|
+
: structureOk
|
|
139
|
+
? "STRUCTURE_INVALID"
|
|
140
|
+
: digestOk || !structure.some((c) => c.name.includes("digest"))
|
|
141
|
+
? "STRUCTURE_INVALID"
|
|
142
|
+
: "DIGEST_MISMATCH";
|
|
143
|
+
|
|
144
|
+
return freeze({
|
|
145
|
+
parserVersion: AER1_PARSER_VERSION,
|
|
146
|
+
version,
|
|
147
|
+
supportedVersion,
|
|
148
|
+
structure,
|
|
149
|
+
structureOk,
|
|
150
|
+
digest: { claimed, computed: computed === null ? null : `sha256:${computed}`, ok: digestOk, byteLength, byteLengthClaimed },
|
|
151
|
+
id,
|
|
152
|
+
verdict,
|
|
153
|
+
code,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function bindId({ idPresent, record, expectedId, resolvedRecord }) {
|
|
158
|
+
if (!idPresent) {
|
|
159
|
+
return Object.freeze({ present: false, state: "unverified", verdict: "absent", expected: null, resolved: null });
|
|
160
|
+
}
|
|
161
|
+
const ownId = record.id;
|
|
162
|
+
|
|
163
|
+
if (typeof expectedId === "string") {
|
|
164
|
+
const same = expectedId === ownId;
|
|
165
|
+
return Object.freeze({
|
|
166
|
+
present: true,
|
|
167
|
+
state: same ? "verified-expected" : "mismatch",
|
|
168
|
+
verdict: same ? "matched" : "mismatched",
|
|
169
|
+
expected: expectedId,
|
|
170
|
+
resolved: null,
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (isObject(resolvedRecord)) {
|
|
175
|
+
const resolvedDigest = typeof resolvedRecord.output_hash === "string" ? resolvedRecord.output_hash : null;
|
|
176
|
+
const ownDigest = typeof record.output_hash === "string" ? record.output_hash : null;
|
|
177
|
+
const agree = resolvedDigest !== null && ownDigest !== null && resolvedDigest === ownDigest;
|
|
178
|
+
return Object.freeze({
|
|
179
|
+
present: true,
|
|
180
|
+
state: agree ? "verified-resolved" : "mismatch",
|
|
181
|
+
verdict: agree ? "resolved" : "mismatched",
|
|
182
|
+
expected: null,
|
|
183
|
+
resolved: { id: typeof resolvedRecord.id === "string" ? resolvedRecord.id : null, digest: resolvedDigest },
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
return Object.freeze({ present: true, state: "unverified", verdict: "unverified", expected: null, resolved: null });
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Turn parsed AER-1 facts into a CG-OUT/1 outcome.
|
|
192
|
+
*
|
|
193
|
+
* `anchor` is the anchor-layer fact set the caller measured, in CG-OUT/1's
|
|
194
|
+
* vocabulary: { present, evaluated, outcome } where outcome is "verified" |
|
|
195
|
+
* "absent" | "not_checked" | "unresolvable".
|
|
196
|
+
*
|
|
197
|
+
* Composition is deliberately CoreGuard's default here (anchor unresolvable
|
|
198
|
+
* composes to UNRESOLVABLE_RECORD). The layered alternative — where the record
|
|
199
|
+
* verdict never moves — is in composition.mjs, and the difference is a switch,
|
|
200
|
+
* not an argument.
|
|
201
|
+
*/
|
|
202
|
+
export function aer1Outcome(parsed, { anchor } = {}) {
|
|
203
|
+
if (!parsed || typeof parsed !== "object") throw new TypeError("aer1Outcome requires parsed facts");
|
|
204
|
+
if (!parsed.supportedVersion) {
|
|
205
|
+
return decideOutcome({
|
|
206
|
+
presented: true,
|
|
207
|
+
record: {
|
|
208
|
+
evaluated: false,
|
|
209
|
+
version: parsed.version ?? "unknown",
|
|
210
|
+
reason: `this build does not implement AER-1 receipt schema ${parsed.version ?? "(absent)"}`,
|
|
211
|
+
},
|
|
212
|
+
anchor,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
return decideOutcome({
|
|
216
|
+
presented: true,
|
|
217
|
+
record: {
|
|
218
|
+
evaluated: true,
|
|
219
|
+
ok: parsed.verdict === "pass",
|
|
220
|
+
code: parsed.code,
|
|
221
|
+
reason:
|
|
222
|
+
parsed.verdict === "pass"
|
|
223
|
+
? undefined
|
|
224
|
+
: parsed.id.verdict === "mismatched"
|
|
225
|
+
? "the committed digest disagrees with the id it was presented under"
|
|
226
|
+
: "a structural check on the AER-1 artifact failed",
|
|
227
|
+
},
|
|
228
|
+
anchor,
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function freeze(value) {
|
|
233
|
+
return Object.freeze(value);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Self-check: the parser's own invariants, for callers that cannot run tests. */
|
|
237
|
+
export function selfCheck() {
|
|
238
|
+
const bytes = Buffer.from(JSON.stringify({ receipt_schema_version: "0.3", output: { text: "ok" } }), "utf8");
|
|
239
|
+
const good = {
|
|
240
|
+
id: "11111111-1111-4111-8111-111111111111",
|
|
241
|
+
receipt_schema_version: "0.3",
|
|
242
|
+
canonical_byte_length: bytes.length,
|
|
243
|
+
canonical_bytes: bytes.toString("base64"),
|
|
244
|
+
output_hash: `sha256:${sha256(bytes)}`,
|
|
245
|
+
};
|
|
246
|
+
const alone = parseAer1Record(good);
|
|
247
|
+
const matched = parseAer1Record(good, { expectedId: good.id });
|
|
248
|
+
const swapped = parseAer1Record(good, { expectedId: "22222222-2222-4222-8222-222222222222" });
|
|
249
|
+
const future = parseAer1Record({ ...good, receipt_schema_version: "9.9" });
|
|
250
|
+
const checks = [
|
|
251
|
+
{ name: "a well-formed artifact verifies", pass: alone.verdict === "pass" },
|
|
252
|
+
{ name: "an unbound id is unverified, not matched", pass: alone.id.verdict === "unverified" },
|
|
253
|
+
{ name: "the same id binds as matched", pass: matched.id.verdict === "matched" },
|
|
254
|
+
{ name: "a swapped id is mismatched", pass: swapped.id.verdict === "mismatched" },
|
|
255
|
+
{ name: "an unimplemented version is not checked", pass: future.supportedVersion === false },
|
|
256
|
+
];
|
|
257
|
+
return Object.freeze({ ok: checks.every((c) => c.pass), checks });
|
|
258
|
+
}
|