sentinelayer-cli 0.1.2 → 0.4.4

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 (129) hide show
  1. package/README.md +998 -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 +63 -54
  6. package/src/agents/jules/config/definition.js +209 -209
  7. package/src/agents/jules/config/system-prompt.js +175 -175
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +377 -377
  10. package/src/agents/jules/loop.js +367 -367
  11. package/src/agents/jules/pulse.js +327 -319
  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 +308 -308
  18. package/src/agents/jules/tools/auth-audit.js +557 -222
  19. package/src/agents/jules/tools/dispatch.js +327 -327
  20. package/src/agents/jules/tools/file-edit.js +180 -180
  21. package/src/agents/jules/tools/file-read.js +100 -100
  22. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  23. package/src/agents/jules/tools/glob.js +168 -168
  24. package/src/agents/jules/tools/grep.js +228 -228
  25. package/src/agents/jules/tools/index.js +29 -29
  26. package/src/agents/jules/tools/path-guards.js +161 -161
  27. package/src/agents/jules/tools/runtime-audit.js +503 -493
  28. package/src/agents/jules/tools/shell.js +383 -383
  29. package/src/agents/jules/tools/url-policy.js +100 -0
  30. package/src/ai/aidenid.js +972 -945
  31. package/src/ai/client.js +508 -508
  32. package/src/ai/domain-target-store.js +268 -268
  33. package/src/ai/identity-store.js +270 -270
  34. package/src/ai/site-store.js +145 -145
  35. package/src/audit/agents/architecture.js +180 -180
  36. package/src/audit/agents/compliance.js +179 -179
  37. package/src/audit/agents/documentation.js +165 -165
  38. package/src/audit/agents/performance.js +145 -145
  39. package/src/audit/agents/security.js +215 -215
  40. package/src/audit/agents/testing.js +172 -172
  41. package/src/audit/orchestrator.js +557 -557
  42. package/src/audit/package.js +204 -204
  43. package/src/audit/registry.js +284 -284
  44. package/src/audit/replay.js +103 -103
  45. package/src/auth/gate.js +45 -11
  46. package/src/auth/http.js +270 -113
  47. package/src/auth/service.js +891 -848
  48. package/src/auth/session-store.js +359 -345
  49. package/src/cli.js +252 -252
  50. package/src/commands/ai/identity-lifecycle.js +1338 -1337
  51. package/src/commands/ai/provision-governance.js +1272 -1246
  52. package/src/commands/ai/shared.js +147 -147
  53. package/src/commands/ai.js +11 -11
  54. package/src/commands/apply.js +12 -12
  55. package/src/commands/audit.js +1166 -1166
  56. package/src/commands/auth.js +375 -366
  57. package/src/commands/chat.js +191 -191
  58. package/src/commands/config.js +184 -184
  59. package/src/commands/cost.js +311 -311
  60. package/src/commands/daemon/core.js +850 -850
  61. package/src/commands/daemon/extended.js +1048 -1048
  62. package/src/commands/daemon/shared.js +213 -213
  63. package/src/commands/daemon.js +11 -11
  64. package/src/commands/guide.js +174 -174
  65. package/src/commands/ingest.js +58 -58
  66. package/src/commands/init.js +55 -55
  67. package/src/commands/legacy-args.js +10 -10
  68. package/src/commands/mcp.js +461 -404
  69. package/src/commands/omargate.js +15 -15
  70. package/src/commands/persona.js +20 -20
  71. package/src/commands/plugin.js +260 -260
  72. package/src/commands/policy.js +132 -132
  73. package/src/commands/prompt.js +238 -238
  74. package/src/commands/review.js +704 -704
  75. package/src/commands/scan.js +866 -788
  76. package/src/commands/spec.js +716 -716
  77. package/src/commands/swarm.js +651 -651
  78. package/src/commands/telemetry.js +202 -202
  79. package/src/commands/watch.js +510 -510
  80. package/src/config/agent-dictionary.js +182 -182
  81. package/src/config/io.js +56 -56
  82. package/src/config/paths.js +18 -18
  83. package/src/config/schema.js +55 -55
  84. package/src/config/service.js +184 -184
  85. package/src/cost/budget.js +235 -235
  86. package/src/cost/history.js +188 -188
  87. package/src/cost/tracker.js +171 -171
  88. package/src/daemon/artifact-lineage.js +534 -534
  89. package/src/daemon/assignment-ledger.js +770 -770
  90. package/src/daemon/ast-parser-layer.js +258 -258
  91. package/src/daemon/budget-governor.js +633 -633
  92. package/src/daemon/callgraph-overlay.js +646 -646
  93. package/src/daemon/error-worker.js +626 -626
  94. package/src/daemon/hybrid-mapper.js +929 -929
  95. package/src/daemon/jira-lifecycle.js +632 -632
  96. package/src/daemon/operator-control.js +657 -657
  97. package/src/daemon/reliability-lane.js +471 -471
  98. package/src/daemon/watchdog.js +971 -971
  99. package/src/guide/generator.js +316 -316
  100. package/src/ingest/engine.js +918 -918
  101. package/src/legacy-cli.js +2592 -2435
  102. package/src/mcp/registry.js +695 -695
  103. package/src/memory/blackboard.js +301 -301
  104. package/src/memory/retrieval.js +581 -581
  105. package/src/plugin/manifest.js +553 -553
  106. package/src/policy/packs.js +144 -144
  107. package/src/prompt/generator.js +118 -106
  108. package/src/review/ai-review.js +669 -669
  109. package/src/review/local-review.js +1295 -1284
  110. package/src/review/replay.js +235 -235
  111. package/src/review/report.js +664 -664
  112. package/src/review/spec-binding.js +487 -487
  113. package/src/scaffold/generator.js +67 -0
  114. package/src/scaffold/templates.js +150 -0
  115. package/src/scan/generator.js +418 -351
  116. package/src/scan/gh-secrets.js +107 -0
  117. package/src/spec/generator.js +519 -519
  118. package/src/spec/regenerate.js +237 -237
  119. package/src/spec/templates.js +91 -91
  120. package/src/swarm/dashboard.js +247 -247
  121. package/src/swarm/factory.js +363 -363
  122. package/src/swarm/pentest.js +934 -934
  123. package/src/swarm/registry.js +419 -419
  124. package/src/swarm/report.js +158 -158
  125. package/src/swarm/runtime.js +576 -576
  126. package/src/swarm/scenario-dsl.js +272 -272
  127. package/src/telemetry/ledger.js +302 -302
  128. package/src/telemetry/sync.js +107 -61
  129. package/src/ui/markdown.js +220 -220
package/src/ai/aidenid.js CHANGED
@@ -1,945 +1,972 @@
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
- export function resolveAidenIdCredentials(
162
- {
163
- apiKey = "",
164
- orgId = "",
165
- projectId = "",
166
- env = process.env,
167
- requireAll = true,
168
- } = {}
169
- ) {
170
- const resolved = {
171
- apiKey: String(apiKey || env.AIDENID_API_KEY || "").trim(),
172
- orgId: String(orgId || env.AIDENID_ORG_ID || "").trim(),
173
- projectId: String(projectId || env.AIDENID_PROJECT_ID || "").trim(),
174
- };
175
-
176
- const missing = [];
177
- if (!resolved.apiKey) {
178
- missing.push("AIDENID_API_KEY");
179
- }
180
- if (!resolved.orgId) {
181
- missing.push("AIDENID_ORG_ID");
182
- }
183
- if (!resolved.projectId) {
184
- missing.push("AIDENID_PROJECT_ID");
185
- }
186
-
187
- if (requireAll && missing.length > 0) {
188
- throw new Error(`Missing AIdenID credentials: ${missing.join(", ")}.`);
189
- }
190
-
191
- return {
192
- ...resolved,
193
- missing,
194
- };
195
- }
196
-
197
- export function normalizeAidenIdApiUrl(rawValue) {
198
- return normalizeApiUrl(rawValue);
199
- }
200
-
201
- function buildProvisionHeaders({ apiKey, orgId, projectId, idempotencyKey }) {
202
- return {
203
- "Content-Type": "application/json",
204
- Authorization: `Bearer ${String(apiKey || "").trim()}`,
205
- "X-Org-Id": String(orgId || "").trim(),
206
- "X-Project-Id": String(projectId || "").trim(),
207
- "Idempotency-Key": String(idempotencyKey || "").trim(),
208
- };
209
- }
210
-
211
- function buildReadHeaders({ apiKey, orgId, projectId }) {
212
- return {
213
- Accept: "application/json",
214
- Authorization: `Bearer ${String(apiKey || "").trim()}`,
215
- "X-Org-Id": String(orgId || "").trim(),
216
- "X-Project-Id": String(projectId || "").trim(),
217
- };
218
- }
219
-
220
- function normalizeExtractionPayload(payload = {}) {
221
- if (!payload || typeof payload !== "object") {
222
- return {
223
- otp: null,
224
- primaryActionUrl: null,
225
- confidence: null,
226
- source: "UNKNOWN",
227
- extractedAt: null,
228
- raw: payload,
229
- };
230
- }
231
-
232
- const rawOtp = payload.otp ?? payload.code ?? payload.oneTimeCode ?? null;
233
- const rawPrimaryActionUrl =
234
- payload.primaryActionUrl ?? payload.primary_action_url ?? payload.verificationUrl ?? payload.link ?? null;
235
- const rawConfidence = payload.confidence ?? payload.score ?? payload.extractionConfidence ?? null;
236
- const numericConfidence = Number(rawConfidence);
237
- const normalizedConfidence = Number.isFinite(numericConfidence) ? numericConfidence : null;
238
- const rawSource = payload.source ?? payload.extractionSource ?? payload.engine ?? payload.method ?? null;
239
-
240
- return {
241
- otp: String(rawOtp || "").trim() || null,
242
- primaryActionUrl: String(rawPrimaryActionUrl || "").trim() || null,
243
- confidence: normalizedConfidence,
244
- source: String(rawSource || "").trim() || "UNKNOWN",
245
- extractedAt: String(payload.extractedAt || payload.createdAt || payload.timestamp || "").trim() || null,
246
- raw: payload,
247
- };
248
- }
249
-
250
- function normalizeEventsResponse(payload = {}) {
251
- if (Array.isArray(payload)) {
252
- return {
253
- events: payload,
254
- nextCursor: null,
255
- previousCursor: null,
256
- };
257
- }
258
-
259
- if (!payload || typeof payload !== "object") {
260
- return {
261
- events: [],
262
- nextCursor: null,
263
- previousCursor: null,
264
- };
265
- }
266
-
267
- const events = Array.isArray(payload.events)
268
- ? payload.events
269
- : Array.isArray(payload.items)
270
- ? payload.items
271
- : Array.isArray(payload.data)
272
- ? payload.data
273
- : [];
274
-
275
- return {
276
- events,
277
- nextCursor:
278
- String(payload.nextCursor || payload.next_cursor || payload.cursor || payload.next || "").trim() || null,
279
- previousCursor:
280
- String(payload.previousCursor || payload.previous_cursor || payload.prev || "").trim() || null,
281
- };
282
- }
283
-
284
- async function parseErrorBody(response) {
285
- try {
286
- const payload = await response.json();
287
- return JSON.stringify(payload);
288
- } catch {
289
- try {
290
- return await response.text();
291
- } catch {
292
- return "";
293
- }
294
- }
295
- }
296
-
297
- export async function provisionEmailIdentity({
298
- apiUrl,
299
- apiKey,
300
- orgId,
301
- projectId,
302
- idempotencyKey,
303
- payload,
304
- fetchImpl = fetch,
305
- } = {}) {
306
- if (typeof fetchImpl !== "function") {
307
- throw new Error("fetchImpl must be a function.");
308
- }
309
-
310
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
311
- const requestHeaders = buildProvisionHeaders({
312
- apiKey,
313
- orgId,
314
- projectId,
315
- idempotencyKey,
316
- });
317
-
318
- const response = await fetchImpl(`${normalizedApiUrl}/v1/identities`, {
319
- method: "POST",
320
- headers: requestHeaders,
321
- body: JSON.stringify(payload || {}),
322
- });
323
-
324
- if (!response.ok) {
325
- const details = await parseErrorBody(response);
326
- throw new Error(
327
- `AIdenID provision request failed with status ${response.status}${
328
- details ? `: ${details}` : ""
329
- }`
330
- );
331
- }
332
-
333
- const body = await response.json();
334
- return {
335
- apiUrl: normalizedApiUrl,
336
- response: body,
337
- requestHeaders,
338
- };
339
- }
340
-
341
- export async function revokeIdentity({
342
- apiUrl,
343
- apiKey,
344
- orgId,
345
- projectId,
346
- idempotencyKey,
347
- identityId,
348
- fetchImpl = fetch,
349
- } = {}) {
350
- if (typeof fetchImpl !== "function") {
351
- throw new Error("fetchImpl must be a function.");
352
- }
353
-
354
- const normalizedIdentityId = normalizeIdentityId(identityId);
355
-
356
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
357
- const requestHeaders = buildProvisionHeaders({
358
- apiKey,
359
- orgId,
360
- projectId,
361
- idempotencyKey,
362
- });
363
-
364
- const response = await fetchImpl(
365
- `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedIdentityId)}/revoke`,
366
- {
367
- method: "POST",
368
- headers: requestHeaders,
369
- }
370
- );
371
-
372
- if (!response.ok) {
373
- const details = await parseErrorBody(response);
374
- throw new Error(
375
- `AIdenID revoke request failed with status ${response.status}${details ? `: ${details}` : ""}`
376
- );
377
- }
378
-
379
- const body = await response.json();
380
- return {
381
- apiUrl: normalizedApiUrl,
382
- response: body,
383
- requestHeaders,
384
- };
385
- }
386
-
387
- export async function listIdentityEvents({
388
- apiUrl,
389
- apiKey,
390
- orgId,
391
- projectId,
392
- identityId,
393
- cursor = "",
394
- limit = 50,
395
- fetchImpl = fetch,
396
- } = {}) {
397
- if (typeof fetchImpl !== "function") {
398
- throw new Error("fetchImpl must be a function.");
399
- }
400
-
401
- const normalizedIdentityId = normalizeIdentityId(identityId);
402
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
403
- const normalizedLimit = normalizePositiveInteger(limit, "limit", { min: 1, max: 500 });
404
- const normalizedCursor = String(cursor || "").trim();
405
- const requestHeaders = buildReadHeaders({ apiKey, orgId, projectId });
406
-
407
- const endpoint = new URL(
408
- `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedIdentityId)}/events`
409
- );
410
- endpoint.searchParams.set("limit", String(normalizedLimit));
411
- if (normalizedCursor) {
412
- endpoint.searchParams.set("cursor", normalizedCursor);
413
- }
414
-
415
- const response = await fetchImpl(endpoint.toString(), {
416
- method: "GET",
417
- headers: requestHeaders,
418
- });
419
-
420
- if (!response.ok) {
421
- const details = await parseErrorBody(response);
422
- throw new Error(
423
- `AIdenID identity events request failed with status ${response.status}${details ? `: ${details}` : ""}`
424
- );
425
- }
426
-
427
- const body = await response.json();
428
- const normalized = normalizeEventsResponse(body);
429
- return {
430
- apiUrl: normalizedApiUrl,
431
- response: body,
432
- requestHeaders,
433
- events: normalized.events,
434
- nextCursor: normalized.nextCursor,
435
- previousCursor: normalized.previousCursor,
436
- };
437
- }
438
-
439
- export async function getLatestIdentityExtraction({
440
- apiUrl,
441
- apiKey,
442
- orgId,
443
- projectId,
444
- identityId,
445
- fetchImpl = fetch,
446
- } = {}) {
447
- if (typeof fetchImpl !== "function") {
448
- throw new Error("fetchImpl must be a function.");
449
- }
450
-
451
- const normalizedIdentityId = normalizeIdentityId(identityId);
452
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
453
- const requestHeaders = buildReadHeaders({ apiKey, orgId, projectId });
454
-
455
- const response = await fetchImpl(
456
- `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedIdentityId)}/latest-extraction`,
457
- {
458
- method: "GET",
459
- headers: requestHeaders,
460
- }
461
- );
462
-
463
- if (response.status === 404) {
464
- return {
465
- apiUrl: normalizedApiUrl,
466
- response: null,
467
- requestHeaders,
468
- extraction: normalizeExtractionPayload({}),
469
- notFound: true,
470
- };
471
- }
472
-
473
- if (!response.ok) {
474
- const details = await parseErrorBody(response);
475
- throw new Error(
476
- `AIdenID latest extraction request failed with status ${response.status}${
477
- details ? `: ${details}` : ""
478
- }`
479
- );
480
- }
481
-
482
- const body = await response.json();
483
- const extractionPayload =
484
- body && typeof body === "object" && body.extraction && typeof body.extraction === "object"
485
- ? body.extraction
486
- : body;
487
-
488
- return {
489
- apiUrl: normalizedApiUrl,
490
- response: body,
491
- requestHeaders,
492
- extraction: normalizeExtractionPayload(extractionPayload),
493
- notFound: false,
494
- };
495
- }
496
-
497
- export async function createChildIdentity({
498
- apiUrl,
499
- apiKey,
500
- orgId,
501
- projectId,
502
- parentIdentityId,
503
- idempotencyKey,
504
- payload,
505
- fetchImpl = fetch,
506
- } = {}) {
507
- if (typeof fetchImpl !== "function") {
508
- throw new Error("fetchImpl must be a function.");
509
- }
510
-
511
- const normalizedParentIdentityId = normalizeIdentityId(parentIdentityId);
512
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
513
- const requestHeaders = buildProvisionHeaders({
514
- apiKey,
515
- orgId,
516
- projectId,
517
- idempotencyKey,
518
- });
519
-
520
- const response = await fetchImpl(
521
- `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedParentIdentityId)}/children`,
522
- {
523
- method: "POST",
524
- headers: requestHeaders,
525
- body: JSON.stringify(payload || {}),
526
- }
527
- );
528
-
529
- if (!response.ok) {
530
- const details = await parseErrorBody(response);
531
- throw new Error(
532
- `AIdenID create child request failed with status ${response.status}${details ? `: ${details}` : ""}`
533
- );
534
- }
535
-
536
- const body = await response.json();
537
- return {
538
- apiUrl: normalizedApiUrl,
539
- response: body,
540
- requestHeaders,
541
- };
542
- }
543
-
544
- export async function getIdentityLineage({
545
- apiUrl,
546
- apiKey,
547
- orgId,
548
- projectId,
549
- identityId,
550
- fetchImpl = fetch,
551
- } = {}) {
552
- if (typeof fetchImpl !== "function") {
553
- throw new Error("fetchImpl must be a function.");
554
- }
555
-
556
- const normalizedIdentityId = normalizeIdentityId(identityId);
557
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
558
- const requestHeaders = buildReadHeaders({ apiKey, orgId, projectId });
559
-
560
- const response = await fetchImpl(
561
- `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedIdentityId)}/lineage`,
562
- {
563
- method: "GET",
564
- headers: requestHeaders,
565
- }
566
- );
567
-
568
- if (!response.ok) {
569
- const details = await parseErrorBody(response);
570
- throw new Error(
571
- `AIdenID identity lineage request failed with status ${response.status}${details ? `: ${details}` : ""}`
572
- );
573
- }
574
-
575
- const body = await response.json();
576
- const nodes = Array.isArray(body?.nodes) ? body.nodes : [];
577
- const edges = Array.isArray(body?.edges) ? body.edges : [];
578
- const rootIdentityId = String(body?.rootIdentityId || "").trim() || normalizedIdentityId;
579
- return {
580
- apiUrl: normalizedApiUrl,
581
- response: body,
582
- requestHeaders,
583
- rootIdentityId,
584
- nodes,
585
- edges,
586
- };
587
- }
588
-
589
- export async function revokeIdentityChildren({
590
- apiUrl,
591
- apiKey,
592
- orgId,
593
- projectId,
594
- identityId,
595
- idempotencyKey,
596
- fetchImpl = fetch,
597
- } = {}) {
598
- if (typeof fetchImpl !== "function") {
599
- throw new Error("fetchImpl must be a function.");
600
- }
601
-
602
- const normalizedIdentityId = normalizeIdentityId(identityId);
603
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
604
- const requestHeaders = buildProvisionHeaders({
605
- apiKey,
606
- orgId,
607
- projectId,
608
- idempotencyKey,
609
- });
610
-
611
- const response = await fetchImpl(
612
- `${normalizedApiUrl}/v1/identities/${encodeURIComponent(normalizedIdentityId)}/revoke-children`,
613
- {
614
- method: "POST",
615
- headers: requestHeaders,
616
- }
617
- );
618
-
619
- if (!response.ok) {
620
- const details = await parseErrorBody(response);
621
- throw new Error(
622
- `AIdenID revoke children request failed with status ${response.status}${details ? `: ${details}` : ""}`
623
- );
624
- }
625
-
626
- const body = await response.json();
627
- const revokedIdentityIds = Array.isArray(body?.revokedIdentityIds) ? body.revokedIdentityIds : [];
628
- const revokedCount = Number.isFinite(Number(body?.revokedCount))
629
- ? Number(body.revokedCount)
630
- : revokedIdentityIds.length;
631
- return {
632
- apiUrl: normalizedApiUrl,
633
- response: body,
634
- requestHeaders,
635
- parentIdentityId: String(body?.parentIdentityId || "").trim() || normalizedIdentityId,
636
- revokedCount,
637
- revokedIdentityIds,
638
- };
639
- }
640
-
641
- export async function createDomain({
642
- apiUrl,
643
- apiKey,
644
- orgId,
645
- projectId,
646
- idempotencyKey,
647
- payload,
648
- fetchImpl = fetch,
649
- } = {}) {
650
- if (typeof fetchImpl !== "function") {
651
- throw new Error("fetchImpl must be a function.");
652
- }
653
-
654
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
655
- const requestHeaders = buildProvisionHeaders({
656
- apiKey,
657
- orgId,
658
- projectId,
659
- idempotencyKey,
660
- });
661
-
662
- const response = await fetchImpl(`${normalizedApiUrl}/v1/domains`, {
663
- method: "POST",
664
- headers: requestHeaders,
665
- body: JSON.stringify(payload || {}),
666
- });
667
-
668
- if (!response.ok) {
669
- const details = await parseErrorBody(response);
670
- throw new Error(
671
- `AIdenID domain create request failed with status ${response.status}${details ? `: ${details}` : ""}`
672
- );
673
- }
674
-
675
- const body = await response.json();
676
- return {
677
- apiUrl: normalizedApiUrl,
678
- response: body,
679
- requestHeaders,
680
- };
681
- }
682
-
683
- export async function verifyDomain({
684
- apiUrl,
685
- apiKey,
686
- orgId,
687
- projectId,
688
- domainId,
689
- idempotencyKey,
690
- payload,
691
- fetchImpl = fetch,
692
- } = {}) {
693
- if (typeof fetchImpl !== "function") {
694
- throw new Error("fetchImpl must be a function.");
695
- }
696
-
697
- const normalizedDomainId = normalizeIdentityId(domainId);
698
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
699
- const requestHeaders = buildProvisionHeaders({
700
- apiKey,
701
- orgId,
702
- projectId,
703
- idempotencyKey,
704
- });
705
-
706
- const response = await fetchImpl(
707
- `${normalizedApiUrl}/v1/domains/${encodeURIComponent(normalizedDomainId)}/verify`,
708
- {
709
- method: "POST",
710
- headers: requestHeaders,
711
- body: JSON.stringify(payload || {}),
712
- }
713
- );
714
-
715
- if (!response.ok) {
716
- const details = await parseErrorBody(response);
717
- throw new Error(
718
- `AIdenID domain verify request failed with status ${response.status}${details ? `: ${details}` : ""}`
719
- );
720
- }
721
-
722
- const body = await response.json();
723
- return {
724
- apiUrl: normalizedApiUrl,
725
- response: body,
726
- requestHeaders,
727
- };
728
- }
729
-
730
- export async function freezeDomain({
731
- apiUrl,
732
- apiKey,
733
- orgId,
734
- projectId,
735
- domainId,
736
- idempotencyKey,
737
- payload,
738
- fetchImpl = fetch,
739
- } = {}) {
740
- if (typeof fetchImpl !== "function") {
741
- throw new Error("fetchImpl must be a function.");
742
- }
743
-
744
- const normalizedDomainId = normalizeIdentityId(domainId);
745
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
746
- const requestHeaders = buildProvisionHeaders({
747
- apiKey,
748
- orgId,
749
- projectId,
750
- idempotencyKey,
751
- });
752
-
753
- const response = await fetchImpl(
754
- `${normalizedApiUrl}/v1/domains/${encodeURIComponent(normalizedDomainId)}/freeze`,
755
- {
756
- method: "POST",
757
- headers: requestHeaders,
758
- body: JSON.stringify(payload || {}),
759
- }
760
- );
761
-
762
- if (!response.ok) {
763
- const details = await parseErrorBody(response);
764
- throw new Error(
765
- `AIdenID domain freeze request failed with status ${response.status}${details ? `: ${details}` : ""}`
766
- );
767
- }
768
-
769
- const body = await response.json();
770
- return {
771
- apiUrl: normalizedApiUrl,
772
- response: body,
773
- requestHeaders,
774
- };
775
- }
776
-
777
- export async function createTarget({
778
- apiUrl,
779
- apiKey,
780
- orgId,
781
- projectId,
782
- idempotencyKey,
783
- payload,
784
- fetchImpl = fetch,
785
- } = {}) {
786
- if (typeof fetchImpl !== "function") {
787
- throw new Error("fetchImpl must be a function.");
788
- }
789
-
790
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
791
- const requestHeaders = buildProvisionHeaders({
792
- apiKey,
793
- orgId,
794
- projectId,
795
- idempotencyKey,
796
- });
797
-
798
- const response = await fetchImpl(`${normalizedApiUrl}/v1/targets`, {
799
- method: "POST",
800
- headers: requestHeaders,
801
- body: JSON.stringify(payload || {}),
802
- });
803
-
804
- if (!response.ok) {
805
- const details = await parseErrorBody(response);
806
- throw new Error(
807
- `AIdenID target create request failed with status ${response.status}${details ? `: ${details}` : ""}`
808
- );
809
- }
810
-
811
- const body = await response.json();
812
- return {
813
- apiUrl: normalizedApiUrl,
814
- response: body,
815
- requestHeaders,
816
- };
817
- }
818
-
819
- export async function verifyTarget({
820
- apiUrl,
821
- apiKey,
822
- orgId,
823
- projectId,
824
- targetId,
825
- idempotencyKey,
826
- payload,
827
- fetchImpl = fetch,
828
- } = {}) {
829
- if (typeof fetchImpl !== "function") {
830
- throw new Error("fetchImpl must be a function.");
831
- }
832
-
833
- const normalizedTargetId = normalizeIdentityId(targetId);
834
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
835
- const requestHeaders = buildProvisionHeaders({
836
- apiKey,
837
- orgId,
838
- projectId,
839
- idempotencyKey,
840
- });
841
-
842
- const response = await fetchImpl(
843
- `${normalizedApiUrl}/v1/targets/${encodeURIComponent(normalizedTargetId)}/verify`,
844
- {
845
- method: "POST",
846
- headers: requestHeaders,
847
- body: JSON.stringify(payload || {}),
848
- }
849
- );
850
-
851
- if (!response.ok) {
852
- const details = await parseErrorBody(response);
853
- throw new Error(
854
- `AIdenID target verify request failed with status ${response.status}${details ? `: ${details}` : ""}`
855
- );
856
- }
857
-
858
- const body = await response.json();
859
- return {
860
- apiUrl: normalizedApiUrl,
861
- response: body,
862
- requestHeaders,
863
- };
864
- }
865
-
866
- export async function getTarget({
867
- apiUrl,
868
- apiKey,
869
- orgId,
870
- projectId,
871
- targetId,
872
- fetchImpl = fetch,
873
- } = {}) {
874
- if (typeof fetchImpl !== "function") {
875
- throw new Error("fetchImpl must be a function.");
876
- }
877
-
878
- const normalizedTargetId = normalizeIdentityId(targetId);
879
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
880
- const requestHeaders = buildReadHeaders({ apiKey, orgId, projectId });
881
-
882
- const response = await fetchImpl(
883
- `${normalizedApiUrl}/v1/targets/${encodeURIComponent(normalizedTargetId)}`,
884
- {
885
- method: "GET",
886
- headers: requestHeaders,
887
- }
888
- );
889
-
890
- if (!response.ok) {
891
- const details = await parseErrorBody(response);
892
- throw new Error(
893
- `AIdenID target show request failed with status ${response.status}${details ? `: ${details}` : ""}`
894
- );
895
- }
896
-
897
- const body = await response.json();
898
- return {
899
- apiUrl: normalizedApiUrl,
900
- response: body,
901
- requestHeaders,
902
- };
903
- }
904
-
905
- export async function createTemporarySite({
906
- apiUrl,
907
- apiKey,
908
- orgId,
909
- projectId,
910
- idempotencyKey,
911
- payload,
912
- fetchImpl = fetch,
913
- } = {}) {
914
- if (typeof fetchImpl !== "function") {
915
- throw new Error("fetchImpl must be a function.");
916
- }
917
-
918
- const normalizedApiUrl = normalizeApiUrl(apiUrl);
919
- const requestHeaders = buildProvisionHeaders({
920
- apiKey,
921
- orgId,
922
- projectId,
923
- idempotencyKey,
924
- });
925
-
926
- const response = await fetchImpl(`${normalizedApiUrl}/v1/sites`, {
927
- method: "POST",
928
- headers: requestHeaders,
929
- body: JSON.stringify(payload || {}),
930
- });
931
-
932
- if (!response.ok) {
933
- const details = await parseErrorBody(response);
934
- throw new Error(
935
- `AIdenID site create request failed with status ${response.status}${details ? `: ${details}` : ""}`
936
- );
937
- }
938
-
939
- const body = await response.json();
940
- return {
941
- apiUrl: normalizedApiUrl,
942
- response: body,
943
- requestHeaders,
944
- };
945
- }
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
+ }