@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,101 @@
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 tagIds: z.ZodPipe<z.ZodArray<z.ZodString>, z.ZodTransform<string[], string[]>>;
5
+ export declare const platformTagInputs: {
6
+ "tags-create-tag-category": z.ZodObject<{
7
+ body: z.ZodObject<{
8
+ name: z.ZodString;
9
+ description: z.ZodOptional<z.ZodString>;
10
+ }, z.core.$strict>;
11
+ }, z.core.$strict>;
12
+ "tags-edit-tag-category": z.ZodObject<{
13
+ id: z.ZodString;
14
+ body: z.ZodObject<{
15
+ name: z.ZodString;
16
+ description: z.ZodOptional<z.ZodString>;
17
+ }, z.core.$strict>;
18
+ }, z.core.$strict>;
19
+ "tags-delete-tag-category": z.ZodObject<{
20
+ id: z.ZodString;
21
+ }, z.core.$strict>;
22
+ "tags-create-tag-value": z.ZodObject<{
23
+ body: z.ZodObject<{
24
+ value: z.ZodString;
25
+ category_name: z.ZodOptional<z.ZodString>;
26
+ category_uuid: z.ZodOptional<z.ZodString>;
27
+ category_description: z.ZodOptional<z.ZodString>;
28
+ description: z.ZodOptional<z.ZodString>;
29
+ filters: z.ZodOptional<z.ZodObject<{
30
+ asset: z.ZodOptional<z.ZodObject<{
31
+ and: z.ZodOptional<z.ZodArray<z.ZodObject<{
32
+ property: z.ZodString;
33
+ operator: z.ZodString;
34
+ value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
35
+ }, z.core.$strict>>>;
36
+ or: z.ZodOptional<z.ZodArray<z.ZodObject<{
37
+ property: z.ZodString;
38
+ operator: z.ZodString;
39
+ value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
40
+ }, z.core.$strict>>>;
41
+ }, z.core.$strict>>;
42
+ }, z.core.$strict>>;
43
+ }, z.core.$strict>;
44
+ }, z.core.$strict>;
45
+ "tags-update-tag-value": z.ZodObject<{
46
+ id: z.ZodString;
47
+ body: z.ZodObject<{
48
+ version: z.ZodOptional<z.ZodNumber>;
49
+ value: z.ZodOptional<z.ZodString>;
50
+ description: z.ZodOptional<z.ZodString>;
51
+ filters: z.ZodOptional<z.ZodObject<{
52
+ asset: z.ZodOptional<z.ZodObject<{
53
+ and: z.ZodOptional<z.ZodArray<z.ZodObject<{
54
+ property: z.ZodString;
55
+ operator: z.ZodString;
56
+ value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
57
+ }, z.core.$strict>>>;
58
+ or: z.ZodOptional<z.ZodArray<z.ZodObject<{
59
+ property: z.ZodString;
60
+ operator: z.ZodString;
61
+ value: z.ZodUnion<readonly [z.ZodString, z.ZodArray<z.ZodString>]>;
62
+ }, z.core.$strict>>>;
63
+ }, z.core.$strict>>;
64
+ }, z.core.$strict>>;
65
+ }, z.core.$strict>;
66
+ }, z.core.$strict>;
67
+ "tags-delete-tag-value": z.ZodObject<{
68
+ id: z.ZodString;
69
+ }, z.core.$strict>;
70
+ "tags-delete-tag-values-bulk": z.ZodObject<{
71
+ body: z.ZodObject<{
72
+ values: z.ZodPipe<z.ZodArray<z.ZodString>, z.ZodTransform<string[], string[]>>;
73
+ }, z.core.$strict>;
74
+ }, z.core.$strict>;
75
+ "tags-assign-asset-tags": z.ZodObject<{
76
+ body: z.ZodObject<{
77
+ action: z.ZodEnum<{
78
+ add: "add";
79
+ remove: "remove";
80
+ }>;
81
+ assets: z.ZodPipe<z.ZodArray<z.ZodString>, z.ZodTransform<string[], string[]>>;
82
+ tags: z.ZodPipe<z.ZodArray<z.ZodString>, z.ZodTransform<string[], string[]>>;
83
+ }, z.core.$strict>;
84
+ }, z.core.$strict>;
85
+ };
86
+ export declare const tagPagination: z.ZodObject<{
87
+ offset: z.ZodNumber;
88
+ limit: z.ZodNumber;
89
+ total: z.ZodNumber;
90
+ }, z.core.$strip>;
91
+ export declare const platformTagBindings: Readonly<Record<string, OperationBinding>>;
92
+ export declare const platformTagMutations: Readonly<Record<string, MutationOperation>>;
93
+ type Entry = {
94
+ description: string;
95
+ operationId: string;
96
+ flags: Record<string, string>;
97
+ defaultFields: string[];
98
+ examples: string[];
99
+ };
100
+ export declare const platformTagCatalogue: Record<string, Entry>;
101
+ export {};
@@ -0,0 +1,180 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { z } from "zod";
3
+ import { TransportError } from "./transport-core.js";
4
+ const uuid = z.string().uuid();
5
+ const categoryName = z.string().min(1).max(127).regex(/^[^:]+$/).refine((value) => !!value.trim());
6
+ const valueName = z.string().min(1).max(50).regex(/^[^,]+$/);
7
+ const rule = z.strictObject({ property: z.string().min(1), operator: z.string().min(1),
8
+ value: z.union([z.string(), z.array(z.string())]).refine((value) => (typeof value === "string" ? value.split(",").length : value.reduce((count, item) => count + item.split(",").length, 0)) <= 1024) });
9
+ const conditions = z.strictObject({ and: z.array(rule).optional(), or: z.array(rule).optional() })
10
+ .refine((value) => (value.and?.length ?? 0) + (value.or?.length ?? 0) <= 40);
11
+ const filters = z.strictObject({ asset: conditions.optional() });
12
+ const categoryBody = z.strictObject({ name: categoryName, description: z.string().max(3000).optional() });
13
+ const valueFields = { value: valueName.optional(), description: z.string().optional(), filters: filters.optional() };
14
+ const createValueBody = z.strictObject({ ...valueFields, value: valueName, category_name: categoryName.optional(),
15
+ category_uuid: uuid.optional(), category_description: z.string().max(3000).optional() })
16
+ .refine((value) => !!value.category_name || !!value.category_uuid);
17
+ const updateValueBody = z.strictObject({ ...valueFields, version: z.number().int().nonnegative().optional() })
18
+ .refine((value) => Object.keys(value).some((key) => key !== "version"));
19
+ export const tagIds = z.array(uuid).min(1).max(10000).transform((ids) => [...new Set(ids)].sort());
20
+ export const platformTagInputs = {
21
+ "tags-create-tag-category": z.strictObject({ body: categoryBody }),
22
+ "tags-edit-tag-category": z.strictObject({ id: uuid, body: categoryBody }),
23
+ "tags-delete-tag-category": z.strictObject({ id: uuid }),
24
+ "tags-create-tag-value": z.strictObject({ body: createValueBody }),
25
+ "tags-update-tag-value": z.strictObject({ id: uuid, body: updateValueBody }),
26
+ "tags-delete-tag-value": z.strictObject({ id: uuid }),
27
+ "tags-delete-tag-values-bulk": z.strictObject({ body: z.strictObject({ values: tagIds }) }),
28
+ "tags-assign-asset-tags": z.strictObject({ body: z.strictObject({ action: z.enum(["add", "remove"]), assets: tagIds, tags: tagIds }) }),
29
+ };
30
+ const record = z.record(z.string(), z.unknown());
31
+ export const tagPagination = z.object({ offset: z.number().int().nonnegative(), limit: z.number().int().positive(), total: z.number().int().nonnegative() });
32
+ const detail = z.object({ uuid }).passthrough();
33
+ const list = (key) => z.object({ [key]: z.array(record), pagination: tagPagination });
34
+ const definitions = [
35
+ ["tags-create-tag-category", "POST", "/tags/categories", "write", [], detail, "Scan Manager [40] or PS.ACCT_MGMT.TAGS.CREATE"],
36
+ ["tags-list-tag-categories", "GET", "/tags/categories", "read", ["f", "ft", "limit", "offset", "sort"], list("categories"), "Basic [16]"],
37
+ ["tags-tag-category-details", "GET", "/tags/categories/{tag_category_uuid}", "read", [], detail, "Basic [16]"],
38
+ ["tags-edit-tag-category", "PUT", "/tags/categories/{tag_category_uuid}", "write", [], detail, "Scan Manager [40] or PS.ACCT_MGMT.TAGS.EDIT; edit permission on all values"],
39
+ ["tags-delete-tag-category", "DELETE", "/tags/categories/{tag_category_uuid}", "write", [], record, "Scan Manager [40] or PS.ACCT_MGMT.TAGS.DELETE; edit permission on all values"],
40
+ ["tags-create-tag-value", "POST", "/tags/values", "write", [], detail, "Scan Manager [40] or PS.ACCT_MGMT.TAGS.CREATE"],
41
+ ["tags-list-tag-values", "GET", "/tags/values", "read", ["f", "ft", "wf", "w", "limit", "offset", "sort"], list("values"), "Basic [16]"],
42
+ ["tags-tag-value-details", "GET", "/tags/values/{tag_value_uuid}", "read", [], detail, "Basic [16]"],
43
+ ["tags-update-tag-value", "PUT", "/tags/values/{tag_value_uuid}", "write", [], detail, "Scan Operator [24] or PS.ACCT_MGMT.TAGS.EDIT"],
44
+ ["tags-delete-tag-value", "DELETE", "/tags/values/{tag_value_uuid}", "write", [], record, "Scan Operator [24] or PS.ACCT_MGMT.TAGS.DELETE; edit permission on the value"],
45
+ ["tags-delete-tag-values-bulk", "POST", "/tags/values/delete-requests", "write", [], record, "Scan Operator [24] or PS.ACCT_MGMT.TAGS.DELETE"],
46
+ ["tags-assign-asset-tags", "POST", "/tags/assets/assignments", "write", [], z.object({ job_uuid: z.string().min(1) }), "Basic [16]"],
47
+ ["tags-list-asset-tags", "GET", "/tags/assets/{asset_uuid}/assignments", "read", [], z.object({ tags: z.array(z.object({ asset_uuid: uuid, value_uuid: uuid }).passthrough()) }), "Basic [16] or PS.ACCT_MGMT.TAGS.READ"],
48
+ ["tags-list-exclusions", "GET", "/tags/values/{tag_value_uuid}/exclusions", "read", ["target_type", "limit", "offset"], list("excluded_targets"), "Basic [16] or PS.ACCT_MGMT.TAGS.READ"],
49
+ ["tags-list-asset-filters", "GET", "/tags/assets/filters", "read", [], z.object({ filters: z.array(record) }), "Basic [16] or PS.ACCT_MGMT.TAGS.READ"],
50
+ ];
51
+ export const platformTagBindings = Object.fromEntries(definitions.map(([id, method, path, effect, query, decoder, permission]) => [id, { method, path, effect, query, decoder,
52
+ permissionHelp: `Requires ${permission}`, validationHelp: "Run tenable-axi tag asset-filter list for dynamic rules; read the current tag and version before retrying" }]));
53
+ function sameBody(state, body) {
54
+ const normalized = { ...state };
55
+ if (body.filters && state.filters) {
56
+ let asset = state.filters.asset;
57
+ if (typeof asset === "string") {
58
+ try {
59
+ asset = JSON.parse(asset);
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ }
65
+ if (asset && typeof asset === "object" && !Array.isArray(asset)) {
66
+ normalized.filters = { ...state.filters, asset: Object.fromEntries(Object.entries(asset).map(([key, rules]) => [key, ["and", "or"].includes(key) && Array.isArray(rules) ? rules.map((item) => {
67
+ if (!item || typeof item !== "object" || Array.isArray(item))
68
+ return item;
69
+ const { field, ...rest } = item;
70
+ return typeof field === "string" && !Object.hasOwn(rest, "property") ? { ...rest, property: field } : item;
71
+ }) : rules])) };
72
+ }
73
+ }
74
+ return Object.entries(body).filter(([key]) => !["version", "category_uuid", "category_name", "category_description"].includes(key))
75
+ .every(([key, value]) => isDeepStrictEqual(normalized[key], value));
76
+ }
77
+ export const platformTagMutations = Object.fromEntries(Object.entries(platformTagInputs).map(([operation, input]) => {
78
+ const category = operation.includes("category"), create = operation.startsWith("tags-create"), update = operation.includes("edit") || operation.includes("update");
79
+ const bulk = operation === "tags-delete-tag-values-bulk", assignment = operation === "tags-assign-asset-tags";
80
+ const noun = category ? "category" : "value";
81
+ return [operation, { input,
82
+ prepare(raw) {
83
+ const { id, body } = raw;
84
+ return { target: assignment ? { kind: "tag-assignment", payload: true }
85
+ : bulk ? { kind: "tag-values", ids: body.values }
86
+ : create ? { kind: `tag-${noun}`, name: category ? body.name : `${body.category_uuid ?? body.category_name}:${body.value}` }
87
+ : { kind: `tag-${noun}`, id: id },
88
+ request: { ...(id ? { pathParams: { [category ? "tag_category_uuid" : "tag_value_uuid"]: id } } : {}), ...(body ? { body } : {}) } };
89
+ },
90
+ async current(transport, raw) {
91
+ const { id, body } = raw;
92
+ if (assignment) {
93
+ const state = {};
94
+ for (const asset of body.assets) {
95
+ const response = (await transport.request("tags-list-asset-tags", { pathParams: { asset_uuid: asset } })).body;
96
+ if (response.tags.some((tag) => tag.asset_uuid !== asset))
97
+ throw new TransportError({ code: "RESPONSE_INVALID", message: "Assignment read returned another asset", operation });
98
+ state[asset] = [...new Set(response.tags.map((tag) => tag.value_uuid))].sort();
99
+ }
100
+ return { state, noop: Object.values(state).every((tags) => body.tags.every((tag) => tags.includes(tag) === (body.action === "add"))) };
101
+ }
102
+ if (bulk) {
103
+ const state = [];
104
+ for (const value of body.values) {
105
+ const current = (await transport.request("tags-tag-value-details", { pathParams: { tag_value_uuid: value } })).body;
106
+ if (current.uuid !== value)
107
+ throw new TransportError({ code: "RESPONSE_INVALID", message: "Tag read returned another identifier", operation });
108
+ state.push(current);
109
+ }
110
+ return { state };
111
+ }
112
+ if (create) {
113
+ const response = (await transport.request(category ? "tags-list-tag-categories" : "tags-list-tag-values", {
114
+ query: { f: category ? [`name:eq:${body.name}`] : [`value:eq:${body.value}`, `category_name:eq:${body.category_name ?? ""}`].slice(0, body.category_name ? 2 : 1), ft: "and", limit: 100, offset: 0 },
115
+ })).body;
116
+ const rows = (category ? response.categories : response.values);
117
+ if (response.pagination.total < rows.length || rows.length > 100 || response.pagination.offset !== 0 || response.pagination.limit !== 100) {
118
+ throw new TransportError({ code: "RESPONSE_INVALID", message: "Malformed tag lookup pagination", operation });
119
+ }
120
+ const matches = rows.filter((row) => category ? row.name === body.name : row.value === body.value
121
+ && (body.category_uuid ? row.category_uuid === body.category_uuid : row.category_name === body.category_name));
122
+ let state = response;
123
+ if (matches.length === 1 && response.pagination.total <= rows.length) {
124
+ const decoded = detail.safeParse(matches[0]);
125
+ if (!decoded.success)
126
+ throw new TransportError({ code: "RESPONSE_INVALID", message: "Tag lookup returned a malformed identifier", operation });
127
+ const match = decoded.data;
128
+ const current = (await transport.request(category ? "tags-tag-category-details" : "tags-tag-value-details", {
129
+ pathParams: { [category ? "tag_category_uuid" : "tag_value_uuid"]: match.uuid },
130
+ })).body;
131
+ if (current.uuid !== match.uuid)
132
+ throw new TransportError({ code: "RESPONSE_INVALID", message: "Tag read returned another identifier", operation });
133
+ state = current;
134
+ const sameCategory = category || (body.category_uuid ? current.category_uuid === body.category_uuid : current.category_name === body.category_name);
135
+ return { state, noop: sameCategory && sameBody(current, body) && (category || body.filters !== undefined || current.type === "static") };
136
+ }
137
+ return { state };
138
+ }
139
+ const state = (await transport.request(category ? "tags-tag-category-details" : "tags-tag-value-details", {
140
+ pathParams: { [category ? "tag_category_uuid" : "tag_value_uuid"]: id },
141
+ })).body;
142
+ if (state.uuid !== id)
143
+ throw new TransportError({ code: "RESPONSE_INVALID", message: "Tag read returned another identifier", operation });
144
+ return { state, noop: update && sameBody(state, body) };
145
+ },
146
+ effect: assignment ? "Add or remove the exact tag set on the exact asset set as proposed, asynchronously; no automatic polling"
147
+ : operation.includes("delete") ? `Delete tag ${noun}${bulk ? "s" : ""} and remove associated asset assignments${category ? "; also delete every value in the category" : "; retain the category"}`
148
+ : `${create ? "Create" : "Update"} tag ${noun}${!category ? "; dynamic filters change automatic asset assignment; a new category name may create a category" : ""}`,
149
+ readBackHelp: [`Run tenable-axi tag ${assignment ? "assignment list --asset-id <id>" : `${noun} show --id <id>`}; reconcile before retrying an unknown outcome`], }];
150
+ }));
151
+ const common = { config: "Config path; default platform path", profile: "Profile name; default credential precedence", fields: "Comma-separated output fields; default compact view", full: "Full text; default false", help: "Show help" };
152
+ const paging = { limit: "Output rows; default 100; maximum 10000", offset: "Starting record; default 0", cursor: "Resume the same scoped collection", all: "Read at most 10000 rows; excludes --limit" };
153
+ const writes = { execute: "Execute once; default preview", "dry-run": "Explicit preview; excludes --execute", confirm: "Exact confirmation from preview", "intent-id": "Unique execution intent for replay protection" };
154
+ export const platformTagCatalogue = {};
155
+ function entry(name, operationId, flags, defaultFields, description) {
156
+ const required = [["id", "<id>"], ["name", '"Location"'], ["body-file", "tag.json"], ["asset-id", "<id>"], ["tag-id", "<id>"],
157
+ ["ids-file", "ids.json"], ["asset-ids-file", "assets.json"], ["tag-ids-file", "tags.json"]]
158
+ .filter(([flag]) => Object.hasOwn(flags, flag)).map(([flag, value]) => `--${flag} ${value}`).join(" ");
159
+ platformTagCatalogue[name] = { operationId, flags: { ...common, ...flags }, defaultFields, description,
160
+ examples: [`tenable-axi ${name} ${required}`.trim(), `tenable-axi ${name} --profile example ${required} --full`] };
161
+ }
162
+ for (const noun of ["category", "value"]) {
163
+ const category = noun === "category", defaults = category ? ["id", "name", "reserved"] : ["id", "category", "value", "type"];
164
+ const operations = category ? ["tags-list-tag-categories", "tags-tag-category-details", "tags-create-tag-category", "tags-edit-tag-category", "tags-delete-tag-category"]
165
+ : ["tags-list-tag-values", "tags-tag-value-details", "tags-create-tag-value", "tags-update-tag-value", "tags-delete-tag-value"];
166
+ for (const [index, verb] of ["list", "show", "create", "update", "delete"].entries())
167
+ entry(`tag ${noun} ${verb}`, operations[index], {
168
+ ...(["show", "update", "delete"].includes(verb) ? { id: "Required exact UUID" } : {}),
169
+ ...(verb === "list" ? { ...paging, filter: "Repeatable field:operator:value", "filter-type": "and|or; API default and", sort: "Comma-separated field:asc|desc",
170
+ ...(!category ? { with: "Wildcard search value (w)", "with-filter": "Comma-separated wildcard fields (wf)" } : {}) } : {}),
171
+ ...(["create", "update"].includes(verb) ? category ? { name: "Required category name, at most 127 characters, no colon", description: "Optional description, at most 3000 characters" } : { "body-file": "Required strict tag JSON; '-' for stdin; maximum 1 MiB; no access_control" } : {}),
172
+ ...(["create", "update", "delete"].includes(verb) ? writes : {}),
173
+ }, verb === "delete" ? ["kind", "auditId", "status"] : defaults, `${verb[0].toUpperCase()}${verb.slice(1)} platform tag ${noun}`);
174
+ }
175
+ entry("tag value bulk-delete", "tags-delete-tag-values-bulk", { ...writes, "ids-file": "Required JSON UUID array; '-' for stdin; maximum 1 MiB" }, ["kind", "auditId", "status"], "Preview or delete the exact tag value set");
176
+ entry("tag assignment list", "tags-list-asset-tags", { "asset-id": "Required exact asset UUID", limit: paging.limit, cursor: paging.cursor, all: paging.all }, ["assetId", "tagId", "value"], "List tags assigned to one asset");
177
+ for (const action of ["add", "remove"])
178
+ entry(`tag assignment ${action}`, "tags-assign-asset-tags", { ...writes, "asset-ids-file": "Required JSON asset UUID array; '-' for stdin", "tag-ids-file": "Required JSON tag UUID array; '-' for stdin" }, ["id", "state"], `${action} tags for the exact asset set`);
179
+ entry("tag exclusion list", "tags-list-exclusions", { ...paging, "tag-id": "Required exact dynamic tag UUID", "target-type": "assets; API default assets" }, ["targetId", "targetType"], "List assets excluded from a dynamic tag");
180
+ entry("tag asset-filter list", "tags-list-asset-filters", { limit: paging.limit, cursor: paging.cursor, all: paging.all }, ["property", "operators"], "List documented dynamic tag filter definitions");
@@ -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 platformTagCommand(argv: string[], store: ReturnType<typeof credentialStore>, factory?: TransportFactory, writeFactory?: WriteCoordinatorFactory): Promise<Record<string, unknown>>;
@@ -0,0 +1,312 @@
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 { platformTagCatalogue, platformTagInputs, tagPagination } from "./platform-tag-catalogue.js";
6
+ import { createTransport, TransportError } from "./transport.js";
7
+ import { createWriteCoordinator } from "./writes.js";
8
+ const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
9
+ const cursorSchema = z.strictObject({ version: z.literal(1), scope: z.string(), offset: integer,
10
+ pending: z.array(z.record(z.string(), z.unknown())), exhausted: z.boolean(), total: integer.nullable(), lastPage: z.string().nullable() });
11
+ const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
12
+ const uuid = z.string().uuid();
13
+ const fieldTypes = { id: uuid, name: z.string(), reserved: z.boolean(), category: z.string(), value: z.string().nullable(),
14
+ type: z.string().nullable(), assetId: uuid, tagId: uuid, targetId: uuid, targetType: z.literal("assets"), property: z.string(), operators: z.array(z.string()),
15
+ description: z.string(), category_uuid: uuid, category_description: z.string(), created_at: z.string(), updated_at: z.string(),
16
+ created_by: z.string(), updated_by: z.string(), version: z.number().int(), filters: z.object({ asset: z.string() }),
17
+ access_control: z.record(z.string(), z.unknown()), control: z.record(z.string(), z.unknown()), readable_name: z.string(),
18
+ ipv4: z.array(z.string()), sources: z.array(z.string()), product: z.string(), source: z.string(), container_uuid: uuid };
19
+ function inputFile(path) {
20
+ const fd = path === "-" ? 0 : openSync(path, "r");
21
+ try {
22
+ const buffer = Buffer.alloc(1024 * 1024 + 1);
23
+ let size = 0;
24
+ while (size < buffer.length) {
25
+ const count = readSync(fd, buffer, size, buffer.length - size, null);
26
+ if (!count)
27
+ break;
28
+ size += count;
29
+ }
30
+ if (size > 1024 * 1024)
31
+ throw new Error("Input exceeds 1 MiB");
32
+ return JSON.parse(buffer.subarray(0, size).toString("utf8"));
33
+ }
34
+ finally {
35
+ if (path !== "-")
36
+ closeSync(fd);
37
+ }
38
+ }
39
+ export async function platformTagCommand(argv, store, factory = createTransport, writeFactory = createWriteCoordinator) {
40
+ const name = argv.slice(0, 3).join(" ");
41
+ const entry = platformTagCatalogue[name];
42
+ const usage = (message) => {
43
+ throw new AxiError(message, "VALIDATION_ERROR", [entry
44
+ ? `Valid flags for ${name}: ${Object.keys(entry.flags).map((flag) => `--${flag}`).join(", ")}`
45
+ : `Valid commands: ${Object.keys(platformTagCatalogue).join(", ")}`]);
46
+ };
47
+ if (!entry)
48
+ usage("Unknown platform tag command");
49
+ const flags = new Map();
50
+ const booleans = ["--help", "--full", "--all", "--execute", "--dry-run"];
51
+ for (let index = 3; index < argv.length; index++) {
52
+ const flag = argv[index];
53
+ if (!flag.startsWith("--") || !Object.hasOwn(entry.flags, flag.slice(2)) || flags.has(flag) && flag !== "--filter")
54
+ usage(`Unknown argument, flag, or duplicate flag: ${flag}`);
55
+ const value = booleans.includes(flag) ? "true" : argv[++index];
56
+ if (value === undefined || value.startsWith("--") || !value && flag !== "--description")
57
+ usage(`Missing value for ${flag}`);
58
+ flags.set(flag, [...flags.get(flag) ?? [], value]);
59
+ }
60
+ const get = (key) => flags.get(`--${key}`)?.[0];
61
+ if (get("help"))
62
+ return { command: name, ...entry };
63
+ const operation = entry.operationId, noun = argv[1], verb = argv[2];
64
+ const invalid = (message) => { throw new TransportError({ code: "RESPONSE_INVALID", message, operation }); };
65
+ const category = noun === "category", value = noun === "value", assignment = noun === "assignment", exclusion = noun === "exclusion";
66
+ const mutating = Object.hasOwn(platformTagInputs, operation);
67
+ const available = mutating && ["delete", "bulk-delete"].includes(verb) ? ["kind", "auditId", "status"]
68
+ : mutating && assignment ? ["id", "state"]
69
+ : category ? ["id", "name", "reserved", "description", "created_at", "created_by", "updated_at", "updated_by"]
70
+ : value ? ["id", "category", "value", "type", "description", "category_uuid", "category_description", "created_at", "created_by", "updated_at", "updated_by", "filters", "access_control", "version"]
71
+ : assignment ? ["assetId", "tagId", "value", "category", "category_uuid", "created_at", "created_by", "product", "source", "container_uuid"]
72
+ : exclusion ? ["targetId", "targetType", "tagId", "name", "ipv4", "sources", "container_uuid"] : ["property", "operators", "readable_name", "control"];
73
+ const fields = get("fields")?.split(",") ?? entry.defaultFields;
74
+ if (fields.some((field) => !available.includes(field)) || new Set(fields).size !== fields.length)
75
+ usage(`Output fields: ${available.join(",")}`);
76
+ if (get("execute") && get("dry-run"))
77
+ usage("--execute and --dry-run are mutually exclusive");
78
+ if (get("intent-id") !== undefined && !get("intent-id").trim())
79
+ usage("--intent-id must not be blank");
80
+ if (get("all") && get("limit") || get("cursor") && get("offset"))
81
+ usage("Incompatible paging flags");
82
+ const number = (flag, fallback, min, max) => {
83
+ const raw = get(flag), result = raw === undefined ? fallback : Number(raw);
84
+ if (raw !== undefined && !/^\d+$/.test(raw) || !Number.isSafeInteger(result) || result < min || result > max)
85
+ usage(`Invalid --${flag}`);
86
+ return result;
87
+ };
88
+ const limit = number("limit", get("all") ? 10000 : 100, 1, 10000);
89
+ let offset = number("offset", 0, 0, Number.MAX_SAFE_INTEGER);
90
+ for (const flag of ["id", "asset-id", "tag-id"]) {
91
+ if (Object.hasOwn(entry.flags, flag) && !uuid.safeParse(get(flag)).success)
92
+ usage(`--${flag} requires an exact UUID`);
93
+ }
94
+ const command = (excluded = []) => ["tenable-axi", name, ...[...flags].flatMap(([flag, values]) => excluded.includes(flag) ? []
95
+ : values.flatMap((value) => [flag, ...(booleans.includes(flag) ? [] : [`'${value.replaceAll("'", "'\"'\"'")}'`])]))].join(" ");
96
+ let truncated = false;
97
+ function preview(input, key) {
98
+ if (typeof input === "string" && key !== "confirm" && input.length > 1000 && !get("full")) {
99
+ truncated = true;
100
+ return `${input.slice(0, 1000)}... (truncated, ${input.length} chars total)`;
101
+ }
102
+ if (Array.isArray(input))
103
+ return input.map((child) => preview(child));
104
+ if (input && typeof input === "object")
105
+ return Object.fromEntries(Object.entries(input).map(([key, child]) => [key, preview(child, key)]));
106
+ return input;
107
+ }
108
+ if (mutating) {
109
+ const fileFlags = ["body-file", "ids-file", "asset-ids-file", "tag-ids-file"].filter((flag) => Object.hasOwn(entry.flags, flag));
110
+ if (fileFlags.filter((flag) => get(flag) === "-").length > 1)
111
+ usage("Only one input file may consume stdin");
112
+ const files = {};
113
+ for (const flag of fileFlags) {
114
+ if (!get(flag))
115
+ usage(`--${flag} is required`);
116
+ try {
117
+ files[flag] = inputFile(get(flag));
118
+ }
119
+ catch {
120
+ usage(`Cannot read --${flag} as JSON within the 1 MiB limit`);
121
+ }
122
+ }
123
+ const body = verb === "delete" ? undefined : verb === "bulk-delete" ? { values: files["ids-file"] }
124
+ : assignment ? { action: verb, assets: files["asset-ids-file"], tags: files["tag-ids-file"] }
125
+ : category ? { name: get("name"), ...(get("description") === undefined ? {} : { description: get("description") }) } : files["body-file"];
126
+ const input = platformTagInputs[operation].safeParse({ ...(get("id") ? { id: get("id") } : {}), ...(body === undefined ? {} : { body }) });
127
+ if (!input.success)
128
+ usage("Invalid tag input; use documented fields and UUID arrays, at most 40 dynamic rules and 1024 values per rule; security fields are forbidden");
129
+ const result = await writeFactory({ config: get("config"), profile: get("profile") }).run(operation, input.data, { execute: !!get("execute"), dryRun: !!get("dry-run"), confirm: get("confirm"), intentId: get("intent-id") });
130
+ if (result.kind !== "success") {
131
+ const output = preview(result);
132
+ return { ...output, ...(truncated ? { help: [`Run ${command(["--full"])} --full to read complete text`] } : {}) };
133
+ }
134
+ const response = result.response;
135
+ const metadata = { kind: "success", auditId: result.auditId, status: result.status };
136
+ let selected;
137
+ try {
138
+ if (assignment) {
139
+ const job = { id: response.job_uuid, state: "ACCEPTED" };
140
+ selected = { ...metadata, job: Object.fromEntries(fields.map((field) => [field, job[field]])) };
141
+ }
142
+ else if (["delete", "bulk-delete"].includes(verb))
143
+ selected = Object.fromEntries(fields.map((field) => [field, metadata[field]]));
144
+ else {
145
+ if (get("id") && response.uuid !== get("id"))
146
+ invalid("Mutation response returned another identifier");
147
+ selected = { ...metadata, tag: preview(project(response)) };
148
+ }
149
+ }
150
+ catch (error) {
151
+ if (!(error instanceof TransportError))
152
+ throw error;
153
+ throw new TransportError({ ...error.error, auditId: result.auditId, status: result.status }, ["Mutation was accepted; read back its target before retrying"]);
154
+ }
155
+ return { ...selected, help: [`Run tenable-axi tag ${assignment ? "assignment list --asset-id <id>" : ["delete", "bulk-delete"].includes(verb) ? `${noun} list` : `${noun} show --id ${response.uuid}`}${get("config") ? ` --config '${get("config").replaceAll("'", "'\"'\"'")}'` : ""} --profile ${result.preview.profile}`,
156
+ ...(truncated ? [`Run ${command(["--full"])} --full to read complete text`] : [])] };
157
+ }
158
+ const query = {};
159
+ const mutableQuery = {};
160
+ const filters = flags.get("--filter") ?? [];
161
+ for (const filter of filters) {
162
+ const match = /^([^:]+):([^:]+):(.+)$/s.exec(filter);
163
+ if (!match)
164
+ usage("--filter requires field:operator:value");
165
+ const [, field, operator, content] = match;
166
+ const dates = category ? ["created_at", "updated_at"] : ["updated_at"];
167
+ const valid = dates.includes(field) ? ["date-eq", "date-gt", "date-lt"].includes(operator) && /^\d+$/.test(content)
168
+ : field === "updated_by" ? operator === "eq" && uuid.safeParse(content).success
169
+ : (category ? ["name", "description"] : ["value", "category_name", "description"]).includes(field) && ["eq", "match"].includes(operator);
170
+ if (!valid)
171
+ usage("Unsupported platform tag filter; use documented fields and operators");
172
+ }
173
+ if (filters.length)
174
+ mutableQuery.f = filters;
175
+ if (get("filter-type")) {
176
+ if (!["and", "or"].includes(get("filter-type")))
177
+ usage("--filter-type requires and or or");
178
+ mutableQuery.ft = get("filter-type");
179
+ }
180
+ if (get("sort")) {
181
+ if (!/^[A-Za-z_]+:(asc|desc)(,[A-Za-z_]+:(asc|desc))*$/.test(get("sort")))
182
+ usage("--sort requires comma-separated field:asc|desc");
183
+ mutableQuery.sort = get("sort");
184
+ }
185
+ if (!!get("with") !== !!get("with-filter"))
186
+ usage("--with and --with-filter must be supplied together");
187
+ if (get("with-filter")) {
188
+ if (get("with-filter").split(",").some((field) => !["category_name", "value", "description"].includes(field)))
189
+ usage("--with-filter fields: category_name,value,description");
190
+ mutableQuery.w = get("with");
191
+ mutableQuery.wf = get("with-filter");
192
+ }
193
+ if (get("target-type") && get("target-type") !== "assets")
194
+ usage("--target-type must be assets");
195
+ if (exclusion)
196
+ mutableQuery.target_type = get("target-type") ?? "assets";
197
+ Object.assign(query, mutableQuery);
198
+ const pathParams = get("id") ? { [category ? "tag_category_uuid" : "tag_value_uuid"]: get("id") }
199
+ : assignment ? { asset_uuid: get("asset-id") } : exclusion ? { tag_value_uuid: get("tag-id") } : undefined;
200
+ let saved;
201
+ if (get("cursor")) {
202
+ try {
203
+ const raw = get("cursor");
204
+ if (raw.length > 28 * 1024 * 1024 || !/^[A-Za-z0-9_-]+$/.test(raw))
205
+ throw new Error();
206
+ saved = cursorSchema.parse(JSON.parse(Buffer.from(raw, "base64url").toString("utf8")));
207
+ }
208
+ catch {
209
+ usage("Invalid resume cursor; retain the original scope and cursor");
210
+ }
211
+ }
212
+ store.readOnly();
213
+ const profile = store.select(store.load(get("config")).config, get("profile"));
214
+ const scope = hash([profile.origin, profile.name, store.configPath(get("config")), operation, pathParams, query, fields, !!get("full")]);
215
+ if (saved && saved.scope !== scope)
216
+ usage("Cursor belongs to a different profile, operation, selector, fields or filters");
217
+ const transport = factory({ keys: store.credentials(profile), origin: profile.origin });
218
+ function project(row) {
219
+ const mapped = { ...row, ...(category ? { id: row.uuid } : value ? { id: row.uuid ?? (row.value === undefined && row.type === undefined ? row.category_uuid : undefined), category: row.category_name,
220
+ value: row.value === undefined && row.type === undefined ? null : row.value, type: row.value === undefined && row.type === undefined ? null : row.type,
221
+ version: row.version ?? row.access_control?.version }
222
+ : assignment ? { assetId: row.asset_uuid, tagId: row.value_uuid, category: row.category_name }
223
+ : exclusion ? { targetId: row.asset_uuid, targetType: "assets", tagId: row.value_uuid } : { property: row.name }) };
224
+ if (assignment && mapped.assetId !== get("asset-id"))
225
+ invalid("Assignment read returned another asset");
226
+ if (exclusion && row.value_uuid !== undefined && row.value_uuid !== get("tag-id"))
227
+ invalid("Exclusion read returned another tag");
228
+ const selected = Object.fromEntries(fields.map((field) => {
229
+ if (!fieldTypes[field].safeParse(mapped[field]).success)
230
+ invalid(`Missing or malformed selected field: ${field}`);
231
+ return [field, mapped[field]];
232
+ }));
233
+ return store.redactor.payload(selected);
234
+ }
235
+ if (verb === "show") {
236
+ const row = (await transport.request(operation, { pathParams })).body;
237
+ if (row.uuid !== get("id"))
238
+ invalid("Tag read returned another identifier");
239
+ const tag = preview(project(row));
240
+ return { tag, ...(truncated ? { help: [`Run ${command(["--full"])} --full to read complete text`] } : {}) };
241
+ }
242
+ const paged = category || value || exclusion;
243
+ const key = category ? "categories" : value ? "values" : assignment ? "tags" : exclusion ? "excluded_targets" : "filters";
244
+ const rows = [];
245
+ let pending = saved?.pending ?? [], exhausted = saved?.exhausted ?? false, total = saved?.total ?? null, lastPage = saved?.lastPage ?? null;
246
+ offset = saved?.offset ?? offset;
247
+ let failure, reason;
248
+ try {
249
+ for (let page = 0; rows.length < limit; page++) {
250
+ while (pending.length && rows.length < limit) {
251
+ const row = pending[0];
252
+ if (fields.some((field) => !fieldTypes[field].safeParse(row[field]).success))
253
+ invalid("Malformed pending tag fields in cursor");
254
+ rows.push(row);
255
+ pending.shift();
256
+ }
257
+ if (rows.length >= limit || exhausted)
258
+ break;
259
+ if (page >= 20) {
260
+ reason = "REQUEST_BUDGET_EXCEEDED";
261
+ break;
262
+ }
263
+ const window = Math.min(1000, limit - rows.length);
264
+ const response = (await transport.request(operation, { pathParams, query: { ...query, ...(paged ? { offset, limit: window } : {}) } })).body;
265
+ const data = response[key];
266
+ let nextTotal = total, nextExhausted = true;
267
+ if (paged) {
268
+ const pagination = tagPagination.parse(response.pagination);
269
+ if (pagination.offset !== offset || data.length > window || pagination.limit !== window || offset + data.length > pagination.total
270
+ || !data.length && offset < pagination.total)
271
+ invalid("Malformed or non-advancing tag pagination");
272
+ nextTotal = pagination.total;
273
+ nextExhausted = offset + data.length >= nextTotal;
274
+ }
275
+ const identity = hash(data);
276
+ if (data.length && identity === lastPage)
277
+ invalid("Tenable repeated the previous tag page");
278
+ const projected = data.map(project);
279
+ if (!Number.isSafeInteger(offset + data.length))
280
+ invalid("Unrepresentable tag offset");
281
+ pending = projected;
282
+ offset += data.length;
283
+ lastPage = identity;
284
+ total = nextTotal;
285
+ exhausted = nextExhausted;
286
+ }
287
+ }
288
+ catch (error) {
289
+ if (!(error instanceof TransportError))
290
+ throw error;
291
+ if (["REQUEST_BUDGET_EXCEEDED", "DEADLINE_EXCEEDED", "BYTE_BUDGET_EXCEEDED"].includes(error.error.code))
292
+ reason = error.error.code;
293
+ else {
294
+ if (!rows.length)
295
+ throw error;
296
+ failure = error;
297
+ }
298
+ }
299
+ const complete = exhausted && !pending.length && !failure && !reason;
300
+ const cursor = complete ? undefined : Buffer.from(JSON.stringify({ version: 1, scope, offset, pending, exhausted, total, lastPage })).toString("base64url");
301
+ if (cursor && cursor.length > 28 * 1024 * 1024)
302
+ invalid("Tag continuation exceeds its byte bound; narrow fields or filters");
303
+ if (failure)
304
+ process.exitCode = 1;
305
+ const output = preview(rows);
306
+ const help = [...(cursor ? [`Run ${command(["--cursor", "--offset"])} --cursor <cursor> to resume; offset paging does not provide snapshot isolation`] : []),
307
+ ...(truncated ? [`Run ${command(["--full"])} --full to read complete text`] : []), ...(failure?.help ?? []),
308
+ ...(noun === "asset-filter" ? ["Resource tag filters cloud.common.resource_tags.key and cloud.common.resource_tags.value also support wc,nwc,exists,nexists; upstream omits them from this list"] : [])];
309
+ return { [key]: output, count: rows.length, total, complete, ...(!rows.length && complete ? { message: `0 tag ${noun} records matched the selected filters` } : {}),
310
+ ...(!complete ? { reason: reason ?? (failure ? "READ_FAILED" : get("all") ? "ROW_BUDGET_EXCEEDED" : "LIMIT"), cursor } : {}),
311
+ ...(failure ? failure.toJSON() : {}), ...(help.length ? { help } : {}) };
312
+ }
@@ -0,0 +1,18 @@
1
+ import { renameSync } from "node:fs";
2
+ export type WindowsAcl = (path: string, action: "check" | "verify" | "restrict", directory: boolean) => void;
3
+ export declare const windowsAcl: WindowsAcl;
4
+ export declare function toolDirectory(kind: "config" | "state", env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform, home?: string): string;
5
+ export type PrivateFileOptions = {
6
+ platform?: NodeJS.Platform;
7
+ acl?: WindowsAcl;
8
+ uid?: number;
9
+ rename?: typeof renameSync;
10
+ wait?: (ms: number) => void;
11
+ };
12
+ export declare function privateFiles(options?: PrivateFileOptions): {
13
+ check: (path: string, secret?: boolean, verifyAcl?: boolean) => void;
14
+ read: (path: string, secret?: boolean, verifyAcl?: boolean) => string;
15
+ directory: (path: string) => void;
16
+ write: (path: string, content: string) => void;
17
+ lock: (path: string) => () => void;
18
+ };