@crimson-crawler/crimson-crawler-client 4.1.1

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 (41) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +14 -0
  3. package/README.md +940 -0
  4. package/dist/.package-build.json +29 -0
  5. package/dist/_generated/client.gen.cjs +11 -0
  6. package/dist/_generated/client.gen.d.cts +15 -0
  7. package/dist/_generated/client.gen.d.ts +15 -0
  8. package/dist/_generated/client.gen.js +2 -0
  9. package/dist/_generated/index.cjs +140 -0
  10. package/dist/_generated/index.d.cts +3 -0
  11. package/dist/_generated/index.d.ts +3 -0
  12. package/dist/_generated/index.js +3 -0
  13. package/dist/_generated/sdk.gen.cjs +140 -0
  14. package/dist/_generated/sdk.gen.d.cts +946 -0
  15. package/dist/_generated/sdk.gen.d.ts +946 -0
  16. package/dist/_generated/sdk.gen.js +3 -0
  17. package/dist/_generated/types.gen.cjs +2 -0
  18. package/dist/_generated/types.gen.d.cts +9950 -0
  19. package/dist/_generated/types.gen.d.ts +9950 -0
  20. package/dist/_generated/types.gen.js +1 -0
  21. package/dist/chunk-2X3CCE46.js +294 -0
  22. package/dist/chunk-4CXMKUDH.cjs +783 -0
  23. package/dist/chunk-4HSWOQA6.cjs +328 -0
  24. package/dist/chunk-4PCL3ANB.cjs +190 -0
  25. package/dist/chunk-75ZPJI57.cjs +9 -0
  26. package/dist/chunk-C53EHGN4.js +170 -0
  27. package/dist/chunk-MLKGABMK.js +7 -0
  28. package/dist/chunk-QU4MM663.js +780 -0
  29. package/dist/index.cjs +2507 -0
  30. package/dist/index.d.cts +1283 -0
  31. package/dist/index.d.ts +1283 -0
  32. package/dist/index.js +2487 -0
  33. package/dist/presets-BMN8jy08.d.cts +110 -0
  34. package/dist/presets-BMN8jy08.d.ts +110 -0
  35. package/dist/presets.cjs +79 -0
  36. package/dist/presets.d.cts +1 -0
  37. package/dist/presets.d.ts +1 -0
  38. package/dist/presets.js +2 -0
  39. package/dist/types.gen-ObPczyUH.d.cts +327 -0
  40. package/dist/types.gen-ObPczyUH.d.ts +327 -0
  41. package/package.json +131 -0
package/dist/index.js ADDED
@@ -0,0 +1,2487 @@
1
+ import { CVE_FULL_WALK, IOC_FULL_WALK, CWE_FULL_WALK, TECHNIQUE_FULL, PRODUCT_FULL, PACKAGE_FULL, ATLAS_FULL, CAMPAIGN_FULL, CAPEC_FULL, DEFEND_FULL, DISARM_FULL, GROUP_FULL, LOCATION_FULL, SECTOR_FULL, SOFTWARE_FULL } from './chunk-C53EHGN4.js';
2
+ export { presets_exports as presets } from './chunk-C53EHGN4.js';
3
+ import { enrichCve, enrichIoc, enrichCwe, enrichTechnique, enrichProduct, enrichPackage, searchCti, enrichAtlas, enrichCampaign, enrichCapec, enrichDefend, enrichDisarm, enrichGroup, enrichLocation, enrichSector, enrichSoftware, enrichBatch, enrichPocSource, assessGroupExposure, assessIocPortfolio, assessTechniqueCoverage, assessVulnerabilityExposure, searchCve, searchD3Fend, searchKev, searchKnowledgebase, searchMisp, searchPoc, searchVendor, artifactEnrich, artifactEnrichStatus, inventoryEnrich, inventoryEnrichStatus } from './chunk-2X3CCE46.js';
4
+ import { createClient, client } from './chunk-QU4MM663.js';
5
+ import './chunk-MLKGABMK.js';
6
+
7
+ // src/exceptions.ts
8
+ var CrawlerClientError = class extends Error {
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = "CrawlerClientError";
12
+ }
13
+ };
14
+ var MissingCredentials = class extends CrawlerClientError {
15
+ constructor(message) {
16
+ super(message);
17
+ this.name = "MissingCredentials";
18
+ }
19
+ };
20
+ var UnexpectedStatus = class extends CrawlerClientError {
21
+ constructor(status, body, message) {
22
+ super(message ?? `Unexpected response status ${status}`);
23
+ this.status = status;
24
+ this.body = body;
25
+ this.name = "UnexpectedStatus";
26
+ }
27
+ status;
28
+ body;
29
+ };
30
+
31
+ // src/_auth.ts
32
+ function withApiKeyHeader(input, init, headerName, apiKey, origin) {
33
+ const inherited = init?.headers ?? (input instanceof Request ? input.headers : void 0);
34
+ const headers = new Headers(inherited);
35
+ const raw = typeof input === "string" ? input : input instanceof URL ? input.href : input instanceof Request ? input.url : String(input);
36
+ let sameOrigin;
37
+ try {
38
+ sameOrigin = new URL(raw).origin === origin;
39
+ } catch {
40
+ sameOrigin = true;
41
+ }
42
+ if (sameOrigin) {
43
+ headers.set(headerName, apiKey);
44
+ }
45
+ return headers;
46
+ }
47
+
48
+ // src/url.ts
49
+ function pathSegment(value) {
50
+ return encodeURIComponent(value);
51
+ }
52
+
53
+ // src/ai-reports.ts
54
+ var MAX_BUFFERED_RAW_BYTES = 1e7;
55
+ async function readBufferedText(resp) {
56
+ const declared = Number(resp.headers.get("content-length"));
57
+ if (Number.isFinite(declared) && declared > MAX_BUFFERED_RAW_BYTES) {
58
+ await resp.body?.cancel().catch(() => void 0);
59
+ throw new RangeError(
60
+ `raw response exceeds the ${MAX_BUFFERED_RAW_BYTES}-byte buffer limit`
61
+ );
62
+ }
63
+ if (!resp.body) return "";
64
+ const reader = resp.body.getReader();
65
+ const decoder = new TextDecoder();
66
+ const parts = [];
67
+ let size = 0;
68
+ for (; ; ) {
69
+ const { done, value } = await reader.read();
70
+ if (done) break;
71
+ size += value.byteLength;
72
+ if (size > MAX_BUFFERED_RAW_BYTES) {
73
+ await reader.cancel().catch(() => void 0);
74
+ throw new RangeError(
75
+ `raw response exceeds the ${MAX_BUFFERED_RAW_BYTES}-byte buffer limit`
76
+ );
77
+ }
78
+ parts.push(decoder.decode(value, { stream: true }));
79
+ }
80
+ parts.push(decoder.decode());
81
+ return parts.join("");
82
+ }
83
+ function downloadFilename(disposition, fallback) {
84
+ let candidate;
85
+ const encoded = disposition.match(/filename\*\s*=\s*UTF-8''([^;]+)/i)?.[1]?.trim();
86
+ if (encoded) {
87
+ try {
88
+ candidate = decodeURIComponent(encoded);
89
+ } catch {
90
+ candidate = void 0;
91
+ }
92
+ }
93
+ candidate ??= disposition.match(/filename\s*=\s*"([^"]*)"/i)?.[1];
94
+ candidate ??= disposition.match(/filename\s*=\s*([^;\s]+)/i)?.[1];
95
+ const basename = candidate?.replace(/\\/g, "/").split("/").at(-1)?.trim();
96
+ const hasControl = basename !== void 0 && Array.from(basename).some((ch) => ch < " " || ch === "\x7F");
97
+ if (!basename || basename === "." || basename === ".." || hasControl) {
98
+ return fallback;
99
+ }
100
+ return basename;
101
+ }
102
+ var AiReportsApi = class {
103
+ baseUrl;
104
+ // True ES2022 private field, not TypeScript `private`: `private` is erased at compile
105
+ // time, leaving an enumerable own property that JSON.stringify and
106
+ // util.inspect (so console.log) print in cleartext. `#` is enforced by the
107
+ // runtime and invisible to both.
108
+ #apiKey;
109
+ doFetch;
110
+ constructor(baseUrl, apiKey, doFetch) {
111
+ this.baseUrl = baseUrl.replace(/\/$/, "");
112
+ this.#apiKey = apiKey;
113
+ this.doFetch = doFetch;
114
+ }
115
+ async request(method, path, opts = {}) {
116
+ const url = new URL(`${this.baseUrl}${path}`);
117
+ for (const [k, v] of Object.entries(opts.params ?? {}))
118
+ url.searchParams.set(k, v);
119
+ const resp = await this.doFetch(url, {
120
+ method,
121
+ headers: {
122
+ apikey: this.#apiKey,
123
+ ...opts.json !== void 0 ? { "Content-Type": "application/json" } : {}
124
+ },
125
+ ...opts.json !== void 0 ? { body: JSON.stringify(opts.json) } : {}
126
+ });
127
+ if (!resp.ok) {
128
+ const body = await resp.text().catch(() => "");
129
+ throw new UnexpectedStatus(
130
+ resp.status,
131
+ body,
132
+ `Report Generator API ${resp.status} on ${path}`
133
+ );
134
+ }
135
+ return resp;
136
+ }
137
+ // -- Discovery + templates --------------------------------------------- //
138
+ /** `GET /ai-reports` — the self-documenting endpoint map + your account context. */
139
+ async discovery() {
140
+ return await (await this.request("GET", "/ai-reports")).json();
141
+ }
142
+ /** The built-in report templates — each `{id, name, description?, ai_sections:[{section_type, label}], needs?}`. */
143
+ async listTemplates() {
144
+ const data = await (await this.request("GET", "/ai-reports/templates")).json();
145
+ return data.templates;
146
+ }
147
+ // -- Reports ----------------------------------------------------------- //
148
+ /** Your saved reports (newest first, no content) — `kind=report` artifacts. */
149
+ async listReports() {
150
+ const data = await (await this.request("GET", "/ai-reports/reports")).json();
151
+ return data.reports;
152
+ }
153
+ /** One report in full, including inline `content` (the report HTML). */
154
+ async getReport(reportId) {
155
+ const data = await (await this.request("GET", `/ai-reports/reports/${pathSegment(reportId)}`)).json();
156
+ return data.report;
157
+ }
158
+ /** Read a report's raw HTML into a string buffer (maximum 10,000,000 bytes; not a streaming return type).
159
+ * Resolves `{ content, id, kind, name, format, createdAt }`. */
160
+ async getReportRaw(reportId) {
161
+ const resp = await this.request(
162
+ "GET",
163
+ `/ai-reports/reports/${pathSegment(reportId)}`,
164
+ { params: { raw: "1" } }
165
+ );
166
+ return {
167
+ content: await readBufferedText(resp),
168
+ id: resp.headers.get("x-artifact-id") ?? reportId,
169
+ kind: resp.headers.get("x-artifact-kind") ?? "",
170
+ name: resp.headers.get("x-artifact-name") ?? "",
171
+ format: resp.headers.get("x-artifact-format") ?? "",
172
+ createdAt: resp.headers.get("x-artifact-created") ?? ""
173
+ };
174
+ }
175
+ /**
176
+ * Create a DRAFT report from a template + source artifacts. Renders the scaffold (static +
177
+ * deterministic data sections) and returns the list of AI sections still to fill.
178
+ *
179
+ * Resolves `{ id, name, html, ai_sections: [{section_type, label, ...}], skipped: [...] }`.
180
+ */
181
+ async createDraft(template, options = {}) {
182
+ const body = { template };
183
+ if (options.sourceIds !== void 0) body.source_ids = options.sourceIds;
184
+ if (options.name !== void 0) body.name = options.name;
185
+ return await (await this.request("POST", "/ai-reports/reports", { json: body })).json();
186
+ }
187
+ /**
188
+ * Generate ONE grounded AI section of a draft (omit `sectionType` to fill the next pending one).
189
+ * Resolves `{ section_type, filled, truncated, remaining: [...], complete }`. Throws
190
+ * `UnexpectedStatus` (409) when no sections remain or (502) on a copilot failure.
191
+ */
192
+ async fillSection(reportId, sectionType) {
193
+ const body = {};
194
+ if (sectionType !== void 0) body.section_type = sectionType;
195
+ return await (await this.request(
196
+ "POST",
197
+ `/ai-reports/reports/${pathSegment(reportId)}/sections`,
198
+ { json: body }
199
+ )).json();
200
+ }
201
+ /** Rename a report. Resolves the updated report. */
202
+ async renameReport(reportId, name) {
203
+ const data = await (await this.request(
204
+ "PATCH",
205
+ `/ai-reports/reports/${pathSegment(reportId)}`,
206
+ { json: { name } }
207
+ )).json();
208
+ return data.report;
209
+ }
210
+ /** Delete a report. Resolves `true` on success (404 throws). */
211
+ async deleteReport(reportId) {
212
+ const resp = await this.request(
213
+ "DELETE",
214
+ `/ai-reports/reports/${pathSegment(reportId)}`
215
+ );
216
+ const data = await resp.json();
217
+ return Boolean(data.deleted);
218
+ }
219
+ /**
220
+ * Generate a single grounded section ad-hoc (NOT tied to a stored report) from `sourceIds`.
221
+ * Provide `sectionType` (a template section) and/or a free-text `instruction`. Resolves
222
+ * `{ text, truncated, grounded, unsupported_ids }`.
223
+ */
224
+ async section(sourceIds, options = {}) {
225
+ const body = { source_ids: sourceIds };
226
+ if (options.sectionType !== void 0)
227
+ body.section_type = options.sectionType;
228
+ if (options.instruction !== void 0)
229
+ body.instruction = options.instruction;
230
+ if (options.selection !== void 0) body.selection = options.selection;
231
+ if (options.verbosity !== void 0) body.verbosity = options.verbosity;
232
+ return await (await this.request("POST", "/ai-reports/section", { json: body })).json();
233
+ }
234
+ /**
235
+ * Export a report as `html` or `md`. The body IS the export file.
236
+ *
237
+ * Resolves `{ content, bytes, filename, contentType }`. `filename` is a sanitized basename from
238
+ * `Content-Disposition`. PDF/DOCX are browser-editor-only; browser-authored reports throw 422 here.
239
+ */
240
+ async exportReport(reportId, fmt = "html") {
241
+ const resp = await this.request(
242
+ "GET",
243
+ `/ai-reports/reports/${pathSegment(reportId)}/export/${pathSegment(fmt)}`
244
+ );
245
+ const disposition = resp.headers.get("content-disposition") ?? "";
246
+ const filename = downloadFilename(disposition, `${reportId}.${fmt}`);
247
+ const bytes = new Uint8Array(await resp.arrayBuffer());
248
+ return {
249
+ content: new TextDecoder().decode(bytes),
250
+ bytes,
251
+ filename,
252
+ contentType: resp.headers.get("content-type") ?? ""
253
+ };
254
+ }
255
+ /**
256
+ * Generate a report end-to-end: create the draft, fill every AI section, return the finished
257
+ * report. The convenience over `createDraft` + `fillSection`.
258
+ *
259
+ * If a section's copilot call fails (502), generation stops there and returns what filled so far:
260
+ * the report keeps the sections completed before the failure, the failed section is recorded in
261
+ * `sections` as `{ error: "generation failed", status: 502 }`, and that section plus any after it
262
+ * stay unfilled cards. Re-run `generateReport` or fill the rest individually with `fillSection`.
263
+ *
264
+ * Resolves `{ report, sections: [<fill result per section>], skipped: [...] }`.
265
+ */
266
+ async generateReport(template, options = {}) {
267
+ const draft = await this.createDraft(template, options);
268
+ const reportId = String(draft.id);
269
+ const pending = Array.isArray(draft.ai_sections) ? draft.ai_sections : [];
270
+ const sections = [];
271
+ for (let i = 0; i < pending.length; i++) {
272
+ let result;
273
+ try {
274
+ result = await this.fillSection(reportId);
275
+ } catch (err) {
276
+ if (err instanceof UnexpectedStatus && err.status === 409) break;
277
+ if (err instanceof UnexpectedStatus && err.status === 502) {
278
+ sections.push({ error: "generation failed", status: 502 });
279
+ break;
280
+ }
281
+ throw err;
282
+ }
283
+ sections.push(result);
284
+ if (result.complete) break;
285
+ }
286
+ const report = await this.getReport(reportId);
287
+ return { report, sections, skipped: draft.skipped ?? [] };
288
+ }
289
+ };
290
+
291
+ // src/artifact-manager.ts
292
+ var MAX_BUFFERED_RAW_BYTES2 = 1e7;
293
+ async function readBufferedText2(resp) {
294
+ const declared = Number(resp.headers.get("content-length"));
295
+ if (Number.isFinite(declared) && declared > MAX_BUFFERED_RAW_BYTES2) {
296
+ await resp.body?.cancel().catch(() => void 0);
297
+ throw new RangeError(
298
+ `raw response exceeds the ${MAX_BUFFERED_RAW_BYTES2}-byte buffer limit`
299
+ );
300
+ }
301
+ if (!resp.body) return "";
302
+ const reader = resp.body.getReader();
303
+ const decoder = new TextDecoder();
304
+ const parts = [];
305
+ let size = 0;
306
+ for (; ; ) {
307
+ const { done, value } = await reader.read();
308
+ if (done) break;
309
+ size += value.byteLength;
310
+ if (size > MAX_BUFFERED_RAW_BYTES2) {
311
+ await reader.cancel().catch(() => void 0);
312
+ throw new RangeError(
313
+ `raw response exceeds the ${MAX_BUFFERED_RAW_BYTES2}-byte buffer limit`
314
+ );
315
+ }
316
+ parts.push(decoder.decode(value, { stream: true }));
317
+ }
318
+ parts.push(decoder.decode());
319
+ return parts.join("");
320
+ }
321
+ function decodeHeader(value, fallback) {
322
+ if (!value) return fallback;
323
+ try {
324
+ return decodeURIComponent(value);
325
+ } catch {
326
+ return fallback;
327
+ }
328
+ }
329
+ function downloadFilename2(disposition, fallback) {
330
+ let candidate;
331
+ const encoded = disposition.match(/filename\*\s*=\s*UTF-8''([^;]+)/i)?.[1]?.trim();
332
+ if (encoded) {
333
+ try {
334
+ candidate = decodeURIComponent(encoded);
335
+ } catch {
336
+ candidate = void 0;
337
+ }
338
+ }
339
+ candidate ??= disposition.match(/filename\s*=\s*"([^"]*)"/i)?.[1];
340
+ candidate ??= disposition.match(/filename\s*=\s*([^;\s]+)/i)?.[1];
341
+ const basename = candidate?.replace(/\\/g, "/").split("/").at(-1)?.trim();
342
+ const hasControl = basename !== void 0 && Array.from(basename).some((ch) => ch < " " || ch === "\x7F");
343
+ if (!basename || basename === "." || basename === ".." || hasControl) {
344
+ return fallback;
345
+ }
346
+ return basename;
347
+ }
348
+ var ArtifactManagerApi = class {
349
+ baseUrl;
350
+ // True ES2022 private field, not TypeScript `private`: `private` is erased at compile
351
+ // time, leaving an enumerable own property that JSON.stringify and
352
+ // util.inspect (so console.log) print in cleartext. `#` is enforced by the
353
+ // runtime and invisible to both.
354
+ #apiKey;
355
+ doFetch;
356
+ constructor(baseUrl, apiKey, doFetch) {
357
+ this.baseUrl = baseUrl.replace(/\/$/, "");
358
+ this.#apiKey = apiKey;
359
+ this.doFetch = doFetch;
360
+ }
361
+ async request(method, path, opts = {}) {
362
+ const url = new URL(`${this.baseUrl}${path}`);
363
+ for (const [k, v] of Object.entries(opts.params ?? {}))
364
+ url.searchParams.set(k, v);
365
+ const resp = await this.doFetch(url, {
366
+ method,
367
+ headers: {
368
+ apikey: this.#apiKey,
369
+ ...opts.json !== void 0 ? { "Content-Type": "application/json" } : {}
370
+ },
371
+ ...opts.json !== void 0 ? { body: JSON.stringify(opts.json) } : {}
372
+ });
373
+ if (!resp.ok) {
374
+ const body = await resp.text().catch(() => "");
375
+ throw new UnexpectedStatus(
376
+ resp.status,
377
+ body,
378
+ `Artifact Manager API ${resp.status} on ${path}`
379
+ );
380
+ }
381
+ return resp;
382
+ }
383
+ // -- Discovery ---------------------------------------------------------- //
384
+ /** `GET /artifact-manager` — the self-documenting endpoint map + your account context. */
385
+ async discovery() {
386
+ return (await this.request("GET", "/artifact-manager")).json();
387
+ }
388
+ // -- Artifacts ---------------------------------------------------------- //
389
+ /**
390
+ * List your artifacts (newest first, no content).
391
+ *
392
+ * @param options `kind` (input|enrichment|report) · `folder` (UUID or `"__root__"`)
393
+ * · `since`/`until` (ISO `created_at` window).
394
+ */
395
+ async listArtifacts(options = {}) {
396
+ const params = {};
397
+ if (options.kind) params.kind = options.kind;
398
+ if (options.folder) params.folder = options.folder;
399
+ if (options.since) params.since = options.since;
400
+ if (options.until) params.until = options.until;
401
+ const resp = await this.request("GET", "/artifact-manager/artifacts", {
402
+ params
403
+ });
404
+ return (await resp.json()).artifacts;
405
+ }
406
+ /**
407
+ * Upload input artifacts (max 20/call, ≤10 MB content each).
408
+ *
409
+ * @param artifacts Each `{ name, content, format: "paste"|"file", mime? }`.
410
+ * @param options File into an existing `folderId`, or create one via `newFolderName`.
411
+ * @returns `{ ids, folderId }` — the new artifact ids.
412
+ */
413
+ async uploadArtifacts(artifacts, options = {}) {
414
+ const body = { artifacts };
415
+ if (options.folderId !== void 0) body.folderId = options.folderId;
416
+ if (options.newFolderName !== void 0)
417
+ body.newFolderName = options.newFolderName;
418
+ const resp = await this.request("POST", "/artifact-manager/artifacts", {
419
+ json: body
420
+ });
421
+ return await resp.json();
422
+ }
423
+ /** One artifact in full, including inline `content`. */
424
+ async getArtifact(artifactId) {
425
+ const resp = await this.request(
426
+ "GET",
427
+ `/artifact-manager/artifacts/${pathSegment(artifactId)}`
428
+ );
429
+ return (await resp.json()).artifact;
430
+ }
431
+ /**
432
+ * Read an artifact's raw body into a string buffer (maximum 10,000,000 bytes; this is not a
433
+ * streaming return type). Metadata rides `X-Artifact-*` headers.
434
+ */
435
+ async getArtifactRaw(artifactId) {
436
+ const resp = await this.request(
437
+ "GET",
438
+ `/artifact-manager/artifacts/${pathSegment(artifactId)}`,
439
+ {
440
+ params: { raw: "1" }
441
+ }
442
+ );
443
+ return {
444
+ content: await readBufferedText2(resp),
445
+ id: resp.headers.get("x-artifact-id") ?? artifactId,
446
+ kind: resp.headers.get("x-artifact-kind") ?? "",
447
+ name: decodeHeader(resp.headers.get("x-artifact-name"), artifactId),
448
+ format: resp.headers.get("x-artifact-format") ?? "",
449
+ mime: resp.headers.get("x-artifact-mime") ?? "",
450
+ created_at: resp.headers.get("x-artifact-created") ?? ""
451
+ };
452
+ }
453
+ /**
454
+ * Partial update: rename, star/unstar, and/or move between folders.
455
+ *
456
+ * `folderId: null` moves the artifact back to root; omit it to leave the
457
+ * folder unchanged.
458
+ */
459
+ async updateArtifact(artifactId, update) {
460
+ const body = {};
461
+ if (update.name !== void 0) body.name = update.name;
462
+ if (update.favorite !== void 0) body.favorite = update.favorite;
463
+ if ("folderId" in update) body.folderId = update.folderId;
464
+ const resp = await this.request(
465
+ "PATCH",
466
+ `/artifact-manager/artifacts/${pathSegment(artifactId)}`,
467
+ { json: body }
468
+ );
469
+ return (await resp.json()).artifact;
470
+ }
471
+ /** Delete one artifact. Resolves `true` on success (404 throws). */
472
+ async deleteArtifact(artifactId) {
473
+ const resp = await this.request(
474
+ "DELETE",
475
+ `/artifact-manager/artifacts/${pathSegment(artifactId)}`
476
+ );
477
+ return Boolean((await resp.json()).deleted);
478
+ }
479
+ /** Duplicate an artifact as "Copy of …". Resolves to the new artifact id. */
480
+ async copyArtifact(artifactId) {
481
+ const resp = await this.request(
482
+ "POST",
483
+ `/artifact-manager/artifacts/${pathSegment(artifactId)}/copy`
484
+ );
485
+ return (await resp.json()).id;
486
+ }
487
+ /**
488
+ * Persist a COMPLETED artifact enrichment into your library, by its engine `enrichmentId`.
489
+ *
490
+ * The programmatic equivalent of the portal's "Save enrichment" button. Run `client.enricher.enrich`
491
+ * (`POST /v1/artifact-enrich` → poll), then pass the returned `enrichment_id` here to file the finished
492
+ * report as a `kind=artifact_enrichment` artifact on your account (or use `enrich({ save: true })` to do both in
493
+ * one call). The engine returns the report but never persists it — this is the only way to add it to the
494
+ * Artifact Manager. Idempotent (a repeat returns `{ already_persisted: true }`). Optionally file it into
495
+ * a folder by id (`folderId`) or create one (`newFolderName`). Usage-exempt. Resolves to
496
+ * `{ enrichment_artifact_id }` (or `{ already_persisted: true }`). Save within ~1 h of completion.
497
+ */
498
+ async saveEnrichment(enrichmentId, opts = {}) {
499
+ const body = { enrichment_id: enrichmentId };
500
+ if (opts.folderId || opts.newFolderName) {
501
+ body.folder = {
502
+ folder_id: opts.folderId ?? null,
503
+ new_folder_name: opts.newFolderName ?? null
504
+ };
505
+ }
506
+ const resp = await this.request(
507
+ "POST",
508
+ "/artifact-manager/artifacts/from-enrichment",
509
+ { json: body }
510
+ );
511
+ return await resp.json();
512
+ }
513
+ // -- Bulk operations ---------------------------------------------------- //
514
+ /** Delete many artifacts in one call (≤200/call). Resolves to the number removed. */
515
+ async bulkDelete(artifactIds) {
516
+ const resp = await this.request(
517
+ "POST",
518
+ "/artifact-manager/artifacts/bulk",
519
+ {
520
+ json: { op: "delete", ids: artifactIds }
521
+ }
522
+ );
523
+ return (await resp.json()).count;
524
+ }
525
+ /**
526
+ * Move many artifacts into a folder (≤200/call). `folderId: null` un-files them
527
+ * to root. Resolves to the number moved.
528
+ */
529
+ async moveToFolder(artifactIds, folderId = null) {
530
+ const resp = await this.request(
531
+ "POST",
532
+ "/artifact-manager/artifacts/bulk",
533
+ {
534
+ json: { op: "move", ids: artifactIds, folder_id: folderId }
535
+ }
536
+ );
537
+ return (await resp.json()).count;
538
+ }
539
+ /**
540
+ * Star (`favorite: true`) or unstar (`false`) many artifacts at once (≤200/call).
541
+ * Resolves to the number updated.
542
+ */
543
+ async bulkSetFavorite(artifactIds, favorite) {
544
+ const resp = await this.request(
545
+ "POST",
546
+ "/artifact-manager/artifacts/bulk",
547
+ {
548
+ json: { op: "favorite", ids: artifactIds, favorite }
549
+ }
550
+ );
551
+ return (await resp.json()).count;
552
+ }
553
+ /** Bundle an explicit set of your artifacts into one `.zip` (the bulk "Download .zip"). Enrichments
554
+ * contribute their machine exports under a per-enrichment subfolder; every other kind contributes its raw
555
+ * deliverable. Returns the raw `.zip` bytes. See {@link downloadFolder} for the whole-folder twin. */
556
+ async downloadBundle(artifactIds) {
557
+ const resp = await this.request(
558
+ "POST",
559
+ "/artifact-manager/artifacts/bundle",
560
+ { json: { ids: artifactIds } }
561
+ );
562
+ return new Uint8Array(await resp.arrayBuffer());
563
+ }
564
+ // -- Enrichment ratings ------------------------------------------------------- //
565
+ /** Your thumbs rating on an enrichment + the aggregate counts. */
566
+ async getRating(enrichmentId) {
567
+ const resp = await this.request(
568
+ "GET",
569
+ `/artifact-manager/artifacts/${pathSegment(enrichmentId)}/rating`
570
+ );
571
+ return await resp.json();
572
+ }
573
+ /** Rate an enrichment `"up"`/`"down"`, or clear your rating with `null`. */
574
+ async setRating(enrichmentId, rating) {
575
+ const resp = await this.request(
576
+ "POST",
577
+ `/artifact-manager/artifacts/${pathSegment(enrichmentId)}/rating`,
578
+ {
579
+ json: { rating }
580
+ }
581
+ );
582
+ return await resp.json();
583
+ }
584
+ // -- Enrichment exports ------------------------------------------------------- //
585
+ /** A saved enrichment's machine-export formats (`stix`, `misp`, `csaf`, `vex`, `csv`, …). */
586
+ async listExports(enrichmentId) {
587
+ const resp = await this.request(
588
+ "GET",
589
+ `/artifact-manager/artifacts/${pathSegment(enrichmentId)}/exports`
590
+ );
591
+ return (await resp.json()).formats;
592
+ }
593
+ /** Download one export. The body is the export file; `filename` is a sanitized basename from
594
+ * `Content-Disposition`. Text formats land in `content`; binary XLSX formats in `bytes`. */
595
+ async getExport(enrichmentId, format) {
596
+ const resp = await this.request(
597
+ "GET",
598
+ `/artifact-manager/artifacts/${pathSegment(enrichmentId)}/exports/${pathSegment(format)}`
599
+ );
600
+ const disposition = resp.headers.get("content-disposition") ?? "";
601
+ const filename = downloadFilename2(disposition, format);
602
+ const bytes = new Uint8Array(await resp.arrayBuffer());
603
+ return {
604
+ content: new TextDecoder().decode(bytes),
605
+ bytes,
606
+ filename,
607
+ contentType: resp.headers.get("content-type") ?? ""
608
+ };
609
+ }
610
+ /** Download EVERY machine export of a saved artifact as one `.zip` (one file per format —
611
+ * `stix.json`, `vex.json`, `emass.xlsx`, …). The bulk twin of {@link getExport}, matching the export
612
+ * panel's "Download all (.zip)" button. Works for any saved enrichment / inventory-enrichment /
613
+ * inventory id. Returns the raw `.zip` bytes. */
614
+ async downloadAllExports(enrichmentId) {
615
+ const resp = await this.request(
616
+ "GET",
617
+ `/artifact-manager/artifacts/${pathSegment(enrichmentId)}/exports/all`
618
+ );
619
+ return new Uint8Array(await resp.arrayBuffer());
620
+ }
621
+ // -- Enrichment compare ------------------------------------------------------- //
622
+ /**
623
+ * Difference matrix across 2–12 of your saved enrichments (oldest → newest). Each
624
+ * row is one finding's trajectory: new / resolved / changed / persistent.
625
+ */
626
+ async compareEnrichments(enrichmentIds) {
627
+ const resp = await this.request(
628
+ "GET",
629
+ "/artifact-manager/enrichment-compare",
630
+ {
631
+ params: { ids: enrichmentIds.join(",") }
632
+ }
633
+ );
634
+ return (await resp.json()).matrix;
635
+ }
636
+ // -- Folders ------------------------------------------------------------ //
637
+ /** Your folders, each with a live `artifact_count`. */
638
+ async listFolders() {
639
+ const resp = await this.request("GET", "/artifact-manager/folders");
640
+ return (await resp.json()).folders;
641
+ }
642
+ /** Create a folder. Resolves to its id. */
643
+ async createFolder(name) {
644
+ const resp = await this.request("POST", "/artifact-manager/folders", {
645
+ json: { name }
646
+ });
647
+ return (await resp.json()).id;
648
+ }
649
+ /** Rename a folder. */
650
+ async renameFolder(folderId, name) {
651
+ const resp = await this.request(
652
+ "PATCH",
653
+ `/artifact-manager/folders/${pathSegment(folderId)}`,
654
+ { json: { name } }
655
+ );
656
+ return await resp.json();
657
+ }
658
+ /** Delete a folder — its artifacts move back to root, never deleted with it. */
659
+ async deleteFolder(folderId) {
660
+ const resp = await this.request(
661
+ "DELETE",
662
+ `/artifact-manager/folders/${pathSegment(folderId)}`
663
+ );
664
+ return Boolean((await resp.json()).deleted);
665
+ }
666
+ /** Download every artifact filed under a folder as one `<folder>.zip` (the folder "Download .zip").
667
+ * Enrichments contribute their machine exports under a per-enrichment subfolder; every other kind
668
+ * contributes its raw deliverable. Returns the raw `.zip` bytes. */
669
+ async downloadFolder(folderId) {
670
+ const resp = await this.request(
671
+ "GET",
672
+ `/artifact-manager/folders/${pathSegment(folderId)}/exports/all`
673
+ );
674
+ return new Uint8Array(await resp.arrayBuffer());
675
+ }
676
+ };
677
+
678
+ // src/_poll.ts
679
+ function timeoutError(enrichmentId) {
680
+ return new Error(
681
+ `enrichment ${enrichmentId} did not finish within the timeout`
682
+ );
683
+ }
684
+ function remainingMs(deadline) {
685
+ return deadline - performance.now();
686
+ }
687
+ var TIMED_OUT = /* @__PURE__ */ Symbol("poll-deadline-elapsed");
688
+ async function beforeDeadline(operation, remaining, enrichmentId) {
689
+ if (remaining <= 0) throw timeoutError(enrichmentId);
690
+ let cancelDeadline = () => {
691
+ };
692
+ const deadline = new Promise((resolve) => {
693
+ const timer = setTimeout(() => resolve(TIMED_OUT), remaining);
694
+ cancelDeadline = () => clearTimeout(timer);
695
+ });
696
+ void Promise.resolve(operation).catch(() => void 0);
697
+ try {
698
+ const outcome = await Promise.race([operation, deadline]);
699
+ if (outcome === TIMED_OUT) throw timeoutError(enrichmentId);
700
+ return outcome;
701
+ } finally {
702
+ cancelDeadline();
703
+ }
704
+ }
705
+ async function emit(onProgress, job, remaining, enrichmentId) {
706
+ if (!onProgress) return;
707
+ const callback = Promise.resolve().then(() => onProgress(job)).then(() => void 0).catch(() => void 0);
708
+ await beforeDeadline(callback, remaining, enrichmentId);
709
+ }
710
+ function validatePollOptions(pollIntervalMs, timeoutMs) {
711
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
712
+ throw new RangeError("timeoutMs must be finite and non-negative");
713
+ }
714
+ if (!Number.isFinite(pollIntervalMs) || pollIntervalMs < 0) {
715
+ throw new RangeError("pollIntervalMs must be finite and non-negative");
716
+ }
717
+ }
718
+ async function pollUntilDone(request, enrichmentId, statusPath, opts) {
719
+ validatePollOptions(opts.pollIntervalMs, opts.timeoutMs);
720
+ const deadline = performance.now() + opts.timeoutMs;
721
+ for (; ; ) {
722
+ let remaining = remainingMs(deadline);
723
+ const resp = await beforeDeadline(
724
+ request("GET", statusPath, remaining),
725
+ remaining,
726
+ enrichmentId
727
+ );
728
+ remaining = remainingMs(deadline);
729
+ const job = await beforeDeadline(
730
+ resp.json(),
731
+ remaining,
732
+ enrichmentId
733
+ );
734
+ remaining = remainingMs(deadline);
735
+ await emit(opts.onProgress, job, remaining, enrichmentId);
736
+ if (remainingMs(deadline) <= 0) throw timeoutError(enrichmentId);
737
+ if (job.status === "done") return job;
738
+ if (job.status === "error") {
739
+ throw new UnexpectedStatus(
740
+ 502,
741
+ "",
742
+ `enrichment ${enrichmentId} errored: ${String(job.error)}`
743
+ );
744
+ }
745
+ remaining = remainingMs(deadline);
746
+ await beforeDeadline(
747
+ new Promise(
748
+ (resolve) => setTimeout(resolve, Math.min(opts.pollIntervalMs, remaining))
749
+ ),
750
+ remaining,
751
+ enrichmentId
752
+ );
753
+ if (remainingMs(deadline) <= 0) throw timeoutError(enrichmentId);
754
+ }
755
+ }
756
+
757
+ // src/ingest.ts
758
+ function assembleBriefing(report, meta) {
759
+ const seen = /* @__PURE__ */ new Map();
760
+ const assets = Array.isArray(report.assets) ? report.assets : [];
761
+ for (const asset of assets) {
762
+ const product = asset.product || asset.name || "\u2014";
763
+ const cves = Array.isArray(asset.top_cves) ? asset.top_cves : [];
764
+ for (const cve of cves) {
765
+ const cid = cve.cve_id;
766
+ if (!cid) continue;
767
+ const weap = cve.weaponization_score || 0;
768
+ const prev = seen.get(cid);
769
+ if (!prev || weap > (prev.weaponization_score || 0)) {
770
+ seen.set(cid, {
771
+ cve_id: cid,
772
+ product,
773
+ weaponization_score: weap,
774
+ kev: Boolean(cve.kev),
775
+ reason: cve.kev ? "KEV-listed \u2014 patch now" : "High weaponization"
776
+ });
777
+ }
778
+ }
779
+ }
780
+ const actions = [...seen.values()].sort(
781
+ (a, b) => (a.kev ? 0 : 1) - (b.kev ? 0 : 1) || (b.weaponization_score || 0) - (a.weaponization_score || 0)
782
+ ).slice(0, 10);
783
+ const out = {
784
+ format: meta.format,
785
+ parsed_count: meta.parsedCount,
786
+ enrichment_id: meta.enrichmentId,
787
+ report,
788
+ recommended_actions: actions
789
+ };
790
+ if (meta.truncated) out.truncated = meta.truncated;
791
+ return out;
792
+ }
793
+ async function ingestScan(invApi, content, format, options = {}) {
794
+ const parsed = await invApi.parseScan(content, format);
795
+ const items = Array.isArray(parsed.items) ? parsed.items : [];
796
+ const fmt = typeof parsed.format === "string" ? parsed.format : format;
797
+ if (items.length === 0)
798
+ return { format: fmt, parsed_count: 0, enrichment_id: null, empty: true };
799
+ const result = await invApi.enrichItems(items, options);
800
+ return assembleBriefing(result.report || {}, {
801
+ format: fmt,
802
+ parsedCount: items.length,
803
+ truncated: parsed.truncated,
804
+ enrichmentId: result.enrichment_id
805
+ });
806
+ }
807
+
808
+ // src/inventory-manager.ts
809
+ function wireContent(content) {
810
+ if (typeof content === "string") return content;
811
+ if (typeof Buffer !== "undefined")
812
+ return Buffer.from(content).toString("base64");
813
+ let bin = "";
814
+ const chunk = 32768;
815
+ for (let i = 0; i < content.length; i += chunk)
816
+ bin += String.fromCharCode(...content.subarray(i, i + chunk));
817
+ return btoa(bin);
818
+ }
819
+ function wireSources(sources) {
820
+ return sources.map((s) => ({ ...s, content: wireContent(s.content) }));
821
+ }
822
+ function inventoryBody(inventoryName, o) {
823
+ const body = { inventory_name: inventoryName };
824
+ if (o.description !== void 0) body.description = o.description;
825
+ if (o.items !== void 0) body.items = o.items;
826
+ if (o.monitoring !== void 0) body.monitoring = o.monitoring;
827
+ if (o.linkedArtifactIds !== void 0)
828
+ body.linked_artifact_ids = o.linkedArtifactIds;
829
+ return body;
830
+ }
831
+ var InventoryManagerApi = class {
832
+ baseUrl;
833
+ // True ES2022 private field, not TypeScript `private`: `private` is erased at compile
834
+ // time, leaving an enumerable own property that JSON.stringify and
835
+ // util.inspect (so console.log) print in cleartext. `#` is enforced by the
836
+ // runtime and invisible to both.
837
+ #apiKey;
838
+ doFetch;
839
+ constructor(baseUrl, apiKey, doFetch) {
840
+ this.baseUrl = baseUrl.replace(/\/$/, "");
841
+ this.#apiKey = apiKey;
842
+ this.doFetch = doFetch;
843
+ }
844
+ async request(method, path, opts = {}) {
845
+ const url = new URL(`${this.baseUrl}${path}`);
846
+ for (const [k, v] of Object.entries(opts.params ?? {}))
847
+ url.searchParams.set(k, v);
848
+ const init = {
849
+ method,
850
+ headers: {
851
+ apikey: this.#apiKey,
852
+ ...opts.json !== void 0 ? { "Content-Type": "application/json" } : {}
853
+ },
854
+ ...opts.json !== void 0 ? { body: JSON.stringify(opts.json) } : {}
855
+ };
856
+ const resp = opts.timeoutMs === void 0 ? await this.doFetch(url, init) : await this.doFetch(
857
+ new Request(url, {
858
+ ...init,
859
+ signal: AbortSignal.timeout(
860
+ Math.max(1, Math.ceil(opts.timeoutMs))
861
+ )
862
+ })
863
+ );
864
+ if (!resp.ok) {
865
+ const body = await resp.text().catch(() => "");
866
+ throw new UnexpectedStatus(
867
+ resp.status,
868
+ body,
869
+ `Inventory Manager API ${resp.status} on ${path}`
870
+ );
871
+ }
872
+ return resp;
873
+ }
874
+ /**
875
+ * List your Inventory Manager inventories — each a continuously-monitored context window
876
+ * (asset inventory + attached artifacts + saved enrichment history). Newest first, no content.
877
+ */
878
+ async listInventories() {
879
+ const resp = await this.request("GET", "/inventory-manager/inventories");
880
+ return (await resp.json()).inventories;
881
+ }
882
+ /**
883
+ * One inventory as a manifest: `{ inventory_name, description, monitoring, inventory[], attached[],
884
+ * enrichments[] }`. Pull specific artifacts/enrichments via the Artifact Manager API.
885
+ */
886
+ async getInventory(inventoryId) {
887
+ const resp = await this.request(
888
+ "GET",
889
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}`
890
+ );
891
+ return await resp.json();
892
+ }
893
+ /**
894
+ * An inventory as a one-shot, bounded context bundle with artifact provenance and delimiters.
895
+ * Returns `{ id, name, inventory_name, description, monitoring, stats, context }`. `context`
896
+ * starts with a safe prompt preamble that labels the enclosed inventory and artifact text as
897
+ * untrusted data.
898
+ */
899
+ async getInventoryContext(inventoryId) {
900
+ const resp = await this.request(
901
+ "GET",
902
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}/context`
903
+ );
904
+ return await resp.json();
905
+ }
906
+ /**
907
+ * List an inventory's saved enrichment history — the inventory's `inventory_enrichment` artifacts (newest first,
908
+ * no content; each row's `meta` carries the card stats: asset/CVE/KEV counts, scanned-at, monitoring
909
+ * delta). The data behind the UI's "Previous enrichments" strip.
910
+ */
911
+ async listEnrichments(inventoryId) {
912
+ const resp = await this.request(
913
+ "GET",
914
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}/enrichments`
915
+ );
916
+ return (await resp.json()).enrichments;
917
+ }
918
+ /**
919
+ * CVE-matched difference matrix across 2–12 of your saved INVENTORY enrichments (oldest → newest). The
920
+ * inventory counterpart of `client.artifactManager.compareEnrichments`: each row is one CVE's trajectory —
921
+ * new / resolved / changed / persistent — across the selected inventory enrichments. Returns the `matrix`
922
+ * object (`columns`, `rows`, `counts`).
923
+ */
924
+ async compareEnrichments(enrichmentIds) {
925
+ const resp = await this.request(
926
+ "GET",
927
+ "/inventory-manager/inventories/compare",
928
+ {
929
+ params: { ids: enrichmentIds.join(",") }
930
+ }
931
+ );
932
+ return (await resp.json()).matrix;
933
+ }
934
+ /**
935
+ * Create an Inventory Manager inventory (a continuously-monitored context window).
936
+ *
937
+ * @param inventoryName The inventory's display name.
938
+ * @param options `description`, `items` (asset inventory — each `{ product, vendor?, versions?,
939
+ * ecosystem?, category?, criticality?, notes? }`), `monitoring` (always full depth — no fast/lite
940
+ * mode), `linkedArtifactIds`.
941
+ * @returns `{ id, item_count }`.
942
+ */
943
+ async createInventory(inventoryName, options = {}) {
944
+ const resp = await this.request("POST", "/inventory-manager/inventories", {
945
+ json: inventoryBody(inventoryName, options)
946
+ });
947
+ return await resp.json();
948
+ }
949
+ /**
950
+ * Update an inventory's definition (name, description, inventory, monitoring, attachments).
951
+ * This is a **partial merge** (PATCH): only the fields you pass change — omitted fields are PRESERVED,
952
+ * including the asset-group metadata and daily-report config this method doesn't expose. `inventoryName`
953
+ * is still required by the API. Resolves `{ id, item_count }`.
954
+ */
955
+ async updateInventory(inventoryId, options) {
956
+ const resp = await this.request(
957
+ "PATCH",
958
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}`,
959
+ { json: inventoryBody(options.inventoryName, options) }
960
+ );
961
+ return await resp.json();
962
+ }
963
+ /**
964
+ * Create an inventory by IMPORTING an asset-inventory file (you PICK the format — no auto-detect).
965
+ *
966
+ * @param options `format` — one of `json` (asset JSON), `sbom` (CycloneDX / SPDX SBOM), `csv`,
967
+ * `nmap` (nmap `-sV` XML), `list` (CPE / purl list), `grype`, `trivy` (SCA JSON), `depcheck`
968
+ * (OWASP Dependency-Check JSON), `nessus` (`.nessus` XML), `gvm` (OpenVAS / Greenbone XML);
969
+ * `content` — the file's text; optional `inventoryName` / `description` (override
970
+ * anything the file carries).
971
+ * @returns `{ id, item_count, imported, format, truncated? }`.
972
+ */
973
+ async importInventory(options) {
974
+ const body = {
975
+ format: options.format,
976
+ content: wireContent(options.content)
977
+ };
978
+ if (options.inventoryName !== void 0)
979
+ body.inventory_name = options.inventoryName;
980
+ if (options.description !== void 0)
981
+ body.description = options.description;
982
+ if (options.inventoryId !== void 0) {
983
+ body.inventory_id = options.inventoryId;
984
+ body.mode = options.mode ?? "replace";
985
+ }
986
+ const resp = await this.request(
987
+ "POST",
988
+ "/inventory-manager/inventories/import",
989
+ { json: body }
990
+ );
991
+ return await resp.json();
992
+ }
993
+ /**
994
+ * Parse + COMBINE several scan / inventory files into ONE deduped asset set WITHOUT saving (the
995
+ * multi-source twin of {@link parseScan}). Stage a CSV + an nmap scan + an SBOM and merge them; duplicate
996
+ * assets are deduped across sources, versions + named groups unioned, the set capped at 200.
997
+ *
998
+ * @param sources A list of `{ content, format?, label? }`. The `format` is **optional** — omit it and the
999
+ * file's format is auto-detected from its content (+ `label` as a filename hint); pin a `format` only to
1000
+ * override. A binary `xlsx` source can't be sniffed, so it needs `format: "xlsx"` + `Uint8Array` content
1001
+ * (base64-encoded on the wire). A source that fails to parse is ISOLATED (it appears in `per_source` with
1002
+ * its `error`, contributing nothing — never failing the whole call).
1003
+ * @returns `{ items, count, asset_groups, truncated?, per_source: [{ label, contributed, truncated?, error? }] }`.
1004
+ */
1005
+ async parseMulti(sources) {
1006
+ const resp = await this.request(
1007
+ "POST",
1008
+ "/inventory-manager/inventories/parse-multi",
1009
+ { json: { sources: wireSources(sources) } }
1010
+ );
1011
+ return await resp.json();
1012
+ }
1013
+ /**
1014
+ * Import + COMBINE several files into ONE inventory in a single call (the multi-source twin of
1015
+ * {@link importInventory}). Each source parses in isolation then merges via the same dedup brain as
1016
+ * {@link parseMulti}. No `inventoryId` CREATES a new inventory; with `inventoryId` the combined assets go
1017
+ * INTO it (`mode` replace / append), preserving attachments / monitoring.
1018
+ */
1019
+ async importMulti(options) {
1020
+ const body = {
1021
+ sources: wireSources(options.sources)
1022
+ };
1023
+ if (options.inventoryName !== void 0)
1024
+ body.inventory_name = options.inventoryName;
1025
+ if (options.description !== void 0)
1026
+ body.description = options.description;
1027
+ if (options.inventoryId !== void 0) {
1028
+ body.inventory_id = options.inventoryId;
1029
+ body.mode = options.mode ?? "replace";
1030
+ }
1031
+ const resp = await this.request(
1032
+ "POST",
1033
+ "/inventory-manager/inventories/import",
1034
+ { json: body }
1035
+ );
1036
+ return await resp.json();
1037
+ }
1038
+ /**
1039
+ * REPLACE an inventory's asset inventory, PRESERVING its name / description / attached artifacts /
1040
+ * monitoring / alert-prefs (the safe alternative to {@link updateInventory}, which resets omitted
1041
+ * fields). To edit one field of one asset: {@link getInventory}, change the item in `inventory`, and
1042
+ * replace it back. Resolves `{ id, item_count, mode }`.
1043
+ */
1044
+ async replaceAssets(inventoryId, items) {
1045
+ const resp = await this.request(
1046
+ "PATCH",
1047
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}/assets`,
1048
+ {
1049
+ json: { items, mode: "replace" }
1050
+ }
1051
+ );
1052
+ return await resp.json();
1053
+ }
1054
+ /** APPEND assets to an inventory's inventory, preserving everything else. Resolves `{ id, item_count, mode }`. */
1055
+ async addAssets(inventoryId, items) {
1056
+ const resp = await this.request(
1057
+ "PATCH",
1058
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}/assets`,
1059
+ {
1060
+ json: { items, mode: "append" }
1061
+ }
1062
+ );
1063
+ return await resp.json();
1064
+ }
1065
+ /**
1066
+ * Apply a recommended upgrade — set the matched asset's version to the published fix the Inventory
1067
+ * Enricher surfaced (`recommended_fix_version` / `recommended_fix_version_kev`), PRESERVING everything
1068
+ * else on the inventory. Match is by `product` (case-insensitive; `vendor` disambiguates duplicate
1069
+ * product names). Writes the inventory only — it does NOT re-enrich (the next enrichment / daily monitor
1070
+ * confirms the CVEs cleared). Resolves `{ id, product, version, item_count }` (404 when no asset matches).
1071
+ */
1072
+ async applyAssetFix(inventoryId, product, version, vendor) {
1073
+ const json = { product, version };
1074
+ if (vendor !== void 0) json.vendor = vendor;
1075
+ const resp = await this.request(
1076
+ "PATCH",
1077
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}/asset-version`,
1078
+ { json }
1079
+ );
1080
+ return await resp.json();
1081
+ }
1082
+ /** List an inventory's asset-inventory export formats (`json` / `csv` / `cyclonedx` / `spdx`). */
1083
+ async listExportFormats(inventoryId) {
1084
+ const resp = await this.request(
1085
+ "GET",
1086
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}/export`
1087
+ );
1088
+ return (await resp.json()).formats;
1089
+ }
1090
+ /**
1091
+ * Export an inventory's asset inventory as a file — the resolved value IS the file. Resolves a
1092
+ * `string` for the text formats and a `Uint8Array` for the binary `workbook` (write it straight to
1093
+ * a `.xlsx` file).
1094
+ *
1095
+ * @param inventoryId The inventory id.
1096
+ * @param format `json` / `csv` / `list` (CPE/purl) / `cyclonedx` / `spdx` (3.0.1) / `spdx2` (SPDX 2.3)
1097
+ * / `workbook` (binary Excel .xlsx). `json` / `csv` / `list` round-trip back through
1098
+ * {@link importInventory}. Defaults to `json`.
1099
+ */
1100
+ async exportInventory(inventoryId, format = "json") {
1101
+ const resp = await this.request(
1102
+ "GET",
1103
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}/export/${pathSegment(format)}`
1104
+ );
1105
+ return format === "workbook" ? new Uint8Array(await resp.arrayBuffer()) : await resp.text();
1106
+ }
1107
+ /** Delete an inventory. Resolves `true` on success (404 throws). */
1108
+ async deleteInventory(inventoryId) {
1109
+ const resp = await this.request(
1110
+ "DELETE",
1111
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}`
1112
+ );
1113
+ return Boolean((await resp.json()).deleted);
1114
+ }
1115
+ /** Link an existing artifact to an inventory. Resolves to `{ ok, linked, already }`. */
1116
+ async attachToInventory(inventoryId, artifactId) {
1117
+ const resp = await this.request(
1118
+ "POST",
1119
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}/attach`,
1120
+ {
1121
+ json: { artifactId }
1122
+ }
1123
+ );
1124
+ return await resp.json();
1125
+ }
1126
+ /** Remove one attached artifact from an inventory (the inverse of {@link attachToInventory}).
1127
+ * Atomic server-side operation that preserves every other field; idempotent. Resolves
1128
+ * `{ ok, linked, removed }`. */
1129
+ async detachFromInventory(inventoryId, artifactId) {
1130
+ const resp = await this.request(
1131
+ "POST",
1132
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}/detach`,
1133
+ { json: { artifactId } }
1134
+ );
1135
+ return await resp.json();
1136
+ }
1137
+ /**
1138
+ * REPLACE an inventory's attached reference artifacts in one call (the bulk twin of
1139
+ * {@link attachToInventory}), PRESERVING its inventory / monitoring / alert-prefs. Only attachable
1140
+ * kinds (`input` / `enrichment` / `report`) are kept; inventories and inventory enrichments are skipped. Deduped +
1141
+ * capped at 100. Resolves `{ id, linked_count, attached, skipped, mode }`.
1142
+ */
1143
+ async setAttachments(inventoryId, artifactIds) {
1144
+ const resp = await this.request(
1145
+ "PATCH",
1146
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}/attachments`,
1147
+ {
1148
+ json: { artifact_ids: artifactIds, mode: "replace" }
1149
+ }
1150
+ );
1151
+ return await resp.json();
1152
+ }
1153
+ /** APPEND several artifacts to an inventory's attachments in one call (bulk {@link attachToInventory});
1154
+ * same filtering/cap/return as {@link setAttachments}. */
1155
+ async addAttachments(inventoryId, artifactIds) {
1156
+ const resp = await this.request(
1157
+ "PATCH",
1158
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}/attachments`,
1159
+ {
1160
+ json: { artifact_ids: artifactIds, mode: "append" }
1161
+ }
1162
+ );
1163
+ return await resp.json();
1164
+ }
1165
+ /** Toggle an inventory's daily monitoring (= daily enrichment). Routes through the automation endpoint
1166
+ * (partial read-modify-write) so assets, attachments, asset groups, AND the daily-report config are
1167
+ * all preserved. Enrichments always run at full depth. Resolves `{ id, automation }`. */
1168
+ async setMonitoring(inventoryId, monitoring) {
1169
+ return this.setAutomation(inventoryId, { monitoring });
1170
+ }
1171
+ /** Star (`favorite: true`) or unstar (`false`) an inventory — the same ★ the inventory cards show. A
1172
+ * favorite-only PATCH that leaves the asset inventory / attachments / monitoring / automation untouched.
1173
+ * `listInventories` + `getInventory` echo `favorite` back. Usage-exempt. Resolves `{ id, favorite }`. */
1174
+ async setFavorite(inventoryId, favorite = true) {
1175
+ const resp = await this.request(
1176
+ "PATCH",
1177
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}`,
1178
+ { json: { favorite } }
1179
+ );
1180
+ return await resp.json();
1181
+ }
1182
+ /** Read an inventory's DAILY-AUTOMATION config (the programmatic twin of the Automation modal):
1183
+ * `{ monitoring, daily_enrichment_email, daily_report, daily_report_email,
1184
+ * daily_report_template, daily_enrichment_next_run_at, custom_template_pinned }`. ONE pipeline on ONE
1185
+ * timer: `daily_enrichment_next_run_at` is the epoch-ms countdown (null when monitoring is off); the
1186
+ * daily report rides the same pipeline (right after the enrichment), no timer of its own. Usage-exempt. */
1187
+ async getAutomation(inventoryId) {
1188
+ const resp = await this.request(
1189
+ "GET",
1190
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}/automation`
1191
+ );
1192
+ return await resp.json();
1193
+ }
1194
+ /** Manage an inventory's daily automation — set ONLY the fields you pass (partial read-modify-write,
1195
+ * preserving assets/attachments). `monitoring` = the daily enrichment; `dailyReport` = ALSO generate a
1196
+ * Report-Generator report from `dailyReportTemplate` (a built-in template id, e.g. `project_brief`) right
1197
+ * after each daily enrichment, off its fresh findings. ONE pipeline: `dailyReport` REQUIRES `monitoring` —
1198
+ * enabling it while monitoring is off rejects with a 400 (`UnexpectedStatus`); turning monitoring off
1199
+ * cascades the report off. Each job's `*Email` toggle controls whether it emails the owner. The pipeline
1200
+ * runs on the owner's key when the daily cron fires (the enrichment counts toward usage then). Resolves
1201
+ * `{ id, automation }`. */
1202
+ async setAutomation(inventoryId, options) {
1203
+ const body = {};
1204
+ if (options.monitoring !== void 0) body.monitoring = options.monitoring;
1205
+ if (options.dailyEnrichmentEmail !== void 0)
1206
+ body.daily_enrichment_email = options.dailyEnrichmentEmail;
1207
+ if (options.dailyReport !== void 0)
1208
+ body.daily_report = options.dailyReport;
1209
+ if (options.dailyReportEmail !== void 0)
1210
+ body.daily_report_email = options.dailyReportEmail;
1211
+ if (options.dailyReportTemplate !== void 0)
1212
+ body.daily_report_template = options.dailyReportTemplate;
1213
+ const resp = await this.request(
1214
+ "PUT",
1215
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}/automation`,
1216
+ { json: body }
1217
+ );
1218
+ return await resp.json();
1219
+ }
1220
+ /**
1221
+ * Enrich an inventory's inventory end-to-end against the /v1 engine: submit → poll → return the report.
1222
+ *
1223
+ * Reads the inventory's asset inventory (`GET /inventory-manager/inventories/{id}`), submits those assets
1224
+ * to the Threat Inventory Enricher (`POST /v1/inventory-enrich`, always full depth — there is no fast/lite
1225
+ * mode), polls until done, and resolves to the enrichment report.
1226
+ *
1227
+ * The enrichment submit is enrichment compute and **counts toward your usage** (it rides your key to
1228
+ * `/v1/inventory-enrich`); reading the inventory and polling do not.
1229
+ *
1230
+ * Resolves to `{ enrichment_id, report }`. If the inventory's inventory is empty this short-circuits and
1231
+ * resolves to `{ enrichment_id: null, empty: true }` without submitting. Throws `UnexpectedStatus` on a
1232
+ * non-2xx (or enrichment error), or `Error` if the enrichment doesn't finish within `timeoutMs`.
1233
+ */
1234
+ async enrichInventory(inventoryId, options = {}) {
1235
+ validatePollOptions(
1236
+ options.pollIntervalMs ?? 3e3,
1237
+ options.timeoutMs ?? 3e5
1238
+ );
1239
+ const manifest = await this.getInventory(inventoryId);
1240
+ const items = Array.isArray(manifest.inventory) ? manifest.inventory : [];
1241
+ if (items.length === 0) return { enrichment_id: null, empty: true };
1242
+ const doAttach = options.enrichAttachments ?? manifest.enrich_attachments === true;
1243
+ let attachmentsText;
1244
+ let attachmentsFiles;
1245
+ let attachmentOmissions = [];
1246
+ if (doAttach) {
1247
+ const ids = (Array.isArray(manifest.attached) ? manifest.attached : []).map((a) => a?.id).filter((x) => typeof x === "string");
1248
+ const resolved = await this.resolveAttachments(ids);
1249
+ attachmentsText = resolved.text;
1250
+ if (resolved.files.length) attachmentsFiles = resolved.files;
1251
+ attachmentOmissions = resolved.omissions;
1252
+ if (options.strictAttachments && attachmentOmissions.length) {
1253
+ throw new Error(
1254
+ `unable to resolve ${attachmentOmissions.length} requested attachment(s): ${attachmentOmissions.map((omission) => omission.attachment_id).join(", ")}`
1255
+ );
1256
+ }
1257
+ }
1258
+ const result = await this.enrichItems(items, {
1259
+ ...options,
1260
+ attachmentsText,
1261
+ attachmentsFiles
1262
+ });
1263
+ if (doAttach) result.attachment_omissions = attachmentOmissions;
1264
+ if (options.save && result.enrichment_id) {
1265
+ result.saved = await this.saveEnrichment(
1266
+ inventoryId,
1267
+ result.enrichment_id
1268
+ );
1269
+ }
1270
+ return result;
1271
+ }
1272
+ /** Fetch the inventory's attached artifacts (≤20) and split them for the engine. Resolution is
1273
+ * permissive: every skipped attachment is returned in `omissions`; callers that need complete
1274
+ * evidence should use `enrichInventory({ strictAttachments: true })`. */
1275
+ async resolveAttachments(attachmentIds) {
1276
+ const parts = [];
1277
+ const files = [];
1278
+ const omissions = attachmentIds.slice(20).map((attachmentId) => ({
1279
+ attachment_id: attachmentId,
1280
+ reason: "attachment limit exceeded (maximum 20)"
1281
+ }));
1282
+ let total = 0;
1283
+ for (const aid of attachmentIds.slice(0, 20)) {
1284
+ try {
1285
+ const resp = await this.request(
1286
+ "GET",
1287
+ `/artifact-manager/artifacts/${pathSegment(aid)}`,
1288
+ { params: { raw: "1" } }
1289
+ );
1290
+ const content = await resp.text();
1291
+ if (!content) {
1292
+ omissions.push({ attachment_id: aid, reason: "empty response body" });
1293
+ continue;
1294
+ }
1295
+ let name = aid;
1296
+ const encodedName = resp.headers.get("X-Artifact-Name");
1297
+ if (encodedName) {
1298
+ try {
1299
+ name = decodeURIComponent(encodedName);
1300
+ } catch {
1301
+ name = aid;
1302
+ }
1303
+ }
1304
+ if (resp.headers.get("X-Artifact-Format") === "file") {
1305
+ files.push({ filename: name, content_b64: content });
1306
+ continue;
1307
+ }
1308
+ if (total >= 5e5) {
1309
+ omissions.push({
1310
+ attachment_id: aid,
1311
+ reason: "combined attachment text limit exceeded"
1312
+ });
1313
+ continue;
1314
+ }
1315
+ const chunk = content.slice(0, Math.min(8e4, 5e5 - total));
1316
+ parts.push(`--- Attached: ${name} ---
1317
+ ${chunk}`);
1318
+ total += chunk.length;
1319
+ } catch (error) {
1320
+ omissions.push({
1321
+ attachment_id: aid,
1322
+ reason: error instanceof Error ? error.message : String(error)
1323
+ });
1324
+ }
1325
+ }
1326
+ const text = parts.join("\n\n");
1327
+ return { text: text.trim() ? text : void 0, files, omissions };
1328
+ }
1329
+ /**
1330
+ * Persist a COMPLETED inventory enrichment into this inventory's saved history, by its engine
1331
+ * `enrichmentId`.
1332
+ *
1333
+ * The programmatic equivalent of the workbench's "Save enrichment" button. Run `enrichInventory`
1334
+ * (`POST /v1/inventory-enrich` → poll), then pass the returned `enrichment_id` here to file the finished
1335
+ * findings as a `kind=inventory_enrichment` artifact linked to the inventory (or use
1336
+ * `enrichInventory({ save: true })` to do both in one call). The engine returns the report but never
1337
+ * persists it — this is the only way to add it to the inventory's history. Idempotent (a repeat returns
1338
+ * `{ ok: true, deduped: true }`). Usage-exempt. Resolves to `{ artifact_id }`. Save within ~1 h of completion.
1339
+ */
1340
+ async saveEnrichment(inventoryId, enrichmentId) {
1341
+ const resp = await this.request(
1342
+ "POST",
1343
+ `/inventory-manager/inventories/${pathSegment(inventoryId)}/enrichments`,
1344
+ { json: { enrichment_id: enrichmentId } }
1345
+ );
1346
+ return await resp.json();
1347
+ }
1348
+ /** Submit a raw asset list to the `/v1/inventory-enrich` engine, poll until done, resolve
1349
+ * `{ enrichment_id, report }`. The shared submit→poll core behind `enrichInventory` and the `ingest`
1350
+ * component. Throws `UnexpectedStatus` on an engine error, or `Error` on timeout. (Internal — used by
1351
+ * `ingest.ts`; not part of the documented public surface.) */
1352
+ async enrichItems(items, options = {}) {
1353
+ validatePollOptions(
1354
+ options.pollIntervalMs ?? 3e3,
1355
+ options.timeoutMs ?? 3e5
1356
+ );
1357
+ const body = { items };
1358
+ if (options.include) body.include = options.include;
1359
+ if (options.attachmentsText)
1360
+ body.attachments_text = options.attachmentsText;
1361
+ if (options.attachmentsFiles?.length)
1362
+ body.attachments_files = options.attachmentsFiles;
1363
+ const submit = await (await this.request("POST", "/v1/inventory-enrich", { json: body })).json();
1364
+ const enrichmentId = submit.enrichment_id;
1365
+ const job = await pollUntilDone(
1366
+ (m, p, timeoutMs) => this.request(m, p, { timeoutMs }),
1367
+ enrichmentId,
1368
+ `/v1/inventory-enrich/${pathSegment(enrichmentId)}`,
1369
+ {
1370
+ pollIntervalMs: options.pollIntervalMs ?? 3e3,
1371
+ timeoutMs: options.timeoutMs ?? 3e5,
1372
+ onProgress: options.onProgress
1373
+ }
1374
+ );
1375
+ return { enrichment_id: enrichmentId, report: job.result };
1376
+ }
1377
+ /** Parse a scan / inventory FILE into canonical asset items WITHOUT saving anything (the parse-only twin
1378
+ * of `importInventory`). You PICK the `format` — one of json/sbom/csv/nmap/list/grype/trivy/depcheck/nessus/gvm/xlsx
1379
+ * (no auto-detect; pass a `Uint8Array` for the binary `xlsx`). Resolves
1380
+ * `{ format, items, count, inventory_name?, truncated? }`. Usage-exempt — the building block for `ingestScan`. */
1381
+ async parseScan(content, format) {
1382
+ const resp = await this.request(
1383
+ "POST",
1384
+ "/inventory-manager/inventories/parse",
1385
+ { json: { format, content: wireContent(content) } }
1386
+ );
1387
+ return await resp.json();
1388
+ }
1389
+ /** Scan → briefing in one call: parse the scan FILE (`parseScan`), enrich the discovered assets against
1390
+ * the `/v1/inventory-enrich` ranking engine, and assemble a structured briefing. `format` is one of
1391
+ * json/sbom/csv/nmap/list/grype/trivy/depcheck/nessus/gvm/xlsx. The parse is usage-exempt; the enrichment **submit counts
1392
+ * toward usage** (one `/v1/inventory-enrich` request). Resolves
1393
+ * `{ format, parsed_count, truncated?, enrichment_id, report, recommended_actions }` (report = the
1394
+ * engine's KEV-first-ranked findings + rollup). An empty parse short-circuits to
1395
+ * `{ format, parsed_count: 0, enrichment_id: null, empty: true }`. */
1396
+ async ingestScan(content, format, options = {}) {
1397
+ return ingestScan(this, content, format, options);
1398
+ }
1399
+ };
1400
+
1401
+ // src/enricher.ts
1402
+ var EnricherApi = class {
1403
+ baseUrl;
1404
+ // True ES2022 private field, not TypeScript `private`: `private` is erased at compile
1405
+ // time, leaving an enumerable own property that JSON.stringify and
1406
+ // util.inspect (so console.log) print in cleartext. `#` is enforced by the
1407
+ // runtime and invisible to both.
1408
+ #apiKey;
1409
+ doFetch;
1410
+ constructor(baseUrl, apiKey, doFetch) {
1411
+ this.baseUrl = baseUrl.replace(/\/$/, "");
1412
+ this.#apiKey = apiKey;
1413
+ this.doFetch = doFetch;
1414
+ }
1415
+ async request(method, path, opts = {}) {
1416
+ const url = new URL(`${this.baseUrl}${path}`);
1417
+ for (const [k, v] of Object.entries(opts.params ?? {}))
1418
+ url.searchParams.set(k, v);
1419
+ const init = {
1420
+ method,
1421
+ headers: {
1422
+ apikey: this.#apiKey,
1423
+ ...opts.json !== void 0 ? { "Content-Type": "application/json" } : {}
1424
+ },
1425
+ ...opts.json !== void 0 ? { body: JSON.stringify(opts.json) } : {}
1426
+ };
1427
+ const resp = opts.timeoutMs === void 0 ? await this.doFetch(url, init) : await this.doFetch(
1428
+ new Request(url, {
1429
+ ...init,
1430
+ signal: AbortSignal.timeout(
1431
+ Math.max(1, Math.ceil(opts.timeoutMs))
1432
+ )
1433
+ })
1434
+ );
1435
+ if (!resp.ok) {
1436
+ const body = await resp.text().catch(() => "");
1437
+ throw new UnexpectedStatus(
1438
+ resp.status,
1439
+ body,
1440
+ `Enricher API ${resp.status} on ${path}`
1441
+ );
1442
+ }
1443
+ return resp;
1444
+ }
1445
+ /**
1446
+ * Run an artifact enrichment end-to-end against the /v1 engine: submit → poll → return the report.
1447
+ *
1448
+ * Stages pasted `text` + base64 `files` (`[{ filename, content_b64 }]`), submits to
1449
+ * `/v1/artifact-enrich`, polls the job until done, and resolves to the enrichment report.
1450
+ *
1451
+ * `stakeholder` is the optional SSVC stakeholder context applied to every reference when `include`
1452
+ * contains `"ssvc"` (`{ method, exposure, human_impact, mission_prevalence, public_wellbeing_impact }`;
1453
+ * omit to use the engine's CISA-coordinator defaults).
1454
+ *
1455
+ * Counts toward your API usage (it's `/v1/artifact-enrich` compute). Throws `UnexpectedStatus` on a
1456
+ * non-2xx (or enrichment error), or `Error` if the enrichment doesn't finish within `timeoutMs`.
1457
+ * Resolves to `{ enrichment_id, report }`.
1458
+ */
1459
+ async enrich(options = {}) {
1460
+ validatePollOptions(
1461
+ options.pollIntervalMs ?? 3e3,
1462
+ options.timeoutMs ?? 3e5
1463
+ );
1464
+ const body = {};
1465
+ if (options.text) body.text = options.text;
1466
+ if (options.files) body.files = options.files;
1467
+ if (options.formats) body.formats = options.formats;
1468
+ if (options.include) body.include = options.include;
1469
+ if (options.stakeholder) body.stakeholder = options.stakeholder;
1470
+ const submit = await (await this.request("POST", "/v1/artifact-enrich", { json: body })).json();
1471
+ const enrichmentId = submit.enrichment_id;
1472
+ const job = await pollUntilDone(
1473
+ (m, p, timeoutMs) => this.request(m, p, { timeoutMs }),
1474
+ enrichmentId,
1475
+ `/v1/artifact-enrich/${pathSegment(enrichmentId)}`,
1476
+ {
1477
+ pollIntervalMs: options.pollIntervalMs ?? 3e3,
1478
+ timeoutMs: options.timeoutMs ?? 3e5,
1479
+ onProgress: options.onProgress
1480
+ }
1481
+ );
1482
+ const result = {
1483
+ enrichment_id: enrichmentId,
1484
+ report: job.result
1485
+ };
1486
+ if (options.save) {
1487
+ const saveBody = { enrichment_id: enrichmentId };
1488
+ if (options.folderId || options.newFolderName) {
1489
+ saveBody.folder = {
1490
+ folder_id: options.folderId ?? null,
1491
+ new_folder_name: options.newFolderName ?? null
1492
+ };
1493
+ }
1494
+ result.saved = await (await this.request(
1495
+ "POST",
1496
+ "/artifact-manager/artifacts/from-enrichment",
1497
+ { json: saveBody }
1498
+ )).json();
1499
+ }
1500
+ return result;
1501
+ }
1502
+ };
1503
+
1504
+ // src/retry.ts
1505
+ var RETRYABLE_STATUS = /* @__PURE__ */ new Set([
1506
+ 429,
1507
+ 502,
1508
+ 503,
1509
+ 504
1510
+ ]);
1511
+ var RETRY_BASE_DELAY = 0.5;
1512
+ var RETRY_MAX_DELAY = 8;
1513
+ var RETRY_JITTER_RATIO = 0.25;
1514
+ var RETRY_AFTER_MAX = 60;
1515
+ var DEFAULT_MAX_RETRIES = 2;
1516
+ var defaultSleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
1517
+ function computeBackoff(attempt, rng = Math.random) {
1518
+ const raw = RETRY_BASE_DELAY * 2 ** attempt;
1519
+ const jitter = raw * RETRY_JITTER_RATIO * (rng() * 2 - 1);
1520
+ const delay = Math.min(RETRY_MAX_DELAY, raw + jitter);
1521
+ return Math.max(0, delay);
1522
+ }
1523
+ function parseRetryAfter(header, now = Date.now()) {
1524
+ if (header == null) return null;
1525
+ const trimmed = header.trim();
1526
+ if (trimmed === "") return null;
1527
+ if (/^\d+$/.test(trimmed)) {
1528
+ return Math.min(RETRY_AFTER_MAX, Number(trimmed));
1529
+ }
1530
+ const when = Date.parse(trimmed);
1531
+ if (Number.isNaN(when)) return null;
1532
+ const seconds = Math.max(0, (when - now) / 1e3);
1533
+ return Math.min(RETRY_AFTER_MAX, seconds);
1534
+ }
1535
+ function resolveDelay(attempt, retryAfter, rng = Math.random) {
1536
+ const parsed = parseRetryAfter(retryAfter);
1537
+ if (parsed !== null) return parsed;
1538
+ return computeBackoff(attempt, rng);
1539
+ }
1540
+ function isRetryableFetchError(err, userSignal) {
1541
+ if (userSignal) return false;
1542
+ if (err instanceof TypeError) return true;
1543
+ if (typeof DOMException !== "undefined" && err instanceof DOMException && err.name === "TimeoutError") {
1544
+ return true;
1545
+ }
1546
+ if (err != null && typeof err === "object" && err.name === "TimeoutError") {
1547
+ return true;
1548
+ }
1549
+ return false;
1550
+ }
1551
+ async function sleepBackoff(attempt, retryAfter, cfg) {
1552
+ const delay = resolveDelay(attempt, retryAfter, cfg.rng ?? Math.random);
1553
+ await (cfg.sleep ?? defaultSleep)(delay);
1554
+ }
1555
+
1556
+ // src/client.ts
1557
+ var BASE_URL = "https://crimsoncrawler.com";
1558
+ var DEFAULT_TIMEOUT_MS = 9e4;
1559
+ var RETRYABLE_METHODS = {
1560
+ GET: true,
1561
+ HEAD: true,
1562
+ OPTIONS: true
1563
+ };
1564
+ var ENV_API_KEY = "CRIMSON_CRAWLER_API_KEY";
1565
+ var ENV_BASE_URL = "CRIMSON_CRAWLER_BASE_URL";
1566
+ var ENV_VERIFY_SSL = "CRIMSON_CRAWLER_VERIFY_SSL";
1567
+ function resolveVerifySsl(verifySsl) {
1568
+ if (verifySsl !== void 0) return verifySsl;
1569
+ const raw = globalThis.process?.env?.[ENV_VERIFY_SSL]?.trim().toLowerCase() ?? "true";
1570
+ return !(raw === "false" || raw === "0" || raw === "no");
1571
+ }
1572
+ function validateBaseUrl(baseUrl) {
1573
+ const invalidUrlMessage = "baseUrl must be a valid HTTPS URL or an HTTP loopback URL";
1574
+ if (!baseUrl || baseUrl !== baseUrl.trim() || /\s/u.test(baseUrl) || !/^[A-Za-z][A-Za-z\d+.-]*:\/\//u.test(baseUrl)) {
1575
+ throw new RangeError(invalidUrlMessage);
1576
+ }
1577
+ let parsed;
1578
+ try {
1579
+ parsed = new URL(baseUrl);
1580
+ } catch {
1581
+ throw new RangeError(invalidUrlMessage);
1582
+ }
1583
+ const authority = baseUrl.slice(baseUrl.indexOf("://") + 3).split(/[/?#]/u, 1)[0];
1584
+ if (!parsed.hostname || authority.includes("@")) {
1585
+ throw new RangeError(invalidUrlMessage);
1586
+ }
1587
+ if (parsed.pathname !== "" && parsed.pathname !== "/" || parsed.search || parsed.hash) {
1588
+ throw new RangeError(
1589
+ "baseUrl must contain only an origin, without a path, query, or fragment"
1590
+ );
1591
+ }
1592
+ const hostname = parsed.hostname.toLowerCase();
1593
+ const loopback = hostname === "localhost" || /^127(?:\.\d{1,3}){3}$/u.test(hostname) || hostname === "[::1]";
1594
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && loopback)) {
1595
+ throw new RangeError("baseUrl must use HTTPS unless its host is loopback");
1596
+ }
1597
+ }
1598
+ var CrawlerClient = class {
1599
+ baseUrl;
1600
+ verifySsl;
1601
+ maxRetries;
1602
+ _client;
1603
+ _artifactManager;
1604
+ _inventoryManager;
1605
+ _enricher;
1606
+ _aiReports;
1607
+ constructor(opts = {}) {
1608
+ const apiKey = opts.apiKey ?? globalThis.process?.env?.[ENV_API_KEY];
1609
+ if (!apiKey) {
1610
+ throw new MissingCredentials(
1611
+ `Set ${ENV_API_KEY} or pass apiKey explicitly.`
1612
+ );
1613
+ }
1614
+ this.baseUrl = opts.baseUrl ?? globalThis.process?.env?.[ENV_BASE_URL] ?? BASE_URL;
1615
+ validateBaseUrl(this.baseUrl);
1616
+ this.verifySsl = resolveVerifySsl(opts.verifySsl);
1617
+ const maxRetries = opts.maxRetries ?? DEFAULT_MAX_RETRIES;
1618
+ if (!Number.isInteger(maxRetries) || maxRetries < 0) {
1619
+ throw new RangeError(
1620
+ `maxRetries must be a non-negative integer, got ${maxRetries}.`
1621
+ );
1622
+ }
1623
+ this.maxRetries = maxRetries;
1624
+ let insecureDispatcher;
1625
+ const fetchWithTls = async (input, init) => {
1626
+ if (this.verifySsl) {
1627
+ return globalThis.fetch(input, init);
1628
+ }
1629
+ if (typeof globalThis.process?.versions?.node !== "string") {
1630
+ throw new Error(
1631
+ "verifySsl=false is only supported in Node.js; this runtime cannot disable TLS verification per client."
1632
+ );
1633
+ }
1634
+ insecureDispatcher ??= import('undici').then(
1635
+ ({ Agent }) => new Agent({ connect: { rejectUnauthorized: false } })
1636
+ );
1637
+ const dispatcher = await insecureDispatcher;
1638
+ const scopedInit = { ...init, dispatcher };
1639
+ return globalThis.fetch(input, scopedInit);
1640
+ };
1641
+ const retryCfg = { maxRetries };
1642
+ const authOrigin = new URL(this.baseUrl).origin;
1643
+ const retryFetch = async (input, init) => {
1644
+ const initSignal = init?.signal;
1645
+ const requestSignal = !initSignal && input instanceof Request ? input.signal : void 0;
1646
+ const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
1647
+ const retryable = RETRYABLE_METHODS[method] === true;
1648
+ let attempt = 0;
1649
+ for (; ; ) {
1650
+ const timeoutSignal = AbortSignal.timeout(DEFAULT_TIMEOUT_MS);
1651
+ const signal = initSignal ?? (requestSignal ? AbortSignal.any([requestSignal, timeoutSignal]) : timeoutSignal);
1652
+ try {
1653
+ const resp = await fetchWithTls(input, {
1654
+ ...init,
1655
+ signal,
1656
+ redirect: "manual",
1657
+ // Stamped per request, and only for our own origin, so the key
1658
+ // never lives on the client config nor travels to another host.
1659
+ headers: withApiKeyHeader(
1660
+ input,
1661
+ init,
1662
+ "apikey",
1663
+ apiKey,
1664
+ authOrigin
1665
+ )
1666
+ });
1667
+ if (retryable && RETRYABLE_STATUS.has(resp.status) && attempt < maxRetries) {
1668
+ try {
1669
+ await resp.body?.cancel();
1670
+ } catch {
1671
+ }
1672
+ await sleepBackoff(
1673
+ attempt,
1674
+ resp.headers.get("retry-after"),
1675
+ retryCfg
1676
+ );
1677
+ attempt++;
1678
+ continue;
1679
+ }
1680
+ return resp;
1681
+ } catch (err) {
1682
+ const requestSignalAborted = requestSignal?.aborted === true;
1683
+ if (!requestSignalAborted && retryable && isRetryableFetchError(err, initSignal) && attempt < maxRetries) {
1684
+ await sleepBackoff(attempt, null, retryCfg);
1685
+ attempt++;
1686
+ continue;
1687
+ }
1688
+ throw err;
1689
+ }
1690
+ }
1691
+ };
1692
+ const clientConfig = {
1693
+ baseUrl: this.baseUrl,
1694
+ // Deliberately no `headers: { apikey }` — the generated client would keep
1695
+ // it in a reachable `Headers` object that `util.inspect` prints in full.
1696
+ // `retryFetch` stamps it onto each request instead (see ./_auth.ts).
1697
+ fetch: retryFetch
1698
+ };
1699
+ this._client = createClient(clientConfig);
1700
+ if (opts.configureGlobalClient) {
1701
+ client.setConfig(clientConfig);
1702
+ }
1703
+ this._artifactManager = new ArtifactManagerApi(
1704
+ this.baseUrl,
1705
+ apiKey,
1706
+ retryFetch
1707
+ );
1708
+ this._inventoryManager = new InventoryManagerApi(
1709
+ this.baseUrl,
1710
+ apiKey,
1711
+ retryFetch
1712
+ );
1713
+ this._enricher = new EnricherApi(this.baseUrl, apiKey, retryFetch);
1714
+ this._aiReports = new AiReportsApi(this.baseUrl, apiKey, retryFetch);
1715
+ }
1716
+ /** Underlying Hey API client, scoped to this instance. Use to call any of the 33 endpoints directly. */
1717
+ get api() {
1718
+ return this._client;
1719
+ }
1720
+ /**
1721
+ * The Artifact Manager API (Artifact Manager) — your stored artifacts, enrichment exports,
1722
+ * ratings, enrichment-compare, and folders over the same key. Hand-written (the
1723
+ * `/artifact-manager/*` surface lives outside the `/v1` OpenAPI contract) and
1724
+ * **usage-exempt** — artifactManager calls never count toward your API usage.
1725
+ */
1726
+ get artifactManager() {
1727
+ return this._artifactManager;
1728
+ }
1729
+ /**
1730
+ * The Inventory Manager API — your monitored inventory context windows (asset inventory + attached
1731
+ * artifacts + saved enrichment history) over the same key. Its own section at
1732
+ * `/inventory-manager/inventories/*` (outside the `/v1` OpenAPI contract). **Usage-exempt** except
1733
+ * `enrichInventory`'s submit, which is enrichment compute and counts toward your usage.
1734
+ */
1735
+ get inventoryManager() {
1736
+ return this._inventoryManager;
1737
+ }
1738
+ /**
1739
+ * The Enricher API — the async artifact-enrichment lifecycle (submit → poll → report) over the same
1740
+ * key, straight against the `/v1/artifact-enrich` engine. The enrichment submit counts toward usage;
1741
+ * polling is the engine's own status read.
1742
+ */
1743
+ get enricher() {
1744
+ return this._enricher;
1745
+ }
1746
+ /**
1747
+ * The Report Generator API — generate + manage grounded intelligence reports from
1748
+ * your saved artifacts, at `/ai-reports/*` (its own section, outside the `/v1` OpenAPI contract).
1749
+ * **Usage-exempt**, including the LLM generation.
1750
+ */
1751
+ get aiReports() {
1752
+ return this._aiReports;
1753
+ }
1754
+ // -- Convenience methods for the most common enrichment chains --------- //
1755
+ /**
1756
+ * Walk the full CVE → CWE → CAPEC → ATT&CK → TIE chain plus MISP/knowledge base/web.
1757
+ *
1758
+ * @param cveId CVE identifier (e.g. `CVE-2024-3400`).
1759
+ * @param include Override the default `CVE_FULL_WALK` chain.
1760
+ */
1761
+ async enrichCveFull(cveId, include = CVE_FULL_WALK) {
1762
+ const result = await enrichCve({
1763
+ client: this._client,
1764
+ body: { cve_id: cveId, include: [...include] }
1765
+ });
1766
+ return ensureOk(result);
1767
+ }
1768
+ /**
1769
+ * Enrich an IOC against MISP, link to ATT&CK, and add knowledge base/web context.
1770
+ *
1771
+ * @param value Indicator value (hash, IP, domain, URL).
1772
+ * @param iocType MISP-style attribute type — `ip-dst`, `ip-src`, `domain`,
1773
+ * `hostname`, `md5`, `sha1`, `sha256`, `url`, etc. Defaults to `ip-dst`.
1774
+ * @param include Override the default `IOC_FULL_WALK` chain.
1775
+ */
1776
+ async enrichIocFull(value, iocType = "ip-dst", include = IOC_FULL_WALK) {
1777
+ const result = await enrichIoc({
1778
+ client: this._client,
1779
+ body: { value, type: iocType, include: [...include] }
1780
+ });
1781
+ return ensureOk(result);
1782
+ }
1783
+ /**
1784
+ * Walk CWE → CAPEC → ATT&CK with TIE predictions.
1785
+ *
1786
+ * @param cweId CWE identifier (e.g. `CWE-79`).
1787
+ * @param include Override the default `CWE_FULL_WALK` chain.
1788
+ */
1789
+ async enrichCweFull(cweId, include = CWE_FULL_WALK) {
1790
+ const result = await enrichCwe({
1791
+ client: this._client,
1792
+ body: { cwe_id: cweId, include: [...include] }
1793
+ });
1794
+ return ensureOk(result);
1795
+ }
1796
+ /**
1797
+ * Enrich one or more ATT&CK techniques with TIE, adversary attribution,
1798
+ * and Navigator JSON.
1799
+ *
1800
+ * @param techniqueIds ATT&CK technique IDs (e.g. `["T1190", "T1059.001"]`).
1801
+ * @param framework ATT&CK matrix variant — `enterprise`, `ics`, or `mobile`.
1802
+ * @param include Override the default `TECHNIQUE_FULL` chain.
1803
+ */
1804
+ async enrichTechniqueFull(techniqueIds, framework = "enterprise", include = TECHNIQUE_FULL) {
1805
+ const result = await enrichTechnique({
1806
+ client: this._client,
1807
+ body: {
1808
+ technique_ids: techniqueIds,
1809
+ framework,
1810
+ include: [...include]
1811
+ }
1812
+ });
1813
+ return ensureOk(result);
1814
+ }
1815
+ /**
1816
+ * Find vulnerabilities affecting a product/version and enrich each matched CVE.
1817
+ *
1818
+ * @param product Product name (e.g. `"Apache HTTP Server"`, `"nginx"`).
1819
+ * @param options Optional `version`, `vendor`, and `include` overrides.
1820
+ */
1821
+ async enrichProductFull(product, options = {}) {
1822
+ const result = await enrichProduct({
1823
+ client: this._client,
1824
+ body: {
1825
+ product,
1826
+ ...options.version !== void 0 && { version: options.version },
1827
+ ...options.vendor !== void 0 && { vendor: options.vendor },
1828
+ include: [...options.include ?? PRODUCT_FULL]
1829
+ }
1830
+ });
1831
+ return ensureOk(result);
1832
+ }
1833
+ /**
1834
+ * Enrich an open-source package — OSV.dev advisories + full CVE enrichment.
1835
+ *
1836
+ * The package-ecosystem sibling of {@link enrichProductFull}: OSV.dev supplies the
1837
+ * package's advisories, and the CVEs they alias are enriched through the same
1838
+ * CWE→CAPEC→ATT&CK + EPSS/KEV chain. Covers the dependency-vuln surface (npm /
1839
+ * PyPI / Go / Maven / crates.io / …) the CPE-keyed product endpoint can't reach.
1840
+ *
1841
+ * @param ecosystem Package ecosystem (e.g. `"PyPI"`, `"npm"`, `"Go"`).
1842
+ * @param packageName Package name as published in its registry (e.g. `"django"`).
1843
+ * @param options Optional `version` and `include` overrides.
1844
+ */
1845
+ async enrichPackageFull(ecosystem, packageName, options = {}) {
1846
+ const result = await enrichPackage({
1847
+ client: this._client,
1848
+ body: {
1849
+ ecosystem,
1850
+ package: packageName,
1851
+ ...options.version !== void 0 && { version: options.version },
1852
+ include: [...options.include ?? PACKAGE_FULL]
1853
+ }
1854
+ });
1855
+ return ensureOk(result);
1856
+ }
1857
+ /**
1858
+ * Keyword-search the ATT&CK knowledge base for matching techniques.
1859
+ *
1860
+ * A convenience wrapper over the generated `search_cti` endpoint, scoped to
1861
+ * ATT&CK attack-patterns. Replaces the raw escape hatch callers previously
1862
+ * used to hand-build the request.
1863
+ *
1864
+ * @param keyword Free-text query (e.g. `"phishing"`, `"credential dumping"`).
1865
+ * @param options Optional `limit` (1-100, default 20).
1866
+ */
1867
+ async searchTechniques(keyword, options = {}) {
1868
+ const result = await searchCti({
1869
+ client: this._client,
1870
+ body: {
1871
+ query: keyword,
1872
+ sources: ["attack"],
1873
+ types: ["attack-pattern"],
1874
+ limit: options.limit ?? 20
1875
+ }
1876
+ });
1877
+ return ensureOk(result);
1878
+ }
1879
+ // -- Entity enrichment: full-walk chains ------------------------------- //
1880
+ //
1881
+ // Each endpoint accepts either its own ID or a `search` keyword, both
1882
+ // optional. Neither is enforced client-side: the server's validator answers
1883
+ // a request carrying neither with `422`, which surfaces as UnexpectedStatus
1884
+ // like every other rejection.
1885
+ /**
1886
+ * Walk an ATLAS adversarial-ML technique to its ATT&CK mappings and adversary graph.
1887
+ *
1888
+ * @param techniqueId ATLAS technique ID (e.g. `AML.T0043`).
1889
+ * @param options Optional `search` keyword and `include` override (default `ATLAS_FULL`).
1890
+ */
1891
+ async enrichAtlasFull(techniqueId, options = {}) {
1892
+ const result = await enrichAtlas({
1893
+ client: this._client,
1894
+ body: {
1895
+ ...techniqueId !== void 0 && { technique_id: techniqueId },
1896
+ ...options.search !== void 0 && { search: options.search },
1897
+ include: [...options.include ?? ATLAS_FULL]
1898
+ }
1899
+ });
1900
+ return ensureOk(result);
1901
+ }
1902
+ /**
1903
+ * Walk a threat campaign to its techniques, the groups behind it, and the CVEs it exploited.
1904
+ *
1905
+ * @param campaignId ATT&CK campaign ID (e.g. `C0011`).
1906
+ * @param options Optional `search` keyword, `framework` matrix, and `include`
1907
+ * override (default `CAMPAIGN_FULL`).
1908
+ */
1909
+ async enrichCampaignFull(campaignId, options = {}) {
1910
+ const result = await enrichCampaign({
1911
+ client: this._client,
1912
+ body: {
1913
+ ...campaignId !== void 0 && { campaign_id: campaignId },
1914
+ ...options.search !== void 0 && { search: options.search },
1915
+ framework: options.framework ?? "enterprise",
1916
+ include: [...options.include ?? CAMPAIGN_FULL]
1917
+ }
1918
+ });
1919
+ return ensureOk(result);
1920
+ }
1921
+ /**
1922
+ * Walk a CAPEC attack pattern to its ATT&CK techniques, exploitable CVEs, and adversaries.
1923
+ *
1924
+ * @param capecId CAPEC identifier (e.g. `CAPEC-66`).
1925
+ * @param options Optional `search` keyword and `include` override (default `CAPEC_FULL`).
1926
+ */
1927
+ async enrichCapecFull(capecId, options = {}) {
1928
+ const result = await enrichCapec({
1929
+ client: this._client,
1930
+ body: {
1931
+ ...capecId !== void 0 && { capec_id: capecId },
1932
+ ...options.search !== void 0 && { search: options.search },
1933
+ include: [...options.include ?? CAPEC_FULL]
1934
+ }
1935
+ });
1936
+ return ensureOk(result);
1937
+ }
1938
+ /**
1939
+ * Resolve a D3FEND defensive technique and the offensive techniques it counters.
1940
+ *
1941
+ * @param d3fendId D3FEND identifier (e.g. `D3-NTA`).
1942
+ * @param options Optional `search` keyword and `include` override (default `DEFEND_FULL`).
1943
+ */
1944
+ async enrichDefendFull(d3fendId, options = {}) {
1945
+ const result = await enrichDefend({
1946
+ client: this._client,
1947
+ body: {
1948
+ ...d3fendId !== void 0 && { d3fend_id: d3fendId },
1949
+ ...options.search !== void 0 && { search: options.search },
1950
+ include: [...options.include ?? DEFEND_FULL]
1951
+ }
1952
+ });
1953
+ return ensureOk(result);
1954
+ }
1955
+ /**
1956
+ * Walk a DISARM disinformation technique to its countermeasures and ATT&CK mappings.
1957
+ *
1958
+ * @param techniqueId DISARM technique ID (e.g. `T0086`).
1959
+ * @param options Optional `search` keyword and `include` override (default `DISARM_FULL`).
1960
+ */
1961
+ async enrichDisarmFull(techniqueId, options = {}) {
1962
+ const result = await enrichDisarm({
1963
+ client: this._client,
1964
+ body: {
1965
+ ...techniqueId !== void 0 && { technique_id: techniqueId },
1966
+ ...options.search !== void 0 && { search: options.search },
1967
+ include: [...options.include ?? DISARM_FULL]
1968
+ }
1969
+ });
1970
+ return ensureOk(result);
1971
+ }
1972
+ /**
1973
+ * Profile a threat actor: techniques, tooling, campaigns, exploited CVEs, and targeting.
1974
+ *
1975
+ * @param groupId ATT&CK group ID (e.g. `G0016`).
1976
+ * @param options Optional `search` keyword, `framework` matrix, and `include`
1977
+ * override (default `GROUP_FULL`).
1978
+ */
1979
+ async enrichGroupFull(groupId, options = {}) {
1980
+ const result = await enrichGroup({
1981
+ client: this._client,
1982
+ body: {
1983
+ ...groupId !== void 0 && { group_id: groupId },
1984
+ ...options.search !== void 0 && { search: options.search },
1985
+ framework: options.framework ?? "enterprise",
1986
+ include: [...options.include ?? GROUP_FULL]
1987
+ }
1988
+ });
1989
+ return ensureOk(result);
1990
+ }
1991
+ /**
1992
+ * Map a region's threat landscape — active groups, their techniques, and affected sectors.
1993
+ *
1994
+ * @param locationId Region identifier (e.g. `UA`, or an ATT&CK location STIX ID).
1995
+ * @param options Optional `search` keyword and `include` override (default `LOCATION_FULL`).
1996
+ */
1997
+ async enrichLocationFull(locationId, options = {}) {
1998
+ const result = await enrichLocation({
1999
+ client: this._client,
2000
+ body: {
2001
+ ...locationId !== void 0 && { location_id: locationId },
2002
+ ...options.search !== void 0 && { search: options.search },
2003
+ include: [...options.include ?? LOCATION_FULL]
2004
+ }
2005
+ });
2006
+ return ensureOk(result);
2007
+ }
2008
+ /**
2009
+ * Map an industry sector's threat landscape — who targets it, how, and from where.
2010
+ *
2011
+ * @param sectorId Sector identifier (e.g. `energy`, or an ATT&CK sector STIX ID).
2012
+ * @param options Optional `search` keyword and `include` override (default `SECTOR_FULL`).
2013
+ */
2014
+ async enrichSectorFull(sectorId, options = {}) {
2015
+ const result = await enrichSector({
2016
+ client: this._client,
2017
+ body: {
2018
+ ...sectorId !== void 0 && { sector_id: sectorId },
2019
+ ...options.search !== void 0 && { search: options.search },
2020
+ include: [...options.include ?? SECTOR_FULL]
2021
+ }
2022
+ });
2023
+ return ensureOk(result);
2024
+ }
2025
+ /**
2026
+ * Profile malware or a tool: the techniques it implements, who uses it, what it exploits.
2027
+ *
2028
+ * @param softwareId ATT&CK software ID (e.g. `S0002`).
2029
+ * @param options Optional `search` keyword, `framework` matrix, and `include`
2030
+ * override (default `SOFTWARE_FULL`).
2031
+ */
2032
+ async enrichSoftwareFull(softwareId, options = {}) {
2033
+ const result = await enrichSoftware({
2034
+ client: this._client,
2035
+ body: {
2036
+ ...softwareId !== void 0 && { software_id: softwareId },
2037
+ ...options.search !== void 0 && { search: options.search },
2038
+ framework: options.framework ?? "enterprise",
2039
+ include: [...options.include ?? SOFTWARE_FULL]
2040
+ }
2041
+ });
2042
+ return ensureOk(result);
2043
+ }
2044
+ // -- Enrichment: batch and PoC source ---------------------------------- //
2045
+ /**
2046
+ * Enrich a heterogeneous list of artifacts in one round trip.
2047
+ *
2048
+ * Each item carries its own `type` discriminator and per-item `include`, so a
2049
+ * single call can mix CVEs, products, packages, techniques, IOCs, and more.
2050
+ * Prefer this over N single-artifact calls: the server fans out internally and
2051
+ * shares upstream lookups across the batch.
2052
+ *
2053
+ * @param items Discriminated batch items (`{ type: "cve", cve_id: "..." }`, …).
2054
+ */
2055
+ async enrichBatch(items) {
2056
+ const result = await enrichBatch({
2057
+ client: this._client,
2058
+ body: { items }
2059
+ });
2060
+ return ensureOk(result);
2061
+ }
2062
+ /**
2063
+ * Fetch the source of a public proof-of-concept exploit repository.
2064
+ *
2065
+ * Retrieves the code behind a PoC reference (as surfaced by the `poc` enrichment
2066
+ * layer) so it can be reviewed without leaving the API.
2067
+ *
2068
+ * @param repoUrl Public repository URL of the PoC.
2069
+ */
2070
+ async enrichPocSource(repoUrl) {
2071
+ const result = await enrichPocSource({
2072
+ client: this._client,
2073
+ body: { repo_url: repoUrl }
2074
+ });
2075
+ return ensureOk(result);
2076
+ }
2077
+ // -- Assessments ------------------------------------------------------- //
2078
+ //
2079
+ // Assessment endpoints score a portfolio rather than enrich one artifact.
2080
+ // `include` has no full-walk preset here — omit it to take the server's
2081
+ // per-endpoint default, or pass an explicit layer list.
2082
+ /**
2083
+ * Score your exposure to specific threat actors.
2084
+ *
2085
+ * Supply `groupIds`, `search` terms, or both; the server rejects a request
2086
+ * carrying neither with `422`.
2087
+ *
2088
+ * @param options `groupIds`, `search` terms, `framework` matrix, and `include` layers.
2089
+ */
2090
+ async assessGroupExposure(options = {}) {
2091
+ const result = await assessGroupExposure({
2092
+ client: this._client,
2093
+ body: {
2094
+ ...options.groupIds !== void 0 && {
2095
+ group_ids: [...options.groupIds]
2096
+ },
2097
+ ...options.search !== void 0 && { search: [...options.search] },
2098
+ framework: options.framework ?? "enterprise",
2099
+ ...options.include !== void 0 && { include: [...options.include] }
2100
+ }
2101
+ });
2102
+ return ensureOk(result);
2103
+ }
2104
+ /**
2105
+ * Assess a portfolio of indicators — MISP corroboration, linked techniques, attribution.
2106
+ *
2107
+ * @param indicators Indicator objects, each `{ value, type? }` (`type` defaults to `ip-dst`).
2108
+ * @param options Optional `include` layers.
2109
+ */
2110
+ async assessIocPortfolio(indicators, options = {}) {
2111
+ const result = await assessIocPortfolio({
2112
+ client: this._client,
2113
+ body: {
2114
+ indicators,
2115
+ ...options.include !== void 0 && { include: [...options.include] }
2116
+ }
2117
+ });
2118
+ return ensureOk(result);
2119
+ }
2120
+ /**
2121
+ * Score detection and mitigation coverage across a set of ATT&CK techniques.
2122
+ *
2123
+ * @param techniqueIds ATT&CK technique IDs (e.g. `["T1190", "T1059.001"]`).
2124
+ * @param options Optional `framework` matrix and `include` layers.
2125
+ */
2126
+ async assessTechniqueCoverage(techniqueIds, options = {}) {
2127
+ const result = await assessTechniqueCoverage({
2128
+ client: this._client,
2129
+ body: {
2130
+ technique_ids: [...techniqueIds],
2131
+ framework: options.framework ?? "enterprise",
2132
+ ...options.include !== void 0 && { include: [...options.include] }
2133
+ }
2134
+ });
2135
+ return ensureOk(result);
2136
+ }
2137
+ /**
2138
+ * Prioritize a set of CVEs — weaponization, exploit chains, and remediation order.
2139
+ *
2140
+ * @param cveIds CVE identifiers to assess.
2141
+ * @param options Optional `include` layers and an SSVC `stakeholder` profile that
2142
+ * tunes the decision to your deployment.
2143
+ */
2144
+ async assessVulnerabilityExposure(cveIds, options = {}) {
2145
+ const result = await assessVulnerabilityExposure({
2146
+ client: this._client,
2147
+ body: {
2148
+ cve_ids: [...cveIds],
2149
+ ...options.include !== void 0 && { include: [...options.include] },
2150
+ ...options.stakeholder !== void 0 && {
2151
+ stakeholder: options.stakeholder
2152
+ }
2153
+ }
2154
+ });
2155
+ return ensureOk(result);
2156
+ }
2157
+ // -- Search ------------------------------------------------------------ //
2158
+ //
2159
+ // Search endpoints query a corpus and return matches; they never walk an
2160
+ // enrichment chain, so none of them takes a full-walk preset. `include` (where
2161
+ // the corpus offers it) is a plain passthrough.
2162
+ /**
2163
+ * Search the CTI knowledge bases — ATT&CK, CWE, CAPEC, ATLAS, DISARM, and more.
2164
+ *
2165
+ * The unscoped sibling of {@link searchTechniques}: use this to reach any object
2166
+ * type across any source, and `searchTechniques` for the common ATT&CK-only case.
2167
+ *
2168
+ * @param query Free-text query.
2169
+ * @param options `sources`, `types`, `limit`, `page`, and the `deprecated`/`revoked` filters.
2170
+ */
2171
+ async searchCti(query, options = {}) {
2172
+ const result = await searchCti({
2173
+ client: this._client,
2174
+ body: {
2175
+ query,
2176
+ ...options.sources !== void 0 && { sources: [...options.sources] },
2177
+ ...options.types !== void 0 && { types: options.types },
2178
+ limit: options.limit ?? 20,
2179
+ page: options.page ?? 1,
2180
+ ...options.deprecated !== void 0 && {
2181
+ deprecated: options.deprecated
2182
+ },
2183
+ ...options.revoked !== void 0 && { revoked: options.revoked }
2184
+ }
2185
+ });
2186
+ return ensureOk(result);
2187
+ }
2188
+ /**
2189
+ * Search the vulnerability corpus by identifier, mapping, score, or date window.
2190
+ *
2191
+ * Every filter is optional and they compose: a bare call returns the newest
2192
+ * CVEs, while `{ kevOnly: true, epssMin: 0.5 }` narrows to actively exploited,
2193
+ * high-probability ones.
2194
+ *
2195
+ * @param query Free-text query. Omit it to filter purely on the structured fields.
2196
+ * @param options Any combination of the corpus filters, plus `sort`, `limit`, `page`.
2197
+ */
2198
+ async searchCve(query, options = {}) {
2199
+ const result = await searchCve({
2200
+ client: this._client,
2201
+ body: {
2202
+ ...query !== void 0 && { query },
2203
+ ...options.cveId !== void 0 && { cve_id: options.cveId },
2204
+ ...options.stixId !== void 0 && { stix_id: options.stixId },
2205
+ ...options.cweId !== void 0 && { cwe_id: options.cweId },
2206
+ ...options.capecId !== void 0 && { capec_id: options.capecId },
2207
+ ...options.attackId !== void 0 && { attack_id: options.attackId },
2208
+ ...options.cpe !== void 0 && { cpe: options.cpe },
2209
+ ...options.cpesNotVulnerable !== void 0 && {
2210
+ cpes_not_vulnerable: options.cpesNotVulnerable
2211
+ },
2212
+ ...options.createdByRef !== void 0 && {
2213
+ created_by_ref: options.createdByRef
2214
+ },
2215
+ ...options.createdMin !== void 0 && {
2216
+ created_min: options.createdMin
2217
+ },
2218
+ ...options.createdMax !== void 0 && {
2219
+ created_max: options.createdMax
2220
+ },
2221
+ ...options.modifiedMin !== void 0 && {
2222
+ modified_min: options.modifiedMin
2223
+ },
2224
+ ...options.modifiedMax !== void 0 && {
2225
+ modified_max: options.modifiedMax
2226
+ },
2227
+ ...options.cvssMin !== void 0 && { cvss_min: options.cvssMin },
2228
+ ...options.cvssV2Min !== void 0 && {
2229
+ cvss_v2_min: options.cvssV2Min
2230
+ },
2231
+ ...options.cvssV4Min !== void 0 && {
2232
+ cvss_v4_min: options.cvssV4Min
2233
+ },
2234
+ ...options.epssMin !== void 0 && { epss_min: options.epssMin },
2235
+ ...options.epssPercentileMin !== void 0 && {
2236
+ epss_percentile_min: options.epssPercentileMin
2237
+ },
2238
+ kev_only: options.kevOnly ?? false,
2239
+ ...options.vulnStatus !== void 0 && {
2240
+ vuln_status: options.vulnStatus
2241
+ },
2242
+ ...options.sort !== void 0 && { sort: options.sort },
2243
+ ...options.include !== void 0 && { include: [...options.include] },
2244
+ limit: options.limit ?? 50,
2245
+ page: options.page ?? 1
2246
+ }
2247
+ });
2248
+ return ensureOk(result);
2249
+ }
2250
+ /**
2251
+ * Search the D3FEND defensive-countermeasure ontology.
2252
+ *
2253
+ * @param query Free-text query (e.g. `"network traffic analysis"`).
2254
+ * @param options `d3fendForm` to scope to a tactic/mitigation/artifact, plus `limit`, `page`.
2255
+ */
2256
+ async searchD3fend(query, options = {}) {
2257
+ const result = await searchD3Fend({
2258
+ client: this._client,
2259
+ body: {
2260
+ query,
2261
+ ...options.d3fendForm !== void 0 && {
2262
+ d3fend_form: options.d3fendForm
2263
+ },
2264
+ limit: options.limit ?? 20,
2265
+ page: options.page ?? 1
2266
+ }
2267
+ });
2268
+ return ensureOk(result);
2269
+ }
2270
+ /**
2271
+ * Search CISA's Known Exploited Vulnerabilities catalog.
2272
+ *
2273
+ * An empty call pages the whole catalog; `cveId` checks one CVE's KEV status.
2274
+ *
2275
+ * @param options `cveId`, `ransomwareStatus`, `limit`, `page`.
2276
+ */
2277
+ async searchKev(options = {}) {
2278
+ const result = await searchKev({
2279
+ client: this._client,
2280
+ body: {
2281
+ ...options.cveId !== void 0 && { cve_id: options.cveId },
2282
+ ...options.ransomwareStatus !== void 0 && {
2283
+ ransomware_status: options.ransomwareStatus
2284
+ },
2285
+ limit: options.limit ?? 50,
2286
+ page: options.page ?? 1
2287
+ }
2288
+ });
2289
+ return ensureOk(result);
2290
+ }
2291
+ /**
2292
+ * Hybrid-search the curated security knowledge base.
2293
+ *
2294
+ * @param query Natural-language question or keyword set.
2295
+ * @param options `collections` to search, `alpha` to trade keyword vs. vector
2296
+ * weighting (0 = pure vector, 1 = pure keyword), and `limit`.
2297
+ */
2298
+ async searchKnowledgebase(query, options = {}) {
2299
+ const result = await searchKnowledgebase({
2300
+ client: this._client,
2301
+ body: {
2302
+ query,
2303
+ ...options.collections !== void 0 && {
2304
+ collections: options.collections
2305
+ },
2306
+ alpha: options.alpha ?? 0.7,
2307
+ limit: options.limit ?? 10
2308
+ }
2309
+ });
2310
+ return ensureOk(result);
2311
+ }
2312
+ /**
2313
+ * Search MISP events and attributes.
2314
+ *
2315
+ * @param options Attribute filters (`value`, `typeAttribute`, `category`, `toIds`),
2316
+ * event filters (`eventId`, `eventinfo`, `tags`, `threatLevelId`, `published`),
2317
+ * a `dateFrom`/`dateTo` window, plus `limit` and `page`.
2318
+ */
2319
+ async searchMisp(options = {}) {
2320
+ const result = await searchMisp({
2321
+ client: this._client,
2322
+ body: {
2323
+ ...options.value !== void 0 && { value: options.value },
2324
+ ...options.typeAttribute !== void 0 && {
2325
+ type_attribute: options.typeAttribute
2326
+ },
2327
+ ...options.category !== void 0 && { category: options.category },
2328
+ ...options.toIds !== void 0 && { to_ids: options.toIds },
2329
+ ...options.eventId !== void 0 && { event_id: options.eventId },
2330
+ ...options.eventinfo !== void 0 && {
2331
+ eventinfo: options.eventinfo
2332
+ },
2333
+ ...options.tags !== void 0 && { tags: [...options.tags] },
2334
+ ...options.threatLevelId !== void 0 && {
2335
+ threat_level_id: options.threatLevelId
2336
+ },
2337
+ ...options.published !== void 0 && {
2338
+ published: options.published
2339
+ },
2340
+ ...options.dateFrom !== void 0 && { date_from: options.dateFrom },
2341
+ ...options.dateTo !== void 0 && { date_to: options.dateTo },
2342
+ limit: options.limit ?? 50,
2343
+ page: options.page ?? 1
2344
+ }
2345
+ });
2346
+ return ensureOk(result);
2347
+ }
2348
+ /**
2349
+ * Find public proof-of-concept exploits for a CVE.
2350
+ *
2351
+ * Pair with {@link enrichPocSource} to pull the code behind a match.
2352
+ *
2353
+ * @param cveId CVE identifier (e.g. `CVE-2024-3400`).
2354
+ * @param options Optional `limit` (default 25).
2355
+ */
2356
+ async searchPoc(cveId, options = {}) {
2357
+ const result = await searchPoc({
2358
+ client: this._client,
2359
+ body: {
2360
+ cve_id: cveId,
2361
+ limit: options.limit ?? 25
2362
+ }
2363
+ });
2364
+ return ensureOk(result);
2365
+ }
2366
+ /**
2367
+ * List the products a vendor ships, as known to the CPE dictionary.
2368
+ *
2369
+ * Use it to resolve the exact product string {@link enrichProductFull} expects.
2370
+ *
2371
+ * @param vendor Vendor name (e.g. `"microsoft"`).
2372
+ * @param options Optional `limit` (default 50).
2373
+ */
2374
+ async searchVendor(vendor, options = {}) {
2375
+ const result = await searchVendor({
2376
+ client: this._client,
2377
+ body: {
2378
+ vendor,
2379
+ limit: options.limit ?? 50
2380
+ }
2381
+ });
2382
+ return ensureOk(result);
2383
+ }
2384
+ // -- Async enrichment engines ------------------------------------------ //
2385
+ //
2386
+ // Both engines are submit-then-poll: the submit returns an `enrichment_id`,
2387
+ // and the matching `*Status` read reports progress until the report is ready.
2388
+ // `client.enricher` wraps the artifact engine's full lifecycle (submit, poll,
2389
+ // fetch) for callers who want the loop written for them; these two pairs are
2390
+ // the raw operations.
2391
+ /**
2392
+ * Submit documents and/or text to the async artifact-enrichment engine.
2393
+ *
2394
+ * Returns immediately with an `enrichment_id` — poll {@link artifactEnrichStatus}
2395
+ * for the result, or use {@link enricher} to run the whole lifecycle.
2396
+ *
2397
+ * @param options `text` and/or base64 `files` to analyze, output `formats`,
2398
+ * report `include` sections, and an SSVC `stakeholder` profile.
2399
+ */
2400
+ async artifactEnrich(options = {}) {
2401
+ const result = await artifactEnrich({
2402
+ client: this._client,
2403
+ body: {
2404
+ ...options.text !== void 0 && { text: options.text },
2405
+ ...options.files !== void 0 && { files: options.files },
2406
+ ...options.formats !== void 0 && { formats: options.formats },
2407
+ ...options.include !== void 0 && { include: [...options.include] },
2408
+ ...options.stakeholder !== void 0 && {
2409
+ stakeholder: options.stakeholder
2410
+ }
2411
+ }
2412
+ });
2413
+ return ensureOk(result);
2414
+ }
2415
+ /**
2416
+ * Read the progress or result of an artifact enrichment.
2417
+ *
2418
+ * @param enrichmentId The `enrichment_id` returned by {@link artifactEnrich}.
2419
+ */
2420
+ async artifactEnrichStatus(enrichmentId) {
2421
+ const result = await artifactEnrichStatus({
2422
+ client: this._client,
2423
+ path: { enrichment_id: enrichmentId }
2424
+ });
2425
+ return ensureOk(result);
2426
+ }
2427
+ /**
2428
+ * Submit an asset inventory to the async inventory-enrichment engine.
2429
+ *
2430
+ * Returns immediately with an `enrichment_id` — poll {@link inventoryEnrichStatus}
2431
+ * for the result. Enriches each asset's CVEs and rolls the findings up to a
2432
+ * fleet-level risk picture.
2433
+ *
2434
+ * @param items Assets to enrich, each at minimum `{ product }`.
2435
+ * @param options Optional `attachmentsText`/`attachmentsFiles` for extra context
2436
+ * and per-asset CVE `include` layers.
2437
+ */
2438
+ async inventoryEnrich(items, options = {}) {
2439
+ const result = await inventoryEnrich({
2440
+ client: this._client,
2441
+ body: {
2442
+ items: [...items],
2443
+ ...options.attachmentsText !== void 0 && {
2444
+ attachments_text: options.attachmentsText
2445
+ },
2446
+ ...options.attachmentsFiles !== void 0 && {
2447
+ attachments_files: options.attachmentsFiles
2448
+ },
2449
+ ...options.include !== void 0 && { include: [...options.include] }
2450
+ }
2451
+ });
2452
+ return ensureOk(result);
2453
+ }
2454
+ /**
2455
+ * Read the progress or result of an inventory enrichment.
2456
+ *
2457
+ * @param enrichmentId The `enrichment_id` returned by {@link inventoryEnrich}.
2458
+ */
2459
+ async inventoryEnrichStatus(enrichmentId) {
2460
+ const result = await inventoryEnrichStatus({
2461
+ client: this._client,
2462
+ path: { enrichment_id: enrichmentId }
2463
+ });
2464
+ return ensureOk(result);
2465
+ }
2466
+ };
2467
+ function ensureOk(result) {
2468
+ if (result.data !== void 0 && result.error === void 0) {
2469
+ return result.data;
2470
+ }
2471
+ const status = result.response?.status ?? 0;
2472
+ const url = result.response?.url ?? "(no url)";
2473
+ throw new UnexpectedStatus(
2474
+ status,
2475
+ result.error ?? result.data,
2476
+ `Crimson Crawler API ${status} on ${url}`
2477
+ );
2478
+ }
2479
+
2480
+ // package.json
2481
+ var package_default = {
2482
+ version: "4.1.1"};
2483
+
2484
+ // src/index.ts
2485
+ var __version__ = package_default.version;
2486
+
2487
+ export { AiReportsApi, ArtifactManagerApi, BASE_URL, CrawlerClient, CrawlerClientError, DEFAULT_TIMEOUT_MS, ENV_API_KEY, ENV_BASE_URL, ENV_VERIFY_SSL, EnricherApi, InventoryManagerApi, MissingCredentials, UnexpectedStatus, __version__, assembleBriefing, ingestScan };