@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.10

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 (285) hide show
  1. package/CHANGELOG.md +251 -0
  2. package/LICENSE +1 -1
  3. package/LICENSE-cobra.txt +174 -0
  4. package/NOTICE +15 -0
  5. package/README.md +55 -259
  6. package/dist/aim-DZHwwiIc.d.ts +139 -0
  7. package/dist/aim.d.ts +1 -116
  8. package/dist/aim.js +13 -414
  9. package/dist/alias-D9_qFlyP.d.ts +174 -0
  10. package/dist/alias.d.ts +2 -73
  11. package/dist/alias.js +27 -207
  12. package/dist/api-DAexsu2H.d.ts +77 -0
  13. package/dist/api.d.ts +1 -62
  14. package/dist/api.js +10 -164
  15. package/dist/auth-2-jfgiHn.d.ts +34 -0
  16. package/dist/auth.d.ts +1 -26
  17. package/dist/auth.js +6 -40
  18. package/dist/chunk-2JV3A7OP.js +1894 -0
  19. package/dist/chunk-3FIKGFKI.js +54 -0
  20. package/dist/chunk-4UE5TCMQ.js +104 -0
  21. package/dist/chunk-6HFAEZ52.js +29 -0
  22. package/dist/chunk-6SVOHNIC.js +17 -0
  23. package/dist/chunk-72XZWQX7.js +504 -0
  24. package/dist/chunk-ABQSE7AI.js +513 -0
  25. package/dist/chunk-BDNNPRX6.js +41 -0
  26. package/dist/chunk-BLS2OBIQ.js +263 -0
  27. package/dist/chunk-BRNEKPWX.js +37 -0
  28. package/dist/chunk-CSJWB6D3.js +151 -0
  29. package/dist/chunk-GGWJRWWA.js +309 -0
  30. package/dist/chunk-GHPJJV5L.js +613 -0
  31. package/dist/chunk-IXVQ62NZ.js +334 -0
  32. package/dist/chunk-JKMQSAJP.js +174 -0
  33. package/dist/chunk-JZ22ZUFA.js +1131 -0
  34. package/dist/chunk-K7VCKJ27.js +814 -0
  35. package/dist/chunk-KVG7YCTS.js +115 -0
  36. package/dist/chunk-L23O2FFE.js +51 -0
  37. package/dist/chunk-MQXYDYRD.js +968 -0
  38. package/dist/chunk-MUIQVU6E.js +251 -0
  39. package/dist/chunk-NLMS7HGP.js +178 -0
  40. package/dist/chunk-POR5L2DG.js +247 -0
  41. package/dist/chunk-PSFYJGDG.js +1445 -0
  42. package/dist/chunk-QJVSKKRQ.js +369 -0
  43. package/dist/chunk-QPUCXQXT.js +67 -0
  44. package/dist/chunk-QQQYCWSC.js +240 -0
  45. package/dist/chunk-R5U7XKVJ.js +16 -0
  46. package/dist/chunk-SNVGDYX7.js +187 -0
  47. package/dist/chunk-T46YPHKN.js +669 -0
  48. package/dist/chunk-UKZIAQA7.js +26 -0
  49. package/dist/chunk-WBVO43HU.js +355 -0
  50. package/dist/chunk-WUOAQVOA.js +86 -0
  51. package/dist/chunk-WWUKGJB5.js +90 -0
  52. package/dist/chunk-XJTRY453.js +868 -0
  53. package/dist/chunk-YGYQUFGY.js +219 -0
  54. package/dist/chunk-YOBAUCVN.js +583 -0
  55. package/dist/cli-C5B5tnpA.d.ts +400 -0
  56. package/dist/cli.d.ts +7 -309
  57. package/dist/cli.js +70 -945
  58. package/dist/completion-csVun6SP.d.ts +112 -0
  59. package/dist/completion-values-By-mnjNt.d.ts +142 -0
  60. package/dist/completion-values.d.ts +1 -0
  61. package/dist/completion-values.js +29 -0
  62. package/dist/completion.d.ts +3 -0
  63. package/dist/completion.js +34 -0
  64. package/dist/compliance-AxFf-uMy.d.ts +60 -0
  65. package/dist/compliance.d.ts +1 -0
  66. package/dist/compliance.js +17 -0
  67. package/dist/config-CaK60ByQ.d.ts +241 -0
  68. package/dist/config.d.ts +1 -97
  69. package/dist/config.js +8 -78
  70. package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
  71. package/dist/errcorrect.d.ts +1 -37
  72. package/dist/errcorrect.js +8 -68
  73. package/dist/error-Do8Qji43.d.ts +231 -0
  74. package/dist/id/index.d.ts +2 -83
  75. package/dist/id/index.js +14 -65
  76. package/dist/index-BKJZClJx.d.ts +1486 -0
  77. package/dist/index-C3Zw4wDJ.d.ts +359 -0
  78. package/dist/index-DCe1boBz.d.ts +328 -0
  79. package/dist/index-VLDcI5NF.d.ts +95 -0
  80. package/dist/index.d.ts +37 -0
  81. package/dist/index.js +132 -0
  82. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  83. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  84. package/dist/llm-anthropic.d.ts +2 -0
  85. package/dist/llm-anthropic.js +13 -0
  86. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  87. package/dist/llm-openai.d.ts +2 -0
  88. package/dist/llm-openai.js +19 -0
  89. package/dist/llm.d.ts +1 -188
  90. package/dist/llm.js +101 -356
  91. package/dist/log-CkaxMX3U.d.ts +115 -0
  92. package/dist/log.d.ts +2 -0
  93. package/dist/log.js +14 -0
  94. package/dist/mcp/index.d.ts +4 -0
  95. package/dist/mcp/index.js +184 -0
  96. package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
  97. package/dist/netpolicy.d.ts +1 -0
  98. package/dist/netpolicy.js +25 -0
  99. package/dist/output-CjZWmL8s.d.ts +420 -0
  100. package/dist/output.d.ts +3 -213
  101. package/dist/output.js +137 -447
  102. package/dist/parity-CvMuYcVI.d.ts +61 -0
  103. package/dist/progress-CAzyxeWl.d.ts +38 -0
  104. package/dist/progress.d.ts +1 -30
  105. package/dist/progress.js +6 -55
  106. package/dist/provenance-SMFHm5gx.d.ts +30 -0
  107. package/dist/provenance.d.ts +1 -24
  108. package/dist/provenance.js +6 -31
  109. package/dist/routellm-B0nv59mH.d.ts +111 -0
  110. package/dist/routellm.d.ts +2 -64
  111. package/dist/routellm.js +13 -255
  112. package/dist/rpc-D31Lg0Kc.d.ts +32 -0
  113. package/dist/rpc.d.ts +2 -25
  114. package/dist/rpc.js +4 -98
  115. package/dist/safety-CUaYEjZc.d.ts +30 -0
  116. package/dist/safety.d.ts +1 -24
  117. package/dist/safety.js +6 -43
  118. package/dist/scope-BrhYB4ij.d.ts +141 -0
  119. package/dist/scope.d.ts +1 -121
  120. package/dist/scope.js +20 -377
  121. package/dist/serve-D8yWMrTc.d.ts +646 -0
  122. package/dist/serve.d.ts +3 -0
  123. package/dist/serve.js +75 -0
  124. package/dist/sqlstore.js +6 -39
  125. package/dist/stream-CrjeCp0M.d.ts +44 -0
  126. package/dist/stream.d.ts +1 -35
  127. package/dist/stream.js +8 -51
  128. package/dist/telemetry/index.d.ts +1 -315
  129. package/dist/telemetry/index.js +26 -599
  130. package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
  131. package/dist/toolspec.d.ts +2 -0
  132. package/dist/toolspec.js +37 -0
  133. package/dist/tui/index.d.ts +6 -298
  134. package/dist/tui/index.js +17 -381
  135. package/dist/upgrade-p_zh3pvV.d.ts +102 -0
  136. package/dist/upgrade.d.ts +1 -95
  137. package/dist/upgrade.js +6 -114
  138. package/dist/xdg-DB7Shoib.d.ts +179 -0
  139. package/dist/xdg.d.ts +1 -169
  140. package/dist/xdg.js +14 -128
  141. package/package.json +192 -24
  142. package/src/README.md +15 -0
  143. package/src/alias.conformance.test.ts +250 -0
  144. package/src/alias.test.ts +206 -2
  145. package/src/alias.ts +196 -21
  146. package/src/cli.help-command.test.ts +105 -0
  147. package/src/cli.offline.test.ts +93 -0
  148. package/src/cli.parity.test.ts +192 -0
  149. package/src/cli.test.ts +95 -1
  150. package/src/cli.ts +195 -25
  151. package/src/completion-scripts.ts +16 -0
  152. package/src/completion-values.test.ts +76 -16
  153. package/src/completion-values.ts +170 -66
  154. package/src/completion.conformance.test.ts +297 -0
  155. package/src/completion.test.ts +256 -145
  156. package/src/completion.ts +767 -121
  157. package/src/compliance.test.ts +196 -2
  158. package/src/compliance.ts +440 -20
  159. package/src/config-merge.test.ts +425 -0
  160. package/src/config.test.ts +228 -1
  161. package/src/config.ts +429 -16
  162. package/src/gen/crud_pb.ts +7 -7
  163. package/src/id/README.md +38 -0
  164. package/src/id/contract.test.ts +1 -1
  165. package/src/id/index.test.ts +1 -1
  166. package/src/id/index.ts +3 -2
  167. package/src/index.test.ts +71 -0
  168. package/src/index.ts +46 -0
  169. package/src/llm-anthropic.conformance.test.ts +1135 -0
  170. package/src/llm-anthropic.test.ts +152 -0
  171. package/src/llm-anthropic.ts +940 -0
  172. package/src/llm-choice-hermetic.test.ts +335 -0
  173. package/src/llm-config.test.ts +232 -0
  174. package/src/llm-config.ts +106 -0
  175. package/src/llm-endpoint.ts +254 -0
  176. package/src/llm-error.ts +17 -0
  177. package/src/llm-errors.ts +152 -0
  178. package/src/llm-file.ts +126 -0
  179. package/src/llm-http.ts +317 -0
  180. package/src/llm-keys.ts +167 -0
  181. package/src/llm-media.conformance.test.ts +87 -0
  182. package/src/llm-media.test.ts +279 -0
  183. package/src/llm-media.ts +322 -0
  184. package/src/llm-openai.conformance.test.ts +407 -0
  185. package/src/llm-openai.test.ts +510 -0
  186. package/src/llm-openai.ts +708 -0
  187. package/src/llm-payload.ts +155 -0
  188. package/src/llm-quote.ts +46 -0
  189. package/src/llm-routellm.conformance.test.ts +44 -0
  190. package/src/llm-toolnames.conformance.test.ts +112 -0
  191. package/src/llm-toolnames.test.ts +132 -0
  192. package/src/llm-toolnames.ts +298 -0
  193. package/src/llm-uri.ts +99 -0
  194. package/src/llm.test.ts +43 -15
  195. package/src/llm.toolcall.test.ts +175 -0
  196. package/src/llm.ts +602 -190
  197. package/src/log.parity.test.ts +105 -0
  198. package/src/log.test.ts +270 -1
  199. package/src/log.ts +228 -49
  200. package/src/mcp/README.md +63 -0
  201. package/src/mcp/args-separator.test.ts +164 -0
  202. package/src/mcp/args.test.ts +223 -0
  203. package/src/mcp/args.ts +160 -0
  204. package/src/mcp/audit.test.ts +520 -0
  205. package/src/mcp/audit.ts +70 -0
  206. package/src/mcp/bridge.test.ts +222 -0
  207. package/src/mcp/bridge.ts +291 -0
  208. package/src/mcp/conformance.test.ts +357 -0
  209. package/src/mcp/dispatch.ts +359 -0
  210. package/src/mcp/identity.test.ts +166 -0
  211. package/src/mcp/identity.ts +72 -0
  212. package/src/mcp/index.ts +176 -0
  213. package/src/mcp/legacy-notify.test.ts +59 -0
  214. package/src/mcp/legacy.ts +367 -0
  215. package/src/mcp/mcp.test.ts +707 -0
  216. package/src/mcp/modern-confirm.test.ts +520 -0
  217. package/src/mcp/modern-confirm.ts +484 -0
  218. package/src/mcp/modern.ts +788 -0
  219. package/src/mcp/stdio.test.ts +313 -0
  220. package/src/mcp/stdio.ts +254 -0
  221. package/src/mcp/tasks.ts +82 -0
  222. package/src/mcp/testtree.ts +250 -0
  223. package/src/mcp/toolname.test.ts +147 -0
  224. package/src/mcp/types.ts +689 -0
  225. package/src/netpolicy.test.ts +280 -0
  226. package/src/netpolicy.ts +256 -0
  227. package/src/output/README.md +46 -0
  228. package/src/output/builtins.ts +5 -5
  229. package/src/output/dispatch.ts +10 -2
  230. package/src/output/error.ts +459 -0
  231. package/src/output/formatter.ts +29 -5
  232. package/src/output/formatters/README.md +50 -0
  233. package/src/output/formatters/csv.ts +48 -12
  234. package/src/output/formatters/json.ts +4 -25
  235. package/src/output/formatters/project.ts +34 -0
  236. package/src/output/formatters/table.ts +8 -6
  237. package/src/output/formatters/text.ts +7 -3
  238. package/src/output/formatters/yaml.ts +5 -22
  239. package/src/output/projection.test.ts +298 -0
  240. package/src/output/projection.ts +33 -59
  241. package/src/output/template.ts +11 -21
  242. package/src/output.surface.test.ts +41 -0
  243. package/src/output.ts +64 -3
  244. package/src/published-types.test.ts +133 -0
  245. package/src/routellm.test.ts +209 -28
  246. package/src/routellm.toolcall.test.ts +521 -0
  247. package/src/routellm.ts +213 -177
  248. package/src/router/README.md +44 -0
  249. package/src/router/server.test.ts +41 -0
  250. package/src/router/server.ts +11 -0
  251. package/src/safety.test.ts +19 -9
  252. package/src/scope-defaults.json +29 -29
  253. package/src/serve.test.ts +1257 -0
  254. package/src/serve.ts +1665 -0
  255. package/src/telemetry/README.md +48 -0
  256. package/src/telemetry/client.test.ts +31 -0
  257. package/src/telemetry/client.ts +12 -6
  258. package/src/telemetry/offline.test.ts +64 -0
  259. package/src/toolspec-internal.ts +279 -0
  260. package/src/toolspec-manifest.test.ts +167 -0
  261. package/src/toolspec-manifest.ts +410 -0
  262. package/src/toolspec-spec-schemas.ts +12 -0
  263. package/src/toolspec-spec.test.ts +273 -0
  264. package/src/toolspec-spec.ts +458 -0
  265. package/src/toolspec.from-command.test.ts +350 -0
  266. package/src/toolspec.test.ts +2 -2
  267. package/src/toolspec.ts +222 -0
  268. package/src/triton/README.md +34 -0
  269. package/src/tui/README.md +42 -0
  270. package/src/tui/parity.test.ts +120 -31
  271. package/src/tui/parity.ts +58 -7
  272. package/src/wizard.test.ts +7 -7
  273. package/test/llm/conformance-helpers.ts +100 -0
  274. package/test/output/csv.test.ts +164 -0
  275. package/test/output/dispatch.test.ts +1 -2
  276. package/test/output/error.test.ts +277 -0
  277. package/test/output/smoke-capture.ts +2 -2
  278. package/test/output/smoke.test.ts +2 -2
  279. package/test/output/taxonomy-contract.test.ts +148 -0
  280. package/test/setup-env.ts +16 -0
  281. package/test/toolspec/fixture.ts +79 -0
  282. package/tsconfig.json +3 -1
  283. package/tsconfig.test.json +10 -0
  284. package/vitest.config.ts +9 -0
  285. package/src/tui/parity.json +0 -74
@@ -0,0 +1,279 @@
1
+ // URL media fetches are guarded against SSRF: http(s) only, public
2
+ // addresses only (checked on what is dialed), no redirects, a size cap,
3
+ // and the offline policy.
4
+
5
+ import { createServer, type Server } from "node:http";
6
+ import type { AddressInfo } from "node:net";
7
+
8
+ import { afterEach, describe, expect, it } from "vitest";
9
+
10
+ import { urlSource } from "./llm";
11
+ import { HTTPStatusError } from "./llm-errors";
12
+ import {
13
+ DEFAULT_MAX_MEDIA_BYTES,
14
+ MediaTooLargeError,
15
+ MediaURLRefusedError,
16
+ _setMediaFetchSeams,
17
+ isPublicAddress,
18
+ } from "./llm-media";
19
+ import { isOfflineError, withOffline } from "./netpolicy";
20
+
21
+ type Handler = Parameters<typeof createServer>[1];
22
+
23
+ let restore: (() => void)[] = [];
24
+ let servers: Server[] = [];
25
+
26
+ afterEach(async () => {
27
+ for (const r of restore.reverse()) r();
28
+ restore = [];
29
+ await Promise.all(
30
+ servers.map((s) => {
31
+ s.closeAllConnections();
32
+ return new Promise((r) => s.close(r));
33
+ }),
34
+ );
35
+ servers = [];
36
+ });
37
+
38
+ function allowLoopback(): void {
39
+ restore.push(
40
+ _setMediaFetchSeams({
41
+ allow: (a, isPublic) => /^127\./.test(a) || a === "::1" || isPublic(a),
42
+ }),
43
+ );
44
+ }
45
+
46
+ function fakeResolve(answers: Record<string, string[]>, count?: { n: number }): void {
47
+ restore.push(
48
+ _setMediaFetchSeams({
49
+ resolve: async (host) => {
50
+ if (count) count.n++;
51
+ const a = answers[host];
52
+ if (!a) throw new Error(`no such host ${host}`);
53
+ return a;
54
+ },
55
+ }),
56
+ );
57
+ }
58
+
59
+ async function serve(h: NonNullable<Handler>): Promise<{ url: string; port: number; hits: () => number }> {
60
+ let n = 0;
61
+ const srv = createServer((req, res) => {
62
+ n++;
63
+ h(req, res);
64
+ });
65
+ servers.push(srv);
66
+ await new Promise<void>((r) => srv.listen(0, "127.0.0.1", r));
67
+ const port = (srv.address() as AddressInfo).port;
68
+ return { url: `http://127.0.0.1:${port}`, port, hits: () => n };
69
+ }
70
+
71
+ describe("urlSource guard", () => {
72
+ it.each(["file:///etc/passwd", "ftp://example.com/x.png", "data:image/png;base64,AAAA", "gopher://example.com/x"])(
73
+ "refuses scheme %s",
74
+ async (url) => {
75
+ const err = await urlSource(url).read().catch((e) => e);
76
+ expect(err).toBeInstanceOf(MediaURLRefusedError);
77
+ expect(String(err.message)).toContain("only http or https URLs are fetched");
78
+ },
79
+ );
80
+
81
+ it.each([
82
+ "http://127.0.0.1/x.png",
83
+ "http://localhost/x.png",
84
+ "http://[::1]/x.png",
85
+ "http://169.254.169.254/latest/meta-data/",
86
+ "http://10.0.0.1/x.png",
87
+ "http://192.168.1.1/x.png",
88
+ "http://172.16.0.1/x.png",
89
+ "http://0.0.0.0/x.png",
90
+ "http://[::ffff:127.0.0.1]/x.png",
91
+ "http://[::ffff:169.254.169.254]/x.png",
92
+ "http://[fc00::1]/x.png",
93
+ "http://[fd12:3456::1]/x.png",
94
+ "http://[fe80::1]/x.png",
95
+ "http://224.0.0.1/x.png",
96
+ "http://100.64.0.1/x.png",
97
+ "http://[64:ff9b::a9fe:a9fe]/x.png",
98
+ ])("refuses non-public %s", async (url) => {
99
+ const err = await urlSource(url).read().catch((e) => e);
100
+ expect(err).toBeInstanceOf(MediaURLRefusedError);
101
+ expect(String(err.message)).toContain("non-public address");
102
+ });
103
+
104
+ it("names the destination without query", async () => {
105
+ const err = await urlSource("http://169.254.169.254/latest/meta-data/?X-Amz-Signature=sekrit")
106
+ .read()
107
+ .catch((e) => e);
108
+ expect(err.message).toBe(
109
+ "media: refusing to fetch http://169.254.169.254/latest/meta-data/: non-public address 169.254.169.254",
110
+ );
111
+ });
112
+
113
+ it("refuses userinfo without echoing it", async () => {
114
+ const err = await urlSource("https://user:pw@example.com/x.png").read().catch((e) => e);
115
+ expect(err).toBeInstanceOf(MediaURLRefusedError);
116
+ expect(err.message).toContain("userinfo");
117
+ expect(err.message).not.toContain("pw");
118
+ });
119
+
120
+ it("refuses a loopback server by default, before any request", async () => {
121
+ const srv = await serve((_q, s) => s.end("PNG"));
122
+ const err = await urlSource(`${srv.url}/x.png`).read().catch((e) => e);
123
+ expect(err).toBeInstanceOf(MediaURLRefusedError);
124
+ expect(srv.hits()).toBe(0);
125
+ });
126
+
127
+ it.each([
128
+ ["private", ["10.1.2.3"]],
129
+ ["metadata", ["169.254.169.254"]],
130
+ ["loopback v6", ["::1"]],
131
+ ["mapped", ["::ffff:192.168.0.1"]],
132
+ ["one of many", ["93.184.216.34", "127.0.0.1"]],
133
+ ["ula", ["fd00::5"]],
134
+ ["no addresses", []],
135
+ ])("refuses a name resolving to %s", async (_n, addrs) => {
136
+ fakeResolve({ "media.example": addrs as string[] });
137
+ const err = await urlSource("http://media.example/x.png").read().catch((e) => e);
138
+ expect(err).toBeInstanceOf(MediaURLRefusedError);
139
+ expect(err.message).toContain("media: refusing to fetch http://media.example/x.png");
140
+ });
141
+
142
+ it("dials the vetted address: one lookup, no rebinding", async () => {
143
+ allowLoopback();
144
+ let host = "";
145
+ const srv = await serve((q, s) => {
146
+ host = q.headers.host ?? "";
147
+ s.end("PNG");
148
+ });
149
+ const count = { n: 0 };
150
+ fakeResolve({ "media.example": ["127.0.0.1"] }, count);
151
+ const got = await urlSource(`http://media.example:${srv.port}/x.png`).read();
152
+ expect(Buffer.from(got).toString()).toBe("PNG");
153
+ expect(host).toBe(`media.example:${srv.port}`);
154
+ expect(count.n).toBe(1);
155
+ });
156
+
157
+ it("fetches a public host", async () => {
158
+ allowLoopback();
159
+ let path = "";
160
+ const srv = await serve((q, s) => {
161
+ path = q.url ?? "";
162
+ s.setHeader("content-type", "image/png");
163
+ s.end("PNG");
164
+ });
165
+ const got = await urlSource(`${srv.url}/x.png`).read();
166
+ expect(Buffer.from(got).toString()).toBe("PNG");
167
+ expect(path).toBe("/x.png");
168
+ });
169
+
170
+ it("does not follow a redirect", async () => {
171
+ allowLoopback();
172
+ const srv = await serve((_q, s) => {
173
+ s.writeHead(302, { location: "http://169.254.169.254/latest/meta-data/" });
174
+ s.end();
175
+ });
176
+ const err = await urlSource(`${srv.url}/x.png`).read().catch((e) => e);
177
+ expect(err).toBeInstanceOf(HTTPStatusError);
178
+ expect(err.statusCode).toBe(302);
179
+ expect(err.message).toContain("redirect not followed");
180
+ expect(srv.hits()).toBe(1);
181
+ });
182
+
183
+ it("fails on an error status", async () => {
184
+ allowLoopback();
185
+ const srv = await serve((_q, s) => {
186
+ s.writeHead(404);
187
+ s.end("nope");
188
+ });
189
+ const err = await urlSource(`${srv.url}/x.png`).read().catch((e) => e);
190
+ expect(err.message).toContain("http 404");
191
+ });
192
+
193
+ it.each([
194
+ ["declared length", false, 2048],
195
+ ["chunked", true, 1025],
196
+ ])("caps the body (%s)", async (_n, chunked, size) => {
197
+ allowLoopback();
198
+ const body = "x".repeat(2048);
199
+ const srv = await serve((_q, s) => {
200
+ if (!chunked) {
201
+ // Declared over the cap and never finished: only the early
202
+ // check on the declared length can fail it in time.
203
+ s.writeHead(200, { "content-length": String(body.length) });
204
+ s.write(body.slice(0, 16));
205
+ return;
206
+ }
207
+ for (let i = 0; i < 4; i++) s.write(body.slice(0, 512));
208
+ s.end();
209
+ });
210
+ const err = await urlSource(`${srv.url}/x.png`, { maxBytes: 1024 }).read().catch((e) => e);
211
+ expect(err).toBeInstanceOf(MediaTooLargeError);
212
+ expect(err.limit).toBe(1024);
213
+ if (!chunked) expect(err.size).toBe(size);
214
+ else expect(err.size).toBeGreaterThan(1024);
215
+ });
216
+
217
+ it("delivers a body exactly at the cap", async () => {
218
+ allowLoopback();
219
+ const srv = await serve((_q, s) => s.end("x".repeat(1024)));
220
+ const got = await urlSource(`${srv.url}/x.png`, { maxBytes: 1024 }).read();
221
+ expect(got.length).toBe(1024);
222
+ });
223
+
224
+ it("defaults to 32 MiB", () => {
225
+ expect(DEFAULT_MAX_MEDIA_BYTES).toBe(32 * 1024 * 1024);
226
+ });
227
+
228
+ it("honours --offline", async () => {
229
+ fakeResolve({ "media.example": ["93.184.216.34"] });
230
+ const err = await withOffline(true, () => urlSource("https://media.example/x.png").read()).catch((e) => e);
231
+ expect(isOfflineError(err)).toBe(true);
232
+ });
233
+ });
234
+
235
+ describe("isPublicAddress", () => {
236
+ it.each([
237
+ ["93.184.216.34", true],
238
+ ["8.8.8.8", true],
239
+ ["2606:4700::1111", true],
240
+ ["127.0.0.1", false],
241
+ ["10.0.0.1", false],
242
+ ["172.31.255.255", false],
243
+ ["192.168.0.1", false],
244
+ ["169.254.169.254", false],
245
+ ["100.64.0.1", false],
246
+ ["0.0.0.0", false],
247
+ ["0.1.2.3", false],
248
+ ["192.0.2.1", false],
249
+ ["198.18.0.1", false],
250
+ ["198.51.100.1", false],
251
+ ["203.0.113.1", false],
252
+ ["224.0.0.1", false],
253
+ ["240.0.0.1", false],
254
+ ["255.255.255.255", false],
255
+ ["::", false],
256
+ ["::1", false],
257
+ ["::ffff:127.0.0.1", false],
258
+ ["::ffff:10.0.0.1", false],
259
+ ["::ffff:100.64.0.1", false],
260
+ ["::ffff:192.0.2.1", false],
261
+ ["::ffff:93.184.216.34", true],
262
+ ["::127.0.0.1", false],
263
+ ["fc00::1", false],
264
+ ["fdff::1", false],
265
+ ["fe80::1", false],
266
+ ["fec0::1", false],
267
+ ["ff02::1", false],
268
+ ["2001:db8::1", false],
269
+ ["2002:7f00:1::1", false],
270
+ ["64:ff9b::7f00:1", false],
271
+ ["64:ff9b::5db8:d822", true],
272
+ ["64:ff9b:1::1", false],
273
+ ["100::1", false],
274
+ ["fe80::1%en0", false],
275
+ ["not-an-address", false],
276
+ ])("%s -> %s", (addr, want) => {
277
+ expect(isPublicAddress(addr)).toBe(want);
278
+ });
279
+ });
@@ -0,0 +1,322 @@
1
+ /**
2
+ * The guarded fetch behind `urlSource(url).read()`.
3
+ *
4
+ * A media URL may come from untrusted input, so the fetch refuses what
5
+ * would make it a server-side request forgery or a local file read:
6
+ *
7
+ * - `http` and `https` only (no `file:`, `ftp:`, `data:`), no userinfo;
8
+ * - every address the host resolves to must be public: loopback,
9
+ * private, link-local (cloud metadata `169.254.169.254` among them),
10
+ * shared, documentation, reserved, unspecified and multicast
11
+ * addresses are refused, v4-mapped and NAT64 IPv6 judged by their
12
+ * IPv4;
13
+ * - the socket connects to an address the check passed (the lookup
14
+ * handed to `node:http` is the vetted one), so a second DNS answer
15
+ * cannot rebind it; TLS still verifies the host name;
16
+ * - no proxy, no redirects (a 3xx is an `HTTPStatusError`); a non-2xx
17
+ * status is an error;
18
+ * - the body is capped ({@link DEFAULT_MAX_MEDIA_BYTES}, or `maxBytes`),
19
+ * 30s for the whole download;
20
+ * - the `--offline` policy (`netpolicy`) applies.
21
+ *
22
+ * Errors name the destination without query or userinfo. There is no
23
+ * switch to allow private hosts: media on a local or private host is
24
+ * read by the caller and passed as `inlineSource` or `fileSource`.
25
+ *
26
+ * @internal
27
+ */
28
+
29
+ import * as dns from "node:dns";
30
+ import * as http from "node:http";
31
+ import * as https from "node:https";
32
+ import { isIP, type LookupFunction } from "node:net";
33
+
34
+ import { LLMError } from "./llm-error";
35
+ import { HTTPStatusError } from "./llm-errors";
36
+ import { OfflineError, isLoopback, isOffline } from "./netpolicy";
37
+
38
+ /** A URL media download is capped at this many bytes unless told otherwise: 32 MiB. */
39
+ export const DEFAULT_MAX_MEDIA_BYTES = 32 << 20;
40
+
41
+ const TIMEOUT_MS = 30_000;
42
+
43
+ /**
44
+ * A URL media source refused to fetch its URL: a scheme other than
45
+ * http(s), userinfo, no host, or an address that is not public.
46
+ * `destination` is the URL without query or userinfo.
47
+ */
48
+ export class MediaURLRefusedError extends LLMError {
49
+ readonly destination: string;
50
+ readonly reason: string;
51
+
52
+ constructor(destination: string, reason: string) {
53
+ super(`media: refusing to fetch ${destination}: ${reason}`);
54
+ this.name = "MediaURLRefusedError";
55
+ this.destination = destination;
56
+ this.reason = reason;
57
+ }
58
+ }
59
+
60
+ /** Media over its size limit. */
61
+ export class MediaTooLargeError extends LLMError {
62
+ readonly size: number;
63
+ readonly limit: number;
64
+ readonly provider: string;
65
+
66
+ constructor(size: number, limit: number, provider: string) {
67
+ super(`media too large (${size} bytes, limit ${limit}) for provider ${JSON.stringify(provider)}`);
68
+ this.name = "MediaTooLargeError";
69
+ this.size = size;
70
+ this.limit = limit;
71
+ this.provider = provider;
72
+ }
73
+ }
74
+
75
+ // ---------------------------------------------------------------------------
76
+ // Addresses
77
+ // ---------------------------------------------------------------------------
78
+
79
+ type Prefix = { bytes: number[]; bits: number };
80
+
81
+ function prefix(cidr: string): Prefix {
82
+ const [addr, bits] = cidr.split("/");
83
+ const bytes = addressBytes(addr);
84
+ if (!bytes) throw new Error(`bad prefix ${cidr}`);
85
+ return { bytes, bits: Number(bits) };
86
+ }
87
+
88
+ /** Special-purpose ranges (IANA registries) that are not public. */
89
+ const NON_PUBLIC_V4 = [
90
+ "0.0.0.0/8",
91
+ "10.0.0.0/8",
92
+ "100.64.0.0/10",
93
+ "127.0.0.0/8",
94
+ "169.254.0.0/16",
95
+ "172.16.0.0/12",
96
+ "192.0.0.0/24",
97
+ "192.0.2.0/24",
98
+ "192.168.0.0/16",
99
+ "198.18.0.0/15",
100
+ "198.51.100.0/24",
101
+ "203.0.113.0/24",
102
+ "224.0.0.0/4",
103
+ "240.0.0.0/4",
104
+ ].map(prefix);
105
+
106
+ const NON_PUBLIC_V6 = [
107
+ "::/96",
108
+ "64:ff9b:1::/48",
109
+ "100::/64",
110
+ "2001::/23",
111
+ "2001:db8::/32",
112
+ "2002::/16",
113
+ "3fff::/20",
114
+ "5f00::/16",
115
+ "fc00::/7",
116
+ "fe80::/10",
117
+ "fec0::/10",
118
+ "ff00::/8",
119
+ ].map(prefix);
120
+
121
+ const MAPPED = prefix("::ffff:0:0/96");
122
+ const NAT64 = prefix("64:ff9b::/96");
123
+
124
+ function contains(p: Prefix, b: number[]): boolean {
125
+ if (p.bytes.length !== b.length) return false;
126
+ let bits = p.bits;
127
+ for (let i = 0; bits > 0; i++, bits -= 8) {
128
+ const mask = bits >= 8 ? 0xff : (0xff << (8 - bits)) & 0xff;
129
+ if ((p.bytes[i] & mask) !== (b[i] & mask)) return false;
130
+ }
131
+ return true;
132
+ }
133
+
134
+ /** The bytes of an IPv4 or IPv6 literal (zone dropped), or undefined. */
135
+ function addressBytes(addr: string): number[] | undefined {
136
+ const a = addr.replace(/%.*$/, "");
137
+ const kind = isIP(a);
138
+ if (kind === 4) return a.split(".").map(Number);
139
+ if (kind !== 6) return undefined;
140
+ // Let WHATWG URL canonicalise: an embedded dotted quad becomes two
141
+ // hex groups, so only "::" compression is left to expand.
142
+ const canon = new URL(`http://[${a}]/`).hostname.slice(1, -1);
143
+ const [head, tail] = canon.includes("::") ? canon.split("::") : [canon, undefined];
144
+ const h = head ? head.split(":") : [];
145
+ const t = tail ? tail.split(":") : [];
146
+ const groups = tail === undefined ? h : [...h, ...Array(8 - h.length - t.length).fill("0"), ...t];
147
+ return groups.flatMap((g) => {
148
+ const n = parseInt(g, 16);
149
+ return [n >> 8, n & 0xff];
150
+ });
151
+ }
152
+
153
+ /**
154
+ * Whether addr (an IPv4 or IPv6 literal) is a globally routable unicast
155
+ * address. A v4-mapped or NAT64 (64:ff9b::/96) address is judged by the
156
+ * IPv4 address it carries. Mirrors Go's guard.
157
+ */
158
+ export function isPublicAddress(addr: string): boolean {
159
+ let b = addressBytes(addr);
160
+ if (!b) return false;
161
+ if (b.length === 16 && (contains(MAPPED, b) || contains(NAT64, b))) b = b.slice(12);
162
+ if (b.length === 4) {
163
+ if (b.every((x) => x === 255)) return false;
164
+ return !NON_PUBLIC_V4.some((p) => contains(p, b));
165
+ }
166
+ return !NON_PUBLIC_V6.some((p) => contains(p, b));
167
+ }
168
+
169
+ // ---------------------------------------------------------------------------
170
+ // Test seams
171
+ // ---------------------------------------------------------------------------
172
+
173
+ type Resolver = (host: string) => Promise<string[]>;
174
+
175
+ const systemResolver: Resolver = async (host) =>
176
+ (await dns.promises.lookup(host, { all: true, verbatim: true })).map((a) => a.address);
177
+
178
+ let addressAllowed: (addr: string) => boolean = isPublicAddress;
179
+ let resolve: Resolver = systemResolver;
180
+
181
+ /**
182
+ * Test hook: replace the address check and the resolver until the
183
+ * returned restore function runs. Not part of the public API.
184
+ *
185
+ * @internal
186
+ */
187
+ export function _setMediaFetchSeams(seams: {
188
+ allow?: (addr: string, isPublic: (a: string) => boolean) => boolean;
189
+ resolve?: Resolver;
190
+ }): () => void {
191
+ const prev = { addressAllowed, resolve };
192
+ if (seams.allow) {
193
+ const allow = seams.allow;
194
+ addressAllowed = (a) => allow(a, isPublicAddress);
195
+ }
196
+ if (seams.resolve) resolve = seams.resolve;
197
+ return () => {
198
+ addressAllowed = prev.addressAllowed;
199
+ resolve = prev.resolve;
200
+ };
201
+ }
202
+
203
+ // ---------------------------------------------------------------------------
204
+ // Fetch
205
+ // ---------------------------------------------------------------------------
206
+
207
+ /**
208
+ * Render url as scheme, host and path only (mirrors Go's guard): query,
209
+ * fragment and userinfo may carry credentials. An opaque URL keeps its
210
+ * scheme alone; one that does not parse is not echoed.
211
+ */
212
+ export function mediaDestination(url: string): string {
213
+ let u: URL;
214
+ try {
215
+ u = new URL(url);
216
+ } catch {
217
+ return "<unparseable URL>";
218
+ }
219
+ if (u.host === "" && !u.pathname.startsWith("/")) return u.protocol;
220
+ return `${u.protocol}//${u.host}${u.pathname}`;
221
+ }
222
+
223
+ /** Resolve host once and refuse it unless every address is allowed. */
224
+ async function vettedAddresses(dest: string, host: string): Promise<{ address: string; family: number }[]> {
225
+ const literal = isIP(host.replace(/%.*$/, ""));
226
+ const addrs = literal ? [host] : await resolve(host);
227
+ if (addrs.length === 0) throw new MediaURLRefusedError(dest, "host resolves to no address");
228
+ for (const a of addrs) {
229
+ if (!addressAllowed(a)) throw new MediaURLRefusedError(dest, `non-public address ${a}`);
230
+ }
231
+ return addrs.map((a) => ({ address: a, family: isIP(a.replace(/%.*$/, "")) }));
232
+ }
233
+
234
+ /**
235
+ * GET url under the rules in the module docs and return its body.
236
+ * `maxBytes` caps the body (default {@link DEFAULT_MAX_MEDIA_BYTES}).
237
+ */
238
+ export async function fetchMedia(url: string, maxBytes: number = DEFAULT_MAX_MEDIA_BYTES): Promise<Uint8Array> {
239
+ const dest = mediaDestination(url);
240
+ let u: URL;
241
+ try {
242
+ u = new URL(url);
243
+ } catch {
244
+ throw new MediaURLRefusedError(dest, "URL does not parse");
245
+ }
246
+ if (u.protocol !== "http:" && u.protocol !== "https:") {
247
+ throw new MediaURLRefusedError(dest, "only http or https URLs are fetched");
248
+ }
249
+ if (u.username !== "" || u.password !== "") throw new MediaURLRefusedError(dest, "URL carries userinfo");
250
+ // URL keeps IPv6 brackets in hostname.
251
+ const host = u.hostname.replace(/^\[(.*)\]$/, "$1");
252
+ if (host === "") throw new MediaURLRefusedError(dest, "URL has no host");
253
+ if (isOffline() && !isLoopback(host)) throw new OfflineError("GET", url);
254
+ const addrs = await vettedAddresses(dest, host);
255
+
256
+ // node:http calls lookup for the host; answer with the vetted
257
+ // addresses, never a fresh resolution. A literal host skips lookup.
258
+ const lookup: LookupFunction = (_hostname, options, cb) => {
259
+ const fam = typeof options === "object" ? options.family : undefined;
260
+ const pick = addrs.filter((a) => !fam || a.family === fam);
261
+ if (pick.length === 0) {
262
+ cb(Object.assign(new Error(`no ${fam === 6 ? "IPv6" : "IPv4"} address`), { code: "ENOTFOUND" }), "", 0);
263
+ return;
264
+ }
265
+ if (typeof options === "object" && options.all) {
266
+ (cb as unknown as (e: null, a: { address: string; family: number }[]) => void)(null, pick);
267
+ } else {
268
+ cb(null, pick[0].address, pick[0].family);
269
+ }
270
+ };
271
+
272
+ const mod = u.protocol === "https:" ? https : http;
273
+ return await new Promise<Uint8Array>((resolveBody, reject) => {
274
+ const req = mod.request(
275
+ u,
276
+ {
277
+ method: "GET",
278
+ headers: { accept: "*/*" },
279
+ lookup,
280
+ agent: false,
281
+ timeout: TIMEOUT_MS,
282
+ },
283
+ (res) => {
284
+ const status = res.statusCode ?? 0;
285
+ const fail = (err: Error) => {
286
+ res.destroy();
287
+ reject(err);
288
+ };
289
+ if (status >= 300 && status < 400) {
290
+ fail(new HTTPStatusError(status, `media: redirect not followed (${dest})`));
291
+ return;
292
+ }
293
+ if (status < 200 || status >= 300) {
294
+ fail(new LLMError(`media: fetch ${dest}: http ${status}`));
295
+ return;
296
+ }
297
+ const declared = Number(res.headers["content-length"]);
298
+ if (Number.isFinite(declared) && declared > maxBytes) {
299
+ fail(new MediaTooLargeError(declared, maxBytes, "media"));
300
+ return;
301
+ }
302
+ const chunks: Buffer[] = [];
303
+ let n = 0;
304
+ res.on("data", (c: Buffer) => {
305
+ n += c.length;
306
+ if (n > maxBytes) {
307
+ fail(new MediaTooLargeError(n, maxBytes, "media"));
308
+ return;
309
+ }
310
+ chunks.push(c);
311
+ });
312
+ res.on("end", () => resolveBody(new Uint8Array(Buffer.concat(chunks))));
313
+ res.on("error", (e) => reject(new LLMError(`media: fetch ${dest}: ${e.message}`)));
314
+ },
315
+ );
316
+ const deadline = setTimeout(() => req.destroy(new Error("timeout")), TIMEOUT_MS);
317
+ req.on("close", () => clearTimeout(deadline));
318
+ req.on("timeout", () => req.destroy(new Error("timeout")));
319
+ req.on("error", (e) => reject(e instanceof LLMError ? e : new LLMError(`media: fetch ${dest}: ${e.message}`)));
320
+ req.end();
321
+ });
322
+ }