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