@knowttl/tenable-axi 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +341 -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 +305 -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 +61 -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 +162 -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 +312 -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 +24 -4
  66. package/skills/tenable-axi/SKILL.md +101 -0
@@ -0,0 +1,96 @@
1
+ import { z } from "zod";
2
+ import type { OperationBinding } from "./transport-core.js";
3
+ import type { MutationOperation } from "./writes-core.js";
4
+ export declare const exportState: z.ZodEnum<{
5
+ QUEUED: "QUEUED";
6
+ PROCESSING: "PROCESSING";
7
+ FINISHED: "FINISHED";
8
+ ERROR: "ERROR";
9
+ }>;
10
+ export declare const exportFields: Record<string, z.ZodType>;
11
+ export declare const exportBody: z.ZodNullable<z.ZodObject<{
12
+ filters: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodObject<{
13
+ property: z.ZodString;
14
+ operator: z.ZodEnum<{
15
+ "": "";
16
+ match: "match";
17
+ contains: "contains";
18
+ "=": "=";
19
+ "!=": "!=";
20
+ "<=": "<=";
21
+ between: "between";
22
+ ">=": ">=";
23
+ "<": "<";
24
+ ">": ">";
25
+ "not contains": "not contains";
26
+ exists: "exists";
27
+ "not exists": "not exists";
28
+ "older than": "older than";
29
+ "newer than": "newer than";
30
+ "within last": "within last";
31
+ }>;
32
+ value: z.ZodArray<z.ZodString>;
33
+ }, z.core.$strict>>>>;
34
+ query: z.ZodOptional<z.ZodObject<{
35
+ mode: z.ZodEnum<{
36
+ simple: "simple";
37
+ advanced: "advanced";
38
+ }>;
39
+ text: z.ZodString;
40
+ }, z.core.$strict>>;
41
+ }, z.core.$strict>>;
42
+ export declare const exportInput: z.ZodObject<{
43
+ body: z.ZodOptional<z.ZodNullable<z.ZodObject<{
44
+ filters: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodObject<{
45
+ property: z.ZodString;
46
+ operator: z.ZodEnum<{
47
+ "": "";
48
+ match: "match";
49
+ contains: "contains";
50
+ "=": "=";
51
+ "!=": "!=";
52
+ "<=": "<=";
53
+ between: "between";
54
+ ">=": ">=";
55
+ "<": "<";
56
+ ">": ">";
57
+ "not contains": "not contains";
58
+ exists: "exists";
59
+ "not exists": "not exists";
60
+ "older than": "older than";
61
+ "newer than": "newer than";
62
+ "within last": "within last";
63
+ }>;
64
+ value: z.ZodArray<z.ZodString>;
65
+ }, z.core.$strict>>>>;
66
+ query: z.ZodOptional<z.ZodObject<{
67
+ mode: z.ZodEnum<{
68
+ simple: "simple";
69
+ advanced: "advanced";
70
+ }>;
71
+ text: z.ZodString;
72
+ }, z.core.$strict>>;
73
+ }, z.core.$strict>>>;
74
+ query: z.ZodObject<{
75
+ properties: z.ZodOptional<z.ZodString>;
76
+ use_readable_name: z.ZodOptional<z.ZodBoolean>;
77
+ max_chunk_file_size: z.ZodOptional<z.ZodNumber>;
78
+ sort: z.ZodOptional<z.ZodString>;
79
+ file_format: z.ZodOptional<z.ZodEnum<{
80
+ CSV: "CSV";
81
+ JSON: "JSON";
82
+ }>>;
83
+ compress: z.ZodOptional<z.ZodBoolean>;
84
+ }, z.core.$strict>;
85
+ }, z.core.$strict>;
86
+ export declare const inventoryExportBindings: Readonly<Record<string, OperationBinding>>;
87
+ export declare const inventoryExportMutations: Readonly<Record<string, MutationOperation>>;
88
+ type Entry = {
89
+ description: string;
90
+ operationId: string;
91
+ flags: Record<string, string>;
92
+ defaultFields: string[];
93
+ examples: string[];
94
+ };
95
+ export declare const inventoryExportCatalogue: Record<string, Entry>;
96
+ export {};
@@ -0,0 +1,47 @@
1
+ import { z } from "zod";
2
+ export const exportState = z.enum(["QUEUED", "PROCESSING", "FINISHED", "ERROR"]);
3
+ const id = z.string().uuid();
4
+ export const exportFields = { id, state: exportState, createdAt: z.string().datetime({ offset: true }),
5
+ availableChunks: z.array(z.number().int().nonnegative()), export_type: z.enum(["assets", "findings"]),
6
+ last_refreshed_at: z.string().datetime({ offset: true }) };
7
+ const filter = z.strictObject({ property: z.string(), operator: z.enum(["", "=", "!=", "<=", "between", "match", ">=", "<", ">", "contains", "not contains", "exists", "not exists", "older than", "newer than", "within last"]), value: z.array(z.string()) });
8
+ export const exportBody = z.strictObject({ filters: z.array(filter).nullable().optional(),
9
+ query: z.strictObject({ mode: z.enum(["simple", "advanced"]), text: z.string() }).optional() }).nullable();
10
+ export const exportInput = z.strictObject({ body: exportBody.optional(), query: z.strictObject({
11
+ properties: z.string().regex(/^[a-zA-Z0-9_]+(,[a-zA-Z0-9_]+)*$/).optional(),
12
+ use_readable_name: z.boolean().optional(), max_chunk_file_size: z.number().int().min(5242880).max(104857600).optional(),
13
+ sort: z.string().regex(/^[a-zA-Z0-9_]+:(asc|desc)$/).optional(), file_format: z.enum(["CSV", "JSON"]).optional(), compress: z.boolean().optional(),
14
+ }) });
15
+ const base = "/api/v1/t1/inventory/export";
16
+ const permissionHelp = "Requires Basic [16] or EXPOSURE_MANAGEMENT.INVENTORY.INVENTORY.EXPORT";
17
+ const validationHelp = "Run tenable-axi export inventory status --help; check the export ID and available chunks";
18
+ const commonBinding = { permissionHelp, validationHelp };
19
+ export const inventoryExportBindings = {
20
+ ...Object.fromEntries(["assets", "findings"].flatMap((kind) => [
21
+ [`inventory-export-${kind}`, { ...commonBinding, method: "POST", path: `${base}/${kind}`, effect: "write",
22
+ query: Object.keys(exportInput.shape.query.shape), decoder: z.object({ export_id: id }),
23
+ validationHelp: `Run tenable-axi ${kind === "assets" ? "asset" : "finding"} properties; check the documented export filters and options` }],
24
+ [`inventory-export-${kind}-jobs`, { ...commonBinding, method: "GET", path: `${base}/${kind}/status`, effect: "read",
25
+ query: ["status", "limit"], decoder: z.object({ exports: z.array(z.record(z.string(), z.unknown())) }) }],
26
+ ])),
27
+ "inventory-export-status": { ...commonBinding, method: "GET", path: `${base}/{export_id}/status`, effect: "read", query: [], decoder: z.record(z.string(), z.unknown()) },
28
+ "inventory-export-download": { ...commonBinding, method: "GET", path: `${base}/{export_id}/download/{chunk_id}`, effect: "read", query: [], decoder: z.unknown(), responseMode: "file" },
29
+ };
30
+ export const inventoryExportMutations = Object.fromEntries(["assets", "findings"].map((kind) => [
31
+ `inventory-export-${kind}`, { input: exportInput,
32
+ prepare: (input) => ({ target: { kind: `inventory-${kind}-export`, payload: true }, request: exportInput.parse(input) }),
33
+ effect: "Create one tenant-side inventory export job with the selected filters, properties, format and compression; no server dry run or idempotency guarantee",
34
+ readBackHelp: [`Run tenable-axi export ${kind === "assets" ? "asset" : "finding"} jobs to reconcile creation; never replay an unknown outcome`], },
35
+ ]));
36
+ const common = { config: "Config path; default platform path", profile: "Profile name; default credential precedence", fields: "Comma-separated output fields; default compact view", full: "Full output; default false", help: "Show help" };
37
+ export const inventoryExportCatalogue = {};
38
+ for (const kind of ["asset", "finding"]) {
39
+ inventoryExportCatalogue[`export ${kind} start`] = { description: `Preview or create an inventory ${kind} export job`, operationId: `inventory-export-${kind}s`,
40
+ flags: { ...common, "body-file": "Optional strict query/filters JSON file, '-' for stdin; maximum 1 MiB", properties: "Comma-separated property names", "use-readable-name": "true|false; API default true",
41
+ "max-chunk-file-size": "5242880-104857600 bytes; API default 20971520", sort: "property:asc|desc", "file-format": "JSON|CSV; API default JSON", compress: "true|false; API default false",
42
+ execute: "Create once; default preview", "dry-run": "Explicit preview; excludes --execute", confirm: "Exact confirmation from preview", "intent-id": "Unique execution intent for replay protection" },
43
+ defaultFields: ["id", "state"], examples: [`tenable-axi export ${kind} start --body-file scope.json`, `tenable-axi export ${kind} start --body-file scope.json --execute --confirm <confirmation>`] };
44
+ inventoryExportCatalogue[`export ${kind} jobs`] = { description: `List recent inventory ${kind} export jobs`, operationId: `inventory-export-${kind}s-jobs`, flags: { ...common, status: "QUEUED|PROCESSING|FINISHED|ERROR", limit: "1-1000; default 100; last three days only" }, defaultFields: ["id", "state", "createdAt"], examples: [`tenable-axi export ${kind} jobs`, `tenable-axi export ${kind} jobs --status FINISHED --limit 10`] };
45
+ }
46
+ inventoryExportCatalogue["export inventory status"] = { description: "Read one inventory export status without polling", operationId: "inventory-export-status", flags: { ...common, id: "Required export UUID" }, defaultFields: ["id", "state", "availableChunks"], examples: ["tenable-axi export inventory status --id <id>", "tenable-axi export inventory status --id <id> --fields id,state,createdAt"] };
47
+ inventoryExportCatalogue["export inventory download"] = { description: "Download one inventory chunk to a new redacted file", operationId: "inventory-export-download", flags: { ...common, id: "Required export UUID", chunk: "Required nonnegative chunk number from status", output: "Required new output file; refuses overwrite" }, defaultFields: ["id", "chunk", "output", "bytes", "format", "compressed"], examples: ["tenable-axi export inventory download --id <id> --chunk 1 --output assets.json", "tenable-axi export inventory download --id <id> --chunk 2 --output assets.csv.gz"] };
@@ -0,0 +1,5 @@
1
+ import type { credentialStore } from "./profiles.js";
2
+ import type { TransportFactory } from "./exposure.js";
3
+ import { createWriteCoordinator, type WriteCoordinatorOptions } from "./writes.js";
4
+ export type WriteCoordinatorFactory = (options: WriteCoordinatorOptions) => ReturnType<typeof createWriteCoordinator>;
5
+ export declare function inventoryExportCommand(argv: string[], store: ReturnType<typeof credentialStore>, factory?: TransportFactory, writeFactory?: WriteCoordinatorFactory): Promise<Record<string, unknown>>;
@@ -0,0 +1,162 @@
1
+ import { AxiError } from "axi-sdk-js";
2
+ import { closeSync, openSync, readSync } from "node:fs";
3
+ import { z } from "zod";
4
+ import { exportFields, exportInput, exportState, inventoryExportCatalogue } from "./inventory-export-catalogue.js";
5
+ import { exportOutputPath, saveExport } from "./export-file.js";
6
+ import { createTransport, TransportError } from "./transport.js";
7
+ import { createWriteCoordinator } from "./writes.js";
8
+ function bodyFile(path) {
9
+ const fd = path === "-" ? 0 : openSync(path, "r");
10
+ try {
11
+ const chunks = [];
12
+ let size = 0;
13
+ for (;;) {
14
+ const chunk = Buffer.alloc(8192);
15
+ const length = readSync(fd, chunk, 0, chunk.length, null);
16
+ if (!length)
17
+ break;
18
+ size += length;
19
+ if (size > 1024 * 1024)
20
+ throw new Error("Input too large");
21
+ chunks.push(chunk.subarray(0, length));
22
+ }
23
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
24
+ }
25
+ finally {
26
+ if (path !== "-")
27
+ closeSync(fd);
28
+ }
29
+ }
30
+ export async function inventoryExportCommand(argv, store, factory = createTransport, writeFactory = createWriteCoordinator) {
31
+ const name = argv.slice(0, 3).join(" ");
32
+ const entry = inventoryExportCatalogue[name];
33
+ const usage = (message) => {
34
+ throw new AxiError(message, "VALIDATION_ERROR", [entry
35
+ ? `Valid flags for ${name}: ${Object.keys(entry.flags).map((flag) => `--${flag}`).join(", ")}`
36
+ : `Valid commands: ${Object.keys(inventoryExportCatalogue).join(", ")}`]);
37
+ };
38
+ if (!entry)
39
+ usage("Unknown inventory export command");
40
+ const flags = new Map();
41
+ for (let index = 3; index < argv.length; index++) {
42
+ const flag = argv[index];
43
+ if (!flag.startsWith("--") || !Object.hasOwn(entry.flags, flag.slice(2)) || flags.has(flag))
44
+ usage(`Unknown argument, flag, or duplicate flag: ${flag}`);
45
+ const value = ["--help", "--full", "--execute", "--dry-run"].includes(flag) ? "true" : argv[++index];
46
+ if (!value || value.startsWith("--"))
47
+ usage(`Missing value for ${flag}`);
48
+ flags.set(flag, value);
49
+ }
50
+ const get = (key) => flags.get(`--${key}`);
51
+ const selectors = (profile) => `${get("config") ? ` --config ${JSON.stringify(get("config"))}` : ""} --profile ${profile}`;
52
+ if (get("help"))
53
+ return { command: name, ...entry };
54
+ const verb = argv[2];
55
+ const operation = entry.operationId;
56
+ const fields = get("fields")?.split(",") ?? entry.defaultFields;
57
+ const allowed = verb === "start" ? ["id", "state"] : verb === "jobs" ? ["id", "state", "createdAt", "export_type", "last_refreshed_at"]
58
+ : verb === "status" ? ["id", "state", "availableChunks", "createdAt", "last_refreshed_at"] : entry.defaultFields;
59
+ if (fields.some((field) => !allowed.includes(field)) || new Set(fields).size !== fields.length)
60
+ usage(`Output fields: ${allowed.join(",")}`);
61
+ const project = (row) => Object.fromEntries(fields.map((field) => {
62
+ if (row[field] === undefined || (exportFields[field] && !exportFields[field].safeParse(row[field]).success)) {
63
+ throw new TransportError({ code: "RESPONSE_INVALID", message: `Missing or malformed selected field: ${field}`, operation });
64
+ }
65
+ return [field, row[field]];
66
+ }));
67
+ if (get("execute") && get("dry-run"))
68
+ usage("--execute and --dry-run are mutually exclusive");
69
+ if (verb === "start") {
70
+ let body;
71
+ if (get("body-file")) {
72
+ try {
73
+ body = bodyFile(get("body-file"));
74
+ }
75
+ catch {
76
+ usage("Cannot read --body-file as JSON within the 1 MiB limit");
77
+ }
78
+ }
79
+ const query = Object.fromEntries(["properties", "use-readable-name", "max-chunk-file-size", "sort", "file-format", "compress"].flatMap((key) => {
80
+ const raw = get(key);
81
+ if (raw === undefined)
82
+ return [];
83
+ let value = raw;
84
+ if (["use-readable-name", "compress"].includes(key)) {
85
+ if (!["true", "false"].includes(raw))
86
+ usage(`--${key} must be true or false`);
87
+ value = raw === "true";
88
+ }
89
+ if (key === "max-chunk-file-size") {
90
+ if (!/^\d+$/.test(raw))
91
+ usage("Invalid chunk size");
92
+ value = Number(raw);
93
+ }
94
+ return [[key.replaceAll("-", "_"), value]];
95
+ }));
96
+ const input = exportInput.safeParse({ ...(body === undefined ? {} : { body }), query });
97
+ if (!input.success)
98
+ usage("Invalid export scope/options; body accepts only documented query and flat property filters");
99
+ const result = await writeFactory({ config: get("config"), profile: get("profile") }).run(operation, input.data, { execute: get("execute") === "true", dryRun: get("dry-run") === "true", confirm: get("confirm"), intentId: get("intent-id") });
100
+ if (result.kind !== "success") {
101
+ let truncated = false;
102
+ const preview = (value) => {
103
+ if (typeof value === "string" && value.length > 1000 && !get("full")) {
104
+ truncated = true;
105
+ return `${value.slice(0, 1000)}... (truncated, ${value.length} chars total)`;
106
+ }
107
+ if (Array.isArray(value))
108
+ return value.map(preview);
109
+ if (value && typeof value === "object")
110
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, preview(child)]));
111
+ return value;
112
+ };
113
+ const output = preview(result);
114
+ return { ...output, ...(truncated ? { help: ["Repeat the same export command with --full to read the complete preview"] } : {}) };
115
+ }
116
+ const parsed = z.object({ export_id: z.string().uuid() }).parse(result.response);
117
+ return { job: project({ id: parsed.export_id, state: "QUEUED" }), auditId: result.auditId,
118
+ help: [`Run tenable-axi export inventory status --id ${parsed.export_id}${selectors(result.preview.profile)}`] };
119
+ }
120
+ let output;
121
+ if (["status", "download"].includes(verb)) {
122
+ if (!z.string().uuid().safeParse(get("id")).success)
123
+ usage("--id requires the exact export UUID");
124
+ if (verb === "download") {
125
+ if (!get("chunk") || !/^\d+$/.test(get("chunk")) || !Number.isSafeInteger(Number(get("chunk"))))
126
+ usage("--chunk requires a nonnegative chunk number");
127
+ if (!get("output"))
128
+ usage("--output requires a new file path");
129
+ output = exportOutputPath(get("output"), operation);
130
+ }
131
+ }
132
+ const limit = Number(get("limit") ?? 100);
133
+ if (get("limit") && (!/^\d+$/.test(get("limit")) || limit < 1 || limit > 1000))
134
+ usage("--limit must be 1-1000");
135
+ if (get("status") && !exportState.safeParse(get("status")).success)
136
+ usage("--status must be QUEUED, PROCESSING, FINISHED or ERROR");
137
+ store.readOnly();
138
+ const profile = store.select(store.load(get("config")).config, get("profile"));
139
+ const transport = factory({ keys: store.credentials(profile), origin: profile.origin });
140
+ const response = await transport.request(operation, verb === "jobs" ? { query: { limit, ...(get("status") ? { status: get("status") } : {}) } }
141
+ : { pathParams: { export_id: get("id"), ...(verb === "download" ? { chunk_id: get("chunk") } : {}) } });
142
+ if (verb === "download")
143
+ return { file: project({ id: get("id"), chunk: Number(get("chunk")), ...saveExport(response.body, output, store.redactor, operation) }) };
144
+ const decode = (row, status) => {
145
+ const parsed = z.record(z.string(), z.unknown()).safeParse(row);
146
+ if (!parsed.success)
147
+ throw new TransportError({ code: "RESPONSE_INVALID", message: "Malformed inventory export job", operation });
148
+ const value = parsed.data;
149
+ if (status && value.export_id !== get("id"))
150
+ throw new TransportError({ code: "RESPONSE_INVALID", message: "Status returned another export ID", operation });
151
+ return project({ ...value, id: value.export_id, state: value.status, createdAt: value.submitted_at, availableChunks: value.chunks_available });
152
+ };
153
+ if (verb === "status")
154
+ return { job: decode(response.body, true) };
155
+ const rows = response.body.exports;
156
+ if (rows.length > limit)
157
+ throw new TransportError({ code: "RESPONSE_INVALID", message: "Job list exceeded the requested limit", operation });
158
+ return { jobs: rows.map((row) => decode(row, false)), count: rows.length, total: null, complete: false,
159
+ reason: "SERVER_HISTORY_LIMIT", ...(!rows.length ? { message: "0 export jobs matched the selected filters in the last three days" } : {}),
160
+ help: ["Only jobs submitted in the last three days are available; the API has no continuation",
161
+ `Run tenable-axi export inventory status --id <id>${selectors(profile.name)}`] };
162
+ }
@@ -0,0 +1,3 @@
1
+ import { credentialStore } from "./profiles.js";
2
+ import { type Transport, type TransportOptions } from "./transport.js";
3
+ export declare function inventoryCommand(argv: string[], store: ReturnType<typeof credentialStore>, transportFactory?: (options: TransportOptions) => Transport): Promise<Record<string, unknown>>;
@@ -0,0 +1,285 @@
1
+ import { AxiError } from "axi-sdk-js";
2
+ import { createHash } from "node:crypto";
3
+ import { closeSync, openSync, readSync } from "node:fs";
4
+ import { z } from "zod";
5
+ import { aliases, assetClasses, filterSchema, inventoryCatalogue, inventoryKinds, inventoryPage, propertyFields, wireFields } from "./inventory-catalogue.js";
6
+ import { createTransport, TransportError } from "./transport.js";
7
+ const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
8
+ const cursorSchema = z.strictObject({ version: z.literal(1), scope: z.string(), offset: integer,
9
+ skip: integer, pageLimit: integer.min(1).max(1000), total: integer.nullable() });
10
+ // Bound input before parsing, including stdin, without reading a whole oversized file.
11
+ function filterFile(path) {
12
+ const fd = path === "-" ? 0 : openSync(path, "r");
13
+ try {
14
+ const chunks = [];
15
+ let bytes = 0;
16
+ for (;;) {
17
+ const chunk = Buffer.alloc(8192);
18
+ const size = readSync(fd, chunk, 0, chunk.length, null);
19
+ if (!size)
20
+ break;
21
+ bytes += size;
22
+ if (bytes > 1024 * 1024)
23
+ throw new Error("Input too large");
24
+ chunks.push(chunk.subarray(0, size));
25
+ }
26
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
27
+ }
28
+ finally {
29
+ if (path !== "-")
30
+ closeSync(fd);
31
+ }
32
+ }
33
+ export async function inventoryCommand(argv, store, transportFactory = createTransport) {
34
+ const name = argv.slice(0, 2).join(" ");
35
+ const entry = inventoryCatalogue[name];
36
+ const usage = (message) => {
37
+ throw new AxiError(message, "VALIDATION_ERROR", [
38
+ entry ? `Valid flags for ${name}: ${Object.keys(entry.flags).map((flag) => `--${flag}`).join(", ")}`
39
+ : "Valid commands: asset list/show/properties, finding list/show/properties, software list/properties",
40
+ ]);
41
+ };
42
+ if (!entry)
43
+ usage("Unknown inventory command");
44
+ const kind = argv[0];
45
+ const verb = argv[1];
46
+ const flags = new Map();
47
+ for (let index = 2; index < argv.length; index++) {
48
+ const flag = argv[index];
49
+ if (!flag.startsWith("--") || !Object.hasOwn(entry.flags, flag.slice(2)) || (flags.has(flag) && flag !== "--filter")) {
50
+ usage(`Unknown argument, flag, or duplicate flag: ${flag}`);
51
+ }
52
+ const value = ["--help", "--full", "--all"].includes(flag) ? "true" : argv[++index];
53
+ if (value === undefined || value.startsWith("--") || !value.length)
54
+ usage(`Missing value for ${flag}`);
55
+ flags.set(flag, [...(flags.get(flag) ?? []), value]);
56
+ }
57
+ const get = (flag) => flags.get(`--${flag}`)?.[0];
58
+ const command = (exclude = []) => ["tenable-axi", name, ...[...flags].flatMap(([flag, values]) => exclude.includes(flag) ? [] : values.flatMap((value) => [flag, ...(["--all", "--full", "--help"].includes(flag) ? [] : [JSON.stringify(value)])]))].join(" ");
59
+ if (get("help"))
60
+ return { command: name, description: entry.description, flags: entry.flags,
61
+ defaultFields: entry.defaultFields, examples: entry.examples };
62
+ if (get("all") && get("limit"))
63
+ usage("--all and --limit are mutually exclusive");
64
+ if (get("cursor") && get("offset"))
65
+ usage("--cursor and --offset are mutually exclusive");
66
+ if (get("filter-file") && get("filter"))
67
+ usage("--filter-file and --filter are mutually exclusive");
68
+ const number = (flag, fallback, min, max) => {
69
+ const raw = get(flag);
70
+ if (raw === undefined)
71
+ return fallback;
72
+ const value = Number(raw);
73
+ if (!/^\d+$/.test(raw) || !Number.isSafeInteger(value) || value < min || value > max)
74
+ usage(`--${flag} must be an integer from ${min} to ${max}`);
75
+ return value;
76
+ };
77
+ const rowLimit = get("all") ? 10000 : number("limit", 100, 1, 10000);
78
+ let offset = number("offset", 0, 0, Number.MAX_SAFE_INTEGER);
79
+ const names = (raw) => {
80
+ const values = raw.split(",");
81
+ if (values.some((value) => !/^[A-Za-z0-9_]+$/.test(value)) || new Set(values).size !== values.length)
82
+ usage("Properties must be unique comma-separated names");
83
+ return values;
84
+ };
85
+ const fields = get("fields") ? names(get("fields")) : entry.defaultFields;
86
+ if (verb === "properties" && fields.some((field) => !Object.hasOwn(propertyFields, field)))
87
+ usage("Unknown properties output field");
88
+ if (kind === "software" && fields.includes("id"))
89
+ usage("The pinned software API exposes no stable ID; use name,version,publisher");
90
+ const extras = new Set(get("extra-properties") ? names(get("extra-properties")) : []);
91
+ if (verb !== "properties")
92
+ for (const field of fields) {
93
+ const wire = aliases[kind][field] ?? field;
94
+ if (!Object.hasOwn(wireFields[kind], wire))
95
+ extras.add(wire);
96
+ }
97
+ const sort = get("sort");
98
+ if (sort !== undefined && !/^[A-Za-z0-9_]+:(asc|desc)$/.test(sort))
99
+ usage("--sort must be property:asc or property:desc");
100
+ const classes = get("asset-classes") ? names(get("asset-classes")) : get("class") ? [get("class")] : [];
101
+ if (classes.some((value) => !assetClasses.includes(value)))
102
+ usage(`Asset classes: ${assetClasses.join(", ")}`);
103
+ const filters = [];
104
+ const invalidFilters = () => usage("Filters must be a flat array of {property, operator, value: string[]}; nested boolean expressions are unsupported; use a documented operator");
105
+ if (get("filter-file")) {
106
+ let value;
107
+ try {
108
+ value = filterFile(get("filter-file"));
109
+ }
110
+ catch {
111
+ usage("Cannot read --filter-file as JSON within the 1 MiB input limit");
112
+ }
113
+ const parsed = z.array(filterSchema).safeParse(value);
114
+ if (!parsed.success)
115
+ invalidFilters();
116
+ filters.push(...parsed.data);
117
+ }
118
+ for (const text of flags.get("--filter") ?? []) {
119
+ const match = /^(\S+)\s+(.+?)\s+(\[.*\])$/s.exec(text);
120
+ if (!match)
121
+ invalidFilters();
122
+ let value;
123
+ try {
124
+ value = JSON.parse(match[3]);
125
+ }
126
+ catch {
127
+ invalidFilters();
128
+ }
129
+ const parsed = filterSchema.safeParse({ property: match[1], operator: match[2], value });
130
+ if (!parsed.success)
131
+ invalidFilters();
132
+ filters.push(parsed.data);
133
+ }
134
+ if (get("class"))
135
+ filters.push({ property: "asset_class", operator: "=", value: classes });
136
+ if (verb === "show") {
137
+ if (!get("id") || !/^[A-Za-z0-9_-]+$/.test(get("id")))
138
+ usage("--id is required and must be an exact inventory identifier");
139
+ filters.push({ property: kind === "asset" ? "asset_id" : "finding_id", operator: "=", value: [get("id")] });
140
+ }
141
+ const body = { ...(get("query") === undefined ? {} : { query: { mode: "simple", text: get("query") } }),
142
+ ...(filters.length ? { filters } : {}) };
143
+ const query = { ...(sort ? { sort } : {}),
144
+ ...(extras.size ? { extra_properties: [...extras].sort().join(",") } : {}),
145
+ ...(get("asset-classes") ? { asset_classes: classes } : {}) };
146
+ const operation = entry.operationId;
147
+ let cursor;
148
+ if (get("cursor")) {
149
+ try {
150
+ if (get("cursor").length > 8192 || !/^[A-Za-z0-9_-]+$/.test(get("cursor")))
151
+ throw new Error();
152
+ cursor = cursorSchema.parse(JSON.parse(Buffer.from(get("cursor"), "base64url").toString("utf8")));
153
+ }
154
+ catch {
155
+ usage("Invalid resume cursor; use the cursor exactly as returned with its original filters");
156
+ }
157
+ }
158
+ store.readOnly();
159
+ const loaded = store.load(get("config"));
160
+ const profile = store.select(loaded.config, get("profile"));
161
+ const scope = createHash("sha256").update(JSON.stringify([profile.origin, profile.name, profile.accessKey, profile.secretKey,
162
+ loaded.path, operation, body, query, fields])).digest("hex");
163
+ if (cursor && cursor.scope !== scope)
164
+ usage("Cursor belongs to a different profile, operation, filters, sort, or fields");
165
+ const transport = transportFactory({ origin: profile.origin, keys: store.credentials(profile) });
166
+ offset = cursor?.offset ?? offset;
167
+ let skip = cursor?.skip ?? 0;
168
+ let total = cursor?.total ?? null;
169
+ let pageLimit = cursor?.pageLimit ?? Math.min(1000, verb === "show" ? 2 : rowLimit);
170
+ const rows = [];
171
+ let complete = false;
172
+ let reason;
173
+ let failure;
174
+ let truncated = false;
175
+ const preview = (value) => {
176
+ if (typeof value === "string" && value.length > 1000 && !get("full")) {
177
+ truncated = true;
178
+ return `${value.slice(0, 1000)}... (truncated, ${value.length} chars total)`;
179
+ }
180
+ if (Array.isArray(value))
181
+ return value.map(preview);
182
+ if (value && typeof value === "object")
183
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, preview(child)]));
184
+ return value;
185
+ };
186
+ const invalid = (message) => { throw new TransportError({ code: "RESPONSE_INVALID", message, operation }); };
187
+ const project = (row) => Object.fromEntries(fields.map((field) => {
188
+ const wire = verb === "properties" ? field : aliases[kind][field] ?? field;
189
+ const native = verb === "properties" || Object.hasOwn(wireFields[kind], wire);
190
+ const extra = z.record(z.string(), z.unknown()).safeParse(row.extra_properties);
191
+ const value = native ? row[wire] : extra.success ? extra.data[wire] : undefined;
192
+ const schema = verb === "properties" ? propertyFields[field] : wireFields[kind][wire] ??
193
+ (field === "version" || field === "description" ? z.string() : z.json());
194
+ if (value === undefined || !schema.safeParse(value).success)
195
+ invalid(`Missing or malformed selected property: ${field}`);
196
+ return [field, preview(store.redactor.payload(value))];
197
+ }));
198
+ const seen = new Set();
199
+ try {
200
+ while (rows.length < (verb === "show" ? 2 : rowLimit)) {
201
+ if (seen.has(offset))
202
+ invalid("The server repeated a page");
203
+ seen.add(offset);
204
+ const response = await transport.request(operation, { query: verb === "properties" ? query : { ...query, offset, limit: pageLimit },
205
+ ...(verb === "properties" ? {} : { body }) });
206
+ let data;
207
+ let exhausted;
208
+ if (verb === "properties") {
209
+ data = response.body[kind === "asset" ? "properties" : "data"];
210
+ exhausted = true;
211
+ }
212
+ else {
213
+ const page = inventoryPage.parse(response.body);
214
+ data = page.data;
215
+ if (page.pagination) {
216
+ if (page.pagination.offset !== offset)
217
+ invalid("The server returned a different or repeated offset");
218
+ total = page.pagination.total ?? total;
219
+ }
220
+ exhausted = total !== null ? offset + data.length >= total : data.length < pageLimit;
221
+ if (!data.length && total !== null && offset < total)
222
+ invalid("The server returned an empty page before the reported total");
223
+ }
224
+ if (skip > data.length)
225
+ invalid("The resumed page no longer contains the saved position");
226
+ const take = Math.min(data.length - skip, (verb === "show" ? 2 : rowLimit) - rows.length);
227
+ for (const row of data.slice(skip, skip + take)) {
228
+ if (verb === "show" && row.id !== get("id"))
229
+ invalid("Exact ID search returned a different resource");
230
+ rows.push(project(row));
231
+ skip++;
232
+ }
233
+ if (skip < data.length)
234
+ break;
235
+ if (exhausted) {
236
+ complete = true;
237
+ break;
238
+ }
239
+ offset += data.length;
240
+ if (!Number.isSafeInteger(offset))
241
+ invalid("The server returned an unrepresentable offset");
242
+ skip = 0;
243
+ pageLimit = Math.min(1000, rowLimit - rows.length || rowLimit);
244
+ }
245
+ }
246
+ catch (error) {
247
+ if (!(error instanceof TransportError))
248
+ throw error;
249
+ if (["REQUEST_BUDGET_EXCEEDED", "BYTE_BUDGET_EXCEEDED", "DEADLINE_EXCEEDED"].includes(error.error.code))
250
+ reason = error.error.code;
251
+ else {
252
+ if (!rows.length)
253
+ throw error;
254
+ failure = error;
255
+ }
256
+ }
257
+ if (verb === "show") {
258
+ if (failure)
259
+ throw failure;
260
+ if (!complete || reason)
261
+ throw new TransportError({ code: reason ?? "RESPONSE_INVALID", message: "Exact ID search did not complete uniquely", operation });
262
+ if (!rows.length)
263
+ throw new TransportError({ code: "NOT_FOUND", message: `No ${kind} matched the exact ID`, operation });
264
+ if (rows.length !== 1)
265
+ invalid("Exact ID search returned multiple resources");
266
+ return { [kind]: rows[0], ...(truncated ? { help: [`Run ${command(["--full"])} --full to read complete text`] } : {}) };
267
+ }
268
+ const help = [];
269
+ const selectors = [get("config") ? `--config ${JSON.stringify(get("config"))}` : "", get("profile") ? `--profile ${get("profile")}` : ""].filter(Boolean).join(" ");
270
+ if (verb === "list")
271
+ help.push(`Run tenable-axi ${kind} properties ${selectors}`.trim());
272
+ if (verb === "list" && kind !== "software")
273
+ help.push(`Run tenable-axi ${kind} show --id <id> ${selectors}`.trim());
274
+ if (kind === "software" && verb === "list")
275
+ help.push("The pinned API exposes no stable software ID");
276
+ if (truncated)
277
+ help.push(`Run ${command(["--full"])} --full to read complete text`);
278
+ if (!complete)
279
+ help.push(`Run ${command(["--cursor", "--offset"])} --cursor <cursor> to resume; offset paging does not provide snapshot isolation`);
280
+ return { [verb === "properties" ? "properties" : inventoryKinds[kind]]: rows, count: rows.length, total, complete,
281
+ ...(!rows.length && complete ? { message: `0 ${verb === "properties" ? `${kind} properties` : inventoryKinds[kind]} matched the selected filters` } : {}),
282
+ ...(!complete ? { reason: reason ?? (failure ? "READ_FAILED" : get("all") ? "ROW_BUDGET_EXCEEDED" : "LIMIT"),
283
+ cursor: Buffer.from(JSON.stringify({ version: 1, scope, offset, skip, pageLimit, total })).toString("base64url") } : {}),
284
+ ...(failure ? failure.toJSON() : {}), ...(help.length ? { help: [...help, ...(failure?.help ?? [])] } : {}) };
285
+ }
@@ -0,0 +1,2 @@
1
+ import { credentialStore } from "./profiles.js";
2
+ export declare function localCommand(argv: string[], store: ReturnType<typeof credentialStore>): Record<string, unknown>;
@@ -0,0 +1,44 @@
1
+ import { AxiError } from "axi-sdk-js";
2
+ import { catalogue } from "./catalogue.js";
3
+ export function localCommand(argv, store) {
4
+ const name = argv.slice(0, 2).join(" ");
5
+ const entry = catalogue[name];
6
+ const usage = () => {
7
+ throw new AxiError("Unknown command, argument, duplicate or invalid flag", "VALIDATION_ERROR", [
8
+ "Valid commands: auth status, profile list, config path; valid flags: --config <path>, --profile <name>, --fields <names>, --full, --help",
9
+ ]);
10
+ };
11
+ if (!entry || name === "home")
12
+ usage();
13
+ const flags = new Map();
14
+ for (let index = 2; index < argv.length; index++) {
15
+ const flag = argv[index];
16
+ if (!flag.startsWith("--") || !Object.hasOwn(entry.flags, flag.slice(2)) || flags.has(flag))
17
+ usage();
18
+ if (flag === "--help" || flag === "--full")
19
+ flags.set(flag, "true");
20
+ else {
21
+ const value = argv[++index];
22
+ if (!value || value.startsWith("--"))
23
+ usage();
24
+ flags.set(flag, value);
25
+ }
26
+ }
27
+ if (flags.has("--help"))
28
+ return { command: name, ...entry };
29
+ // Validation, including output selection, must finish before reading credentials.
30
+ const available = name === "auth status" ? ["profile", "source", "origin", "config", "accessKey", "secretKey", "readOnly"]
31
+ : name === "profile list" ? ["profiles", "count", "config"] : ["config", "state"];
32
+ const fields = flags.get("--fields")?.split(",") ?? available;
33
+ if (fields.some((field) => !available.includes(field)) || new Set(fields).size !== fields.length)
34
+ usage();
35
+ const config = flags.get("--config");
36
+ let result;
37
+ if (name === "auth status")
38
+ result = store.status(config, flags.get("--profile"));
39
+ else if (name === "profile list")
40
+ result = store.list(config);
41
+ else
42
+ result = { config: store.configPath(config), state: store.statePath() };
43
+ return Object.fromEntries(fields.map((field) => [field, result[field]]));
44
+ }