@knowttl/tenable-axi 0.0.0-stage → 0.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 (66) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +347 -2
  3. package/axi-credential.schema.json +28 -0
  4. package/bin/tenable-axi-hook.js +13 -0
  5. package/bin/tenable-axi.js +8 -0
  6. package/bin/version.js +3 -0
  7. package/dist/src/attack-catalogue.d.ts +176 -0
  8. package/dist/src/attack-catalogue.js +71 -0
  9. package/dist/src/attack-export-catalogue.d.ts +29 -0
  10. package/dist/src/attack-export-catalogue.js +58 -0
  11. package/dist/src/attack-export.d.ts +5 -0
  12. package/dist/src/attack-export.js +151 -0
  13. package/dist/src/attack.d.ts +3 -0
  14. package/dist/src/attack.js +287 -0
  15. package/dist/src/catalogue.d.ts +150 -0
  16. package/dist/src/catalogue.js +68 -0
  17. package/dist/src/cli.d.ts +11 -0
  18. package/dist/src/cli.js +61 -0
  19. package/dist/src/export-file.d.ts +8 -0
  20. package/dist/src/export-file.js +157 -0
  21. package/dist/src/exposure-contracts.d.ts +31 -0
  22. package/dist/src/exposure-contracts.js +31 -0
  23. package/dist/src/exposure.d.ts +4 -0
  24. package/dist/src/exposure.js +323 -0
  25. package/dist/src/hook-install.d.ts +1 -0
  26. package/dist/src/hook-install.js +132 -0
  27. package/dist/src/inventory/schema.d.ts +34 -0
  28. package/dist/src/inventory/schema.js +18 -0
  29. package/dist/src/inventory-catalogue.d.ts +55 -0
  30. package/dist/src/inventory-catalogue.js +62 -0
  31. package/dist/src/inventory-export-catalogue.d.ts +96 -0
  32. package/dist/src/inventory-export-catalogue.js +47 -0
  33. package/dist/src/inventory-export.d.ts +5 -0
  34. package/dist/src/inventory-export.js +164 -0
  35. package/dist/src/inventory.d.ts +3 -0
  36. package/dist/src/inventory.js +285 -0
  37. package/dist/src/local-commands.d.ts +2 -0
  38. package/dist/src/local-commands.js +44 -0
  39. package/dist/src/platform-tag-catalogue.d.ts +101 -0
  40. package/dist/src/platform-tag-catalogue.js +180 -0
  41. package/dist/src/platform-tag.d.ts +4 -0
  42. package/dist/src/platform-tag.js +322 -0
  43. package/dist/src/private-file.d.ts +18 -0
  44. package/dist/src/private-file.js +156 -0
  45. package/dist/src/profiles.d.ts +116 -0
  46. package/dist/src/profiles.js +147 -0
  47. package/dist/src/redact.d.ts +7 -0
  48. package/dist/src/redact.js +41 -0
  49. package/dist/src/response-catalogue.d.ts +41 -0
  50. package/dist/src/response-catalogue.js +134 -0
  51. package/dist/src/response.d.ts +4 -0
  52. package/dist/src/response.js +227 -0
  53. package/dist/src/setup.d.ts +1 -0
  54. package/dist/src/setup.js +39 -0
  55. package/dist/src/transport-core.d.ts +85 -0
  56. package/dist/src/transport-core.js +274 -0
  57. package/dist/src/transport.d.ts +4 -0
  58. package/dist/src/transport.js +6 -0
  59. package/dist/src/writes-core.d.ts +112 -0
  60. package/dist/src/writes-core.js +215 -0
  61. package/dist/src/writes.d.ts +57 -0
  62. package/dist/src/writes.js +5 -0
  63. package/docs/commands.md +1377 -0
  64. package/inventory/capabilities.json +3728 -0
  65. package/package.json +55 -4
  66. package/skills/tenable-axi/SKILL.md +101 -0
@@ -0,0 +1,323 @@
1
+ import { AxiError } from "axi-sdk-js";
2
+ import { createHash } from "node:crypto";
3
+ import { closeSync, openSync, readSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { z } from "zod";
6
+ import { catalogue, DESCRIPTION, SETUP_GUIDANCE } from "./catalogue.js";
7
+ import { cardDetails, cardRecord, properties, tagRecord, TAG_PRIVILEGE } from "./exposure-contracts.js";
8
+ import { createTransport, TransportError } from "./transport.js";
9
+ const operators = ["=", "!=", "<=", "between", "match", ">=", "<", ">", "contains", "not contains", "exists", "not exists", "older than", "newer than", "within last"];
10
+ const filterSchema = z.array(z.strictObject({ property: z.string().min(1), operator: z.enum(operators), value: z.array(z.string()) }));
11
+ const cardFields = ["id", "name", "score", "card_type", "is_global_card", "tag_count", "created_at", "updated_at", "sla_percentage", "ces_trend", "exposure_class", "last_data_update_date", "sources"];
12
+ const detailFields = [...cardFields.filter((field) => !["sla_percentage", "exposure_class"].includes(field)), "ces_scores", "exposures", "exposure_classes_details"];
13
+ const tagFields = ["id", "category", "value", "name", "product", "asset_count", "weakness_severity_counts", "total_weakness_count", "type", "extra_properties"];
14
+ const propertyFields = ["property", "operators", "readable_name", "control", "sortable", "filterable", "description"];
15
+ const cursorSchema = z.strictObject({ scope: z.string(), offset: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
16
+ pending: z.array(cardRecord).max(24).optional(), total: z.number().int().nonnegative().optional() });
17
+ const cursorMaxLength = 64 * 1024;
18
+ const fieldTypes = {
19
+ id: z.string(), name: z.string(), value: z.string(), category: z.string(), score: z.number(),
20
+ product: z.string(), type: z.string(), card_type: z.string(), is_global_card: z.boolean(),
21
+ asset_count: z.number().int(), tag_count: z.number().int(), total_weakness_count: z.number().int(),
22
+ sla_percentage: z.number(), created_at: z.string(), updated_at: z.string(), last_data_update_date: z.string(),
23
+ ces_trend: z.array(z.object({ date: z.string(), ces_score: z.number() }).passthrough()),
24
+ sources: z.array(z.string()), exposures: z.array(z.string()), exposure_class: z.array(z.string()),
25
+ ces_scores: z.object({ total: z.object({ score: z.number() }).passthrough() }).passthrough(),
26
+ exposure_classes_details: z.record(z.string(), z.record(z.string(), z.unknown())),
27
+ extra_properties: z.record(z.string(), z.unknown()), weakness_severity_counts: z.record(z.string(), z.number()),
28
+ };
29
+ export async function exposureCommand(argv, store, factory = createTransport) {
30
+ const name = !argv.length || argv[0]?.startsWith("--") ? "home"
31
+ : ["card", "tag"].includes(argv[0]) ? argv.slice(0, 2).join(" ") : argv[0];
32
+ const entry = catalogue[name];
33
+ const usage = (message = "Unknown command, argument, duplicate or invalid flag") => {
34
+ throw new AxiError(message, "VALIDATION_ERROR", [entry
35
+ ? `Valid flags for ${name}: ${Object.keys(entry.flags).map((flag) => `--${flag}`).join(", ")}`
36
+ : "Valid commands: home, card list, card show, tag list, tag properties, doctor, hook; run tenable-axi --help"]);
37
+ };
38
+ if (!entry)
39
+ usage();
40
+ const flags = new Map();
41
+ const filters = [];
42
+ const start = !argv.length || argv[0]?.startsWith("--") ? 0 : name.includes(" ") ? 2 : 1;
43
+ for (let index = start; index < argv.length; index++) {
44
+ const arg = argv[index];
45
+ const flag = arg.slice(2);
46
+ if (!arg.startsWith("--") || !Object.hasOwn(entry.flags, flag) || (flags.has(flag) && flag !== "filter"))
47
+ usage();
48
+ if (["help", "full", "all"].includes(flag))
49
+ flags.set(flag, "true");
50
+ else {
51
+ const value = argv[++index];
52
+ if (!value || value.startsWith("--"))
53
+ usage();
54
+ flags.set(flag, value);
55
+ if (flag === "filter")
56
+ filters.push(value);
57
+ }
58
+ }
59
+ if (flags.has("help"))
60
+ return { command: name, ...entry };
61
+ const quote = (value) => `'${value.replaceAll("'", "'\"'\"'")}'`;
62
+ const fullCommand = `tenable-axi ${argv.map(quote).join(" ")} --full`;
63
+ const defaults = name === "tag list" ? ["id", "category", "value"] : name === "tag properties" ? ["property", "operators"]
64
+ : name === "doctor" ? ["profile", "origin", "readOnly", "check", "status", "scope"]
65
+ : name === "hook" ? ["profile", "origin", "readOnly"] : name === "card show" ? ["id", "name", "score", "ces_scores", "ces_trend", "exposure_classes_details"] : ["id", "name", "score"];
66
+ const available = name === "tag list" ? tagFields : name === "tag properties" ? propertyFields : name === "card show" ? detailFields
67
+ : ["doctor", "hook"].includes(name) ? defaults : cardFields;
68
+ const fields = flags.get("fields")?.split(",") ?? defaults;
69
+ if (fields.some((field) => !available.includes(field) && !(name === "tag list" && /^[a-zA-Z0-9_]+$/.test(field))) || new Set(fields).size !== fields.length)
70
+ usage("Unknown or duplicate output field");
71
+ const integer = (flag, fallback, minimum, maximum) => {
72
+ const text = flags.get(flag);
73
+ const value = text === undefined ? fallback : Number(text);
74
+ if (text !== undefined && !/^\d+$/.test(text) || !Number.isSafeInteger(value) || value < minimum || value > maximum)
75
+ usage(`Invalid --${flag}`);
76
+ return value;
77
+ };
78
+ if (flags.has("all") && flags.has("limit") || flags.has("cursor") && flags.has("offset"))
79
+ usage("Incompatible paging flags");
80
+ const limit = integer("limit", flags.has("all") ? 10_000 : name === "home" ? 5 : 100, 1, 10_000);
81
+ let offset = integer("offset", 0, 0, Number.MAX_SAFE_INTEGER);
82
+ const query = {};
83
+ for (const [flag, wire] of [["global", "is_global_card"], ["include-trend-events", "include_trend_events"]]) {
84
+ const value = flags.get(flag);
85
+ if (value !== undefined) {
86
+ if (!["true", "false"].includes(value))
87
+ usage(`--${flag} requires true or false`);
88
+ query[wire] = value === "true";
89
+ }
90
+ }
91
+ if (flags.has("sorting-order")) {
92
+ if (!["asc", "desc"].includes(flags.get("sorting-order")))
93
+ usage("Invalid --sorting-order");
94
+ query.sorting_order = flags.get("sorting-order");
95
+ }
96
+ for (const flag of ["trend-start-date", "trend-end-date", "sla-efficiency-start-date", "sla-efficiency-end-date"]) {
97
+ const value = flags.get(flag);
98
+ if (value !== undefined) {
99
+ if (!z.iso.datetime().safeParse(value).success)
100
+ usage(`--${flag} requires a UTC ISO timestamp`);
101
+ query[flag.replaceAll("-", "_")] = value;
102
+ }
103
+ }
104
+ for (const prefix of ["trend", "sla-efficiency"]) {
105
+ const start = flags.get(`${prefix}-start-date`), end = flags.get(`${prefix}-end-date`);
106
+ if ((start === undefined) !== (end === undefined) || start && end && Date.parse(start) > Date.parse(end))
107
+ usage(`Provide an ordered pair of --${prefix}-start-date and --${prefix}-end-date`);
108
+ }
109
+ if (flags.has("sla-breakdown-filter")) {
110
+ const value = flags.get("sla-breakdown-filter");
111
+ if (!["ANY", "REMEDIATED", "NON_REMEDIATED"].includes(value))
112
+ usage("Invalid --sla-breakdown-filter");
113
+ query.sla_breakdown_filter = value;
114
+ }
115
+ if (name === "card show" && (!flags.get("id") || /[\s/%\\]/.test(flags.get("id")) || [".", ".."].includes(flags.get("id"))))
116
+ usage("--id is required and must be a single card identifier");
117
+ if (flags.has("sort")) {
118
+ if (!/^[a-zA-Z0-9_]+:(asc|desc)$/.test(flags.get("sort")))
119
+ usage("--sort requires property:asc or property:desc");
120
+ query.sort = flags.get("sort");
121
+ }
122
+ let body;
123
+ if (name === "tag list") {
124
+ body = {};
125
+ if (flags.has("query"))
126
+ body.query = { mode: "simple", text: flags.get("query") };
127
+ if (flags.has("filter-file") && filters.length)
128
+ usage("--filter-file and --filter are mutually exclusive");
129
+ let input = [];
130
+ try {
131
+ if (flags.has("filter-file")) {
132
+ const fd = flags.get("filter-file") === "-" ? 0 : openSync(flags.get("filter-file"), "r");
133
+ try {
134
+ const bytes = Buffer.alloc(1024 * 1024 + 1);
135
+ let length = 0, count;
136
+ while (length < bytes.length && (count = readSync(fd, bytes, length, bytes.length - length, null)) > 0)
137
+ length += count;
138
+ if (length > 1024 * 1024)
139
+ usage("Filter input exceeds 1 MiB");
140
+ input = JSON.parse(bytes.subarray(0, length).toString("utf8"));
141
+ }
142
+ finally {
143
+ if (fd !== 0)
144
+ closeSync(fd);
145
+ }
146
+ }
147
+ else
148
+ input = filters.map((text) => {
149
+ const match = text.match(/^(\S+)\s+(.+?)\s+(\[.*\])$/s);
150
+ if (!match)
151
+ return usage("--filter requires property operator JSON-array-of-strings");
152
+ return { property: match[1], operator: match[2], value: JSON.parse(match[3]) };
153
+ });
154
+ }
155
+ catch (error) {
156
+ if (error instanceof AxiError)
157
+ throw error;
158
+ usage("Cannot read filters as JSON; use the documented tag filter array");
159
+ }
160
+ const parsed = filterSchema.safeParse(input);
161
+ if (!parsed.success)
162
+ usage("Invalid tag filter array; run tenable-axi tag properties");
163
+ if (parsed.data.length)
164
+ body.filters = parsed.data;
165
+ const extras = flags.get("extra-properties")?.split(",") ?? [];
166
+ if (extras.some((property) => !/^[a-zA-Z0-9_]+$/.test(property)))
167
+ usage("Invalid --extra-properties");
168
+ if (fields.includes("category"))
169
+ extras.push("tag_category_name");
170
+ extras.push(...fields.filter((field) => !tagFields.includes(field)));
171
+ if (extras.length)
172
+ query.extra_properties = [...new Set(extras)].join(",");
173
+ }
174
+ else if (flags.has("query"))
175
+ query.text_query = flags.get("query");
176
+ let parsedCursor;
177
+ if (flags.has("cursor")) {
178
+ try {
179
+ const text = flags.get("cursor");
180
+ if (text.length > cursorMaxLength)
181
+ usage("Invalid cursor");
182
+ parsedCursor = cursorSchema.parse(JSON.parse(Buffer.from(text, "base64url").toString("utf8")));
183
+ if (parsedCursor.pending && (name !== "card list" && name !== "home" || parsedCursor.pending.length > parsedCursor.offset))
184
+ usage("Invalid cursor");
185
+ }
186
+ catch {
187
+ usage("Cursor does not match this profile, operation, fields or filters");
188
+ }
189
+ }
190
+ const config = flags.get("config"), selected = flags.get("profile");
191
+ const identity = { bin: process.argv[1]?.replace(homedir(), "~"), description: DESCRIPTION };
192
+ let profile;
193
+ try {
194
+ store.readOnly();
195
+ profile = store.select(store.load(config, name === "doctor").config, selected);
196
+ }
197
+ catch (error) {
198
+ if (["home", "hook"].includes(name) && error instanceof AxiError && error.code === "PROFILE_REQUIRED") {
199
+ return { ...(name === "home" ? identity : {}), status: "not configured", help: [SETUP_GUIDANCE] };
200
+ }
201
+ throw error;
202
+ }
203
+ const context = { profile: profile.name, origin: profile.origin, readOnly: store.readOnly() || !profile.writes.allowWrites || !profile.writes.operations.length };
204
+ const select = (record) => Object.fromEntries(fields.map((field) => [field, record[field] ?? null]));
205
+ if (name === "hook")
206
+ return select(context);
207
+ const operation = name === "tag list" ? "inventory-tag-search" : "exposure-view-cards-search";
208
+ const scope = createHash("sha256").update(JSON.stringify([profile.origin, profile.name, store.configPath(config), operation, query, body, fields])).digest("hex");
209
+ if (parsedCursor) {
210
+ if (parsedCursor.scope !== scope)
211
+ usage("Cursor does not match this profile, operation, fields or filters");
212
+ offset = parsedCursor.offset;
213
+ }
214
+ const keys = store.credentials(profile, name === "doctor");
215
+ const transport = factory({ keys, origin: profile.origin });
216
+ if (name === "doctor") {
217
+ try {
218
+ await transport.request("inventory-tag-properties-list", { retry: false });
219
+ }
220
+ catch (error) {
221
+ if (error instanceof TransportError && error.error.status === 401)
222
+ throw new TransportError(error.error, [...error.help, `This check requires ${TAG_PRIVILEGE}; authentication failure does not establish module access`]);
223
+ throw error;
224
+ }
225
+ return select({ ...context, check: "inventory-tag-properties-list", status: "ok", scope: `Verified one tag-properties read (${TAG_PRIVILEGE}); other modules are untested` });
226
+ }
227
+ const truncated = [];
228
+ function preview(value, path) {
229
+ if (typeof value === "string" && value.length > 1000 && !flags.has("full")) {
230
+ truncated.push(path);
231
+ return { text: value.slice(0, 1000), length: value.length };
232
+ }
233
+ if (Array.isArray(value))
234
+ return value.map((item, index) => preview(item, `${path}.${index}`));
235
+ if (value && typeof value === "object")
236
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, preview(item, `${path}.${key}`)]));
237
+ return value;
238
+ }
239
+ function project(record, detail = false) {
240
+ const mapped = { ...record };
241
+ if (name === "tag list") {
242
+ for (const field of fields.filter((field) => !tagFields.includes(field)))
243
+ mapped[field] = record.extra_properties?.[field];
244
+ mapped.value = record.name;
245
+ mapped.category = record.extra_properties?.tag_category_name ?? null;
246
+ }
247
+ else
248
+ mapped.score = detail ? record.ces_scores?.total?.score : record.ces_score?.score;
249
+ if (fields.includes("score") && mapped.score === undefined)
250
+ throw new TransportError({ code: "RESPONSE_INVALID", message: "Card response is missing the selected score", operation: detail ? "exposure-view-card-details" : "exposure-view-cards-search" });
251
+ for (const field of fields) {
252
+ if (mapped[field] != null && fieldTypes[field] && !fieldTypes[field].safeParse(mapped[field]).success) {
253
+ throw new TransportError({ code: "RESPONSE_INVALID", message: `Response has an invalid ${field} field`, operation: detail ? "exposure-view-card-details" : operation });
254
+ }
255
+ }
256
+ return preview(store.redactor.payload(select(mapped)), "data");
257
+ }
258
+ if (name === "card show") {
259
+ const response = await transport.request("exposure-view-card-details", { pathParams: { card_id: flags.get("id") }, query });
260
+ const card = project(cardDetails.parse(response.body), true);
261
+ return { card, ...(truncated.length ? { help: [`Run ${fullCommand} to see full text`] } : {}) };
262
+ }
263
+ if (name === "tag properties") {
264
+ const response = properties.parse((await transport.request("inventory-tag-properties-list")).body);
265
+ const rows = response.data.map((record) => preview(store.redactor.payload(select({ ...record, property: record.key })), "properties"));
266
+ return { properties: rows, count: rows.length, complete: true, ...(rows.length ? {} : { message: "0 tag properties available" }), ...(truncated.length ? { help: [`Run ${fullCommand} to see full text`] } : {}) };
267
+ }
268
+ const rows = [];
269
+ const pages = new Set();
270
+ let pending = parsedCursor?.pending ?? [];
271
+ let total = parsedCursor?.total, complete = false, reason = "limit", failure;
272
+ const buffered = pending.map((record) => project(record));
273
+ rows.push(...buffered.slice(0, limit));
274
+ pending = pending.slice(rows.length);
275
+ complete = !pending.length && total !== undefined && offset >= total;
276
+ for (let page = 0; page < 20 && !complete && rows.length < limit; page++) {
277
+ const window = Math.min(name === "tag list" ? 1000 : 25, limit - rows.length);
278
+ try {
279
+ const response = (await transport.request(operation, { query: { ...query, limit: window, offset }, ...(body ? { body } : {}) })).body;
280
+ if (response.data.length > (name === "tag list" ? window : 25))
281
+ throw new TransportError({ code: "RESPONSE_INVALID", message: "Tenable returned more rows than the page bound", operation });
282
+ const records = response.data.map((record) => project(name === "tag list" ? tagRecord.parse(record) : cardRecord.parse(record)));
283
+ const pageIdentity = JSON.stringify(response.data.map((record) => record.id));
284
+ if (records.length && pages.has(pageIdentity))
285
+ throw new TransportError({ code: "CONTINUATION_REPEATED", message: "Tenable repeated a result page; resume after checking the collection", operation });
286
+ pages.add(pageIdentity);
287
+ const remainder = response.data.slice(window);
288
+ // Redact before encoding: base64 cursors must not bypass output redaction.
289
+ const nextPending = store.redactor.payload(remainder);
290
+ const nextTotal = response.pagination?.total_record_count ?? response.pagination?.total ?? total;
291
+ const nextCursor = Buffer.from(JSON.stringify({ scope, offset: offset + records.length, pending: nextPending, total: nextTotal })).toString("base64url");
292
+ if (nextCursor.length > cursorMaxLength)
293
+ throw new TransportError({ code: "RESPONSE_INVALID", message: "Card continuation exceeds the cursor byte bound", operation });
294
+ pending = nextPending;
295
+ rows.push(...records.slice(0, window));
296
+ offset += records.length;
297
+ total = nextTotal;
298
+ complete = !pending.length && (records.length === 0 || total !== undefined && offset >= total);
299
+ if (complete || rows.length >= limit || name === "home")
300
+ break;
301
+ reason = "request budget";
302
+ }
303
+ catch (error) {
304
+ if (!(error instanceof TransportError) || !rows.length)
305
+ throw error;
306
+ reason = error.error.code;
307
+ if (!["REQUEST_BUDGET_EXCEEDED", "DEADLINE_EXCEEDED", "BYTE_BUDGET_EXCEEDED"].includes(reason))
308
+ failure = error;
309
+ break;
310
+ }
311
+ }
312
+ if (failure)
313
+ process.exitCode = 1;
314
+ const noun = name === "tag list" ? "tags" : "cards";
315
+ const suffix = [config ? `--config ${quote(config)}` : "", selected ? `--profile ${quote(selected)}` : ""].filter(Boolean).join(" ");
316
+ const resumeArgs = argv.slice(start).filter((arg, index, args) => !["--cursor", "--offset"].includes(arg) && !["--cursor", "--offset"].includes(args[index - 1] ?? ""));
317
+ const cursor = Buffer.from(JSON.stringify({ scope, offset, ...(pending.length ? { pending } : {}), ...(total === undefined ? {} : { total }) })).toString("base64url");
318
+ return { ...(name === "home" ? { ...identity, ...context } : {}), [noun]: rows, count: rows.length, ...(total === undefined ? {} : { total }), complete,
319
+ ...(!rows.length ? { message: `0 ${noun} matched the selected filters` } : {}),
320
+ ...(!complete ? { reason, cursor } : {}),
321
+ ...(failure ? failure.toJSON() : {}),
322
+ help: [`Run tenable-axi ${noun === "cards" ? "card show --id <id>" : "tag properties"} ${suffix}`.trim(), ...(!complete ? [`Run tenable-axi ${noun === "cards" ? "card list" : "tag list"} ${resumeArgs.map(quote).join(" ")} --cursor ${quote(cursor)}`] : []), ...(truncated.length ? [`Run ${fullCommand} to see full text`] : [])] };
323
+ }
@@ -0,0 +1 @@
1
+ export declare function installHooks(execPath: string, scope: "user" | "project", onError: (message: string) => void): void;
@@ -0,0 +1,132 @@
1
+ import { computeSessionStartHookUpdate, extractNpmShimScriptPath } from "axi-sdk-js";
2
+ import { accessSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { delimiter, dirname, join, resolve } from "node:path";
5
+ import { parse, stringify } from "smol-toml";
6
+ function portableHookCommand(execPath, name) {
7
+ const extensions = process.platform === "win32" ? ["", ...(process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";")] : [""];
8
+ for (const directory of (process.env.PATH ?? process.env.Path ?? "").split(delimiter)) {
9
+ for (const extension of extensions) {
10
+ const candidate = resolve(directory || ".", `${name}${extension}`);
11
+ try {
12
+ if (!statSync(candidate).isFile())
13
+ continue;
14
+ accessSync(candidate, constants.X_OK);
15
+ }
16
+ catch {
17
+ continue;
18
+ }
19
+ try {
20
+ if (realpathSync(candidate) === execPath)
21
+ return name;
22
+ if (process.platform === "win32") {
23
+ const target = extractNpmShimScriptPath(readFileSync(candidate, "utf8"));
24
+ if (target && realpathSync(resolve(dirname(candidate), target)) === execPath)
25
+ return name;
26
+ }
27
+ }
28
+ catch {
29
+ return execPath;
30
+ }
31
+ return execPath;
32
+ }
33
+ }
34
+ return execPath;
35
+ }
36
+ export function installHooks(execPath, scope, onError) {
37
+ const marker = "tenable-axi-hook";
38
+ const home = homedir();
39
+ const root = process.cwd();
40
+ const codexHome = process.env.CODEX_HOME || join(home, ".codex");
41
+ const claudeSettingsPath = join(scope === "project" ? join(root, ".claude") : process.env.CLAUDE_CONFIG_DIR || join(home, ".claude"), "settings.json");
42
+ const codexHooksPath = join(scope === "project" ? join(root, ".codex") : codexHome, "hooks.json");
43
+ const openCodeDirectory = scope === "project" ? join(root, ".opencode") : join(process.env.XDG_CONFIG_HOME || join(home, ".config"), "opencode");
44
+ const command = portableHookCommand(execPath, marker);
45
+ const shellCommand = command === marker ? command : `'${command.replaceAll("'", "'\\''")}'`;
46
+ const update = (path, transform) => {
47
+ try {
48
+ const current = existsSync(path) ? readFileSync(path, "utf8") : "";
49
+ const next = transform(current);
50
+ if (current !== next) {
51
+ mkdirSync(dirname(path), { recursive: true });
52
+ writeFileSync(path, next, "utf8");
53
+ }
54
+ }
55
+ catch (error) {
56
+ onError(`${path}: ${error instanceof Error ? error.message : String(error)}`);
57
+ }
58
+ };
59
+ for (const path of [claudeSettingsPath, codexHooksPath]) {
60
+ update(path, (current) => {
61
+ const settings = current ? JSON.parse(current) : {};
62
+ for (const group of settings.hooks?.SessionStart ?? []) {
63
+ for (const hook of group.hooks ?? []) {
64
+ if (Array.isArray(hook.args) && hook.args.some((arg) => typeof arg === "string" && arg.includes(marker))) {
65
+ hook.command = shellCommand;
66
+ }
67
+ }
68
+ }
69
+ const [next] = computeSessionStartHookUpdate(settings, { marker, command: shellCommand });
70
+ const hook = next.hooks.SessionStart.flatMap((group) => group.hooks ?? [])
71
+ .find((hook) => hook.command === shellCommand);
72
+ delete hook.args;
73
+ delete hook.commandWindows;
74
+ if (process.platform === "win32") {
75
+ if (path === claudeSettingsPath) {
76
+ hook.command = process.execPath;
77
+ hook.args = [execPath];
78
+ }
79
+ else {
80
+ const argv = Buffer.from(JSON.stringify([process.execPath, execPath])).toString("base64");
81
+ const script = `$ErrorActionPreference = 'Stop'; $argv = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${argv}')) | ConvertFrom-Json; & $argv[0] $argv[1]; exit $LASTEXITCODE`;
82
+ hook.commandWindows = `powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script, "utf16le").toString("base64")}`;
83
+ }
84
+ }
85
+ return `${JSON.stringify(next, null, 2)}\n`;
86
+ });
87
+ }
88
+ update(join(codexHome, "config.toml"), (current) => {
89
+ const config = parse(current, { integersAsBigInt: true });
90
+ const features = config.features ?? {};
91
+ if (typeof features !== "object" || features === null || Array.isArray(features) || features instanceof Date) {
92
+ throw new Error("Codex features must be a TOML table");
93
+ }
94
+ const table = features;
95
+ if (table.hooks === true)
96
+ return current;
97
+ table.hooks = true;
98
+ config.features = table;
99
+ return stringify(config);
100
+ });
101
+ const managedMarker = `axi-sdk-js managed opencode plugin: ${marker}`;
102
+ update(join(openCodeDirectory, "plugins/axi-tenable-axi-hook.js"), (current) => {
103
+ if (current && !current.includes(managedMarker))
104
+ throw new Error("refusing to overwrite unmanaged OpenCode plugin");
105
+ return `// ${managedMarker}
106
+ import { execFile } from "node:child_process";
107
+
108
+ function ambientContext(directory) {
109
+ const sessions = new Map();
110
+ return (sessionID) => {
111
+ if (!sessions.has(sessionID)) {
112
+ sessions.set(sessionID, new Promise((resolve) => {
113
+ execFile(${JSON.stringify(process.execPath)}, [${JSON.stringify(execPath)}], { cwd: directory, timeout: 10000 }, (error, stdout, stderr) => {
114
+ const text = error ? "error: tenable-axi-hook ambient context failed: " + (stderr || stdout || error.message).trim() : stdout.trim();
115
+ resolve(text ? "## AXI ambient context: tenable-axi-hook\\n" + text : "");
116
+ });
117
+ }));
118
+ }
119
+ return sessions.get(sessionID);
120
+ };
121
+ }
122
+
123
+ export default async function ({ directory }) {
124
+ const context = ambientContext(directory);
125
+ return { "experimental.chat.system.transform": async (input, output) => {
126
+ const text = await context(input.sessionID);
127
+ if (text) output.system.push(text);
128
+ } };
129
+ }
130
+ `;
131
+ });
132
+ }
@@ -0,0 +1,34 @@
1
+ import { z } from "zod";
2
+ export declare const inventorySchema: z.ZodObject<{
3
+ schemaVersion: z.ZodLiteral<1>;
4
+ sources: z.ZodArray<z.ZodObject<{
5
+ id: z.ZodString;
6
+ url: z.ZodURL;
7
+ sha256: z.ZodString;
8
+ operations: z.ZodNumber;
9
+ }, z.core.$strict>>;
10
+ operations: z.ZodArray<z.ZodObject<{
11
+ source: z.ZodString;
12
+ operationId: z.ZodString;
13
+ method: z.ZodEnum<{
14
+ GET: "GET";
15
+ POST: "POST";
16
+ PUT: "PUT";
17
+ PATCH: "PATCH";
18
+ DELETE: "DELETE";
19
+ HEAD: "HEAD";
20
+ OPTIONS: "OPTIONS";
21
+ TRACE: "TRACE";
22
+ }>;
23
+ path: z.ZodString;
24
+ disposition: z.ZodEnum<{
25
+ "v1-read": "v1-read";
26
+ "v1-write": "v1-write";
27
+ blocked: "blocked";
28
+ }>;
29
+ plannedCommands: z.ZodArray<z.ZodString>;
30
+ reason: z.ZodString;
31
+ slice: z.ZodNullable<z.ZodString>;
32
+ }, z.core.$strict>>;
33
+ }, z.core.$strict>;
34
+ export type CapabilityInventory = z.infer<typeof inventorySchema>;
@@ -0,0 +1,18 @@
1
+ import { z } from "zod";
2
+ const text = z.string().min(1);
3
+ export const inventorySchema = z.strictObject({
4
+ schemaVersion: z.literal(1),
5
+ sources: z.array(z.strictObject({
6
+ id: text, url: z.url(), sha256: z.string().regex(/^[a-f0-9]{64}$/), operations: z.number().int().positive(),
7
+ })),
8
+ operations: z.array(z.strictObject({
9
+ source: text,
10
+ operationId: text,
11
+ method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "TRACE"]),
12
+ path: z.string().startsWith("/"),
13
+ disposition: z.enum(["v1-read", "v1-write", "blocked"]),
14
+ plannedCommands: z.array(text),
15
+ reason: text,
16
+ slice: z.string().regex(/^T\d+$/).nullable(),
17
+ })),
18
+ });
@@ -0,0 +1,55 @@
1
+ import { z } from "zod";
2
+ import type { OperationBinding } from "./transport-core.js";
3
+ export declare const inventoryKinds: {
4
+ readonly asset: "assets";
5
+ readonly finding: "findings";
6
+ readonly software: "software";
7
+ };
8
+ export type InventoryKind = keyof typeof inventoryKinds;
9
+ export declare const defaultFields: {
10
+ asset: string[];
11
+ finding: string[];
12
+ software: string[];
13
+ };
14
+ export declare const aliases: Record<InventoryKind, Record<string, string>>;
15
+ export declare const wireFields: Record<InventoryKind, Record<string, z.ZodType>>;
16
+ export declare const propertyFields: Record<string, z.ZodType>;
17
+ export declare const assetClasses: readonly ["ACCOUNT", "APPLICATION", "CONTAINER", "DEVICE", "GENERAL", "GROUP", "IAC", "IDENTITY", "RESOURCE", "ROLE", "STORAGE", "UNKNOWN"];
18
+ export declare const filterSchema: z.ZodObject<{
19
+ property: z.ZodString;
20
+ operator: z.ZodEnum<{
21
+ match: "match";
22
+ contains: "contains";
23
+ "=": "=";
24
+ "!=": "!=";
25
+ "<=": "<=";
26
+ between: "between";
27
+ ">=": ">=";
28
+ "<": "<";
29
+ ">": ">";
30
+ "not contains": "not contains";
31
+ exists: "exists";
32
+ "not exists": "not exists";
33
+ "older than": "older than";
34
+ "newer than": "newer than";
35
+ "within last": "within last";
36
+ }>;
37
+ value: z.ZodArray<z.ZodString>;
38
+ }, z.core.$strict>;
39
+ export declare const inventoryPage: z.ZodObject<{
40
+ data: z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
41
+ pagination: z.ZodOptional<z.ZodObject<{
42
+ total: z.ZodOptional<z.ZodNumber>;
43
+ offset: z.ZodNumber;
44
+ limit: z.ZodNumber;
45
+ }, z.core.$strip>>;
46
+ }, z.core.$strip>;
47
+ export declare const inventoryBindings: Readonly<Record<string, OperationBinding>>;
48
+ export declare const inventoryCatalogue: Record<string, {
49
+ description: string;
50
+ flags: Record<string, string>;
51
+ examples: string[];
52
+ operationId: string;
53
+ defaultFields: string[];
54
+ evidence: string;
55
+ }>;
@@ -0,0 +1,62 @@
1
+ import { z } from "zod";
2
+ export const inventoryKinds = { asset: "assets", finding: "findings", software: "software" };
3
+ export const defaultFields = { asset: ["id", "name", "class", "exposureScore"], finding: ["id", "name", "severity", "state"],
4
+ software: ["name", "version", "publisher"] };
5
+ export const aliases = {
6
+ asset: { class: "asset_class", exposureScore: "aes" }, finding: {}, software: { name: "application" },
7
+ };
8
+ export const wireFields = {
9
+ asset: { id: z.string(), name: z.string(), asset_class: z.string(), aes: z.number(), acr: z.number() },
10
+ finding: { id: z.string(), name: z.string(), severity: z.string(), state: z.string(), asset_id: z.string() },
11
+ software: { application: z.string(), publisher: z.string(), type: z.array(z.string()), devices_count: z.number().int().nonnegative() },
12
+ };
13
+ export const propertyFields = { key: z.string(), readable_name: z.string(), operators: z.array(z.string()),
14
+ sortable: z.boolean(), filterable: z.boolean(), control: z.record(z.string(), z.unknown()), description: z.string() };
15
+ export const assetClasses = ["ACCOUNT", "APPLICATION", "CONTAINER", "DEVICE", "GENERAL", "GROUP", "IAC", "IDENTITY", "RESOURCE", "ROLE", "STORAGE", "UNKNOWN"];
16
+ export const filterSchema = z.strictObject({
17
+ property: z.string().min(1),
18
+ operator: z.enum(["=", "!=", "<=", "between", "match", ">=", "<", ">", "contains", "not contains", "exists", "not exists", "older than", "newer than", "within last"]),
19
+ value: z.array(z.string()),
20
+ });
21
+ export const inventoryPage = z.object({
22
+ data: z.array(z.record(z.string(), z.unknown())),
23
+ pagination: z.object({ total: z.number().int().nonnegative().optional(), offset: z.number().int().nonnegative(),
24
+ limit: z.number().int().positive() }).optional(),
25
+ });
26
+ const properties = z.array(z.record(z.string(), z.unknown()));
27
+ export const inventoryBindings = Object.freeze(Object.fromEntries(Object.keys(inventoryKinds).flatMap((kind) => {
28
+ const noun = inventoryKinds[kind];
29
+ const advice = {
30
+ permissionHelp: "Inventory reads require EXPOSURE_MANAGEMENT.INVENTORY.INVENTORY.READ; check the selected user's access",
31
+ validationHelp: `Run tenable-axi ${kind} properties to discover supported properties and operators`,
32
+ };
33
+ return [
34
+ [`inventory-${noun}-search`, { ...advice, method: "POST", path: `/api/v1/t1/inventory/${noun}/search`,
35
+ effect: "read", query: ["offset", "limit", "sort", "extra_properties"], paging: ["offset", "limit"], decoder: inventoryPage }],
36
+ [`inventory-${kind}-properties-list`, { ...advice, method: "GET", path: `/api/v1/t1/inventory/${noun}/properties`,
37
+ effect: "read", query: kind === "asset" ? ["asset_classes"] : [],
38
+ decoder: kind === "asset" ? z.union([z.object({ properties }).transform(({ properties }) => ({ data: properties })),
39
+ z.object({ data: properties })]) : z.object({ data: properties }) }],
40
+ ];
41
+ })));
42
+ const common = { config: "Config path; default credential precedence", profile: "Profile name; default credential precedence",
43
+ fields: "Comma-separated display or wire properties; default compact view", full: "Show full text; default false", help: "Show help" };
44
+ const collection = { limit: "Maximum emitted rows, 1-10000; default 100", all: "Read up to 10000 rows within invocation budgets; excludes --limit",
45
+ cursor: "Opaque resume cursor; retain the original selectors and filters" };
46
+ const search = { query: "Simple query text", filter: "Repeatable: <property> <operator> <JSON string array>",
47
+ "filter-file": "JSON flat array of {property, operator, value: string[]}; '-' reads stdin; excludes --filter",
48
+ sort: "Wire property:asc|desc", "extra-properties": "Comma-separated extra wire properties", offset: "Starting record; default 0; excludes --cursor" };
49
+ export const inventoryCatalogue = Object.fromEntries(Object.keys(inventoryKinds).flatMap((kind) => [
50
+ [`${kind} list`, { description: `Search ${inventoryKinds[kind]}${kind === "software" ? "; the pinned API exposes no stable software ID" : ""}`,
51
+ operationId: `inventory-${inventoryKinds[kind]}-search`, defaultFields: defaultFields[kind], evidence: "specs/exposure-management.json",
52
+ flags: { ...common, ...collection, ...search, ...(kind === "asset" ? { class: "Server-side asset class filter" } : {}) },
53
+ examples: [`tenable-axi ${kind} list --limit 20`, `tenable-axi ${kind} list --query example`] }],
54
+ [`${kind} properties`, { description: `Discover ${kind} properties and supported operators`,
55
+ operationId: `inventory-${kind}-properties-list`, defaultFields: ["key", "readable_name", "operators", "sortable", "filterable"], evidence: "specs/exposure-management.json",
56
+ flags: { ...common, ...collection, ...(kind === "asset" ? { "asset-classes": "Comma-separated documented asset classes" } : {}) },
57
+ examples: [`tenable-axi ${kind} properties`, `tenable-axi ${kind} properties --full`] }],
58
+ ...(kind === "software" ? [] : [[`${kind} show`, { description: `Find one ${kind} by exact ID search`,
59
+ operationId: `inventory-${inventoryKinds[kind]}-search`, defaultFields: defaultFields[kind], evidence: "specs/exposure-management.json",
60
+ flags: { ...common, id: "Required exact inventory ID", "extra-properties": search["extra-properties"] },
61
+ examples: [`tenable-axi ${kind} show --id <id>`, `tenable-axi ${kind} show --id <id> --fields id,name,description --full`] }]]),
62
+ ]));