@coreguard/agent-commerce 0.1.2 → 0.1.4

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,169 @@
1
+ /**
2
+ * CG-OUT/1 bridges — the outcome layer as the surfaces actually print it.
3
+ *
4
+ * An outcome vocabulary that only exists in a library is a vocabulary nobody
5
+ * reads. This file is the seam between the layer (`outcomes.mjs`) and the three
6
+ * places a human or a machine meets it: the `verify-run` CLI, the PSAR/1
7
+ * pre-sign verifier, and the AGR/1 risk taxonomy.
8
+ *
9
+ * The seam exists because those three surfaces already have their own words,
10
+ * and the words are not wrong — they answer narrower questions:
11
+ *
12
+ * verify-run VERIFIED / INVALID / UNVERIFIED / INCONCLUSIVE + exit code
13
+ * PSAR/1 PASS / BLOCK + a named reject code
14
+ * AGR/1 CLEAN / VIOLATIONS over authorization drift
15
+ *
16
+ * What none of them can say is "nobody handed us a record". The mapping below
17
+ * adds exactly that, without changing any existing field, exit code or verdict:
18
+ * every surface keeps the words its consumers already parse and gains one
19
+ * `outcome` field that says what a reader is allowed to conclude.
20
+ *
21
+ * The mapping rules, deliberately few:
22
+ *
23
+ * no record at all -> ABSENT
24
+ * evaluated and passed -> VERIFIED
25
+ * evaluated and a check failed -> VERIFICATION_FAILED (code kept)
26
+ * presented, never evaluated -> NOT_CHECKED (reason named)
27
+ * present, anchor unresolvable -> UNRESOLVABLE_RECORD
28
+ * a verdict this build does not know -> VERIFICATION_FAILED / VERIFIER_ERROR
29
+ *
30
+ * That last line is the fail-closed edge: an unrecognised verdict string from
31
+ * somebody's report is never allowed to become a pass.
32
+ *
33
+ * One deliberate asymmetry, stated here so nobody discovers it in production:
34
+ * `verify-run` reports UNVERIFIED when required evidence is missing and
35
+ * INCONCLUSIVE when a level has no runtime pathway. Both are real exit codes
36
+ * and both stay exactly as they are. As outcomes, both are NOT_CHECKED — the
37
+ * run did not reach a judgement, and rendering a missing binding as a failed
38
+ * verification is the defect this layer exists to prevent. A consumer that
39
+ * should refuse either way still refuses: refusal is its policy, and `blocks`
40
+ * is not a permission slip.
41
+ */
42
+
43
+ import { decideOutcome, OUTCOME_CODES } from "./outcomes.mjs";
44
+ import { PROFILE_ID, makeProfileReference } from "./profile-ref.mjs";
45
+
46
+ export const BRIDGE_VERSION = "CG-OUT-BRIDGE/1";
47
+
48
+ const VERDICTS_KNOWN = Object.freeze(["VERIFIED", "INVALID", "UNVERIFIED", "INCONCLUSIVE"]);
49
+
50
+ /**
51
+ * Outcome for a `runVerification` report (the verify-run surface).
52
+ * Returns the CG-OUT/1 result object, or an ABSENT result when no report was
53
+ * produced at all.
54
+ */
55
+ export function outcomeForVerificationReport(report) {
56
+ if (!report || typeof report !== "object" || !report.verdict || typeof report.verdict !== "object") {
57
+ return decideOutcome({ presented: false });
58
+ }
59
+ const { verdict, code, reason, requiredMissing } = report.verdict;
60
+ const presented = report.observed?.present ?? {};
61
+ const anyPresent = ["evidence", "intent", "policy", "trace"].some((k) => presented[k] === true);
62
+ if (!anyPresent && !report.observed?.receiptId) {
63
+ return decideOutcome({ presented: false });
64
+ }
65
+
66
+ if (!VERDICTS_KNOWN.includes(verdict)) {
67
+ return decideOutcome({
68
+ presented: true,
69
+ record: { evaluated: true, ok: false, code: "VERIFIER_ERROR", reason: `unknown verdict: ${JSON.stringify(verdict)}` },
70
+ });
71
+ }
72
+
73
+ if (verdict === "VERIFIED") {
74
+ return decideOutcome({ presented: true, record: { evaluated: true, ok: true } });
75
+ }
76
+
77
+ if (verdict === "INVALID") {
78
+ return decideOutcome({
79
+ presented: true,
80
+ record: { evaluated: true, ok: false, code: code ?? "VERIFIER_ERROR", reason: reason ?? null },
81
+ });
82
+ }
83
+
84
+ // UNVERIFIED and INCONCLUSIVE: presented and deliberately not judged.
85
+ const why = Array.isArray(requiredMissing) && requiredMissing.length
86
+ ? `required bindings not present: ${requiredMissing.join(", ")}`
87
+ : reason ?? "the verifier did not reach a judgement for this record";
88
+ return decideOutcome({ presented: true, record: { evaluated: false, reason: why } });
89
+ }
90
+
91
+ /**
92
+ * Outcome for a PSAR/1 `verifyAuthorizationReceipt` result.
93
+ *
94
+ * result the verifier's own { decision, code, ... }
95
+ * receipt optional, only to read the version a receipt claims
96
+ *
97
+ * A receipt claiming a version this build does not implement is NOT_CHECKED
98
+ * with the version named, even though PSAR/1's own `decision` stays BLOCK: the
99
+ * decision is what this build does under its fail-closed policy, the outcome is
100
+ * what a reader may conclude. They differ here, and the difference is the point.
101
+ */
102
+ export function outcomeForPsarResult(result, { receipt } = {}) {
103
+ if (!result || typeof result !== "object") return decideOutcome({ presented: false });
104
+ const claimed = receipt && typeof receipt === "object" && typeof receipt.v === "string" ? receipt.v : null;
105
+ if (claimed && claimed !== "PSAR/1") {
106
+ return decideOutcome({ presented: true, record: { evaluated: false, version: claimed } });
107
+ }
108
+ if (result.decision === "PASS") {
109
+ return decideOutcome({ presented: true, record: { evaluated: true, ok: true } });
110
+ }
111
+ if (result.decision === "BLOCK") {
112
+ const code = typeof result.code === "string" ? result.code : "VERIFIER_ERROR";
113
+ return decideOutcome({
114
+ presented: true,
115
+ record: { evaluated: true, ok: false, code, reason: Array.isArray(result.reasons) ? result.reasons[0] ?? null : null },
116
+ });
117
+ }
118
+ return decideOutcome({
119
+ presented: true,
120
+ record: {
121
+ evaluated: true,
122
+ ok: false,
123
+ code: "VERIFIER_ERROR",
124
+ reason: `unknown decision: ${JSON.stringify(result.decision)}`,
125
+ },
126
+ });
127
+ }
128
+
129
+ /**
130
+ * What an authorization-dependent system may DO with an outcome.
131
+ *
132
+ * This is the function that turns a vocabulary into behaviour, and the two
133
+ * lines that matter are the first two: an absent record and a record nobody
134
+ * evaluated both yield `NONE`, never `PASS` and never `BLOCK`. A risk engine
135
+ * that treats "no receipt" as "no objection" is the failure this prevents, and
136
+ * so is one that treats it as an objection: both are decisions the facts do not
137
+ * support.
138
+ *
139
+ * VERIFIED -> PASS
140
+ * VERIFICATION_FAILED / UNRESOLVABLE_RECORD -> BLOCK
141
+ * ABSENT / NOT_CHECKED -> NONE (no decision, ever)
142
+ */
143
+ export function authorizationDecision(outcome) {
144
+ const name = outcome && typeof outcome === "object" ? outcome.outcome : outcome;
145
+ if (name === "VERIFIED") return Object.freeze({ decision: "PASS", reason: null });
146
+ if (name === "VERIFICATION_FAILED") {
147
+ return Object.freeze({ decision: "BLOCK", reason: outcome?.code ?? "VERIFICATION_FAILED" });
148
+ }
149
+ if (name === "UNRESOLVABLE_RECORD") {
150
+ return Object.freeze({ decision: "BLOCK", reason: OUTCOME_CODES.UNRESOLVABLE_RECORD });
151
+ }
152
+ if (name === "ABSENT") {
153
+ return Object.freeze({ decision: "NONE", reason: "no record was presented — nothing to decide on" });
154
+ }
155
+ if (name === "NOT_CHECKED") {
156
+ return Object.freeze({ decision: "NONE", reason: "the record was presented and evaluated by nobody" });
157
+ }
158
+ return Object.freeze({ decision: "BLOCK", reason: "VERIFIER_ERROR: unknown outcome" });
159
+ }
160
+
161
+ /**
162
+ * The pointer a protocol would carry alongside a receipt: which receipt, which
163
+ * profile, which version. Nothing about the verdict travels with it.
164
+ */
165
+ export function profileReferenceFor(receiptId) {
166
+ return makeProfileReference({ receiptId });
167
+ }
168
+
169
+ export { PROFILE_ID };
package/outcomes.mjs ADDED
@@ -0,0 +1,220 @@
1
+ /**
2
+ * CoreGuard Outcome Layer (CG-OUT/1) — the words above the reject codes.
3
+ *
4
+ * A reject code describes a record that was PRESENTED and CHECKED. It has no
5
+ * way to say "nobody handed us one", and rendering that silence as a failure
6
+ * is how an opt-in layer dies: every party that never adopted is scored as
7
+ * having failed a verification it never took part in.
8
+ *
9
+ * So this layer sits above the codes and answers a different question — what is
10
+ * a consumer allowed to conclude — with five outcomes and no sixth:
11
+ *
12
+ * VERIFIED the record was evaluated and its checks passed
13
+ * VERIFICATION_FAILED the record was evaluated and a check failed, named
14
+ * ABSENT no record was presented; never a failure of a record
15
+ * NOT_CHECKED a layer was presented and not evaluated; claims nothing
16
+ * UNRESOLVABLE_RECORD a present, well-formed record whose anchor cannot be
17
+ * resolved; not a failure of the record, not an absence
18
+ *
19
+ * Three layers, three answers. A run can be VERIFIED at the record layer,
20
+ * `matched` at the identity layer and `absent` at the anchor layer at once, and
21
+ * the composite outcome names the weakest layer instead of a single PASS/BLOCK
22
+ * hiding the only interesting fact in the run.
23
+ *
24
+ * BOUNDARY (standing, load-bearing):
25
+ * - ABSENT and NOT_CHECKED NEVER travel as BLOCK. A caller that maps them to
26
+ * a refusal is reporting a decision it did not make.
27
+ * - This layer decides nothing about quality, safety or delivery: VERIFIED
28
+ * means the receipt's own checks passed, never that the result was right.
29
+ * - It is deterministic and pure: no clock, no network, no keys. The caller
30
+ * supplies measured facts, not opinions, and nothing here trusts a string
31
+ * it did not check against a frozen set.
32
+ */
33
+
34
+ export const OUTCOME_VERSION = "CG-OUT/1";
35
+
36
+ /** The five outcomes. Adding one is a schema change; none may be renamed. */
37
+ export const OUTCOMES = Object.freeze([
38
+ "VERIFIED",
39
+ "VERIFICATION_FAILED",
40
+ "ABSENT",
41
+ "NOT_CHECKED",
42
+ "UNRESOLVABLE_RECORD",
43
+ ]);
44
+
45
+ /**
46
+ * The codes this layer owns. They appear ONLY beside their own outcome and are
47
+ * never used as a BLOCK reason: collapsing them into the reject vocabulary is
48
+ * the defect this file exists to prevent.
49
+ */
50
+ export const OUTCOME_CODES = Object.freeze({
51
+ ABSENT: "ABSENT",
52
+ NOT_CHECKED: "NOT_CHECKED",
53
+ UNRESOLVABLE_RECORD: "UNRESOLVABLE_RECORD",
54
+ });
55
+
56
+ /**
57
+ * Outcomes that must never be rendered as a refusal, by anybody, anywhere.
58
+ * VERIFIED is on the list for the same reason ABSENT is: a pass is not a
59
+ * refusal either, and a caller that renders it as one is reporting a decision
60
+ * nobody made. Only VERIFICATION_FAILED and UNRESOLVABLE_RECORD may block.
61
+ */
62
+ export const NON_BLOCKING_OUTCOMES = Object.freeze(["VERIFIED", "ABSENT", "NOT_CHECKED"]);
63
+
64
+ /** The only two outcomes that may be presented as a refusal. */
65
+ export const BLOCKING_OUTCOMES = Object.freeze(["VERIFICATION_FAILED", "UNRESOLVABLE_RECORD"]);
66
+
67
+ /** Facts a caller may supply. Anything else is ignored, never inferred. */
68
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
69
+
70
+ const layerVerdict = (layer) => {
71
+ if (!isObject(layer)) return { evaluated: false, stated: false };
72
+ return {
73
+ evaluated: layer.evaluated === true,
74
+ stated: true,
75
+ ok: layer.ok === true,
76
+ code: typeof layer.code === "string" ? layer.code : null,
77
+ reason: typeof layer.reason === "string" ? layer.reason : null,
78
+ outcome: typeof layer.outcome === "string" ? layer.outcome : null,
79
+ present: layer.present === true,
80
+ version: typeof layer.version === "string" ? layer.version : null,
81
+ };
82
+ };
83
+
84
+ const result = (outcome, code, reason, layers, detail) => {
85
+ if (!OUTCOMES.includes(outcome)) throw new Error(`unknown outcome: ${outcome}`);
86
+ return Object.freeze({
87
+ outcome,
88
+ code: code ?? null,
89
+ reason,
90
+ layers,
91
+ blocks: BLOCKING_OUTCOMES.includes(outcome),
92
+ outcomeVersion: OUTCOME_VERSION,
93
+ detail: detail ?? null,
94
+ });
95
+ };
96
+
97
+ /**
98
+ * decideOutcome({ presented, record, anchor })
99
+ *
100
+ * presented true only if a record was actually handed to the verifier
101
+ * record { evaluated, ok, code?, reason?, version? }
102
+ * anchor { present, evaluated, outcome? } where outcome is one of
103
+ * "verified" | "absent" | "not_checked" | "unresolvable"
104
+ *
105
+ * Precedence is deliberate and documented, because the order IS the policy:
106
+ * 1. absent — nothing was presented
107
+ * 2. not checked — the record layer never evaluated it
108
+ * 3. failed — the record layer evaluated it and a check failed
109
+ * 4. not checked — the record is fine but the anchor layer never ran
110
+ * 5. unresolvable — the anchor layer ran and could not resolve
111
+ * 6. verified
112
+ */
113
+ export function decideOutcome({ presented, record, anchor } = {}) {
114
+ const recordLayer = layerVerdict(record);
115
+ const anchorLayer = layerVerdict(anchor);
116
+ const layers = Object.freeze({
117
+ record: recordLayer.stated
118
+ ? { evaluated: recordLayer.evaluated, ok: recordLayer.evaluated && recordLayer.ok, code: recordLayer.code }
119
+ : { evaluated: false, ok: null, code: null },
120
+ anchor: {
121
+ present: anchorLayer.present,
122
+ evaluated: anchorLayer.evaluated,
123
+ outcome: anchorLayer.outcome,
124
+ },
125
+ });
126
+
127
+ if (presented !== true) {
128
+ return result(
129
+ "ABSENT",
130
+ OUTCOME_CODES.ABSENT,
131
+ "no record was presented — silence is not a failed verification",
132
+ layers,
133
+ );
134
+ }
135
+
136
+ if (!recordLayer.evaluated) {
137
+ // A caller that knows WHY a layer was skipped says so; otherwise the layer
138
+ // names the version it did not implement, and only then falls back to the
139
+ // generic sentence. The reason is never dropped on the floor: "not checked"
140
+ // without a why is the vague answer this layer exists to replace.
141
+ const why = recordLayer.version
142
+ ? `the record layer did not evaluate version ${recordLayer.version}`
143
+ : recordLayer.reason
144
+ ? recordLayer.reason
145
+ : "the record layer was not evaluated";
146
+ return result("NOT_CHECKED", OUTCOME_CODES.NOT_CHECKED, why, layers, {
147
+ version: recordLayer.version,
148
+ });
149
+ }
150
+
151
+ if (!recordLayer.ok) {
152
+ return result(
153
+ "VERIFICATION_FAILED",
154
+ recordLayer.code ?? "VERIFIER_ERROR",
155
+ recordLayer.reason ?? "a record-layer check failed",
156
+ layers,
157
+ );
158
+ }
159
+
160
+ if (anchorLayer.present && !anchorLayer.evaluated) {
161
+ return result(
162
+ "NOT_CHECKED",
163
+ OUTCOME_CODES.NOT_CHECKED,
164
+ "the anchor layer was present and deliberately not evaluated",
165
+ layers,
166
+ );
167
+ }
168
+
169
+ if (anchorLayer.evaluated && anchorLayer.outcome === "unresolvable") {
170
+ return result(
171
+ "UNRESOLVABLE_RECORD",
172
+ OUTCOME_CODES.UNRESOLVABLE_RECORD,
173
+ "the record is well formed and its anchor cannot be resolved",
174
+ layers,
175
+ );
176
+ }
177
+
178
+ return result("VERIFIED", null, "the record layer evaluated the record and it passed", layers);
179
+ }
180
+
181
+ /**
182
+ * A caller-side guard for the one mistake that would quietly break opt-in:
183
+ * turning an absence into a refusal. Returns the outcome unchanged when it is
184
+ * safe to render, and throws when a non-blocking outcome is about to be
185
+ * presented as a block.
186
+ */
187
+ export function assertNotRenderedAsBlock(outcome) {
188
+ if (!OUTCOMES.includes(outcome)) throw new Error(`unknown outcome: ${outcome}`);
189
+ if (NON_BLOCKING_OUTCOMES.includes(outcome)) {
190
+ throw new Error(`${outcome} must never travel as BLOCK — it is not a decision`);
191
+ }
192
+ return outcome;
193
+ }
194
+
195
+ /** Self-check: the layer's own invariants, for callers that cannot run tests. */
196
+ export function selfCheck() {
197
+ const absent = decideOutcome({ presented: false });
198
+ const unchecked = decideOutcome({ presented: true, record: { evaluated: false } });
199
+ const failed = decideOutcome({
200
+ presented: true,
201
+ record: { evaluated: true, ok: false, code: "BAD_DIGEST" },
202
+ });
203
+ const verified = decideOutcome({ presented: true, record: { evaluated: true, ok: true } });
204
+ const checks = [
205
+ { name: "absent is ABSENT", pass: absent.outcome === "ABSENT" },
206
+ { name: "absent never blocks", pass: absent.blocks === false },
207
+ { name: "unevaluated is NOT_CHECKED", pass: unchecked.outcome === "NOT_CHECKED" },
208
+ { name: "unevaluated never blocks", pass: unchecked.blocks === false },
209
+ { name: "failed keeps its code", pass: failed.outcome === "VERIFICATION_FAILED" && failed.code === "BAD_DIGEST" },
210
+ { name: "failed blocks", pass: failed.blocks === true },
211
+ { name: "verified is VERIFIED", pass: verified.outcome === "VERIFIED" },
212
+ { name: "every outcome reachable", pass: new Set([absent, unchecked, failed, verified].map((r) => r.outcome)).size >= 4 },
213
+ ];
214
+ return Object.freeze({
215
+ outcomeVersion: OUTCOME_VERSION,
216
+ outcomes: OUTCOMES,
217
+ checks,
218
+ ok: checks.every((c) => c.pass),
219
+ });
220
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@coreguard/agent-commerce",
3
- "version": "0.1.2",
4
- "description": "CoreGuard Agent Commerce: consent receipts (CGCR/1) and fail-closed execution verification (AGR/1) for agentic purchases — SDK, REST surface, and a stdio MCP server (JSON-RPC 2.0, offline, zero keys)",
3
+ "version": "0.1.4",
4
+ "description": "CoreGuard Agent Commerce: consent receipts (CGCR/1) and fail-closed execution verification (AGR/1) for agentic purchases — SDK, REST surface, and a stdio MCP server (26 tools, JSON-RPC 2.0, offline, zero keys)",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
7
7
  "exports": {
@@ -12,25 +12,71 @@
12
12
  "./firewall.mjs": "./firewall.mjs",
13
13
  "./risk.mjs": "./risk.mjs",
14
14
  "./risk-cli.mjs": "./risk-cli.mjs",
15
- "./attest.mjs": "./attest.mjs"
15
+ "./outcomes.mjs": "./outcomes.mjs",
16
+ "./outcomes-bridge.mjs": "./outcomes-bridge.mjs",
17
+ "./identity.mjs": "./identity.mjs",
18
+ "./profile-ref.mjs": "./profile-ref.mjs",
19
+ "./attest.mjs": "./attest.mjs",
20
+ "./aer1.mjs": "./aer1.mjs",
21
+ "./observations.mjs": "./observations.mjs",
22
+ "./anchor.mjs": "./anchor.mjs",
23
+ "./composition.mjs": "./composition.mjs",
24
+ "./reference.mjs": "./reference.mjs",
25
+ "./trust.mjs": "./trust.mjs",
26
+ "./spend.mjs": "./spend.mjs",
27
+ "./decision.mjs": "./decision.mjs",
28
+ "./control-plane.mjs": "./control-plane.mjs",
29
+ "./control-plane-http.mjs": "./control-plane-http.mjs",
30
+ "./control-plane-cli.mjs": "./control-plane-cli.mjs",
31
+ "./prod/schema.mjs": "./prod/schema.mjs",
32
+ "./prod/sqlite-storage.mjs": "./prod/sqlite-storage.mjs",
33
+ "./prod/migrate.mjs": "./prod/migrate.mjs",
34
+ "./prod/rbac.mjs": "./prod/rbac.mjs",
35
+ "./prod/observability.mjs": "./prod/observability.mjs",
36
+ "./prod/kms-anchor.mjs": "./prod/kms-anchor.mjs",
37
+ "./machine-economy.mjs": "./machine-economy.mjs",
38
+ "./cgcp-mcp-tools.mjs": "./cgcp-mcp-tools.mjs"
16
39
  },
17
40
  "bin": {
18
41
  "coreguard-agent-commerce-mcp": "./bin/mcp.mjs"
19
42
  },
20
43
  "files": [
21
- "index.mjs",
22
- "index.d.ts",
23
- "mcp.mjs",
24
- "http.mjs",
44
+ "README.md",
45
+ "aer1.mjs",
46
+ "anchor.mjs",
47
+ "attest.mjs",
48
+ "bin/mcp.mjs",
49
+ "cgcp-mcp-tools.mjs",
25
50
  "client.mjs",
51
+ "composition.mjs",
52
+ "consumption-store.mjs",
53
+ "control-plane-cli.mjs",
54
+ "control-plane-http.mjs",
55
+ "control-plane.mjs",
56
+ "decision.mjs",
26
57
  "firewall.mjs",
27
- "risk.mjs",
28
- "risk-cli.mjs",
29
- "attest.mjs",
58
+ "http.mjs",
59
+ "identity.mjs",
60
+ "index.d.ts",
61
+ "index.mjs",
62
+ "machine-economy.mjs",
63
+ "mcp.mjs",
64
+ "observations.mjs",
65
+ "outcomes-bridge.mjs",
66
+ "outcomes.mjs",
30
67
  "policy-context.mjs",
31
- "consumption-store.mjs",
32
- "bin/mcp.mjs",
33
- "README.md"
68
+ "prod/kms-anchor.mjs",
69
+ "prod/migrate.mjs",
70
+ "prod/observability.mjs",
71
+ "prod/rbac.mjs",
72
+ "prod/schema.mjs",
73
+ "prod/sqlite-storage.mjs",
74
+ "profile-ref.mjs",
75
+ "reference.mjs",
76
+ "risk-cli.mjs",
77
+ "risk.mjs",
78
+ "spend.mjs",
79
+ "trust.mjs"
34
80
  ],
35
81
  "engines": {
36
82
  "node": ">=18"
@@ -58,7 +104,11 @@
58
104
  "fail-closed",
59
105
  "agentic-payments",
60
106
  "cgep",
61
- "coreguard"
107
+ "coreguard",
108
+ "x402",
109
+ "machine-economy",
110
+ "robotics",
111
+ "delegation"
62
112
  ],
63
113
  "license": "MIT"
64
114
  }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * M4 (BUILT as interfaces/local adapters): KMS and audit anchor abstractions.
3
+ * NOT_BUILT: real KMS/HSM integration, managed external witness/on-chain anchor service.
4
+ */
5
+ import { createHash, createHmac, randomUUID } from "node:crypto";
6
+
7
+ export function createLocalKeyProvider({ keys = {} } = {}) {
8
+ const store = new Map(Object.entries(keys));
9
+ return {
10
+ kind: "local-dev-only",
11
+ async getActiveKey(keyId = "default") {
12
+ const k = store.get(keyId);
13
+ if (!k) throw new Error(`key not found: ${keyId}`);
14
+ return { keyId, material: k };
15
+ },
16
+ async rotateKey(keyId = "default", material) {
17
+ const next = material || randomUUID().replace(/-/g, "") + randomUUID().replace(/-/g, "");
18
+ store.set(keyId, next);
19
+ return { keyId, rotatedAt: new Date().toISOString(), fingerprint: fingerprint(next) };
20
+ },
21
+ async sign(keyId, payload) {
22
+ const { material } = await this.getActiveKey(keyId);
23
+ const sig = createHmac("sha256", String(material)).update(payload).digest("hex");
24
+ return { alg: "HMAC-SHA256", keyId, sig, fingerprint: fingerprint(material) };
25
+ },
26
+ };
27
+ }
28
+
29
+ function fingerprint(material) { return "sha256:" + createHash("sha256").update(String(material)).digest("hex").slice(0, 16); }
30
+
31
+ export function createAnchorProvider({ mode = "local-file", hmacKey = null } = {}) {
32
+ return {
33
+ kind: mode,
34
+ async anchor(head) {
35
+ const base = { headHash: head.headHash, length: head.length, at: new Date().toISOString(), mode };
36
+ if (hmacKey) base.hmacSha256 = createHmac("sha256", String(hmacKey)).update(JSON.stringify({ headHash: base.headHash, length: base.length })).digest("hex");
37
+ base.receiptId = "anchor_" + randomUUID();
38
+ base.boundary = mode === "local-file" ? "local witness only; NOT_BUILT external witness" : "adapter boundary; external service NOT_BUILT in this environment";
39
+ return base;
40
+ },
41
+ async verify(receipt, head) {
42
+ const headOk = receipt.headHash === head.headHash && receipt.length === head.length;
43
+ let hmacOk = true;
44
+ if (receipt.hmacSha256) {
45
+ if (!hmacKey) hmacOk = false;
46
+ else hmacOk = receipt.hmacSha256 === createHmac("sha256", String(hmacKey)).update(JSON.stringify({ headHash: head.headHash, length: head.length })).digest("hex");
47
+ }
48
+ return { ok: headOk && hmacOk, headOk, hmacOk, mode };
49
+ },
50
+ };
51
+ }
@@ -0,0 +1,73 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { openSqliteStorage } from "./sqlite-storage.mjs";
3
+ import { canonicalJson, verifyAuditChain } from "../control-plane.mjs";
4
+
5
+ export function loadCgcp1Store(storePath) {
6
+ const data = JSON.parse(readFileSync(storePath, "utf8"));
7
+ if (data?.schema !== "coreguard.control-plane/1") throw new Error(`expected coreguard.control-plane/1, got ${data?.schema}`);
8
+ return data;
9
+ }
10
+
11
+ export function migrateCgcp1ToSqlite({ sourcePath, targetPath, tenantId = "default", tenantName = "Migrated CGCP/1" } = {}) {
12
+ const src = loadCgcp1Store(sourcePath);
13
+ const chain = verifyAuditChain(src);
14
+ if (!chain.ok) throw new Error(`source audit chain invalid: ${chain.reason} at ${chain.brokenAt}`);
15
+ const db = openSqliteStorage(targetPath);
16
+ const report = { tenantId, sourceSchema: src.schema, ok: false, counts: {} };
17
+ db.tx(() => {
18
+ db.ensureTenant({ id: tenantId, name: tenantName, status: "active", createdAt: src.createdAt ?? new Date().toISOString(), metadata: { migratedFrom: sourcePath, migratedAt: new Date().toISOString(), sourceBoundary: src.boundary ?? null } });
19
+ for (const agent of Object.values(src.agents ?? {})) {
20
+ db.upsertAgent(tenantId, { id: agent.id, status: agent.status, policyId: agent.policyId ?? null, name: agent.name ?? null, metadata: agent.metadata ?? {}, revokedAt: agent.revokedAt ?? null, revocationReason: agent.revocationReason ?? null });
21
+ }
22
+ for (const policy of Object.values(src.policies ?? {})) {
23
+ db.upsertPolicy(tenantId, { id: policy.id, status: policy.status ?? "active", metadata: policy.metadata ?? {} });
24
+ for (const v of (policy.versions ?? [])) {
25
+ db.upsertPolicyVersion(tenantId, policy.id, v.version, v.spec ?? {}, v.createdAt ?? src.createdAt, v.createdBy ?? null);
26
+ }
27
+ }
28
+ for (const approval of Object.values(src.approvals ?? {})) {
29
+ db.putApproval(tenantId, {
30
+ id: approval.id, agentId: approval.agentId, policyId: approval.policyId, status: approval.status,
31
+ merchant: approval.merchant ?? null, address: approval.address ?? null, amountMinor: approval.amountMinor ?? null,
32
+ currency: approval.currency ?? null, requestedBy: approval.requestedBy ?? null, decidedBy: approval.decidedBy ?? null,
33
+ reason: approval.reason ?? null,
34
+ createdAt: approval.createdAt ?? approval.requestedAt ?? src.createdAt ?? new Date().toISOString(),
35
+ updatedAt: approval.updatedAt ?? approval.decidedAt ?? approval.requestedAt ?? approval.createdAt ?? src.createdAt ?? new Date().toISOString(),
36
+ expiresAt: approval.expiresAt ?? null, hash: approval.hash ?? null, metadata: { ...(approval.metadata ?? {}), requestedAt: approval.requestedAt ?? null, decidedAt: approval.decidedAt ?? null },
37
+ });
38
+ }
39
+ for (const ex of (src.executions ?? [])) {
40
+ db.putExecution(tenantId, {
41
+ id: ex.id, agentId: ex.agentId, policyId: ex.policyId, approvalId: ex.approvalId ?? null, merchant: ex.merchant ?? null,
42
+ address: ex.address ?? null, amountMinor: ex.amountMinor, currency: ex.currency ?? null, receiptId: ex.receiptId ?? null,
43
+ verdict: ex.verdict ?? null, orderRef: ex.orderRef ?? null, createdAt: ex.createdAt ?? ex.at ?? src.createdAt ?? new Date().toISOString(), hash: ex.hash ?? null, metadata: ex.metadata ?? {},
44
+ });
45
+ }
46
+ for (const v of (src.verifications ?? [])) {
47
+ db.putVerification(tenantId, { ...v, createdAt: v.createdAt ?? v.at ?? src.createdAt ?? new Date().toISOString() });
48
+ }
49
+ for (const r of Object.values(src.revocations ?? {})) {
50
+ db.putRevocation(tenantId, { targetType: r.targetType, targetId: r.targetId, reason: r.reason ?? null, createdAt: r.createdAt ?? r.at ?? src.createdAt ?? new Date().toISOString(), metadata: r.metadata ?? {} });
51
+ }
52
+ for (const a of (src.audit ?? [])) {
53
+ db.appendAudit(tenantId, { seq: a.seq, type: a.type, at: a.at, detail: a.detail ?? {}, prevHash: a.prevHash, hash: a.hash, actor: a.actor ?? null, requestId: a.requestId ?? null, source: a.source ?? null });
54
+ }
55
+ report.counts = {
56
+ agents: Object.keys(src.agents ?? {}).length,
57
+ policies: Object.keys(src.policies ?? {}).length,
58
+ approvals: Object.keys(src.approvals ?? {}).length,
59
+ executions: (src.executions ?? []).length,
60
+ verifications: (src.verifications ?? []).length,
61
+ revocations: Object.keys(src.revocations ?? {}).length,
62
+ audit: (src.audit ?? []).length,
63
+ };
64
+ report.ok = true;
65
+ });
66
+ const exported = db.exportTenantState(tenantId);
67
+ report.exportedCounts = {
68
+ agents: exported.agents.length, policies: exported.policies.length, approvals: exported.approvals.length,
69
+ executions: exported.executions.length, verifications: exported.verifications.length, revocations: exported.revocations.length, audit: exported.audit.length,
70
+ };
71
+ report.parity = JSON.stringify(report.counts) === JSON.stringify(report.exportedCounts);
72
+ return { report, db, source: src };
73
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * M3 (BUILT as interfaces/hooks): observability hooks for prod control plane.
3
+ * NOT_BUILT: managed Prometheus/Grafana/OTel collector/SLO paging.
4
+ */
5
+ export function createMetrics() {
6
+ const counters = new Map();
7
+ const timings = [];
8
+ return {
9
+ inc(name, labels = {}, n = 1) {
10
+ const k = JSON.stringify([name, labels]);
11
+ counters.set(k, (counters.get(k) ?? 0) + n);
12
+ },
13
+ observe(name, ms, labels = {}) { timings.push({ name, ms, labels, at: Date.now() }); },
14
+ snapshot() {
15
+ return {
16
+ counters: [...counters.entries()].map(([k, v]) => { const [name, labels] = JSON.parse(k); return { name, labels, value: v }; }),
17
+ timings: timings.slice(-200),
18
+ };
19
+ },
20
+ };
21
+ }
22
+
23
+ export function createHealth({ storage, tenantId = "default" } = {}) {
24
+ return {
25
+ live() { return { ok: true, status: "live", at: new Date().toISOString() }; },
26
+ ready() {
27
+ try {
28
+ const t = storage?.getTenant?.(tenantId);
29
+ return { ok: !!t, status: t ? "ready" : "not_ready", tenantId, at: new Date().toISOString() };
30
+ } catch (err) {
31
+ return { ok: false, status: "not_ready", error: err?.message ?? String(err), at: new Date().toISOString() };
32
+ }
33
+ },
34
+ };
35
+ }