@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,147 @@
1
+ import { AxiError } from "axi-sdk-js";
2
+ import { z } from "zod";
3
+ import { homedir } from "node:os";
4
+ import { isAbsolute, join, resolve, win32 } from "node:path";
5
+ import { privateFiles, toolDirectory } from "./private-file.js";
6
+ import { SecretRedactor } from "./redact.js";
7
+ export const ORIGIN = "https://cloud.tenable.com";
8
+ const profileName = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/);
9
+ const envName = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/);
10
+ function schemas(platform) {
11
+ const secretRef = z.union([
12
+ z.strictObject({ env: envName }),
13
+ z.strictObject({ file: z.string().refine((path) => platform === "win32" ? /^[A-Za-z]:[\\/]/.test(path) : isAbsolute(path)) }),
14
+ ]);
15
+ const profile = z.strictObject({
16
+ origin: z.literal(ORIGIN).default(ORIGIN),
17
+ accessKey: secretRef.default({ env: "TENABLE_AXI_ACCESS_KEY" }),
18
+ secretKey: secretRef.default({ env: "TENABLE_AXI_SECRET_KEY" }),
19
+ writes: z.strictObject({ allowWrites: z.boolean(), operations: z.array(z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/)) })
20
+ .default({ allowWrites: false, operations: [] }),
21
+ });
22
+ return z.strictObject({ version: z.literal(1), defaultProfile: profileName.optional(), profiles: z.record(profileName, profile) })
23
+ .refine((config) => config.defaultProfile === undefined || Object.hasOwn(config.profiles, config.defaultProfile));
24
+ }
25
+ export function credentialStore(options = {}, redactor = new SecretRedactor()) {
26
+ const env = options.env ?? process.env;
27
+ const platform = options.platform ?? process.platform;
28
+ const home = options.home ?? homedir();
29
+ const files = privateFiles(options);
30
+ const invalid = (message) => {
31
+ throw new AxiError(message, "CONFIG_INVALID", [
32
+ "Use version: 1, named profiles, exact origin https://cloud.tenable.com and accessKey/secretKey SecretRefs; run tenable-axi auth status --help",
33
+ ]);
34
+ };
35
+ for (const name of ["TENABLE_AXI_ACCESS_KEY", "TENABLE_AXI_SECRET_KEY"])
36
+ redactor.add(env[name]);
37
+ function configPath(explicit) {
38
+ const selected = explicit ?? env.TENABLE_AXI_CONFIG;
39
+ if (selected !== undefined && !selected.trim())
40
+ invalid("Config path must not be blank");
41
+ if (selected !== undefined)
42
+ return resolve(selected);
43
+ return (platform === "win32" ? win32.join : join)(toolDirectory("config", env, platform, home), "config.json");
44
+ }
45
+ function readOnly() {
46
+ const value = env.TENABLE_AXI_READ_ONLY?.toLowerCase();
47
+ if (value === undefined || value === "0" || value === "false")
48
+ return false;
49
+ if (value === "1" || value === "true")
50
+ return true;
51
+ return invalid("TENABLE_AXI_READ_ONLY must be 1, true, 0 or false");
52
+ }
53
+ function load(explicit, verifyAcl = false) {
54
+ const path = configPath(explicit);
55
+ let raw;
56
+ try {
57
+ raw = JSON.parse(files.read(path, false, verifyAcl));
58
+ }
59
+ catch (error) {
60
+ if (error instanceof AxiError)
61
+ throw error;
62
+ if (explicit === undefined && env.TENABLE_AXI_CONFIG === undefined && error.code === "ENOENT") {
63
+ return { path, config: { version: 1, profiles: {}, defaultProfile: undefined } };
64
+ }
65
+ return invalid("Cannot read profile configuration as JSON; check its path and syntax");
66
+ }
67
+ // Register known secrets before validation so malformed metadata cannot echo them.
68
+ if (raw && typeof raw === "object" && "profiles" in raw && raw.profiles && typeof raw.profiles === "object") {
69
+ for (const profile of Object.values(raw.profiles)) {
70
+ if (!profile || typeof profile !== "object")
71
+ continue;
72
+ for (const field of ["accessKey", "secretKey"]) {
73
+ if (!(field in profile))
74
+ continue;
75
+ const ref = profile[field];
76
+ if (typeof ref === "string")
77
+ redactor.add(ref);
78
+ if (ref && typeof ref === "object" && "env" in ref && typeof ref.env === "string")
79
+ redactor.add(env[ref.env]);
80
+ }
81
+ }
82
+ }
83
+ const parsed = schemas(platform).safeParse(raw);
84
+ if (!parsed.success)
85
+ return invalid("Invalid configuration: check profile names, defaultProfile, unknown fields and accessKey/secretKey SecretRefs");
86
+ return { path, config: parsed.data };
87
+ }
88
+ function select(config, flag) {
89
+ const selected = flag ?? env.TENABLE_AXI_PROFILE;
90
+ if (selected !== undefined && !profileName.safeParse(selected).success)
91
+ invalid("Invalid selected profile name");
92
+ if (selected === undefined && ["TENABLE_AXI_ACCESS_KEY", "TENABLE_AXI_SECRET_KEY", "TENABLE_AXI_ORIGIN"].some((name) => env[name] !== undefined)) {
93
+ if (!env.TENABLE_AXI_ACCESS_KEY?.trim() || !env.TENABLE_AXI_SECRET_KEY?.trim() || (env.TENABLE_AXI_ORIGIN !== undefined && env.TENABLE_AXI_ORIGIN !== ORIGIN)) {
94
+ return invalid("Incomplete or invalid TENABLE_AXI env profile; set both ACCESS_KEY and SECRET_KEY and use the allowed ORIGIN");
95
+ }
96
+ return { origin: ORIGIN, accessKey: { env: "TENABLE_AXI_ACCESS_KEY" }, secretKey: { env: "TENABLE_AXI_SECRET_KEY" },
97
+ writes: { allowWrites: false, operations: [] }, name: "env", source: "env-profile" };
98
+ }
99
+ const names = Object.keys(config.profiles);
100
+ const name = selected ?? config.defaultProfile ?? (names.length === 1 ? names[0] : undefined);
101
+ if (name === undefined)
102
+ throw new AxiError(names.length ? "Select one of the configured profiles" : "No profiles are configured", names.length ? "PROFILE_AMBIGUOUS" : "PROFILE_REQUIRED", ["Pass --profile <name>, set TENABLE_AXI_PROFILE, or configure defaultProfile; run tenable-axi config path"]);
103
+ if (!Object.hasOwn(config.profiles, name))
104
+ throw new AxiError("Selected profile is not configured", "PROFILE_NOT_FOUND", ["Run tenable-axi profile list"]);
105
+ return { ...config.profiles[name], name, source: flag !== undefined ? "flag" : env.TENABLE_AXI_PROFILE !== undefined ? "env" : config.defaultProfile !== undefined ? "config-default" : "sole" };
106
+ }
107
+ function credentials(profile, verifyAcl = false) {
108
+ const values = {};
109
+ for (const field of ["accessKey", "secretKey"]) {
110
+ const ref = profile[field];
111
+ let value;
112
+ try {
113
+ value = "env" in ref ? env[ref.env] : files.read(ref.file, true, verifyAcl).replace(/^\uFEFF/, "").trimEnd();
114
+ }
115
+ catch (error) {
116
+ if (error instanceof AxiError)
117
+ throw error;
118
+ throw new AxiError(`Cannot read ${field} SecretRef file`, "AUTH_REQUIRED", ["Check the SecretRef file exists and is readable"]);
119
+ }
120
+ redactor.add(value);
121
+ if (!value?.trim())
122
+ throw new AxiError(`${field} is required`, "AUTH_REQUIRED", ["Set the selected accessKey and secretKey SecretRef sources; run tenable-axi auth status --help"]);
123
+ if (/[;=\s\p{Cc}]/u.test(value))
124
+ invalid(`${field} contains a header delimiter or control character`);
125
+ values[field] = value;
126
+ }
127
+ // Mirror the sink's exact header spacing for redaction only; never send it here.
128
+ redactor.add(`accessKey=${values.accessKey}; secretKey=${values.secretKey}`);
129
+ return values;
130
+ }
131
+ function status(explicit, flag) {
132
+ const forced = readOnly();
133
+ const loaded = load(explicit, true);
134
+ const profile = select(loaded.config, flag);
135
+ credentials(profile, true);
136
+ return { profile: profile.name, source: profile.source, origin: profile.origin, config: loaded.path,
137
+ accessKey: profile.accessKey, secretKey: profile.secretKey,
138
+ readOnly: forced || !profile.writes.allowWrites || profile.writes.operations.length === 0 };
139
+ }
140
+ function list(explicit) {
141
+ readOnly();
142
+ const loaded = load(explicit);
143
+ return { profiles: Object.entries(loaded.config.profiles).map(([name, profile]) => ({ name, origin: profile.origin, default: name === loaded.config.defaultProfile })),
144
+ count: Object.keys(loaded.config.profiles).length, config: loaded.path };
145
+ }
146
+ return { configPath, statePath: () => toolDirectory("state", env, platform, home), readOnly, load, select, credentials, status, list, redactor };
147
+ }
@@ -0,0 +1,7 @@
1
+ export declare class SecretRedactor {
2
+ private readonly secrets;
3
+ add(secret: string | undefined): void;
4
+ text(value: string): string;
5
+ value(value: unknown): unknown;
6
+ payload(value: unknown): unknown;
7
+ }
@@ -0,0 +1,41 @@
1
+ const REDACTED = "***redacted***";
2
+ // A registry belongs to one invocation and is shared with the sink and journal.
3
+ export class SecretRedactor {
4
+ secrets = new Set();
5
+ add(secret) {
6
+ if (!secret)
7
+ return;
8
+ this.secrets.add(secret);
9
+ this.secrets.add(JSON.stringify(secret).slice(1, -1));
10
+ if (secret.isWellFormed())
11
+ this.secrets.add(encodeURIComponent(secret));
12
+ }
13
+ text(value) {
14
+ for (const secret of [...this.secrets].sort((a, b) => b.length - a.length))
15
+ value = value.split(secret).join(REDACTED);
16
+ return value;
17
+ }
18
+ value(value) {
19
+ if (typeof value === "string")
20
+ return this.text(value);
21
+ if (Array.isArray(value))
22
+ return value.map((child) => this.value(child));
23
+ if (value && typeof value === "object")
24
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [this.text(key), this.value(child)]));
25
+ return value;
26
+ }
27
+ payload(value) {
28
+ if (typeof value === "string")
29
+ return this.text(value)
30
+ .replace(/-----BEGIN (?:[A-Z]+ )*PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )*PRIVATE KEY-----/g, REDACTED)
31
+ .replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g, REDACTED)
32
+ .replace(/(\bAccountKey=)[^;\s]+/gi, `$1${REDACTED}`)
33
+ .replace(/([?&]sig=)[^&\s]+/gi, `$1${REDACTED}`);
34
+ if (Array.isArray(value))
35
+ return value.map((child) => this.payload(child));
36
+ if (value && typeof value === "object")
37
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [this.text(key),
38
+ /^(?:password|secret|access[_-]?key|secret[_-]?key|x-apikeys|client[_-]?secret|token|access[_-]?token|refresh[_-]?token|authorization|private[_-]?key|accountkey|sas[_-]?token)$/i.test(key) ? REDACTED : this.payload(child)]));
39
+ return value;
40
+ }
41
+ }
@@ -0,0 +1,41 @@
1
+ import { z } from "zod";
2
+ import { type OperationBinding } from "./transport-core.js";
3
+ import type { MutationOperation } from "./writes-core.js";
4
+ type Query = {
5
+ property: string;
6
+ operator: string;
7
+ value?: string | number | boolean | (string | number)[];
8
+ } | {
9
+ and: Query[];
10
+ } | {
11
+ or: Query[];
12
+ };
13
+ export declare const responseBodies: {
14
+ combination: z.ZodObject<{
15
+ name: z.ZodString;
16
+ description: z.ZodOptional<z.ZodString>;
17
+ is_public: z.ZodBoolean;
18
+ query: z.ZodType<Query, unknown, z.core.$ZodTypeInternals<Query, unknown>>;
19
+ }, z.core.$strict>;
20
+ initiative: z.ZodObject<{
21
+ name: z.ZodString;
22
+ description: z.ZodOptional<z.ZodString>;
23
+ owner: z.ZodString;
24
+ sla_in_days: z.ZodNumber;
25
+ scope: z.ZodArray<z.ZodString>;
26
+ combination_ids: z.ZodArray<z.ZodString>;
27
+ tenable_ids: z.ZodArray<z.ZodString>;
28
+ }, z.core.$strict>;
29
+ };
30
+ export type ResponseKind = keyof typeof responseBodies;
31
+ export declare const responseBindings: Record<string, OperationBinding>;
32
+ export declare const responseMutations: Record<string, MutationOperation>;
33
+ export declare const responseCatalogue: Record<string, {
34
+ description: string;
35
+ operationId: string;
36
+ flags: Record<string, string>;
37
+ defaultFields: string[];
38
+ examples: string[];
39
+ evidence: string;
40
+ }>;
41
+ export {};
@@ -0,0 +1,134 @@
1
+ import { z } from "zod";
2
+ import { TransportError } from "./transport-core.js";
3
+ const uuid = z.string().uuid();
4
+ const query = z.lazy(() => z.union([
5
+ z.strictObject({ property: z.string().min(1), operator: z.string().min(1),
6
+ value: z.union([z.string(), z.number(), z.boolean(), z.array(z.union([z.string(), z.number()]))]).optional() })
7
+ .refine((value) => ["exists", "nexists"].includes(value.operator) || value.value !== undefined),
8
+ z.strictObject({ and: z.array(query).min(1).max(6) }), z.strictObject({ or: z.array(query).min(1).max(6) }),
9
+ ]));
10
+ function queryCount(value) {
11
+ if (!value || typeof value !== "object")
12
+ return Infinity;
13
+ const row = value;
14
+ if (typeof row.property === "string")
15
+ return 1;
16
+ const children = row.and ?? row.or;
17
+ return Array.isArray(children) && children.length ? children.reduce((sum, child) => sum + queryCount(child), 0) : Infinity;
18
+ }
19
+ export const responseBodies = {
20
+ combination: z.strictObject({ name: z.string().min(1).max(128), description: z.string().max(1024).optional(),
21
+ is_public: z.boolean(), query: query.refine((value) => queryCount(value) <= 6) }),
22
+ initiative: z.strictObject({ name: z.string().min(1).max(128), description: z.string().max(1024).optional(), owner: uuid,
23
+ sla_in_days: z.number().int().min(-2147483648).max(2147483647), scope: z.array(uuid).max(10),
24
+ combination_ids: z.array(uuid).max(10), tenable_ids: z.array(uuid).max(10) }),
25
+ };
26
+ const record = z.object({ id: uuid, name: z.string() }).passthrough();
27
+ const filter = z.object({ name: z.string(), operators: z.array(z.string()) }).passthrough();
28
+ export const responseBindings = {};
29
+ export const responseMutations = {};
30
+ export const responseCatalogue = {};
31
+ const common = { config: "Config path; default credential precedence", profile: "Profile name; default credential precedence",
32
+ fields: "Comma-separated fields; default compact view", full: "Full text; default false", help: "Show help" };
33
+ const paging = { limit: "Output rows; default 100, maximum 10000", all: "Up to 10000 rows; excludes --limit", cursor: "Re-fetch and resume an unchanged unpaged collection; requires original selectors" };
34
+ const write = { execute: "Send once; default preview", "dry-run": "Preview only; excludes --execute", confirm: "Exact preview confirmation; required to execute" };
35
+ const fail = (code, message, operation) => { throw new TransportError({ code, message, operation }); };
36
+ const canonical = (value) => JSON.stringify(value && typeof value === "object"
37
+ ? Array.isArray(value) ? value.map((item) => JSON.parse(canonical(item)))
38
+ : Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => [key, JSON.parse(canonical(child))])) : value);
39
+ for (const kind of ["initiative", "combination"]) {
40
+ const normalize = (value) => kind === "initiative"
41
+ ? Object.fromEntries(Object.entries(value).map(([key, child]) => [key,
42
+ ["scope", "combination_ids", "tenable_ids"].includes(key) && Array.isArray(child) ? [...child].sort() : child])) : value;
43
+ const plural = `${kind}s`;
44
+ const path = `/exposure-response/${plural}`;
45
+ for (const verb of ["list", "show", "create", "update", "delete"]) {
46
+ const operation = `${plural}-${verb === "show" ? "details" : verb}`;
47
+ const mutating = ["create", "update", "delete"].includes(verb);
48
+ const selected = ["show", "update", "delete"].includes(verb);
49
+ const permission = mutating ? verb === "create" ? "CREATE" : verb === "delete" ? "DELETE" : "EDIT" : "READ";
50
+ responseBindings[operation] = { method: verb === "create" ? "POST" : verb === "update" ? "PUT" : verb === "delete" ? "DELETE" : "GET",
51
+ path: selected ? `${path}/{${kind}_id}` : path, effect: mutating ? "write" : "read",
52
+ query: verb === "list" && kind === "combination" ? ["type"] : [],
53
+ decoder: verb === "list" ? z.object({ [plural]: z.array(record) }) : verb === "delete" ? z.object({}).passthrough()
54
+ : verb === "create" ? z.object({ id: uuid }) : record,
55
+ permissionHelp: `Requires EXPOSURE_MANAGEMENT.EM_ER.EM_ER.${permission} or VM.VM_ER.VM_ER.${permission}; check the selected user's role and ownership`,
56
+ validationHelp: `Run tenable-axi ${kind} ${verb} --help; combination queries use combination filters, with six queries per combination and seventeen per initiative` };
57
+ responseCatalogue[`${kind} ${verb}`] = { description: `${mutating ? "Preview or " : ""}${verb} ${kind}${verb === "list" ? "s" : ""}`,
58
+ operationId: operation, flags: { ...common, ...(verb === "list" ? { ...paging, ...(kind === "combination" ? { type: "private, shared or tenable; default all accessible" } : {}) } : {}),
59
+ ...(selected ? { id: "Required exact UUID" } : {}), ...(mutating ? write : {}),
60
+ ...(["create", "update"].includes(verb) ? { "body-file": "Required strict JSON, at most 1 MiB; '-' reads stdin" } : {}) },
61
+ defaultFields: mutating ? ["id"] : verb === "show" ? kind === "initiative"
62
+ ? ["id", "name", "description", "owner", "slaInDays", "scope", "combination_ids", "tenable_ids"]
63
+ : ["id", "name", "description", "type", "query"] : kind === "initiative" ? ["id", "name", "owner", "slaInDays"] : ["id", "name", "type"],
64
+ examples: [`tenable-axi ${kind} ${verb}${selected ? " --id <id>" : ""}${["create", "update"].includes(verb) ? " --body-file body.json" : ""}`,
65
+ `tenable-axi ${kind} ${verb} --help`], evidence: "specs/vulnerability-management.json" };
66
+ if (!mutating)
67
+ continue;
68
+ const input = z.strictObject({ ...(selected ? { id: uuid } : {}), ...(verb === "delete" ? {} : { body: responseBodies[kind] }) });
69
+ responseMutations[operation] = { input,
70
+ prepare(raw) {
71
+ const { id, body } = raw;
72
+ return { target: id ? { kind, id } : { kind, name: body.name }, request: { ...(id ? { pathParams: { [`${kind}_id`]: id } } : {}), ...(body ? { body } : {}) } };
73
+ },
74
+ async current(transport, raw) {
75
+ const { id, body } = raw;
76
+ let existing;
77
+ // A list verifies absence; a detail 404 alone never establishes a no-op.
78
+ if (verb !== "update") {
79
+ const listed = (await transport.request(`${plural}-list`)).body;
80
+ const matches = listed[plural].filter((row) => id ? row.id === id : row.name === body.name);
81
+ if (matches.length > 1)
82
+ fail("RESPONSE_INVALID", "Multiple resources matched the exact target", operation);
83
+ existing = matches[0];
84
+ }
85
+ if (verb === "update" || existing) {
86
+ const targetId = id ?? existing.id;
87
+ existing = (await transport.request(`${plural}-details`, { pathParams: { [`${kind}_id`]: targetId } })).body;
88
+ if (existing.id !== targetId)
89
+ fail("RESPONSE_INVALID", "Details returned a different target", operation);
90
+ if (kind === "combination" && (verb !== "delete" || existing.query !== undefined)
91
+ && !responseBodies.combination.shape.query.safeParse(existing.query).success)
92
+ fail("RESPONSE_INVALID", "Existing combination has an invalid query", operation);
93
+ existing = normalize(existing);
94
+ }
95
+ const combinations = [];
96
+ if (kind === "initiative" && body) {
97
+ let count = 0;
98
+ const ids = [...new Set([...body.combination_ids, ...body.tenable_ids])].sort();
99
+ // One unpaged read keeps even large valid selections inside the shared request budget on both state reads.
100
+ if (ids.length) {
101
+ const listed = (await transport.request("combinations-list")).body;
102
+ for (const combinationId of ids) {
103
+ const matches = listed.combinations.filter((row) => row.id === combinationId);
104
+ if (!matches.length)
105
+ fail("NOT_FOUND", "A selected combination is unavailable; check explicit IDs and read privileges", operation);
106
+ if (matches.length !== 1 || !responseBodies.combination.shape.query.safeParse(matches[0].query).success)
107
+ fail("RESPONSE_INVALID", "Selected combination has an invalid or ambiguous query", operation);
108
+ count += queryCount(matches[0].query);
109
+ combinations.push(matches[0]);
110
+ }
111
+ }
112
+ if (count > 17)
113
+ fail("VALIDATION_ERROR", "Initiatives support at most seventeen queries across all selected combinations", operation);
114
+ }
115
+ let identical = false;
116
+ if (existing && body) {
117
+ const proposed = normalize({ description: "", ...body });
118
+ const current = Object.fromEntries(Object.keys(proposed).map((key) => [key, key === "description" ? existing[key] ?? "" : existing[key]]));
119
+ identical = Object.values(current).every((value) => value !== undefined) && canonical(current) === canonical(proposed);
120
+ if (verb === "create" && !identical)
121
+ fail("CONFLICT", "The proposed name already exists with different or unverified state", operation);
122
+ }
123
+ return { state: { existing: existing ?? null, combinations }, noop: verb === "delete" ? !existing : identical };
124
+ },
125
+ effect: kind === "combination" ? `${verb} a combination; is_public=true shares it across the organization, false keeps it private; existing initiatives may change`
126
+ : `${verb} an initiative with the explicit owner, asset scope, combinations and SLA; owner assignment remains subject to upstream permissions`,
127
+ readBackHelp: [`Run tenable-axi ${kind} list or ${kind} show --id <known-id> before retrying; an interrupted mutation may have succeeded`], };
128
+ }
129
+ }
130
+ responseBindings["combinations-filters-list"] = { method: "GET", path: "/exposure-response/combinations/allowed/filters", effect: "read", query: [],
131
+ decoder: z.object({ filters: z.array(filter) }), permissionHelp: "Check Exposure Response read privileges",
132
+ validationHelp: "Run tenable-axi combination filters" };
133
+ responseCatalogue["combination filters"] = { description: "List allowed combination query properties and operators", operationId: "combinations-filters-list",
134
+ flags: { ...common, ...paging }, defaultFields: ["property", "operators"], examples: ["tenable-axi combination filters", "tenable-axi combination filters --fields property,operators,type"], evidence: "specs/vulnerability-management.json" };
@@ -0,0 +1,4 @@
1
+ import type { credentialStore } from "./profiles.js";
2
+ import type { TransportFactory } from "./exposure.js";
3
+ import type { WriteCoordinatorFactory } from "./inventory-export.js";
4
+ export declare function responseCommand(argv: string[], store: ReturnType<typeof credentialStore>, factory?: TransportFactory, writeFactory?: WriteCoordinatorFactory): Promise<Record<string, unknown>>;
@@ -0,0 +1,227 @@
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 { responseBodies, responseCatalogue } from "./response-catalogue.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
+ const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
31
+ const cursorSchema = z.strictObject({ version: z.literal(2), scope: z.string().regex(/^[a-f0-9]{64}$/),
32
+ snapshot: z.string().regex(/^[a-f0-9]{64}$/), position: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER) });
33
+ const maxCursor = 1024;
34
+ const counts = z.object({ last_count: z.number().int(), current_count: z.number().int() }).partial().passthrough();
35
+ const statistics = z.object({ total_assets: z.number().int(), total_findings: z.number().int(), findings_remediated: z.number().int(),
36
+ average_vuln_age: z.number(), average_remediated_time: z.number(), total_cves: z.number().int(), total_cves_change: z.number(),
37
+ by_combination: z.array(z.object({ combination_id: z.string().uuid(), asset_count: z.number().int(), findings_count: z.number().int() }).partial().passthrough()),
38
+ by_tag: z.array(z.object({ tag_id: z.string().uuid(), asset_count: z.number().int(), findings_count: z.number().int() }).partial().passthrough()),
39
+ }).partial().passthrough();
40
+ const trending = z.array(z.object({ date_generated: z.string(), remediated_count: z.number().int(), active_count: z.number().int(), cve_count: z.number().int(),
41
+ average_vuln_age: z.number(), average_remediation_time: z.number(), event: z.object({ active_findings: counts, resurfaced_findings: counts, assets: counts,
42
+ combination_change: z.object({ added: z.number().int(), updated_by_tenable: z.number().int(), updated: z.number().int(), deleted: z.number().int() }).partial().passthrough(),
43
+ }).partial().passthrough(),
44
+ }).partial().passthrough());
45
+ const fields = { id: z.string().uuid(), name: z.string(), description: z.string(), owner: z.string().uuid(),
46
+ sla_in_days: z.number().int(), scope: z.array(z.string().uuid()), combination_ids: z.array(z.string().uuid()), tenable_ids: z.array(z.string().uuid()),
47
+ query: responseBodies.combination.shape.query, is_public: z.boolean(), read_only: z.boolean().nullable(), last_updated_at: z.string(), modified_at: z.string(),
48
+ product: z.string(), used_in_initiative: z.boolean(), used_in_non_owned_initiative: z.boolean(), operators: z.array(z.string()),
49
+ type: z.union([z.string(), z.record(z.string(), z.string()), z.null()]), selectMultiValue: z.boolean(), allowedValues: z.array(z.string()), total_assets: z.number(), total_findings: z.number(),
50
+ remediated_findings: z.number(), average_vuln_age: z.number(), average_remediation_time: z.number(), total_cves: z.number(),
51
+ total_cves_change: z.number(), total_assets_change: z.number(), total_findings_change: z.number(), last_computed_at: z.string(),
52
+ total_unassigned_findings: z.number().int(), statistics, trending, tickets_count: z.number().int(), delivery_methods: z.object({}).passthrough() };
53
+ export async function responseCommand(argv, store, factory = createTransport, writeFactory = createWriteCoordinator) {
54
+ const name = argv.slice(0, 2).join(" ");
55
+ const entry = responseCatalogue[name];
56
+ const usage = (message) => {
57
+ throw new AxiError(message, "VALIDATION_ERROR", [entry
58
+ ? `Valid flags for ${name}: ${Object.keys(entry.flags).map((flag) => `--${flag}`).join(", ")}`
59
+ : `Valid commands: ${Object.keys(responseCatalogue).join(", ")}`]);
60
+ };
61
+ if (!entry)
62
+ usage("Unknown exposure response command");
63
+ const flags = new Map();
64
+ for (let index = 2; index < argv.length; index++) {
65
+ const flag = argv[index];
66
+ if (!flag.startsWith("--") || !Object.hasOwn(entry.flags, flag.slice(2)) || flags.has(flag))
67
+ usage(`Unknown argument, flag, or duplicate flag: ${flag}`);
68
+ const value = ["--help", "--full", "--all", "--execute", "--dry-run"].includes(flag) ? "true" : argv[++index];
69
+ if (!value || value.startsWith("--"))
70
+ usage(`Missing value for ${flag}`);
71
+ flags.set(flag, value);
72
+ }
73
+ const get = (key) => flags.get(`--${key}`);
74
+ if (get("help"))
75
+ return { command: name, ...entry };
76
+ const kind = argv[0], verb = argv[1];
77
+ const operation = entry.operationId;
78
+ if (["show", "update", "delete"].includes(verb) && !z.string().uuid().safeParse(get("id")).success)
79
+ usage("--id requires the exact UUID");
80
+ if (get("type") && !["private", "shared", "tenable"].includes(get("type")))
81
+ usage("--type must be private, shared or tenable");
82
+ if (get("all") && get("limit"))
83
+ usage("--all and --limit are mutually exclusive");
84
+ if (get("execute") && get("dry-run"))
85
+ usage("--execute and --dry-run are mutually exclusive");
86
+ const limit = get("all") ? 10000 : Number(get("limit") ?? 100);
87
+ if (get("limit") && (!/^\d+$/.test(get("limit")) || !Number.isSafeInteger(limit) || limit < 1 || limit > 10000))
88
+ usage("--limit must be 1-10000");
89
+ const selected = get("fields")?.split(",") ?? entry.defaultFields;
90
+ const alias = { slaInDays: "sla_in_days", ...(verb === "filters" ? { property: "name" } : {}) };
91
+ const allowed = verb === "filters" ? ["name", "operators", "type", "selectMultiValue", "allowedValues"] : ["create", "delete"].includes(verb) ? ["id"]
92
+ : kind === "combination" ? ["id", "name", "description", "owner", "query", "last_updated_at", "is_public", "read_only", "used_in_initiative", "used_in_non_owned_initiative", "product", "type"]
93
+ : ["id", "name", "description", "owner", "sla_in_days", "scope", "combination_ids", "tenable_ids", "product", "last_computed_at", "modified_at", "tickets_count", "delivery_methods",
94
+ ...(verb === "show" ? ["statistics", "trending"] : ["total_assets_change", "total_findings_change"]),
95
+ ...(verb === "list" ? ["total_assets", "total_findings", "remediated_findings", "average_vuln_age", "average_remediation_time", "total_cves", "total_cves_change", "total_unassigned_findings"] : [])];
96
+ if (selected.some((field) => !allowed.includes(alias[field] ?? field)) || new Set(selected).size !== selected.length)
97
+ usage(`Output fields: ${allowed.join(",")}; fields must be unique`);
98
+ let cursor;
99
+ if (get("cursor")) {
100
+ try {
101
+ if (get("cursor").length > maxCursor || !/^[A-Za-z0-9_-]+$/.test(get("cursor")))
102
+ throw new Error();
103
+ cursor = cursorSchema.parse(JSON.parse(Buffer.from(get("cursor"), "base64url").toString("utf8")));
104
+ }
105
+ catch {
106
+ usage("Invalid cursor; use the returned cursor with its original selectors");
107
+ }
108
+ }
109
+ let truncated = false;
110
+ const preview = (value) => {
111
+ if (typeof value === "string")
112
+ value = store.redactor.payload(value);
113
+ if (typeof value === "string" && value.length > 1000 && !get("full")) {
114
+ truncated = true;
115
+ return `${value.slice(0, 1000)}... (truncated, ${value.length} chars total)`;
116
+ }
117
+ if (Array.isArray(value))
118
+ return value.map(preview);
119
+ if (value && typeof value === "object")
120
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, preview(child)]));
121
+ return value;
122
+ };
123
+ const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
124
+ const command = (exclude = []) => ["tenable-axi", name, ...[...flags].flatMap(([flag, value]) => exclude.includes(flag) ? []
125
+ : [flag, ...(["--help", "--full", "--all", "--execute", "--dry-run"].includes(flag) ? [] : [quote(value)])])].join(" ");
126
+ const fullHelp = () => truncated ? [`Run ${command(["--full", "--execute", "--confirm"])} --full to read complete text`] : [];
127
+ const project = (row) => Object.fromEntries(selected.flatMap((field) => {
128
+ const wire = alias[field] ?? field;
129
+ if (verb === "filters" && ["selectMultiValue", "allowedValues"].includes(wire) && row[wire] === undefined)
130
+ return [];
131
+ if (!get("fields") && field === "description" && row[wire] === undefined)
132
+ return [];
133
+ const value = field === "type" && kind === "combination" && verb !== "filters"
134
+ ? get("type") ?? (row.is_public === true ? "shared" : row.is_public === false ? "private" : null) : row[wire];
135
+ if (!fields[wire].safeParse(value).success)
136
+ throw new TransportError({ code: "RESPONSE_INVALID", message: `Missing or malformed selected field: ${field}`, operation });
137
+ return [[field, preview(value)]];
138
+ }));
139
+ if (["create", "update", "delete"].includes(verb)) {
140
+ let body;
141
+ if (verb !== "delete") {
142
+ if (!get("body-file"))
143
+ usage("--body-file is required");
144
+ try {
145
+ body = bodyFile(get("body-file"));
146
+ }
147
+ catch {
148
+ usage("Cannot read --body-file as JSON within the 1 MiB limit");
149
+ }
150
+ const parsed = responseBodies[kind].safeParse(body);
151
+ if (!parsed.success)
152
+ usage("Invalid body; use documented non-security fields, UUIDs, name/description limits, at most ten scope/combinations, and six queries per combination");
153
+ body = parsed.data;
154
+ }
155
+ let auditId, status;
156
+ try {
157
+ const result = await writeFactory({ config: get("config"), profile: get("profile") }).run(operation, { ...(get("id") ? { id: get("id") } : {}), ...(body === undefined ? {} : { body }) }, { execute: get("execute") === "true", dryRun: get("dry-run") === "true", confirm: get("confirm") });
158
+ if (result.kind === "success") {
159
+ auditId = result.auditId;
160
+ status = result.status;
161
+ const row = result.response;
162
+ if (get("id") && (verb === "update" || Object.hasOwn(row, "id")) && row.id !== get("id")) {
163
+ throw new TransportError({ code: "RESPONSE_INVALID", message: "Mutation response returned a different target ID", operation });
164
+ }
165
+ }
166
+ const output = preview(result.kind === "success" ? { ...result, response: project({ ...(get("id") ? { id: get("id") } : {}),
167
+ ...result.response }) } : result);
168
+ // Confirmation is an exact contract even when long names or other text are truncated.
169
+ output.preview = { ...output.preview, confirm: result.preview.confirm };
170
+ return { ...output, ...(truncated ? { help: fullHelp() } : {}) };
171
+ }
172
+ catch (error) {
173
+ if (!(error instanceof TransportError))
174
+ throw error;
175
+ const details = { ...error.error, auditId: error.error.auditId ?? auditId, status: error.error.status ?? status };
176
+ if (details.code !== "RESPONSE_INVALID" || !details.auditId || details.status === undefined || details.status < 200 || details.status >= 300)
177
+ throw error;
178
+ throw new TransportError({ ...details, message: `${details.message}; mutation may have been applied` }, ["Read back the requested target and reconcile the audit journal before retrying; do not replay this mutation"]);
179
+ }
180
+ }
181
+ store.readOnly();
182
+ const loaded = store.load(get("config"));
183
+ const profile = store.select(loaded.config, get("profile"));
184
+ const scope = hash([profile.origin, profile.name, profile.accessKey, profile.secretKey, loaded.path, operation, get("type"), selected]);
185
+ if (cursor && cursor.scope !== scope)
186
+ usage("Cursor belongs to different profile, operation, type or fields");
187
+ const transport = factory({ keys: store.credentials(profile), origin: profile.origin });
188
+ const response = await transport.request(operation, verb === "show" ? { pathParams: { [`${kind}_id`]: get("id") } }
189
+ : get("type") ? { query: { type: get("type") } } : {});
190
+ if (verb === "show") {
191
+ const row = response.body;
192
+ if (row.id !== get("id"))
193
+ throw new TransportError({ code: "RESPONSE_INVALID", message: "Details returned a different ID", operation });
194
+ const output = project(row);
195
+ return { [kind]: output, ...(truncated ? { help: fullHelp() } : {}) };
196
+ }
197
+ const key = verb === "filters" ? "filters" : `${kind}s`;
198
+ const rows = response.body[key];
199
+ const snapshot = hash(rows);
200
+ if (cursor && (cursor.snapshot !== snapshot || cursor.position >= rows.length))
201
+ usage("Collection changed or cursor position is invalid; restart without --cursor");
202
+ const position = cursor?.position ?? 0;
203
+ const data = [];
204
+ let failure;
205
+ for (const row of rows.slice(position, position + limit)) {
206
+ try {
207
+ data.push(project(row));
208
+ }
209
+ catch (error) {
210
+ if (!(error instanceof TransportError) || !data.length)
211
+ throw error;
212
+ failure = error;
213
+ break;
214
+ }
215
+ }
216
+ const next = position + data.length;
217
+ const complete = next === rows.length;
218
+ const resume = complete ? undefined : Buffer.from(JSON.stringify({ version: 2, scope, snapshot, position: next })).toString("base64url");
219
+ const help = [...fullHelp(), ...(verb === "list" ? [`Run tenable-axi ${kind} show --id <id>${get("config") ? ` --config ${quote(get("config"))}` : ""}${profile.source === "env-profile" ? "" : ` --profile ${quote(profile.name)}`}`] : [])];
220
+ if (!complete)
221
+ help.push(`Run ${command(["--cursor"])} --cursor <cursor> to re-fetch the collection and resume`);
222
+ return { [key]: data, count: data.length, total: null, complete,
223
+ ...(!data.length ? { message: `0 ${key} matched the selected filters` } : {}),
224
+ ...(!complete ? { reason: failure ? "READ_FAILED" : get("all") ? "ROW_BUDGET_EXCEEDED" : "LIMIT", cursor: resume } : {}),
225
+ ...(failure ? failure.toJSON() : {}),
226
+ ...(help.length ? { help } : {}) };
227
+ }
@@ -0,0 +1 @@
1
+ export declare function setupHooks(argv: string[]): Record<string, unknown>;