@coreguard/agent-commerce 0.1.3 → 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.
@@ -13,10 +13,18 @@
13
13
  */
14
14
 
15
15
  import { createServer } from "node:http";
16
- import { timingSafeEqual } from "node:crypto";
16
+ import { createHash, timingSafeEqual } from "node:crypto";
17
17
  import { CONTROL_PLANE_BOUNDARY, CONTROL_PLANE_VERSION, createControlPlane } from "./control-plane.mjs";
18
18
 
19
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
+ }
20
28
 
21
29
  function json(res, status, body) {
22
30
  const payload = JSON.stringify(body);
@@ -33,9 +41,9 @@ function apiError(res, status, code, detail) {
33
41
  }
34
42
 
35
43
  function safeEqual(a, b) {
36
- const left = Buffer.from(String(a));
37
- const right = Buffer.from(String(b));
38
- if (left.length !== right.length) return false;
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();
39
47
  return timingSafeEqual(left, right);
40
48
  }
41
49
 
@@ -88,9 +96,26 @@ async function readJson(req, maxBodyBytes) {
88
96
  * Build the request handler. Exported separately from the server so a host can
89
97
  * mount it in its own HTTP stack or test it without a socket.
90
98
  */
91
- export function createControlPlaneHandler({ controlPlane, apiKey, maxBodyBytes = MAX_BODY_BYTES } = {}) {
99
+ export function createControlPlaneHandler({ controlPlane, apiKey, apiKeys, maxBodyBytes = MAX_BODY_BYTES } = {}) {
92
100
  if (!controlPlane) throw new TypeError("CGCP/1: controlPlane is required");
93
- if (typeof apiKey !== "string" || apiKey.length === 0) throw new TypeError("CGCP/1: apiKey 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
+ }
94
119
 
95
120
  return async function handler(req, res) {
96
121
  const url = new URL(req.url ?? "/", "http://control-plane.local");
@@ -98,20 +123,35 @@ export function createControlPlaneHandler({ controlPlane, apiKey, maxBodyBytes =
98
123
  const method = req.method ?? "GET";
99
124
 
100
125
  if (path === "/health" && method === "GET") {
101
- const ledger = controlPlane.verifyLedger();
126
+ // CP-08: liveness only — no ledger read/verify, no store data.
102
127
  return json(res, 200, {
103
- ok: ledger.ok,
128
+ ok: true,
104
129
  version: CONTROL_PLANE_VERSION,
105
130
  boundary: CONTROL_PLANE_BOUNDARY,
106
- chain: { ok: ledger.chain.ok, length: ledger.chain.length },
131
+ service: "coreguard-control-plane",
107
132
  });
108
133
  }
109
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
+ }
110
140
  const auth = req.headers.authorization ?? "";
111
141
  const token = auth.startsWith("Bearer ") ? auth.slice(7) : "";
112
- if (!safeEqual(token, apiKey)) return apiError(res, 401, "UNAUTHORIZED", "a valid bearer API key is required");
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
+ }
113
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
+ };
114
153
  try {
154
+ return await controlPlane.withAuditMeta(auditMeta, async () => {
115
155
  let body = {};
116
156
  if (method === "POST" || method === "PUT" || method === "PATCH") body = await readJson(req, maxBodyBytes);
117
157
 
@@ -181,7 +221,7 @@ export function createControlPlaneHandler({ controlPlane, apiKey, maxBodyBytes =
181
221
  }
182
222
 
183
223
  if (path === "/v1/executions" && method === "GET") {
184
- return json(res, 200, { executions: controlPlane.listExecutions({ limit: Number(url.searchParams.get("limit") ?? 100) }) });
224
+ return json(res, 200, { executions: controlPlane.listExecutions({ limit: parseLimit(url.searchParams.get("limit"), 100) }) });
185
225
  }
186
226
  if (path === "/v1/executions" && method === "POST") {
187
227
  const result = controlPlane.commitExecution(body);
@@ -204,21 +244,53 @@ export function createControlPlaneHandler({ controlPlane, apiKey, maxBodyBytes =
204
244
  }
205
245
 
206
246
  if (path === "/v1/audit" && method === "GET") {
207
- return json(res, 200, { audit: controlPlane.auditReport({ limit: Number(url.searchParams.get("limit") ?? 200) }).recentAudit });
247
+ return json(res, 200, { audit: controlPlane.auditReport({ limit: parseLimit(url.searchParams.get("limit"), 200) }).recentAudit });
208
248
  }
209
249
  if (path === "/v1/audit/verify" && method === "GET") {
210
250
  return json(res, 200, controlPlane.verifyLedger());
211
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
+ }
212
258
  if (path === "/v1/report" && method === "GET") {
213
- return json(res, 200, controlPlane.auditReport({ limit: Number(url.searchParams.get("limit") ?? 200) }));
259
+ return json(res, 200, controlPlane.auditReport({ limit: parseLimit(url.searchParams.get("limit"), 200) }));
214
260
  }
215
261
 
216
262
  return apiError(res, 404, "NOT_FOUND", `${method} ${path} is not a control-plane route`);
263
+ });
217
264
  } catch (err) {
218
- const status = err?.statusCode ?? (err instanceof TypeError ? 400 : 400);
219
- if (status === 413) return apiError(res, 413, "BODY_TOO_LARGE", "request body exceeds the configured limit");
220
- // Never leak a stack trace to a caller.
221
- return apiError(res, status, err?.code ?? "INVALID_REQUEST", err?.message ?? "request failed");
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");
222
294
  }
223
295
  };
224
296
  }
@@ -246,8 +318,9 @@ export async function startControlPlaneServer({
246
318
  host = "127.0.0.1",
247
319
  controlPlane = null,
248
320
  maxBodyBytes = MAX_BODY_BYTES,
321
+ create = true,
249
322
  } = {}) {
250
- const plane = controlPlane ?? createControlPlane({ storePath });
323
+ const plane = controlPlane ?? createControlPlane({ storePath, create });
251
324
  const server = createControlPlaneServer({ controlPlane: plane, apiKey, maxBodyBytes });
252
325
  await new Promise((resolve, reject) => {
253
326
  server.once("error", reject);