@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.
@@ -3,33 +3,47 @@
3
3
  *
4
4
  * A Set-compatible consumption ledger adapter that persists consumed receipt
5
5
  * IDs to a JSON file so a single-use authorization cannot be replayed across
6
- * process restarts on the same host (the "shared-ledger/store adapter via
7
- * existing consumedSet injection" named by the spec's next step).
6
+ * process restarts — or across two live processes on the same host.
8
7
  *
9
- * Interface: `has(id)` / `add(id)` — the same shape `verifyExecution`, the
10
- * firewall, and `assessRisk` already accept via `consumedSet`, so this is a
11
- * drop-in replacement for the process-local `Set` with no change to the
12
- * verification semantics.
8
+ * Interface: `has(id)` / `add(id)` / `tryAdd(id)` — the same shape
9
+ * `verifyExecution`, the firewall, and `assessRisk` accept via `consumedSet`.
10
+ * `tryAdd(id)` is the correct single-use primitive: it reloads the ledger under
11
+ * an exclusive file lock and returns true only for the caller that actually
12
+ * added the id, so two racing processes cannot both believe they were first.
13
13
  *
14
- * Durability model (honest): file-backed, atomic rename-on-write within the
15
- * host process's visibility. It is NOT a distributed ledger, NOT an on-chain
16
- * single-use marker, and NOT a guarantee against concurrent writers racing on
17
- * the same file without external locking. An on-chain consumption marker is
18
- * OWNER-GATED / NOT_BUILT — this adapter closes the cross-process gap the spec
19
- * named, not the on-chain anchoring gap.
14
+ * Durability model (honest): every read is a fresh file read; every mutation
15
+ * takes `<file>.lock` (O_EXCL, stale-lock recovery) and rewrites the ledger with
16
+ * an atomic temp+rename. That closes the cross-PROCESS gap on one host. It is
17
+ * still NOT a distributed ledger and NOT an on-chain marker: two hosts with two
18
+ * local files can each consume the same receipt. The built answer for crossing
19
+ * hosts is the append-only signed log in `spend.mjs` (CG-SPEND/1, `mergeLogs`),
20
+ * which makes a double-spend across exchanged logs a named `conflict`; a global
21
+ * on-chain marker remains OWNER-GATED / NOT_BUILT.
20
22
  *
21
23
  * BOUNDARY (standing): VERIFIED ≠ SAFE; consumption anchoring here is a local
22
24
  * persistence aid, never a broadcast, never chain state.
23
25
  */
24
26
 
25
- import { readFileSync, writeFileSync, mkdirSync, renameSync } from "node:fs";
27
+ import {
28
+ readFileSync,
29
+ writeFileSync,
30
+ mkdirSync,
31
+ renameSync,
32
+ openSync,
33
+ closeSync,
34
+ statSync,
35
+ unlinkSync,
36
+ } from "node:fs";
26
37
  import { dirname } from "node:path";
27
38
 
28
39
  export const CONSUMPTION_STORE_VERSION = "AC-CS/1";
29
40
  export const CONSUMPTION_STORE_BOUNDARY =
30
- "file-backed consumption ledger — durable across process restarts on this host; " +
41
+ "file-backed consumption ledger — durable across process restarts and lock-guarded across processes on this host; " +
31
42
  "NOT a distributed ledger, NOT an on-chain marker (on-chain anchoring OWNER-GATED / NOT_BUILT); " +
32
- "VERIFIED ≠ SAFE";
43
+ "cross-host reconciliation is CG-SPEND/1 merge (spend.mjs), not this file; VERIFIED ≠ SAFE";
44
+
45
+ const SLEEP_CELL = new Int32Array(new SharedArrayBuffer(4));
46
+ const sleep = (ms) => Atomics.wait(SLEEP_CELL, 0, 0, ms);
33
47
 
34
48
  function loadIds(filePath) {
35
49
  try {
@@ -57,57 +71,119 @@ function persist(filePath, ids) {
57
71
  null,
58
72
  2,
59
73
  ) + "\n";
60
- const tmp = `${filePath}.tmp`;
74
+ const tmp = `${filePath}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`;
61
75
  writeFileSync(tmp, payload, "utf8");
62
76
  renameSync(tmp, filePath);
63
77
  }
64
78
 
79
+ /** Exclusive lock around a read-modify-write of one ledger file. */
80
+ function withLock(filePath, fn, { lockTimeoutMs = 2000, staleLockMs = 10000 } = {}) {
81
+ const lockPath = `${filePath}.lock`;
82
+ mkdirSync(dirname(lockPath), { recursive: true });
83
+ const deadline = Date.now() + lockTimeoutMs;
84
+ for (;;) {
85
+ try {
86
+ const fd = openSync(lockPath, "wx");
87
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, at: Date.now() }));
88
+ closeSync(fd);
89
+ break;
90
+ } catch (err) {
91
+ if (err.code !== "EEXIST") throw err;
92
+ try {
93
+ const st = statSync(lockPath);
94
+ if (Date.now() - st.mtimeMs > staleLockMs) unlinkSync(lockPath);
95
+ } catch {
96
+ // Released between EEXIST and stat.
97
+ }
98
+ if (Date.now() > deadline) throw new Error(`AC-CS/1: ledger is locked by another process (${lockPath})`);
99
+ sleep(3 + Math.floor(Math.random() * 5));
100
+ }
101
+ }
102
+ try {
103
+ return fn();
104
+ } finally {
105
+ try {
106
+ unlinkSync(lockPath);
107
+ } catch {
108
+ // Nothing to release.
109
+ }
110
+ }
111
+ }
112
+
65
113
  /**
66
114
  * Create (or open) a file-backed consumption store.
67
115
  *
68
116
  * `filePath` — path to the JSON ledger file (created if absent).
69
- * The returned object is Set-compatible for `has`/`add` and also exposes
70
- * `size`, `ids()` (sorted snapshot), `spec`, `filePath`, and `boundary`.
117
+ * Options: `lockTimeoutMs`, `staleLockMs` for the cross-process lock.
71
118
  */
72
- export function createConsumptionStore(filePath) {
119
+ export function createConsumptionStore(filePath, { lockTimeoutMs = 2000, staleLockMs = 10000 } = {}) {
73
120
  if (!filePath || typeof filePath !== "string") {
74
121
  throw new Error("AC-CS/1: createConsumptionStore requires a filePath string");
75
122
  }
76
- const ids = loadIds(filePath);
123
+ const lockOptions = { lockTimeoutMs, staleLockMs };
77
124
 
78
125
  const store = {
79
126
  spec: CONSUMPTION_STORE_VERSION,
80
127
  filePath,
81
128
  boundary: CONSUMPTION_STORE_BOUNDARY,
129
+ /** Fresh read: another process's commit is visible immediately. */
82
130
  has(id) {
83
- return ids.has(id);
131
+ return loadIds(filePath).has(id);
84
132
  },
85
133
  add(id) {
86
- if (!ids.has(id)) {
87
- ids.add(id);
88
- persist(filePath, ids);
89
- }
134
+ store.tryAdd(id);
90
135
  return store;
91
136
  },
137
+ /**
138
+ * Atomic cross-process claim. Returns true only for the caller that added
139
+ * the id; a concurrent process that already added it gets false.
140
+ */
141
+ tryAdd(id) {
142
+ if (typeof id !== "string" || id.length === 0) throw new Error("AC-CS/1: id must be a non-empty string");
143
+ return withLock(
144
+ filePath,
145
+ () => {
146
+ const ids = loadIds(filePath);
147
+ if (ids.has(id)) return false;
148
+ ids.add(id);
149
+ persist(filePath, ids);
150
+ return true;
151
+ },
152
+ lockOptions,
153
+ );
154
+ },
92
155
  delete(id) {
93
- const removed = ids.delete(id);
94
- if (removed) persist(filePath, ids);
95
- return removed;
156
+ return withLock(
157
+ filePath,
158
+ () => {
159
+ const ids = loadIds(filePath);
160
+ const removed = ids.delete(id);
161
+ if (removed) persist(filePath, ids);
162
+ return removed;
163
+ },
164
+ lockOptions,
165
+ );
96
166
  },
97
167
  clear() {
98
- ids.clear();
99
- persist(filePath, ids);
168
+ withLock(
169
+ filePath,
170
+ () => {
171
+ persist(filePath, new Set());
172
+ return true;
173
+ },
174
+ lockOptions,
175
+ );
100
176
  },
101
177
  get size() {
102
- return ids.size;
178
+ return loadIds(filePath).size;
103
179
  },
104
180
  ids() {
105
- return [...ids].sort();
181
+ return [...loadIds(filePath)].sort();
106
182
  },
107
183
  toJSON() {
108
184
  return {
109
185
  spec: CONSUMPTION_STORE_VERSION,
110
- ids: [...ids].sort(),
186
+ ids: [...loadIds(filePath)].sort(),
111
187
  boundary: CONSUMPTION_STORE_BOUNDARY,
112
188
  };
113
189
  },
@@ -115,7 +191,7 @@ export function createConsumptionStore(filePath) {
115
191
 
116
192
  // Iterable like a Set for consumers that spread/iterate.
117
193
  store[Symbol.iterator] = function* () {
118
- yield* [...ids].sort();
194
+ yield* store.ids();
119
195
  };
120
196
 
121
197
  return store;
@@ -124,24 +200,24 @@ export function createConsumptionStore(filePath) {
124
200
  /**
125
201
  * Open an existing store as a read-only snapshot (no writes; mutation methods
126
202
  * are absent). Useful for inspection/audit without mutating the ledger.
203
+ * `has`/`ids`/`size` stay live reads, so an inspector sees new commits.
127
204
  */
128
205
  export function openConsumptionStore(filePath) {
129
206
  if (!filePath || typeof filePath !== "string") {
130
207
  throw new Error("AC-CS/1: openConsumptionStore requires a filePath string");
131
208
  }
132
- const ids = loadIds(filePath);
133
209
  return Object.freeze({
134
210
  spec: CONSUMPTION_STORE_VERSION,
135
211
  filePath,
136
212
  boundary: CONSUMPTION_STORE_BOUNDARY,
137
213
  has(id) {
138
- return ids.has(id);
214
+ return loadIds(filePath).has(id);
139
215
  },
140
216
  get size() {
141
- return ids.size;
217
+ return loadIds(filePath).size;
142
218
  },
143
219
  ids() {
144
- return [...ids].sort();
220
+ return [...loadIds(filePath)].sort();
145
221
  },
146
222
  });
147
223
  }
@@ -0,0 +1,272 @@
1
+ #!/usr/bin/env node
2
+ import { pathToFileURL } from "node:url";
3
+ /**
4
+ * CoreGuard Control Plane CLI (CGCP/1) — operator surface over the same plane
5
+ * the SDK and HTTP API use. Every command prints canonical JSON to stdout and
6
+ * exits 0; a failure prints `{error:{code,detail}}` to stderr and exits 1.
7
+ *
8
+ * node packages/agent-commerce/control-plane-cli.mjs --store ./cp.json init
9
+ * ... policy upsert --id p1 --spend-limit 5000 --daily-limit 20000 --approval-above 1000
10
+ * ... agent upsert --id a1 --policy p1
11
+ * ... evaluate --agent a1 --merchant m1 --amount 900
12
+ * ... approval request --agent a1 --merchant m1 --amount 2000
13
+ * ... approval decide --id ap_x --decision approved --by ops@example
14
+ * ... exec --agent a1 --merchant m1 --amount 2000 --approval ap_x
15
+ * ... report
16
+ * ... serve --port 8787 (API key from --api-key or COREGUARD_CONTROL_PLANE_API_KEY)
17
+ *
18
+ * BOUNDARY: single-host, single-API-key. No RBAC/SSO/tenancy (NOT_BUILT).
19
+ */
20
+
21
+ import { readFileSync } from "node:fs";
22
+ import { createControlPlane, CONTROL_PLANE_VERSION, CONTROL_PLANE_BOUNDARY } from "./control-plane.mjs";
23
+ import { startControlPlaneServer } from "./control-plane-http.mjs";
24
+
25
+ function parseArgs(argv) {
26
+ const positional = [];
27
+ const flags = {};
28
+ for (let i = 0; i < argv.length; i += 1) {
29
+ const token = argv[i];
30
+ if (token.startsWith("--")) {
31
+ const key = token.slice(2);
32
+ const next = argv[i + 1];
33
+ if (next === undefined || next.startsWith("--")) {
34
+ flags[key] = true;
35
+ } else {
36
+ flags[key] = next;
37
+ i += 1;
38
+ }
39
+ } else {
40
+ positional.push(token);
41
+ }
42
+ }
43
+ return { positional, flags };
44
+ }
45
+
46
+ const list = (value) =>
47
+ value === undefined || value === true ? [] : String(value).split(",").map((s) => s.trim()).filter(Boolean);
48
+
49
+ function requireFlag(flags, name) {
50
+ if (flags[name] === undefined || flags[name] === true) throw new Error(`--${name} is required`);
51
+ return flags[name];
52
+ }
53
+
54
+ function out(value) {
55
+ process.stdout.write(JSON.stringify(value, null, 2) + "\n");
56
+ }
57
+
58
+ async function main() {
59
+ const { positional, flags } = parseArgs(process.argv.slice(2));
60
+ const storePath = flags.store ?? process.env.COREGUARD_CONTROL_PLANE_STORE ?? "./.coreguard/control-plane.json";
61
+ const plane = createControlPlane({ storePath, lockTimeoutMs: Number(flags["lock-timeout-ms"] ?? 5000), create: positional[0] === "init" });
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
+ }
104
+
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"),
171
+ policyId: flags.policy ?? null,
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,
177
+ }),
178
+ );
179
+
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,
188
+ currency: flags.currency ?? null,
189
+ approvalId: flags.approval ?? null,
190
+ }),
191
+ );
192
+
193
+ case "exec":
194
+ return out(
195
+ plane.commitExecution({
196
+ id: flags.id,
197
+ agentId: requireFlag(flags, "agent"),
198
+ policyId: flags.policy ?? null,
199
+ merchant: flags.merchant ?? null,
200
+ address: flags.address ?? null,
201
+ amountMinor: requireFlag(flags, "amount"),
202
+ currency: flags.currency ?? null,
203
+ approvalId: flags.approval ?? null,
204
+ receiptId: flags.receipt ?? null,
205
+ verdict: flags.verdict ?? null,
206
+ orderRef: flags.order ?? null,
207
+ }),
208
+ );
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,
217
+ }),
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) } });
254
+ return;
255
+ }
256
+ }
257
+
258
+ throw new Error(`unknown command: ${positional.join(" ") || "(none)"}`);
259
+ };
260
+ if (auditMeta) await plane.withAuditMeta(auditMeta, dispatch);
261
+ else await dispatch();
262
+ }
263
+
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
+ });
270
+ }
271
+
272
+ export { main };