sentinelayer-cli 0.4.5 → 0.6.2

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 (149) hide show
  1. package/README.md +996 -998
  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 +63 -63
  6. package/src/agents/jules/config/definition.js +160 -209
  7. package/src/agents/jules/config/system-prompt.js +182 -175
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -377
  10. package/src/agents/jules/loop.js +450 -367
  11. package/src/agents/jules/pulse.js +10 -327
  12. package/src/agents/jules/stream.js +186 -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 +309 -308
  18. package/src/agents/jules/tools/aidenid-email.js +189 -0
  19. package/src/agents/jules/tools/auth-audit.js +1691 -557
  20. package/src/agents/jules/tools/dispatch.js +335 -327
  21. package/src/agents/jules/tools/file-edit.js +2 -180
  22. package/src/agents/jules/tools/file-read.js +2 -100
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -168
  25. package/src/agents/jules/tools/grep.js +2 -228
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -161
  28. package/src/agents/jules/tools/runtime-audit.js +507 -503
  29. package/src/agents/jules/tools/shell.js +2 -383
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +61 -0
  32. package/src/agents/shared-tools/dispatch-core.js +315 -0
  33. package/src/agents/shared-tools/file-edit.js +180 -0
  34. package/src/agents/shared-tools/file-read.js +100 -0
  35. package/src/agents/shared-tools/glob.js +168 -0
  36. package/src/agents/shared-tools/grep.js +228 -0
  37. package/src/agents/shared-tools/index.js +46 -0
  38. package/src/agents/shared-tools/path-guards.js +161 -0
  39. package/src/agents/shared-tools/shell.js +383 -0
  40. package/src/ai/aidenid.js +1009 -972
  41. package/src/ai/client.js +553 -508
  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 -0
  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 +371 -126
  57. package/src/auth/http.js +611 -270
  58. package/src/auth/service.js +1106 -891
  59. package/src/auth/session-store.js +813 -359
  60. package/src/cli.js +252 -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 +1166 -1166
  67. package/src/commands/auth.js +419 -375
  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 -21
  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 -866
  87. package/src/commands/spec.js +716 -716
  88. package/src/commands/swarm.js +651 -651
  89. package/src/commands/telemetry.js +202 -202
  90. package/src/commands/watch.js +511 -510
  91. package/src/config/agent-dictionary.js +182 -182
  92. package/src/config/io.js +56 -56
  93. package/src/config/paths.js +18 -18
  94. package/src/config/schema.js +55 -55
  95. package/src/config/service.js +184 -184
  96. package/src/cost/budget.js +235 -235
  97. package/src/cost/history.js +188 -188
  98. package/src/cost/tracker.js +171 -171
  99. package/src/daemon/artifact-lineage.js +534 -534
  100. package/src/daemon/assignment-ledger.js +770 -770
  101. package/src/daemon/ast-parser-layer.js +258 -258
  102. package/src/daemon/budget-governor.js +633 -633
  103. package/src/daemon/callgraph-overlay.js +646 -646
  104. package/src/daemon/error-worker.js +626 -626
  105. package/src/daemon/fix-cycle.js +377 -0
  106. package/src/daemon/hybrid-mapper.js +929 -929
  107. package/src/daemon/jira-lifecycle.js +632 -632
  108. package/src/daemon/operator-control.js +657 -657
  109. package/src/daemon/pulse.js +327 -0
  110. package/src/daemon/reliability-lane.js +471 -471
  111. package/src/daemon/watchdog.js +971 -971
  112. package/src/guide/generator.js +316 -316
  113. package/src/ingest/engine.js +918 -918
  114. package/src/interactive/index.js +97 -95
  115. package/src/legacy-cli.js +2994 -2592
  116. package/src/mcp/registry.js +695 -695
  117. package/src/memory/blackboard.js +301 -301
  118. package/src/memory/retrieval.js +581 -581
  119. package/src/plugin/manifest.js +553 -553
  120. package/src/policy/packs.js +144 -144
  121. package/src/prompt/generator.js +118 -118
  122. package/src/review/ai-review.js +679 -669
  123. package/src/review/local-review.js +1305 -1295
  124. package/src/review/omargate-interactive.js +68 -0
  125. package/src/review/omargate-orchestrator.js +300 -0
  126. package/src/review/persona-prompts.js +296 -0
  127. package/src/review/replay.js +235 -235
  128. package/src/review/report.js +664 -664
  129. package/src/review/scan-modes.js +42 -0
  130. package/src/review/spec-binding.js +487 -487
  131. package/src/scaffold/generator.js +67 -67
  132. package/src/scaffold/templates.js +150 -150
  133. package/src/scan/generator.js +418 -418
  134. package/src/scan/gh-secrets.js +107 -107
  135. package/src/spec/generator.js +519 -519
  136. package/src/spec/regenerate.js +237 -237
  137. package/src/spec/templates.js +91 -91
  138. package/src/swarm/dashboard.js +247 -247
  139. package/src/swarm/factory.js +363 -363
  140. package/src/swarm/pentest.js +934 -934
  141. package/src/swarm/registry.js +419 -419
  142. package/src/swarm/report.js +158 -158
  143. package/src/swarm/runtime.js +576 -576
  144. package/src/swarm/scenario-dsl.js +272 -272
  145. package/src/telemetry/ledger.js +302 -302
  146. package/src/telemetry/session-tracker.js +234 -118
  147. package/src/telemetry/sync.js +203 -199
  148. package/src/ui/command-hints.js +13 -0
  149. package/src/ui/markdown.js +220 -220
@@ -1,891 +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 } from "./http.js";
9
- import {
10
- clearStoredSession,
11
- readStoredSession,
12
- readStoredSessionMetadata,
13
- writeStoredSession,
14
- } from "./session-store.js";
15
-
16
- const DEFAULT_API_URL = "https://api.sentinelayer.com";
17
- /** Default maximum wall-clock wait for browser-based CLI auth approval (ms). */
18
- export const DEFAULT_AUTH_TIMEOUT_MS = 10 * 60 * 1000;
19
- /** Default lifetime for issued API tokens used by CLI sessions (days). */
20
- export const DEFAULT_API_TOKEN_TTL_DAYS = 365;
21
- /** Default threshold at which stored tokens are rotated before expiry (days). */
22
- export const DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS = 7;
23
- const DEFAULT_IDE_NAME = "sl-cli";
24
-
25
- function normalizeApiUrl(rawValue) {
26
- const candidate = String(rawValue || "").trim() || DEFAULT_API_URL;
27
- let parsed;
28
- try {
29
- parsed = new URL(candidate);
30
- } catch {
31
- throw new Error(`Invalid API URL '${candidate}'.`);
32
- }
33
- parsed.pathname = "/";
34
- parsed.search = "";
35
- parsed.hash = "";
36
- return parsed.toString().replace(/\/$/, "");
37
- }
38
-
39
- function normalizePositiveNumber(rawValue, field, fallbackValue) {
40
- if (rawValue === undefined || rawValue === null || String(rawValue).trim() === "") {
41
- return fallbackValue;
42
- }
43
- const normalized = Number(rawValue);
44
- if (!Number.isFinite(normalized) || normalized <= 0) {
45
- throw new Error(`${field} must be a positive number.`);
46
- }
47
- return normalized;
48
- }
49
-
50
- function toAuthHeader(token) {
51
- return {
52
- Authorization: `Bearer ${String(token || "").trim()}`,
53
- };
54
- }
55
-
56
- function normalizeUser(user = {}) {
57
- return {
58
- id: String(user.id || "").trim(),
59
- githubUsername: String(user.githubUsername || user.github_username || "").trim(),
60
- email: String(user.email || "").trim(),
61
- avatarUrl: String(user.avatarUrl || user.avatar_url || "").trim(),
62
- isAdmin: Boolean(user.isAdmin || user.is_admin),
63
- };
64
- }
65
-
66
- function buildApiPath(apiUrl, pathSuffix) {
67
- return `${normalizeApiUrl(apiUrl)}${String(pathSuffix || "")}`;
68
- }
69
-
70
- function generateChallenge() {
71
- return crypto.randomBytes(48).toString("base64url");
72
- }
73
-
74
- function defaultTokenLabel() {
75
- const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..+/, "").replace("T", "-");
76
- return `sl-cli-session-${stamp}`;
77
- }
78
-
79
- function isNearExpiry(tokenExpiresAt, thresholdDays) {
80
- const normalized = String(tokenExpiresAt || "").trim();
81
- if (!normalized) {
82
- return false;
83
- }
84
- const expiryEpoch = Date.parse(normalized);
85
- if (!Number.isFinite(expiryEpoch)) {
86
- return false;
87
- }
88
- const thresholdMs = Number(thresholdDays || DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS) * 24 * 60 * 60 * 1000;
89
- return expiryEpoch - Date.now() <= thresholdMs;
90
- }
91
-
92
- /**
93
- * Resolve API URL precedence for auth operations: explicit -> env -> config -> default.
94
- *
95
- * @param {{
96
- * cwd?: string,
97
- * env?: NodeJS.ProcessEnv,
98
- * explicitApiUrl?: string,
99
- * homeDir?: string
100
- * }} [options]
101
- * @returns {Promise<string>}
102
- */
103
- export async function resolveApiUrl({
104
- cwd = process.cwd(),
105
- env = process.env,
106
- explicitApiUrl = "",
107
- homeDir,
108
- } = {}) {
109
- const overrideUrl = String(explicitApiUrl || "").trim();
110
- if (overrideUrl) {
111
- return normalizeApiUrl(overrideUrl);
112
- }
113
-
114
- const envUrl = String(env.SENTINELAYER_API_URL || "").trim();
115
- if (envUrl) {
116
- return normalizeApiUrl(envUrl);
117
- }
118
-
119
- const config = await loadConfig({ cwd, env, homeDir });
120
- const configuredApiUrl = String(config.resolved.apiUrl || "").trim();
121
- if (configuredApiUrl) {
122
- return normalizeApiUrl(configuredApiUrl);
123
- }
124
-
125
- return normalizeApiUrl(DEFAULT_API_URL);
126
- }
127
-
128
- async function startCliAuthSession({ apiUrl, challenge, ide, cliVersion }) {
129
- return requestJson(buildApiPath(apiUrl, "/api/v1/auth/cli/sessions/start"), {
130
- method: "POST",
131
- body: {
132
- challenge,
133
- ide: String(ide || DEFAULT_IDE_NAME),
134
- cli_version: String(cliVersion || "").trim() || null,
135
- },
136
- });
137
- }
138
-
139
- async function pollCliAuthSession({
140
- apiUrl,
141
- sessionId,
142
- challenge,
143
- timeoutMs,
144
- pollIntervalSeconds,
145
- }) {
146
- const timeout = normalizePositiveNumber(timeoutMs, "timeoutMs", DEFAULT_AUTH_TIMEOUT_MS);
147
- const pollIntervalMs = Math.max(250, Math.round(Number(pollIntervalSeconds || 2) * 1000));
148
- const deadline = Date.now() + timeout;
149
- const isTransientPollError = (error) =>
150
- error instanceof SentinelayerApiError &&
151
- (error.code === "NETWORK_ERROR" ||
152
- error.code === "TIMEOUT" ||
153
- error.status === 429 ||
154
- error.status >= 500);
155
-
156
- while (Date.now() < deadline) {
157
- let payload;
158
- try {
159
- payload = await requestJson(buildApiPath(apiUrl, "/api/v1/auth/cli/sessions/poll"), {
160
- method: "POST",
161
- body: {
162
- session_id: sessionId,
163
- challenge,
164
- },
165
- });
166
- } catch (error) {
167
- if (isTransientPollError(error)) {
168
- await sleep(pollIntervalMs);
169
- continue;
170
- }
171
- throw error;
172
- }
173
-
174
- const status = String(payload.status || "pending").trim().toLowerCase();
175
- if (status === "approved" && payload.auth_token) {
176
- return payload;
177
- }
178
- if (status === "rejected" || status === "denied" || status === "cancelled") {
179
- throw new SentinelayerApiError("CLI authentication was not approved.", {
180
- status: 401,
181
- code: "CLI_AUTH_REJECTED",
182
- });
183
- }
184
- if (status === "expired") {
185
- throw new SentinelayerApiError("CLI authentication session expired.", {
186
- status: 401,
187
- code: "CLI_AUTH_EXPIRED",
188
- });
189
- }
190
-
191
- await sleep(pollIntervalMs);
192
- }
193
-
194
- throw new SentinelayerApiError("CLI authentication timed out. Restart and try again.", {
195
- status: 408,
196
- code: "CLI_AUTH_TIMEOUT",
197
- });
198
- }
199
-
200
- async function fetchCurrentUser({ apiUrl, token }) {
201
- return requestJson(buildApiPath(apiUrl, "/api/v1/auth/me"), {
202
- method: "GET",
203
- headers: toAuthHeader(token),
204
- });
205
- }
206
-
207
- async function issueApiToken({
208
- apiUrl,
209
- authToken,
210
- tokenLabel,
211
- tokenTtlDays,
212
- }) {
213
- const expiresInDays = Math.round(
214
- normalizePositiveNumber(tokenTtlDays, "apiTokenTtlDays", DEFAULT_API_TOKEN_TTL_DAYS)
215
- );
216
- return requestJson(buildApiPath(apiUrl, "/api/v1/auth/api-tokens"), {
217
- method: "POST",
218
- headers: toAuthHeader(authToken),
219
- body: {
220
- label: String(tokenLabel || "").trim() || defaultTokenLabel(),
221
- scope: "github_app_bridge",
222
- llm_credential_mode: "managed",
223
- expires_in_days: expiresInDays,
224
- },
225
- });
226
- }
227
-
228
- async function revokeApiToken({ apiUrl, authToken, tokenId }) {
229
- const normalizedTokenId = String(tokenId || "").trim();
230
- if (!normalizedTokenId) {
231
- return false;
232
- }
233
- await requestJson(buildApiPath(apiUrl, `/api/v1/auth/api-tokens/${encodeURIComponent(normalizedTokenId)}`), {
234
- method: "DELETE",
235
- headers: toAuthHeader(authToken),
236
- });
237
- return true;
238
- }
239
-
240
- async function rotateStoredApiTokenIfNeeded({
241
- session,
242
- thresholdDays,
243
- tokenLabel,
244
- tokenTtlDays,
245
- homeDir,
246
- }) {
247
- if (!session || !session.token || !session.tokenExpiresAt) {
248
- return { session, rotated: false };
249
- }
250
- if (!isNearExpiry(session.tokenExpiresAt, thresholdDays)) {
251
- return { session, rotated: false };
252
- }
253
-
254
- const issued = await issueApiToken({
255
- apiUrl: session.apiUrl,
256
- authToken: session.token,
257
- tokenLabel,
258
- tokenTtlDays,
259
- });
260
-
261
- const nextSession = await writeStoredSession(
262
- {
263
- apiUrl: session.apiUrl,
264
- token: String(issued.token || ""),
265
- tokenId: issued.id || null,
266
- tokenPrefix: issued.token_prefix || null,
267
- tokenExpiresAt: issued.expires_at || null,
268
- user: session.user,
269
- },
270
- { homeDir }
271
- );
272
-
273
- if (session.tokenId) {
274
- try {
275
- await revokeApiToken({
276
- apiUrl: session.apiUrl,
277
- authToken: nextSession.token,
278
- tokenId: session.tokenId,
279
- });
280
- } catch {
281
- // Ignore revoke failures; new token is already active.
282
- }
283
- }
284
-
285
- return {
286
- session: nextSession,
287
- rotated: true,
288
- };
289
- }
290
-
291
- /**
292
- * Perform browser-based CLI login flow and persist an API token session locally.
293
- *
294
- * @param {{
295
- * cwd?: string,
296
- * env?: NodeJS.ProcessEnv,
297
- * explicitApiUrl?: string,
298
- * skipBrowserOpen?: boolean,
299
- * timeoutMs?: number,
300
- * tokenLabel?: string,
301
- * tokenTtlDays?: number,
302
- * ide?: string,
303
- * cliVersion?: string,
304
- * homeDir?: string
305
- * }} [options]
306
- * @returns {Promise<{
307
- * apiUrl: string,
308
- * authorizeUrl: string,
309
- * browserOpened: boolean,
310
- * user: {
311
- * id: string,
312
- * githubUsername: string,
313
- * email: string,
314
- * avatarUrl: string,
315
- * isAdmin: boolean
316
- * },
317
- * tokenId: string | null,
318
- * tokenPrefix: string | null,
319
- * tokenExpiresAt: string | null,
320
- * storage: string,
321
- * filePath: string
322
- * }>}
323
- */
324
- export async function loginAndPersistSession({
325
- cwd = process.cwd(),
326
- env = process.env,
327
- explicitApiUrl = "",
328
- skipBrowserOpen = false,
329
- timeoutMs = DEFAULT_AUTH_TIMEOUT_MS,
330
- tokenLabel = "",
331
- tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
332
- ide = DEFAULT_IDE_NAME,
333
- cliVersion = "",
334
- homeDir,
335
- } = {}) {
336
- const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
337
- const challenge = generateChallenge();
338
- const session = await startCliAuthSession({
339
- apiUrl,
340
- challenge,
341
- ide,
342
- cliVersion,
343
- });
344
-
345
- const authorizeUrl = String(session.authorize_url || "").trim();
346
- let browserOpened = false;
347
- if (!skipBrowserOpen && authorizeUrl) {
348
- try {
349
- await open(authorizeUrl);
350
- browserOpened = true;
351
- } catch {
352
- browserOpened = false;
353
- }
354
- }
355
-
356
- const approval = await pollCliAuthSession({
357
- apiUrl,
358
- sessionId: String(session.session_id || "").trim(),
359
- challenge,
360
- timeoutMs,
361
- pollIntervalSeconds: Number(session.poll_interval_seconds || 2),
362
- });
363
-
364
- const approvalToken = String(approval.auth_token || "").trim();
365
- if (!approvalToken) {
366
- throw new SentinelayerApiError("Authentication completed but no auth token was returned.", {
367
- status: 503,
368
- code: "CLI_AUTH_MISSING_TOKEN",
369
- });
370
- }
371
-
372
- const user = normalizeUser(approval.user || (await fetchCurrentUser({ apiUrl, token: approvalToken })));
373
- const issuedApiToken = await issueApiToken({
374
- apiUrl,
375
- authToken: approvalToken,
376
- tokenLabel,
377
- tokenTtlDays,
378
- });
379
-
380
- // Extract AIdenID metadata from approval (no secret stored locally)
381
- const rawAidenId = approval.aidenidCredentials || approval.aidenid_credentials || null;
382
- const aidenid =
383
- rawAidenId && rawAidenId.provisioned
384
- ? {
385
- orgId: String(rawAidenId.orgId || rawAidenId.org_id || "").trim() || null,
386
- projectId: String(rawAidenId.projectId || rawAidenId.project_id || "").trim() || null,
387
- apiKeyPrefix: String(rawAidenId.apiKeyPrefix || rawAidenId.api_key_prefix || "").trim() || null,
388
- provisionedAt: new Date().toISOString(),
389
- }
390
- : null;
391
-
392
- const stored = await writeStoredSession(
393
- {
394
- apiUrl,
395
- token: String(issuedApiToken.token || ""),
396
- tokenId: issuedApiToken.id || null,
397
- tokenPrefix: issuedApiToken.token_prefix || null,
398
- tokenExpiresAt: issuedApiToken.expires_at || null,
399
- user,
400
- aidenid,
401
- },
402
- { homeDir }
403
- );
404
-
405
- return {
406
- apiUrl,
407
- authorizeUrl,
408
- browserOpened,
409
- user,
410
- tokenId: stored.tokenId,
411
- tokenPrefix: stored.tokenPrefix,
412
- tokenExpiresAt: stored.tokenExpiresAt,
413
- storage: stored.storage,
414
- filePath: stored.filePath,
415
- aidenid: stored.aidenid || null,
416
- };
417
- }
418
-
419
- /**
420
- * Resolve active auth credentials used by CLI commands, optionally rotating near-expiry session tokens.
421
- *
422
- * @param {{
423
- * cwd?: string,
424
- * env?: NodeJS.ProcessEnv,
425
- * explicitApiUrl?: string,
426
- * autoRotate?: boolean,
427
- * rotateThresholdDays?: number,
428
- * tokenLabel?: string,
429
- * tokenTtlDays?: number,
430
- * homeDir?: string
431
- * }} [options]
432
- * @returns {Promise<null | {
433
- * apiUrl: string,
434
- * token: string,
435
- * source: "env" | "config" | "session",
436
- * user: {
437
- * id: string,
438
- * githubUsername: string,
439
- * email: string,
440
- * avatarUrl: string,
441
- * isAdmin: boolean
442
- * } | null,
443
- * storage: string,
444
- * tokenId: string | null,
445
- * tokenPrefix: string | null,
446
- * tokenExpiresAt: string | null,
447
- * rotated: boolean,
448
- * filePath: string | null
449
- * }>}
450
- */
451
- export async function resolveActiveAuthSession({
452
- cwd = process.cwd(),
453
- env = process.env,
454
- explicitApiUrl = "",
455
- autoRotate = true,
456
- rotateThresholdDays = DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS,
457
- tokenLabel = "",
458
- tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
459
- homeDir,
460
- } = {}) {
461
- const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
462
-
463
- const envToken = String(env.SENTINELAYER_TOKEN || "").trim();
464
- if (envToken) {
465
- return {
466
- apiUrl,
467
- token: envToken,
468
- source: "env",
469
- user: null,
470
- aidenid: null,
471
- storage: "env",
472
- tokenId: null,
473
- tokenPrefix: null,
474
- tokenExpiresAt: null,
475
- rotated: false,
476
- filePath: null,
477
- };
478
- }
479
-
480
- const config = await loadConfig({ cwd, env, homeDir });
481
- const configuredToken = String(config.resolved.sentinelayerToken || "").trim();
482
- if (configuredToken) {
483
- return {
484
- apiUrl,
485
- token: configuredToken,
486
- source: "config",
487
- user: null,
488
- aidenid: null,
489
- storage: "config",
490
- tokenId: null,
491
- tokenPrefix: null,
492
- tokenExpiresAt: null,
493
- rotated: false,
494
- filePath: null,
495
- };
496
- }
497
-
498
- const stored = await readStoredSession({ homeDir });
499
- if (!stored) {
500
- return null;
501
- }
502
-
503
- let active = stored;
504
- let rotated = false;
505
- if (autoRotate) {
506
- try {
507
- const rotateResult = await rotateStoredApiTokenIfNeeded({
508
- session: stored,
509
- thresholdDays: rotateThresholdDays,
510
- tokenLabel,
511
- tokenTtlDays,
512
- homeDir,
513
- });
514
- active = rotateResult.session;
515
- rotated = rotateResult.rotated;
516
- } catch {
517
- // Keep existing token if rotation fails.
518
- active = stored;
519
- rotated = false;
520
- }
521
- }
522
-
523
- return {
524
- apiUrl,
525
- token: active.token,
526
- source: "session",
527
- user: normalizeUser(active.user || {}),
528
- aidenid: active.aidenid || null,
529
- storage: active.storage,
530
- tokenId: active.tokenId || null,
531
- tokenPrefix: active.tokenPrefix || null,
532
- tokenExpiresAt: active.tokenExpiresAt || null,
533
- rotated,
534
- filePath: active.filePath,
535
- };
536
- }
537
-
538
- /**
539
- * Return current authentication state, with optional remote `/auth/me` verification.
540
- *
541
- * @param {{
542
- * cwd?: string,
543
- * env?: NodeJS.ProcessEnv,
544
- * explicitApiUrl?: string,
545
- * checkRemote?: boolean,
546
- * autoRotate?: boolean,
547
- * rotateThresholdDays?: number,
548
- * tokenLabel?: string,
549
- * tokenTtlDays?: number,
550
- * homeDir?: string
551
- * }} [options]
552
- * @returns {Promise<{
553
- * authenticated: boolean,
554
- * apiUrl: string,
555
- * source: string | null,
556
- * storage: string | null,
557
- * user: any,
558
- * remoteUser: any,
559
- * remoteError: null | { code: string, message: string, status: number, requestId: string | null },
560
- * rotated: boolean,
561
- * tokenExpiresAt: string | null,
562
- * tokenPrefix: string | null,
563
- * tokenId: string | null,
564
- * filePath: string | null
565
- * }>}
566
- */
567
- export async function getAuthStatus({
568
- cwd = process.cwd(),
569
- env = process.env,
570
- explicitApiUrl = "",
571
- checkRemote = true,
572
- autoRotate = true,
573
- rotateThresholdDays = DEFAULT_TOKEN_ROTATE_THRESHOLD_DAYS,
574
- tokenLabel = "",
575
- tokenTtlDays = DEFAULT_API_TOKEN_TTL_DAYS,
576
- homeDir,
577
- } = {}) {
578
- const session = await resolveActiveAuthSession({
579
- cwd,
580
- env,
581
- explicitApiUrl,
582
- autoRotate,
583
- rotateThresholdDays,
584
- tokenLabel,
585
- tokenTtlDays,
586
- homeDir,
587
- });
588
-
589
- if (!session) {
590
- return {
591
- authenticated: false,
592
- apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
593
- source: null,
594
- storage: null,
595
- user: null,
596
- aidenid: null,
597
- remoteUser: null,
598
- remoteError: null,
599
- rotated: false,
600
- tokenExpiresAt: null,
601
- tokenPrefix: null,
602
- tokenId: null,
603
- filePath: null,
604
- };
605
- }
606
-
607
- let remoteUser = null;
608
- let remoteError = null;
609
- if (checkRemote) {
610
- try {
611
- remoteUser = normalizeUser(await fetchCurrentUser({ apiUrl: session.apiUrl, token: session.token }));
612
- } catch (error) {
613
- remoteError =
614
- error instanceof SentinelayerApiError
615
- ? {
616
- code: error.code,
617
- message: error.message,
618
- status: error.status,
619
- requestId: error.requestId,
620
- }
621
- : {
622
- code: "UNKNOWN",
623
- message: error instanceof Error ? error.message : String(error || "Unknown error"),
624
- status: 500,
625
- requestId: null,
626
- };
627
- }
628
- }
629
-
630
- return {
631
- authenticated: !remoteError,
632
- apiUrl: session.apiUrl,
633
- source: session.source,
634
- storage: session.storage,
635
- user: session.user,
636
- aidenid: session.aidenid || null,
637
- remoteUser,
638
- remoteError,
639
- rotated: session.rotated,
640
- tokenExpiresAt: session.tokenExpiresAt,
641
- tokenPrefix: session.tokenPrefix,
642
- tokenId: session.tokenId,
643
- filePath: session.filePath,
644
- };
645
- }
646
-
647
- /**
648
- * List persisted local session metadata for CLI operators/HITL dashboards.
649
- *
650
- * @param {{ cwd?: string, env?: NodeJS.ProcessEnv, explicitApiUrl?: string, homeDir?: string }} [options]
651
- * @returns {Promise<{ apiUrl: string, sessions: Array<any> }>}
652
- */
653
- export async function listStoredAuthSessions({
654
- cwd = process.cwd(),
655
- env = process.env,
656
- explicitApiUrl = "",
657
- homeDir,
658
- } = {}) {
659
- const apiUrl = await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir });
660
- const stored = await readStoredSessionMetadata({ homeDir });
661
- if (!stored) {
662
- return {
663
- apiUrl,
664
- sessions: [],
665
- };
666
- }
667
-
668
- return {
669
- apiUrl,
670
- sessions: [
671
- {
672
- source: "session",
673
- storage: stored.storage || null,
674
- tokenId: stored.tokenId || null,
675
- tokenPrefix: stored.tokenPrefix || null,
676
- tokenExpiresAt: stored.tokenExpiresAt || null,
677
- createdAt: stored.createdAt || null,
678
- updatedAt: stored.updatedAt || null,
679
- user: normalizeUser(stored.user || {}),
680
- filePath: stored.filePath || null,
681
- },
682
- ],
683
- };
684
- }
685
-
686
- /**
687
- * Revoke an API token remotely and clear matching local stored session metadata when applicable.
688
- *
689
- * @param {{
690
- * cwd?: string,
691
- * env?: NodeJS.ProcessEnv,
692
- * explicitApiUrl?: string,
693
- * tokenId?: string,
694
- * homeDir?: string
695
- * }} [options]
696
- * @returns {Promise<{
697
- * apiUrl: string,
698
- * source: string,
699
- * tokenId: string,
700
- * revokedRemote: boolean,
701
- * matchedStoredSession: boolean,
702
- * clearedLocal: boolean,
703
- * filePath: string | null
704
- * }>}
705
- */
706
- export async function revokeAuthToken({
707
- cwd = process.cwd(),
708
- env = process.env,
709
- explicitApiUrl = "",
710
- tokenId = "",
711
- homeDir,
712
- } = {}) {
713
- const active = await resolveActiveAuthSession({
714
- cwd,
715
- env,
716
- explicitApiUrl,
717
- autoRotate: false,
718
- homeDir,
719
- });
720
- if (!active || !active.token) {
721
- throw new SentinelayerApiError("No active auth token found. Run `sl auth login` first.", {
722
- status: 401,
723
- code: "AUTH_REQUIRED",
724
- });
725
- }
726
-
727
- const targetTokenId = String(tokenId || "").trim() || String(active.tokenId || "").trim();
728
- if (!targetTokenId) {
729
- throw new Error(
730
- "tokenId is required. Provide --token-id or use a stored session that includes token metadata."
731
- );
732
- }
733
-
734
- await revokeApiToken({
735
- apiUrl: active.apiUrl,
736
- authToken: active.token,
737
- tokenId: targetTokenId,
738
- });
739
-
740
- let matchedStoredSession = false;
741
- let clearedLocal = false;
742
- let filePath = null;
743
- const stored = await readStoredSession({ homeDir });
744
- if (stored && String(stored.tokenId || "").trim() === targetTokenId) {
745
- matchedStoredSession = true;
746
- const cleared = await clearStoredSession({ homeDir });
747
- clearedLocal = Boolean(cleared.hadSession);
748
- filePath = cleared.filePath || null;
749
- }
750
-
751
- return {
752
- apiUrl: active.apiUrl,
753
- source: active.source,
754
- tokenId: targetTokenId,
755
- revokedRemote: true,
756
- matchedStoredSession,
757
- clearedLocal,
758
- filePath,
759
- };
760
- }
761
-
762
- /**
763
- * Clear local CLI session state and optionally revoke the remote token first.
764
- *
765
- * @param {{
766
- * homeDir?: string,
767
- * cwd?: string,
768
- * env?: NodeJS.ProcessEnv,
769
- * explicitApiUrl?: string,
770
- * revokeRemote?: boolean
771
- * }} [options]
772
- * @returns {Promise<{
773
- * hadStoredSession: boolean,
774
- * revokedRemote: boolean,
775
- * clearedLocal: boolean,
776
- * apiUrl?: string,
777
- * filePath?: string
778
- * }>}
779
- */
780
- export async function logoutSession({
781
- homeDir,
782
- cwd = process.cwd(),
783
- env = process.env,
784
- explicitApiUrl = "",
785
- revokeRemote = true,
786
- } = {}) {
787
- const stored = await readStoredSession({ homeDir });
788
- if (!stored) {
789
- return {
790
- hadStoredSession: false,
791
- revokedRemote: false,
792
- clearedLocal: false,
793
- apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
794
- };
795
- }
796
-
797
- let revokedRemote = false;
798
- if (revokeRemote && stored.tokenId && stored.token) {
799
- try {
800
- await revokeApiToken({
801
- apiUrl: await resolveApiUrl({ cwd, env, explicitApiUrl, homeDir }),
802
- authToken: stored.token,
803
- tokenId: stored.tokenId,
804
- });
805
- revokedRemote = true;
806
- } catch {
807
- revokedRemote = false;
808
- }
809
- }
810
-
811
- const cleared = await clearStoredSession({ homeDir });
812
- return {
813
- hadStoredSession: true,
814
- revokedRemote,
815
- clearedLocal: cleared.hadSession,
816
- filePath: cleared.filePath,
817
- };
818
- }
819
-
820
- /**
821
- * Fetch runtime run event stream slices used by `sl watch` and reproducibility artifacts.
822
- *
823
- * @param {{
824
- * apiUrl: string,
825
- * authToken: string,
826
- * runId: string,
827
- * afterEventId?: string | null
828
- * }} [options]
829
- * @returns {Promise<any>}
830
- */
831
- export async function listRuntimeRunEvents({
832
- apiUrl,
833
- authToken,
834
- runId,
835
- afterEventId = null,
836
- } = {}) {
837
- const query = afterEventId
838
- ? `?after_event_id=${encodeURIComponent(String(afterEventId))}`
839
- : "";
840
- return requestJson(
841
- buildApiPath(apiUrl, `/api/v1/runtime/runs/${encodeURIComponent(String(runId || ""))}/events/list${query}`),
842
- {
843
- method: "GET",
844
- headers: toAuthHeader(authToken),
845
- }
846
- );
847
- }
848
-
849
- /**
850
- * Fetch runtime run status snapshot from the Sentinelayer API.
851
- *
852
- * @param {{ apiUrl: string, authToken: string, runId: string }} [options]
853
- * @returns {Promise<any>}
854
- */
855
- /**
856
- * Fetch AIdenID credentials from the SentinelLayer API (lazy-provisioning).
857
- * The secret is returned in-memory only, never persisted to disk.
858
- */
859
- export async function fetchAidenIdCredentials({
860
- apiUrl = DEFAULT_API_URL,
861
- token = "",
862
- } = {}) {
863
- const response = await requestJson(
864
- buildApiPath(apiUrl, "/api/v1/aidenid/credentials"),
865
- {
866
- method: "GET",
867
- headers: toAuthHeader(token),
868
- }
869
- );
870
- return {
871
- orgId: String(response.orgId || response.org_id || "").trim(),
872
- projectId: String(response.projectId || response.project_id || "").trim(),
873
- apiKeyPrefix: String(response.apiKeyPrefix || response.api_key_prefix || "").trim(),
874
- apiKey: String(response.apiKey || response.api_key || "").trim(),
875
- provisioned: Boolean(response.provisioned),
876
- };
877
- }
878
-
879
- export async function getRuntimeRunStatus({
880
- apiUrl,
881
- authToken,
882
- runId,
883
- } = {}) {
884
- return requestJson(
885
- buildApiPath(apiUrl, `/api/v1/runtime/runs/${encodeURIComponent(String(runId || ""))}/status`),
886
- {
887
- method: "GET",
888
- headers: toAuthHeader(authToken),
889
- }
890
- );
891
- }
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
+ }