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
@@ -1,1106 +1,1106 @@
1
- import crypto from "node:crypto";
2
- import process from "node:process";
3
- import { setTimeout as sleep } from "node:timers/promises";
4
-
5
- import open from "open";
6
-
7
- import { loadConfig } from "../config/service.js";
8
- import { SentinelayerApiError, requestJson, requestJsonMutation } from "./http.js";
9
- import {
10
- clearStoredSession,
11
- readStoredSession,
12
- readStoredSessionMetadata,
13
- writeStoredSession,
14
- } from "./session-store.js";
15
- import { authLoginHint } from "../ui/command-hints.js";
16
-
17
- const DEFAULT_API_URL = "https://api.sentinelayer.com";
18
- /** Default maximum wall-clock wait for browser-based CLI auth approval (ms). */
19
- export const DEFAULT_AUTH_TIMEOUT_MS = 10 * 60 * 1000;
20
- /** Default lifetime for issued API tokens used by CLI sessions (days). */
21
- export const DEFAULT_API_TOKEN_TTL_DAYS = 365;
22
- /** Default threshold at which stored tokens are rotated before expiry (days). */
23
- export const DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS = 7;
24
- const DEFAULT_IDE_NAME = "sl-cli";
25
- const MAX_AUTH_POLL_REQUESTS = 600;
26
- const MIN_TRANSIENT_POLL_DELAY_MS = 2_000;
27
- const TRANSIENT_DELAY_THRESHOLD = 3;
28
-
29
- function normalizeApiUrl(rawValue) {
30
- const candidate = String(rawValue || "").trim() || DEFAULT_API_URL;
31
- let parsed;
32
- try {
33
- parsed = new URL(candidate);
34
- } catch {
35
- throw new Error(`Invalid API URL '${candidate}'.`);
36
- }
37
- const hostname = String(parsed.hostname || "").toLowerCase();
38
- const isLocalhost = hostname === "localhost" || hostname === "127.0.0.1";
39
- if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLocalhost)) {
40
- throw new Error(`API URL must use https (received '${candidate}').`);
41
- }
42
- parsed.pathname = "/";
43
- parsed.search = "";
44
- parsed.hash = "";
45
- return parsed.toString().replace(/\/$/, "");
46
- }
47
-
48
- function normalizePositiveNumber(rawValue, field, fallbackValue) {
49
- if (rawValue === undefined || rawValue === null || String(rawValue).trim() === "") {
50
- return fallbackValue;
51
- }
52
- const normalized = Number(rawValue);
53
- if (!Number.isFinite(normalized) || normalized <= 0) {
54
- throw new Error(`${field} must be a positive number.`);
55
- }
56
- return normalized;
57
- }
58
-
59
- function toAuthHeader(token) {
60
- return {
61
- Authorization: `Bearer ${String(token || "").trim()}`,
62
- };
63
- }
64
-
65
- function normalizeUser(user = {}) {
66
- return {
67
- id: String(user.id || "").trim(),
68
- githubUsername: String(user.githubUsername || user.github_username || "").trim(),
69
- email: String(user.email || "").trim(),
70
- avatarUrl: String(user.avatarUrl || user.avatar_url || "").trim(),
71
- isAdmin: Boolean(user.isAdmin || user.is_admin),
72
- };
73
- }
74
-
75
- function buildApiPath(apiUrl, pathSuffix) {
76
- return `${normalizeApiUrl(apiUrl)}${String(pathSuffix || "")}`;
77
- }
78
-
79
- function generateChallenge() {
80
- return crypto.randomBytes(48).toString("base64url");
81
- }
82
-
83
- function createFlowRequestId() {
84
- try {
85
- return crypto.randomUUID();
86
- } catch {
87
- return `flow-${Date.now().toString(36)}-${crypto.randomBytes(8).toString("hex")}`;
88
- }
89
- }
90
-
91
- function withFlowRequestHeaders(headers, flowRequestId) {
92
- const merged = {
93
- ...(headers || {}),
94
- "X-Request-Id": createFlowRequestId(),
95
- };
96
- if (flowRequestId) {
97
- merged["X-Flow-Request-Id"] = flowRequestId;
98
- }
99
- return merged;
100
- }
101
-
102
- async function requestAuthJson(flowRequestId, ...args) {
103
- try {
104
- return await requestJson(...args);
105
- } catch (error) {
106
- if (error instanceof SentinelayerApiError && !error.requestId && flowRequestId) {
107
- error.requestId = flowRequestId;
108
- }
109
- throw error;
110
- }
111
- }
112
-
113
- async function requestAuthJsonMutation(flowRequestId, ...args) {
114
- try {
115
- return await requestJsonMutation(...args);
116
- } catch (error) {
117
- if (error instanceof SentinelayerApiError && !error.requestId && flowRequestId) {
118
- error.requestId = flowRequestId;
119
- }
120
- throw error;
121
- }
122
- }
123
-
124
- function defaultTokenLabel() {
125
- const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..+/, "").replace("T", "-");
126
- return `sl-cli-session-${stamp}`;
127
- }
128
-
129
- function createIdempotencyKey(prefix) {
130
- const normalizedPrefix = String(prefix || "sl-cli").trim() || "sl-cli";
131
- let suffix;
132
- try {
133
- suffix = crypto.randomUUID();
134
- } catch {
135
- suffix = `${Date.now().toString(36)}-${crypto.randomBytes(8).toString("hex")}`;
136
- }
137
- return `${normalizedPrefix}-${suffix}`;
138
- }
139
-
140
- function computeDeterministicJitterFactor({ sessionId, attempt }) {
141
- const seed = `${String(sessionId || "").trim()}|${Number(attempt) || 0}`;
142
- const digest = crypto.createHash("sha256").update(seed).digest();
143
- const raw = digest.readUInt32BE(0);
144
- const ratio = raw / 0xffffffff;
145
- return 0.85 + ratio * 0.3;
146
- }
147
-
148
- function isNearExpiry(tokenExpiresAt, thresholdDays) {
149
- const normalized = String(tokenExpiresAt || "").trim();
150
- if (!normalized) {
151
- return false;
152
- }
153
- const expiryEpoch = Date.parse(normalized);
154
- if (!Number.isFinite(expiryEpoch)) {
155
- return false;
156
- }
157
- const thresholdMs = Number(thresholdDays || DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS) * 24 * 60 * 60 * 1000;
158
- return expiryEpoch - Date.now() <= thresholdMs;
159
- }
160
-
161
- /**
162
- * Resolve API URL precedence for auth operations: explicit -> env -> config -> default.
163
- *
164
- * @param {{
165
- * cwd?: string,
166
- * env?: NodeJS.ProcessEnv,
167
- * explicitApiUrl?: string,
168
- * homeDir?: string
169
- * }} [options]
170
- * @returns {Promise<string>}
171
- */
172
- export async function resolveApiUrl({
173
- cwd = process.cwd(),
174
- env = process.env,
175
- explicitApiUrl = "",
176
- homeDir,
177
- } = {}) {
178
- const overrideUrl = String(explicitApiUrl || "").trim();
179
- if (overrideUrl) {
180
- return normalizeApiUrl(overrideUrl);
181
- }
182
-
183
- const envUrl = String(env.SENTINELAYER_API_URL || "").trim();
184
- if (envUrl) {
185
- return normalizeApiUrl(envUrl);
186
- }
187
-
188
- const config = await loadConfig({ cwd, env, homeDir });
189
- const configuredApiUrl = String(config.resolved.apiUrl || "").trim();
190
- if (configuredApiUrl) {
191
- return normalizeApiUrl(configuredApiUrl);
192
- }
193
-
194
- return normalizeApiUrl(DEFAULT_API_URL);
195
- }
196
-
197
- async function startCliAuthSession({ apiUrl, challenge, ide, cliVersion, flowRequestId }) {
198
- return requestAuthJsonMutation(
199
- flowRequestId,
200
- buildApiPath(apiUrl, "/api/v1/auth/cli/sessions/start"),
201
- {
202
- method: "POST",
203
- operationName: "auth-start",
204
- headers: withFlowRequestHeaders(null, flowRequestId),
205
- body: {
206
- challenge,
207
- ide: String(ide || DEFAULT_IDE_NAME),
208
- cli_version: String(cliVersion || "").trim() || null,
209
- },
210
- }
211
- );
212
- }
213
-
214
- async function pollCliAuthSession({
215
- apiUrl,
216
- sessionId,
217
- challenge,
218
- timeoutMs,
219
- pollIntervalSeconds,
220
- flowRequestId,
221
- }) {
222
- const timeout = normalizePositiveNumber(timeoutMs, "timeoutMs", DEFAULT_AUTH_TIMEOUT_MS);
223
- const pollIntervalMs = Math.max(250, Math.round(Number(pollIntervalSeconds || 2) * 1000));
224
- const maxPollIntervalMs = Math.max(pollIntervalMs, Math.min(5_000, Math.floor(timeout / 4)));
225
- const pollRequestTimeoutMs = Math.min(5_000, Math.max(1_000, pollIntervalMs));
226
- const pollRequestMaxRetries = 1;
227
- const pollRequestRetryDelayMs = 250;
228
- let pollAttempt = 0;
229
- const transientErrorBudget = Math.max(8, Math.ceil(timeout / maxPollIntervalMs) * 3);
230
- const maxSleepBudgetMs = Math.max(2_000, Math.floor(timeout * 0.8));
231
- const maxPollAttempts = Math.min(
232
- MAX_AUTH_POLL_REQUESTS,
233
- Math.max(1, Math.ceil(timeout / Math.max(250, pollIntervalMs)))
234
- );
235
- let rateLimitErrorCount = 0;
236
- let serverErrorCount = 0;
237
- let networkErrorCount = 0;
238
- let transientBudgetUsed = 0;
239
- let cumulativeSleepMs = 0;
240
- let pollIterations = 0;
241
- const deadline = Date.now() + timeout;
242
- const classifyPollError = (error) => {
243
- if (!(error instanceof SentinelayerApiError)) {
244
- return null;
245
- }
246
- if (error.status === 429) {
247
- return "rate_limit";
248
- }
249
- if (error.status >= 500) {
250
- return "server";
251
- }
252
- if (error.code === "NETWORK_ERROR" || error.code === "TIMEOUT") {
253
- return "network";
254
- }
255
- return null;
256
- };
257
- const computePollDelayMs = (retryAfterMs = null) => {
258
- const transientErrorCount = rateLimitErrorCount + serverErrorCount + networkErrorCount;
259
- const minDelayMs =
260
- transientErrorCount >= TRANSIENT_DELAY_THRESHOLD ? MIN_TRANSIENT_POLL_DELAY_MS : 250;
261
- if (Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
262
- return Math.max(minDelayMs, Math.min(maxPollIntervalMs, Math.round(retryAfterMs)));
263
- }
264
- const exponent = Math.min(6, pollAttempt);
265
- const backoffMs = Math.min(maxPollIntervalMs, Math.round(pollIntervalMs * Math.pow(1.5, exponent)));
266
- const jitterFactor = computeDeterministicJitterFactor({ sessionId, attempt: pollAttempt });
267
- return Math.max(minDelayMs, Math.round(backoffMs * jitterFactor));
268
- };
269
-
270
- while (Date.now() < deadline) {
271
- const remainingBeforeRequestMs = deadline - Date.now();
272
- if (remainingBeforeRequestMs <= 250) {
273
- break;
274
- }
275
- pollIterations += 1;
276
- if (pollIterations > maxPollAttempts) {
277
- throw new SentinelayerApiError("CLI authentication polling exceeded attempt budget.", {
278
- status: 408,
279
- code: "CLI_AUTH_POLL_EXHAUSTED",
280
- requestId: flowRequestId || null,
281
- });
282
- }
283
- let payload;
284
- try {
285
- payload = await requestAuthJsonMutation(
286
- flowRequestId,
287
- buildApiPath(apiUrl, "/api/v1/auth/cli/sessions/poll"),
288
- {
289
- method: "POST",
290
- operationName: "auth-poll",
291
- headers: withFlowRequestHeaders(null, flowRequestId),
292
- body: {
293
- session_id: sessionId,
294
- challenge,
295
- },
296
- timeoutMs: Math.max(250, Math.min(pollRequestTimeoutMs, remainingBeforeRequestMs)),
297
- maxRetries: pollRequestMaxRetries,
298
- retryDelayMs: pollRequestRetryDelayMs,
299
- }
300
- );
301
- } catch (error) {
302
- if (error instanceof SentinelayerApiError && !error.requestId && flowRequestId) {
303
- error.requestId = flowRequestId;
304
- }
305
- const classification = classifyPollError(error);
306
- if (classification) {
307
- const transientWeight = classification === "rate_limit" ? 3 : classification === "server" ? 2 : 1;
308
- if (transientBudgetUsed + transientWeight > transientErrorBudget) {
309
- throw new SentinelayerApiError("CLI authentication polling exhausted transient error budget.", {
310
- status: 503,
311
- code: "CLI_AUTH_TRANSIENT_BUDGET_EXHAUSTED",
312
- requestId: error.requestId || flowRequestId || null,
313
- });
314
- }
315
- transientBudgetUsed += transientWeight;
316
- if (classification === "rate_limit") {
317
- rateLimitErrorCount += 1;
318
- } else if (classification === "server") {
319
- serverErrorCount += 1;
320
- } else {
321
- networkErrorCount += 1;
322
- }
323
- const retryAfterMs = Number.isFinite(error.retryAfterMs) ? error.retryAfterMs : null;
324
- const delayMs = computePollDelayMs(retryAfterMs);
325
- const remainingBeforeSleepMs = deadline - Date.now();
326
- if (remainingBeforeSleepMs <= 250) {
327
- break;
328
- }
329
- const boundedDelayMs = Math.max(250, Math.min(delayMs, remainingBeforeSleepMs));
330
- if (cumulativeSleepMs + boundedDelayMs > maxSleepBudgetMs) {
331
- throw new SentinelayerApiError("CLI authentication polling exceeded retry sleep budget.", {
332
- status: 503,
333
- code: "CLI_AUTH_SLEEP_BUDGET_EXHAUSTED",
334
- requestId: error.requestId || flowRequestId || null,
335
- });
336
- }
337
- cumulativeSleepMs += boundedDelayMs;
338
- pollAttempt += 1;
339
- await sleep(boundedDelayMs);
340
- continue;
341
- }
342
- throw error;
343
- }
344
-
345
- const status = String(payload.status || "pending").trim().toLowerCase();
346
- if (status === "approved" && payload.auth_token) {
347
- return payload;
348
- }
349
- if (status === "rejected" || status === "denied" || status === "cancelled") {
350
- throw new SentinelayerApiError("CLI authentication was not approved.", {
351
- status: 401,
352
- code: "CLI_AUTH_REJECTED",
353
- requestId: flowRequestId || null,
354
- });
355
- }
356
- if (status === "expired") {
357
- throw new SentinelayerApiError("CLI authentication session expired.", {
358
- status: 401,
359
- code: "CLI_AUTH_EXPIRED",
360
- requestId: flowRequestId || null,
361
- });
362
- }
363
-
364
- const delayMs = computePollDelayMs();
365
- const remainingBeforeSleepMs = deadline - Date.now();
366
- if (remainingBeforeSleepMs <= 250) {
367
- break;
368
- }
369
- const boundedDelayMs = Math.max(250, Math.min(delayMs, remainingBeforeSleepMs));
370
- pollAttempt += 1;
371
- await sleep(boundedDelayMs);
372
- }
373
-
374
- throw new SentinelayerApiError("CLI authentication timed out. Restart and try again.", {
375
- status: 408,
376
- code: "CLI_AUTH_TIMEOUT",
377
- requestId: flowRequestId || null,
378
- });
379
- }
380
-
381
- async function fetchCurrentUser({ apiUrl, token, flowRequestId }) {
382
- return requestAuthJson(
383
- flowRequestId,
384
- buildApiPath(apiUrl, "/api/v1/auth/me"),
385
- {
386
- method: "GET",
387
- headers: withFlowRequestHeaders(toAuthHeader(token), flowRequestId),
388
- }
389
- );
390
- }
391
-
392
- async function issueApiToken({
393
- apiUrl,
394
- authToken,
395
- tokenLabel,
396
- tokenTtlDays,
397
- flowRequestId,
398
- }) {
399
- const expiresInDays = Math.round(
400
- normalizePositiveNumber(tokenTtlDays, "apiTokenTtlDays", DEFAULT_API_TOKEN_TTL_DAYS)
401
- );
402
- return requestAuthJsonMutation(
403
- flowRequestId,
404
- buildApiPath(apiUrl, "/api/v1/auth/api-tokens"),
405
- {
406
- method: "POST",
407
- operationName: "issue-token",
408
- headers: withFlowRequestHeaders(
409
- {
410
- ...toAuthHeader(authToken),
411
- },
412
- flowRequestId
413
- ),
414
- body: {
415
- label: String(tokenLabel || "").trim() || defaultTokenLabel(),
416
- scope: "cli",
417
- llm_credential_mode: "managed",
418
- expires_in_days: expiresInDays,
419
- },
420
- }
421
- );
422
- }
423
-
424
- async function revokeApiToken({ apiUrl, authToken, tokenId }) {
425
- const normalizedTokenId = String(tokenId || "").trim();
426
- if (!normalizedTokenId) {
427
- return false;
428
- }
429
- await requestJsonMutation(buildApiPath(apiUrl, `/api/v1/auth/api-tokens/${encodeURIComponent(normalizedTokenId)}`), {
430
- method: "DELETE",
431
- operationName: "revoke-token",
432
- headers: {
433
- ...toAuthHeader(authToken),
434
- },
435
- });
436
- return true;
437
- }
438
-
439
- async function rotateStoredApiTokenIfNeeded({
440
- session,
441
- thresholdDays,
442
- tokenLabel,
443
- tokenTtlDays,
444
- homeDir,
445
- }) {
446
- if (!session || !session.token || !session.tokenExpiresAt) {
447
- return { session, rotated: false };
448
- }
449
- if (!isNearExpiry(session.tokenExpiresAt, thresholdDays)) {
450
- return { session, rotated: false };
451
- }
452
-
453
- const issued = await issueApiToken({
454
- apiUrl: session.apiUrl,
455
- authToken: session.token,
456
- tokenLabel,
457
- tokenTtlDays,
458
- });
459
-
460
- const nextSession = await writeStoredSession(
461
- {
462
- apiUrl: session.apiUrl,
463
- token: String(issued.token || ""),
464
- tokenId: issued.id || null,
465
- tokenPrefix: issued.token_prefix || null,
466
- tokenExpiresAt: issued.expires_at || null,
467
- user: session.user,
468
- },
469
- { homeDir }
470
- );
471
-
472
- let revokeError = null;
473
- if (session.tokenId) {
474
- try {
475
- await revokeApiToken({
476
- apiUrl: session.apiUrl,
477
- authToken: nextSession.token,
478
- tokenId: session.tokenId,
479
- });
480
- } catch (error) {
481
- revokeError = error;
482
- }
483
- }
484
-
485
- return {
486
- session: nextSession,
487
- rotated: true,
488
- revokeError,
489
- };
490
- }
491
-
492
- /**
493
- * Perform browser-based CLI login flow and persist an API token session locally.
494
- *
495
- * @param {{
496
- * cwd?: string,
497
- * env?: NodeJS.ProcessEnv,
498
- * explicitApiUrl?: string,
499
- * skipBrowserOpen?: boolean,
500
- * timeoutMs?: number,
501
- * tokenLabel?: string,
502
- * tokenTtlDays?: number,
503
- * ide?: string,
504
- * cliVersion?: string,
505
- * homeDir?: string
506
- * }} [options]
507
- * @returns {Promise<{
508
- * apiUrl: string,
509
- * authorizeUrl: string,
510
- * browserOpened: boolean,
511
- * user: {
512
- * id: string,
513
- * githubUsername: string,
514
- * email: string,
515
- * avatarUrl: string,
516
- * isAdmin: boolean
517
- * },
518
- * tokenId: string | null,
519
- * tokenPrefix: string | null,
520
- * tokenExpiresAt: string | null,
521
- * storage: string,
522
- * filePath: string
523
- * }>}
524
- */
525
- export async function loginAndPersistSession({
526
- cwd = process.cwd(),
527
- env = process.env,
528
- explicitApiUrl = "",
529
- skipBrowserOpen = false,
530
- timeoutMs = DEFAULT_AUTH_TIMEOUT_MS,
531
- tokenLabel = "",
532
- tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
533
- ide = DEFAULT_IDE_NAME,
534
- cliVersion = "",
535
- homeDir,
536
- } = {}) {
537
- const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
538
- const challenge = generateChallenge();
539
- const flowRequestId = createFlowRequestId();
540
- const session = await startCliAuthSession({
541
- apiUrl,
542
- challenge,
543
- ide,
544
- cliVersion,
545
- flowRequestId,
546
- });
547
-
548
- const authorizeUrl = String(session.authorize_url || "").trim();
549
- let browserOpened = false;
550
- if (!skipBrowserOpen && authorizeUrl) {
551
- try {
552
- await open(authorizeUrl);
553
- browserOpened = true;
554
- } catch {
555
- browserOpened = false;
556
- }
557
- }
558
-
559
- const approval = await pollCliAuthSession({
560
- apiUrl,
561
- sessionId: String(session.session_id || "").trim(),
562
- challenge,
563
- timeoutMs,
564
- pollIntervalSeconds: Number(session.poll_interval_seconds || 2),
565
- flowRequestId,
566
- });
567
-
568
- const approvalToken = String(approval.auth_token || "").trim();
569
- if (!approvalToken) {
570
- throw new SentinelayerApiError("Authentication completed but no auth token was returned.", {
571
- status: 503,
572
- code: "CLI_AUTH_MISSING_TOKEN",
573
- requestId: flowRequestId || null,
574
- });
575
- }
576
-
577
- const user = normalizeUser(
578
- approval.user || (await fetchCurrentUser({ apiUrl, token: approvalToken, flowRequestId }))
579
- );
580
- const issuedApiToken = await issueApiToken({
581
- apiUrl,
582
- authToken: approvalToken,
583
- tokenLabel,
584
- tokenTtlDays,
585
- flowRequestId,
586
- });
587
-
588
- // Extract AIdenID metadata from approval (no secret stored locally)
589
- const rawAidenId = approval.aidenidCredentials || approval.aidenid_credentials || null;
590
- const aidenid =
591
- rawAidenId && rawAidenId.provisioned
592
- ? {
593
- orgId: String(rawAidenId.orgId || rawAidenId.org_id || "").trim() || null,
594
- projectId: String(rawAidenId.projectId || rawAidenId.project_id || "").trim() || null,
595
- apiKeyPrefix: String(rawAidenId.apiKeyPrefix || rawAidenId.api_key_prefix || "").trim() || null,
596
- provisionedAt: new Date().toISOString(),
597
- }
598
- : null;
599
-
600
- const stored = await writeStoredSession(
601
- {
602
- apiUrl,
603
- token: String(issuedApiToken.token || ""),
604
- tokenId: issuedApiToken.id || null,
605
- tokenPrefix: issuedApiToken.token_prefix || null,
606
- tokenExpiresAt: issuedApiToken.expires_at || null,
607
- user,
608
- aidenid,
609
- },
610
- { homeDir }
611
- );
612
-
613
- return {
614
- apiUrl,
615
- authorizeUrl,
616
- browserOpened,
617
- user,
618
- tokenId: stored.tokenId,
619
- tokenPrefix: stored.tokenPrefix,
620
- tokenExpiresAt: stored.tokenExpiresAt,
621
- storage: stored.storage,
622
- filePath: stored.filePath,
623
- aidenid: stored.aidenid || null,
624
- flowRequestId,
625
- };
626
- }
627
-
628
- /**
629
- * Resolve active auth credentials used by CLI commands, optionally rotating near-expiry session tokens.
630
- *
631
- * @param {{
632
- * cwd?: string,
633
- * env?: NodeJS.ProcessEnv,
634
- * explicitApiUrl?: string,
635
- * autoRotate?: boolean,
636
- * rotateThresholdDays?: number,
637
- * tokenLabel?: string,
638
- * tokenTtlDays?: number,
639
- * homeDir?: string
640
- * }} [options]
641
- * @returns {Promise<null | {
642
- * apiUrl: string,
643
- * token: string,
644
- * source: "env" | "config" | "session",
645
- * user: {
646
- * id: string,
647
- * githubUsername: string,
648
- * email: string,
649
- * avatarUrl: string,
650
- * isAdmin: boolean
651
- * } | null,
652
- * storage: string,
653
- * tokenId: string | null,
654
- * tokenPrefix: string | null,
655
- * tokenExpiresAt: string | null,
656
- * rotated: boolean,
657
- * filePath: string | null
658
- * }>}
659
- */
660
- export async function resolveActiveAuthSession({
661
- cwd = process.cwd(),
662
- env = process.env,
663
- explicitApiUrl = "",
664
- autoRotate = true,
665
- rotateThresholdDays = DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS,
666
- tokenLabel = "",
667
- tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
668
- homeDir,
669
- } = {}) {
670
- const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
671
-
672
- const envToken = String(env.SENTINELAYER_TOKEN || "").trim();
673
- if (envToken) {
674
- return {
675
- apiUrl,
676
- token: envToken,
677
- source: "env",
678
- user: null,
679
- aidenid: null,
680
- storage: "env",
681
- tokenId: null,
682
- tokenPrefix: null,
683
- tokenExpiresAt: null,
684
- rotated: false,
685
- filePath: null,
686
- };
687
- }
688
-
689
- const config = await loadConfig({ cwd, env, homeDir });
690
- const configuredToken = String(config.resolved.sentinelayerToken || "").trim();
691
- if (configuredToken) {
692
- return {
693
- apiUrl,
694
- token: configuredToken,
695
- source: "config",
696
- user: null,
697
- aidenid: null,
698
- storage: "config",
699
- tokenId: null,
700
- tokenPrefix: null,
701
- tokenExpiresAt: null,
702
- rotated: false,
703
- filePath: null,
704
- };
705
- }
706
-
707
- const stored = await readStoredSession({ homeDir });
708
- if (!stored) {
709
- return null;
710
- }
711
-
712
- let active = stored;
713
- let rotated = false;
714
- if (autoRotate) {
715
- try {
716
- const rotateResult = await rotateStoredApiTokenIfNeeded({
717
- session: stored,
718
- thresholdDays: rotateThresholdDays,
719
- tokenLabel,
720
- tokenTtlDays,
721
- homeDir,
722
- });
723
- active = rotateResult.session;
724
- rotated = rotateResult.rotated;
725
- if (rotateResult.revokeError) {
726
- console.warn(
727
- "Sentinelayer token rotation succeeded but previous token revocation failed. " +
728
- "Revoke the old token manually in the dashboard if needed."
729
- );
730
- }
731
- } catch {
732
- // Keep existing token if rotation fails.
733
- active = stored;
734
- rotated = false;
735
- }
736
- }
737
-
738
- return {
739
- apiUrl,
740
- token: active.token,
741
- source: "session",
742
- user: normalizeUser(active.user || {}),
743
- aidenid: active.aidenid || null,
744
- storage: active.storage,
745
- tokenId: active.tokenId || null,
746
- tokenPrefix: active.tokenPrefix || null,
747
- tokenExpiresAt: active.tokenExpiresAt || null,
748
- rotated,
749
- filePath: active.filePath,
750
- };
751
- }
752
-
753
- /**
754
- * Return current authentication state, with optional remote `/auth/me` verification.
755
- *
756
- * @param {{
757
- * cwd?: string,
758
- * env?: NodeJS.ProcessEnv,
759
- * explicitApiUrl?: string,
760
- * checkRemote?: boolean,
761
- * autoRotate?: boolean,
762
- * rotateThresholdDays?: number,
763
- * tokenLabel?: string,
764
- * tokenTtlDays?: number,
765
- * homeDir?: string
766
- * }} [options]
767
- * @returns {Promise<{
768
- * authenticated: boolean,
769
- * apiUrl: string,
770
- * source: string | null,
771
- * storage: string | null,
772
- * user: any,
773
- * remoteUser: any,
774
- * remoteError: null | { code: string, message: string, status: number, requestId: string | null },
775
- * rotated: boolean,
776
- * tokenExpiresAt: string | null,
777
- * tokenPrefix: string | null,
778
- * tokenId: string | null,
779
- * filePath: string | null
780
- * }>}
781
- */
782
- export async function getAuthStatus({
783
- cwd = process.cwd(),
784
- env = process.env,
785
- explicitApiUrl = "",
786
- checkRemote = true,
787
- autoRotate = true,
788
- rotateThresholdDays = DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS,
789
- tokenLabel = "",
790
- tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
791
- homeDir,
792
- } = {}) {
793
- const session = await resolveActiveAuthSession({
794
- cwd,
795
- env,
796
- explicitApiUrl,
797
- autoRotate,
798
- rotateThresholdDays,
799
- tokenLabel,
800
- tokenTtlDays,
801
- homeDir,
802
- });
803
-
804
- if (!session) {
805
- return {
806
- authenticated: false,
807
- apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
808
- source: null,
809
- storage: null,
810
- user: null,
811
- aidenid: null,
812
- remoteUser: null,
813
- remoteError: null,
814
- rotated: false,
815
- tokenExpiresAt: null,
816
- tokenPrefix: null,
817
- tokenId: null,
818
- filePath: null,
819
- };
820
- }
821
-
822
- let remoteUser = null;
823
- let remoteError = null;
824
- if (checkRemote) {
825
- try {
826
- remoteUser = normalizeUser(await fetchCurrentUser({ apiUrl: session.apiUrl, token: session.token }));
827
- } catch (error) {
828
- remoteError =
829
- error instanceof SentinelayerApiError
830
- ? {
831
- code: error.code,
832
- message: error.message,
833
- status: error.status,
834
- requestId: error.requestId,
835
- }
836
- : {
837
- code: "UNKNOWN",
838
- message: error instanceof Error ? error.message : String(error || "Unknown error"),
839
- status: 500,
840
- requestId: null,
841
- };
842
- }
843
- }
844
-
845
- return {
846
- authenticated: !remoteError,
847
- apiUrl: session.apiUrl,
848
- source: session.source,
849
- storage: session.storage,
850
- user: session.user,
851
- aidenid: session.aidenid || null,
852
- remoteUser,
853
- remoteError,
854
- rotated: session.rotated,
855
- tokenExpiresAt: session.tokenExpiresAt,
856
- tokenPrefix: session.tokenPrefix,
857
- tokenId: session.tokenId,
858
- filePath: session.filePath,
859
- };
860
- }
861
-
862
- /**
863
- * List persisted local session metadata for CLI operators/HITL dashboards.
864
- *
865
- * @param {{ cwd?: string, env?: NodeJS.ProcessEnv, explicitApiUrl?: string, homeDir?: string }} [options]
866
- * @returns {Promise<{ apiUrl: string, sessions: Array<any> }>}
867
- */
868
- export async function listStoredAuthSessions({
869
- cwd = process.cwd(),
870
- env = process.env,
871
- explicitApiUrl = "",
872
- homeDir,
873
- } = {}) {
874
- const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
875
- const stored = await readStoredSessionMetadata({ homeDir });
876
- if (!stored) {
877
- return {
878
- apiUrl,
879
- sessions: [],
880
- };
881
- }
882
-
883
- return {
884
- apiUrl,
885
- sessions: [
886
- {
887
- source: "session",
888
- storage: stored.storage || null,
889
- tokenId: stored.tokenId || null,
890
- tokenPrefix: stored.tokenPrefix || null,
891
- tokenExpiresAt: stored.tokenExpiresAt || null,
892
- createdAt: stored.createdAt || null,
893
- updatedAt: stored.updatedAt || null,
894
- user: normalizeUser(stored.user || {}),
895
- filePath: stored.filePath || null,
896
- },
897
- ],
898
- };
899
- }
900
-
901
- /**
902
- * Revoke an API token remotely and clear matching local stored session metadata when applicable.
903
- *
904
- * @param {{
905
- * cwd?: string,
906
- * env?: NodeJS.ProcessEnv,
907
- * explicitApiUrl?: string,
908
- * tokenId?: string,
909
- * homeDir?: string
910
- * }} [options]
911
- * @returns {Promise<{
912
- * apiUrl: string,
913
- * source: string,
914
- * tokenId: string,
915
- * revokedRemote: boolean,
916
- * matchedStoredSession: boolean,
917
- * clearedLocal: boolean,
918
- * filePath: string | null
919
- * }>}
920
- */
921
- export async function revokeAuthToken({
922
- cwd = process.cwd(),
923
- env = process.env,
924
- explicitApiUrl = "",
925
- tokenId = "",
926
- homeDir,
927
- } = {}) {
928
- const active = await resolveActiveAuthSession({
929
- cwd,
930
- env,
931
- explicitApiUrl,
932
- autoRotate: false,
933
- homeDir,
934
- });
935
- if (!active || !active.token) {
936
- throw new SentinelayerApiError(`No active auth token found. Run \`${authLoginHint()}\` first.`, {
937
- status: 401,
938
- code: "AUTH_REQUIRED",
939
- });
940
- }
941
-
942
- const targetTokenId = String(tokenId || "").trim() || String(active.tokenId || "").trim();
943
- if (!targetTokenId) {
944
- throw new Error(
945
- "tokenId is required. Provide --token-id or use a stored session that includes token metadata."
946
- );
947
- }
948
-
949
- await revokeApiToken({
950
- apiUrl: active.apiUrl,
951
- authToken: active.token,
952
- tokenId: targetTokenId,
953
- });
954
-
955
- let matchedStoredSession = false;
956
- let clearedLocal = false;
957
- let filePath = null;
958
- const stored = await readStoredSession({ homeDir });
959
- if (stored && String(stored.tokenId || "").trim() === targetTokenId) {
960
- matchedStoredSession = true;
961
- const cleared = await clearStoredSession({ homeDir });
962
- clearedLocal = Boolean(cleared.hadSession);
963
- filePath = cleared.filePath || null;
964
- }
965
-
966
- return {
967
- apiUrl: active.apiUrl,
968
- source: active.source,
969
- tokenId: targetTokenId,
970
- revokedRemote: true,
971
- matchedStoredSession,
972
- clearedLocal,
973
- filePath,
974
- };
975
- }
976
-
977
- /**
978
- * Clear local CLI session state and optionally revoke the remote token first.
979
- *
980
- * @param {{
981
- * homeDir?: string,
982
- * cwd?: string,
983
- * env?: NodeJS.ProcessEnv,
984
- * explicitApiUrl?: string,
985
- * revokeRemote?: boolean
986
- * }} [options]
987
- * @returns {Promise<{
988
- * hadStoredSession: boolean,
989
- * revokedRemote: boolean,
990
- * clearedLocal: boolean,
991
- * apiUrl?: string,
992
- * filePath?: string
993
- * }>}
994
- */
995
- export async function logoutSession({
996
- homeDir,
997
- cwd = process.cwd(),
998
- env = process.env,
999
- explicitApiUrl = "",
1000
- revokeRemote = true,
1001
- } = {}) {
1002
- const stored = await readStoredSession({ homeDir });
1003
- if (!stored) {
1004
- return {
1005
- hadStoredSession: false,
1006
- revokedRemote: false,
1007
- clearedLocal: false,
1008
- apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
1009
- };
1010
- }
1011
-
1012
- let revokedRemote = false;
1013
- if (revokeRemote && stored.tokenId && stored.token) {
1014
- try {
1015
- await revokeApiToken({
1016
- apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
1017
- authToken: stored.token,
1018
- tokenId: stored.tokenId,
1019
- });
1020
- revokedRemote = true;
1021
- } catch {
1022
- revokedRemote = false;
1023
- }
1024
- }
1025
-
1026
- const cleared = await clearStoredSession({ homeDir });
1027
- return {
1028
- hadStoredSession: true,
1029
- revokedRemote,
1030
- clearedLocal: cleared.hadSession,
1031
- filePath: cleared.filePath,
1032
- };
1033
- }
1034
-
1035
- /**
1036
- * Fetch runtime run event stream slices used by `sl watch` and reproducibility artifacts.
1037
- *
1038
- * @param {{
1039
- * apiUrl: string,
1040
- * authToken: string,
1041
- * runId: string,
1042
- * afterEventId?: string | null
1043
- * }} [options]
1044
- * @returns {Promise<any>}
1045
- */
1046
- export async function listRuntimeRunEvents({
1047
- apiUrl,
1048
- authToken,
1049
- runId,
1050
- afterEventId = null,
1051
- } = {}) {
1052
- const query = afterEventId
1053
- ? `?after_event_id=${encodeURIComponent(String(afterEventId))}`
1054
- : "";
1055
- return requestJson(
1056
- buildApiPath(apiUrl, `/api/v1/runtime/runs/${encodeURIComponent(String(runId || ""))}/events/list${query}`),
1057
- {
1058
- method: "GET",
1059
- headers: toAuthHeader(authToken),
1060
- }
1061
- );
1062
- }
1063
-
1064
- /**
1065
- * Fetch runtime run status snapshot from the Sentinelayer API.
1066
- *
1067
- * @param {{ apiUrl: string, authToken: string, runId: string }} [options]
1068
- * @returns {Promise<any>}
1069
- */
1070
- /**
1071
- * Fetch AIdenID credentials from the SentinelLayer API (lazy-provisioning).
1072
- * The secret is returned in-memory only, never persisted to disk.
1073
- */
1074
- export async function fetchAidenIdCredentials({
1075
- apiUrl = DEFAULT_API_URL,
1076
- token = "",
1077
- } = {}) {
1078
- const response = await requestJson(
1079
- buildApiPath(apiUrl, "/api/v1/aidenid/credentials"),
1080
- {
1081
- method: "GET",
1082
- headers: toAuthHeader(token),
1083
- }
1084
- );
1085
- return {
1086
- orgId: String(response.orgId || response.org_id || "").trim(),
1087
- projectId: String(response.projectId || response.project_id || "").trim(),
1088
- apiKeyPrefix: String(response.apiKeyPrefix || response.api_key_prefix || "").trim(),
1089
- apiKey: String(response.apiKey || response.api_key || "").trim(),
1090
- provisioned: Boolean(response.provisioned),
1091
- };
1092
- }
1093
-
1094
- export async function getRuntimeRunStatus({
1095
- apiUrl,
1096
- authToken,
1097
- runId,
1098
- } = {}) {
1099
- return requestJson(
1100
- buildApiPath(apiUrl, `/api/v1/runtime/runs/${encodeURIComponent(String(runId || ""))}/status`),
1101
- {
1102
- method: "GET",
1103
- headers: toAuthHeader(authToken),
1104
- }
1105
- );
1106
- }
1
+ import crypto from "node:crypto";
2
+ import process from "node:process";
3
+ import { setTimeout as sleep } from "node:timers/promises";
4
+
5
+ import open from "open";
6
+
7
+ import { loadConfig } from "../config/service.js";
8
+ import { SentinelayerApiError, requestJson, requestJsonMutation } from "./http.js";
9
+ import {
10
+ clearStoredSession,
11
+ readStoredSession,
12
+ readStoredSessionMetadata,
13
+ writeStoredSession,
14
+ } from "./session-store.js";
15
+ import { authLoginHint } from "../ui/command-hints.js";
16
+
17
+ const DEFAULT_API_URL = "https://api.sentinelayer.com";
18
+ /** Default maximum wall-clock wait for browser-based CLI auth approval (ms). */
19
+ export const DEFAULT_AUTH_TIMEOUT_MS = 10 * 60 * 1000;
20
+ /** Default lifetime for issued API tokens used by CLI sessions (days). */
21
+ export const DEFAULT_API_TOKEN_TTL_DAYS = 365;
22
+ /** Default threshold at which stored tokens are rotated before expiry (days). */
23
+ export const DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS = 7;
24
+ const DEFAULT_IDE_NAME = "sl-cli";
25
+ const MAX_AUTH_POLL_REQUESTS = 600;
26
+ const MIN_TRANSIENT_POLL_DELAY_MS = 2_000;
27
+ const TRANSIENT_DELAY_THRESHOLD = 3;
28
+
29
+ function normalizeApiUrl(rawValue) {
30
+ const candidate = String(rawValue || "").trim() || DEFAULT_API_URL;
31
+ let parsed;
32
+ try {
33
+ parsed = new URL(candidate);
34
+ } catch {
35
+ throw new Error(`Invalid API URL '${candidate}'.`);
36
+ }
37
+ const hostname = String(parsed.hostname || "").toLowerCase();
38
+ const isLocalhost = hostname === "localhost" || hostname === "127.0.0.1";
39
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLocalhost)) {
40
+ throw new Error(`API URL must use https (received '${candidate}').`);
41
+ }
42
+ parsed.pathname = "/";
43
+ parsed.search = "";
44
+ parsed.hash = "";
45
+ return parsed.toString().replace(/\/$/, "");
46
+ }
47
+
48
+ function normalizePositiveNumber(rawValue, field, fallbackValue) {
49
+ if (rawValue === undefined || rawValue === null || String(rawValue).trim() === "") {
50
+ return fallbackValue;
51
+ }
52
+ const normalized = Number(rawValue);
53
+ if (!Number.isFinite(normalized) || normalized <= 0) {
54
+ throw new Error(`${field} must be a positive number.`);
55
+ }
56
+ return normalized;
57
+ }
58
+
59
+ function toAuthHeader(token) {
60
+ return {
61
+ Authorization: `Bearer ${String(token || "").trim()}`,
62
+ };
63
+ }
64
+
65
+ function normalizeUser(user = {}) {
66
+ return {
67
+ id: String(user.id || "").trim(),
68
+ githubUsername: String(user.githubUsername || user.github_username || "").trim(),
69
+ email: String(user.email || "").trim(),
70
+ avatarUrl: String(user.avatarUrl || user.avatar_url || "").trim(),
71
+ isAdmin: Boolean(user.isAdmin || user.is_admin),
72
+ };
73
+ }
74
+
75
+ function buildApiPath(apiUrl, pathSuffix) {
76
+ return `${normalizeApiUrl(apiUrl)}${String(pathSuffix || "")}`;
77
+ }
78
+
79
+ function generateChallenge() {
80
+ return crypto.randomBytes(48).toString("base64url");
81
+ }
82
+
83
+ function createFlowRequestId() {
84
+ try {
85
+ return crypto.randomUUID();
86
+ } catch {
87
+ return `flow-${Date.now().toString(36)}-${crypto.randomBytes(8).toString("hex")}`;
88
+ }
89
+ }
90
+
91
+ function withFlowRequestHeaders(headers, flowRequestId) {
92
+ const merged = {
93
+ ...(headers || {}),
94
+ "X-Request-Id": createFlowRequestId(),
95
+ };
96
+ if (flowRequestId) {
97
+ merged["X-Flow-Request-Id"] = flowRequestId;
98
+ }
99
+ return merged;
100
+ }
101
+
102
+ async function requestAuthJson(flowRequestId, ...args) {
103
+ try {
104
+ return await requestJson(...args);
105
+ } catch (error) {
106
+ if (error instanceof SentinelayerApiError && !error.requestId && flowRequestId) {
107
+ error.requestId = flowRequestId;
108
+ }
109
+ throw error;
110
+ }
111
+ }
112
+
113
+ async function requestAuthJsonMutation(flowRequestId, ...args) {
114
+ try {
115
+ return await requestJsonMutation(...args);
116
+ } catch (error) {
117
+ if (error instanceof SentinelayerApiError && !error.requestId && flowRequestId) {
118
+ error.requestId = flowRequestId;
119
+ }
120
+ throw error;
121
+ }
122
+ }
123
+
124
+ function defaultTokenLabel() {
125
+ const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..+/, "").replace("T", "-");
126
+ return `sl-cli-session-${stamp}`;
127
+ }
128
+
129
+ function createIdempotencyKey(prefix) {
130
+ const normalizedPrefix = String(prefix || "sl-cli").trim() || "sl-cli";
131
+ let suffix;
132
+ try {
133
+ suffix = crypto.randomUUID();
134
+ } catch {
135
+ suffix = `${Date.now().toString(36)}-${crypto.randomBytes(8).toString("hex")}`;
136
+ }
137
+ return `${normalizedPrefix}-${suffix}`;
138
+ }
139
+
140
+ function computeDeterministicJitterFactor({ sessionId, attempt }) {
141
+ const seed = `${String(sessionId || "").trim()}|${Number(attempt) || 0}`;
142
+ const digest = crypto.createHash("sha256").update(seed).digest();
143
+ const raw = digest.readUInt32BE(0);
144
+ const ratio = raw / 0xffffffff;
145
+ return 0.85 + ratio * 0.3;
146
+ }
147
+
148
+ function isNearExpiry(tokenExpiresAt, thresholdDays) {
149
+ const normalized = String(tokenExpiresAt || "").trim();
150
+ if (!normalized) {
151
+ return false;
152
+ }
153
+ const expiryEpoch = Date.parse(normalized);
154
+ if (!Number.isFinite(expiryEpoch)) {
155
+ return false;
156
+ }
157
+ const thresholdMs = Number(thresholdDays || DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS) * 24 * 60 * 60 * 1000;
158
+ return expiryEpoch - Date.now() <= thresholdMs;
159
+ }
160
+
161
+ /**
162
+ * Resolve API URL precedence for auth operations: explicit -> env -> config -> default.
163
+ *
164
+ * @param {{
165
+ * cwd?: string,
166
+ * env?: NodeJS.ProcessEnv,
167
+ * explicitApiUrl?: string,
168
+ * homeDir?: string
169
+ * }} [options]
170
+ * @returns {Promise<string>}
171
+ */
172
+ export async function resolveApiUrl({
173
+ cwd = process.cwd(),
174
+ env = process.env,
175
+ explicitApiUrl = "",
176
+ homeDir,
177
+ } = {}) {
178
+ const overrideUrl = String(explicitApiUrl || "").trim();
179
+ if (overrideUrl) {
180
+ return normalizeApiUrl(overrideUrl);
181
+ }
182
+
183
+ const envUrl = String(env.SENTINELAYER_API_URL || "").trim();
184
+ if (envUrl) {
185
+ return normalizeApiUrl(envUrl);
186
+ }
187
+
188
+ const config = await loadConfig({ cwd, env, homeDir });
189
+ const configuredApiUrl = String(config.resolved.apiUrl || "").trim();
190
+ if (configuredApiUrl) {
191
+ return normalizeApiUrl(configuredApiUrl);
192
+ }
193
+
194
+ return normalizeApiUrl(DEFAULT_API_URL);
195
+ }
196
+
197
+ async function startCliAuthSession({ apiUrl, challenge, ide, cliVersion, flowRequestId }) {
198
+ return requestAuthJsonMutation(
199
+ flowRequestId,
200
+ buildApiPath(apiUrl, "/api/v1/auth/cli/sessions/start"),
201
+ {
202
+ method: "POST",
203
+ operationName: "auth-start",
204
+ headers: withFlowRequestHeaders(null, flowRequestId),
205
+ body: {
206
+ challenge,
207
+ ide: String(ide || DEFAULT_IDE_NAME),
208
+ cli_version: String(cliVersion || "").trim() || null,
209
+ },
210
+ }
211
+ );
212
+ }
213
+
214
+ async function pollCliAuthSession({
215
+ apiUrl,
216
+ sessionId,
217
+ challenge,
218
+ timeoutMs,
219
+ pollIntervalSeconds,
220
+ flowRequestId,
221
+ }) {
222
+ const timeout = normalizePositiveNumber(timeoutMs, "timeoutMs", DEFAULT_AUTH_TIMEOUT_MS);
223
+ const pollIntervalMs = Math.max(250, Math.round(Number(pollIntervalSeconds || 2) * 1000));
224
+ const maxPollIntervalMs = Math.max(pollIntervalMs, Math.min(5_000, Math.floor(timeout / 4)));
225
+ const pollRequestTimeoutMs = Math.min(5_000, Math.max(1_000, pollIntervalMs));
226
+ const pollRequestMaxRetries = 1;
227
+ const pollRequestRetryDelayMs = 250;
228
+ let pollAttempt = 0;
229
+ const transientErrorBudget = Math.max(8, Math.ceil(timeout / maxPollIntervalMs) * 3);
230
+ const maxSleepBudgetMs = Math.max(2_000, Math.floor(timeout * 0.8));
231
+ const maxPollAttempts = Math.min(
232
+ MAX_AUTH_POLL_REQUESTS,
233
+ Math.max(1, Math.ceil(timeout / Math.max(250, pollIntervalMs)))
234
+ );
235
+ let rateLimitErrorCount = 0;
236
+ let serverErrorCount = 0;
237
+ let networkErrorCount = 0;
238
+ let transientBudgetUsed = 0;
239
+ let cumulativeSleepMs = 0;
240
+ let pollIterations = 0;
241
+ const deadline = Date.now() + timeout;
242
+ const classifyPollError = (error) => {
243
+ if (!(error instanceof SentinelayerApiError)) {
244
+ return null;
245
+ }
246
+ if (error.status === 429) {
247
+ return "rate_limit";
248
+ }
249
+ if (error.status >= 500) {
250
+ return "server";
251
+ }
252
+ if (error.code === "NETWORK_ERROR" || error.code === "TIMEOUT") {
253
+ return "network";
254
+ }
255
+ return null;
256
+ };
257
+ const computePollDelayMs = (retryAfterMs = null) => {
258
+ const transientErrorCount = rateLimitErrorCount + serverErrorCount + networkErrorCount;
259
+ const minDelayMs =
260
+ transientErrorCount >= TRANSIENT_DELAY_THRESHOLD ? MIN_TRANSIENT_POLL_DELAY_MS : 250;
261
+ if (Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
262
+ return Math.max(minDelayMs, Math.min(maxPollIntervalMs, Math.round(retryAfterMs)));
263
+ }
264
+ const exponent = Math.min(6, pollAttempt);
265
+ const backoffMs = Math.min(maxPollIntervalMs, Math.round(pollIntervalMs * Math.pow(1.5, exponent)));
266
+ const jitterFactor = computeDeterministicJitterFactor({ sessionId, attempt: pollAttempt });
267
+ return Math.max(minDelayMs, Math.round(backoffMs * jitterFactor));
268
+ };
269
+
270
+ while (Date.now() < deadline) {
271
+ const remainingBeforeRequestMs = deadline - Date.now();
272
+ if (remainingBeforeRequestMs <= 250) {
273
+ break;
274
+ }
275
+ pollIterations += 1;
276
+ if (pollIterations > maxPollAttempts) {
277
+ throw new SentinelayerApiError("CLI authentication polling exceeded attempt budget.", {
278
+ status: 408,
279
+ code: "CLI_AUTH_POLL_EXHAUSTED",
280
+ requestId: flowRequestId || null,
281
+ });
282
+ }
283
+ let payload;
284
+ try {
285
+ payload = await requestAuthJsonMutation(
286
+ flowRequestId,
287
+ buildApiPath(apiUrl, "/api/v1/auth/cli/sessions/poll"),
288
+ {
289
+ method: "POST",
290
+ operationName: "auth-poll",
291
+ headers: withFlowRequestHeaders(null, flowRequestId),
292
+ body: {
293
+ session_id: sessionId,
294
+ challenge,
295
+ },
296
+ timeoutMs: Math.max(250, Math.min(pollRequestTimeoutMs, remainingBeforeRequestMs)),
297
+ maxRetries: pollRequestMaxRetries,
298
+ retryDelayMs: pollRequestRetryDelayMs,
299
+ }
300
+ );
301
+ } catch (error) {
302
+ if (error instanceof SentinelayerApiError && !error.requestId && flowRequestId) {
303
+ error.requestId = flowRequestId;
304
+ }
305
+ const classification = classifyPollError(error);
306
+ if (classification) {
307
+ const transientWeight = classification === "rate_limit" ? 3 : classification === "server" ? 2 : 1;
308
+ if (transientBudgetUsed + transientWeight > transientErrorBudget) {
309
+ throw new SentinelayerApiError("CLI authentication polling exhausted transient error budget.", {
310
+ status: 503,
311
+ code: "CLI_AUTH_TRANSIENT_BUDGET_EXHAUSTED",
312
+ requestId: error.requestId || flowRequestId || null,
313
+ });
314
+ }
315
+ transientBudgetUsed += transientWeight;
316
+ if (classification === "rate_limit") {
317
+ rateLimitErrorCount += 1;
318
+ } else if (classification === "server") {
319
+ serverErrorCount += 1;
320
+ } else {
321
+ networkErrorCount += 1;
322
+ }
323
+ const retryAfterMs = Number.isFinite(error.retryAfterMs) ? error.retryAfterMs : null;
324
+ const delayMs = computePollDelayMs(retryAfterMs);
325
+ const remainingBeforeSleepMs = deadline - Date.now();
326
+ if (remainingBeforeSleepMs <= 250) {
327
+ break;
328
+ }
329
+ const boundedDelayMs = Math.max(250, Math.min(delayMs, remainingBeforeSleepMs));
330
+ if (cumulativeSleepMs + boundedDelayMs > maxSleepBudgetMs) {
331
+ throw new SentinelayerApiError("CLI authentication polling exceeded retry sleep budget.", {
332
+ status: 503,
333
+ code: "CLI_AUTH_SLEEP_BUDGET_EXHAUSTED",
334
+ requestId: error.requestId || flowRequestId || null,
335
+ });
336
+ }
337
+ cumulativeSleepMs += boundedDelayMs;
338
+ pollAttempt += 1;
339
+ await sleep(boundedDelayMs);
340
+ continue;
341
+ }
342
+ throw error;
343
+ }
344
+
345
+ const status = String(payload.status || "pending").trim().toLowerCase();
346
+ if (status === "approved" && payload.auth_token) {
347
+ return payload;
348
+ }
349
+ if (status === "rejected" || status === "denied" || status === "cancelled") {
350
+ throw new SentinelayerApiError("CLI authentication was not approved.", {
351
+ status: 401,
352
+ code: "CLI_AUTH_REJECTED",
353
+ requestId: flowRequestId || null,
354
+ });
355
+ }
356
+ if (status === "expired") {
357
+ throw new SentinelayerApiError("CLI authentication session expired.", {
358
+ status: 401,
359
+ code: "CLI_AUTH_EXPIRED",
360
+ requestId: flowRequestId || null,
361
+ });
362
+ }
363
+
364
+ const delayMs = computePollDelayMs();
365
+ const remainingBeforeSleepMs = deadline - Date.now();
366
+ if (remainingBeforeSleepMs <= 250) {
367
+ break;
368
+ }
369
+ const boundedDelayMs = Math.max(250, Math.min(delayMs, remainingBeforeSleepMs));
370
+ pollAttempt += 1;
371
+ await sleep(boundedDelayMs);
372
+ }
373
+
374
+ throw new SentinelayerApiError("CLI authentication timed out. Restart and try again.", {
375
+ status: 408,
376
+ code: "CLI_AUTH_TIMEOUT",
377
+ requestId: flowRequestId || null,
378
+ });
379
+ }
380
+
381
+ async function fetchCurrentUser({ apiUrl, token, flowRequestId }) {
382
+ return requestAuthJson(
383
+ flowRequestId,
384
+ buildApiPath(apiUrl, "/api/v1/auth/me"),
385
+ {
386
+ method: "GET",
387
+ headers: withFlowRequestHeaders(toAuthHeader(token), flowRequestId),
388
+ }
389
+ );
390
+ }
391
+
392
+ async function issueApiToken({
393
+ apiUrl,
394
+ authToken,
395
+ tokenLabel,
396
+ tokenTtlDays,
397
+ flowRequestId,
398
+ }) {
399
+ const expiresInDays = Math.round(
400
+ normalizePositiveNumber(tokenTtlDays, "apiTokenTtlDays", DEFAULT_API_TOKEN_TTL_DAYS)
401
+ );
402
+ return requestAuthJsonMutation(
403
+ flowRequestId,
404
+ buildApiPath(apiUrl, "/api/v1/auth/api-tokens"),
405
+ {
406
+ method: "POST",
407
+ operationName: "issue-token",
408
+ headers: withFlowRequestHeaders(
409
+ {
410
+ ...toAuthHeader(authToken),
411
+ },
412
+ flowRequestId
413
+ ),
414
+ body: {
415
+ label: String(tokenLabel || "").trim() || defaultTokenLabel(),
416
+ scope: "cli",
417
+ llm_credential_mode: "managed",
418
+ expires_in_days: expiresInDays,
419
+ },
420
+ }
421
+ );
422
+ }
423
+
424
+ async function revokeApiToken({ apiUrl, authToken, tokenId }) {
425
+ const normalizedTokenId = String(tokenId || "").trim();
426
+ if (!normalizedTokenId) {
427
+ return false;
428
+ }
429
+ await requestJsonMutation(buildApiPath(apiUrl, `/api/v1/auth/api-tokens/${encodeURIComponent(normalizedTokenId)}`), {
430
+ method: "DELETE",
431
+ operationName: "revoke-token",
432
+ headers: {
433
+ ...toAuthHeader(authToken),
434
+ },
435
+ });
436
+ return true;
437
+ }
438
+
439
+ async function rotateStoredApiTokenIfNeeded({
440
+ session,
441
+ thresholdDays,
442
+ tokenLabel,
443
+ tokenTtlDays,
444
+ homeDir,
445
+ }) {
446
+ if (!session || !session.token || !session.tokenExpiresAt) {
447
+ return { session, rotated: false };
448
+ }
449
+ if (!isNearExpiry(session.tokenExpiresAt, thresholdDays)) {
450
+ return { session, rotated: false };
451
+ }
452
+
453
+ const issued = await issueApiToken({
454
+ apiUrl: session.apiUrl,
455
+ authToken: session.token,
456
+ tokenLabel,
457
+ tokenTtlDays,
458
+ });
459
+
460
+ const nextSession = await writeStoredSession(
461
+ {
462
+ apiUrl: session.apiUrl,
463
+ token: String(issued.token || ""),
464
+ tokenId: issued.id || null,
465
+ tokenPrefix: issued.token_prefix || null,
466
+ tokenExpiresAt: issued.expires_at || null,
467
+ user: session.user,
468
+ },
469
+ { homeDir }
470
+ );
471
+
472
+ let revokeError = null;
473
+ if (session.tokenId) {
474
+ try {
475
+ await revokeApiToken({
476
+ apiUrl: session.apiUrl,
477
+ authToken: nextSession.token,
478
+ tokenId: session.tokenId,
479
+ });
480
+ } catch (error) {
481
+ revokeError = error;
482
+ }
483
+ }
484
+
485
+ return {
486
+ session: nextSession,
487
+ rotated: true,
488
+ revokeError,
489
+ };
490
+ }
491
+
492
+ /**
493
+ * Perform browser-based CLI login flow and persist an API token session locally.
494
+ *
495
+ * @param {{
496
+ * cwd?: string,
497
+ * env?: NodeJS.ProcessEnv,
498
+ * explicitApiUrl?: string,
499
+ * skipBrowserOpen?: boolean,
500
+ * timeoutMs?: number,
501
+ * tokenLabel?: string,
502
+ * tokenTtlDays?: number,
503
+ * ide?: string,
504
+ * cliVersion?: string,
505
+ * homeDir?: string
506
+ * }} [options]
507
+ * @returns {Promise<{
508
+ * apiUrl: string,
509
+ * authorizeUrl: string,
510
+ * browserOpened: boolean,
511
+ * user: {
512
+ * id: string,
513
+ * githubUsername: string,
514
+ * email: string,
515
+ * avatarUrl: string,
516
+ * isAdmin: boolean
517
+ * },
518
+ * tokenId: string | null,
519
+ * tokenPrefix: string | null,
520
+ * tokenExpiresAt: string | null,
521
+ * storage: string,
522
+ * filePath: string
523
+ * }>}
524
+ */
525
+ export async function loginAndPersistSession({
526
+ cwd = process.cwd(),
527
+ env = process.env,
528
+ explicitApiUrl = "",
529
+ skipBrowserOpen = false,
530
+ timeoutMs = DEFAULT_AUTH_TIMEOUT_MS,
531
+ tokenLabel = "",
532
+ tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
533
+ ide = DEFAULT_IDE_NAME,
534
+ cliVersion = "",
535
+ homeDir,
536
+ } = {}) {
537
+ const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
538
+ const challenge = generateChallenge();
539
+ const flowRequestId = createFlowRequestId();
540
+ const session = await startCliAuthSession({
541
+ apiUrl,
542
+ challenge,
543
+ ide,
544
+ cliVersion,
545
+ flowRequestId,
546
+ });
547
+
548
+ const authorizeUrl = String(session.authorize_url || "").trim();
549
+ let browserOpened = false;
550
+ if (!skipBrowserOpen && authorizeUrl) {
551
+ try {
552
+ await open(authorizeUrl);
553
+ browserOpened = true;
554
+ } catch {
555
+ browserOpened = false;
556
+ }
557
+ }
558
+
559
+ const approval = await pollCliAuthSession({
560
+ apiUrl,
561
+ sessionId: String(session.session_id || "").trim(),
562
+ challenge,
563
+ timeoutMs,
564
+ pollIntervalSeconds: Number(session.poll_interval_seconds || 2),
565
+ flowRequestId,
566
+ });
567
+
568
+ const approvalToken = String(approval.auth_token || "").trim();
569
+ if (!approvalToken) {
570
+ throw new SentinelayerApiError("Authentication completed but no auth token was returned.", {
571
+ status: 503,
572
+ code: "CLI_AUTH_MISSING_TOKEN",
573
+ requestId: flowRequestId || null,
574
+ });
575
+ }
576
+
577
+ const user = normalizeUser(
578
+ approval.user || (await fetchCurrentUser({ apiUrl, token: approvalToken, flowRequestId }))
579
+ );
580
+ const issuedApiToken = await issueApiToken({
581
+ apiUrl,
582
+ authToken: approvalToken,
583
+ tokenLabel,
584
+ tokenTtlDays,
585
+ flowRequestId,
586
+ });
587
+
588
+ // Extract AIdenID metadata from approval (no secret stored locally)
589
+ const rawAidenId = approval.aidenidCredentials || approval.aidenid_credentials || null;
590
+ const aidenid =
591
+ rawAidenId && rawAidenId.provisioned
592
+ ? {
593
+ orgId: String(rawAidenId.orgId || rawAidenId.org_id || "").trim() || null,
594
+ projectId: String(rawAidenId.projectId || rawAidenId.project_id || "").trim() || null,
595
+ apiKeyPrefix: String(rawAidenId.apiKeyPrefix || rawAidenId.api_key_prefix || "").trim() || null,
596
+ provisionedAt: new Date().toISOString(),
597
+ }
598
+ : null;
599
+
600
+ const stored = await writeStoredSession(
601
+ {
602
+ apiUrl,
603
+ token: String(issuedApiToken.token || ""),
604
+ tokenId: issuedApiToken.id || null,
605
+ tokenPrefix: issuedApiToken.token_prefix || null,
606
+ tokenExpiresAt: issuedApiToken.expires_at || null,
607
+ user,
608
+ aidenid,
609
+ },
610
+ { homeDir }
611
+ );
612
+
613
+ return {
614
+ apiUrl,
615
+ authorizeUrl,
616
+ browserOpened,
617
+ user,
618
+ tokenId: stored.tokenId,
619
+ tokenPrefix: stored.tokenPrefix,
620
+ tokenExpiresAt: stored.tokenExpiresAt,
621
+ storage: stored.storage,
622
+ filePath: stored.filePath,
623
+ aidenid: stored.aidenid || null,
624
+ flowRequestId,
625
+ };
626
+ }
627
+
628
+ /**
629
+ * Resolve active auth credentials used by CLI commands, optionally rotating near-expiry session tokens.
630
+ *
631
+ * @param {{
632
+ * cwd?: string,
633
+ * env?: NodeJS.ProcessEnv,
634
+ * explicitApiUrl?: string,
635
+ * autoRotate?: boolean,
636
+ * rotateThresholdDays?: number,
637
+ * tokenLabel?: string,
638
+ * tokenTtlDays?: number,
639
+ * homeDir?: string
640
+ * }} [options]
641
+ * @returns {Promise<null | {
642
+ * apiUrl: string,
643
+ * token: string,
644
+ * source: "env" | "config" | "session",
645
+ * user: {
646
+ * id: string,
647
+ * githubUsername: string,
648
+ * email: string,
649
+ * avatarUrl: string,
650
+ * isAdmin: boolean
651
+ * } | null,
652
+ * storage: string,
653
+ * tokenId: string | null,
654
+ * tokenPrefix: string | null,
655
+ * tokenExpiresAt: string | null,
656
+ * rotated: boolean,
657
+ * filePath: string | null
658
+ * }>}
659
+ */
660
+ export async function resolveActiveAuthSession({
661
+ cwd = process.cwd(),
662
+ env = process.env,
663
+ explicitApiUrl = "",
664
+ autoRotate = true,
665
+ rotateThresholdDays = DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS,
666
+ tokenLabel = "",
667
+ tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
668
+ homeDir,
669
+ } = {}) {
670
+ const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
671
+
672
+ const envToken = String(env.SENTINELAYER_TOKEN || "").trim();
673
+ if (envToken) {
674
+ return {
675
+ apiUrl,
676
+ token: envToken,
677
+ source: "env",
678
+ user: null,
679
+ aidenid: null,
680
+ storage: "env",
681
+ tokenId: null,
682
+ tokenPrefix: null,
683
+ tokenExpiresAt: null,
684
+ rotated: false,
685
+ filePath: null,
686
+ };
687
+ }
688
+
689
+ const config = await loadConfig({ cwd, env, homeDir });
690
+ const configuredToken = String(config.resolved.sentinelayerToken || "").trim();
691
+ if (configuredToken) {
692
+ return {
693
+ apiUrl,
694
+ token: configuredToken,
695
+ source: "config",
696
+ user: null,
697
+ aidenid: null,
698
+ storage: "config",
699
+ tokenId: null,
700
+ tokenPrefix: null,
701
+ tokenExpiresAt: null,
702
+ rotated: false,
703
+ filePath: null,
704
+ };
705
+ }
706
+
707
+ const stored = await readStoredSession({ homeDir });
708
+ if (!stored) {
709
+ return null;
710
+ }
711
+
712
+ let active = stored;
713
+ let rotated = false;
714
+ if (autoRotate) {
715
+ try {
716
+ const rotateResult = await rotateStoredApiTokenIfNeeded({
717
+ session: stored,
718
+ thresholdDays: rotateThresholdDays,
719
+ tokenLabel,
720
+ tokenTtlDays,
721
+ homeDir,
722
+ });
723
+ active = rotateResult.session;
724
+ rotated = rotateResult.rotated;
725
+ if (rotateResult.revokeError) {
726
+ console.warn(
727
+ "Sentinelayer token rotation succeeded but previous token revocation failed. " +
728
+ "Revoke the old token manually in the dashboard if needed."
729
+ );
730
+ }
731
+ } catch {
732
+ // Keep existing token if rotation fails.
733
+ active = stored;
734
+ rotated = false;
735
+ }
736
+ }
737
+
738
+ return {
739
+ apiUrl,
740
+ token: active.token,
741
+ source: "session",
742
+ user: normalizeUser(active.user || {}),
743
+ aidenid: active.aidenid || null,
744
+ storage: active.storage,
745
+ tokenId: active.tokenId || null,
746
+ tokenPrefix: active.tokenPrefix || null,
747
+ tokenExpiresAt: active.tokenExpiresAt || null,
748
+ rotated,
749
+ filePath: active.filePath,
750
+ };
751
+ }
752
+
753
+ /**
754
+ * Return current authentication state, with optional remote `/auth/me` verification.
755
+ *
756
+ * @param {{
757
+ * cwd?: string,
758
+ * env?: NodeJS.ProcessEnv,
759
+ * explicitApiUrl?: string,
760
+ * checkRemote?: boolean,
761
+ * autoRotate?: boolean,
762
+ * rotateThresholdDays?: number,
763
+ * tokenLabel?: string,
764
+ * tokenTtlDays?: number,
765
+ * homeDir?: string
766
+ * }} [options]
767
+ * @returns {Promise<{
768
+ * authenticated: boolean,
769
+ * apiUrl: string,
770
+ * source: string | null,
771
+ * storage: string | null,
772
+ * user: any,
773
+ * remoteUser: any,
774
+ * remoteError: null | { code: string, message: string, status: number, requestId: string | null },
775
+ * rotated: boolean,
776
+ * tokenExpiresAt: string | null,
777
+ * tokenPrefix: string | null,
778
+ * tokenId: string | null,
779
+ * filePath: string | null
780
+ * }>}
781
+ */
782
+ export async function getAuthStatus({
783
+ cwd = process.cwd(),
784
+ env = process.env,
785
+ explicitApiUrl = "",
786
+ checkRemote = true,
787
+ autoRotate = true,
788
+ rotateThresholdDays = DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS,
789
+ tokenLabel = "",
790
+ tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
791
+ homeDir,
792
+ } = {}) {
793
+ const session = await resolveActiveAuthSession({
794
+ cwd,
795
+ env,
796
+ explicitApiUrl,
797
+ autoRotate,
798
+ rotateThresholdDays,
799
+ tokenLabel,
800
+ tokenTtlDays,
801
+ homeDir,
802
+ });
803
+
804
+ if (!session) {
805
+ return {
806
+ authenticated: false,
807
+ apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
808
+ source: null,
809
+ storage: null,
810
+ user: null,
811
+ aidenid: null,
812
+ remoteUser: null,
813
+ remoteError: null,
814
+ rotated: false,
815
+ tokenExpiresAt: null,
816
+ tokenPrefix: null,
817
+ tokenId: null,
818
+ filePath: null,
819
+ };
820
+ }
821
+
822
+ let remoteUser = null;
823
+ let remoteError = null;
824
+ if (checkRemote) {
825
+ try {
826
+ remoteUser = normalizeUser(await fetchCurrentUser({ apiUrl: session.apiUrl, token: session.token }));
827
+ } catch (error) {
828
+ remoteError =
829
+ error instanceof SentinelayerApiError
830
+ ? {
831
+ code: error.code,
832
+ message: error.message,
833
+ status: error.status,
834
+ requestId: error.requestId,
835
+ }
836
+ : {
837
+ code: "UNKNOWN",
838
+ message: error instanceof Error ? error.message : String(error || "Unknown error"),
839
+ status: 500,
840
+ requestId: null,
841
+ };
842
+ }
843
+ }
844
+
845
+ return {
846
+ authenticated: !remoteError,
847
+ apiUrl: session.apiUrl,
848
+ source: session.source,
849
+ storage: session.storage,
850
+ user: session.user,
851
+ aidenid: session.aidenid || null,
852
+ remoteUser,
853
+ remoteError,
854
+ rotated: session.rotated,
855
+ tokenExpiresAt: session.tokenExpiresAt,
856
+ tokenPrefix: session.tokenPrefix,
857
+ tokenId: session.tokenId,
858
+ filePath: session.filePath,
859
+ };
860
+ }
861
+
862
+ /**
863
+ * List persisted local session metadata for CLI operators/HITL dashboards.
864
+ *
865
+ * @param {{ cwd?: string, env?: NodeJS.ProcessEnv, explicitApiUrl?: string, homeDir?: string }} [options]
866
+ * @returns {Promise<{ apiUrl: string, sessions: Array<any> }>}
867
+ */
868
+ export async function listStoredAuthSessions({
869
+ cwd = process.cwd(),
870
+ env = process.env,
871
+ explicitApiUrl = "",
872
+ homeDir,
873
+ } = {}) {
874
+ const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
875
+ const stored = await readStoredSessionMetadata({ homeDir });
876
+ if (!stored) {
877
+ return {
878
+ apiUrl,
879
+ sessions: [],
880
+ };
881
+ }
882
+
883
+ return {
884
+ apiUrl,
885
+ sessions: [
886
+ {
887
+ source: "session",
888
+ storage: stored.storage || null,
889
+ tokenId: stored.tokenId || null,
890
+ tokenPrefix: stored.tokenPrefix || null,
891
+ tokenExpiresAt: stored.tokenExpiresAt || null,
892
+ createdAt: stored.createdAt || null,
893
+ updatedAt: stored.updatedAt || null,
894
+ user: normalizeUser(stored.user || {}),
895
+ filePath: stored.filePath || null,
896
+ },
897
+ ],
898
+ };
899
+ }
900
+
901
+ /**
902
+ * Revoke an API token remotely and clear matching local stored session metadata when applicable.
903
+ *
904
+ * @param {{
905
+ * cwd?: string,
906
+ * env?: NodeJS.ProcessEnv,
907
+ * explicitApiUrl?: string,
908
+ * tokenId?: string,
909
+ * homeDir?: string
910
+ * }} [options]
911
+ * @returns {Promise<{
912
+ * apiUrl: string,
913
+ * source: string,
914
+ * tokenId: string,
915
+ * revokedRemote: boolean,
916
+ * matchedStoredSession: boolean,
917
+ * clearedLocal: boolean,
918
+ * filePath: string | null
919
+ * }>}
920
+ */
921
+ export async function revokeAuthToken({
922
+ cwd = process.cwd(),
923
+ env = process.env,
924
+ explicitApiUrl = "",
925
+ tokenId = "",
926
+ homeDir,
927
+ } = {}) {
928
+ const active = await resolveActiveAuthSession({
929
+ cwd,
930
+ env,
931
+ explicitApiUrl,
932
+ autoRotate: false,
933
+ homeDir,
934
+ });
935
+ if (!active || !active.token) {
936
+ throw new SentinelayerApiError(`No active auth token found. Run \`${authLoginHint()}\` first.`, {
937
+ status: 401,
938
+ code: "AUTH_REQUIRED",
939
+ });
940
+ }
941
+
942
+ const targetTokenId = String(tokenId || "").trim() || String(active.tokenId || "").trim();
943
+ if (!targetTokenId) {
944
+ throw new Error(
945
+ "tokenId is required. Provide --token-id or use a stored session that includes token metadata."
946
+ );
947
+ }
948
+
949
+ await revokeApiToken({
950
+ apiUrl: active.apiUrl,
951
+ authToken: active.token,
952
+ tokenId: targetTokenId,
953
+ });
954
+
955
+ let matchedStoredSession = false;
956
+ let clearedLocal = false;
957
+ let filePath = null;
958
+ const stored = await readStoredSession({ homeDir });
959
+ if (stored && String(stored.tokenId || "").trim() === targetTokenId) {
960
+ matchedStoredSession = true;
961
+ const cleared = await clearStoredSession({ homeDir });
962
+ clearedLocal = Boolean(cleared.hadSession);
963
+ filePath = cleared.filePath || null;
964
+ }
965
+
966
+ return {
967
+ apiUrl: active.apiUrl,
968
+ source: active.source,
969
+ tokenId: targetTokenId,
970
+ revokedRemote: true,
971
+ matchedStoredSession,
972
+ clearedLocal,
973
+ filePath,
974
+ };
975
+ }
976
+
977
+ /**
978
+ * Clear local CLI session state and optionally revoke the remote token first.
979
+ *
980
+ * @param {{
981
+ * homeDir?: string,
982
+ * cwd?: string,
983
+ * env?: NodeJS.ProcessEnv,
984
+ * explicitApiUrl?: string,
985
+ * revokeRemote?: boolean
986
+ * }} [options]
987
+ * @returns {Promise<{
988
+ * hadStoredSession: boolean,
989
+ * revokedRemote: boolean,
990
+ * clearedLocal: boolean,
991
+ * apiUrl?: string,
992
+ * filePath?: string
993
+ * }>}
994
+ */
995
+ export async function logoutSession({
996
+ homeDir,
997
+ cwd = process.cwd(),
998
+ env = process.env,
999
+ explicitApiUrl = "",
1000
+ revokeRemote = true,
1001
+ } = {}) {
1002
+ const stored = await readStoredSession({ homeDir });
1003
+ if (!stored) {
1004
+ return {
1005
+ hadStoredSession: false,
1006
+ revokedRemote: false,
1007
+ clearedLocal: false,
1008
+ apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
1009
+ };
1010
+ }
1011
+
1012
+ let revokedRemote = false;
1013
+ if (revokeRemote && stored.tokenId && stored.token) {
1014
+ try {
1015
+ await revokeApiToken({
1016
+ apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
1017
+ authToken: stored.token,
1018
+ tokenId: stored.tokenId,
1019
+ });
1020
+ revokedRemote = true;
1021
+ } catch {
1022
+ revokedRemote = false;
1023
+ }
1024
+ }
1025
+
1026
+ const cleared = await clearStoredSession({ homeDir });
1027
+ return {
1028
+ hadStoredSession: true,
1029
+ revokedRemote,
1030
+ clearedLocal: cleared.hadSession,
1031
+ filePath: cleared.filePath,
1032
+ };
1033
+ }
1034
+
1035
+ /**
1036
+ * Fetch runtime run event stream slices used by `sl watch` and reproducibility artifacts.
1037
+ *
1038
+ * @param {{
1039
+ * apiUrl: string,
1040
+ * authToken: string,
1041
+ * runId: string,
1042
+ * afterEventId?: string | null
1043
+ * }} [options]
1044
+ * @returns {Promise<any>}
1045
+ */
1046
+ export async function listRuntimeRunEvents({
1047
+ apiUrl,
1048
+ authToken,
1049
+ runId,
1050
+ afterEventId = null,
1051
+ } = {}) {
1052
+ const query = afterEventId
1053
+ ? `?after_event_id=${encodeURIComponent(String(afterEventId))}`
1054
+ : "";
1055
+ return requestJson(
1056
+ buildApiPath(apiUrl, `/api/v1/runtime/runs/${encodeURIComponent(String(runId || ""))}/events/list${query}`),
1057
+ {
1058
+ method: "GET",
1059
+ headers: toAuthHeader(authToken),
1060
+ }
1061
+ );
1062
+ }
1063
+
1064
+ /**
1065
+ * Fetch runtime run status snapshot from the Sentinelayer API.
1066
+ *
1067
+ * @param {{ apiUrl: string, authToken: string, runId: string }} [options]
1068
+ * @returns {Promise<any>}
1069
+ */
1070
+ /**
1071
+ * Fetch AIdenID credentials from the SentinelLayer API (lazy-provisioning).
1072
+ * The secret is returned in-memory only, never persisted to disk.
1073
+ */
1074
+ export async function fetchAidenIdCredentials({
1075
+ apiUrl = DEFAULT_API_URL,
1076
+ token = "",
1077
+ } = {}) {
1078
+ const response = await requestJson(
1079
+ buildApiPath(apiUrl, "/api/v1/aidenid/credentials"),
1080
+ {
1081
+ method: "GET",
1082
+ headers: toAuthHeader(token),
1083
+ }
1084
+ );
1085
+ return {
1086
+ orgId: String(response.orgId || response.org_id || "").trim(),
1087
+ projectId: String(response.projectId || response.project_id || "").trim(),
1088
+ apiKeyPrefix: String(response.apiKeyPrefix || response.api_key_prefix || "").trim(),
1089
+ apiKey: String(response.apiKey || response.api_key || "").trim(),
1090
+ provisioned: Boolean(response.provisioned),
1091
+ };
1092
+ }
1093
+
1094
+ export async function getRuntimeRunStatus({
1095
+ apiUrl,
1096
+ authToken,
1097
+ runId,
1098
+ } = {}) {
1099
+ return requestJson(
1100
+ buildApiPath(apiUrl, `/api/v1/runtime/runs/${encodeURIComponent(String(runId || ""))}/status`),
1101
+ {
1102
+ method: "GET",
1103
+ headers: toAuthHeader(authToken),
1104
+ }
1105
+ );
1106
+ }