@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.
- package/README.md +307 -11
- package/aer1.mjs +954 -0
- package/anchor.mjs +278 -0
- package/bin/mcp.mjs +0 -0
- package/cgcp-mcp-tools.mjs +142 -0
- package/composition.mjs +150 -0
- package/consumption-store.mjs +114 -38
- package/control-plane-cli.mjs +272 -0
- package/control-plane-http.mjs +348 -0
- package/control-plane.mjs +1177 -0
- package/decision.mjs +152 -0
- package/firewall.mjs +1 -1
- package/identity.mjs +205 -0
- package/index.d.ts +991 -1
- package/index.mjs +240 -3
- package/machine-economy.mjs +366 -0
- package/mcp.mjs +657 -28
- package/observations.mjs +524 -0
- package/outcomes-bridge.mjs +169 -0
- package/outcomes.mjs +220 -0
- package/package.json +64 -14
- 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/profile-ref.mjs +130 -0
- package/reference.mjs +350 -0
- package/risk-cli.mjs +10 -2
- package/risk.mjs +49 -2
- package/spend.mjs +291 -0
- package/trust.mjs +322 -0
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CoreGuard Control Plane HTTP API (CGCP/1) — zero-dependency node:http surface.
|
|
3
|
+
*
|
|
4
|
+
* The same plane the SDK and CLI use, reachable by an agent runtime, a CI job or
|
|
5
|
+
* an operator console. Every /v1 route requires a bearer API key compared in
|
|
6
|
+
* constant time; /health is deliberately public (liveness only, no data).
|
|
7
|
+
*
|
|
8
|
+
* BOUNDARY (standing): a single API key is host-level authorisation, NOT
|
|
9
|
+
* multi-user identity. There is no RBAC/SSO/tenant isolation here — that is
|
|
10
|
+
* NOT_BUILT and is stated by `CONTROL_PLANE_BOUNDARY` on every report. Bind it
|
|
11
|
+
* to loopback or a private network; TLS and an authenticating reverse proxy are
|
|
12
|
+
* deployment concerns, not claims of this module.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { createServer } from "node:http";
|
|
16
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
17
|
+
import { CONTROL_PLANE_BOUNDARY, CONTROL_PLANE_VERSION, createControlPlane } from "./control-plane.mjs";
|
|
18
|
+
|
|
19
|
+
const MAX_BODY_BYTES = 256 * 1024;
|
|
20
|
+
const MAX_LIMIT = 1000;
|
|
21
|
+
|
|
22
|
+
function parseLimit(value, def = 100) {
|
|
23
|
+
if (value == null || value === "") return def;
|
|
24
|
+
const n = Number.parseInt(String(value), 10);
|
|
25
|
+
if (!Number.isFinite(n) || n < 1) return def;
|
|
26
|
+
return Math.min(n, MAX_LIMIT);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function json(res, status, body) {
|
|
30
|
+
const payload = JSON.stringify(body);
|
|
31
|
+
res.writeHead(status, {
|
|
32
|
+
"content-type": "application/json; charset=utf-8",
|
|
33
|
+
"cache-control": "no-store",
|
|
34
|
+
"content-length": Buffer.byteLength(payload),
|
|
35
|
+
});
|
|
36
|
+
res.end(payload);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function apiError(res, status, code, detail) {
|
|
40
|
+
json(res, status, { error: { code, detail }, boundary: CONTROL_PLANE_BOUNDARY });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function safeEqual(a, b) {
|
|
44
|
+
// CP-11: compare fixed-length digests so key length does not short-circuit.
|
|
45
|
+
const left = createHash("sha256").update(String(a)).digest();
|
|
46
|
+
const right = createHash("sha256").update(String(b)).digest();
|
|
47
|
+
return timingSafeEqual(left, right);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function readJson(req, maxBodyBytes) {
|
|
51
|
+
return new Promise((resolve, reject) => {
|
|
52
|
+
let size = 0;
|
|
53
|
+
let tooLarge = false;
|
|
54
|
+
const chunks = [];
|
|
55
|
+
req.on("data", (chunk) => {
|
|
56
|
+
size += chunk.length;
|
|
57
|
+
if (size > maxBodyBytes) {
|
|
58
|
+
// Keep draining so the client can read the 413 instead of seeing a
|
|
59
|
+
// reset socket; stop buffering and reject at end of stream.
|
|
60
|
+
tooLarge = true;
|
|
61
|
+
chunks.length = 0;
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
if (tooLarge) return;
|
|
65
|
+
chunks.push(chunk);
|
|
66
|
+
});
|
|
67
|
+
req.on("end", () => {
|
|
68
|
+
if (tooLarge) {
|
|
69
|
+
const err = new Error("request body too large");
|
|
70
|
+
err.statusCode = 413;
|
|
71
|
+
err.code = "BODY_TOO_LARGE";
|
|
72
|
+
return reject(err);
|
|
73
|
+
}
|
|
74
|
+
if (chunks.length === 0) return resolve({});
|
|
75
|
+
try {
|
|
76
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
77
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
78
|
+
const err = new Error("body must be a JSON object");
|
|
79
|
+
err.statusCode = 400;
|
|
80
|
+
err.code = "INVALID_JSON";
|
|
81
|
+
return reject(err);
|
|
82
|
+
}
|
|
83
|
+
return resolve(parsed);
|
|
84
|
+
} catch {
|
|
85
|
+
const err = new Error("body is not valid JSON");
|
|
86
|
+
err.statusCode = 400;
|
|
87
|
+
err.code = "INVALID_JSON";
|
|
88
|
+
return reject(err);
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
req.on("error", reject);
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Build the request handler. Exported separately from the server so a host can
|
|
97
|
+
* mount it in its own HTTP stack or test it without a socket.
|
|
98
|
+
*/
|
|
99
|
+
export function createControlPlaneHandler({ controlPlane, apiKey, apiKeys, maxBodyBytes = MAX_BODY_BYTES } = {}) {
|
|
100
|
+
if (!controlPlane) throw new TypeError("CGCP/1: controlPlane is required");
|
|
101
|
+
const keys = Array.isArray(apiKeys) ? apiKeys.filter((k) => typeof k === "string" && k.length > 0) : [];
|
|
102
|
+
if (typeof apiKey === "string" && apiKey.length > 0) keys.unshift(apiKey);
|
|
103
|
+
const uniqKeys = [...new Set(keys)];
|
|
104
|
+
if (uniqKeys.length === 0) throw new TypeError("CGCP/1: apiKey or apiKeys is required");
|
|
105
|
+
const authFailures = new Map(); // ip -> { count, resetAt }
|
|
106
|
+
const AUTH_FAIL_WINDOW_MS = 60_000;
|
|
107
|
+
const AUTH_FAIL_LIMIT = 30;
|
|
108
|
+
|
|
109
|
+
function authThrottle(ip) {
|
|
110
|
+
const now = Date.now();
|
|
111
|
+
const rec = authFailures.get(ip);
|
|
112
|
+
if (!rec || now >= rec.resetAt) {
|
|
113
|
+
const fresh = { count: 0, resetAt: now + AUTH_FAIL_WINDOW_MS };
|
|
114
|
+
authFailures.set(ip, fresh);
|
|
115
|
+
return fresh;
|
|
116
|
+
}
|
|
117
|
+
return rec;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return async function handler(req, res) {
|
|
121
|
+
const url = new URL(req.url ?? "/", "http://control-plane.local");
|
|
122
|
+
const path = url.pathname;
|
|
123
|
+
const method = req.method ?? "GET";
|
|
124
|
+
|
|
125
|
+
if (path === "/health" && method === "GET") {
|
|
126
|
+
// CP-08: liveness only — no ledger read/verify, no store data.
|
|
127
|
+
return json(res, 200, {
|
|
128
|
+
ok: true,
|
|
129
|
+
version: CONTROL_PLANE_VERSION,
|
|
130
|
+
boundary: CONTROL_PLANE_BOUNDARY,
|
|
131
|
+
service: "coreguard-control-plane",
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const ip = req.socket?.remoteAddress || "unknown";
|
|
136
|
+
const authState = authThrottle(ip);
|
|
137
|
+
if (authState.count >= AUTH_FAIL_LIMIT) {
|
|
138
|
+
return apiError(res, 429, "RATE_LIMITED", "too many authentication failures");
|
|
139
|
+
}
|
|
140
|
+
const auth = req.headers.authorization ?? "";
|
|
141
|
+
const token = auth.startsWith("Bearer ") ? auth.slice(7) : "";
|
|
142
|
+
const authorized = uniqKeys.some((k) => safeEqual(token, k));
|
|
143
|
+
if (!authorized) {
|
|
144
|
+
authState.count += 1;
|
|
145
|
+
return apiError(res, 401, "UNAUTHORIZED", "a valid bearer API key is required");
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const auditMeta = {
|
|
149
|
+
actor: typeof req.headers["x-actor"] === "string" ? req.headers["x-actor"].slice(0, 200) : null,
|
|
150
|
+
requestId: typeof req.headers["x-request-id"] === "string" ? req.headers["x-request-id"].slice(0, 200) : null,
|
|
151
|
+
source: ip,
|
|
152
|
+
};
|
|
153
|
+
try {
|
|
154
|
+
return await controlPlane.withAuditMeta(auditMeta, async () => {
|
|
155
|
+
let body = {};
|
|
156
|
+
if (method === "POST" || method === "PUT" || method === "PATCH") body = await readJson(req, maxBodyBytes);
|
|
157
|
+
|
|
158
|
+
if (path === "/v1/version" && method === "GET") {
|
|
159
|
+
return json(res, 200, { version: CONTROL_PLANE_VERSION, boundary: CONTROL_PLANE_BOUNDARY });
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (path === "/v1/agents" && method === "GET") {
|
|
163
|
+
return json(res, 200, { agents: controlPlane.listAgents() });
|
|
164
|
+
}
|
|
165
|
+
if (path === "/v1/agents" && method === "POST") {
|
|
166
|
+
return json(res, 201, controlPlane.upsertAgent(body));
|
|
167
|
+
}
|
|
168
|
+
const revokeAgent = path.match(/^\/v1\/agents\/([^/]+)\/revoke$/);
|
|
169
|
+
if (revokeAgent && method === "POST") {
|
|
170
|
+
return json(res, 200, controlPlane.revokeAgent(decodeURIComponent(revokeAgent[1]), body.reason ?? ""));
|
|
171
|
+
}
|
|
172
|
+
const bind = path.match(/^\/v1\/agents\/([^/]+)\/policy$/);
|
|
173
|
+
if (bind && method === "POST") {
|
|
174
|
+
return json(res, 200, controlPlane.bindPolicy(decodeURIComponent(bind[1]), body.policyId));
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (path === "/v1/policies" && method === "GET") {
|
|
178
|
+
return json(res, 200, { policies: controlPlane.listPolicies() });
|
|
179
|
+
}
|
|
180
|
+
if (path === "/v1/policies" && method === "POST") {
|
|
181
|
+
return json(res, 201, controlPlane.upsertPolicy(body));
|
|
182
|
+
}
|
|
183
|
+
const policy = path.match(/^\/v1\/policies\/([^/]+)$/);
|
|
184
|
+
if (policy && method === "GET") {
|
|
185
|
+
const record = controlPlane.getPolicy(decodeURIComponent(policy[1]));
|
|
186
|
+
if (!record) return apiError(res, 404, "NOT_FOUND", "unknown policy");
|
|
187
|
+
return json(res, 200, record);
|
|
188
|
+
}
|
|
189
|
+
const revokePolicy = path.match(/^\/v1\/policies\/([^/]+)\/revoke$/);
|
|
190
|
+
if (revokePolicy && method === "POST") {
|
|
191
|
+
return json(res, 200, controlPlane.revokePolicy(decodeURIComponent(revokePolicy[1]), body.reason ?? ""));
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (path === "/v1/evaluate" && method === "POST") {
|
|
195
|
+
return json(res, 200, controlPlane.evaluate(body));
|
|
196
|
+
}
|
|
197
|
+
if (path === "/v1/authorize" && method === "POST") {
|
|
198
|
+
return json(res, 200, controlPlane.authorize(body));
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (path === "/v1/approvals" && method === "POST") {
|
|
202
|
+
return json(res, 201, controlPlane.requestApproval(body));
|
|
203
|
+
}
|
|
204
|
+
const approval = path.match(/^\/v1\/approvals\/([^/]+)$/);
|
|
205
|
+
if (approval && method === "GET") {
|
|
206
|
+
const record = controlPlane.getApproval(decodeURIComponent(approval[1]));
|
|
207
|
+
if (!record) return apiError(res, 404, "NOT_FOUND", "unknown approval");
|
|
208
|
+
return json(res, 200, record);
|
|
209
|
+
}
|
|
210
|
+
const decide = path.match(/^\/v1\/approvals\/([^/]+)\/decide$/);
|
|
211
|
+
if (decide && method === "POST") {
|
|
212
|
+
return json(
|
|
213
|
+
res,
|
|
214
|
+
200,
|
|
215
|
+
controlPlane.decideApproval(decodeURIComponent(decide[1]), {
|
|
216
|
+
decision: body.decision,
|
|
217
|
+
decidedBy: body.decidedBy ?? null,
|
|
218
|
+
reason: body.reason ?? null,
|
|
219
|
+
}),
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (path === "/v1/executions" && method === "GET") {
|
|
224
|
+
return json(res, 200, { executions: controlPlane.listExecutions({ limit: parseLimit(url.searchParams.get("limit"), 100) }) });
|
|
225
|
+
}
|
|
226
|
+
if (path === "/v1/executions" && method === "POST") {
|
|
227
|
+
const result = controlPlane.commitExecution(body);
|
|
228
|
+
return json(res, result.committed ? 201 : 409, result);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (path === "/v1/verifications" && method === "POST") {
|
|
232
|
+
return json(res, 201, controlPlane.recordVerification(body));
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (path === "/v1/spend" && method === "GET") {
|
|
236
|
+
return json(
|
|
237
|
+
res,
|
|
238
|
+
200,
|
|
239
|
+
controlPlane.spend({
|
|
240
|
+
agentId: url.searchParams.get("agentId"),
|
|
241
|
+
policyId: url.searchParams.get("policyId"),
|
|
242
|
+
}),
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
if (path === "/v1/audit" && method === "GET") {
|
|
247
|
+
return json(res, 200, { audit: controlPlane.auditReport({ limit: parseLimit(url.searchParams.get("limit"), 200) }).recentAudit });
|
|
248
|
+
}
|
|
249
|
+
if (path === "/v1/audit/verify" && method === "GET") {
|
|
250
|
+
return json(res, 200, controlPlane.verifyLedger());
|
|
251
|
+
}
|
|
252
|
+
if (path === "/v1/audit/anchor" && method === "GET") {
|
|
253
|
+
return json(res, 200, controlPlane.auditAnchor());
|
|
254
|
+
}
|
|
255
|
+
if (path === "/v1/audit/anchor/verify" && method === "POST") {
|
|
256
|
+
return json(res, 200, controlPlane.verifyAnchor(body));
|
|
257
|
+
}
|
|
258
|
+
if (path === "/v1/report" && method === "GET") {
|
|
259
|
+
return json(res, 200, controlPlane.auditReport({ limit: parseLimit(url.searchParams.get("limit"), 200) }));
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return apiError(res, 404, "NOT_FOUND", `${method} ${path} is not a control-plane route`);
|
|
263
|
+
});
|
|
264
|
+
} catch (err) {
|
|
265
|
+
// CP-10: stable public taxonomy; never leak internal paths/stack traces.
|
|
266
|
+
const code = err?.code;
|
|
267
|
+
const status = err?.statusCode;
|
|
268
|
+
if (status === 413 || code === "BODY_TOO_LARGE") {
|
|
269
|
+
return apiError(res, 413, "BODY_TOO_LARGE", "request body exceeds the configured limit");
|
|
270
|
+
}
|
|
271
|
+
if (code === "STORE_LOCKED") {
|
|
272
|
+
return apiError(res, 503, "STORE_UNAVAILABLE", "control plane store is temporarily unavailable");
|
|
273
|
+
}
|
|
274
|
+
if (code === "STORE_MISSING") {
|
|
275
|
+
return apiError(res, 503, "STORE_UNAVAILABLE", "control plane store is not initialized");
|
|
276
|
+
}
|
|
277
|
+
if (err instanceof TypeError) {
|
|
278
|
+
return apiError(res, 400, "INVALID_REQUEST", err.message || "invalid request");
|
|
279
|
+
}
|
|
280
|
+
if (status === 409 || code === "CONFLICT") {
|
|
281
|
+
return apiError(res, 409, "CONFLICT", "request conflicts with current state");
|
|
282
|
+
}
|
|
283
|
+
if (status === 400) {
|
|
284
|
+
const safeCode = typeof code === "string" && /^[A-Z0-9_]+$/.test(code) ? code : "INVALID_REQUEST";
|
|
285
|
+
const msg = typeof err?.message === "string" ? err.message : "invalid request";
|
|
286
|
+
return apiError(res, 400, safeCode, msg.startsWith("CGCP/1:") ? msg.replace(/^CGCP\/1:\s*/, "") : msg);
|
|
287
|
+
}
|
|
288
|
+
// Known CGCP operational errors: expose stable message without paths.
|
|
289
|
+
const msg = typeof err?.message === "string" ? err.message : "request failed";
|
|
290
|
+
if (msg.startsWith("CGCP/1:")) {
|
|
291
|
+
return apiError(res, 400, "INVALID_REQUEST", msg.replace(/^CGCP\/1:\s*/, ""));
|
|
292
|
+
}
|
|
293
|
+
return apiError(res, 500, "INTERNAL_ERROR", "internal control plane error");
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Create (but do not start) an HTTP server bound to one plane.
|
|
300
|
+
*/
|
|
301
|
+
export function createControlPlaneServer({ controlPlane, apiKey, maxBodyBytes = MAX_BODY_BYTES } = {}) {
|
|
302
|
+
const handler = createControlPlaneHandler({ controlPlane, apiKey, maxBodyBytes });
|
|
303
|
+
return createServer((req, res) => {
|
|
304
|
+
handler(req, res).catch(() => {
|
|
305
|
+
if (!res.headersSent) apiError(res, 500, "INTERNAL", "request failed");
|
|
306
|
+
});
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Open a plane and start its HTTP API. Port 0 asks the OS for a free port (the
|
|
312
|
+
* resolved URL is returned), which is what the example and tests use.
|
|
313
|
+
*/
|
|
314
|
+
export async function startControlPlaneServer({
|
|
315
|
+
storePath,
|
|
316
|
+
apiKey,
|
|
317
|
+
port = 0,
|
|
318
|
+
host = "127.0.0.1",
|
|
319
|
+
controlPlane = null,
|
|
320
|
+
maxBodyBytes = MAX_BODY_BYTES,
|
|
321
|
+
create = true,
|
|
322
|
+
} = {}) {
|
|
323
|
+
const plane = controlPlane ?? createControlPlane({ storePath, create });
|
|
324
|
+
const server = createControlPlaneServer({ controlPlane: plane, apiKey, maxBodyBytes });
|
|
325
|
+
await new Promise((resolve, reject) => {
|
|
326
|
+
server.once("error", reject);
|
|
327
|
+
server.listen(port, host, () => {
|
|
328
|
+
server.off("error", reject);
|
|
329
|
+
resolve();
|
|
330
|
+
});
|
|
331
|
+
});
|
|
332
|
+
const address = server.address();
|
|
333
|
+
const boundPort = typeof address === "object" && address ? address.port : port;
|
|
334
|
+
const baseUrl = `http://${host === "0.0.0.0" ? "127.0.0.1" : host}:${boundPort}`;
|
|
335
|
+
return {
|
|
336
|
+
server,
|
|
337
|
+
controlPlane: plane,
|
|
338
|
+
url: baseUrl,
|
|
339
|
+
port: boundPort,
|
|
340
|
+
close: () =>
|
|
341
|
+
new Promise((resolve, reject) => {
|
|
342
|
+
// Node's fetch keeps sockets alive; without this the close callback
|
|
343
|
+
// waits for the client pool and a test/CLI shutdown hangs.
|
|
344
|
+
server.closeAllConnections?.();
|
|
345
|
+
server.close((err) => (err ? reject(err) : resolve()));
|
|
346
|
+
}),
|
|
347
|
+
};
|
|
348
|
+
}
|