sentinelayer-cli 0.6.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/README.md +996 -996
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +64 -63
  6. package/src/agents/jules/config/definition.js +160 -160
  7. package/src/agents/jules/config/system-prompt.js +182 -182
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -17
  10. package/src/agents/jules/loop.js +457 -450
  11. package/src/agents/jules/pulse.js +10 -10
  12. package/src/agents/jules/stream.js +187 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +311 -309
  18. package/src/agents/jules/tools/aidenid-email.js +189 -189
  19. package/src/agents/jules/tools/auth-audit.js +1699 -1691
  20. package/src/agents/jules/tools/dispatch.js +340 -335
  21. package/src/agents/jules/tools/file-edit.js +2 -2
  22. package/src/agents/jules/tools/file-read.js +2 -2
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -2
  25. package/src/agents/jules/tools/grep.js +2 -2
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -2
  28. package/src/agents/jules/tools/runtime-audit.js +507 -507
  29. package/src/agents/jules/tools/shell.js +2 -2
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +64 -61
  32. package/src/agents/shared-tools/dispatch-core.js +320 -315
  33. package/src/agents/shared-tools/file-edit.js +180 -180
  34. package/src/agents/shared-tools/file-read.js +100 -100
  35. package/src/agents/shared-tools/glob.js +168 -168
  36. package/src/agents/shared-tools/grep.js +228 -228
  37. package/src/agents/shared-tools/index.js +46 -46
  38. package/src/agents/shared-tools/path-guards.js +161 -161
  39. package/src/agents/shared-tools/shell.js +383 -383
  40. package/src/ai/aidenid.js +1021 -1009
  41. package/src/ai/client.js +553 -553
  42. package/src/ai/domain-target-store.js +268 -268
  43. package/src/ai/identity-store.js +270 -270
  44. package/src/ai/proxy.js +137 -137
  45. package/src/ai/site-store.js +145 -145
  46. package/src/audit/agents/architecture.js +180 -180
  47. package/src/audit/agents/compliance.js +179 -179
  48. package/src/audit/agents/documentation.js +165 -165
  49. package/src/audit/agents/performance.js +145 -145
  50. package/src/audit/agents/security.js +215 -215
  51. package/src/audit/agents/testing.js +172 -172
  52. package/src/audit/orchestrator.js +557 -557
  53. package/src/audit/package.js +204 -204
  54. package/src/audit/registry.js +284 -284
  55. package/src/audit/replay.js +103 -103
  56. package/src/auth/gate.js +400 -371
  57. package/src/auth/http.js +681 -611
  58. package/src/auth/service.js +1106 -1106
  59. package/src/auth/session-store.js +813 -813
  60. package/src/cli.js +257 -252
  61. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  62. package/src/commands/ai/provision-governance.js +1272 -1272
  63. package/src/commands/ai/shared.js +147 -147
  64. package/src/commands/ai.js +11 -11
  65. package/src/commands/apply.js +12 -12
  66. package/src/commands/audit.js +1171 -1166
  67. package/src/commands/auth.js +419 -419
  68. package/src/commands/chat.js +191 -191
  69. package/src/commands/config.js +184 -184
  70. package/src/commands/cost.js +311 -311
  71. package/src/commands/daemon/core.js +850 -850
  72. package/src/commands/daemon/extended.js +1048 -1048
  73. package/src/commands/daemon/shared.js +213 -213
  74. package/src/commands/daemon.js +11 -11
  75. package/src/commands/guide.js +174 -174
  76. package/src/commands/ingest.js +58 -58
  77. package/src/commands/init.js +55 -55
  78. package/src/commands/legacy-args.js +10 -10
  79. package/src/commands/mcp.js +461 -461
  80. package/src/commands/omargate.js +29 -29
  81. package/src/commands/persona.js +20 -20
  82. package/src/commands/plugin.js +260 -260
  83. package/src/commands/policy.js +132 -132
  84. package/src/commands/prompt.js +238 -238
  85. package/src/commands/review.js +704 -704
  86. package/src/commands/scan.js +872 -872
  87. package/src/commands/session.js +590 -0
  88. package/src/commands/spec.js +778 -716
  89. package/src/commands/swarm.js +651 -651
  90. package/src/commands/telemetry.js +202 -202
  91. package/src/commands/watch.js +511 -511
  92. package/src/config/agent-dictionary.js +182 -182
  93. package/src/config/io.js +56 -56
  94. package/src/config/paths.js +18 -18
  95. package/src/config/schema.js +55 -55
  96. package/src/config/service.js +184 -184
  97. package/src/cost/budget.js +235 -235
  98. package/src/cost/history.js +188 -188
  99. package/src/cost/tracker.js +171 -171
  100. package/src/daemon/artifact-lineage.js +534 -534
  101. package/src/daemon/assignment-ledger.js +966 -770
  102. package/src/daemon/ast-parser-layer.js +258 -258
  103. package/src/daemon/budget-governor.js +633 -633
  104. package/src/daemon/callgraph-overlay.js +646 -646
  105. package/src/daemon/error-worker.js +1209 -626
  106. package/src/daemon/fix-cycle.js +384 -377
  107. package/src/daemon/hybrid-mapper.js +929 -929
  108. package/src/daemon/ingest-refresh.js +10 -9
  109. package/src/daemon/jira-lifecycle.js +767 -632
  110. package/src/daemon/operator-control.js +657 -657
  111. package/src/daemon/pulse.js +327 -327
  112. package/src/daemon/reliability-lane.js +471 -471
  113. package/src/daemon/scope-engine.js +1068 -0
  114. package/src/daemon/watchdog.js +971 -971
  115. package/src/events/schema.js +190 -0
  116. package/src/guide/generator.js +316 -316
  117. package/src/ingest/engine.js +918 -918
  118. package/src/interactive/index.js +97 -97
  119. package/src/legacy-cli.js +3161 -2994
  120. package/src/mcp/registry.js +695 -695
  121. package/src/memory/blackboard.js +301 -301
  122. package/src/memory/retrieval.js +581 -581
  123. package/src/plugin/manifest.js +553 -553
  124. package/src/policy/packs.js +144 -144
  125. package/src/prompt/generator.js +136 -118
  126. package/src/review/ai-review.js +679 -679
  127. package/src/review/local-review.js +1351 -1305
  128. package/src/review/omargate-interactive.js +68 -68
  129. package/src/review/omargate-orchestrator.js +404 -300
  130. package/src/review/persona-prompts.js +296 -296
  131. package/src/review/replay.js +235 -235
  132. package/src/review/report.js +664 -664
  133. package/src/review/scan-modes.js +48 -42
  134. package/src/review/spec-binding.js +487 -487
  135. package/src/scaffold/generator.js +67 -67
  136. package/src/scaffold/templates.js +150 -150
  137. package/src/scan/generator.js +418 -418
  138. package/src/scan/gh-secrets.js +107 -107
  139. package/src/session/agent-registry.js +352 -0
  140. package/src/session/daemon.js +801 -0
  141. package/src/session/paths.js +33 -0
  142. package/src/session/runtime-bridge.js +739 -0
  143. package/src/session/store.js +388 -0
  144. package/src/session/stream.js +325 -0
  145. package/src/spec/generator.js +619 -519
  146. package/src/spec/regenerate.js +237 -237
  147. package/src/spec/templates.js +91 -91
  148. package/src/swarm/dashboard.js +247 -247
  149. package/src/swarm/factory.js +363 -363
  150. package/src/swarm/pentest.js +934 -934
  151. package/src/swarm/registry.js +419 -419
  152. package/src/swarm/report.js +158 -158
  153. package/src/swarm/runtime.js +576 -576
  154. package/src/swarm/scenario-dsl.js +272 -272
  155. package/src/telemetry/ledger.js +302 -302
  156. package/src/telemetry/session-tracker.js +234 -234
  157. package/src/telemetry/sync.js +203 -203
  158. package/src/ui/command-hints.js +13 -13
  159. package/src/ui/markdown.js +220 -220
package/src/ai/aidenid.js CHANGED
@@ -1,1009 +1,1021 @@
1
- import process from "node:process";
2
- import { authLoginHint } from "../ui/command-hints.js";
3
-
4
- export const DEFAULT_AIDENID_API_URL = "https://api.aidenid.com";
5
-
6
- function normalizeApiUrl(rawValue) {
7
- const candidate = String(rawValue || "").trim() || DEFAULT_AIDENID_API_URL;
8
- let parsed;
9
- try {
10
- parsed = new URL(candidate);
11
- } catch {
12
- throw new Error(`Invalid AIdenID API URL '${candidate}'.`);
13
- }
14
- parsed.pathname = "/";
15
- parsed.search = "";
16
- parsed.hash = "";
17
- return parsed.toString().replace(/\/$/, "");
18
- }
19
-
20
- function normalizeCsvList(rawValue) {
21
- const input = String(rawValue || "").trim();
22
- if (!input) {
23
- return [];
24
- }
25
- const unique = new Set();
26
- for (const token of input.split(",")) {
27
- const normalized = token.trim();
28
- if (normalized) {
29
- unique.add(normalized);
30
- }
31
- }
32
- return [...unique];
33
- }
34
-
35
- function normalizeTtlHours(rawValue, fallbackValue = 24) {
36
- if (rawValue === undefined || rawValue === null || String(rawValue).trim() === "") {
37
- return fallbackValue;
38
- }
39
- const normalized = Number(rawValue);
40
- if (!Number.isFinite(normalized) || normalized <= 0 || normalized > 24 * 30) {
41
- throw new Error("ttlHours must be between 1 and 720.");
42
- }
43
- return Math.round(normalized);
44
- }
45
-
46
- function normalizePositiveInteger(rawValue, field, { min = 1, max = Number.MAX_SAFE_INTEGER } = {}) {
47
- const normalized = Number(rawValue);
48
- if (!Number.isFinite(normalized) || normalized < min || normalized > max) {
49
- throw new Error(`${field} must be between ${min} and ${max}.`);
50
- }
51
- return Math.round(normalized);
52
- }
53
-
54
- function normalizeIdentityId(rawValue) {
55
- const normalized = String(rawValue || "").trim();
56
- if (!normalized) {
57
- throw new Error("identityId is required.");
58
- }
59
- return normalized;
60
- }
61
-
62
- function normalizeAliasTemplate(rawValue) {
63
- const normalized = String(rawValue || "").trim();
64
- return normalized || null;
65
- }
66
-
67
- function normalizeDomainPoolId(rawValue) {
68
- const normalized = String(rawValue || "").trim();
69
- return normalized || null;
70
- }
71
-
72
- function normalizeReceiveMode(rawValue) {
73
- const normalized = String(rawValue || "").trim();
74
- return normalized || "EDGE_ACCEPT";
75
- }
76
-
77
- function normalizeExtractionTypes(rawValue) {
78
- if (Array.isArray(rawValue)) {
79
- const unique = new Set();
80
- for (const item of rawValue) {
81
- const normalized = String(item || "").trim();
82
- if (normalized) {
83
- unique.add(normalized);
84
- }
85
- }
86
- return unique.size > 0 ? [...unique] : ["otp", "link"];
87
- }
88
-
89
- const parsed = normalizeCsvList(rawValue);
90
- return parsed.length > 0 ? parsed : ["otp", "link"];
91
- }
92
-
93
- function normalizeTags(rawValue) {
94
- if (Array.isArray(rawValue)) {
95
- const unique = new Set();
96
- for (const item of rawValue) {
97
- const normalized = String(item || "").trim();
98
- if (normalized) {
99
- unique.add(normalized);
100
- }
101
- }
102
- return [...unique];
103
- }
104
- return normalizeCsvList(rawValue);
105
- }
106
-
107
- function normalizeEventBudget(rawValue) {
108
- if (rawValue === undefined || rawValue === null || String(rawValue).trim() === "") {
109
- return null;
110
- }
111
- return normalizePositiveInteger(rawValue, "eventBudget", { min: 1, max: 1000000 });
112
- }
113
-
114
- export function buildProvisionEmailPayload({
115
- aliasTemplate = "",
116
- ttlHours = 24,
117
- tags = [],
118
- domainPoolId = "",
119
- receiveMode = "EDGE_ACCEPT",
120
- allowWebhooks = true,
121
- extractionTypes = ["otp", "link"],
122
- } = {}) {
123
- return {
124
- aliasTemplate: normalizeAliasTemplate(aliasTemplate),
125
- ttlHours: normalizeTtlHours(ttlHours, 24),
126
- tags: normalizeTags(tags),
127
- domainPoolId: normalizeDomainPoolId(domainPoolId),
128
- policy: {
129
- receiveMode: normalizeReceiveMode(receiveMode),
130
- allowWebhooks: Boolean(allowWebhooks),
131
- extractionTypes: normalizeExtractionTypes(extractionTypes),
132
- },
133
- };
134
- }
135
-
136
- export function buildChildIdentityPayload({
137
- aliasTemplate = "",
138
- ttlHours = 24,
139
- tags = [],
140
- domainPoolId = "",
141
- receiveMode = "EDGE_ACCEPT",
142
- allowWebhooks = true,
143
- extractionTypes = ["otp", "link"],
144
- eventBudget = null,
145
- } = {}) {
146
- const base = buildProvisionEmailPayload({
147
- aliasTemplate,
148
- ttlHours,
149
- tags,
150
- domainPoolId,
151
- receiveMode,
152
- allowWebhooks,
153
- extractionTypes,
154
- });
155
-
156
- return {
157
- ...base,
158
- eventBudget: normalizeEventBudget(eventBudget),
159
- };
160
- }
161
-
162
- async function resolveSessionCredentialContext({ env, session, fetchCredentials }) {
163
- let resolvedSession = session;
164
- let resolvedFetcher = typeof fetchCredentials === "function" ? fetchCredentials : null;
165
-
166
- try {
167
- const { resolveActiveAuthSession, fetchAidenIdCredentials } = await import("../auth/service.js");
168
- const activeSession = await resolveActiveAuthSession({
169
- cwd: process.cwd(),
170
- env,
171
- autoRotate: false,
172
- });
173
- if (activeSession && activeSession.token) {
174
- resolvedSession = activeSession;
175
- }
176
- if (resolvedSession && resolvedSession.token && (!resolvedFetcher || activeSession?.token)) {
177
- resolvedFetcher = () =>
178
- fetchAidenIdCredentials({
179
- apiUrl: resolvedSession.apiUrl || "https://api.sentinelayer.com",
180
- token: resolvedSession.token,
181
- });
182
- }
183
- } catch {
184
- // Auth context resolution is best-effort.
185
- }
186
-
187
- return { session: resolvedSession, fetchCredentials: resolvedFetcher };
188
- }
189
-
190
- /**
191
- * Resolve AIdenID credentials with precedence:
192
- * 1. Explicit flags (--api-key, --org-id, --project-id)
193
- * 2. Environment vars (AIDENID_API_KEY, AIDENID_ORG_ID, AIDENID_PROJECT_ID)
194
- * 3. Session metadata (org_id, project_id) + lazy-fetch secret from SL API
195
- * using active auth source resolution (env -> config -> stored session)
196
- * 4. Error with guidance
197
- *
198
- * @param {object} options
199
- * @param {object} [options.session] - Stored session from readStoredSession(), may contain aidenid metadata
200
- * @param {Function} [options.fetchCredentials] - Async function to lazy-fetch secret from SL API
201
- */
202
- export async function resolveAidenIdCredentials(
203
- {
204
- apiKey = "",
205
- orgId = "",
206
- projectId = "",
207
- env = process.env,
208
- requireAll = true,
209
- session = null,
210
- fetchCredentials = null,
211
- } = {}
212
- ) {
213
- const sessionContext = await resolveSessionCredentialContext({
214
- env,
215
- session,
216
- fetchCredentials,
217
- });
218
- const activeSession = sessionContext.session;
219
- const activeFetchCredentials = sessionContext.fetchCredentials;
220
- const sessionAidenId = activeSession && activeSession.aidenid ? activeSession.aidenid : null;
221
- const hasSessionToken = Boolean(String(activeSession && activeSession.token ? activeSession.token : "").trim());
222
-
223
- let resolvedApiKey = String(apiKey || env.AIDENID_API_KEY || "").trim();
224
- let resolvedOrgId = String(orgId || env.AIDENID_ORG_ID || (sessionAidenId && sessionAidenId.orgId) || "").trim();
225
- let resolvedProjectId = String(projectId || env.AIDENID_PROJECT_ID || (sessionAidenId && sessionAidenId.projectId) || "").trim();
226
-
227
- // Lazy-fetch secret from SentinelLayer API when a CLI session token is available.
228
- if (!resolvedApiKey && hasSessionToken && typeof activeFetchCredentials === "function") {
229
- try {
230
- const fetched = await activeFetchCredentials();
231
- if (fetched && fetched.apiKey) {
232
- resolvedApiKey = String(fetched.apiKey).trim();
233
- if (!resolvedOrgId && fetched.orgId) resolvedOrgId = String(fetched.orgId).trim();
234
- if (!resolvedProjectId && fetched.projectId) resolvedProjectId = String(fetched.projectId).trim();
235
- }
236
- } catch {
237
- // Lazy-fetch failed continue with what we have
238
- }
239
- }
240
-
241
- const missing = [];
242
- if (!resolvedApiKey) missing.push("AIDENID_API_KEY");
243
- if (!resolvedOrgId) missing.push("AIDENID_ORG_ID");
244
- if (!resolvedProjectId) missing.push("AIDENID_PROJECT_ID");
245
-
246
- if (requireAll && missing.length > 0) {
247
- const hint = hasSessionToken
248
- ? ` (session token exists but AIdenID credential fetch failed — check network or run '${authLoginHint()}' again)`
249
- : ` (run '${authLoginHint()}' to auto-provision, or set env vars manually)`;
250
- throw new Error(`Missing AIdenID credentials: ${missing.join(", ")}.${hint}`);
251
- }
252
-
253
- return {
254
- apiKey: resolvedApiKey,
255
- orgId: resolvedOrgId,
256
- projectId: resolvedProjectId,
257
- missing,
258
- };
259
- }
260
-
261
- export function normalizeAidenIdApiUrl(rawValue) {
262
- return normalizeApiUrl(rawValue);
263
- }
264
-
265
- function buildProvisionHeaders({ apiKey, orgId, projectId, idempotencyKey }) {
266
- return {
267
- "Content-Type": "application/json",
268
- Authorization: `Bearer ${String(apiKey || "").trim()}`,
269
- "X-Org-Id": String(orgId || "").trim(),
270
- "X-Project-Id": String(projectId || "").trim(),
271
- "Idempotency-Key": String(idempotencyKey || "").trim(),
272
- };
273
- }
274
-
275
- function buildReadHeaders({ apiKey, orgId, projectId }) {
276
- return {
277
- Accept: "application/json",
278
- Authorization: `Bearer ${String(apiKey || "").trim()}`,
279
- "X-Org-Id": String(orgId || "").trim(),
280
- "X-Project-Id": String(projectId || "").trim(),
281
- };
282
- }
283
-
284
- function normalizeExtractionPayload(payload = {}) {
285
- if (!payload || typeof payload !== "object") {
286
- return {
287
- otp: null,
288
- primaryActionUrl: null,
289
- confidence: null,
290
- source: "UNKNOWN",
291
- extractedAt: null,
292
- raw: payload,
293
- };
294
- }
295
-
296
- const rawOtp = payload.otp ?? payload.code ?? payload.oneTimeCode ?? null;
297
- const rawPrimaryActionUrl =
298
- payload.primaryActionUrl ?? payload.primary_action_url ?? payload.verificationUrl ?? payload.link ?? null;
299
- const rawConfidence = payload.confidence ?? payload.score ?? payload.extractionConfidence ?? null;
300
- const numericConfidence = Number(rawConfidence);
301
- const normalizedConfidence = Number.isFinite(numericConfidence) ? numericConfidence : null;
302
- const rawSource = payload.source ?? payload.extractionSource ?? payload.engine ?? payload.method ?? null;
303
-
304
- return {
305
- otp: String(rawOtp || "").trim() || null,
306
- primaryActionUrl: String(rawPrimaryActionUrl || "").trim() || null,
307
- confidence: normalizedConfidence,
308
- source: String(rawSource || "").trim() || "UNKNOWN",
309
- extractedAt: String(payload.extractedAt || payload.createdAt || payload.timestamp || "").trim() || null,
310
- raw: payload,
311
- };
312
- }
313
-
314
- function normalizeEventsResponse(payload = {}) {
315
- if (Array.isArray(payload)) {
316
- return {
317
- events: payload,
318
- nextCursor: null,
319
- previousCursor: null,
320
- };
321
- }
322
-
323
- if (!payload || typeof payload !== "object") {
324
- return {
325
- events: [],
326
- nextCursor: null,
327
- previousCursor: null,
328
- };
329
- }
330
-
331
- const events = Array.isArray(payload.events)
332
- ? payload.events
333
- : Array.isArray(payload.items)
334
- ? payload.items
335
- : Array.isArray(payload.data)
336
- ? payload.data
337
- : [];
338
-
339
- return {
340
- events,
341
- nextCursor:
342
- String(payload.nextCursor || payload.next_cursor || payload.cursor || payload.next || "").trim() || null,
343
- previousCursor:
344
- String(payload.previousCursor || payload.previous_cursor || payload.prev || "").trim() || null,
345
- };
346
- }
347
-
348
- async function parseErrorBody(response) {
349
- try {
350
- const payload = await response.json();
351
- return JSON.stringify(payload);
352
- } catch {
353
- try {
354
- return await response.text();
355
- } catch {
356
- return "";
357
- }
358
- }
359
- }
360
-
361
- export async function provisionEmailIdentity({
362
- apiUrl,
363
- apiKey,
364
- orgId,
365
- projectId,
366
- idempotencyKey,
367
- payload,
368
- fetchImpl = fetch,
369
- } = {}) {
370
- if (typeof fetchImpl !== "function") {
371
- throw new Error("fetchImpl must be a function.");
372
- }
373
-
374
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
375
- const requestHeaders = buildProvisionHeaders({
376
- apiKey,
377
- orgId,
378
- projectId,
379
- idempotencyKey,
380
- });
381
-
382
- const response = await fetchImpl(`${normalizedApiUrl}/v1/identities`, {
383
- method: "POST",
384
- headers: requestHeaders,
385
- body: JSON.stringify(payload || {}),
386
- });
387
-
388
- if (!response.ok) {
389
- const details = await parseErrorBody(response);
390
- throw new Error(
391
- `AIdenID provision request failed with status ${response.status}${
392
- details ? `: ${details}` : ""
393
- }`
394
- );
395
- }
396
-
397
- const body = await response.json();
398
- return {
399
- apiUrl: normalizedApiUrl,
400
- response: body,
401
- requestHeaders,
402
- };
403
- }
404
-
405
- export async function revokeIdentity({
406
- apiUrl,
407
- apiKey,
408
- orgId,
409
- projectId,
410
- idempotencyKey,
411
- identityId,
412
- fetchImpl = fetch,
413
- } = {}) {
414
- if (typeof fetchImpl !== "function") {
415
- throw new Error("fetchImpl must be a function.");
416
- }
417
-
418
- const normalizedIdentityId = normalizeIdentityId(identityId);
419
-
420
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
421
- const requestHeaders = buildProvisionHeaders({
422
- apiKey,
423
- orgId,
424
- projectId,
425
- idempotencyKey,
426
- });
427
-
428
- const response = await fetchImpl(
429
- `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedIdentityId)}/revoke`,
430
- {
431
- method: "POST",
432
- headers: requestHeaders,
433
- }
434
- );
435
-
436
- if (!response.ok) {
437
- const details = await parseErrorBody(response);
438
- throw new Error(
439
- `AIdenID revoke request failed with status ${response.status}${details ? `: ${details}` : ""}`
440
- );
441
- }
442
-
443
- const body = await response.json();
444
- return {
445
- apiUrl: normalizedApiUrl,
446
- response: body,
447
- requestHeaders,
448
- };
449
- }
450
-
451
- export async function listIdentityEvents({
452
- apiUrl,
453
- apiKey,
454
- orgId,
455
- projectId,
456
- identityId,
457
- cursor = "",
458
- limit = 50,
459
- fetchImpl = fetch,
460
- } = {}) {
461
- if (typeof fetchImpl !== "function") {
462
- throw new Error("fetchImpl must be a function.");
463
- }
464
-
465
- const normalizedIdentityId = normalizeIdentityId(identityId);
466
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
467
- const normalizedLimit = normalizePositiveInteger(limit, "limit", { min: 1, max: 500 });
468
- const normalizedCursor = String(cursor || "").trim();
469
- const requestHeaders = buildReadHeaders({ apiKey, orgId, projectId });
470
-
471
- const endpoint = new URL(
472
- `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedIdentityId)}/events`
473
- );
474
- endpoint.searchParams.set("limit", String(normalizedLimit));
475
- if (normalizedCursor) {
476
- endpoint.searchParams.set("cursor", normalizedCursor);
477
- }
478
-
479
- const response = await fetchImpl(endpoint.toString(), {
480
- method: "GET",
481
- headers: requestHeaders,
482
- });
483
-
484
- if (!response.ok) {
485
- const details = await parseErrorBody(response);
486
- throw new Error(
487
- `AIdenID identity events request failed with status ${response.status}${details ? `: ${details}` : ""}`
488
- );
489
- }
490
-
491
- const body = await response.json();
492
- const normalized = normalizeEventsResponse(body);
493
- return {
494
- apiUrl: normalizedApiUrl,
495
- response: body,
496
- requestHeaders,
497
- events: normalized.events,
498
- nextCursor: normalized.nextCursor,
499
- previousCursor: normalized.previousCursor,
500
- };
501
- }
502
-
503
- export async function getLatestIdentityExtraction({
504
- apiUrl,
505
- apiKey,
506
- orgId,
507
- projectId,
508
- identityId,
509
- fetchImpl = fetch,
510
- } = {}) {
511
- if (typeof fetchImpl !== "function") {
512
- throw new Error("fetchImpl must be a function.");
513
- }
514
-
515
- const normalizedIdentityId = normalizeIdentityId(identityId);
516
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
517
- const requestHeaders = buildReadHeaders({ apiKey, orgId, projectId });
518
-
519
- const response = await fetchImpl(
520
- `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedIdentityId)}/latest-extraction`,
521
- {
522
- method: "GET",
523
- headers: requestHeaders,
524
- }
525
- );
526
-
527
- if (response.status === 404) {
528
- return {
529
- apiUrl: normalizedApiUrl,
530
- response: null,
531
- requestHeaders,
532
- extraction: normalizeExtractionPayload({}),
533
- notFound: true,
534
- };
535
- }
536
-
537
- if (!response.ok) {
538
- const details = await parseErrorBody(response);
539
- throw new Error(
540
- `AIdenID latest extraction request failed with status ${response.status}${
541
- details ? `: ${details}` : ""
542
- }`
543
- );
544
- }
545
-
546
- const body = await response.json();
547
- const extractionPayload =
548
- body && typeof body === "object" && body.extraction && typeof body.extraction === "object"
549
- ? body.extraction
550
- : body;
551
-
552
- return {
553
- apiUrl: normalizedApiUrl,
554
- response: body,
555
- requestHeaders,
556
- extraction: normalizeExtractionPayload(extractionPayload),
557
- notFound: false,
558
- };
559
- }
560
-
561
- export async function createChildIdentity({
562
- apiUrl,
563
- apiKey,
564
- orgId,
565
- projectId,
566
- parentIdentityId,
567
- idempotencyKey,
568
- payload,
569
- fetchImpl = fetch,
570
- } = {}) {
571
- if (typeof fetchImpl !== "function") {
572
- throw new Error("fetchImpl must be a function.");
573
- }
574
-
575
- const normalizedParentIdentityId = normalizeIdentityId(parentIdentityId);
576
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
577
- const requestHeaders = buildProvisionHeaders({
578
- apiKey,
579
- orgId,
580
- projectId,
581
- idempotencyKey,
582
- });
583
-
584
- const response = await fetchImpl(
585
- `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedParentIdentityId)}/children`,
586
- {
587
- method: "POST",
588
- headers: requestHeaders,
589
- body: JSON.stringify(payload || {}),
590
- }
591
- );
592
-
593
- if (!response.ok) {
594
- const details = await parseErrorBody(response);
595
- throw new Error(
596
- `AIdenID create child request failed with status ${response.status}${details ? `: ${details}` : ""}`
597
- );
598
- }
599
-
600
- const body = await response.json();
601
- return {
602
- apiUrl: normalizedApiUrl,
603
- response: body,
604
- requestHeaders,
605
- };
606
- }
607
-
608
- export async function getIdentityLineage({
609
- apiUrl,
610
- apiKey,
611
- orgId,
612
- projectId,
613
- identityId,
614
- fetchImpl = fetch,
615
- } = {}) {
616
- if (typeof fetchImpl !== "function") {
617
- throw new Error("fetchImpl must be a function.");
618
- }
619
-
620
- const normalizedIdentityId = normalizeIdentityId(identityId);
621
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
622
- const requestHeaders = buildReadHeaders({ apiKey, orgId, projectId });
623
-
624
- const response = await fetchImpl(
625
- `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedIdentityId)}/lineage`,
626
- {
627
- method: "GET",
628
- headers: requestHeaders,
629
- }
630
- );
631
-
632
- if (!response.ok) {
633
- const details = await parseErrorBody(response);
634
- throw new Error(
635
- `AIdenID identity lineage request failed with status ${response.status}${details ? `: ${details}` : ""}`
636
- );
637
- }
638
-
639
- const body = await response.json();
640
- const nodes = Array.isArray(body?.nodes) ? body.nodes : [];
641
- const edges = Array.isArray(body?.edges) ? body.edges : [];
642
- const rootIdentityId = String(body?.rootIdentityId || "").trim() || normalizedIdentityId;
643
- return {
644
- apiUrl: normalizedApiUrl,
645
- response: body,
646
- requestHeaders,
647
- rootIdentityId,
648
- nodes,
649
- edges,
650
- };
651
- }
652
-
653
- export async function revokeIdentityChildren({
654
- apiUrl,
655
- apiKey,
656
- orgId,
657
- projectId,
658
- identityId,
659
- idempotencyKey,
660
- fetchImpl = fetch,
661
- } = {}) {
662
- if (typeof fetchImpl !== "function") {
663
- throw new Error("fetchImpl must be a function.");
664
- }
665
-
666
- const normalizedIdentityId = normalizeIdentityId(identityId);
667
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
668
- const requestHeaders = buildProvisionHeaders({
669
- apiKey,
670
- orgId,
671
- projectId,
672
- idempotencyKey,
673
- });
674
-
675
- const response = await fetchImpl(
676
- `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedIdentityId)}/revoke-children`,
677
- {
678
- method: "POST",
679
- headers: requestHeaders,
680
- }
681
- );
682
-
683
- if (!response.ok) {
684
- const details = await parseErrorBody(response);
685
- throw new Error(
686
- `AIdenID revoke children request failed with status ${response.status}${details ? `: ${details}` : ""}`
687
- );
688
- }
689
-
690
- const body = await response.json();
691
- const revokedIdentityIds = Array.isArray(body?.revokedIdentityIds) ? body.revokedIdentityIds : [];
692
- const revokedCount = Number.isFinite(Number(body?.revokedCount))
693
- ? Number(body.revokedCount)
694
- : revokedIdentityIds.length;
695
- return {
696
- apiUrl: normalizedApiUrl,
697
- response: body,
698
- requestHeaders,
699
- parentIdentityId: String(body?.parentIdentityId || "").trim() || normalizedIdentityId,
700
- revokedCount,
701
- revokedIdentityIds,
702
- };
703
- }
704
-
705
- export async function createDomain({
706
- apiUrl,
707
- apiKey,
708
- orgId,
709
- projectId,
710
- idempotencyKey,
711
- payload,
712
- fetchImpl = fetch,
713
- } = {}) {
714
- if (typeof fetchImpl !== "function") {
715
- throw new Error("fetchImpl must be a function.");
716
- }
717
-
718
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
719
- const requestHeaders = buildProvisionHeaders({
720
- apiKey,
721
- orgId,
722
- projectId,
723
- idempotencyKey,
724
- });
725
-
726
- const response = await fetchImpl(`${normalizedApiUrl}/v1/domains`, {
727
- method: "POST",
728
- headers: requestHeaders,
729
- body: JSON.stringify(payload || {}),
730
- });
731
-
732
- if (!response.ok) {
733
- const details = await parseErrorBody(response);
734
- throw new Error(
735
- `AIdenID domain create request failed with status ${response.status}${details ? `: ${details}` : ""}`
736
- );
737
- }
738
-
739
- const body = await response.json();
740
- return {
741
- apiUrl: normalizedApiUrl,
742
- response: body,
743
- requestHeaders,
744
- };
745
- }
746
-
747
- export async function verifyDomain({
748
- apiUrl,
749
- apiKey,
750
- orgId,
751
- projectId,
752
- domainId,
753
- idempotencyKey,
754
- payload,
755
- fetchImpl = fetch,
756
- } = {}) {
757
- if (typeof fetchImpl !== "function") {
758
- throw new Error("fetchImpl must be a function.");
759
- }
760
-
761
- const normalizedDomainId = normalizeIdentityId(domainId);
762
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
763
- const requestHeaders = buildProvisionHeaders({
764
- apiKey,
765
- orgId,
766
- projectId,
767
- idempotencyKey,
768
- });
769
-
770
- const response = await fetchImpl(
771
- `${normalizedApiUrl}/v1/domains/${encodeURIComponent(normalizedDomainId)}/verify`,
772
- {
773
- method: "POST",
774
- headers: requestHeaders,
775
- body: JSON.stringify(payload || {}),
776
- }
777
- );
778
-
779
- if (!response.ok) {
780
- const details = await parseErrorBody(response);
781
- throw new Error(
782
- `AIdenID domain verify request failed with status ${response.status}${details ? `: ${details}` : ""}`
783
- );
784
- }
785
-
786
- const body = await response.json();
787
- return {
788
- apiUrl: normalizedApiUrl,
789
- response: body,
790
- requestHeaders,
791
- };
792
- }
793
-
794
- export async function freezeDomain({
795
- apiUrl,
796
- apiKey,
797
- orgId,
798
- projectId,
799
- domainId,
800
- idempotencyKey,
801
- payload,
802
- fetchImpl = fetch,
803
- } = {}) {
804
- if (typeof fetchImpl !== "function") {
805
- throw new Error("fetchImpl must be a function.");
806
- }
807
-
808
- const normalizedDomainId = normalizeIdentityId(domainId);
809
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
810
- const requestHeaders = buildProvisionHeaders({
811
- apiKey,
812
- orgId,
813
- projectId,
814
- idempotencyKey,
815
- });
816
-
817
- const response = await fetchImpl(
818
- `${normalizedApiUrl}/v1/domains/${encodeURIComponent(normalizedDomainId)}/freeze`,
819
- {
820
- method: "POST",
821
- headers: requestHeaders,
822
- body: JSON.stringify(payload || {}),
823
- }
824
- );
825
-
826
- if (!response.ok) {
827
- const details = await parseErrorBody(response);
828
- throw new Error(
829
- `AIdenID domain freeze request failed with status ${response.status}${details ? `: ${details}` : ""}`
830
- );
831
- }
832
-
833
- const body = await response.json();
834
- return {
835
- apiUrl: normalizedApiUrl,
836
- response: body,
837
- requestHeaders,
838
- };
839
- }
840
-
841
- export async function createTarget({
842
- apiUrl,
843
- apiKey,
844
- orgId,
845
- projectId,
846
- idempotencyKey,
847
- payload,
848
- fetchImpl = fetch,
849
- } = {}) {
850
- if (typeof fetchImpl !== "function") {
851
- throw new Error("fetchImpl must be a function.");
852
- }
853
-
854
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
855
- const requestHeaders = buildProvisionHeaders({
856
- apiKey,
857
- orgId,
858
- projectId,
859
- idempotencyKey,
860
- });
861
-
862
- const response = await fetchImpl(`${normalizedApiUrl}/v1/targets`, {
863
- method: "POST",
864
- headers: requestHeaders,
865
- body: JSON.stringify(payload || {}),
866
- });
867
-
868
- if (!response.ok) {
869
- const details = await parseErrorBody(response);
870
- throw new Error(
871
- `AIdenID target create request failed with status ${response.status}${details ? `: ${details}` : ""}`
872
- );
873
- }
874
-
875
- const body = await response.json();
876
- return {
877
- apiUrl: normalizedApiUrl,
878
- response: body,
879
- requestHeaders,
880
- };
881
- }
882
-
883
- export async function verifyTarget({
884
- apiUrl,
885
- apiKey,
886
- orgId,
887
- projectId,
888
- targetId,
889
- idempotencyKey,
890
- payload,
891
- fetchImpl = fetch,
892
- } = {}) {
893
- if (typeof fetchImpl !== "function") {
894
- throw new Error("fetchImpl must be a function.");
895
- }
896
-
897
- const normalizedTargetId = normalizeIdentityId(targetId);
898
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
899
- const requestHeaders = buildProvisionHeaders({
900
- apiKey,
901
- orgId,
902
- projectId,
903
- idempotencyKey,
904
- });
905
-
906
- const response = await fetchImpl(
907
- `${normalizedApiUrl}/v1/targets/${encodeURIComponent(normalizedTargetId)}/verify`,
908
- {
909
- method: "POST",
910
- headers: requestHeaders,
911
- body: JSON.stringify(payload || {}),
912
- }
913
- );
914
-
915
- if (!response.ok) {
916
- const details = await parseErrorBody(response);
917
- throw new Error(
918
- `AIdenID target verify request failed with status ${response.status}${details ? `: ${details}` : ""}`
919
- );
920
- }
921
-
922
- const body = await response.json();
923
- return {
924
- apiUrl: normalizedApiUrl,
925
- response: body,
926
- requestHeaders,
927
- };
928
- }
929
-
930
- export async function getTarget({
931
- apiUrl,
932
- apiKey,
933
- orgId,
934
- projectId,
935
- targetId,
936
- fetchImpl = fetch,
937
- } = {}) {
938
- if (typeof fetchImpl !== "function") {
939
- throw new Error("fetchImpl must be a function.");
940
- }
941
-
942
- const normalizedTargetId = normalizeIdentityId(targetId);
943
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
944
- const requestHeaders = buildReadHeaders({ apiKey, orgId, projectId });
945
-
946
- const response = await fetchImpl(
947
- `${normalizedApiUrl}/v1/targets/${encodeURIComponent(normalizedTargetId)}`,
948
- {
949
- method: "GET",
950
- headers: requestHeaders,
951
- }
952
- );
953
-
954
- if (!response.ok) {
955
- const details = await parseErrorBody(response);
956
- throw new Error(
957
- `AIdenID target show request failed with status ${response.status}${details ? `: ${details}` : ""}`
958
- );
959
- }
960
-
961
- const body = await response.json();
962
- return {
963
- apiUrl: normalizedApiUrl,
964
- response: body,
965
- requestHeaders,
966
- };
967
- }
968
-
969
- export async function createTemporarySite({
970
- apiUrl,
971
- apiKey,
972
- orgId,
973
- projectId,
974
- idempotencyKey,
975
- payload,
976
- fetchImpl = fetch,
977
- } = {}) {
978
- if (typeof fetchImpl !== "function") {
979
- throw new Error("fetchImpl must be a function.");
980
- }
981
-
982
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
983
- const requestHeaders = buildProvisionHeaders({
984
- apiKey,
985
- orgId,
986
- projectId,
987
- idempotencyKey,
988
- });
989
-
990
- const response = await fetchImpl(`${normalizedApiUrl}/v1/sites`, {
991
- method: "POST",
992
- headers: requestHeaders,
993
- body: JSON.stringify(payload || {}),
994
- });
995
-
996
- if (!response.ok) {
997
- const details = await parseErrorBody(response);
998
- throw new Error(
999
- `AIdenID site create request failed with status ${response.status}${details ? `: ${details}` : ""}`
1000
- );
1001
- }
1002
-
1003
- const body = await response.json();
1004
- return {
1005
- apiUrl: normalizedApiUrl,
1006
- response: body,
1007
- requestHeaders,
1008
- };
1009
- }
1
+ import process from "node:process";
2
+ import { authLoginHint } from "../ui/command-hints.js";
3
+
4
+ export const DEFAULT_AIDENID_API_URL = "https://api.aidenid.com";
5
+
6
+ function normalizeApiUrl(rawValue) {
7
+ const candidate = String(rawValue || "").trim() || DEFAULT_AIDENID_API_URL;
8
+ let parsed;
9
+ try {
10
+ parsed = new URL(candidate);
11
+ } catch {
12
+ throw new Error(`Invalid AIdenID API URL '${candidate}'.`);
13
+ }
14
+ parsed.pathname = "/";
15
+ parsed.search = "";
16
+ parsed.hash = "";
17
+ return parsed.toString().replace(/\/$/, "");
18
+ }
19
+
20
+ function normalizeCsvList(rawValue) {
21
+ const input = String(rawValue || "").trim();
22
+ if (!input) {
23
+ return [];
24
+ }
25
+ const unique = new Set();
26
+ for (const token of input.split(",")) {
27
+ const normalized = token.trim();
28
+ if (normalized) {
29
+ unique.add(normalized);
30
+ }
31
+ }
32
+ return [...unique];
33
+ }
34
+
35
+ function normalizeTtlHours(rawValue, fallbackValue = 24) {
36
+ if (rawValue === undefined || rawValue === null || String(rawValue).trim() === "") {
37
+ return fallbackValue;
38
+ }
39
+ const normalized = Number(rawValue);
40
+ if (!Number.isFinite(normalized) || normalized <= 0 || normalized > 24 * 30) {
41
+ throw new Error("ttlHours must be between 1 and 720.");
42
+ }
43
+ return Math.round(normalized);
44
+ }
45
+
46
+ function normalizePositiveInteger(rawValue, field, { min = 1, max = Number.MAX_SAFE_INTEGER } = {}) {
47
+ const normalized = Number(rawValue);
48
+ if (!Number.isFinite(normalized) || normalized < min || normalized > max) {
49
+ throw new Error(`${field} must be between ${min} and ${max}.`);
50
+ }
51
+ return Math.round(normalized);
52
+ }
53
+
54
+ function normalizeIdentityId(rawValue) {
55
+ const normalized = String(rawValue || "").trim();
56
+ if (!normalized) {
57
+ throw new Error("identityId is required.");
58
+ }
59
+ return normalized;
60
+ }
61
+
62
+ function normalizeAliasTemplate(rawValue) {
63
+ const normalized = String(rawValue || "").trim();
64
+ return normalized || null;
65
+ }
66
+
67
+ function normalizeDomainPoolId(rawValue) {
68
+ const normalized = String(rawValue || "").trim();
69
+ return normalized || null;
70
+ }
71
+
72
+ function normalizeReceiveMode(rawValue) {
73
+ const normalized = String(rawValue || "").trim();
74
+ return normalized || "EDGE_ACCEPT";
75
+ }
76
+
77
+ function normalizeExtractionTypes(rawValue) {
78
+ if (Array.isArray(rawValue)) {
79
+ const unique = new Set();
80
+ for (const item of rawValue) {
81
+ const normalized = String(item || "").trim();
82
+ if (normalized) {
83
+ unique.add(normalized);
84
+ }
85
+ }
86
+ return unique.size > 0 ? [...unique] : ["otp", "link"];
87
+ }
88
+
89
+ const parsed = normalizeCsvList(rawValue);
90
+ return parsed.length > 0 ? parsed : ["otp", "link"];
91
+ }
92
+
93
+ function normalizeTags(rawValue) {
94
+ if (Array.isArray(rawValue)) {
95
+ const unique = new Set();
96
+ for (const item of rawValue) {
97
+ const normalized = String(item || "").trim();
98
+ if (normalized) {
99
+ unique.add(normalized);
100
+ }
101
+ }
102
+ return [...unique];
103
+ }
104
+ return normalizeCsvList(rawValue);
105
+ }
106
+
107
+ function normalizeEventBudget(rawValue) {
108
+ if (rawValue === undefined || rawValue === null || String(rawValue).trim() === "") {
109
+ return null;
110
+ }
111
+ return normalizePositiveInteger(rawValue, "eventBudget", { min: 1, max: 1000000 });
112
+ }
113
+
114
+ export function buildProvisionEmailPayload({
115
+ aliasTemplate = "",
116
+ ttlHours = 24,
117
+ tags = [],
118
+ domainPoolId = "",
119
+ receiveMode = "EDGE_ACCEPT",
120
+ allowWebhooks = true,
121
+ extractionTypes = ["otp", "link"],
122
+ } = {}) {
123
+ return {
124
+ aliasTemplate: normalizeAliasTemplate(aliasTemplate),
125
+ ttlHours: normalizeTtlHours(ttlHours, 24),
126
+ tags: normalizeTags(tags),
127
+ domainPoolId: normalizeDomainPoolId(domainPoolId),
128
+ policy: {
129
+ receiveMode: normalizeReceiveMode(receiveMode),
130
+ allowWebhooks: Boolean(allowWebhooks),
131
+ extractionTypes: normalizeExtractionTypes(extractionTypes),
132
+ },
133
+ };
134
+ }
135
+
136
+ export function buildChildIdentityPayload({
137
+ aliasTemplate = "",
138
+ ttlHours = 24,
139
+ tags = [],
140
+ domainPoolId = "",
141
+ receiveMode = "EDGE_ACCEPT",
142
+ allowWebhooks = true,
143
+ extractionTypes = ["otp", "link"],
144
+ eventBudget = null,
145
+ } = {}) {
146
+ const base = buildProvisionEmailPayload({
147
+ aliasTemplate,
148
+ ttlHours,
149
+ tags,
150
+ domainPoolId,
151
+ receiveMode,
152
+ allowWebhooks,
153
+ extractionTypes,
154
+ });
155
+
156
+ return {
157
+ ...base,
158
+ eventBudget: normalizeEventBudget(eventBudget),
159
+ };
160
+ }
161
+
162
+ async function resolveSessionCredentialContext({
163
+ env,
164
+ session,
165
+ fetchCredentials,
166
+ autoResolveSession = true,
167
+ }) {
168
+ let resolvedSession = session;
169
+ let resolvedFetcher = typeof fetchCredentials === "function" ? fetchCredentials : null;
170
+
171
+ if (!autoResolveSession) {
172
+ return { session: resolvedSession, fetchCredentials: resolvedFetcher };
173
+ }
174
+
175
+ try {
176
+ const { resolveActiveAuthSession, fetchAidenIdCredentials } = await import("../auth/service.js");
177
+ const activeSession = await resolveActiveAuthSession({
178
+ cwd: process.cwd(),
179
+ env,
180
+ autoRotate: false,
181
+ });
182
+ if (activeSession && activeSession.token) {
183
+ resolvedSession = activeSession;
184
+ }
185
+ if (resolvedSession && resolvedSession.token && (!resolvedFetcher || activeSession?.token)) {
186
+ resolvedFetcher = () =>
187
+ fetchAidenIdCredentials({
188
+ apiUrl: resolvedSession.apiUrl || "https://api.sentinelayer.com",
189
+ token: resolvedSession.token,
190
+ });
191
+ }
192
+ } catch {
193
+ // Auth context resolution is best-effort.
194
+ }
195
+
196
+ return { session: resolvedSession, fetchCredentials: resolvedFetcher };
197
+ }
198
+
199
+ /**
200
+ * Resolve AIdenID credentials with precedence:
201
+ * 1. Explicit flags (--api-key, --org-id, --project-id)
202
+ * 2. Environment vars (AIDENID_API_KEY, AIDENID_ORG_ID, AIDENID_PROJECT_ID)
203
+ * 3. Session metadata (org_id, project_id) + lazy-fetch secret from SL API
204
+ * using active auth source resolution (env -> config -> stored session)
205
+ * 4. Error with guidance
206
+ *
207
+ * @param {object} options
208
+ * @param {object} [options.session] - Stored session from readStoredSession(), may contain aidenid metadata
209
+ * @param {Function} [options.fetchCredentials] - Async function to lazy-fetch secret from SL API
210
+ * @param {boolean} [options.autoResolveSession] - Auto-discover active SL auth session from local context
211
+ */
212
+ export async function resolveAidenIdCredentials(
213
+ {
214
+ apiKey = "",
215
+ orgId = "",
216
+ projectId = "",
217
+ env = process.env,
218
+ requireAll = true,
219
+ session = null,
220
+ fetchCredentials = null,
221
+ autoResolveSession = true,
222
+ } = {}
223
+ ) {
224
+ const sessionContext = await resolveSessionCredentialContext({
225
+ env,
226
+ session,
227
+ fetchCredentials,
228
+ autoResolveSession,
229
+ });
230
+ const activeSession = sessionContext.session;
231
+ const activeFetchCredentials = sessionContext.fetchCredentials;
232
+ const sessionAidenId = activeSession && activeSession.aidenid ? activeSession.aidenid : null;
233
+ const hasSessionToken = Boolean(String(activeSession && activeSession.token ? activeSession.token : "").trim());
234
+
235
+ let resolvedApiKey = String(apiKey || env.AIDENID_API_KEY || "").trim();
236
+ let resolvedOrgId = String(orgId || env.AIDENID_ORG_ID || (sessionAidenId && sessionAidenId.orgId) || "").trim();
237
+ let resolvedProjectId = String(projectId || env.AIDENID_PROJECT_ID || (sessionAidenId && sessionAidenId.projectId) || "").trim();
238
+
239
+ // Lazy-fetch secret from SentinelLayer API when a CLI session token is available.
240
+ if (!resolvedApiKey && hasSessionToken && typeof activeFetchCredentials === "function") {
241
+ try {
242
+ const fetched = await activeFetchCredentials();
243
+ if (fetched && fetched.apiKey) {
244
+ resolvedApiKey = String(fetched.apiKey).trim();
245
+ if (!resolvedOrgId && fetched.orgId) resolvedOrgId = String(fetched.orgId).trim();
246
+ if (!resolvedProjectId && fetched.projectId) resolvedProjectId = String(fetched.projectId).trim();
247
+ }
248
+ } catch {
249
+ // Lazy-fetch failed continue with what we have
250
+ }
251
+ }
252
+
253
+ const missing = [];
254
+ if (!resolvedApiKey) missing.push("AIDENID_API_KEY");
255
+ if (!resolvedOrgId) missing.push("AIDENID_ORG_ID");
256
+ if (!resolvedProjectId) missing.push("AIDENID_PROJECT_ID");
257
+
258
+ if (requireAll && missing.length > 0) {
259
+ const hint = hasSessionToken
260
+ ? ` (session token exists but AIdenID credential fetch failed — check network or run '${authLoginHint()}' again)`
261
+ : ` (run '${authLoginHint()}' to auto-provision, or set env vars manually)`;
262
+ throw new Error(`Missing AIdenID credentials: ${missing.join(", ")}.${hint}`);
263
+ }
264
+
265
+ return {
266
+ apiKey: resolvedApiKey,
267
+ orgId: resolvedOrgId,
268
+ projectId: resolvedProjectId,
269
+ missing,
270
+ };
271
+ }
272
+
273
+ export function normalizeAidenIdApiUrl(rawValue) {
274
+ return normalizeApiUrl(rawValue);
275
+ }
276
+
277
+ function buildProvisionHeaders({ apiKey, orgId, projectId, idempotencyKey }) {
278
+ return {
279
+ "Content-Type": "application/json",
280
+ Authorization: `Bearer ${String(apiKey || "").trim()}`,
281
+ "X-Org-Id": String(orgId || "").trim(),
282
+ "X-Project-Id": String(projectId || "").trim(),
283
+ "Idempotency-Key": String(idempotencyKey || "").trim(),
284
+ };
285
+ }
286
+
287
+ function buildReadHeaders({ apiKey, orgId, projectId }) {
288
+ return {
289
+ Accept: "application/json",
290
+ Authorization: `Bearer ${String(apiKey || "").trim()}`,
291
+ "X-Org-Id": String(orgId || "").trim(),
292
+ "X-Project-Id": String(projectId || "").trim(),
293
+ };
294
+ }
295
+
296
+ function normalizeExtractionPayload(payload = {}) {
297
+ if (!payload || typeof payload !== "object") {
298
+ return {
299
+ otp: null,
300
+ primaryActionUrl: null,
301
+ confidence: null,
302
+ source: "UNKNOWN",
303
+ extractedAt: null,
304
+ raw: payload,
305
+ };
306
+ }
307
+
308
+ const rawOtp = payload.otp ?? payload.code ?? payload.oneTimeCode ?? null;
309
+ const rawPrimaryActionUrl =
310
+ payload.primaryActionUrl ?? payload.primary_action_url ?? payload.verificationUrl ?? payload.link ?? null;
311
+ const rawConfidence = payload.confidence ?? payload.score ?? payload.extractionConfidence ?? null;
312
+ const numericConfidence = Number(rawConfidence);
313
+ const normalizedConfidence = Number.isFinite(numericConfidence) ? numericConfidence : null;
314
+ const rawSource = payload.source ?? payload.extractionSource ?? payload.engine ?? payload.method ?? null;
315
+
316
+ return {
317
+ otp: String(rawOtp || "").trim() || null,
318
+ primaryActionUrl: String(rawPrimaryActionUrl || "").trim() || null,
319
+ confidence: normalizedConfidence,
320
+ source: String(rawSource || "").trim() || "UNKNOWN",
321
+ extractedAt: String(payload.extractedAt || payload.createdAt || payload.timestamp || "").trim() || null,
322
+ raw: payload,
323
+ };
324
+ }
325
+
326
+ function normalizeEventsResponse(payload = {}) {
327
+ if (Array.isArray(payload)) {
328
+ return {
329
+ events: payload,
330
+ nextCursor: null,
331
+ previousCursor: null,
332
+ };
333
+ }
334
+
335
+ if (!payload || typeof payload !== "object") {
336
+ return {
337
+ events: [],
338
+ nextCursor: null,
339
+ previousCursor: null,
340
+ };
341
+ }
342
+
343
+ const events = Array.isArray(payload.events)
344
+ ? payload.events
345
+ : Array.isArray(payload.items)
346
+ ? payload.items
347
+ : Array.isArray(payload.data)
348
+ ? payload.data
349
+ : [];
350
+
351
+ return {
352
+ events,
353
+ nextCursor:
354
+ String(payload.nextCursor || payload.next_cursor || payload.cursor || payload.next || "").trim() || null,
355
+ previousCursor:
356
+ String(payload.previousCursor || payload.previous_cursor || payload.prev || "").trim() || null,
357
+ };
358
+ }
359
+
360
+ async function parseErrorBody(response) {
361
+ try {
362
+ const payload = await response.json();
363
+ return JSON.stringify(payload);
364
+ } catch {
365
+ try {
366
+ return await response.text();
367
+ } catch {
368
+ return "";
369
+ }
370
+ }
371
+ }
372
+
373
+ export async function provisionEmailIdentity({
374
+ apiUrl,
375
+ apiKey,
376
+ orgId,
377
+ projectId,
378
+ idempotencyKey,
379
+ payload,
380
+ fetchImpl = fetch,
381
+ } = {}) {
382
+ if (typeof fetchImpl !== "function") {
383
+ throw new Error("fetchImpl must be a function.");
384
+ }
385
+
386
+ const normalizedApiUrl = normalizeApiUrl(apiUrl);
387
+ const requestHeaders = buildProvisionHeaders({
388
+ apiKey,
389
+ orgId,
390
+ projectId,
391
+ idempotencyKey,
392
+ });
393
+
394
+ const response = await fetchImpl(`${normalizedApiUrl}/v1/identities`, {
395
+ method: "POST",
396
+ headers: requestHeaders,
397
+ body: JSON.stringify(payload || {}),
398
+ });
399
+
400
+ if (!response.ok) {
401
+ const details = await parseErrorBody(response);
402
+ throw new Error(
403
+ `AIdenID provision request failed with status ${response.status}${
404
+ details ? `: ${details}` : ""
405
+ }`
406
+ );
407
+ }
408
+
409
+ const body = await response.json();
410
+ return {
411
+ apiUrl: normalizedApiUrl,
412
+ response: body,
413
+ requestHeaders,
414
+ };
415
+ }
416
+
417
+ export async function revokeIdentity({
418
+ apiUrl,
419
+ apiKey,
420
+ orgId,
421
+ projectId,
422
+ idempotencyKey,
423
+ identityId,
424
+ fetchImpl = fetch,
425
+ } = {}) {
426
+ if (typeof fetchImpl !== "function") {
427
+ throw new Error("fetchImpl must be a function.");
428
+ }
429
+
430
+ const normalizedIdentityId = normalizeIdentityId(identityId);
431
+
432
+ const normalizedApiUrl = normalizeApiUrl(apiUrl);
433
+ const requestHeaders = buildProvisionHeaders({
434
+ apiKey,
435
+ orgId,
436
+ projectId,
437
+ idempotencyKey,
438
+ });
439
+
440
+ const response = await fetchImpl(
441
+ `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedIdentityId)}/revoke`,
442
+ {
443
+ method: "POST",
444
+ headers: requestHeaders,
445
+ }
446
+ );
447
+
448
+ if (!response.ok) {
449
+ const details = await parseErrorBody(response);
450
+ throw new Error(
451
+ `AIdenID revoke request failed with status ${response.status}${details ? `: ${details}` : ""}`
452
+ );
453
+ }
454
+
455
+ const body = await response.json();
456
+ return {
457
+ apiUrl: normalizedApiUrl,
458
+ response: body,
459
+ requestHeaders,
460
+ };
461
+ }
462
+
463
+ export async function listIdentityEvents({
464
+ apiUrl,
465
+ apiKey,
466
+ orgId,
467
+ projectId,
468
+ identityId,
469
+ cursor = "",
470
+ limit = 50,
471
+ fetchImpl = fetch,
472
+ } = {}) {
473
+ if (typeof fetchImpl !== "function") {
474
+ throw new Error("fetchImpl must be a function.");
475
+ }
476
+
477
+ const normalizedIdentityId = normalizeIdentityId(identityId);
478
+ const normalizedApiUrl = normalizeApiUrl(apiUrl);
479
+ const normalizedLimit = normalizePositiveInteger(limit, "limit", { min: 1, max: 500 });
480
+ const normalizedCursor = String(cursor || "").trim();
481
+ const requestHeaders = buildReadHeaders({ apiKey, orgId, projectId });
482
+
483
+ const endpoint = new URL(
484
+ `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedIdentityId)}/events`
485
+ );
486
+ endpoint.searchParams.set("limit", String(normalizedLimit));
487
+ if (normalizedCursor) {
488
+ endpoint.searchParams.set("cursor", normalizedCursor);
489
+ }
490
+
491
+ const response = await fetchImpl(endpoint.toString(), {
492
+ method: "GET",
493
+ headers: requestHeaders,
494
+ });
495
+
496
+ if (!response.ok) {
497
+ const details = await parseErrorBody(response);
498
+ throw new Error(
499
+ `AIdenID identity events request failed with status ${response.status}${details ? `: ${details}` : ""}`
500
+ );
501
+ }
502
+
503
+ const body = await response.json();
504
+ const normalized = normalizeEventsResponse(body);
505
+ return {
506
+ apiUrl: normalizedApiUrl,
507
+ response: body,
508
+ requestHeaders,
509
+ events: normalized.events,
510
+ nextCursor: normalized.nextCursor,
511
+ previousCursor: normalized.previousCursor,
512
+ };
513
+ }
514
+
515
+ export async function getLatestIdentityExtraction({
516
+ apiUrl,
517
+ apiKey,
518
+ orgId,
519
+ projectId,
520
+ identityId,
521
+ fetchImpl = fetch,
522
+ } = {}) {
523
+ if (typeof fetchImpl !== "function") {
524
+ throw new Error("fetchImpl must be a function.");
525
+ }
526
+
527
+ const normalizedIdentityId = normalizeIdentityId(identityId);
528
+ const normalizedApiUrl = normalizeApiUrl(apiUrl);
529
+ const requestHeaders = buildReadHeaders({ apiKey, orgId, projectId });
530
+
531
+ const response = await fetchImpl(
532
+ `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedIdentityId)}/latest-extraction`,
533
+ {
534
+ method: "GET",
535
+ headers: requestHeaders,
536
+ }
537
+ );
538
+
539
+ if (response.status === 404) {
540
+ return {
541
+ apiUrl: normalizedApiUrl,
542
+ response: null,
543
+ requestHeaders,
544
+ extraction: normalizeExtractionPayload({}),
545
+ notFound: true,
546
+ };
547
+ }
548
+
549
+ if (!response.ok) {
550
+ const details = await parseErrorBody(response);
551
+ throw new Error(
552
+ `AIdenID latest extraction request failed with status ${response.status}${
553
+ details ? `: ${details}` : ""
554
+ }`
555
+ );
556
+ }
557
+
558
+ const body = await response.json();
559
+ const extractionPayload =
560
+ body && typeof body === "object" && body.extraction && typeof body.extraction === "object"
561
+ ? body.extraction
562
+ : body;
563
+
564
+ return {
565
+ apiUrl: normalizedApiUrl,
566
+ response: body,
567
+ requestHeaders,
568
+ extraction: normalizeExtractionPayload(extractionPayload),
569
+ notFound: false,
570
+ };
571
+ }
572
+
573
+ export async function createChildIdentity({
574
+ apiUrl,
575
+ apiKey,
576
+ orgId,
577
+ projectId,
578
+ parentIdentityId,
579
+ idempotencyKey,
580
+ payload,
581
+ fetchImpl = fetch,
582
+ } = {}) {
583
+ if (typeof fetchImpl !== "function") {
584
+ throw new Error("fetchImpl must be a function.");
585
+ }
586
+
587
+ const normalizedParentIdentityId = normalizeIdentityId(parentIdentityId);
588
+ const normalizedApiUrl = normalizeApiUrl(apiUrl);
589
+ const requestHeaders = buildProvisionHeaders({
590
+ apiKey,
591
+ orgId,
592
+ projectId,
593
+ idempotencyKey,
594
+ });
595
+
596
+ const response = await fetchImpl(
597
+ `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedParentIdentityId)}/children`,
598
+ {
599
+ method: "POST",
600
+ headers: requestHeaders,
601
+ body: JSON.stringify(payload || {}),
602
+ }
603
+ );
604
+
605
+ if (!response.ok) {
606
+ const details = await parseErrorBody(response);
607
+ throw new Error(
608
+ `AIdenID create child request failed with status ${response.status}${details ? `: ${details}` : ""}`
609
+ );
610
+ }
611
+
612
+ const body = await response.json();
613
+ return {
614
+ apiUrl: normalizedApiUrl,
615
+ response: body,
616
+ requestHeaders,
617
+ };
618
+ }
619
+
620
+ export async function getIdentityLineage({
621
+ apiUrl,
622
+ apiKey,
623
+ orgId,
624
+ projectId,
625
+ identityId,
626
+ fetchImpl = fetch,
627
+ } = {}) {
628
+ if (typeof fetchImpl !== "function") {
629
+ throw new Error("fetchImpl must be a function.");
630
+ }
631
+
632
+ const normalizedIdentityId = normalizeIdentityId(identityId);
633
+ const normalizedApiUrl = normalizeApiUrl(apiUrl);
634
+ const requestHeaders = buildReadHeaders({ apiKey, orgId, projectId });
635
+
636
+ const response = await fetchImpl(
637
+ `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedIdentityId)}/lineage`,
638
+ {
639
+ method: "GET",
640
+ headers: requestHeaders,
641
+ }
642
+ );
643
+
644
+ if (!response.ok) {
645
+ const details = await parseErrorBody(response);
646
+ throw new Error(
647
+ `AIdenID identity lineage request failed with status ${response.status}${details ? `: ${details}` : ""}`
648
+ );
649
+ }
650
+
651
+ const body = await response.json();
652
+ const nodes = Array.isArray(body?.nodes) ? body.nodes : [];
653
+ const edges = Array.isArray(body?.edges) ? body.edges : [];
654
+ const rootIdentityId = String(body?.rootIdentityId || "").trim() || normalizedIdentityId;
655
+ return {
656
+ apiUrl: normalizedApiUrl,
657
+ response: body,
658
+ requestHeaders,
659
+ rootIdentityId,
660
+ nodes,
661
+ edges,
662
+ };
663
+ }
664
+
665
+ export async function revokeIdentityChildren({
666
+ apiUrl,
667
+ apiKey,
668
+ orgId,
669
+ projectId,
670
+ identityId,
671
+ idempotencyKey,
672
+ fetchImpl = fetch,
673
+ } = {}) {
674
+ if (typeof fetchImpl !== "function") {
675
+ throw new Error("fetchImpl must be a function.");
676
+ }
677
+
678
+ const normalizedIdentityId = normalizeIdentityId(identityId);
679
+ const normalizedApiUrl = normalizeApiUrl(apiUrl);
680
+ const requestHeaders = buildProvisionHeaders({
681
+ apiKey,
682
+ orgId,
683
+ projectId,
684
+ idempotencyKey,
685
+ });
686
+
687
+ const response = await fetchImpl(
688
+ `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedIdentityId)}/revoke-children`,
689
+ {
690
+ method: "POST",
691
+ headers: requestHeaders,
692
+ }
693
+ );
694
+
695
+ if (!response.ok) {
696
+ const details = await parseErrorBody(response);
697
+ throw new Error(
698
+ `AIdenID revoke children request failed with status ${response.status}${details ? `: ${details}` : ""}`
699
+ );
700
+ }
701
+
702
+ const body = await response.json();
703
+ const revokedIdentityIds = Array.isArray(body?.revokedIdentityIds) ? body.revokedIdentityIds : [];
704
+ const revokedCount = Number.isFinite(Number(body?.revokedCount))
705
+ ? Number(body.revokedCount)
706
+ : revokedIdentityIds.length;
707
+ return {
708
+ apiUrl: normalizedApiUrl,
709
+ response: body,
710
+ requestHeaders,
711
+ parentIdentityId: String(body?.parentIdentityId || "").trim() || normalizedIdentityId,
712
+ revokedCount,
713
+ revokedIdentityIds,
714
+ };
715
+ }
716
+
717
+ export async function createDomain({
718
+ apiUrl,
719
+ apiKey,
720
+ orgId,
721
+ projectId,
722
+ idempotencyKey,
723
+ payload,
724
+ fetchImpl = fetch,
725
+ } = {}) {
726
+ if (typeof fetchImpl !== "function") {
727
+ throw new Error("fetchImpl must be a function.");
728
+ }
729
+
730
+ const normalizedApiUrl = normalizeApiUrl(apiUrl);
731
+ const requestHeaders = buildProvisionHeaders({
732
+ apiKey,
733
+ orgId,
734
+ projectId,
735
+ idempotencyKey,
736
+ });
737
+
738
+ const response = await fetchImpl(`${normalizedApiUrl}/v1/domains`, {
739
+ method: "POST",
740
+ headers: requestHeaders,
741
+ body: JSON.stringify(payload || {}),
742
+ });
743
+
744
+ if (!response.ok) {
745
+ const details = await parseErrorBody(response);
746
+ throw new Error(
747
+ `AIdenID domain create request failed with status ${response.status}${details ? `: ${details}` : ""}`
748
+ );
749
+ }
750
+
751
+ const body = await response.json();
752
+ return {
753
+ apiUrl: normalizedApiUrl,
754
+ response: body,
755
+ requestHeaders,
756
+ };
757
+ }
758
+
759
+ export async function verifyDomain({
760
+ apiUrl,
761
+ apiKey,
762
+ orgId,
763
+ projectId,
764
+ domainId,
765
+ idempotencyKey,
766
+ payload,
767
+ fetchImpl = fetch,
768
+ } = {}) {
769
+ if (typeof fetchImpl !== "function") {
770
+ throw new Error("fetchImpl must be a function.");
771
+ }
772
+
773
+ const normalizedDomainId = normalizeIdentityId(domainId);
774
+ const normalizedApiUrl = normalizeApiUrl(apiUrl);
775
+ const requestHeaders = buildProvisionHeaders({
776
+ apiKey,
777
+ orgId,
778
+ projectId,
779
+ idempotencyKey,
780
+ });
781
+
782
+ const response = await fetchImpl(
783
+ `${normalizedApiUrl}/v1/domains/${encodeURIComponent(normalizedDomainId)}/verify`,
784
+ {
785
+ method: "POST",
786
+ headers: requestHeaders,
787
+ body: JSON.stringify(payload || {}),
788
+ }
789
+ );
790
+
791
+ if (!response.ok) {
792
+ const details = await parseErrorBody(response);
793
+ throw new Error(
794
+ `AIdenID domain verify request failed with status ${response.status}${details ? `: ${details}` : ""}`
795
+ );
796
+ }
797
+
798
+ const body = await response.json();
799
+ return {
800
+ apiUrl: normalizedApiUrl,
801
+ response: body,
802
+ requestHeaders,
803
+ };
804
+ }
805
+
806
+ export async function freezeDomain({
807
+ apiUrl,
808
+ apiKey,
809
+ orgId,
810
+ projectId,
811
+ domainId,
812
+ idempotencyKey,
813
+ payload,
814
+ fetchImpl = fetch,
815
+ } = {}) {
816
+ if (typeof fetchImpl !== "function") {
817
+ throw new Error("fetchImpl must be a function.");
818
+ }
819
+
820
+ const normalizedDomainId = normalizeIdentityId(domainId);
821
+ const normalizedApiUrl = normalizeApiUrl(apiUrl);
822
+ const requestHeaders = buildProvisionHeaders({
823
+ apiKey,
824
+ orgId,
825
+ projectId,
826
+ idempotencyKey,
827
+ });
828
+
829
+ const response = await fetchImpl(
830
+ `${normalizedApiUrl}/v1/domains/${encodeURIComponent(normalizedDomainId)}/freeze`,
831
+ {
832
+ method: "POST",
833
+ headers: requestHeaders,
834
+ body: JSON.stringify(payload || {}),
835
+ }
836
+ );
837
+
838
+ if (!response.ok) {
839
+ const details = await parseErrorBody(response);
840
+ throw new Error(
841
+ `AIdenID domain freeze request failed with status ${response.status}${details ? `: ${details}` : ""}`
842
+ );
843
+ }
844
+
845
+ const body = await response.json();
846
+ return {
847
+ apiUrl: normalizedApiUrl,
848
+ response: body,
849
+ requestHeaders,
850
+ };
851
+ }
852
+
853
+ export async function createTarget({
854
+ apiUrl,
855
+ apiKey,
856
+ orgId,
857
+ projectId,
858
+ idempotencyKey,
859
+ payload,
860
+ fetchImpl = fetch,
861
+ } = {}) {
862
+ if (typeof fetchImpl !== "function") {
863
+ throw new Error("fetchImpl must be a function.");
864
+ }
865
+
866
+ const normalizedApiUrl = normalizeApiUrl(apiUrl);
867
+ const requestHeaders = buildProvisionHeaders({
868
+ apiKey,
869
+ orgId,
870
+ projectId,
871
+ idempotencyKey,
872
+ });
873
+
874
+ const response = await fetchImpl(`${normalizedApiUrl}/v1/targets`, {
875
+ method: "POST",
876
+ headers: requestHeaders,
877
+ body: JSON.stringify(payload || {}),
878
+ });
879
+
880
+ if (!response.ok) {
881
+ const details = await parseErrorBody(response);
882
+ throw new Error(
883
+ `AIdenID target create request failed with status ${response.status}${details ? `: ${details}` : ""}`
884
+ );
885
+ }
886
+
887
+ const body = await response.json();
888
+ return {
889
+ apiUrl: normalizedApiUrl,
890
+ response: body,
891
+ requestHeaders,
892
+ };
893
+ }
894
+
895
+ export async function verifyTarget({
896
+ apiUrl,
897
+ apiKey,
898
+ orgId,
899
+ projectId,
900
+ targetId,
901
+ idempotencyKey,
902
+ payload,
903
+ fetchImpl = fetch,
904
+ } = {}) {
905
+ if (typeof fetchImpl !== "function") {
906
+ throw new Error("fetchImpl must be a function.");
907
+ }
908
+
909
+ const normalizedTargetId = normalizeIdentityId(targetId);
910
+ const normalizedApiUrl = normalizeApiUrl(apiUrl);
911
+ const requestHeaders = buildProvisionHeaders({
912
+ apiKey,
913
+ orgId,
914
+ projectId,
915
+ idempotencyKey,
916
+ });
917
+
918
+ const response = await fetchImpl(
919
+ `${normalizedApiUrl}/v1/targets/${encodeURIComponent(normalizedTargetId)}/verify`,
920
+ {
921
+ method: "POST",
922
+ headers: requestHeaders,
923
+ body: JSON.stringify(payload || {}),
924
+ }
925
+ );
926
+
927
+ if (!response.ok) {
928
+ const details = await parseErrorBody(response);
929
+ throw new Error(
930
+ `AIdenID target verify request failed with status ${response.status}${details ? `: ${details}` : ""}`
931
+ );
932
+ }
933
+
934
+ const body = await response.json();
935
+ return {
936
+ apiUrl: normalizedApiUrl,
937
+ response: body,
938
+ requestHeaders,
939
+ };
940
+ }
941
+
942
+ export async function getTarget({
943
+ apiUrl,
944
+ apiKey,
945
+ orgId,
946
+ projectId,
947
+ targetId,
948
+ fetchImpl = fetch,
949
+ } = {}) {
950
+ if (typeof fetchImpl !== "function") {
951
+ throw new Error("fetchImpl must be a function.");
952
+ }
953
+
954
+ const normalizedTargetId = normalizeIdentityId(targetId);
955
+ const normalizedApiUrl = normalizeApiUrl(apiUrl);
956
+ const requestHeaders = buildReadHeaders({ apiKey, orgId, projectId });
957
+
958
+ const response = await fetchImpl(
959
+ `${normalizedApiUrl}/v1/targets/${encodeURIComponent(normalizedTargetId)}`,
960
+ {
961
+ method: "GET",
962
+ headers: requestHeaders,
963
+ }
964
+ );
965
+
966
+ if (!response.ok) {
967
+ const details = await parseErrorBody(response);
968
+ throw new Error(
969
+ `AIdenID target show request failed with status ${response.status}${details ? `: ${details}` : ""}`
970
+ );
971
+ }
972
+
973
+ const body = await response.json();
974
+ return {
975
+ apiUrl: normalizedApiUrl,
976
+ response: body,
977
+ requestHeaders,
978
+ };
979
+ }
980
+
981
+ export async function createTemporarySite({
982
+ apiUrl,
983
+ apiKey,
984
+ orgId,
985
+ projectId,
986
+ idempotencyKey,
987
+ payload,
988
+ fetchImpl = fetch,
989
+ } = {}) {
990
+ if (typeof fetchImpl !== "function") {
991
+ throw new Error("fetchImpl must be a function.");
992
+ }
993
+
994
+ const normalizedApiUrl = normalizeApiUrl(apiUrl);
995
+ const requestHeaders = buildProvisionHeaders({
996
+ apiKey,
997
+ orgId,
998
+ projectId,
999
+ idempotencyKey,
1000
+ });
1001
+
1002
+ const response = await fetchImpl(`${normalizedApiUrl}/v1/sites`, {
1003
+ method: "POST",
1004
+ headers: requestHeaders,
1005
+ body: JSON.stringify(payload || {}),
1006
+ });
1007
+
1008
+ if (!response.ok) {
1009
+ const details = await parseErrorBody(response);
1010
+ throw new Error(
1011
+ `AIdenID site create request failed with status ${response.status}${details ? `: ${details}` : ""}`
1012
+ );
1013
+ }
1014
+
1015
+ const body = await response.json();
1016
+ return {
1017
+ apiUrl: normalizedApiUrl,
1018
+ response: body,
1019
+ requestHeaders,
1020
+ };
1021
+ }