@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.
- package/README.md +33 -1
- package/aer1.mjs +698 -2
- package/cgcp-mcp-tools.mjs +142 -0
- package/control-plane-cli.mjs +187 -161
- package/control-plane-http.mjs +91 -18
- package/control-plane.mjs +297 -43
- package/index.d.ts +143 -0
- package/index.mjs +51 -0
- package/machine-economy.mjs +366 -0
- package/mcp.mjs +182 -8
- package/observations.mjs +524 -0
- package/package.json +30 -7
- package/prod/kms-anchor.mjs +51 -0
- package/prod/migrate.mjs +73 -0
- package/prod/observability.mjs +35 -0
- package/prod/rbac.mjs +46 -0
- package/prod/schema.mjs +188 -0
- package/prod/sqlite-storage.mjs +135 -0
- package/server.json +20 -0
package/control-plane.mjs
CHANGED
|
@@ -48,9 +48,11 @@ import {
|
|
|
48
48
|
closeSync,
|
|
49
49
|
statSync,
|
|
50
50
|
unlinkSync,
|
|
51
|
+
fsyncSync,
|
|
52
|
+
existsSync,
|
|
51
53
|
} from "node:fs";
|
|
52
54
|
import { dirname } from "node:path";
|
|
53
|
-
import { randomUUID, createHash } from "node:crypto";
|
|
55
|
+
import { randomUUID, createHash, createHmac } from "node:crypto";
|
|
54
56
|
|
|
55
57
|
export const CONTROL_PLANE_VERSION = "CGCP/1";
|
|
56
58
|
export const CONTROL_PLANE_SCHEMA = "coreguard.control-plane/1";
|
|
@@ -65,11 +67,15 @@ export const CONTROL_PLANE_DECISION_REASONS = Object.freeze([
|
|
|
65
67
|
"UNKNOWN_POLICY",
|
|
66
68
|
"POLICY_INACTIVE",
|
|
67
69
|
"POLICY_UNREADABLE",
|
|
70
|
+
"AMOUNT_REQUIRED",
|
|
68
71
|
"MERCHANT_DENIED",
|
|
69
72
|
"MERCHANT_NOT_ALLOWED",
|
|
73
|
+
"MERCHANT_MISSING",
|
|
70
74
|
"ADDRESS_DENIED",
|
|
71
75
|
"ADDRESS_NOT_ALLOWED",
|
|
76
|
+
"ADDRESS_MISSING",
|
|
72
77
|
"CURRENCY_MISMATCH",
|
|
78
|
+
"CURRENCY_MISSING",
|
|
73
79
|
"SPEND_LIMIT_EXCEEDED",
|
|
74
80
|
"DAILY_LIMIT_EXCEEDED",
|
|
75
81
|
"TOTAL_LIMIT_EXCEEDED",
|
|
@@ -77,6 +83,7 @@ export const CONTROL_PLANE_DECISION_REASONS = Object.freeze([
|
|
|
77
83
|
"APPROVAL_NOT_APPROVED",
|
|
78
84
|
"APPROVAL_MISMATCH",
|
|
79
85
|
"APPROVAL_EXPIRED",
|
|
86
|
+
"APPROVAL_EXPIRES_AT_INVALID",
|
|
80
87
|
]);
|
|
81
88
|
|
|
82
89
|
const ZERO_HASH = "sha256:" + "0".repeat(64);
|
|
@@ -109,11 +116,22 @@ function optionalDecimal(value, field) {
|
|
|
109
116
|
return BigInt(s).toString();
|
|
110
117
|
}
|
|
111
118
|
|
|
119
|
+
const RESERVED_IDS = new Set(["__proto__", "prototype", "constructor"]);
|
|
120
|
+
const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
121
|
+
|
|
112
122
|
function requiredString(value, field) {
|
|
113
123
|
if (typeof value !== "string" || value.length === 0) throw new TypeError(`${field} must be a non-empty string`);
|
|
114
124
|
return value;
|
|
115
125
|
}
|
|
116
126
|
|
|
127
|
+
function requiredId(value, field) {
|
|
128
|
+
const id = requiredString(value, field);
|
|
129
|
+
if (RESERVED_IDS.has(id) || !SAFE_ID.test(id)) {
|
|
130
|
+
throw new TypeError(`${field} must match ${SAFE_ID} and not be a reserved key`);
|
|
131
|
+
}
|
|
132
|
+
return id;
|
|
133
|
+
}
|
|
134
|
+
|
|
117
135
|
function stringArray(value, field) {
|
|
118
136
|
if (value === undefined || value === null) return [];
|
|
119
137
|
if (!Array.isArray(value)) throw new TypeError(`${field} must be an array of strings`);
|
|
@@ -145,6 +163,14 @@ const sleep = (() => {
|
|
|
145
163
|
return (ms) => Atomics.wait(cell, 0, 0, ms);
|
|
146
164
|
})();
|
|
147
165
|
|
|
166
|
+
function nullMap(obj) {
|
|
167
|
+
const out = Object.create(null);
|
|
168
|
+
if (obj && typeof obj === "object") {
|
|
169
|
+
for (const [k, v] of Object.entries(obj)) out[k] = v;
|
|
170
|
+
}
|
|
171
|
+
return out;
|
|
172
|
+
}
|
|
173
|
+
|
|
148
174
|
function defaultState() {
|
|
149
175
|
return {
|
|
150
176
|
version: CONTROL_PLANE_VERSION,
|
|
@@ -152,37 +178,69 @@ function defaultState() {
|
|
|
152
178
|
boundary: CONTROL_PLANE_BOUNDARY,
|
|
153
179
|
createdAt: null,
|
|
154
180
|
updatedAt: null,
|
|
155
|
-
agents:
|
|
156
|
-
policies:
|
|
157
|
-
approvals:
|
|
181
|
+
agents: Object.create(null),
|
|
182
|
+
policies: Object.create(null),
|
|
183
|
+
approvals: Object.create(null),
|
|
158
184
|
executions: [],
|
|
159
185
|
verifications: [],
|
|
160
|
-
revocations:
|
|
186
|
+
revocations: Object.create(null),
|
|
161
187
|
audit: [],
|
|
162
188
|
};
|
|
163
189
|
}
|
|
164
190
|
|
|
191
|
+
function normalizeState(data) {
|
|
192
|
+
if (!data || typeof data !== "object") throw new Error("not a CGCP/1 control-plane store");
|
|
193
|
+
if (data.schema !== CONTROL_PLANE_SCHEMA) throw new Error("not a CGCP/1 control-plane store");
|
|
194
|
+
data.agents = nullMap(data.agents);
|
|
195
|
+
data.policies = nullMap(data.policies);
|
|
196
|
+
data.approvals = nullMap(data.approvals);
|
|
197
|
+
data.revocations = nullMap(data.revocations);
|
|
198
|
+
if (!Array.isArray(data.executions)) data.executions = [];
|
|
199
|
+
if (!Array.isArray(data.verifications)) data.verifications = [];
|
|
200
|
+
if (!Array.isArray(data.audit)) data.audit = [];
|
|
201
|
+
return data;
|
|
202
|
+
}
|
|
203
|
+
|
|
165
204
|
function loadState(path) {
|
|
166
205
|
try {
|
|
167
206
|
const data = JSON.parse(readFileSync(path, "utf8"));
|
|
168
|
-
|
|
169
|
-
return data;
|
|
207
|
+
return normalizeState(data);
|
|
170
208
|
} catch (err) {
|
|
171
209
|
if (err && err.code === "ENOENT") return null;
|
|
172
210
|
throw err;
|
|
173
211
|
}
|
|
174
212
|
}
|
|
175
213
|
|
|
176
|
-
function saveState(path, state) {
|
|
214
|
+
function saveState(path, state, { fsync = false } = {}) {
|
|
177
215
|
mkdirSync(dirname(path), { recursive: true });
|
|
178
216
|
const tmp = path + ".tmp-" + process.pid + "-" + Math.random().toString(16).slice(2);
|
|
179
|
-
|
|
217
|
+
const fd = openSync(tmp, "w");
|
|
218
|
+
try {
|
|
219
|
+
writeFileSync(fd, JSON.stringify(state, null, 2) + "\n", "utf8");
|
|
220
|
+
if (fsync) fsyncSync(fd);
|
|
221
|
+
} finally {
|
|
222
|
+
closeSync(fd);
|
|
223
|
+
}
|
|
180
224
|
renameSync(tmp, path);
|
|
225
|
+
if (fsync) {
|
|
226
|
+
try {
|
|
227
|
+
const dirFd = openSync(dirname(path), "r");
|
|
228
|
+
try { fsyncSync(dirFd); } finally { closeSync(dirFd); }
|
|
229
|
+
} catch {
|
|
230
|
+
// Best-effort directory fsync; not supported on all platforms/filesystems.
|
|
231
|
+
}
|
|
232
|
+
}
|
|
181
233
|
}
|
|
182
234
|
|
|
183
|
-
function appendAudit(state, type, detail, at) {
|
|
235
|
+
function appendAudit(state, type, detail, at, meta = null) {
|
|
184
236
|
const prevHash = state.audit.length ? state.audit[state.audit.length - 1].hash : ZERO_HASH;
|
|
185
237
|
const body = { seq: state.audit.length + 1, type, at, detail, prevHash };
|
|
238
|
+
const m = meta && typeof meta === "object" ? meta : (state?._auditMeta && typeof state._auditMeta === "object" ? state._auditMeta : null);
|
|
239
|
+
if (m) {
|
|
240
|
+
if (m.actor != null) body.actor = String(m.actor);
|
|
241
|
+
if (m.requestId != null) body.requestId = String(m.requestId);
|
|
242
|
+
if (m.source != null) body.source = String(m.source);
|
|
243
|
+
}
|
|
186
244
|
const entry = { ...body, hash: digestOf(body) };
|
|
187
245
|
state.audit.push(entry);
|
|
188
246
|
return entry;
|
|
@@ -208,7 +266,11 @@ export function verifyAuditChain(state) {
|
|
|
208
266
|
if (entry.prevHash !== prev) {
|
|
209
267
|
return { ok: false, length: audit.length, brokenAt: expectedSeq, reason: "previous hash does not chain", headHash: prev };
|
|
210
268
|
}
|
|
211
|
-
const
|
|
269
|
+
const body = { seq: entry.seq, type: entry.type, at: entry.at, detail: entry.detail, prevHash: entry.prevHash };
|
|
270
|
+
if (entry.actor != null) body.actor = entry.actor;
|
|
271
|
+
if (entry.requestId != null) body.requestId = entry.requestId;
|
|
272
|
+
if (entry.source != null) body.source = entry.source;
|
|
273
|
+
const recomputed = digestOf(body);
|
|
212
274
|
if (entry.hash !== recomputed) {
|
|
213
275
|
return { ok: false, length: audit.length, brokenAt: expectedSeq, reason: "entry hash does not recompute", headHash: prev };
|
|
214
276
|
}
|
|
@@ -251,7 +313,11 @@ function approvalProblem({ state, approvalId, agentId, policyId, merchant, addre
|
|
|
251
313
|
const approval = state.approvals[approvalId];
|
|
252
314
|
if (!approval) return "APPROVAL_REQUIRED";
|
|
253
315
|
if (approval.status !== "approved") return "APPROVAL_NOT_APPROVED";
|
|
254
|
-
if (approval.expiresAt
|
|
316
|
+
if (approval.expiresAt) {
|
|
317
|
+
const exp = Date.parse(approval.expiresAt);
|
|
318
|
+
if (!Number.isFinite(exp)) return "APPROVAL_EXPIRES_AT_INVALID";
|
|
319
|
+
if (exp < nowMs) return "APPROVAL_EXPIRED";
|
|
320
|
+
}
|
|
255
321
|
const same = (a, b) => (a == null ? b == null : String(a) === String(b));
|
|
256
322
|
if (!same(approval.agentId, agentId)) return "APPROVAL_MISMATCH";
|
|
257
323
|
if (approval.policyId != null && !same(approval.policyId, policyId)) return "APPROVAL_MISMATCH";
|
|
@@ -292,7 +358,15 @@ function evaluateRequest({ state, agentId, policyId, merchant, address, amountMi
|
|
|
292
358
|
|
|
293
359
|
const spec = version?.spec ?? null;
|
|
294
360
|
if (spec) {
|
|
295
|
-
|
|
361
|
+
const amount = amountMinor == null ? null : BigInt(amountMinor);
|
|
362
|
+
const monetaryPolicy = spec.spendLimitMinor != null || spec.dailyLimitMinor != null || spec.totalLimitMinor != null || spec.requireApprovalAboveMinor != null;
|
|
363
|
+
|
|
364
|
+
checks.merchant = { ok: true, merchant: merchant ?? null, denied: false, notOnAllowlist: false, missing: false };
|
|
365
|
+
if (merchant == null && (spec.denyMerchants.length > 0 || spec.allowMerchants.length > 0)) {
|
|
366
|
+
reasons.push("MERCHANT_MISSING");
|
|
367
|
+
checks.merchant.missing = true;
|
|
368
|
+
checks.merchant.ok = false;
|
|
369
|
+
}
|
|
296
370
|
if (merchant != null && spec.denyMerchants.includes(merchant)) {
|
|
297
371
|
reasons.push("MERCHANT_DENIED");
|
|
298
372
|
checks.merchant.denied = true;
|
|
@@ -304,7 +378,12 @@ function evaluateRequest({ state, agentId, policyId, merchant, address, amountMi
|
|
|
304
378
|
checks.merchant.ok = false;
|
|
305
379
|
}
|
|
306
380
|
|
|
307
|
-
checks.address = { ok: true, address: address ?? null, denied: false, notOnAllowlist: false };
|
|
381
|
+
checks.address = { ok: true, address: address ?? null, denied: false, notOnAllowlist: false, missing: false };
|
|
382
|
+
if (address == null && (spec.denyAddresses.length > 0 || spec.allowAddresses.length > 0)) {
|
|
383
|
+
reasons.push("ADDRESS_MISSING");
|
|
384
|
+
checks.address.missing = true;
|
|
385
|
+
checks.address.ok = false;
|
|
386
|
+
}
|
|
308
387
|
if (address != null && spec.denyAddresses.includes(address)) {
|
|
309
388
|
reasons.push("ADDRESS_DENIED");
|
|
310
389
|
checks.address.denied = true;
|
|
@@ -316,13 +395,17 @@ function evaluateRequest({ state, agentId, policyId, merchant, address, amountMi
|
|
|
316
395
|
checks.address.ok = false;
|
|
317
396
|
}
|
|
318
397
|
|
|
319
|
-
checks.currency = { ok: true, expected: spec.currency, observed: currency ?? null };
|
|
398
|
+
checks.currency = { ok: true, expected: spec.currency, observed: currency ?? null, missing: false };
|
|
399
|
+
if (spec.currency != null && currency == null) {
|
|
400
|
+
reasons.push("CURRENCY_MISSING");
|
|
401
|
+
checks.currency.missing = true;
|
|
402
|
+
checks.currency.ok = false;
|
|
403
|
+
}
|
|
320
404
|
if (spec.currency != null && currency != null && String(spec.currency) !== String(currency)) {
|
|
321
405
|
reasons.push("CURRENCY_MISMATCH");
|
|
322
406
|
checks.currency.ok = false;
|
|
323
407
|
}
|
|
324
408
|
|
|
325
|
-
const amount = amountMinor == null ? null : BigInt(amountMinor);
|
|
326
409
|
const totals = spendTotals(state.executions, {
|
|
327
410
|
agentId,
|
|
328
411
|
policyId: resolvedPolicyId,
|
|
@@ -339,7 +422,13 @@ function evaluateRequest({ state, agentId, policyId, merchant, address, amountMi
|
|
|
339
422
|
dailyLimitMinor: spec.dailyLimitMinor,
|
|
340
423
|
projectedTotalMinor: projectedTotal.toString(),
|
|
341
424
|
totalLimitMinor: spec.totalLimitMinor,
|
|
425
|
+
missing: false,
|
|
342
426
|
};
|
|
427
|
+
if (amount == null && monetaryPolicy) {
|
|
428
|
+
reasons.push("AMOUNT_REQUIRED");
|
|
429
|
+
checks.amount.missing = true;
|
|
430
|
+
checks.amount.ok = false;
|
|
431
|
+
}
|
|
343
432
|
if (amount != null && spec.spendLimitMinor != null && amount > BigInt(spec.spendLimitMinor)) {
|
|
344
433
|
reasons.push("SPEND_LIMIT_EXCEEDED");
|
|
345
434
|
checks.amount.ok = false;
|
|
@@ -401,60 +490,151 @@ export function createControlPlane({
|
|
|
401
490
|
now = () => new Date(),
|
|
402
491
|
lockTimeoutMs = 5000,
|
|
403
492
|
staleLockMs = 30000,
|
|
493
|
+
create = false,
|
|
494
|
+
fsync = false,
|
|
404
495
|
} = {}) {
|
|
405
496
|
if (typeof storePath !== "string" || storePath.length === 0) throw new TypeError("CGCP/1: storePath is required");
|
|
406
497
|
const lockPath = storePath + ".lock";
|
|
407
498
|
const nowIso = () => now().toISOString();
|
|
408
499
|
const nowMs = () => now().getTime();
|
|
500
|
+
let storeInitialized = existsSync(storePath);
|
|
501
|
+
if (!create && !storeInitialized) {
|
|
502
|
+
const missing = new Error("CGCP/1: store missing (pass create: true to initialize a new plane)");
|
|
503
|
+
missing.code = "STORE_MISSING";
|
|
504
|
+
missing.statusCode = 503;
|
|
505
|
+
throw missing;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function readLock() {
|
|
509
|
+
try {
|
|
510
|
+
const raw = JSON.parse(readFileSync(lockPath, "utf8"));
|
|
511
|
+
return raw && typeof raw === "object" ? raw : null;
|
|
512
|
+
} catch {
|
|
513
|
+
return null;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function pidAlive(pid) {
|
|
518
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
519
|
+
try {
|
|
520
|
+
process.kill(pid, 0);
|
|
521
|
+
return true;
|
|
522
|
+
} catch (err) {
|
|
523
|
+
// EPERM means process exists but we lack permission to signal it.
|
|
524
|
+
return err?.code === "EPERM";
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function tryBreakStaleLock() {
|
|
529
|
+
let lock;
|
|
530
|
+
let st;
|
|
531
|
+
try {
|
|
532
|
+
lock = readLock();
|
|
533
|
+
st = statSync(lockPath);
|
|
534
|
+
} catch {
|
|
535
|
+
return false; // released or unreadable; caller retries
|
|
536
|
+
}
|
|
537
|
+
const ageMs = Date.now() - (Number(lock?.at) || st.mtimeMs);
|
|
538
|
+
if (ageMs <= staleLockMs) return false;
|
|
539
|
+
// CP-05: never break by age alone when holder pid is still alive.
|
|
540
|
+
if (lock && pidAlive(lock.pid)) return false;
|
|
541
|
+
try {
|
|
542
|
+
// Best-effort ownership-safe break: only remove if same inode/file still looks like this lock.
|
|
543
|
+
const st2 = statSync(lockPath);
|
|
544
|
+
if (st2.ino !== st.ino || st2.mtimeMs !== st.mtimeMs) return false;
|
|
545
|
+
unlinkSync(lockPath);
|
|
546
|
+
return true;
|
|
547
|
+
} catch {
|
|
548
|
+
return false;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
409
551
|
|
|
410
552
|
function acquireLock() {
|
|
411
553
|
const deadline = Date.now() + lockTimeoutMs;
|
|
554
|
+
const ownerToken = randomUUID();
|
|
412
555
|
for (;;) {
|
|
413
556
|
try {
|
|
414
557
|
const fd = openSync(lockPath, "wx");
|
|
415
|
-
writeFileSync(fd, JSON.stringify({ pid: process.pid, at: Date.now() }));
|
|
416
|
-
closeSync(fd);
|
|
417
|
-
return;
|
|
418
|
-
} catch (err) {
|
|
419
|
-
if (err.code !== "EEXIST") throw err;
|
|
420
558
|
try {
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
// The holder released between EEXIST and stat — retry immediately.
|
|
559
|
+
writeFileSync(fd, JSON.stringify({ pid: process.pid, at: Date.now(), ownerToken }));
|
|
560
|
+
} finally {
|
|
561
|
+
closeSync(fd);
|
|
425
562
|
}
|
|
563
|
+
return ownerToken;
|
|
564
|
+
} catch (err) {
|
|
565
|
+
if (err.code !== "EEXIST") throw err;
|
|
566
|
+
tryBreakStaleLock();
|
|
426
567
|
if (Date.now() > deadline) {
|
|
427
|
-
|
|
568
|
+
const lockErr = new Error("CGCP/1: store is locked by another process");
|
|
569
|
+
lockErr.code = "STORE_LOCKED";
|
|
570
|
+
lockErr.statusCode = 503;
|
|
571
|
+
throw lockErr;
|
|
428
572
|
}
|
|
429
573
|
sleep(3 + Math.floor(Math.random() * 5));
|
|
430
574
|
}
|
|
431
575
|
}
|
|
432
576
|
}
|
|
433
577
|
|
|
434
|
-
function releaseLock() {
|
|
578
|
+
function releaseLock(ownerToken) {
|
|
435
579
|
try {
|
|
580
|
+
const lock = readLock();
|
|
581
|
+
// CP-04: only the owner may remove its lock.
|
|
582
|
+
if (lock && lock.ownerToken && lock.ownerToken !== ownerToken) return;
|
|
436
583
|
unlinkSync(lockPath);
|
|
437
584
|
} catch {
|
|
438
|
-
// Nothing to release.
|
|
585
|
+
// Nothing to release or already removed.
|
|
439
586
|
}
|
|
440
587
|
}
|
|
441
588
|
|
|
442
589
|
function read() {
|
|
443
|
-
|
|
590
|
+
const state = loadState(storePath);
|
|
591
|
+
if (state) {
|
|
592
|
+
storeInitialized = true;
|
|
593
|
+
return state;
|
|
594
|
+
}
|
|
595
|
+
if (!create && !storeInitialized) {
|
|
596
|
+
const missing = new Error("CGCP/1: store missing (pass create: true to initialize a new plane)");
|
|
597
|
+
missing.code = "STORE_MISSING";
|
|
598
|
+
missing.statusCode = 503;
|
|
599
|
+
throw missing;
|
|
600
|
+
}
|
|
601
|
+
return defaultState();
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
let pendingAuditMeta = null;
|
|
605
|
+
function withAuditMeta(meta, fn) {
|
|
606
|
+
const prev = pendingAuditMeta;
|
|
607
|
+
pendingAuditMeta = meta && typeof meta === "object" ? meta : null;
|
|
608
|
+
let out;
|
|
609
|
+
try {
|
|
610
|
+
out = fn();
|
|
611
|
+
} catch (err) {
|
|
612
|
+
pendingAuditMeta = prev;
|
|
613
|
+
throw err;
|
|
614
|
+
}
|
|
615
|
+
if (out && typeof out.then === "function") {
|
|
616
|
+
return Promise.resolve(out).finally(() => { pendingAuditMeta = prev; });
|
|
617
|
+
}
|
|
618
|
+
pendingAuditMeta = prev;
|
|
619
|
+
return out;
|
|
444
620
|
}
|
|
445
621
|
|
|
446
622
|
/** Every mutation: exclusive lock → reload → mutate → atomic save → unlock. */
|
|
447
|
-
function mutate(fn) {
|
|
448
|
-
acquireLock();
|
|
623
|
+
function mutate(fn, meta = null) {
|
|
624
|
+
const ownerToken = acquireLock();
|
|
449
625
|
try {
|
|
450
626
|
const state = read();
|
|
451
627
|
if (!state.createdAt) state.createdAt = nowIso();
|
|
628
|
+
const m = meta || pendingAuditMeta;
|
|
629
|
+
if (m && typeof m === "object") {
|
|
630
|
+
Object.defineProperty(state, "_auditMeta", { value: m, enumerable: false, configurable: true, writable: true });
|
|
631
|
+
}
|
|
452
632
|
const result = fn(state);
|
|
453
633
|
state.updatedAt = nowIso();
|
|
454
|
-
saveState(storePath, state);
|
|
634
|
+
saveState(storePath, state, { fsync });
|
|
455
635
|
return result;
|
|
456
636
|
} finally {
|
|
457
|
-
releaseLock();
|
|
637
|
+
releaseLock(ownerToken);
|
|
458
638
|
}
|
|
459
639
|
}
|
|
460
640
|
|
|
@@ -465,7 +645,7 @@ export function createControlPlane({
|
|
|
465
645
|
// -- agents --------------------------------------------------------------
|
|
466
646
|
|
|
467
647
|
function upsertAgent(agent = {}) {
|
|
468
|
-
const id =
|
|
648
|
+
const id = requiredId(agent.id, "agent.id");
|
|
469
649
|
return mutate((state) => {
|
|
470
650
|
const prev = state.agents[id] ?? null;
|
|
471
651
|
const status = agent.status ?? prev?.status ?? "active";
|
|
@@ -525,7 +705,7 @@ export function createControlPlane({
|
|
|
525
705
|
// -- policies (immutable versions; upsert appends) -----------------------
|
|
526
706
|
|
|
527
707
|
function upsertPolicy(policy = {}) {
|
|
528
|
-
const id =
|
|
708
|
+
const id = requiredId(policy.id, "policy.id");
|
|
529
709
|
return mutate((state) => {
|
|
530
710
|
const prev = state.policies[id] ?? null;
|
|
531
711
|
const spec = normalizePolicySpec(policy);
|
|
@@ -585,14 +765,14 @@ export function createControlPlane({
|
|
|
585
765
|
// -- approvals -----------------------------------------------------------
|
|
586
766
|
|
|
587
767
|
function requestApproval(request = {}) {
|
|
588
|
-
const approvalId = request.id ?? "ap_" + randomUUID();
|
|
589
|
-
const agentId =
|
|
768
|
+
const approvalId = requiredId(request.id ?? "ap_" + randomUUID(), "approval.id");
|
|
769
|
+
const agentId = requiredId(request.agentId, "approval.agentId");
|
|
590
770
|
return mutate((state) => {
|
|
591
771
|
if (!state.agents[agentId]) throw new Error("CGCP/1: unknown agent");
|
|
592
772
|
const record = {
|
|
593
773
|
id: approvalId,
|
|
594
774
|
agentId,
|
|
595
|
-
policyId: request.policyId
|
|
775
|
+
policyId: request.policyId == null ? (state.agents[agentId].policyId ?? null) : requiredId(request.policyId, "approval.policyId"),
|
|
596
776
|
merchant: request.merchant ?? null,
|
|
597
777
|
address: request.address ?? null,
|
|
598
778
|
amountMinor: optionalDecimal(request.amountMinor, "approval.amountMinor"),
|
|
@@ -600,7 +780,12 @@ export function createControlPlane({
|
|
|
600
780
|
status: "pending",
|
|
601
781
|
requestedAt: nowIso(),
|
|
602
782
|
requestedBy: request.requestedBy ?? null,
|
|
603
|
-
expiresAt:
|
|
783
|
+
expiresAt: (() => {
|
|
784
|
+
const v = request.expiresAt ?? new Date(nowMs() + 15 * 60 * 1000).toISOString();
|
|
785
|
+
const t = Date.parse(v);
|
|
786
|
+
if (!Number.isFinite(t)) throw new TypeError("approval.expiresAt must be a valid ISO-8601 datetime");
|
|
787
|
+
return new Date(t).toISOString();
|
|
788
|
+
})(),
|
|
604
789
|
decidedAt: null,
|
|
605
790
|
decidedBy: null,
|
|
606
791
|
reason: null,
|
|
@@ -698,13 +883,24 @@ export function createControlPlane({
|
|
|
698
883
|
boundary: CONTROL_PLANE_BOUNDARY,
|
|
699
884
|
};
|
|
700
885
|
}
|
|
886
|
+
const amountMinor = optionalDecimal(execution.amountMinor, "execution.amountMinor");
|
|
887
|
+
if (amountMinor == null) {
|
|
888
|
+
appendAudit(state, "execution.refused", { executionId, reasons: ["AMOUNT_REQUIRED"], agentId: execution.agentId ?? null }, nowIso());
|
|
889
|
+
return {
|
|
890
|
+
committed: false,
|
|
891
|
+
duplicate: false,
|
|
892
|
+
reasons: ["AMOUNT_REQUIRED"],
|
|
893
|
+
executionId,
|
|
894
|
+
boundary: CONTROL_PLANE_BOUNDARY,
|
|
895
|
+
};
|
|
896
|
+
}
|
|
701
897
|
const decision = evaluateRequest({
|
|
702
898
|
state,
|
|
703
899
|
agentId: execution.agentId ?? null,
|
|
704
900
|
policyId: execution.policyId ?? null,
|
|
705
901
|
merchant: execution.merchant ?? null,
|
|
706
902
|
address: execution.address ?? null,
|
|
707
|
-
amountMinor
|
|
903
|
+
amountMinor,
|
|
708
904
|
currency: execution.currency ?? null,
|
|
709
905
|
approvalId: execution.approvalId ?? null,
|
|
710
906
|
nowMs: nowMs(),
|
|
@@ -765,7 +961,7 @@ export function createControlPlane({
|
|
|
765
961
|
|
|
766
962
|
/** Kept for the v0 contract: record a pre-computed execution without gating. */
|
|
767
963
|
function recordExecution(execution = {}) {
|
|
768
|
-
const id =
|
|
964
|
+
const id = requiredId(execution.id, "execution.id");
|
|
769
965
|
return mutate((state) => {
|
|
770
966
|
const record = { ...execution, id, at: execution.at ?? nowIso() };
|
|
771
967
|
record.hash = digestOf({ ...record, hash: null });
|
|
@@ -777,8 +973,8 @@ export function createControlPlane({
|
|
|
777
973
|
|
|
778
974
|
/** Kept for the v0 contract: record a pre-computed approval. */
|
|
779
975
|
function recordApproval(approval = {}) {
|
|
780
|
-
const id =
|
|
781
|
-
|
|
976
|
+
const id = requiredId(approval.id, "approval.id");
|
|
977
|
+
requiredId(approval.agentId, "approval.agentId");
|
|
782
978
|
return mutate((state) => {
|
|
783
979
|
const record = { ...approval, id, at: approval.at ?? nowIso() };
|
|
784
980
|
record.hash = digestOf({ ...record, hash: null });
|
|
@@ -863,6 +1059,56 @@ export function createControlPlane({
|
|
|
863
1059
|
});
|
|
864
1060
|
}
|
|
865
1061
|
|
|
1062
|
+
function auditAnchor(options = {}) {
|
|
1063
|
+
return view((state) => {
|
|
1064
|
+
const chain = verifyAuditChain(state);
|
|
1065
|
+
const anchor = {
|
|
1066
|
+
ok: chain.ok,
|
|
1067
|
+
headHash: chain.headHash,
|
|
1068
|
+
length: chain.length,
|
|
1069
|
+
at: nowIso(),
|
|
1070
|
+
};
|
|
1071
|
+
const hmacKey = options.hmacKey ?? process.env.COREGUARD_CONTROL_PLANE_ANCHOR_HMAC_KEY ?? null;
|
|
1072
|
+
if (hmacKey) {
|
|
1073
|
+
anchor.hmacSha256 = createHmac("sha256", String(hmacKey)).update(canonicalJson({ headHash: anchor.headHash, length: anchor.length })).digest("hex");
|
|
1074
|
+
anchor.hmac = "hmac-sha256";
|
|
1075
|
+
}
|
|
1076
|
+
anchor.boundary = "Local audit head anchor. Optional HMAC is local shared-key integrity only. NOT_BUILT: external witness/anchoring service, KMS/HSM signatures, or on-chain anchoring.";
|
|
1077
|
+
return anchor;
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
function verifyAnchor(expected = {}) {
|
|
1082
|
+
return view((state) => {
|
|
1083
|
+
const chain = verifyAuditChain(state);
|
|
1084
|
+
const expectedHead = expected.headHash ?? null;
|
|
1085
|
+
const expectedLength = expected.length ?? null;
|
|
1086
|
+
const headOk = expectedHead == null ? true : chain.headHash === expectedHead;
|
|
1087
|
+
const lengthOk = expectedLength == null ? true : chain.length === expectedLength;
|
|
1088
|
+
let hmacOk = true;
|
|
1089
|
+
const hmacKey = expected.hmacKey ?? process.env.COREGUARD_CONTROL_PLANE_ANCHOR_HMAC_KEY ?? null;
|
|
1090
|
+
if (expected.hmacSha256) {
|
|
1091
|
+
if (!hmacKey) hmacOk = false;
|
|
1092
|
+
else {
|
|
1093
|
+
const actual = createHmac("sha256", String(hmacKey)).update(canonicalJson({ headHash: chain.headHash, length: chain.length })).digest("hex");
|
|
1094
|
+
hmacOk = actual === String(expected.hmacSha256);
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
return {
|
|
1098
|
+
ok: chain.ok && headOk && lengthOk && hmacOk,
|
|
1099
|
+
chainOk: chain.ok,
|
|
1100
|
+
headOk,
|
|
1101
|
+
lengthOk,
|
|
1102
|
+
hmacOk,
|
|
1103
|
+
expectedHead,
|
|
1104
|
+
expectedLength,
|
|
1105
|
+
actualHead: chain.headHash,
|
|
1106
|
+
actualLength: chain.length,
|
|
1107
|
+
boundary: "Local anchor comparison only. Optional HMAC is local shared-key integrity only. NOT_BUILT: external witness/anchoring service.",
|
|
1108
|
+
};
|
|
1109
|
+
});
|
|
1110
|
+
}
|
|
1111
|
+
|
|
866
1112
|
function verifyLedger() {
|
|
867
1113
|
return view((state) => {
|
|
868
1114
|
const chain = verifyAuditChain(state);
|
|
@@ -881,6 +1127,11 @@ export function createControlPlane({
|
|
|
881
1127
|
executionHashesOk,
|
|
882
1128
|
approvals: Object.keys(state.approvals).length,
|
|
883
1129
|
approvalHashesOk,
|
|
1130
|
+
anchor: {
|
|
1131
|
+
headHash: chain.headHash,
|
|
1132
|
+
length: chain.length,
|
|
1133
|
+
boundary: "Local anchor only; external witness NOT_BUILT.",
|
|
1134
|
+
},
|
|
884
1135
|
boundary: CONTROL_PLANE_BOUNDARY,
|
|
885
1136
|
};
|
|
886
1137
|
});
|
|
@@ -918,6 +1169,9 @@ export function createControlPlane({
|
|
|
918
1169
|
spend,
|
|
919
1170
|
auditReport,
|
|
920
1171
|
verifyLedger,
|
|
1172
|
+
auditAnchor,
|
|
1173
|
+
verifyAnchor,
|
|
921
1174
|
getState,
|
|
1175
|
+
withAuditMeta,
|
|
922
1176
|
};
|
|
923
1177
|
}
|