@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,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>;
@@ -0,0 +1,39 @@
1
+ import { AxiError } from "axi-sdk-js";
2
+ import { existsSync, realpathSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ import { catalogue } from "./catalogue.js";
5
+ import { installHooks } from "./hook-install.js";
6
+ export function setupHooks(argv) {
7
+ const usage = () => {
8
+ throw new AxiError("Invalid hook setup command or flags", "VALIDATION_ERROR", [
9
+ "Valid commands: setup hooks; valid flags: --scope user|project, --help",
10
+ ]);
11
+ };
12
+ if (argv[1] !== "hooks")
13
+ usage();
14
+ let scope = "user";
15
+ const seen = new Set();
16
+ for (let index = 2; index < argv.length; index++) {
17
+ const flag = argv[index];
18
+ if (!["--help", "--scope"].includes(flag) || seen.has(flag))
19
+ usage();
20
+ seen.add(flag);
21
+ if (flag === "--scope") {
22
+ const value = argv[++index];
23
+ if (value !== "user" && value !== "project")
24
+ usage();
25
+ scope = value;
26
+ }
27
+ }
28
+ if (seen.has("--help"))
29
+ return { command: "setup hooks", ...catalogue["setup hooks"] };
30
+ const entry = fileURLToPath(new URL("../../bin/tenable-axi-hook.js", import.meta.url));
31
+ if (!existsSync(entry))
32
+ throw new AxiError("Hook entry point is missing", "HOOK_INSTALL_FAILED", ["Reinstall @knowttl/tenable-axi, then run tenable-axi setup hooks"]);
33
+ const failures = [];
34
+ installHooks(realpathSync(entry), scope, (message) => { failures.push(message); });
35
+ if (failures.length)
36
+ throw new AxiError("Agent hook setup did not complete", "HOOK_INSTALL_FAILED", failures);
37
+ return { hooks: { status: "installed", scope, integrations: "Claude Code, Codex, OpenCode" },
38
+ help: ["Restart your agent session; context uses TENABLE_AXI_PROFILE and TENABLE_AXI_CONFIG from the session environment"] };
39
+ }
@@ -0,0 +1,85 @@
1
+ import type { z } from "zod";
2
+ export declare const TENABLE_ORIGIN = "https://cloud.tenable.com";
3
+ export type ApiKeys = Readonly<{
4
+ accessKey: string;
5
+ secretKey: string;
6
+ }>;
7
+ export type OperationBinding = Readonly<{
8
+ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
9
+ path: string;
10
+ effect: "read" | "write";
11
+ query: readonly string[];
12
+ paging?: readonly string[];
13
+ decoder: z.ZodType;
14
+ responseMode?: "file";
15
+ permissionHelp: string;
16
+ validationHelp: string;
17
+ }>;
18
+ export type RequestOptions = {
19
+ pathParams?: Readonly<Record<string, string>>;
20
+ query?: Readonly<Record<string, string | number | boolean | readonly string[]>>;
21
+ body?: unknown;
22
+ continuation?: string;
23
+ signal?: AbortSignal;
24
+ authorization?: unknown;
25
+ retry?: false;
26
+ };
27
+ export type Transport = {
28
+ prepare(operation: string, options?: RequestOptions): PreparedRequest;
29
+ request(operation: string, options?: RequestOptions): Promise<{
30
+ status: number;
31
+ body: unknown;
32
+ }>;
33
+ };
34
+ export type PreparedRequest = Readonly<{
35
+ operation: string;
36
+ method: string;
37
+ url: string;
38
+ body?: string;
39
+ effect: "read" | "write";
40
+ }>;
41
+ export type TransportOptions = {
42
+ keys: ApiKeys;
43
+ origin?: string;
44
+ };
45
+ export declare class TransportError extends Error {
46
+ readonly error: {
47
+ code: string;
48
+ message: string;
49
+ operation: string;
50
+ status?: number;
51
+ retryAfter?: number;
52
+ auditId?: string;
53
+ };
54
+ readonly help: readonly string[];
55
+ constructor(error: {
56
+ code: string;
57
+ message: string;
58
+ operation: string;
59
+ status?: number;
60
+ retryAfter?: number;
61
+ auditId?: string;
62
+ }, help?: readonly string[]);
63
+ toJSON(): {
64
+ help?: readonly string[] | undefined;
65
+ error: {
66
+ code: string;
67
+ message: string;
68
+ operation: string;
69
+ status?: number;
70
+ retryAfter?: number;
71
+ auditId?: string;
72
+ };
73
+ };
74
+ }
75
+ export declare function constructTransport(options: TransportOptions, dependencies: {
76
+ bindings: Readonly<Record<string, OperationBinding>>;
77
+ fetch: typeof globalThis.fetch;
78
+ now?: () => number;
79
+ consumeWriteAuthorization?: (authorization: unknown, request: {
80
+ operation: string;
81
+ method: string;
82
+ url: string;
83
+ body?: string;
84
+ }) => boolean;
85
+ }): Transport;
@@ -0,0 +1,274 @@
1
+ export const TENABLE_ORIGIN = "https://cloud.tenable.com";
2
+ export class TransportError extends Error {
3
+ error;
4
+ help;
5
+ constructor(error, help = []) {
6
+ super(error.message);
7
+ this.error = error;
8
+ this.help = help;
9
+ this.name = "TransportError";
10
+ }
11
+ toJSON() { return { error: this.error, ...(this.help.length ? { help: this.help } : {}) }; }
12
+ }
13
+ // Internal construction seam. Production supplies only catalogue bindings and the
14
+ // native fetch; test support supplies synthetic bindings and a loopback adapter.
15
+ export function constructTransport(options, dependencies) {
16
+ const fail = (code, message, operation = "transport", help = [], details = {}) => {
17
+ throw new TransportError({ code, message, operation, ...details }, help);
18
+ };
19
+ if ((options.origin ?? TENABLE_ORIGIN) !== TENABLE_ORIGIN) {
20
+ fail("CONFIG_INVALID", "Origin must be exactly https://cloud.tenable.com");
21
+ }
22
+ const { accessKey, secretKey } = options.keys;
23
+ if ([accessKey, secretKey].some((key) => !key || /[\s\x00-\x1f\x7f;=,]/u.test(key))) {
24
+ fail("CONFIG_INVALID", "API keys must be nonempty and contain no header delimiters or control characters");
25
+ }
26
+ const header = `accessKey=${accessKey}; secretKey=${secretKey}`;
27
+ const secrets = [accessKey, secretKey, header].flatMap((value) => [value, JSON.stringify(value).slice(1, -1), encodeURIComponent(value)]).sort((a, b) => b.length - a.length);
28
+ const redact = (text) => {
29
+ for (const secret of secrets)
30
+ text = text.split(secret).join("[REDACTED]");
31
+ return text.replace(/(?:accessKey|secretKey|api[_-]?key|authorization|password|token)["']?\s*[=:]\s*["']?[^\s,;}"']+/gi, "[REDACTED]").replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 1000);
32
+ };
33
+ // Snapshot caller-owned bindings and keys before the first asynchronous send.
34
+ const bindings = Object.fromEntries(Object.entries(dependencies.bindings).map(([id, binding]) => [id, { ...binding, query: [...binding.query], paging: [...(binding.paging ?? [])] }]));
35
+ const now = dependencies.now ?? Date.now;
36
+ const deadline = now() + 20_000;
37
+ let requests = 0;
38
+ let bytes = 0;
39
+ const seen = new Set();
40
+ function destination(operation, binding, input) {
41
+ const params = input.pathParams ?? {};
42
+ const names = [...binding.path.matchAll(/\{([A-Za-z0-9_]+)\}/g)].map((match) => match[1]);
43
+ if (Object.keys(params).some((name) => !names.includes(name))) {
44
+ fail("VALIDATION_ERROR", "Unexpected path parameter", operation);
45
+ }
46
+ const path = binding.path.replace(/\{([A-Za-z0-9_]+)\}/g, (_, name) => {
47
+ const value = params[name];
48
+ if (!value || /[\s\x00-\x1f\x7f/\\%]/u.test(value) || value === "." || value === "..") {
49
+ fail("VALIDATION_ERROR", "Invalid or missing path parameter", operation);
50
+ }
51
+ return encodeURIComponent(value);
52
+ });
53
+ if (!path.startsWith("/") || path.startsWith("//") || /[?#\\]/.test(path)
54
+ || path.split("/").some((part) => part === "." || part === "..")) {
55
+ fail("DESTINATION_DENIED", "Operation has an invalid route binding", operation);
56
+ }
57
+ const initial = new URL(path, TENABLE_ORIGIN);
58
+ for (const [key, value] of Object.entries(input.query ?? {})) {
59
+ if (!binding.query.includes(key))
60
+ fail("VALIDATION_ERROR", "Unsupported query parameter", operation);
61
+ for (const item of Array.isArray(value) ? value : [value])
62
+ initial.searchParams.append(key, String(item));
63
+ }
64
+ if (input.continuation === undefined)
65
+ return initial;
66
+ const next = input.continuation;
67
+ let url;
68
+ try {
69
+ url = new URL(next, initial);
70
+ }
71
+ catch {
72
+ return fail("DESTINATION_DENIED", "Invalid continuation destination", operation);
73
+ }
74
+ // Reject normalization tricks before URL parsing can hide traversal or ports.
75
+ if (/[\\\x00-\x20\x7f#]/.test(next) || /%2e|%2f|%5c/i.test(next)
76
+ || next.split(/[/?]/).some((part) => part === "." || part === "..")
77
+ || (next.startsWith("https://") && !next.startsWith(`${TENABLE_ORIGIN}/`))
78
+ || url.origin !== TENABLE_ORIGIN || url.username || url.password || url.hash || url.pathname !== path
79
+ || [...url.searchParams.keys()].some((key) => !binding.query.includes(key)
80
+ || url.searchParams.getAll(key).length !== 1)) {
81
+ fail("DESTINATION_DENIED", "Continuation must retain the bound Tenable route", operation);
82
+ }
83
+ for (const key of new Set([...initial.searchParams.keys(), ...url.searchParams.keys()])) {
84
+ if (!binding.paging?.includes(key) && initial.searchParams.get(key) !== url.searchParams.get(key)) {
85
+ fail("DESTINATION_DENIED", "Continuation changed the request scope", operation);
86
+ }
87
+ }
88
+ return url;
89
+ }
90
+ function prepare(operation, input = {}) {
91
+ const binding = Object.hasOwn(bindings, operation) ? bindings[operation] : undefined;
92
+ if (!binding)
93
+ fail("OPERATION_BLOCKED", "Operation has no executable catalogue binding");
94
+ const url = destination(operation, binding, input).href;
95
+ const body = input.body === undefined ? undefined : JSON.stringify(input.body);
96
+ return Object.freeze({ operation, method: binding.method, url, body, effect: binding.effect });
97
+ }
98
+ async function request(operation, input = {}) {
99
+ const { url, body } = prepare(operation, input);
100
+ const record = bindings[operation];
101
+ const canonical = new URL(url);
102
+ canonical.searchParams.sort();
103
+ const identity = JSON.stringify([operation, canonical.href, body]);
104
+ if (input.continuation !== undefined && seen.has(identity)) {
105
+ fail("CONTINUATION_REPEATED", "The server repeated a continuation", operation);
106
+ }
107
+ if (record.effect === "write" && !dependencies.consumeWriteAuthorization?.(input.authorization, { operation, method: record.method, url, body })) {
108
+ fail("OPERATION_BLOCKED", "Writes require coordinator authorization", operation);
109
+ }
110
+ seen.add(identity);
111
+ let lastRetryAfter;
112
+ for (let attempt = 0;; attempt++) {
113
+ if (input.signal?.aborted)
114
+ fail("REQUEST_CANCELLED", "Request was cancelled", operation);
115
+ const remaining = deadline - now();
116
+ if (remaining <= 0)
117
+ fail("DEADLINE_EXCEEDED", "Invocation deadline exceeded", operation);
118
+ if (requests >= 20)
119
+ fail("REQUEST_BUDGET_EXCEEDED", "Invocation request budget exceeded", operation);
120
+ requests++;
121
+ const controller = new AbortController();
122
+ const abort = () => controller.abort();
123
+ input.signal?.addEventListener("abort", abort, { once: true });
124
+ let timedOut = false;
125
+ const timer = setTimeout(() => { timedOut = true; controller.abort(); }, remaining);
126
+ let response;
127
+ let text;
128
+ let file;
129
+ try {
130
+ response = await dependencies.fetch(url, {
131
+ method: record.method, redirect: "error", signal: controller.signal,
132
+ headers: { "X-ApiKeys": header, Accept: record.responseMode === "file" ? "application/octet-stream" : "application/json", ...(body === undefined ? {} : { "Content-Type": "application/json" }) },
133
+ ...(body === undefined ? {} : { body }),
134
+ });
135
+ if (response.status >= 300 && response.status < 400) {
136
+ await response.body?.cancel();
137
+ fail("DESTINATION_DENIED", "Tenable redirects are refused", operation, [], { status: response.status });
138
+ }
139
+ const reader = response.body?.getReader();
140
+ const chunks = [];
141
+ const downloading = record.responseMode === "file" && response.status >= 200 && response.status < 300;
142
+ const ceiling = downloading ? 128 * 1024 * 1024 : 20 * 1024 * 1024;
143
+ if (downloading && Number(response.headers.get("content-length")) > ceiling) {
144
+ await reader?.cancel();
145
+ fail("BYTE_BUDGET_EXCEEDED", "Export encoded file exceeds 128 MiB", operation);
146
+ }
147
+ try {
148
+ while (reader) {
149
+ const chunk = await reader.read();
150
+ if (chunk.done)
151
+ break;
152
+ bytes += chunk.value.byteLength;
153
+ if (bytes > ceiling) {
154
+ controller.abort();
155
+ fail("BYTE_BUDGET_EXCEEDED", "Invocation decoded response byte budget exceeded", operation);
156
+ }
157
+ chunks.push(chunk.value);
158
+ }
159
+ }
160
+ finally {
161
+ await reader?.cancel().catch(() => { });
162
+ }
163
+ const contents = Buffer.concat(chunks);
164
+ if (downloading)
165
+ file = contents;
166
+ text = downloading ? "" : contents.toString("utf8");
167
+ }
168
+ catch (error) {
169
+ if (error instanceof TransportError)
170
+ throw error;
171
+ const code = record.effect === "write" ? "OUTCOME_UNKNOWN"
172
+ : input.signal?.aborted ? "REQUEST_CANCELLED" : timedOut ? "DEADLINE_EXCEEDED" : "TRANSPORT_FAILED";
173
+ fail(code, record.effect === "write" ? "Mutation outcome is unknown; read back before retrying"
174
+ : "Tenable request could not complete", operation, ["Check connectivity and retry the read when ready"]);
175
+ }
176
+ finally {
177
+ clearTimeout(timer);
178
+ input.signal?.removeEventListener("abort", abort);
179
+ }
180
+ if (input.signal?.aborted)
181
+ fail(record.effect === "write" ? "OUTCOME_UNKNOWN" : "REQUEST_CANCELLED", "Request was cancelled", operation);
182
+ if (now() >= deadline)
183
+ fail(record.effect === "write" ? "OUTCOME_UNKNOWN" : "DEADLINE_EXCEEDED", "Invocation deadline exceeded", operation);
184
+ if (response.status >= 200 && response.status < 300) {
185
+ if (record.responseMode === "file") {
186
+ if (response.status === 204)
187
+ fail("EXPORT_NOT_READY", "Export chunk is not ready; check status before downloading", operation);
188
+ return { status: response.status, body: file };
189
+ }
190
+ let decoded;
191
+ try {
192
+ decoded = text ? JSON.parse(text) : undefined;
193
+ }
194
+ catch {
195
+ fail("RESPONSE_INVALID", "Tenable response is not valid JSON", operation, [], { status: response.status });
196
+ }
197
+ const result = record.decoder.safeParse(decoded);
198
+ if (!result.success)
199
+ fail("RESPONSE_INVALID", "Tenable response does not match the selected view", operation, ["Check the operation response contract; no result was inferred"], { status: response.status });
200
+ return { status: response.status, body: result.data };
201
+ }
202
+ const status = response.status;
203
+ const delay = retryAfter(response.headers.get("retry-after"), now());
204
+ if (delay !== undefined)
205
+ lastRetryAfter = delay;
206
+ const retryable = input.retry !== false && record.effect === "read" && [429, 502, 503, 504].includes(status);
207
+ const wait = delay ?? (attempt === 0 ? 250 : 500);
208
+ if (retryable && attempt < 2 && requests < 20 && wait < deadline - now()) {
209
+ await new Promise((resolve, reject) => {
210
+ const cancel = () => {
211
+ clearTimeout(pause);
212
+ reject(new TransportError({ code: "REQUEST_CANCELLED", message: "Request was cancelled", operation }));
213
+ };
214
+ const pause = setTimeout(() => { input.signal?.removeEventListener("abort", cancel); resolve(); }, wait);
215
+ input.signal?.addEventListener("abort", cancel, { once: true });
216
+ if (input.signal?.aborted)
217
+ cancel();
218
+ });
219
+ continue;
220
+ }
221
+ const code = status === 401 ? "AUTH_REQUIRED" : status === 403 ? "PERMISSION_DENIED"
222
+ : status === 404 ? "NOT_FOUND" : status === 429 ? "RATE_LIMITED"
223
+ : [400, 409, 422].includes(status) ? "VALIDATION_ERROR" : "REQUEST_FAILED";
224
+ const hint = status === 401 ? "Check both SecretRefs and run tenable-axi auth status"
225
+ : status === 403 ? record.permissionHelp : status === 404 ? "Check the resource identifier and operation scope"
226
+ : status === 429 ? "Retry after the reported delay; narrow reads to reduce requests" : record.validationHelp;
227
+ const message = errorMessage(text) ?? `Tenable returned HTTP ${status}`;
228
+ fail(code, redact(message), operation, [hint], { status,
229
+ ...(lastRetryAfter === undefined ? {} : { retryAfter: lastRetryAfter }) });
230
+ }
231
+ }
232
+ return { prepare, request };
233
+ }
234
+ function retryAfter(value, now) {
235
+ if (value === null)
236
+ return undefined;
237
+ const text = value.trim();
238
+ if (/^\d+$/.test(text)) {
239
+ const seconds = Number(text);
240
+ return Number.isSafeInteger(seconds * 1000) ? seconds * 1000 : undefined;
241
+ }
242
+ // The obsolete asctime HTTP-date has no zone but is defined in GMT.
243
+ const asctimeForm = /^[A-Za-z]{3} [A-Za-z]{3} (?: [1-9]|[12]\d|3[01]) \d{2}:\d{2}:\d{2} \d{4}$/.test(text);
244
+ const date = Date.parse(asctimeForm ? `${text} GMT` : text);
245
+ if (Number.isNaN(date))
246
+ return undefined;
247
+ const parsed = new Date(date);
248
+ const standard = parsed.toUTCString();
249
+ const [weekday, day, month, year, time] = standard.split(" ");
250
+ const weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
251
+ const obsolete = `${weekdays[parsed.getUTCDay()]}, ${day}-${month}-${year.slice(-2)} ${time} GMT`;
252
+ const asctime = `${weekday.slice(0, 3)} ${month} ${String(Number(day)).padStart(2, " ")} ${time} ${year}`;
253
+ if (![standard, obsolete, asctime].includes(text))
254
+ return undefined;
255
+ return Math.max(0, date - now);
256
+ }
257
+ function errorMessage(text) {
258
+ let body;
259
+ try {
260
+ body = JSON.parse(text);
261
+ }
262
+ catch {
263
+ return undefined;
264
+ }
265
+ if (!body || typeof body !== "object")
266
+ return undefined;
267
+ const record = body;
268
+ const detail = record.detail && typeof record.detail === "object" ? record.detail : {};
269
+ const nested = [record.error, record.errors].flatMap((value) => Array.isArray(value) ? value : [])
270
+ .flatMap((value) => value && typeof value === "object" && "message" in value ? [value.message] : []);
271
+ const messages = [record.message, detail.display_message, detail.msg, ...nested, record.error, record.detail]
272
+ .filter((value) => typeof value === "string" && value.trim().length > 0 && !/[<>]/.test(value));
273
+ return messages.length ? messages.join("; ") : undefined;
274
+ }
@@ -0,0 +1,4 @@
1
+ import { type Transport, type TransportOptions } from "./transport-core.js";
2
+ export { TENABLE_ORIGIN, TransportError } from "./transport-core.js";
3
+ export type { ApiKeys, OperationBinding, RequestOptions, Transport, TransportOptions } from "./transport-core.js";
4
+ export declare function createTransport(options: TransportOptions): Transport;
@@ -0,0 +1,6 @@
1
+ import { transportBindings } from "./catalogue.js";
2
+ import { constructTransport } from "./transport-core.js";
3
+ export { TENABLE_ORIGIN, TransportError } from "./transport-core.js";
4
+ export function createTransport(options) {
5
+ return constructTransport(options, { bindings: transportBindings, fetch: globalThis.fetch });
6
+ }