@coreguard/agent-commerce 0.1.3 → 0.1.5

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,142 @@
1
+ /**
2
+ * CGCP/1 MCP Wave 2 mapping tools - deterministic, file-backed control plane operations.
3
+ * BOUNDARIES: self-hosted single-host file-backed control plane; no distributed HA,
4
+ * no external IdP/KMS/witness, no payment custody/broadcast. VERIFIED != SAFE.
5
+ */
6
+ import { createControlPlane, verifyAuditChain, CONTROL_PLANE_BOUNDARY } from "./control-plane.mjs";
7
+
8
+ export const CGCP_MCP_BOUNDARY = CONTROL_PLANE_BOUNDARY +
9
+ " MCP Wave 2 tools are CGCP/1 mappings; they do not create blockchain receipts, do not custody funds, and do not prove external settlement.";
10
+
11
+ function reqString(args, k) { const v = args?.[k]; if (typeof v !== "string" || !v) throw new Error(`${k} is required`); return v; }
12
+ function optString(args, k) { const v = args?.[k]; if (v === undefined || v === null) return undefined; if (typeof v !== "string") throw new Error(`${k} must be a string`); return v; }
13
+
14
+ function withCp(storePath) {
15
+ return createControlPlane({ storePath, create: true });
16
+ }
17
+
18
+ export function createIntent(args = {}) {
19
+ const storePath = reqString(args, "storePath");
20
+ const cp = withCp(storePath);
21
+ const approval = cp.requestApproval({
22
+ id: optString(args, "intentId"),
23
+ agentId: reqString(args, "agentId"),
24
+ policyId: optString(args, "policyId"),
25
+ merchant: optString(args, "merchant"),
26
+ address: optString(args, "address"),
27
+ amountMinor: optString(args, "amountMinor"),
28
+ currency: optString(args, "currency"),
29
+ requestedBy: optString(args, "requestedBy"),
30
+ expiresAt: optString(args, "expiresAt"),
31
+ });
32
+ return { type: "cgcp_intent", spec: "CGCP/1", intent: approval, mapping: "coreguard_create_intent -> CGCP requestApproval (intent/approval request)", boundary: CGCP_MCP_BOUNDARY };
33
+ }
34
+
35
+ export function issueReceipt(args = {}) {
36
+ const storePath = reqString(args, "storePath");
37
+ const cp = withCp(storePath);
38
+ const execution = cp.recordExecution({
39
+ id: optString(args, "receiptId"),
40
+ agentId: reqString(args, "agentId"),
41
+ policyId: optString(args, "policyId"),
42
+ approvalId: optString(args, "approvalId"),
43
+ merchant: optString(args, "merchant"),
44
+ address: optString(args, "address"),
45
+ amountMinor: optString(args, "amountMinor"),
46
+ currency: optString(args, "currency"),
47
+ status: optString(args, "status") ?? "executed",
48
+ txRef: optString(args, "txRef"),
49
+ metadata: args.metadata && typeof args.metadata === "object" ? args.metadata : undefined,
50
+ });
51
+ return { type: "cgcp_receipt", spec: "CGCP/1", receipt: execution, mapping: "coreguard_issue_receipt -> CGCP recordExecution (execution receipt record)", boundary: CGCP_MCP_BOUNDARY };
52
+ }
53
+
54
+ export function verifyReceipt(args = {}) {
55
+ const storePath = reqString(args, "storePath");
56
+ const cp = withCp(storePath);
57
+ const report = cp.auditReport({ limit: 10000 });
58
+ const chain = report.chain;
59
+ const receiptId = optString(args, "receiptId");
60
+ let receipt = null;
61
+ let receiptFound = false;
62
+ if (receiptId) {
63
+ receipt = (report.recentExecutions || []).find((e) => e.id === receiptId) ||
64
+ (report.recentVerifications || []).find((v) => v.id === receiptId || v.receiptId === receiptId) ||
65
+ null;
66
+ receiptFound = !!receipt;
67
+ }
68
+ const issues = [];
69
+ if (!chain?.ok) issues.push("AUDIT_CHAIN_INVALID");
70
+ if (receiptId && !receiptFound) issues.push("RECEIPT_NOT_FOUND");
71
+ return {
72
+ type: "cgcp_receipt_verification", spec: "CGCP/1",
73
+ verdict: issues.length === 0 ? "VERIFIED" : "INVALID",
74
+ issues,
75
+ receiptId: receiptId ?? null,
76
+ receiptFound,
77
+ receipt,
78
+ auditChain: chain,
79
+ mapping: "coreguard_verify_receipt -> CGCP audit chain verification + receipt lookup in audit report",
80
+ boundary: CGCP_MCP_BOUNDARY,
81
+ };
82
+ }
83
+
84
+ export function checkLimits(args = {}) {
85
+ const storePath = reqString(args, "storePath");
86
+ const cp = withCp(storePath);
87
+ const decision = cp.evaluate({
88
+ agentId: reqString(args, "agentId"),
89
+ policyId: optString(args, "policyId"),
90
+ merchant: optString(args, "merchant"),
91
+ address: optString(args, "address"),
92
+ amountMinor: optString(args, "amountMinor"),
93
+ currency: optString(args, "currency"),
94
+ approvalId: optString(args, "approvalId"),
95
+ });
96
+ return { type: "cgcp_limit_check", spec: "CGCP/1", decision, mapping: "coreguard_check_limits -> CGCP evaluate (policy/limit decision)", boundary: CGCP_MCP_BOUNDARY };
97
+ }
98
+
99
+ export function revokeConsent(args = {}) {
100
+ const storePath = reqString(args, "storePath");
101
+ const cp = withCp(storePath);
102
+ const targetType = reqString(args, "targetType"); // approval|agent|policy
103
+ const reason = optString(args, "reason") ?? "revoked via MCP";
104
+ let result;
105
+ if (targetType === "approval") {
106
+ result = cp.decideApproval(reqString(args, "targetId"), { decision: "rejected", decidedBy: optString(args, "decidedBy"), reason });
107
+ } else if (targetType === "agent") {
108
+ result = cp.revokeAgent(reqString(args, "targetId"), reason);
109
+ } else if (targetType === "policy") {
110
+ result = cp.revokePolicy(reqString(args, "targetId"), reason);
111
+ } else {
112
+ throw new Error("targetType must be approval, agent, or policy");
113
+ }
114
+ return { type: "cgcp_revocation", spec: "CGCP/1", targetType, targetId: args.targetId, result, mapping: "coreguard_revoke_consent -> CGCP revoke/decision mapping", boundary: CGCP_MCP_BOUNDARY };
115
+ }
116
+
117
+ export function auditTransaction(args = {}) {
118
+ const storePath = reqString(args, "storePath");
119
+ const cp = withCp(storePath);
120
+ const limit = Number.isInteger(args.limit) ? args.limit : 200;
121
+ const report = cp.auditReport({ limit });
122
+ const txRef = optString(args, "txRef");
123
+ const approvalId = optString(args, "approvalId");
124
+ const agentId = optString(args, "agentId");
125
+ const filterFn = (e) => {
126
+ const d = e?.detail || {};
127
+ if (txRef && d.txRef !== txRef && d.receiptId !== txRef && d.executionId !== txRef) return false;
128
+ if (approvalId && d.approvalId !== approvalId) return false;
129
+ if (agentId && d.agentId !== agentId) return false;
130
+ return true;
131
+ };
132
+ if (txRef || approvalId || agentId) {
133
+ report.recentAudit = (report.recentAudit || []).filter(filterFn);
134
+ report.recentExecutions = (report.recentExecutions || []).filter((e) => {
135
+ if (txRef && e.txRef !== txRef && e.id !== txRef) return false;
136
+ if (approvalId && e.approvalId !== approvalId) return false;
137
+ if (agentId && e.agentId !== agentId) return false;
138
+ return true;
139
+ });
140
+ }
141
+ return { type: "cgcp_audit_report", spec: "CGCP/1", report, mapping: "coreguard_audit_transaction -> CGCP auditReport/filter", boundary: CGCP_MCP_BOUNDARY };
142
+ }
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { pathToFileURL } from "node:url";
2
3
  /**
3
4
  * CoreGuard Control Plane CLI (CGCP/1) — operator surface over the same plane
4
5
  * the SDK and HTTP API use. Every command prints canonical JSON to stdout and
@@ -17,6 +18,7 @@
17
18
  * BOUNDARY: single-host, single-API-key. No RBAC/SSO/tenancy (NOT_BUILT).
18
19
  */
19
20
 
21
+ import { readFileSync } from "node:fs";
20
22
  import { createControlPlane, CONTROL_PLANE_VERSION, CONTROL_PLANE_BOUNDARY } from "./control-plane.mjs";
21
23
  import { startControlPlaneServer } from "./control-plane-http.mjs";
22
24
 
@@ -56,191 +58,215 @@ function out(value) {
56
58
  async function main() {
57
59
  const { positional, flags } = parseArgs(process.argv.slice(2));
58
60
  const storePath = flags.store ?? process.env.COREGUARD_CONTROL_PLANE_STORE ?? "./.coreguard/control-plane.json";
59
- const plane = createControlPlane({ storePath, lockTimeoutMs: Number(flags["lock-timeout-ms"] ?? 5000) });
61
+ const plane = createControlPlane({ storePath, lockTimeoutMs: Number(flags["lock-timeout-ms"] ?? 5000), create: positional[0] === "init" });
60
62
  const [command, sub] = positional;
63
+ const auditMeta = (flags.actor || flags["request-id"]) ? { actor: flags.actor ?? null, requestId: flags["request-id"] ?? null, source: "cli" } : null;
64
+ const dispatch = async () => {
65
+ switch (command) {
66
+ case undefined:
67
+ case "help":
68
+ out({
69
+ version: CONTROL_PLANE_VERSION,
70
+ boundary: CONTROL_PLANE_BOUNDARY,
71
+ store: storePath,
72
+ commands: [
73
+ "init",
74
+ "agent upsert|list|revoke",
75
+ "policy upsert|list|revoke",
76
+ "approval request|decide|get",
77
+ "evaluate|authorize|exec|verification",
78
+ "spend|report|verify|anchor|serve",
79
+ ],
80
+ });
81
+ return;
82
+
83
+ case "init":
84
+ out({ version: CONTROL_PLANE_VERSION, storePath, created: plane.getState().createdAt, boundary: CONTROL_PLANE_BOUNDARY });
85
+ return;
86
+
87
+ case "agent": {
88
+ if (sub === "upsert") {
89
+ out(
90
+ plane.upsertAgent({
91
+ id: requireFlag(flags, "id"),
92
+ name: flags.name ?? null,
93
+ policyId: flags.policy ?? null,
94
+ status: flags.status ?? undefined,
95
+ metadata: flags.metadata ? JSON.parse(flags.metadata) : undefined,
96
+ }),
97
+ );
98
+ return;
99
+ }
100
+ if (sub === "list") return out({ agents: plane.listAgents() });
101
+ if (sub === "revoke") return out(plane.revokeAgent(requireFlag(flags, "id"), flags.reason ?? ""));
102
+ break;
103
+ }
61
104
 
62
- switch (command) {
63
- case undefined:
64
- case "help":
65
- out({
66
- version: CONTROL_PLANE_VERSION,
67
- boundary: CONTROL_PLANE_BOUNDARY,
68
- store: storePath,
69
- commands: [
70
- "init",
71
- "agent upsert|list|revoke",
72
- "policy upsert|list|revoke",
73
- "approval request|decide|get",
74
- "evaluate|authorize|exec|verification",
75
- "spend|report|verify|serve",
76
- ],
77
- });
78
- return;
79
-
80
- case "init":
81
- out({ version: CONTROL_PLANE_VERSION, storePath, created: plane.getState().createdAt, boundary: CONTROL_PLANE_BOUNDARY });
82
- return;
83
-
84
- case "agent": {
85
- if (sub === "upsert") {
86
- out(
87
- plane.upsertAgent({
88
- id: requireFlag(flags, "id"),
89
- name: flags.name ?? null,
105
+ case "policy": {
106
+ if (sub === "upsert") {
107
+ out(
108
+ plane.upsertPolicy({
109
+ id: requireFlag(flags, "id"),
110
+ name: flags.name ?? null,
111
+ status: flags.status ?? undefined,
112
+ note: flags.note ?? null,
113
+ spendLimitMinor: flags["spend-limit"] ?? null,
114
+ dailyLimitMinor: flags["daily-limit"] ?? null,
115
+ totalLimitMinor: flags["total-limit"] ?? null,
116
+ requireApprovalAboveMinor: flags["approval-above"] ?? null,
117
+ currency: flags.currency ?? null,
118
+ allowMerchants: list(flags["allow-merchants"]),
119
+ denyMerchants: list(flags["deny-merchants"]),
120
+ allowAddresses: list(flags["allow-addresses"]),
121
+ denyAddresses: list(flags["deny-addresses"]),
122
+ }),
123
+ );
124
+ return;
125
+ }
126
+ if (sub === "list") return out({ policies: plane.listPolicies() });
127
+ if (sub === "revoke") return out(plane.revokePolicy(requireFlag(flags, "id"), flags.reason ?? ""));
128
+ break;
129
+ }
130
+
131
+ case "approval": {
132
+ if (sub === "request") {
133
+ out(
134
+ plane.requestApproval({
135
+ id: flags.id,
136
+ agentId: requireFlag(flags, "agent"),
137
+ policyId: flags.policy ?? null,
138
+ merchant: flags.merchant ?? null,
139
+ address: flags.address ?? null,
140
+ amountMinor: flags.amount ?? null,
141
+ currency: flags.currency ?? null,
142
+ requestedBy: flags.by ?? null,
143
+ expiresAt: flags.expires ?? null,
144
+ }),
145
+ );
146
+ return;
147
+ }
148
+ if (sub === "decide") {
149
+ out(
150
+ plane.decideApproval(requireFlag(flags, "id"), {
151
+ decision: requireFlag(flags, "decision"),
152
+ decidedBy: flags.by ?? null,
153
+ reason: flags.reason ?? null,
154
+ }),
155
+ );
156
+ return;
157
+ }
158
+ if (sub === "get") {
159
+ const record = plane.getApproval(requireFlag(flags, "id"));
160
+ if (!record) throw new Error("unknown approval");
161
+ out(record);
162
+ return;
163
+ }
164
+ break;
165
+ }
166
+
167
+ case "evaluate":
168
+ return out(
169
+ plane.evaluate({
170
+ agentId: requireFlag(flags, "agent"),
90
171
  policyId: flags.policy ?? null,
91
- status: flags.status ?? undefined,
92
- metadata: flags.metadata ? JSON.parse(flags.metadata) : undefined,
172
+ merchant: flags.merchant ?? null,
173
+ address: flags.address ?? null,
174
+ amountMinor: flags.amount ?? null,
175
+ currency: flags.currency ?? null,
176
+ approvalId: flags.approval ?? null,
93
177
  }),
94
178
  );
95
- return;
96
- }
97
- if (sub === "list") return out({ agents: plane.listAgents() });
98
- if (sub === "revoke") return out(plane.revokeAgent(requireFlag(flags, "id"), flags.reason ?? ""));
99
- break;
100
- }
101
179
 
102
- case "policy": {
103
- if (sub === "upsert") {
104
- out(
105
- plane.upsertPolicy({
106
- id: requireFlag(flags, "id"),
107
- name: flags.name ?? null,
108
- status: flags.status ?? undefined,
109
- note: flags.note ?? null,
110
- spendLimitMinor: flags["spend-limit"] ?? null,
111
- dailyLimitMinor: flags["daily-limit"] ?? null,
112
- totalLimitMinor: flags["total-limit"] ?? null,
113
- requireApprovalAboveMinor: flags["approval-above"] ?? null,
180
+ case "authorize":
181
+ return out(
182
+ plane.authorize({
183
+ agentId: requireFlag(flags, "agent"),
184
+ policyId: flags.policy ?? null,
185
+ merchant: flags.merchant ?? null,
186
+ address: flags.address ?? null,
187
+ amountMinor: flags.amount ?? null,
114
188
  currency: flags.currency ?? null,
115
- allowMerchants: list(flags["allow-merchants"]),
116
- denyMerchants: list(flags["deny-merchants"]),
117
- allowAddresses: list(flags["allow-addresses"]),
118
- denyAddresses: list(flags["deny-addresses"]),
189
+ approvalId: flags.approval ?? null,
119
190
  }),
120
191
  );
121
- return;
122
- }
123
- if (sub === "list") return out({ policies: plane.listPolicies() });
124
- if (sub === "revoke") return out(plane.revokePolicy(requireFlag(flags, "id"), flags.reason ?? ""));
125
- break;
126
- }
127
192
 
128
- case "approval": {
129
- if (sub === "request") {
130
- out(
131
- plane.requestApproval({
193
+ case "exec":
194
+ return out(
195
+ plane.commitExecution({
132
196
  id: flags.id,
133
197
  agentId: requireFlag(flags, "agent"),
134
198
  policyId: flags.policy ?? null,
135
199
  merchant: flags.merchant ?? null,
136
200
  address: flags.address ?? null,
137
- amountMinor: flags.amount ?? null,
201
+ amountMinor: requireFlag(flags, "amount"),
138
202
  currency: flags.currency ?? null,
139
- requestedBy: flags.by ?? null,
140
- expiresAt: flags.expires ?? null,
203
+ approvalId: flags.approval ?? null,
204
+ receiptId: flags.receipt ?? null,
205
+ verdict: flags.verdict ?? null,
206
+ orderRef: flags.order ?? null,
141
207
  }),
142
208
  );
143
- return;
144
- }
145
- if (sub === "decide") {
146
- out(
147
- plane.decideApproval(requireFlag(flags, "id"), {
148
- decision: requireFlag(flags, "decision"),
149
- decidedBy: flags.by ?? null,
150
- reason: flags.reason ?? null,
209
+
210
+ case "verification":
211
+ return out(
212
+ plane.recordVerification({
213
+ executionId: flags.execution ?? null,
214
+ receiptId: flags.receipt ?? null,
215
+ verdict: flags.verdict ?? null,
216
+ source: flags.source ?? null,
151
217
  }),
152
218
  );
219
+
220
+ case "spend":
221
+ return out(plane.spend({ agentId: flags.agent ?? null, policyId: flags.policy ?? null }));
222
+
223
+
224
+ case "report":
225
+ return out(plane.auditReport({ limit: Number(flags.limit ?? 200) }));
226
+
227
+ case "verify":
228
+ return out(plane.verifyLedger());
229
+
230
+ case "anchor":
231
+ return out(plane.auditAnchor());
232
+
233
+ case "serve": {
234
+ const keyFile = flags["api-key-file"] ?? process.env.COREGUARD_CONTROL_PLANE_API_KEY_FILE;
235
+ let apiKey = flags["api-key"] ?? process.env.COREGUARD_CONTROL_PLANE_API_KEY;
236
+ const usedInlineKey = !!(flags["api-key"] && flags["api-key"] !== true);
237
+ if ((!apiKey || apiKey === true) && keyFile && keyFile !== true) {
238
+ apiKey = readFileSync(String(keyFile), "utf8").trim();
239
+ }
240
+ if (!apiKey || apiKey === true) throw new Error("--api-key-file, --api-key, or COREGUARD_CONTROL_PLANE_API_KEY/COREGUARD_CONTROL_PLANE_API_KEY_FILE is required");
241
+ if (usedInlineKey) {
242
+ process.stderr.write(JSON.stringify({ warning: "DEPRECATED_FLAG", detail: "--api-key is visible in process listings; prefer --api-key-file or COREGUARD_CONTROL_PLANE_API_KEY_FILE / secret mount." }) + "\n");
243
+ }
244
+ if (String(apiKey).length < 32) {
245
+ process.stderr.write(JSON.stringify({ warning: "WEAK_API_KEY", detail: "API key should be >= 32 chars with high entropy; short keys are easier to brute force." }) + "\n");
246
+ }
247
+ const started = await startControlPlaneServer({
248
+ controlPlane: plane,
249
+ apiKey: String(apiKey),
250
+ port: Number(flags.port ?? 8787),
251
+ host: flags.host ?? "127.0.0.1",
252
+ });
253
+ out({ serving: started.url, version: CONTROL_PLANE_VERSION, boundary: CONTROL_PLANE_BOUNDARY, security: { inlineKeyDeprecated: usedInlineKey, keyFileUsed: !!(keyFile && keyFile !== true) } });
153
254
  return;
154
255
  }
155
- if (sub === "get") {
156
- const record = plane.getApproval(requireFlag(flags, "id"));
157
- if (!record) throw new Error("unknown approval");
158
- out(record);
159
- return;
160
- }
161
- break;
162
256
  }
163
257
 
164
- case "evaluate":
165
- return out(
166
- plane.evaluate({
167
- agentId: requireFlag(flags, "agent"),
168
- policyId: flags.policy ?? null,
169
- merchant: flags.merchant ?? null,
170
- address: flags.address ?? null,
171
- amountMinor: flags.amount ?? null,
172
- currency: flags.currency ?? null,
173
- approvalId: flags.approval ?? null,
174
- }),
175
- );
176
-
177
- case "authorize":
178
- return out(
179
- plane.authorize({
180
- agentId: requireFlag(flags, "agent"),
181
- policyId: flags.policy ?? null,
182
- merchant: flags.merchant ?? null,
183
- address: flags.address ?? null,
184
- amountMinor: flags.amount ?? null,
185
- currency: flags.currency ?? null,
186
- approvalId: flags.approval ?? null,
187
- }),
188
- );
189
-
190
- case "exec":
191
- return out(
192
- plane.commitExecution({
193
- id: flags.id,
194
- agentId: requireFlag(flags, "agent"),
195
- policyId: flags.policy ?? null,
196
- merchant: flags.merchant ?? null,
197
- address: flags.address ?? null,
198
- amountMinor: requireFlag(flags, "amount"),
199
- currency: flags.currency ?? null,
200
- approvalId: flags.approval ?? null,
201
- receiptId: flags.receipt ?? null,
202
- verdict: flags.verdict ?? null,
203
- orderRef: flags.order ?? null,
204
- }),
205
- );
206
-
207
- case "verification":
208
- return out(
209
- plane.recordVerification({
210
- executionId: flags.execution ?? null,
211
- receiptId: flags.receipt ?? null,
212
- verdict: flags.verdict ?? null,
213
- source: flags.source ?? null,
214
- }),
215
- );
216
-
217
- case "spend":
218
- return out(plane.spend({ agentId: flags.agent ?? null, policyId: flags.policy ?? null }));
219
-
220
- case "report":
221
- return out(plane.auditReport({ limit: Number(flags.limit ?? 200) }));
222
-
223
- case "verify":
224
- return out(plane.verifyLedger());
225
-
226
- case "serve": {
227
- const apiKey = flags["api-key"] ?? process.env.COREGUARD_CONTROL_PLANE_API_KEY;
228
- if (!apiKey || apiKey === true) throw new Error("--api-key or COREGUARD_CONTROL_PLANE_API_KEY is required");
229
- const started = await startControlPlaneServer({
230
- controlPlane: plane,
231
- apiKey,
232
- port: Number(flags.port ?? 8787),
233
- host: flags.host ?? "127.0.0.1",
234
- });
235
- out({ serving: started.url, version: CONTROL_PLANE_VERSION, boundary: CONTROL_PLANE_BOUNDARY });
236
- return;
237
- }
238
- }
258
+ throw new Error(`unknown command: ${positional.join(" ") || "(none)"}`);
259
+ };
260
+ if (auditMeta) await plane.withAuditMeta(auditMeta, dispatch);
261
+ else await dispatch();
262
+ }
239
263
 
240
- throw new Error(`unknown command: ${positional.join(" ") || "(none)"}`);
264
+ const isMain = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
265
+ if (isMain) {
266
+ main().catch((err) => {
267
+ process.stderr.write(JSON.stringify({ error: { code: "CLI_ERROR", detail: err?.message ?? String(err) } }) + "\n");
268
+ process.exit(1);
269
+ });
241
270
  }
242
271
 
243
- main().catch((err) => {
244
- process.stderr.write(JSON.stringify({ error: { code: "CLI_ERROR", detail: err?.message ?? String(err) } }) + "\n");
245
- process.exit(1);
246
- });
272
+ export { main };