@akai-workflow-builder/cli-sdk 0.19.0 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Hold a `ctx.fetch` connection to the addresses safe-fetch checked.
3
+ *
4
+ * safe-fetch resolves a host and refuses it when any answer is private. Global
5
+ * fetch then resolves the name again on its own, so a name that answers public
6
+ * for the check and private a moment later (DNS rebinding) would be dialled at
7
+ * the private address. The dispatcher here is an undici Agent whose
8
+ * `connect.lookup` never asks DNS: it answers with the addresses safe-fetch
9
+ * vetted for that hostname, the same idea as the worker's `publicLookup`.
10
+ *
11
+ * What stays as it was:
12
+ * - The URL still names the request. The `Host` header and the TLS servername
13
+ * (and so certificate verification) are the hostname; only the address a
14
+ * socket dials comes from the vetted list.
15
+ * - Pooling. One Agent serves every call, so keep-alive works as it did on the
16
+ * global dispatcher. A pooled socket was dialled at an address vetted for its
17
+ * host, so reusing it reaches nothing new.
18
+ * - A host-installed transport. When the global dispatcher is not a plain
19
+ * direct Agent (the worker's PROXY_LOCATION ProxyAgent, Node's env proxy, a
20
+ * test's MockAgent, anything else) it is left alone: {@link vettedDispatcher}
21
+ * returns null and the call rides global fetch as before. A proxy resolves
22
+ * the name itself; the SDK has no say over which address it dials.
23
+ *
24
+ * undici 8 is loaded by file, not through its index: the index claims Node's
25
+ * global dispatcher when it loads, and this module must not change the
26
+ * transport of any other fetch in the host process. The imports are literal
27
+ * dynamic imports so a bundler inlines them: cli-service's baseline bundle
28
+ * carries this runtime to a directory with no node_modules.
29
+ */
30
+ import { isIPv6 } from 'node:net';
31
+ /** Error code for a connection to a hostname with no vetted addresses on record. */
32
+ export const UNVETTED_CODE = 'ESAFEFETCHUNVETTED';
33
+ /** Hostnames whose vetted addresses are kept. Far more than any one process dials at once. */
34
+ const MAX_VETTED_HOSTS = 4096;
35
+ const vetted = new Map();
36
+ /** The key a hostname is filed under: URL hostnames are already lowercase; IPv6 brackets and case are dropped. */
37
+ const hostKey = (hostname) => hostname.replace(/^\[|\]$/g, '').toLowerCase();
38
+ /**
39
+ * Record the addresses safe-fetch checked for `hostname`. The next connection
40
+ * the dispatcher opens to that host dials one of these and nothing else. A
41
+ * later call replaces the entry; every entry ever stored passed the check.
42
+ */
43
+ export function rememberVetted(hostname, addresses) {
44
+ const key = hostKey(hostname);
45
+ vetted.delete(key);
46
+ vetted.set(key, addresses.map((address) => ({ address, family: isIPv6(address) ? 6 : 4 })));
47
+ if (vetted.size > MAX_VETTED_HOSTS) {
48
+ const oldest = vetted.keys().next();
49
+ if (!oldest.done)
50
+ vetted.delete(oldest.value);
51
+ }
52
+ }
53
+ /**
54
+ * The `connect.lookup` of the dispatcher: answers with the vetted addresses
55
+ * for the hostname, in either shape Node asks for (`all: true` for
56
+ * happy-eyeballs, the default since Node 20, or a single address and family),
57
+ * honouring a requested family. A hostname with nothing on record fails the
58
+ * connection rather than falling back to DNS.
59
+ */
60
+ export const vettedLookup = (hostname, options, callback) => {
61
+ const entries = vetted.get(hostKey(hostname));
62
+ if (entries === undefined || entries.length === 0) {
63
+ const err = Object.assign(new Error(`safe-fetch: no checked address for ${hostname}`), { code: UNVETTED_CODE });
64
+ callback(err, '', 4);
65
+ return;
66
+ }
67
+ const family = options.family === 4 || options.family === 6 ? options.family : null;
68
+ const answers = family === null ? entries : entries.filter((entry) => entry.family === family);
69
+ if (answers.length === 0) {
70
+ const err = Object.assign(new Error(`safe-fetch: no checked IPv${family} address for ${hostname}`), { code: 'ENOTFOUND' });
71
+ callback(err, '', 4);
72
+ return;
73
+ }
74
+ if (options.all) {
75
+ callback(null, answers.map((entry) => ({ ...entry })));
76
+ }
77
+ else {
78
+ callback(null, answers[0].address, answers[0].family);
79
+ }
80
+ };
81
+ /** What a global dispatcher is, judged by its class name: undici's own classes, unminified in node_modules. */
82
+ const className = (value) => typeof value === 'object' && value !== null ? value.constructor?.name : undefined;
83
+ const LEGACY_GLOBAL_DISPATCHER = Symbol.for('undici.globalDispatcher.1');
84
+ const GLOBAL_DISPATCHER = Symbol.for('undici.globalDispatcher.2');
85
+ /**
86
+ * How Node's global fetch connects right now:
87
+ * - `node`: Node's own default Agent (undici 7, HTTP/1.1 only), or none yet —
88
+ * Node creates that same default on its first fetch;
89
+ * - `undici8`: an undici 8 Agent set through its `setGlobalDispatcher`, which
90
+ * stores the Agent and a Dispatcher1Wrapper for Node's fetch (the worker's
91
+ * `installGlobalDispatcher`);
92
+ * - `other`: anything else — a proxy, a mock, a custom dispatcher.
93
+ */
94
+ function globalTransport() {
95
+ const store = globalThis;
96
+ const legacy = store[LEGACY_GLOBAL_DISPATCHER];
97
+ if (legacy === undefined)
98
+ return 'node';
99
+ const name = className(legacy);
100
+ if (name === 'Agent')
101
+ return 'node';
102
+ if (name === 'Dispatcher1Wrapper' && className(store[GLOBAL_DISPATCHER]) === 'Agent')
103
+ return 'undici8';
104
+ return 'other';
105
+ }
106
+ /** The undici classes, or null once loading them failed (then calls keep global fetch's own dispatcher). */
107
+ let modules = null;
108
+ function loadUndici() {
109
+ modules ??= Promise.all([
110
+ import('undici/lib/dispatcher/agent.js'),
111
+ import('undici/lib/dispatcher/dispatcher1-wrapper.js'),
112
+ ]).then(([agent, wrapper]) => ({ Agent: agent.default, Dispatcher1Wrapper: wrapper.default }), () => null);
113
+ return modules;
114
+ }
115
+ const dispatchers = new Map();
116
+ /**
117
+ * The dispatcher a vetted `ctx.fetch` call passes to global fetch, or null when
118
+ * the host has installed a transport of its own (see the module comment) or
119
+ * undici could not be loaded — the call then goes out exactly as it did before
120
+ * this module existed, rather than failing.
121
+ *
122
+ * It mirrors the transport it stands in for: under Node's default it speaks
123
+ * HTTP/1.1 only, as Node's Agent does; under an undici 8 global Agent it keeps
124
+ * undici 8's defaults, HTTP/2 negotiation included. Node 24's fetch speaks the
125
+ * v1 handler API, so the undici 8 Agent sits behind Dispatcher1Wrapper, as in
126
+ * the worker.
127
+ */
128
+ export async function vettedDispatcher() {
129
+ const transport = globalTransport();
130
+ if (transport === 'other')
131
+ return null;
132
+ let dispatcher = dispatchers.get(transport);
133
+ if (dispatcher === undefined) {
134
+ const loaded = await loadUndici();
135
+ if (loaded === null)
136
+ return null;
137
+ // Another call may have built it while this one waited on the import.
138
+ const built = dispatchers.get(transport);
139
+ if (built !== undefined)
140
+ return built;
141
+ const { Agent, Dispatcher1Wrapper } = loaded;
142
+ const agent = new Agent({
143
+ connect: { lookup: vettedLookup },
144
+ ...(transport === 'node' ? { allowH2: false } : {}),
145
+ });
146
+ dispatcher = new Dispatcher1Wrapper(agent);
147
+ dispatchers.set(transport, dispatcher);
148
+ }
149
+ return dispatcher;
150
+ }
151
+ /**
152
+ * Whether Node routes `node:https` through an env-configured proxy
153
+ * (`NODE_USE_ENV_PROXY` / `--use-env-proxy`). The mutual-TLS path leaves its
154
+ * lookup alone then: the socket goes to the proxy, not to the vetted address.
155
+ */
156
+ export function nodeEnvProxyEnabled() {
157
+ const flag = process.env.NODE_USE_ENV_PROXY;
158
+ if (flag !== undefined && flag !== '' && flag !== '0' && flag.toLowerCase() !== 'false')
159
+ return true;
160
+ return process.execArgv.includes('--use-env-proxy') || (process.env.NODE_OPTIONS ?? '').includes('--use-env-proxy');
161
+ }
162
+ /** Test seam: forget every vetted address and dispatcher. */
163
+ export function resetVettedDispatchForTests() {
164
+ vetted.clear();
165
+ for (const dispatcher of dispatchers.values())
166
+ dispatcher.close().catch(() => { });
167
+ dispatchers.clear();
168
+ }
@@ -13,10 +13,9 @@ export declare const FILE_INPUT_META_KEY = "x-akai-file-input";
13
13
  * - An absolute path (resolved via `ctx.safePath`).
14
14
  * - A relative path (resolved against the worker's `workdir` allowlist).
15
15
  * - A `file://` URL (prefix stripped, then resolved as a path).
16
- * - An `http(s)://` URL — the runtime that routes the tool call across
17
- * pods (e.g. worker → DT) is responsible for upgrading local paths to
18
- * trusted presigned URLs before dispatch; the SDK's `ctx.readFile`
19
- * fetches without an egress allowlist.
16
+ * - An `http(s)://` URL, as the agent passed it. `ctx.readFile` fetches it
17
+ * without an egress allowlist but refuses a blocked-domain host and any
18
+ * host that resolves to a private address.
20
19
  *
21
20
  * The schema is a plain `z.string().min(1)` (so existing path-only
22
21
  * consumers keep working), branded with `x-akai-file-input: true` in its
@@ -1 +1 @@
1
- {"version":3,"file":"file-input.d.ts","sourceRoot":"","sources":["../src/file-input.ts"],"names":[],"mappings":"AAAA,OAAO,EAAK,KAAK,SAAS,EAAE,MAAM,KAAK,CAAC;AAExC;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB,sBAAsB,CAAC;AAEvD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,QAAQ,IAAI,SAAS,CAEpC"}
1
+ {"version":3,"file":"file-input.d.ts","sourceRoot":"","sources":["../src/file-input.ts"],"names":[],"mappings":"AAAA,OAAO,EAAK,KAAK,SAAS,EAAE,MAAM,KAAK,CAAC;AAExC;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB,sBAAsB,CAAC;AAEvD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,QAAQ,IAAI,SAAS,CAEpC"}
@@ -13,10 +13,9 @@ export const FILE_INPUT_META_KEY = 'x-akai-file-input';
13
13
  * - An absolute path (resolved via `ctx.safePath`).
14
14
  * - A relative path (resolved against the worker's `workdir` allowlist).
15
15
  * - A `file://` URL (prefix stripped, then resolved as a path).
16
- * - An `http(s)://` URL — the runtime that routes the tool call across
17
- * pods (e.g. worker → DT) is responsible for upgrading local paths to
18
- * trusted presigned URLs before dispatch; the SDK's `ctx.readFile`
19
- * fetches without an egress allowlist.
16
+ * - An `http(s)://` URL, as the agent passed it. `ctx.readFile` fetches it
17
+ * without an egress allowlist but refuses a blocked-domain host and any
18
+ * host that resolves to a private address.
20
19
  *
21
20
  * The schema is a plain `z.string().min(1)` (so existing path-only
22
21
  * consumers keep working), branded with `x-akai-file-input: true` in its
package/dist/types.d.ts CHANGED
@@ -164,9 +164,9 @@ export interface ToolCtx<S extends string = string, P extends string = string> {
164
164
  safePath: (userPath: string) => string;
165
165
  /**
166
166
  * Read a file referenced by either a local path (resolved via {@link safePath})
167
- * or an `http(s)://` URL (fetched, no egress allowlist — runtimes that route
168
- * tool inputs across pods, e.g. via presigned object-store URLs, control
169
- * which URLs reach the handler at the request boundary). Strips `file://`
167
+ * or an `http(s)://` URL (fetched with no egress allowlist, but a host on the
168
+ * blocked-domain list or one that resolves to a private address is refused,
169
+ * as in {@link fetch}; the URL is whatever the agent passed). Strips `file://`
170
170
  * before resolving as a local path.
171
171
  *
172
172
  * Pairs with `filePath()` from the SDK: tool authors switch
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akai-workflow-builder/cli-sdk",
3
- "version": "0.19.0",
3
+ "version": "0.20.1",
4
4
  "description": "Authoring SDK for atomic, agent-executable CLIs and tools.",
5
5
  "keywords": [
6
6
  "akai",
@@ -58,7 +58,8 @@
58
58
  },
59
59
  "dependencies": {
60
60
  "ssh2": "^1.17.0",
61
- "tar": "^7.5.22"
61
+ "tar": "^7.5.22",
62
+ "undici": "8.12.2"
62
63
  },
63
64
  "peerDependencies": {
64
65
  "zod": "^4.4.1",