@knowttl/tenable-axi 0.1.5 → 0.1.7

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.
package/README.md CHANGED
@@ -62,7 +62,7 @@ The [generated command reference](https://github.com/knowttl/tenable-axi/blob/ma
62
62
  | Group | Purpose | Access | Reference |
63
63
  | --- | --- | --- | --- |
64
64
  | `home`, `card` | Profile posture and exposure cards | Read | [Cards](https://github.com/knowttl/tenable-axi/blob/main/docs/commands.md#card-list) |
65
- | `asset` | Search inventory and inspect assets | Read | [Assets](https://github.com/knowttl/tenable-axi/blob/main/docs/commands.md#asset-list) |
65
+ | `asset` | Search inventory, inspect assets and investigate their findings | Read | [Assets](https://github.com/knowttl/tenable-axi/blob/main/docs/behavior.md#inventory-reads) |
66
66
  | `finding` | Search findings and count severity/sensor totals | Read | [Findings](https://github.com/knowttl/tenable-axi/blob/main/docs/commands.md#finding-list) |
67
67
  | `software` | Search software and available properties | Read | [Software](https://github.com/knowttl/tenable-axi/blob/main/docs/commands.md#software-list) |
68
68
  | `attack-path`, `attack-technique` | Investigate attack evidence | Read | [Attack paths](https://github.com/knowttl/tenable-axi/blob/main/docs/commands.md#attack-path-list) |
@@ -71,6 +71,7 @@ The [generated command reference](https://github.com/knowttl/tenable-axi/blob/ma
71
71
  | `tag category/value/assignment/exclusion/asset-filter` | Inspect and manage platform tags | Read/write | [Platform tags](https://github.com/knowttl/tenable-axi/blob/main/docs/behavior.md#platform-tags) |
72
72
  | `initiative`, `combination` | Manage Exposure Response workflows | Read/write | [Exposure Response](https://github.com/knowttl/tenable-axi/blob/main/docs/behavior.md#exposure-response) |
73
73
  | `export` | Create jobs, check status and download results | Read/write | [Exports](https://github.com/knowttl/tenable-axi/blob/main/docs/behavior.md#inventory-exports) |
74
+ | `raw` | Read API paths and send guarded writes | Read/write | [Raw API](https://github.com/knowttl/tenable-axi/blob/main/docs/behavior.md#raw-api) |
74
75
  | `auth`, `profile`, `config`, `doctor` | Inspect setup and module access | Local/read | [Doctor](https://github.com/knowttl/tenable-axi/blob/main/docs/commands.md#doctor) |
75
76
  | `setup hooks`, `hook` | Install integrations and read local context | Local | [Integration](https://github.com/knowttl/tenable-axi/blob/main/docs/agent-integration.md) |
76
77
 
@@ -83,7 +84,7 @@ Preview first, then pass `--execute --confirm '<exact preview confirmation>'` to
83
84
  There is no `TENABLE_AXI_ALLOW_*` environment gate; configured operation allowlists control scope.
84
85
  A durable redacted journal records intent before sending; reconcile unknown outcomes before retrying.
85
86
  Credentials use environment/file SecretRefs, never inline secrets or arguments.
86
- Credential minting, users, roles, access-control administration and arbitrary HTTP stay blocked.
87
+ Credential minting, users, roles and access-control administration stay blocked; raw HTTP is limited to validated paths on the exact origin.
87
88
  See [write safety](https://github.com/knowttl/tenable-axi/blob/main/docs/safety.md) and the [permission ledger](https://github.com/knowttl/tenable-axi/blob/main/docs/design.md#complete-operation-ledger).
88
89
 
89
90
  ## Configuration
@@ -111,7 +112,7 @@ See [configuration](https://github.com/knowttl/tenable-axi/blob/main/docs/config
111
112
 
112
113
  ## Output and exit codes
113
114
 
114
- Stdout uses compact TOON; bare `--version`, `-v` and `-V` print the package version.
115
+ Stdout uses compact TOON except for successful raw responses; bare `--version`, `-v` and `-V` print the package version.
115
116
  `--fields` selects properties and `--full` removes text truncation without expanding row or transport bounds.
116
117
  Ordinary lists default to 100 rows; `--all` remains bounded at 10,000.
117
118
  Resume a returned `--cursor` with the same profile, filters, fields and sort.
@@ -21,11 +21,11 @@ export declare const techniqueProperties: readonly ["priority", "state", "status
21
21
  export declare function attackFilterSchema(technique: boolean): z.ZodUnion<readonly [z.ZodObject<{
22
22
  property: z.ZodEnum<{
23
23
  status: "status";
24
+ target: "target";
24
25
  name: "name";
25
26
  priority: "priority";
26
27
  summary: "summary";
27
28
  path_status: "path_status";
28
- target: "target";
29
29
  serial_id: "serial_id";
30
30
  mitre_id: "mitre_id";
31
31
  state: "state";
@@ -72,11 +72,11 @@ export declare function attackFilterSchema(technique: boolean): z.ZodUnion<reado
72
72
  value: z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
73
73
  property: z.ZodEnum<{
74
74
  status: "status";
75
+ target: "target";
75
76
  name: "name";
76
77
  priority: "priority";
77
78
  summary: "summary";
78
79
  path_status: "path_status";
79
- target: "target";
80
80
  serial_id: "serial_id";
81
81
  mitre_id: "mitre_id";
82
82
  state: "state";
@@ -123,11 +123,11 @@ export declare function attackFilterSchema(technique: boolean): z.ZodUnion<reado
123
123
  value: z.ZodArray<z.ZodObject<{
124
124
  property: z.ZodEnum<{
125
125
  status: "status";
126
+ target: "target";
126
127
  name: "name";
127
128
  priority: "priority";
128
129
  summary: "summary";
129
130
  path_status: "path_status";
130
- target: "target";
131
131
  serial_id: "serial_id";
132
132
  mitre_id: "mitre_id";
133
133
  state: "state";
@@ -42,12 +42,13 @@ const global = { config: "Config path; default credential precedence", profile:
42
42
  fields: "Comma-separated metadata fields; default compact view", full: "Full metadata text; default false", help: "Show help" };
43
43
  const write = { "body-file": "Required strict operation-specific JSON file, at most 1 MiB; '-' reads stdin",
44
44
  execute: "Create the previewed job once; default false", "dry-run": "Preview only; excludes --execute",
45
- confirm: "Exact confirmation string from preview; required with --execute" };
45
+ confirm: "Exact confirmation string from preview; required with --execute",
46
+ wait: "After confirmed creation, poll within the shared 20-second/20-request budgets; never creates a replacement; default false" };
46
47
  export const attackExportCatalogue = {
47
48
  ...Object.fromEntries(["attack-path", "attack-technique", "mitre-heatmap"].map((kind) => [`export ${kind} start`, {
48
49
  description: `Preview or start one ${kind} export; requires configured write scope and ATTACK_PATH.WRITE`, operationId: `apa-export-${kind}`,
49
50
  flags: { ...global, ...write }, defaultFields: ["id", "state"],
50
- examples: [`tenable-axi export ${kind} start --body-file export.json`, `tenable-axi export ${kind} start --body-file export.json --execute --confirm '<preview-confirmation>'`], evidence: "specs/exposure-management.json",
51
+ examples: [`tenable-axi export ${kind} start --body-file export.json`, `tenable-axi export ${kind} start --body-file export.json --execute --confirm '<preview-confirmation>' --wait`], evidence: "specs/exposure-management.json",
51
52
  }])),
52
53
  "export attack status": { description: "Read an attack export job; no polling by default", operationId: "apa-export-status",
53
54
  flags: { ...global, id: "Required attack export UUID", wait: "Poll once per second within 20-second/20-request budgets; default false" }, defaultFields: ["id", "state"],
@@ -3,6 +3,7 @@ import { closeSync, openSync, readSync } from "node:fs";
3
3
  import { z } from "zod";
4
4
  import { attackExportCatalogue, attackExportCreated, attackExportInputs, attackExportStatus } from "./attack-export-catalogue.js";
5
5
  import { exportOutputPath, saveExport } from "./export-file.js";
6
+ import { exportStatus } from "./export-wait.js";
6
7
  import { createTransport, TransportError } from "./transport.js";
7
8
  import { createWriteCoordinator } from "./writes.js";
8
9
  export async function attackExportCommand(argv, store, transportFactory = createTransport, writeFactory = createWriteCoordinator) {
@@ -35,6 +36,12 @@ export async function attackExportCommand(argv, store, transportFactory = create
35
36
  if (new Set(fields).size !== fields.length || fields.some((field) => !available.includes(field)))
36
37
  usage(`Available fields: ${available.join(", ")}`);
37
38
  const project = (value) => Object.fromEntries(fields.filter((key) => value[key] !== undefined).map((key) => [key, value[key]]));
39
+ const decode = (body, id) => {
40
+ const status = attackExportStatus.parse(body);
41
+ if (status.export_id !== id)
42
+ throw new TransportError({ code: "RESPONSE_INVALID", message: "Status belongs to a different attack export", operation: "apa-export-status" });
43
+ return { id, state: status.status, submittedAt: status.submitted_at, lastRefreshedAt: status.last_refreshed_at };
44
+ };
38
45
  let body;
39
46
  if (start) {
40
47
  if (get("execute") && get("dry-run"))
@@ -85,7 +92,8 @@ export async function attackExportCommand(argv, store, transportFactory = create
85
92
  }
86
93
  const operation = entry.operationId;
87
94
  if (start) {
88
- const result = await writeFactory({ config: get("config"), profile: get("profile") }).run(operation, body, { execute: !!get("execute"), dryRun: !!get("dry-run"), confirm: get("confirm") });
95
+ const coordinator = writeFactory({ config: get("config"), profile: get("profile") });
96
+ const result = await coordinator.run(operation, body, { execute: !!get("execute"), dryRun: !!get("dry-run"), confirm: get("confirm") });
89
97
  if (result.kind !== "success") {
90
98
  let truncated = false;
91
99
  const previewText = (value) => {
@@ -103,6 +111,11 @@ export async function attackExportCommand(argv, store, transportFactory = create
103
111
  return { kind: result.kind, preview, ...(truncated ? { help: [`Run tenable-axi ${name} --body-file ${JSON.stringify(get("body-file"))} --full${get("config") ? ` --config ${JSON.stringify(get("config"))}` : ""}${get("profile") ? ` --profile ${get("profile")}` : ""} to see full preview text`] } : {}) };
104
112
  }
105
113
  const created = attackExportCreated.parse(result.response);
114
+ if (get("wait")) {
115
+ const status = await exportStatus(coordinator.reader, "apa-export-status", created.export_id, (body) => decode(body, created.export_id), true, { id: created.export_id, state: "SUBMITTED" });
116
+ return { ...status, job: project(status.job), auditId: result.auditId,
117
+ help: [`tenable-axi export attack status --id ${created.export_id}${get("config") ? ` --config ${JSON.stringify(get("config"))}` : ""} --profile ${result.preview.profile}`] };
118
+ }
106
119
  return { job: project({ id: created.export_id, state: "SUBMITTED" }), auditId: result.auditId,
107
120
  help: [`tenable-axi export attack status --id ${created.export_id}${get("config") ? ` --config ${JSON.stringify(get("config"))}` : ""}${get("profile") ? ` --profile ${get("profile")}` : ""}`] };
108
121
  }
@@ -124,28 +137,6 @@ export async function attackExportCommand(argv, store, transportFactory = create
124
137
  throw new TransportError({ code: "EXPORT_FILE_INVALID", message: "Export could not be validated, redacted or saved within 128 MiB to a new file", operation });
125
138
  }
126
139
  }
127
- const deadline = Date.now() + 19_000;
128
- let status;
129
- for (;;) {
130
- let response;
131
- try {
132
- response = await transport.request(operation, request);
133
- }
134
- catch (error) {
135
- if (get("wait") && status && error instanceof TransportError && ["REQUEST_BUDGET_EXCEEDED", "DEADLINE_EXCEEDED"].includes(error.error.code))
136
- break;
137
- throw error;
138
- }
139
- status = attackExportStatus.parse(response.body);
140
- if (status.export_id !== get("id"))
141
- throw new TransportError({ code: "RESPONSE_INVALID", message: "Status belongs to a different attack export", operation });
142
- const pending = ["QUEUED", "PROCESSING"].includes(status.status);
143
- if (!get("wait") || !pending || Date.now() + 1000 >= deadline)
144
- break;
145
- await new Promise((resolve) => setTimeout(resolve, 1000));
146
- }
147
- return {
148
- job: project({ id: status.export_id, state: status.status, submittedAt: status.submitted_at, lastRefreshedAt: status.last_refreshed_at }),
149
- ...(get("wait") && ["QUEUED", "PROCESSING"].includes(status.status) ? { complete: false, reason: "POLL_BUDGET_EXCEEDED" } : {}),
150
- };
140
+ const status = await exportStatus(transport, operation, get("id"), (body) => decode(body, get("id")), !!get("wait"));
141
+ return { ...status, job: project(status.job) };
151
142
  }
@@ -2,6 +2,9 @@ import type { OperationBinding } from "./transport-core.js";
2
2
  import type { MutationOperation } from "./writes-core.js";
3
3
  export declare const DESCRIPTION = "Investigate Tenable One exposure and run explicitly guarded writes";
4
4
  export declare const SETUP_GUIDANCE = "Run tenable-axi config path; configure a profile with accessKey and secretKey SecretRefs";
5
+ export declare const capabilities: {
6
+ readonly rawWrites: true;
7
+ };
5
8
  export declare const transportBindings: Readonly<Record<string, OperationBinding>>;
6
9
  export declare const mutationOperations: Readonly<Record<string, MutationOperation>>;
7
10
  export declare const catalogue: {
@@ -94,6 +97,35 @@ export declare const catalogue: {
94
97
  };
95
98
  examples: string[];
96
99
  };
100
+ readonly "raw get": {
101
+ readonly description: "Read any Tenable API path on the exact origin with the selected profile keys";
102
+ readonly flags: {
103
+ readonly config: "Config path; default platform path";
104
+ readonly profile: "Profile name; default credential precedence";
105
+ readonly path: "Required absolute API path such as /api/v1/t1/tags/properties";
106
+ readonly query: "URL query such as limit=10&offset=0";
107
+ readonly out: "Save response bytes to a new file";
108
+ readonly help: "Show help; default false";
109
+ };
110
+ readonly examples: readonly ["tenable-axi raw get --path /api/v1/t1/tags/properties", "tenable-axi raw get --path /api/v1/t1/tags/search --query limit=5"];
111
+ };
112
+ readonly "raw write": {
113
+ readonly description: "Send one raw write when the profile allows writes and the operation list includes raw-write";
114
+ readonly flags: {
115
+ readonly config: "Config path; default platform path";
116
+ readonly profile: "Profile name; default credential precedence";
117
+ readonly method: "Required POST, PUT, PATCH or DELETE";
118
+ readonly path: "Required absolute API path such as /api/v1/...";
119
+ readonly query: "URL query such as key=value";
120
+ readonly "body-file": "JSON body file or - for stdin";
121
+ readonly execute: "Send after exact confirmation; default preview only";
122
+ readonly "dry-run": "Preview only; incompatible with --execute";
123
+ readonly confirm: "Exact preview confirmation";
124
+ readonly "intent-id": "Optional durable intent identifier";
125
+ readonly help: "Show help; default false";
126
+ };
127
+ readonly examples: readonly ["tenable-axi raw write --method PATCH --path /api/v1/example --body-file body.json", "tenable-axi raw write --method PATCH --path /api/v1/example --body-file body.json --execute --confirm <preview confirm>"];
128
+ };
97
129
  readonly "setup hooks": {
98
130
  readonly description: "Explicitly install or repair local agent session integrations";
99
131
  readonly flags: {
@@ -7,6 +7,7 @@ import { platformTagBindings, platformTagCatalogue, platformTagMutations } from
7
7
  import { responseBindings, responseCatalogue, responseMutations } from "./response-catalogue.js";
8
8
  export const DESCRIPTION = "Investigate Tenable One exposure and run explicitly guarded writes";
9
9
  export const SETUP_GUIDANCE = "Run tenable-axi config path; configure a profile with accessKey and secretKey SecretRefs";
10
+ export const capabilities = { rawWrites: true };
10
11
  // Endpoint slices add reviewed executable bindings alongside their commands.
11
12
  export const transportBindings = Object.freeze({ ...inventoryBindings, ...exposureBindings, ...attackBindings, ...inventoryExportBindings, ...attackExportBindings, ...platformTagBindings, ...responseBindings });
12
13
  export const mutationOperations = Object.freeze({ ...inventoryExportMutations, ...attackExportMutations, ...platformTagMutations, ...responseMutations });
@@ -18,6 +19,16 @@ export const catalogue = {
18
19
  ...attackExportCatalogue,
19
20
  ...platformTagCatalogue,
20
21
  ...responseCatalogue,
22
+ "raw get": {
23
+ description: "Read any Tenable API path on the exact origin with the selected profile keys",
24
+ flags: { config: "Config path; default platform path", profile: "Profile name; default credential precedence", path: "Required absolute API path such as /api/v1/t1/tags/properties", query: "URL query such as limit=10&offset=0", out: "Save response bytes to a new file", help: "Show help; default false" },
25
+ examples: ["tenable-axi raw get --path /api/v1/t1/tags/properties", "tenable-axi raw get --path /api/v1/t1/tags/search --query limit=5"],
26
+ },
27
+ "raw write": {
28
+ description: "Send one raw write when the profile allows writes and the operation list includes raw-write",
29
+ flags: { config: "Config path; default platform path", profile: "Profile name; default credential precedence", method: "Required POST, PUT, PATCH or DELETE", path: "Required absolute API path such as /api/v1/...", query: "URL query such as key=value", "body-file": "JSON body file or - for stdin", execute: "Send after exact confirmation; default preview only", "dry-run": "Preview only; incompatible with --execute", confirm: "Exact preview confirmation", "intent-id": "Optional durable intent identifier", help: "Show help; default false" },
30
+ examples: ["tenable-axi raw write --method PATCH --path /api/v1/example --body-file body.json", "tenable-axi raw write --method PATCH --path /api/v1/example --body-file body.json --execute --confirm <preview confirm>"],
31
+ },
21
32
  "setup hooks": {
22
33
  description: "Explicitly install or repair local agent session integrations",
23
34
  flags: { scope: "user or project; default user; project targets the current directory", help: "Show help; default false" },
@@ -61,6 +72,7 @@ export function help() {
61
72
  return {
62
73
  description: DESCRIPTION,
63
74
  commands: Object.fromEntries(Object.entries(catalogue).map(([name, entry]) => [name, entry.description])),
75
+ capabilities,
64
76
  flags: Object.fromEntries(Object.entries(catalogue.home.flags).map(([name, description]) => [`--${name}`, description])),
65
77
  version: "-v, -V, --version: print the bare version",
66
78
  examples: catalogue.home.examples,
package/dist/src/cli.d.ts CHANGED
@@ -6,6 +6,10 @@ export declare function main(argv?: string[], options?: {
6
6
  stdout?: {
7
7
  write: (chunk: string) => unknown;
8
8
  };
9
+ rawOutput?: (chunk: Uint8Array) => void | Promise<void>;
10
+ stderr?: {
11
+ write: (chunk: string) => unknown;
12
+ };
9
13
  transportFactory?: TransportFactory;
10
14
  writeCoordinatorFactory?: WriteCoordinatorFactory;
11
15
  }): Promise<void>;
package/dist/src/cli.js CHANGED
@@ -4,26 +4,35 @@ import { encode } from "@toon-format/toon";
4
4
  import { credentialStore } from "./profiles.js";
5
5
  import { localCommand } from "./local-commands.js";
6
6
  import { inventoryCommand } from "./inventory.js";
7
- import { exposureCommand } from "./exposure.js";
7
+ import { exposureCommand, homeIdentity } from "./exposure.js";
8
8
  import { TransportError } from "./transport.js";
9
9
  import { attackCommand } from "./attack.js";
10
10
  import { attackExportCommand } from "./attack-export.js";
11
11
  import { inventoryExportCommand } from "./inventory-export.js";
12
+ import { rawCommand } from "./raw.js";
12
13
  import { createWriteCoordinator } from "./writes.js";
13
14
  import { platformTagCommand } from "./platform-tag.js";
14
15
  import { responseCommand } from "./response.js";
15
16
  import { setupHooks } from "./setup.js";
16
17
  export async function main(argv = process.argv.slice(2), options = {}) {
17
18
  const store = credentialStore(options.credentials);
19
+ let rawStream = false;
20
+ let rawStreamError = false;
21
+ let abortedStdout = false;
18
22
  await runAxiCli({
19
23
  description: DESCRIPTION,
20
24
  argv: ["scaffold"],
21
25
  topLevelHelp: "",
22
26
  home: async () => store.redactor.payload(await exposureCommand([], store, options.transportFactory)),
23
- stdout: { write: (chunk) => (options.stdout ?? process.stdout).write(store.redactor.text(chunk)) },
24
- formatError: (error) => ({
25
- output: `${encode(store.redactor.value(error instanceof TransportError ? error.toJSON() : error instanceof AxiError ? { error: { code: error.code, message: error.message }, help: error.suggestions }
26
- : { error: { code: "CONFIG_INVALID", message: "Command could not complete" } }))}\n`,
27
+ stdout: { write: (chunk) => rawStreamError ? (options.stderr ?? process.stderr).write(store.redactor.text(chunk))
28
+ : rawStream ? undefined : (options.stdout ?? process.stdout).write(store.redactor.text(chunk)) },
29
+ formatError: (error) => (rawStreamError = rawStream, {
30
+ output: `${encode(store.redactor.value({
31
+ ...((!argv.length || argv[0] === "home" || argv[0]?.startsWith("--") && argv[0] !== "--help")
32
+ && !(error instanceof AxiError && error.code === "VALIDATION_ERROR") ? homeIdentity() : {}),
33
+ ...(error instanceof TransportError ? error.toJSON() : error instanceof AxiError ? { error: { code: error.code, message: error.message }, help: error.suggestions }
34
+ : { error: { code: "CONFIG_INVALID", message: "Command could not complete" } }),
35
+ }))}\n`,
27
36
  exitCode: error instanceof AxiError && error.code === "VALIDATION_ERROR" ? 2 : 1,
28
37
  }),
29
38
  commands: {
@@ -32,14 +41,41 @@ export async function main(argv = process.argv.slice(2), options = {}) {
32
41
  return setupHooks(argv);
33
42
  if (argv[0] === "tag" && !["list", "properties"].includes(argv[1] ?? ""))
34
43
  return store.redactor.payload(await platformTagCommand(argv, store, options.transportFactory, options.writeCoordinatorFactory ?? ((flags) => createWriteCoordinator(flags, options.credentials))));
44
+ if (argv[0] === "raw")
45
+ return store.redactor.payload(await rawCommand(argv, store, options.transportFactory, options.writeCoordinatorFactory ?? ((flags) => createWriteCoordinator(flags, options.credentials)), (chunk, contentType, signal) => {
46
+ if (!rawStream)
47
+ (options.stderr ?? process.stderr).write(`Content-Type: ${contentType ?? "application/octet-stream"}\n`);
48
+ rawStream = true;
49
+ return (options.rawOutput ?? ((bytes) => new Promise((resolve, reject) => {
50
+ const onError = (error) => reject(error);
51
+ const onAbort = () => { abortedStdout = true; process.stdout.destroy(); };
52
+ process.stdout.once("error", onError);
53
+ signal.addEventListener("abort", onAbort, { once: true });
54
+ if (signal.aborted)
55
+ onAbort();
56
+ process.stdout.write(bytes, (error) => {
57
+ signal.removeEventListener("abort", onAbort);
58
+ if (error)
59
+ reject(error);
60
+ else {
61
+ process.stdout.off("error", onError);
62
+ resolve();
63
+ }
64
+ });
65
+ })))(chunk);
66
+ }));
35
67
  if (["initiative", "combination"].includes(argv[0] ?? "")) {
36
68
  const result = await responseCommand(argv, store, options.transportFactory, options.writeCoordinatorFactory ?? ((flags) => createWriteCoordinator(flags, options.credentials)));
37
69
  if (result.error)
38
70
  process.exitCode = 1;
39
71
  return store.redactor.payload(result);
40
72
  }
41
- if (argv[0] === "export")
42
- return store.redactor.payload(await (["attack-path", "attack-technique", "mitre-heatmap", "attack"].includes(argv[1] ?? "") ? attackExportCommand : inventoryExportCommand)(argv, store, options.transportFactory, options.writeCoordinatorFactory ?? ((flags) => createWriteCoordinator(flags, options.credentials))));
73
+ if (argv[0] === "export") {
74
+ const result = await (["attack-path", "attack-technique", "mitre-heatmap", "attack"].includes(argv[1] ?? "") ? attackExportCommand : inventoryExportCommand)(argv, store, options.transportFactory, options.writeCoordinatorFactory ?? ((flags) => createWriteCoordinator(flags, options.credentials)));
75
+ if (result.error)
76
+ process.exitCode = 1;
77
+ return store.redactor.payload(result);
78
+ }
43
79
  if (["attack-path", "attack-technique", "connector"].includes(argv[0] ?? "")) {
44
80
  const result = await attackCommand(argv, store, options.transportFactory);
45
81
  if (result.error)
@@ -58,4 +94,6 @@ export async function main(argv = process.argv.slice(2), options = {}) {
58
94
  },
59
95
  },
60
96
  });
97
+ if (abortedStdout)
98
+ process.stderr.write("", () => process.exit(process.exitCode));
61
99
  }
@@ -0,0 +1,40 @@
1
+ import { type Transport } from "./transport.js";
2
+ export declare function exportStatus(reader: Pick<Transport, "request">, operation: string, id: string, decode: (body: unknown) => Record<string, unknown>, wait: boolean, initial?: Record<string, unknown>): Promise<{
3
+ job: Record<string, unknown>;
4
+ complete: boolean;
5
+ reason: string;
6
+ } | {
7
+ help?: readonly string[] | undefined;
8
+ error: {
9
+ code: string;
10
+ message: string;
11
+ operation: string;
12
+ status?: number;
13
+ retryAfter?: number;
14
+ auditId?: string;
15
+ contentType?: string | null;
16
+ shape?: readonly {
17
+ path: string;
18
+ type: string;
19
+ count?: number;
20
+ expected?: string;
21
+ }[];
22
+ shapeTruncated?: boolean;
23
+ issues?: readonly {
24
+ path: string;
25
+ received: string;
26
+ expected: string;
27
+ code?: string;
28
+ pathTruncated?: boolean;
29
+ }[];
30
+ issuePaths?: readonly string[];
31
+ issuePathsTruncated?: boolean;
32
+ };
33
+ job: Record<string, unknown>;
34
+ complete: boolean;
35
+ reason?: undefined;
36
+ } | {
37
+ job: Record<string, unknown>;
38
+ complete?: undefined;
39
+ reason?: undefined;
40
+ }>;
@@ -0,0 +1,24 @@
1
+ import { TransportError } from "./transport.js";
2
+ export async function exportStatus(reader, operation, id, decode, wait, initial) {
3
+ const deadline = Date.now() + 19_000;
4
+ let job = initial;
5
+ for (;;) {
6
+ try {
7
+ const response = await reader.request(operation, { pathParams: { export_id: id } });
8
+ job = decode(response.body);
9
+ }
10
+ catch (error) {
11
+ if (!(error instanceof TransportError) || !wait || !job)
12
+ throw error;
13
+ if (["REQUEST_BUDGET_EXCEEDED", "DEADLINE_EXCEEDED"].includes(error.error.code)) {
14
+ return { job, complete: false, reason: "POLL_BUDGET_EXCEEDED" };
15
+ }
16
+ return { job, complete: false, ...error.toJSON() };
17
+ }
18
+ if (!wait || !["QUEUED", "PROCESSING"].includes(job.state))
19
+ return { job };
20
+ if (Date.now() + 1000 >= deadline)
21
+ return { job, complete: false, reason: "POLL_BUDGET_EXCEEDED" };
22
+ await new Promise((resolve) => setTimeout(resolve, 1000));
23
+ }
24
+ }
@@ -1,4 +1,8 @@
1
1
  import { credentialStore } from "./profiles.js";
2
2
  import { type Transport, type TransportOptions } from "./transport.js";
3
3
  export type TransportFactory = (options: TransportOptions) => Transport;
4
+ export declare function homeIdentity(): {
5
+ bin: string;
6
+ description: string;
7
+ };
4
8
  export declare function exposureCommand(argv: string[], store: ReturnType<typeof credentialStore>, factory?: TransportFactory): Promise<Record<string, unknown>>;
@@ -1,10 +1,18 @@
1
1
  import { AxiError } from "axi-sdk-js";
2
2
  import { createHash } from "node:crypto";
3
3
  import { closeSync, openSync, readSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { resolve, sep } from "node:path";
4
6
  import { z } from "zod";
5
7
  import { catalogue, DESCRIPTION, SETUP_GUIDANCE, transportBindings } from "./catalogue.js";
6
8
  import { cardDetails, cardRecord, properties, tagRecord } from "./exposure-contracts.js";
7
9
  import { createTransport, TransportError } from "./transport.js";
10
+ export function homeIdentity() {
11
+ const executable = resolve(process.argv[1]);
12
+ const home = homedir();
13
+ const prefix = home.endsWith(sep) ? home : `${home}${sep}`;
14
+ return { bin: executable.startsWith(prefix) ? `~${sep}${executable.slice(prefix.length)}` : executable, description: DESCRIPTION };
15
+ }
8
16
  const operators = ["=", "!=", "<=", "between", "match", ">=", "<", ">", "contains", "not contains", "exists", "not exists", "older than", "newer than", "within last"];
9
17
  const filterSchema = z.array(z.strictObject({ property: z.string().min(1), operator: z.enum(operators), value: z.array(z.string()) }));
10
18
  const cardFields = ["id", "name", "score", "card_type", "is_global_card", "tag_count", "created_at", "updated_at", "sla_percentage", "ces_trend", "exposure_class", "last_data_update_date", "sources"];
@@ -26,7 +34,7 @@ const fieldTypes = {
26
34
  extra_properties: z.record(z.string(), z.unknown()), weakness_severity_counts: z.record(z.string(), z.number()),
27
35
  };
28
36
  export async function exposureCommand(argv, store, factory = createTransport) {
29
- const name = !argv.length || argv[0]?.startsWith("--") ? "home"
37
+ const name = !argv.length || argv[0]?.startsWith("-") ? "home"
30
38
  : ["card", "tag"].includes(argv[0]) ? argv.slice(0, 2).join(" ") : argv[0];
31
39
  const entry = catalogue[name];
32
40
  const usage = (message = "Unknown command, argument, duplicate or invalid flag") => {
@@ -38,12 +46,12 @@ export async function exposureCommand(argv, store, factory = createTransport) {
38
46
  usage();
39
47
  const flags = new Map();
40
48
  const filters = [];
41
- const start = !argv.length || argv[0]?.startsWith("--") ? 0 : name.includes(" ") ? 2 : 1;
49
+ const start = !argv.length || argv[0]?.startsWith("-") ? 0 : name.includes(" ") ? 2 : 1;
42
50
  for (let index = start; index < argv.length; index++) {
43
51
  const arg = argv[index];
44
52
  const flag = arg.slice(2);
45
53
  if (!arg.startsWith("--") || !Object.hasOwn(entry.flags, flag) || (flags.has(flag) && flag !== "filter"))
46
- usage();
54
+ usage(`Unknown argument, flag, or duplicate flag: ${arg}`);
47
55
  if (["help", "full", "all"].includes(flag))
48
56
  flags.set(flag, "true");
49
57
  else {
@@ -193,8 +201,7 @@ export async function exposureCommand(argv, store, factory = createTransport) {
193
201
  }
194
202
  }
195
203
  const config = flags.get("config"), selected = flags.get("profile");
196
- // Never print the executable path: on a hosted server it is an absolute server path.
197
- const identity = { description: DESCRIPTION };
204
+ const identity = name === "home" ? homeIdentity() : {};
198
205
  let profile;
199
206
  try {
200
207
  store.readOnly();
@@ -81,6 +81,14 @@ const search = { query: "Simple query text", filter: "Repeatable: <property> <op
81
81
  "filter-file": "JSON flat array of {property, operator, value: string[]}; '-' reads stdin; excludes --filter",
82
82
  sort: "Sortable display or wire property:asc|desc; unknown names report valid choices", "extra-properties": "Comma-separated extra wire properties", offset: "Starting record; default 0; excludes --cursor" };
83
83
  export const inventoryCatalogue = Object.fromEntries(Object.keys(inventoryKinds).flatMap((kind) => [
84
+ ...(kind !== "asset" ? [] : [["asset investigate", {
85
+ description: "Resolve a unique asset text query and read its findings within one shared invocation budget; ambiguous or incomplete lookups never pivot",
86
+ operationId: "inventory-findings-search", defaultFields: defaultFields.finding, evidence: "specs/exposure-management.json",
87
+ flags: { ...common(listFields("finding")), query: "Required asset simple query text; lookup returns at most two compact asset candidates",
88
+ limit: collection.limit, all: collection.all, "extra-properties": search["extra-properties"] },
89
+ examples: ["tenable-axi asset investigate --query example-device --limit 20",
90
+ "tenable-axi asset investigate --query example-device --fields id,name,severity,state,sensor_type,cves"],
91
+ }]]),
84
92
  ...(kind !== "finding" ? [] : [["finding summary", {
85
93
  description: "Count findings by each published severity and sensor_type value using limit-1 searches; no per-asset grouping",
86
94
  operationId: "inventory-findings-search", defaultFields: [], evidence: "specs/exposure-management.json",
@@ -39,9 +39,10 @@ for (const kind of ["asset", "finding"]) {
39
39
  inventoryExportCatalogue[`export ${kind} start`] = { description: `Preview or create an inventory ${kind} export job`, operationId: `inventory-export-${kind}s`,
40
40
  flags: { ...common, "body-file": "Optional strict query/filters JSON file, '-' for stdin; maximum 1 MiB", properties: `Comma-separated names from ${kind} properties; id maps to ${kind}_id`, "use-readable-name": "true|false; API default true",
41
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>`] };
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
+ wait: "After confirmed creation, poll within the shared 20-second/20-request budgets; never creates a replacement; default false" },
44
+ 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> --wait`] };
44
45
  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
  }
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 status"] = { description: "Read one inventory export status; no polling by default", operationId: "inventory-export-status", flags: { ...common, id: "Required export UUID", wait: "Poll once per second within 20-second/20-request budgets; default false" }, defaultFields: ["id", "state", "availableChunks"], examples: ["tenable-axi export inventory status --id <id>", "tenable-axi export inventory status --id <id> --wait"] };
47
48
  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"] };
@@ -2,4 +2,5 @@ import type { credentialStore } from "./profiles.js";
2
2
  import type { TransportFactory } from "./exposure.js";
3
3
  import { createWriteCoordinator, type WriteCoordinatorOptions } from "./writes.js";
4
4
  export type WriteCoordinatorFactory = (options: WriteCoordinatorOptions) => ReturnType<typeof createWriteCoordinator>;
5
+ export declare function bodyFile(path: string): unknown;
5
6
  export declare function inventoryExportCommand(argv: string[], store: ReturnType<typeof credentialStore>, factory?: TransportFactory, writeFactory?: WriteCoordinatorFactory): Promise<Record<string, unknown>>;
@@ -3,9 +3,10 @@ import { closeSync, openSync, readSync } from "node:fs";
3
3
  import { z } from "zod";
4
4
  import { exportFields, exportInput, exportState, inventoryExportCatalogue } from "./inventory-export-catalogue.js";
5
5
  import { exportOutputPath, saveExport } from "./export-file.js";
6
+ import { exportStatus } from "./export-wait.js";
6
7
  import { createTransport, TransportError } from "./transport.js";
7
8
  import { createWriteCoordinator } from "./writes.js";
8
- function bodyFile(path) {
9
+ export function bodyFile(path) {
9
10
  const fd = path === "-" ? 0 : openSync(path, "r");
10
11
  try {
11
12
  const chunks = [];
@@ -42,7 +43,7 @@ export async function inventoryExportCommand(argv, store, factory = createTransp
42
43
  const flag = argv[index];
43
44
  if (!flag.startsWith("--") || !Object.hasOwn(entry.flags, flag.slice(2)) || flags.has(flag))
44
45
  usage(`Unknown argument, flag, or duplicate flag: ${flag}`);
45
- const value = ["--help", "--full", "--execute", "--dry-run"].includes(flag) ? "true" : argv[++index];
46
+ const value = ["--help", "--full", "--execute", "--dry-run", "--wait"].includes(flag) ? "true" : argv[++index];
46
47
  if (!value || value.startsWith("--"))
47
48
  usage(`Missing value for ${flag}`);
48
49
  flags.set(flag, value);
@@ -64,6 +65,15 @@ export async function inventoryExportCommand(argv, store, factory = createTransp
64
65
  }
65
66
  return [field, row[field]];
66
67
  }));
68
+ const decodeStatus = (body, id) => {
69
+ const parsed = z.object({ export_id: z.literal(id), status: exportState }).safeParse(body);
70
+ if (!parsed.success)
71
+ throw new TransportError({ code: "RESPONSE_INVALID", message: "Malformed or mismatched inventory export status", operation: "inventory-export-status" });
72
+ const value = body;
73
+ const row = { ...value, id, state: parsed.data.status, createdAt: value.submitted_at, availableChunks: value.chunks_available };
74
+ project(row);
75
+ return row;
76
+ };
67
77
  if (get("execute") && get("dry-run"))
68
78
  usage("--execute and --dry-run are mutually exclusive");
69
79
  if (verb === "start") {
@@ -98,7 +108,8 @@ export async function inventoryExportCommand(argv, store, factory = createTransp
98
108
  const input = exportInput.safeParse({ ...(body === undefined ? {} : { body }), query });
99
109
  if (!input.success)
100
110
  usage("Invalid export scope/options; body accepts only documented query and flat property filters");
101
- 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") });
111
+ const coordinator = writeFactory({ config: get("config"), profile: get("profile") });
112
+ const result = await coordinator.run(operation, input.data, { execute: get("execute") === "true", dryRun: get("dry-run") === "true", confirm: get("confirm"), intentId: get("intent-id") });
102
113
  if (result.kind !== "success") {
103
114
  let truncated = false;
104
115
  const preview = (value) => {
@@ -116,6 +127,11 @@ export async function inventoryExportCommand(argv, store, factory = createTransp
116
127
  return { ...output, ...(truncated ? { help: ["Repeat the same export command with --full to read the complete preview"] } : {}) };
117
128
  }
118
129
  const parsed = z.object({ export_id: z.string().uuid() }).parse(result.response);
130
+ if (get("wait")) {
131
+ const status = await exportStatus(coordinator.reader, "inventory-export-status", parsed.export_id, (body) => decodeStatus(body, parsed.export_id), true, { id: parsed.export_id, state: "QUEUED" });
132
+ return { ...status, job: project(status.job), auditId: result.auditId,
133
+ help: [`Run tenable-axi export inventory status --id ${parsed.export_id}${selectors(result.preview.profile)}`] };
134
+ }
119
135
  return { job: project({ id: parsed.export_id, state: "QUEUED" }), auditId: result.auditId,
120
136
  help: [`Run tenable-axi export inventory status --id ${parsed.export_id}${selectors(result.preview.profile)}`] };
121
137
  }
@@ -139,25 +155,25 @@ export async function inventoryExportCommand(argv, store, factory = createTransp
139
155
  store.readOnly();
140
156
  const profile = store.select(store.load(get("config")).config, get("profile"));
141
157
  const transport = factory({ keys: store.credentials(profile), origin: profile.origin });
158
+ if (verb === "status") {
159
+ const status = await exportStatus(transport, operation, get("id"), (body) => decodeStatus(body, get("id")), !!get("wait"));
160
+ return { ...status, job: project(status.job) };
161
+ }
142
162
  const response = await transport.request(operation, verb === "jobs" ? { query: { limit, ...(get("status") ? { status: get("status") } : {}) } }
143
163
  : { pathParams: { export_id: get("id"), ...(verb === "download" ? { chunk_id: get("chunk") } : {}) } });
144
164
  if (verb === "download")
145
165
  return { file: project({ id: get("id"), chunk: Number(get("chunk")), ...saveExport(response.body, output, store.redactor, operation) }) };
146
- const decode = (row, status) => {
166
+ const decode = (row) => {
147
167
  const parsed = z.record(z.string(), z.unknown()).safeParse(row);
148
168
  if (!parsed.success)
149
169
  throw new TransportError({ code: "RESPONSE_INVALID", message: "Malformed inventory export job", operation });
150
170
  const value = parsed.data;
151
- if (status && value.export_id !== get("id"))
152
- throw new TransportError({ code: "RESPONSE_INVALID", message: "Status returned another export ID", operation });
153
171
  return project({ ...value, id: value.export_id, state: value.status, createdAt: value.submitted_at, availableChunks: value.chunks_available });
154
172
  };
155
- if (verb === "status")
156
- return { job: decode(response.body, true) };
157
173
  const rows = response.body.exports;
158
174
  if (rows.length > limit)
159
175
  throw new TransportError({ code: "RESPONSE_INVALID", message: "Job list exceeded the requested limit", operation });
160
- return { jobs: rows.map((row) => decode(row, false)), count: rows.length, total: null, complete: false,
176
+ return { jobs: rows.map(decode), count: rows.length, total: null, complete: false,
161
177
  reason: "SERVER_HISTORY_LIMIT", ...(!rows.length ? { message: "0 export jobs matched the selected filters in the last three days" } : {}),
162
178
  help: ["Only jobs submitted in the last three days are available; the API has no continuation",
163
179
  `Run tenable-axi export inventory status --id <id>${selectors(profile.name)}`] };