sentinelayer-cli 0.6.2 → 0.8.0

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.
Files changed (159) hide show
  1. package/README.md +996 -996
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +64 -63
  6. package/src/agents/jules/config/definition.js +160 -160
  7. package/src/agents/jules/config/system-prompt.js +182 -182
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -17
  10. package/src/agents/jules/loop.js +457 -450
  11. package/src/agents/jules/pulse.js +10 -10
  12. package/src/agents/jules/stream.js +187 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +311 -309
  18. package/src/agents/jules/tools/aidenid-email.js +189 -189
  19. package/src/agents/jules/tools/auth-audit.js +1699 -1691
  20. package/src/agents/jules/tools/dispatch.js +340 -335
  21. package/src/agents/jules/tools/file-edit.js +2 -2
  22. package/src/agents/jules/tools/file-read.js +2 -2
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -2
  25. package/src/agents/jules/tools/grep.js +2 -2
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -2
  28. package/src/agents/jules/tools/runtime-audit.js +507 -507
  29. package/src/agents/jules/tools/shell.js +2 -2
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +64 -61
  32. package/src/agents/shared-tools/dispatch-core.js +320 -315
  33. package/src/agents/shared-tools/file-edit.js +180 -180
  34. package/src/agents/shared-tools/file-read.js +100 -100
  35. package/src/agents/shared-tools/glob.js +168 -168
  36. package/src/agents/shared-tools/grep.js +228 -228
  37. package/src/agents/shared-tools/index.js +46 -46
  38. package/src/agents/shared-tools/path-guards.js +161 -161
  39. package/src/agents/shared-tools/shell.js +383 -383
  40. package/src/ai/aidenid.js +1021 -1009
  41. package/src/ai/client.js +553 -553
  42. package/src/ai/domain-target-store.js +268 -268
  43. package/src/ai/identity-store.js +270 -270
  44. package/src/ai/proxy.js +137 -137
  45. package/src/ai/site-store.js +145 -145
  46. package/src/audit/agents/architecture.js +180 -180
  47. package/src/audit/agents/compliance.js +179 -179
  48. package/src/audit/agents/documentation.js +165 -165
  49. package/src/audit/agents/performance.js +145 -145
  50. package/src/audit/agents/security.js +215 -215
  51. package/src/audit/agents/testing.js +172 -172
  52. package/src/audit/orchestrator.js +557 -557
  53. package/src/audit/package.js +204 -204
  54. package/src/audit/registry.js +284 -284
  55. package/src/audit/replay.js +103 -103
  56. package/src/auth/gate.js +400 -371
  57. package/src/auth/http.js +681 -611
  58. package/src/auth/service.js +1106 -1106
  59. package/src/auth/session-store.js +813 -813
  60. package/src/cli.js +257 -252
  61. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  62. package/src/commands/ai/provision-governance.js +1272 -1272
  63. package/src/commands/ai/shared.js +147 -147
  64. package/src/commands/ai.js +11 -11
  65. package/src/commands/apply.js +12 -12
  66. package/src/commands/audit.js +1171 -1166
  67. package/src/commands/auth.js +419 -419
  68. package/src/commands/chat.js +191 -191
  69. package/src/commands/config.js +184 -184
  70. package/src/commands/cost.js +311 -311
  71. package/src/commands/daemon/core.js +850 -850
  72. package/src/commands/daemon/extended.js +1048 -1048
  73. package/src/commands/daemon/shared.js +213 -213
  74. package/src/commands/daemon.js +11 -11
  75. package/src/commands/guide.js +174 -174
  76. package/src/commands/ingest.js +58 -58
  77. package/src/commands/init.js +55 -55
  78. package/src/commands/legacy-args.js +10 -10
  79. package/src/commands/mcp.js +461 -461
  80. package/src/commands/omargate.js +29 -29
  81. package/src/commands/persona.js +20 -20
  82. package/src/commands/plugin.js +260 -260
  83. package/src/commands/policy.js +132 -132
  84. package/src/commands/prompt.js +238 -238
  85. package/src/commands/review.js +704 -704
  86. package/src/commands/scan.js +872 -872
  87. package/src/commands/session.js +590 -0
  88. package/src/commands/spec.js +778 -716
  89. package/src/commands/swarm.js +651 -651
  90. package/src/commands/telemetry.js +202 -202
  91. package/src/commands/watch.js +511 -511
  92. package/src/config/agent-dictionary.js +182 -182
  93. package/src/config/io.js +56 -56
  94. package/src/config/paths.js +18 -18
  95. package/src/config/schema.js +55 -55
  96. package/src/config/service.js +184 -184
  97. package/src/cost/budget.js +235 -235
  98. package/src/cost/history.js +188 -188
  99. package/src/cost/tracker.js +171 -171
  100. package/src/daemon/artifact-lineage.js +534 -534
  101. package/src/daemon/assignment-ledger.js +966 -770
  102. package/src/daemon/ast-parser-layer.js +258 -258
  103. package/src/daemon/budget-governor.js +633 -633
  104. package/src/daemon/callgraph-overlay.js +646 -646
  105. package/src/daemon/error-worker.js +1209 -626
  106. package/src/daemon/fix-cycle.js +384 -377
  107. package/src/daemon/hybrid-mapper.js +929 -929
  108. package/src/daemon/ingest-refresh.js +10 -9
  109. package/src/daemon/jira-lifecycle.js +767 -632
  110. package/src/daemon/operator-control.js +657 -657
  111. package/src/daemon/pulse.js +327 -327
  112. package/src/daemon/reliability-lane.js +471 -471
  113. package/src/daemon/scope-engine.js +1068 -0
  114. package/src/daemon/watchdog.js +971 -971
  115. package/src/events/schema.js +190 -0
  116. package/src/guide/generator.js +316 -316
  117. package/src/ingest/engine.js +918 -918
  118. package/src/interactive/index.js +97 -97
  119. package/src/legacy-cli.js +3161 -2994
  120. package/src/mcp/registry.js +695 -695
  121. package/src/memory/blackboard.js +301 -301
  122. package/src/memory/retrieval.js +581 -581
  123. package/src/plugin/manifest.js +553 -553
  124. package/src/policy/packs.js +144 -144
  125. package/src/prompt/generator.js +136 -118
  126. package/src/review/ai-review.js +679 -679
  127. package/src/review/local-review.js +1351 -1305
  128. package/src/review/omargate-interactive.js +68 -68
  129. package/src/review/omargate-orchestrator.js +404 -300
  130. package/src/review/persona-prompts.js +296 -296
  131. package/src/review/replay.js +235 -235
  132. package/src/review/report.js +664 -664
  133. package/src/review/scan-modes.js +48 -42
  134. package/src/review/spec-binding.js +487 -487
  135. package/src/scaffold/generator.js +67 -67
  136. package/src/scaffold/templates.js +150 -150
  137. package/src/scan/generator.js +418 -418
  138. package/src/scan/gh-secrets.js +107 -107
  139. package/src/session/agent-registry.js +352 -0
  140. package/src/session/daemon.js +801 -0
  141. package/src/session/paths.js +33 -0
  142. package/src/session/runtime-bridge.js +739 -0
  143. package/src/session/store.js +388 -0
  144. package/src/session/stream.js +325 -0
  145. package/src/spec/generator.js +619 -519
  146. package/src/spec/regenerate.js +237 -237
  147. package/src/spec/templates.js +91 -91
  148. package/src/swarm/dashboard.js +247 -247
  149. package/src/swarm/factory.js +363 -363
  150. package/src/swarm/pentest.js +934 -934
  151. package/src/swarm/registry.js +419 -419
  152. package/src/swarm/report.js +158 -158
  153. package/src/swarm/runtime.js +576 -576
  154. package/src/swarm/scenario-dsl.js +272 -272
  155. package/src/telemetry/ledger.js +302 -302
  156. package/src/telemetry/session-tracker.js +234 -234
  157. package/src/telemetry/sync.js +203 -203
  158. package/src/ui/command-hints.js +13 -13
  159. package/src/ui/markdown.js +220 -220
package/src/auth/http.js CHANGED
@@ -1,611 +1,681 @@
1
- import { setTimeout as sleep } from "node:timers/promises";
2
- import crypto from "node:crypto";
3
-
4
- /**
5
- * Default timeout applied to Sentinelayer API requests when no override is provided.
6
- * @type {number}
7
- */
8
- export const DEFAULT_REQUEST_TIMEOUT_MS = 20_000;
9
- export const DEFAULT_MAX_RETRIES = 2;
10
- export const DEFAULT_RETRY_DELAY_MS = 250;
11
- export const MAX_RETRY_DELAY_MS = 2_000;
12
- export const CIRCUIT_BREAKER_THRESHOLD = 5;
13
- export const CIRCUIT_BREAKER_COOLDOWN_MS = 30_000;
14
-
15
- const RETRYABLE_STATUS_CODES = new Set([408, 425, 429, 500, 502, 503, 504]);
16
- const CIRCUIT_TRACK_STATUS_CODES = new Set([401, 403, 408, 425, 429, 500, 502, 503, 504]);
17
- const circuitStateByScope = new Map();
18
- const REQUEST_ID_HEADERS = ["x-request-id", "request-id", "x-correlation-id"];
19
- const DEBUG_API_ERRORS_ENV = "SENTINELAYER_DEBUG_ERRORS";
20
- const MAX_API_ERROR_MESSAGE_LENGTH = 512;
21
- const IDEMPOTENCY_KEY_MIN_LENGTH = 32;
22
- const UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
23
- const PREFIXED_UUID_V4_PATTERN = /^[a-z0-9][a-z0-9_-]{1,48}-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
24
-
25
- function resolveCircuitScope(url) {
26
- try {
27
- const parsed = new URL(String(url));
28
- return parsed.origin;
29
- } catch {
30
- return "unknown";
31
- }
32
- }
33
-
34
- function getCircuitState(scope) {
35
- const key = String(scope || "unknown");
36
- if (!circuitStateByScope.has(key)) {
37
- circuitStateByScope.set(key, { consecutiveFailures: 0, openedAtMs: 0 });
38
- }
39
- return circuitStateByScope.get(key);
40
- }
41
-
42
- function normalizeApiError(errorPayload = {}) {
43
- const fallbackMessage = "Unknown API error";
44
- if (!errorPayload || typeof errorPayload !== "object" || Array.isArray(errorPayload)) {
45
- return {
46
- code: "UNKNOWN",
47
- message: sanitizeApiErrorMessage(fallbackMessage, fallbackMessage),
48
- requestId: null,
49
- };
50
- }
51
- const rawMessage = String(errorPayload.message || fallbackMessage);
52
- const safeMessage = sanitizeApiErrorMessage(rawMessage, fallbackMessage);
53
- const message = appendDebugContext(safeMessage, {
54
- code: String(errorPayload.code || "UNKNOWN"),
55
- requestId: errorPayload.request_id ? String(errorPayload.request_id) : null,
56
- });
57
- return {
58
- code: String(errorPayload.code || "UNKNOWN"),
59
- message,
60
- requestId: errorPayload.request_id ? String(errorPayload.request_id) : null,
61
- };
62
- }
63
-
64
- function resolveRequestId(headers) {
65
- if (!headers || typeof headers.get !== "function") {
66
- return null;
67
- }
68
- for (const headerName of REQUEST_ID_HEADERS) {
69
- const value = headers.get(headerName);
70
- if (value) {
71
- return String(value);
72
- }
73
- }
74
- return null;
75
- }
76
-
77
- function resolveIdempotencyKey(headers) {
78
- if (!headers) {
79
- return null;
80
- }
81
- if (typeof headers.get === "function") {
82
- const value =
83
- headers.get("idempotency-key") ||
84
- headers.get("Idempotency-Key") ||
85
- headers.get("IDEMPOTENCY-KEY");
86
- return String(value || "").trim() || null;
87
- }
88
- if (typeof headers !== "object") {
89
- return null;
90
- }
91
- for (const [key, value] of Object.entries(headers)) {
92
- if (String(key || "").toLowerCase() === "idempotency-key") {
93
- const normalized = String(value || "").trim();
94
- return normalized || null;
95
- }
96
- }
97
- return null;
98
- }
99
-
100
- function isValidIdempotencyKey(value) {
101
- const normalized = String(value || "").trim();
102
- if (!normalized) {
103
- return false;
104
- }
105
- if (UUID_V4_PATTERN.test(normalized)) {
106
- return true;
107
- }
108
- if (PREFIXED_UUID_V4_PATTERN.test(normalized)) {
109
- return true;
110
- }
111
- if (normalized.length < IDEMPOTENCY_KEY_MIN_LENGTH) {
112
- return false;
113
- }
114
- return /^[A-Za-z0-9_-]+$/.test(normalized);
115
- }
116
-
117
- function validateIdempotencyKey(value) {
118
- if (!isValidIdempotencyKey(value)) {
119
- throw new SentinelayerApiError("Idempotency-Key must be a UUIDv4 or a prefixed UUID.", {
120
- status: 400,
121
- code: "IDEMPOTENCY_KEY_INVALID",
122
- });
123
- }
124
- }
125
-
126
- function sanitizeOperationName(value) {
127
- const normalized = String(value || "").toLowerCase();
128
- const cleaned = normalized.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
129
- return cleaned.slice(0, 32) || "mutation";
130
- }
131
-
132
- function createIdempotencyKeyForOperation(operationName) {
133
- const op = sanitizeOperationName(operationName);
134
- let suffix;
135
- try {
136
- suffix = crypto.randomUUID();
137
- } catch {
138
- suffix = crypto.randomBytes(16).toString("hex");
139
- }
140
- return `sl-cli-${op}-${suffix}`;
141
- }
142
-
143
- function normalizeHeaderObject(headers) {
144
- if (!headers) {
145
- return {};
146
- }
147
- if (typeof headers.get === "function") {
148
- const normalized = {};
149
- for (const [key, value] of headers.entries()) {
150
- normalized[key] = value;
151
- }
152
- return normalized;
153
- }
154
- if (typeof headers !== "object") {
155
- return {};
156
- }
157
- return { ...headers };
158
- }
159
-
160
- function isMutationVerb(method) {
161
- const normalized = String(method || "").trim().toUpperCase();
162
- return (
163
- normalized === "POST" ||
164
- normalized === "PUT" ||
165
- normalized === "PATCH" ||
166
- normalized === "DELETE"
167
- );
168
- }
169
-
170
- function applyIdempotencyKey(headers, idempotencyKey) {
171
- const normalized = normalizeHeaderObject(headers);
172
- if (idempotencyKey && !resolveIdempotencyKey(normalized)) {
173
- normalized["Idempotency-Key"] = idempotencyKey;
174
- }
175
- return normalized;
176
- }
177
-
178
- export class SentinelayerApiError extends Error {
179
- /**
180
- * @param {string} message
181
- * @param {{ status?: number, code?: string, requestId?: string | null }} [options]
182
- */
183
- constructor(message, { status = 500, code = "UNKNOWN", requestId = null } = {}) {
184
- const safeMessage = sanitizeApiErrorMessage(message, "Sentinelayer API error");
185
- super(appendDebugContext(safeMessage, { code, status, requestId }));
186
- this.name = "SentinelayerApiError";
187
- this.status = Number(status || 500);
188
- this.code = String(code || "UNKNOWN");
189
- this.requestId = requestId ? String(requestId) : null;
190
- }
191
- }
192
-
193
- function normalizePositiveNumber(value, fallback) {
194
- const parsed = Number(value);
195
- if (!Number.isFinite(parsed) || parsed <= 0) {
196
- return fallback;
197
- }
198
- return parsed;
199
- }
200
-
201
- function normalizeNonNegativeInteger(value, fallback) {
202
- const parsed = Number(value);
203
- if (!Number.isFinite(parsed) || parsed < 0) {
204
- return fallback;
205
- }
206
- return Math.floor(parsed);
207
- }
208
-
209
- function parseRetryAfterMs(value) {
210
- const raw = String(value || "").trim();
211
- if (!raw) {
212
- return null;
213
- }
214
- const seconds = Number(raw);
215
- if (Number.isFinite(seconds) && seconds >= 0) {
216
- return Math.round(seconds * 1000);
217
- }
218
- const parsedDate = Date.parse(raw);
219
- if (Number.isFinite(parsedDate)) {
220
- const delta = parsedDate - Date.now();
221
- if (delta > 0) {
222
- return delta;
223
- }
224
- }
225
- return null;
226
- }
227
-
228
- function computeBackoffMs({ attempt, retryDelayMs, retryAfterHeader }) {
229
- const retryAfterMs = parseRetryAfterMs(retryAfterHeader);
230
- if (retryAfterMs !== null) {
231
- return Math.min(retryAfterMs, MAX_RETRY_DELAY_MS);
232
- }
233
- const exponent = Math.max(0, Number(attempt) - 1);
234
- const computed = Math.round(retryDelayMs * Math.pow(2, exponent));
235
- return Math.min(Math.max(1, computed), MAX_RETRY_DELAY_MS);
236
- }
237
-
238
- function isCircuitOpen(scope) {
239
- const circuitState = getCircuitState(scope);
240
- if (circuitState.openedAtMs <= 0) {
241
- return false;
242
- }
243
- if (Date.now() - circuitState.openedAtMs >= CIRCUIT_BREAKER_COOLDOWN_MS) {
244
- circuitState.openedAtMs = 0;
245
- circuitState.consecutiveFailures = 0;
246
- return false;
247
- }
248
- return true;
249
- }
250
-
251
- function recordFailureForCircuit(scope) {
252
- const circuitState = getCircuitState(scope);
253
- circuitState.consecutiveFailures += 1;
254
- if (circuitState.consecutiveFailures >= CIRCUIT_BREAKER_THRESHOLD) {
255
- circuitState.openedAtMs = Date.now();
256
- }
257
- }
258
-
259
- function shouldExposeApiErrorDetails() {
260
- const normalized = String(process.env[DEBUG_API_ERRORS_ENV] || "").trim().toLowerCase();
261
- return normalized === "true" || normalized === "1" || normalized === "yes";
262
- }
263
-
264
- function isTestNonIdempotentAllowed() {
265
- return (
266
- process.env.NODE_ENV === "test" &&
267
- process.env.SENTINELAYER_ALLOW_NON_IDEMPOTENT === "1" &&
268
- process.env.SENTINELAYER_CLI_TEST_MODE === "1" &&
269
- !process.env.CI
270
- );
271
- }
272
-
273
- function sanitizeApiErrorMessage(message, fallback = "Sentinelayer API error") {
274
- const fallbackMessage = String(fallback || "Sentinelayer API error");
275
- const normalized = String(message || "").trim();
276
- const candidate = normalized || fallbackMessage;
277
- const sanitized = candidate
278
- .replace(/\bbearer\s+[a-z0-9._~+/=-]+\b/gi, "bearer [REDACTED]")
279
- .replace(/\b(token|secret|password|api[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token)\b\s*[:=]\s*["']?[^"'\s,;]+["']?/gi, "$1=[REDACTED]")
280
- .replace(/\b[a-z0-9_-]+\.[a-z0-9_-]+\.[a-z0-9_-]+\b/gi, "[REDACTED_JWT]")
281
- .replace(/\bhttps?:\/\/[^\s"'`]+/gi, () => "<redacted-url>")
282
- .replace(/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/gi, "<redacted-email>");
283
- if (sanitized.length <= MAX_API_ERROR_MESSAGE_LENGTH) {
284
- return sanitized;
285
- }
286
- return `${sanitized.slice(0, MAX_API_ERROR_MESSAGE_LENGTH - 3)}...`;
287
- }
288
-
289
- function anonymizeRequestIdForDebug(requestId) {
290
- const normalized = String(requestId || "").trim();
291
- if (!normalized) {
292
- return "";
293
- }
294
- return crypto.createHash("sha256").update(normalized).digest("hex").slice(0, 12);
295
- }
296
-
297
- function appendDebugContext(safeMessage, { code, status, requestId } = {}) {
298
- if (!shouldExposeApiErrorDetails()) {
299
- return safeMessage;
300
- }
301
- const parts = [];
302
- const normalizedCode = String(code || "").trim();
303
- const normalizedStatus = Number.isFinite(Number(status)) ? Number(status) : null;
304
- const requestIdHash = anonymizeRequestIdForDebug(requestId);
305
- if (normalizedCode) parts.push(`code=${normalizedCode}`);
306
- if (normalizedStatus) parts.push(`status=${normalizedStatus}`);
307
- if (requestIdHash) parts.push(`request_id_hash=${requestIdHash}`);
308
- if (parts.length === 0) return safeMessage;
309
- return `${safeMessage} (${parts.join(", ")})`;
310
- }
311
-
312
- function recordSuccessForCircuit(scope) {
313
- const circuitState = getCircuitState(scope);
314
- circuitState.consecutiveFailures = 0;
315
- circuitState.openedAtMs = 0;
316
- }
317
-
318
- function shouldRetryStatus(statusCode) {
319
- return RETRYABLE_STATUS_CODES.has(Number(statusCode || 0));
320
- }
321
-
322
- function shouldRecordFailureForStatus(statusCode) {
323
- return CIRCUIT_TRACK_STATUS_CODES.has(Number(statusCode || 0));
324
- }
325
-
326
- export function __resetRequestCircuitForTests(scope) {
327
- if (scope) {
328
- const circuitState = getCircuitState(scope);
329
- circuitState.consecutiveFailures = 0;
330
- circuitState.openedAtMs = 0;
331
- return;
332
- }
333
- circuitStateByScope.clear();
334
- }
335
-
336
- /**
337
- * Execute an HTTP request against the Sentinelayer API and parse a JSON response.
338
- * Throws `SentinelayerApiError` for transport errors, timeouts, API failures, and invalid JSON.
339
- *
340
- * @param {string} url
341
- * @param {{
342
- * method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
343
- * headers?: Record<string, string>,
344
- * body?: unknown,
345
- * idempotencyKey?: string | null,
346
- * allowNonIdempotent?: boolean,
347
- * timeoutMs?: number
348
- * maxRetries?: number,
349
- * retryDelayMs?: number
350
- * allowEmptyBody?: boolean
351
- * }} [options]
352
- * @returns {Promise<any>}
353
- */
354
- export async function requestJson(
355
- url,
356
- {
357
- method = "GET",
358
- headers = {},
359
- body,
360
- idempotencyKey = null,
361
- allowNonIdempotent = false,
362
- timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
363
- maxRetries = DEFAULT_MAX_RETRIES,
364
- retryDelayMs = DEFAULT_RETRY_DELAY_MS,
365
- allowEmptyBody = false,
366
- } = {}
367
- ) {
368
- const normalizedMethod = String(method || "GET").trim().toUpperCase();
369
- const explicitIdempotencyKey = String(idempotencyKey || "").trim() || null;
370
- const existingIdempotencyKey = explicitIdempotencyKey || resolveIdempotencyKey(headers);
371
- const isMutationMethod = isMutationVerb(normalizedMethod);
372
- const resolvedIdempotencyKey = existingIdempotencyKey;
373
- const requestHeaders = applyIdempotencyKey(headers, resolvedIdempotencyKey);
374
- const outgoingHeaders = { ...requestHeaders };
375
- if (body !== undefined) {
376
- outgoingHeaders["Content-Type"] = "application/json";
377
- }
378
- const isIdempotentMutation = Boolean(resolvedIdempotencyKey);
379
- const allowUnsafeMutation = Boolean(allowNonIdempotent) && isTestNonIdempotentAllowed();
380
- if (isMutationMethod && !isIdempotentMutation && !allowUnsafeMutation) {
381
- throw new SentinelayerApiError("Idempotency-Key is required for mutation requests.", {
382
- status: 400,
383
- code: "IDEMPOTENCY_KEY_REQUIRED",
384
- });
385
- }
386
- if (isMutationMethod && isIdempotentMutation) {
387
- validateIdempotencyKey(resolvedIdempotencyKey);
388
- }
389
- const retryableMethod =
390
- normalizedMethod === "GET" ||
391
- normalizedMethod === "HEAD" ||
392
- normalizedMethod === "OPTIONS" ||
393
- (isIdempotentMutation &&
394
- (normalizedMethod === "POST" ||
395
- normalizedMethod === "PUT" ||
396
- normalizedMethod === "PATCH" ||
397
- normalizedMethod === "DELETE"));
398
- const circuitScope = resolveCircuitScope(url);
399
- if (isCircuitOpen(circuitScope)) {
400
- throw new SentinelayerApiError("Request circuit breaker is open after consecutive API failures.", {
401
- status: 503,
402
- code: "CIRCUIT_OPEN",
403
- });
404
- }
405
-
406
- const normalizedTimeoutMs = normalizePositiveNumber(timeoutMs, DEFAULT_REQUEST_TIMEOUT_MS);
407
- const normalizedMaxRetries = normalizeNonNegativeInteger(maxRetries, DEFAULT_MAX_RETRIES);
408
- const normalizedRetryDelayMs = normalizePositiveNumber(retryDelayMs, DEFAULT_RETRY_DELAY_MS);
409
-
410
- let lastRetryableError = null;
411
- for (let attempt = 0; attempt <= normalizedMaxRetries; attempt += 1) {
412
- const controller = new AbortController();
413
- let timeoutTriggered = false;
414
- let timeoutHandle;
415
- timeoutHandle = setTimeout(() => {
416
- timeoutTriggered = true;
417
- controller.abort();
418
- }, normalizedTimeoutMs);
419
-
420
- try {
421
- const response = await fetch(String(url), {
422
- method: normalizedMethod,
423
- headers: outgoingHeaders,
424
- body: body === undefined ? undefined : JSON.stringify(body),
425
- redirect: "error",
426
- signal: controller.signal,
427
- });
428
-
429
- const rawBody = await response.text();
430
- const trimmedBody = rawBody.trim();
431
- const contentType = response.headers.get("content-type") || "";
432
- const isJson = /application\/json/i.test(contentType);
433
- let json = {};
434
- if (!trimmedBody) {
435
- const statusCode = Number(response.status || 0);
436
- const allowEmpty = Boolean(allowEmptyBody) || statusCode === 204 || statusCode === 205;
437
- if (response.ok && !allowEmpty) {
438
- const requestId = resolveRequestId(response.headers);
439
- throw new SentinelayerApiError("Empty response body returned by API.", {
440
- status: response.status,
441
- code: "EMPTY_BODY",
442
- requestId,
443
- });
444
- }
445
- } else {
446
- if (response.ok && !isJson) {
447
- const requestId = resolveRequestId(response.headers);
448
- throw new SentinelayerApiError("Invalid content-type returned by API.", {
449
- status: response.status,
450
- code: "INVALID_CONTENT_TYPE",
451
- requestId,
452
- });
453
- }
454
- if (isJson) {
455
- try {
456
- json = JSON.parse(rawBody);
457
- } catch {
458
- const requestId = resolveRequestId(response.headers);
459
- if (response.ok) {
460
- throw new SentinelayerApiError("Invalid JSON returned by API.", {
461
- status: response.status,
462
- code: "INVALID_JSON",
463
- requestId,
464
- });
465
- }
466
- }
467
- }
468
- }
469
-
470
- if (response.ok) {
471
- recordSuccessForCircuit(circuitScope);
472
- return json;
473
- }
474
-
475
- const apiError = normalizeApiError(json && typeof json === "object" ? json.error : {});
476
- const requestId = apiError.requestId || resolveRequestId(response.headers);
477
- const statusCode = Number(response.status || 500);
478
- const retryable = retryableMethod && shouldRetryStatus(statusCode);
479
- const shouldRecordCircuitFailure = shouldRecordFailureForStatus(statusCode);
480
- const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"));
481
- const error = new SentinelayerApiError(apiError.message, {
482
- status: statusCode,
483
- code: apiError.code,
484
- requestId,
485
- });
486
- error.retryAfterMs = retryAfterMs;
487
-
488
- if (!retryable || attempt >= normalizedMaxRetries) {
489
- if (shouldRecordCircuitFailure) {
490
- recordFailureForCircuit(circuitScope);
491
- }
492
- throw error;
493
- }
494
-
495
- lastRetryableError = error;
496
- const delayMs = computeBackoffMs({
497
- attempt: attempt + 1,
498
- retryDelayMs: normalizedRetryDelayMs,
499
- retryAfterHeader: response.headers.get("retry-after"),
500
- });
501
- await sleep(delayMs);
502
- continue;
503
- } catch (error) {
504
- if (error instanceof SentinelayerApiError) {
505
- throw error;
506
- }
507
-
508
- const isAbortError = Boolean(error && typeof error === "object" && error.name === "AbortError");
509
- const abortMessage = error instanceof Error ? error.message : String(error || "");
510
- const abortReason =
511
- isAbortError && !timeoutTriggered && /cancel/i.test(abortMessage) ? "CANCELLED" : "TIMEOUT";
512
- const abortCode = isAbortError ? abortReason : "NETWORK_ERROR";
513
- const abortStatus = isAbortError ? (abortReason === "CANCELLED" ? 499 : 408) : 503;
514
- const normalizedError = new SentinelayerApiError(
515
- isAbortError
516
- ? (abortReason === "CANCELLED" ? "Request cancelled." : "Request timed out.")
517
- : (error instanceof Error ? error.message : String(error || "Request failed")),
518
- {
519
- status: abortStatus,
520
- code: abortCode,
521
- }
522
- );
523
-
524
- if (!retryableMethod || attempt >= normalizedMaxRetries) {
525
- recordFailureForCircuit(circuitScope);
526
- throw normalizedError;
527
- }
528
-
529
- lastRetryableError = normalizedError;
530
- const delayMs = computeBackoffMs({
531
- attempt: attempt + 1,
532
- retryDelayMs: normalizedRetryDelayMs,
533
- retryAfterHeader: null,
534
- });
535
- await sleep(delayMs);
536
- continue;
537
- } finally {
538
- if (timeoutHandle) {
539
- clearTimeout(timeoutHandle);
540
- }
541
- await sleep(0);
542
- }
543
- }
544
-
545
- if (lastRetryableError instanceof SentinelayerApiError) {
546
- throw lastRetryableError;
547
- }
548
- throw new SentinelayerApiError("Request failed without a terminal response.", {
549
- status: 503,
550
- code: "NETWORK_ERROR",
551
- });
552
- }
553
-
554
- /**
555
- * Execute an HTTP mutation request and auto-derive an idempotency key when missing.
556
- *
557
- * @param {string} url
558
- * @param {{
559
- * method?: "POST" | "PUT" | "PATCH" | "DELETE",
560
- * headers?: Record<string, string>,
561
- * body?: unknown,
562
- * idempotencyKey?: string | null,
563
- * operationName: string,
564
- * timeoutMs?: number
565
- * maxRetries?: number,
566
- * retryDelayMs?: number
567
- * allowEmptyBody?: boolean
568
- * }} options
569
- * @returns {Promise<any>}
570
- */
571
- export async function requestJsonMutation(
572
- url,
573
- {
574
- method = "POST",
575
- headers = {},
576
- body,
577
- idempotencyKey = null,
578
- operationName,
579
- timeoutMs,
580
- maxRetries,
581
- retryDelayMs,
582
- allowEmptyBody = false,
583
- } = {}
584
- ) {
585
- const normalizedMethod = String(method || "POST").trim().toUpperCase();
586
- if (!isMutationVerb(normalizedMethod)) {
587
- throw new SentinelayerApiError("requestJsonMutation requires a mutation HTTP method.", {
588
- status: 400,
589
- code: "INVALID_MUTATION_METHOD",
590
- });
591
- }
592
- const resolvedOperation = String(operationName || "").trim();
593
- if (!resolvedOperation) {
594
- throw new SentinelayerApiError("requestJsonMutation requires an operationName.", {
595
- status: 400,
596
- code: "OPERATION_NAME_REQUIRED",
597
- });
598
- }
599
- const resolvedIdempotencyKey =
600
- String(idempotencyKey || "").trim() || createIdempotencyKeyForOperation(resolvedOperation);
601
- return requestJson(url, {
602
- method: normalizedMethod,
603
- headers,
604
- body,
605
- idempotencyKey: resolvedIdempotencyKey,
606
- timeoutMs,
607
- maxRetries,
608
- retryDelayMs,
609
- allowEmptyBody,
610
- });
611
- }
1
+ import { setTimeout as sleep } from "node:timers/promises";
2
+ import crypto from "node:crypto";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+
7
+ /**
8
+ * Default timeout applied to Sentinelayer API requests when no override is provided.
9
+ * @type {number}
10
+ */
11
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 20_000;
12
+ export const DEFAULT_MAX_RETRIES = 2;
13
+ export const DEFAULT_RETRY_DELAY_MS = 250;
14
+ export const MAX_RETRY_DELAY_MS = 2_000;
15
+ export const CIRCUIT_BREAKER_THRESHOLD = 5;
16
+ export const CIRCUIT_BREAKER_COOLDOWN_MS = 30_000;
17
+
18
+ const RETRYABLE_STATUS_CODES = new Set([408, 425, 429, 500, 502, 503, 504]);
19
+ const CIRCUIT_TRACK_STATUS_CODES = new Set([401, 403, 408, 425, 429, 500, 502, 503, 504]);
20
+ const circuitStateByScope = new Map();
21
+
22
+ // File-backed cache. Lets cooldown + failure counts survive across CLI
23
+ // invocations without it, each new process hammers a degraded upstream
24
+ // until it hits the threshold again. Best-effort: if file ops fail, we
25
+ // silently fall back to in-memory behavior (no hard dependency).
26
+ const CIRCUIT_STATE_FILE = (() => {
27
+ const base = process.env.SENTINELAYER_CIRCUIT_STATE_DIR ||
28
+ path.join(os.homedir() || os.tmpdir(), ".sentinelayer");
29
+ try {
30
+ fs.mkdirSync(base, { recursive: true });
31
+ } catch {
32
+ /* noop */
33
+ }
34
+ return path.join(base, "circuit-state.json");
35
+ })();
36
+ let circuitStateLoaded = false;
37
+
38
+ function loadCircuitStateFromDisk() {
39
+ if (circuitStateLoaded) return;
40
+ circuitStateLoaded = true;
41
+ try {
42
+ const raw = fs.readFileSync(CIRCUIT_STATE_FILE, "utf-8");
43
+ const parsed = JSON.parse(raw);
44
+ if (!parsed || typeof parsed !== "object") return;
45
+ const now = Date.now();
46
+ for (const [key, value] of Object.entries(parsed)) {
47
+ if (!value || typeof value !== "object") continue;
48
+ const consecutiveFailures = Number(value.consecutiveFailures) || 0;
49
+ const openedAtMs = Number(value.openedAtMs) || 0;
50
+ // TTL: only carry over entries within the cooldown window — older
51
+ // entries are stale and should reset naturally on this process.
52
+ if (openedAtMs > 0 && now - openedAtMs < CIRCUIT_BREAKER_COOLDOWN_MS) {
53
+ circuitStateByScope.set(String(key), { consecutiveFailures, openedAtMs });
54
+ }
55
+ }
56
+ } catch {
57
+ /* noop: missing, corrupt, or unreadable — start fresh */
58
+ }
59
+ }
60
+
61
+ function persistCircuitState() {
62
+ try {
63
+ const snapshot = {};
64
+ for (const [key, value] of circuitStateByScope.entries()) {
65
+ snapshot[key] = {
66
+ consecutiveFailures: value.consecutiveFailures || 0,
67
+ openedAtMs: value.openedAtMs || 0,
68
+ };
69
+ }
70
+ const tmp = `${CIRCUIT_STATE_FILE}.${process.pid}.tmp`;
71
+ fs.writeFileSync(tmp, JSON.stringify(snapshot), "utf-8");
72
+ fs.renameSync(tmp, CIRCUIT_STATE_FILE);
73
+ } catch {
74
+ /* noop */
75
+ }
76
+ }
77
+ const REQUEST_ID_HEADERS = ["x-request-id", "request-id", "x-correlation-id"];
78
+ const DEBUG_API_ERRORS_ENV = "SENTINELAYER_DEBUG_ERRORS";
79
+ const MAX_API_ERROR_MESSAGE_LENGTH = 512;
80
+ const IDEMPOTENCY_KEY_MIN_LENGTH = 32;
81
+ const UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
82
+ const PREFIXED_UUID_V4_PATTERN = /^[a-z0-9][a-z0-9_-]{1,48}-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
83
+
84
+ function resolveCircuitScope(url) {
85
+ try {
86
+ const parsed = new URL(String(url));
87
+ return parsed.origin;
88
+ } catch {
89
+ return "unknown";
90
+ }
91
+ }
92
+
93
+ function getCircuitState(scope) {
94
+ loadCircuitStateFromDisk();
95
+ const key = String(scope || "unknown");
96
+ if (!circuitStateByScope.has(key)) {
97
+ circuitStateByScope.set(key, { consecutiveFailures: 0, openedAtMs: 0 });
98
+ }
99
+ return circuitStateByScope.get(key);
100
+ }
101
+
102
+ function normalizeApiError(errorPayload = {}) {
103
+ const fallbackMessage = "Unknown API error";
104
+ if (!errorPayload || typeof errorPayload !== "object" || Array.isArray(errorPayload)) {
105
+ return {
106
+ code: "UNKNOWN",
107
+ message: sanitizeApiErrorMessage(fallbackMessage, fallbackMessage),
108
+ requestId: null,
109
+ };
110
+ }
111
+ const rawMessage = String(errorPayload.message || fallbackMessage);
112
+ const safeMessage = sanitizeApiErrorMessage(rawMessage, fallbackMessage);
113
+ const message = appendDebugContext(safeMessage, {
114
+ code: String(errorPayload.code || "UNKNOWN"),
115
+ requestId: errorPayload.request_id ? String(errorPayload.request_id) : null,
116
+ });
117
+ return {
118
+ code: String(errorPayload.code || "UNKNOWN"),
119
+ message,
120
+ requestId: errorPayload.request_id ? String(errorPayload.request_id) : null,
121
+ };
122
+ }
123
+
124
+ function resolveRequestId(headers) {
125
+ if (!headers || typeof headers.get !== "function") {
126
+ return null;
127
+ }
128
+ for (const headerName of REQUEST_ID_HEADERS) {
129
+ const value = headers.get(headerName);
130
+ if (value) {
131
+ return String(value);
132
+ }
133
+ }
134
+ return null;
135
+ }
136
+
137
+ function resolveIdempotencyKey(headers) {
138
+ if (!headers) {
139
+ return null;
140
+ }
141
+ if (typeof headers.get === "function") {
142
+ const value =
143
+ headers.get("idempotency-key") ||
144
+ headers.get("Idempotency-Key") ||
145
+ headers.get("IDEMPOTENCY-KEY");
146
+ return String(value || "").trim() || null;
147
+ }
148
+ if (typeof headers !== "object") {
149
+ return null;
150
+ }
151
+ for (const [key, value] of Object.entries(headers)) {
152
+ if (String(key || "").toLowerCase() === "idempotency-key") {
153
+ const normalized = String(value || "").trim();
154
+ return normalized || null;
155
+ }
156
+ }
157
+ return null;
158
+ }
159
+
160
+ function isValidIdempotencyKey(value) {
161
+ const normalized = String(value || "").trim();
162
+ if (!normalized) {
163
+ return false;
164
+ }
165
+ if (UUID_V4_PATTERN.test(normalized)) {
166
+ return true;
167
+ }
168
+ if (PREFIXED_UUID_V4_PATTERN.test(normalized)) {
169
+ return true;
170
+ }
171
+ if (normalized.length < IDEMPOTENCY_KEY_MIN_LENGTH) {
172
+ return false;
173
+ }
174
+ return /^[A-Za-z0-9_-]+$/.test(normalized);
175
+ }
176
+
177
+ function validateIdempotencyKey(value) {
178
+ if (!isValidIdempotencyKey(value)) {
179
+ throw new SentinelayerApiError("Idempotency-Key must be a UUIDv4 or a prefixed UUID.", {
180
+ status: 400,
181
+ code: "IDEMPOTENCY_KEY_INVALID",
182
+ });
183
+ }
184
+ }
185
+
186
+ function sanitizeOperationName(value) {
187
+ const normalized = String(value || "").toLowerCase();
188
+ const cleaned = normalized.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
189
+ return cleaned.slice(0, 32) || "mutation";
190
+ }
191
+
192
+ function createIdempotencyKeyForOperation(operationName) {
193
+ const op = sanitizeOperationName(operationName);
194
+ let suffix;
195
+ try {
196
+ suffix = crypto.randomUUID();
197
+ } catch {
198
+ suffix = crypto.randomBytes(16).toString("hex");
199
+ }
200
+ return `sl-cli-${op}-${suffix}`;
201
+ }
202
+
203
+ function normalizeHeaderObject(headers) {
204
+ if (!headers) {
205
+ return {};
206
+ }
207
+ if (typeof headers.get === "function") {
208
+ const normalized = {};
209
+ for (const [key, value] of headers.entries()) {
210
+ normalized[key] = value;
211
+ }
212
+ return normalized;
213
+ }
214
+ if (typeof headers !== "object") {
215
+ return {};
216
+ }
217
+ return { ...headers };
218
+ }
219
+
220
+ function isMutationVerb(method) {
221
+ const normalized = String(method || "").trim().toUpperCase();
222
+ return (
223
+ normalized === "POST" ||
224
+ normalized === "PUT" ||
225
+ normalized === "PATCH" ||
226
+ normalized === "DELETE"
227
+ );
228
+ }
229
+
230
+ function applyIdempotencyKey(headers, idempotencyKey) {
231
+ const normalized = normalizeHeaderObject(headers);
232
+ if (idempotencyKey && !resolveIdempotencyKey(normalized)) {
233
+ normalized["Idempotency-Key"] = idempotencyKey;
234
+ }
235
+ return normalized;
236
+ }
237
+
238
+ export class SentinelayerApiError extends Error {
239
+ /**
240
+ * @param {string} message
241
+ * @param {{ status?: number, code?: string, requestId?: string | null }} [options]
242
+ */
243
+ constructor(message, { status = 500, code = "UNKNOWN", requestId = null } = {}) {
244
+ const safeMessage = sanitizeApiErrorMessage(message, "Sentinelayer API error");
245
+ super(appendDebugContext(safeMessage, { code, status, requestId }));
246
+ this.name = "SentinelayerApiError";
247
+ this.status = Number(status || 500);
248
+ this.code = String(code || "UNKNOWN");
249
+ this.requestId = requestId ? String(requestId) : null;
250
+ }
251
+ }
252
+
253
+ function normalizePositiveNumber(value, fallback) {
254
+ const parsed = Number(value);
255
+ if (!Number.isFinite(parsed) || parsed <= 0) {
256
+ return fallback;
257
+ }
258
+ return parsed;
259
+ }
260
+
261
+ function normalizeNonNegativeInteger(value, fallback) {
262
+ const parsed = Number(value);
263
+ if (!Number.isFinite(parsed) || parsed < 0) {
264
+ return fallback;
265
+ }
266
+ return Math.floor(parsed);
267
+ }
268
+
269
+ function parseRetryAfterMs(value) {
270
+ const raw = String(value || "").trim();
271
+ if (!raw) {
272
+ return null;
273
+ }
274
+ const seconds = Number(raw);
275
+ if (Number.isFinite(seconds) && seconds >= 0) {
276
+ return Math.round(seconds * 1000);
277
+ }
278
+ const parsedDate = Date.parse(raw);
279
+ if (Number.isFinite(parsedDate)) {
280
+ const delta = parsedDate - Date.now();
281
+ if (delta > 0) {
282
+ return delta;
283
+ }
284
+ }
285
+ return null;
286
+ }
287
+
288
+ function computeBackoffMs({ attempt, retryDelayMs, retryAfterHeader }) {
289
+ const retryAfterMs = parseRetryAfterMs(retryAfterHeader);
290
+ if (retryAfterMs !== null) {
291
+ return Math.min(retryAfterMs, MAX_RETRY_DELAY_MS);
292
+ }
293
+ const exponent = Math.max(0, Number(attempt) - 1);
294
+ const computed = Math.round(retryDelayMs * Math.pow(2, exponent));
295
+ return Math.min(Math.max(1, computed), MAX_RETRY_DELAY_MS);
296
+ }
297
+
298
+ function isCircuitOpen(scope) {
299
+ const circuitState = getCircuitState(scope);
300
+ if (circuitState.openedAtMs <= 0) {
301
+ return false;
302
+ }
303
+ if (Date.now() - circuitState.openedAtMs >= CIRCUIT_BREAKER_COOLDOWN_MS) {
304
+ circuitState.openedAtMs = 0;
305
+ circuitState.consecutiveFailures = 0;
306
+ persistCircuitState();
307
+ return false;
308
+ }
309
+ return true;
310
+ }
311
+
312
+ function recordFailureForCircuit(scope) {
313
+ const circuitState = getCircuitState(scope);
314
+ circuitState.consecutiveFailures += 1;
315
+ if (circuitState.consecutiveFailures >= CIRCUIT_BREAKER_THRESHOLD) {
316
+ circuitState.openedAtMs = Date.now();
317
+ }
318
+ persistCircuitState();
319
+ }
320
+
321
+ function shouldExposeApiErrorDetails() {
322
+ const normalized = String(process.env[DEBUG_API_ERRORS_ENV] || "").trim().toLowerCase();
323
+ return normalized === "true" || normalized === "1" || normalized === "yes";
324
+ }
325
+
326
+ function isTestNonIdempotentAllowed() {
327
+ return (
328
+ process.env.NODE_ENV === "test" &&
329
+ process.env.SENTINELAYER_ALLOW_NON_IDEMPOTENT === "1" &&
330
+ process.env.SENTINELAYER_CLI_TEST_MODE === "1" &&
331
+ !process.env.CI
332
+ );
333
+ }
334
+
335
+ function sanitizeApiErrorMessage(message, fallback = "Sentinelayer API error") {
336
+ const fallbackMessage = String(fallback || "Sentinelayer API error");
337
+ const normalized = String(message || "").trim();
338
+ const candidate = normalized || fallbackMessage;
339
+ const sanitized = candidate
340
+ .replace(/\bbearer\s+[a-z0-9._~+/=-]+\b/gi, "bearer [REDACTED]")
341
+ .replace(/\b(token|secret|password|api[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token)\b\s*[:=]\s*["']?[^"'\s,;]+["']?/gi, "$1=[REDACTED]")
342
+ .replace(/\b[a-z0-9_-]+\.[a-z0-9_-]+\.[a-z0-9_-]+\b/gi, "[REDACTED_JWT]")
343
+ .replace(/\bhttps?:\/\/[^\s"'`]+/gi, () => "<redacted-url>")
344
+ .replace(/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/gi, "<redacted-email>");
345
+ if (sanitized.length <= MAX_API_ERROR_MESSAGE_LENGTH) {
346
+ return sanitized;
347
+ }
348
+ return `${sanitized.slice(0, MAX_API_ERROR_MESSAGE_LENGTH - 3)}...`;
349
+ }
350
+
351
+ function anonymizeRequestIdForDebug(requestId) {
352
+ const normalized = String(requestId || "").trim();
353
+ if (!normalized) {
354
+ return "";
355
+ }
356
+ return crypto.createHash("sha256").update(normalized).digest("hex").slice(0, 12);
357
+ }
358
+
359
+ function appendDebugContext(safeMessage, { code, status, requestId } = {}) {
360
+ if (!shouldExposeApiErrorDetails()) {
361
+ return safeMessage;
362
+ }
363
+ const parts = [];
364
+ const normalizedCode = String(code || "").trim();
365
+ const normalizedStatus = Number.isFinite(Number(status)) ? Number(status) : null;
366
+ const requestIdHash = anonymizeRequestIdForDebug(requestId);
367
+ if (normalizedCode) parts.push(`code=${normalizedCode}`);
368
+ if (normalizedStatus) parts.push(`status=${normalizedStatus}`);
369
+ if (requestIdHash) parts.push(`request_id_hash=${requestIdHash}`);
370
+ if (parts.length === 0) return safeMessage;
371
+ return `${safeMessage} (${parts.join(", ")})`;
372
+ }
373
+
374
+ function recordSuccessForCircuit(scope) {
375
+ const circuitState = getCircuitState(scope);
376
+ circuitState.consecutiveFailures = 0;
377
+ circuitState.openedAtMs = 0;
378
+ persistCircuitState();
379
+ }
380
+
381
+ function shouldRetryStatus(statusCode) {
382
+ return RETRYABLE_STATUS_CODES.has(Number(statusCode || 0));
383
+ }
384
+
385
+ function shouldRecordFailureForStatus(statusCode) {
386
+ return CIRCUIT_TRACK_STATUS_CODES.has(Number(statusCode || 0));
387
+ }
388
+
389
+ export function __resetRequestCircuitForTests(scope) {
390
+ if (scope) {
391
+ const circuitState = getCircuitState(scope);
392
+ circuitState.consecutiveFailures = 0;
393
+ circuitState.openedAtMs = 0;
394
+ persistCircuitState();
395
+ return;
396
+ }
397
+ circuitStateByScope.clear();
398
+ circuitStateLoaded = true; // block disk reload after manual reset
399
+ try {
400
+ fs.rmSync(CIRCUIT_STATE_FILE, { force: true });
401
+ } catch {
402
+ /* noop */
403
+ }
404
+ }
405
+
406
+ /**
407
+ * Execute an HTTP request against the Sentinelayer API and parse a JSON response.
408
+ * Throws `SentinelayerApiError` for transport errors, timeouts, API failures, and invalid JSON.
409
+ *
410
+ * @param {string} url
411
+ * @param {{
412
+ * method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
413
+ * headers?: Record<string, string>,
414
+ * body?: unknown,
415
+ * idempotencyKey?: string | null,
416
+ * allowNonIdempotent?: boolean,
417
+ * timeoutMs?: number
418
+ * maxRetries?: number,
419
+ * retryDelayMs?: number
420
+ * allowEmptyBody?: boolean
421
+ * }} [options]
422
+ * @returns {Promise<any>}
423
+ */
424
+ export async function requestJson(
425
+ url,
426
+ {
427
+ method = "GET",
428
+ headers = {},
429
+ body,
430
+ idempotencyKey = null,
431
+ allowNonIdempotent = false,
432
+ timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
433
+ maxRetries = DEFAULT_MAX_RETRIES,
434
+ retryDelayMs = DEFAULT_RETRY_DELAY_MS,
435
+ allowEmptyBody = false,
436
+ } = {}
437
+ ) {
438
+ const normalizedMethod = String(method || "GET").trim().toUpperCase();
439
+ const explicitIdempotencyKey = String(idempotencyKey || "").trim() || null;
440
+ const existingIdempotencyKey = explicitIdempotencyKey || resolveIdempotencyKey(headers);
441
+ const isMutationMethod = isMutationVerb(normalizedMethod);
442
+ const resolvedIdempotencyKey = existingIdempotencyKey;
443
+ const requestHeaders = applyIdempotencyKey(headers, resolvedIdempotencyKey);
444
+ const outgoingHeaders = { ...requestHeaders };
445
+ if (body !== undefined) {
446
+ outgoingHeaders["Content-Type"] = "application/json";
447
+ }
448
+ const isIdempotentMutation = Boolean(resolvedIdempotencyKey);
449
+ const allowUnsafeMutation = Boolean(allowNonIdempotent) && isTestNonIdempotentAllowed();
450
+ if (isMutationMethod && !isIdempotentMutation && !allowUnsafeMutation) {
451
+ throw new SentinelayerApiError("Idempotency-Key is required for mutation requests.", {
452
+ status: 400,
453
+ code: "IDEMPOTENCY_KEY_REQUIRED",
454
+ });
455
+ }
456
+ if (isMutationMethod && isIdempotentMutation) {
457
+ validateIdempotencyKey(resolvedIdempotencyKey);
458
+ }
459
+ const retryableMethod =
460
+ normalizedMethod === "GET" ||
461
+ normalizedMethod === "HEAD" ||
462
+ normalizedMethod === "OPTIONS" ||
463
+ (isIdempotentMutation &&
464
+ (normalizedMethod === "POST" ||
465
+ normalizedMethod === "PUT" ||
466
+ normalizedMethod === "PATCH" ||
467
+ normalizedMethod === "DELETE"));
468
+ const circuitScope = resolveCircuitScope(url);
469
+ if (isCircuitOpen(circuitScope)) {
470
+ throw new SentinelayerApiError("Request circuit breaker is open after consecutive API failures.", {
471
+ status: 503,
472
+ code: "CIRCUIT_OPEN",
473
+ });
474
+ }
475
+
476
+ const normalizedTimeoutMs = normalizePositiveNumber(timeoutMs, DEFAULT_REQUEST_TIMEOUT_MS);
477
+ const normalizedMaxRetries = normalizeNonNegativeInteger(maxRetries, DEFAULT_MAX_RETRIES);
478
+ const normalizedRetryDelayMs = normalizePositiveNumber(retryDelayMs, DEFAULT_RETRY_DELAY_MS);
479
+
480
+ let lastRetryableError = null;
481
+ for (let attempt = 0; attempt <= normalizedMaxRetries; attempt += 1) {
482
+ const controller = new AbortController();
483
+ let timeoutTriggered = false;
484
+ let timeoutHandle;
485
+ timeoutHandle = setTimeout(() => {
486
+ timeoutTriggered = true;
487
+ controller.abort();
488
+ }, normalizedTimeoutMs);
489
+
490
+ try {
491
+ const response = await fetch(String(url), {
492
+ method: normalizedMethod,
493
+ headers: outgoingHeaders,
494
+ body: body === undefined ? undefined : JSON.stringify(body),
495
+ redirect: "error",
496
+ signal: controller.signal,
497
+ });
498
+
499
+ const rawBody = await response.text();
500
+ const trimmedBody = rawBody.trim();
501
+ const contentType = response.headers.get("content-type") || "";
502
+ const isJson = /application\/json/i.test(contentType);
503
+ let json = {};
504
+ if (!trimmedBody) {
505
+ const statusCode = Number(response.status || 0);
506
+ const allowEmpty = Boolean(allowEmptyBody) || statusCode === 204 || statusCode === 205;
507
+ if (response.ok && !allowEmpty) {
508
+ const requestId = resolveRequestId(response.headers);
509
+ throw new SentinelayerApiError("Empty response body returned by API.", {
510
+ status: response.status,
511
+ code: "EMPTY_BODY",
512
+ requestId,
513
+ });
514
+ }
515
+ } else {
516
+ if (response.ok && !isJson) {
517
+ const requestId = resolveRequestId(response.headers);
518
+ throw new SentinelayerApiError("Invalid content-type returned by API.", {
519
+ status: response.status,
520
+ code: "INVALID_CONTENT_TYPE",
521
+ requestId,
522
+ });
523
+ }
524
+ if (isJson) {
525
+ try {
526
+ json = JSON.parse(rawBody);
527
+ } catch {
528
+ const requestId = resolveRequestId(response.headers);
529
+ if (response.ok) {
530
+ throw new SentinelayerApiError("Invalid JSON returned by API.", {
531
+ status: response.status,
532
+ code: "INVALID_JSON",
533
+ requestId,
534
+ });
535
+ }
536
+ }
537
+ }
538
+ }
539
+
540
+ if (response.ok) {
541
+ recordSuccessForCircuit(circuitScope);
542
+ return json;
543
+ }
544
+
545
+ const apiError = normalizeApiError(json && typeof json === "object" ? json.error : {});
546
+ const requestId = apiError.requestId || resolveRequestId(response.headers);
547
+ const statusCode = Number(response.status || 500);
548
+ const retryable = retryableMethod && shouldRetryStatus(statusCode);
549
+ const shouldRecordCircuitFailure = shouldRecordFailureForStatus(statusCode);
550
+ const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"));
551
+ const error = new SentinelayerApiError(apiError.message, {
552
+ status: statusCode,
553
+ code: apiError.code,
554
+ requestId,
555
+ });
556
+ error.retryAfterMs = retryAfterMs;
557
+
558
+ if (!retryable || attempt >= normalizedMaxRetries) {
559
+ if (shouldRecordCircuitFailure) {
560
+ recordFailureForCircuit(circuitScope);
561
+ }
562
+ throw error;
563
+ }
564
+
565
+ lastRetryableError = error;
566
+ const delayMs = computeBackoffMs({
567
+ attempt: attempt + 1,
568
+ retryDelayMs: normalizedRetryDelayMs,
569
+ retryAfterHeader: response.headers.get("retry-after"),
570
+ });
571
+ await sleep(delayMs);
572
+ continue;
573
+ } catch (error) {
574
+ if (error instanceof SentinelayerApiError) {
575
+ throw error;
576
+ }
577
+
578
+ const isAbortError = Boolean(error && typeof error === "object" && error.name === "AbortError");
579
+ const abortMessage = error instanceof Error ? error.message : String(error || "");
580
+ const abortReason =
581
+ isAbortError && !timeoutTriggered && /cancel/i.test(abortMessage) ? "CANCELLED" : "TIMEOUT";
582
+ const abortCode = isAbortError ? abortReason : "NETWORK_ERROR";
583
+ const abortStatus = isAbortError ? (abortReason === "CANCELLED" ? 499 : 408) : 503;
584
+ const normalizedError = new SentinelayerApiError(
585
+ isAbortError
586
+ ? (abortReason === "CANCELLED" ? "Request cancelled." : "Request timed out.")
587
+ : (error instanceof Error ? error.message : String(error || "Request failed")),
588
+ {
589
+ status: abortStatus,
590
+ code: abortCode,
591
+ }
592
+ );
593
+
594
+ if (!retryableMethod || attempt >= normalizedMaxRetries) {
595
+ recordFailureForCircuit(circuitScope);
596
+ throw normalizedError;
597
+ }
598
+
599
+ lastRetryableError = normalizedError;
600
+ const delayMs = computeBackoffMs({
601
+ attempt: attempt + 1,
602
+ retryDelayMs: normalizedRetryDelayMs,
603
+ retryAfterHeader: null,
604
+ });
605
+ await sleep(delayMs);
606
+ continue;
607
+ } finally {
608
+ if (timeoutHandle) {
609
+ clearTimeout(timeoutHandle);
610
+ }
611
+ await sleep(0);
612
+ }
613
+ }
614
+
615
+ if (lastRetryableError instanceof SentinelayerApiError) {
616
+ throw lastRetryableError;
617
+ }
618
+ throw new SentinelayerApiError("Request failed without a terminal response.", {
619
+ status: 503,
620
+ code: "NETWORK_ERROR",
621
+ });
622
+ }
623
+
624
+ /**
625
+ * Execute an HTTP mutation request and auto-derive an idempotency key when missing.
626
+ *
627
+ * @param {string} url
628
+ * @param {{
629
+ * method?: "POST" | "PUT" | "PATCH" | "DELETE",
630
+ * headers?: Record<string, string>,
631
+ * body?: unknown,
632
+ * idempotencyKey?: string | null,
633
+ * operationName: string,
634
+ * timeoutMs?: number
635
+ * maxRetries?: number,
636
+ * retryDelayMs?: number
637
+ * allowEmptyBody?: boolean
638
+ * }} options
639
+ * @returns {Promise<any>}
640
+ */
641
+ export async function requestJsonMutation(
642
+ url,
643
+ {
644
+ method = "POST",
645
+ headers = {},
646
+ body,
647
+ idempotencyKey = null,
648
+ operationName,
649
+ timeoutMs,
650
+ maxRetries,
651
+ retryDelayMs,
652
+ allowEmptyBody = false,
653
+ } = {}
654
+ ) {
655
+ const normalizedMethod = String(method || "POST").trim().toUpperCase();
656
+ if (!isMutationVerb(normalizedMethod)) {
657
+ throw new SentinelayerApiError("requestJsonMutation requires a mutation HTTP method.", {
658
+ status: 400,
659
+ code: "INVALID_MUTATION_METHOD",
660
+ });
661
+ }
662
+ const resolvedOperation = String(operationName || "").trim();
663
+ if (!resolvedOperation) {
664
+ throw new SentinelayerApiError("requestJsonMutation requires an operationName.", {
665
+ status: 400,
666
+ code: "OPERATION_NAME_REQUIRED",
667
+ });
668
+ }
669
+ const resolvedIdempotencyKey =
670
+ String(idempotencyKey || "").trim() || createIdempotencyKeyForOperation(resolvedOperation);
671
+ return requestJson(url, {
672
+ method: normalizedMethod,
673
+ headers,
674
+ body,
675
+ idempotencyKey: resolvedIdempotencyKey,
676
+ timeoutMs,
677
+ maxRetries,
678
+ retryDelayMs,
679
+ allowEmptyBody,
680
+ });
681
+ }