milieu-cli 0.3.2 → 0.4.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 (330) hide show
  1. package/README.md +177 -76
  2. package/dist/bridges/context/agents-json.d.ts +0 -1
  3. package/dist/bridges/context/agents-json.js +21 -12
  4. package/dist/bridges/context/auth-clarity.d.ts +0 -1
  5. package/dist/bridges/context/auth-clarity.js +11 -9
  6. package/dist/bridges/context/auth-legibility.d.ts +2 -2
  7. package/dist/bridges/context/auth-legibility.js +67 -60
  8. package/dist/bridges/context/index.d.ts +1 -2
  9. package/dist/bridges/context/index.js +19 -40
  10. package/dist/bridges/context/oauth-metadata.d.ts +14 -0
  11. package/dist/bridges/context/oauth-metadata.js +127 -0
  12. package/dist/bridges/context/probe.d.ts +33 -0
  13. package/dist/bridges/context/probe.js +157 -0
  14. package/dist/bridges/context/rate-limits.d.ts +5 -2
  15. package/dist/bridges/context/rate-limits.js +27 -51
  16. package/dist/bridges/context/tos-contact.d.ts +13 -4
  17. package/dist/bridges/context/tos-contact.js +108 -46
  18. package/dist/bridges/context/versioning.d.ts +1 -2
  19. package/dist/bridges/context/versioning.js +42 -7
  20. package/dist/bridges/index.d.ts +0 -1
  21. package/dist/bridges/index.js +0 -1
  22. package/dist/bridges/reachability/crawler-policy.d.ts +30 -10
  23. package/dist/bridges/reachability/crawler-policy.js +41 -56
  24. package/dist/bridges/reachability/http-status.d.ts +3 -2
  25. package/dist/bridges/reachability/http-status.js +18 -3
  26. package/dist/bridges/reachability/https-check.d.ts +2 -2
  27. package/dist/bridges/reachability/https-check.js +6 -3
  28. package/dist/bridges/reachability/index.d.ts +1 -2
  29. package/dist/bridges/reachability/index.js +34 -43
  30. package/dist/bridges/reachability/meta-robots.d.ts +0 -13
  31. package/dist/bridges/reachability/meta-robots.js +89 -101
  32. package/dist/bridges/reachability/robots-parser.d.ts +7 -7
  33. package/dist/bridges/reachability/robots-parser.js +65 -15
  34. package/dist/bridges/reachability/robots-txt.d.ts +4 -2
  35. package/dist/bridges/reachability/robots-txt.js +33 -60
  36. package/dist/bridges/schema/descriptions.d.ts +2 -2
  37. package/dist/bridges/schema/descriptions.js +79 -44
  38. package/dist/bridges/schema/error-schemas.d.ts +2 -2
  39. package/dist/bridges/schema/error-schemas.js +31 -18
  40. package/dist/bridges/schema/index.d.ts +2 -2
  41. package/dist/bridges/schema/index.js +48 -30
  42. package/dist/bridges/schema/oas-types.d.ts +65 -26
  43. package/dist/bridges/schema/oas-types.js +37 -7
  44. package/dist/bridges/schema/operation-ids.d.ts +2 -2
  45. package/dist/bridges/schema/operation-ids.js +2 -3
  46. package/dist/bridges/schema/required-fields.d.ts +2 -2
  47. package/dist/bridges/schema/required-fields.js +12 -10
  48. package/dist/bridges/schema/schema-sources.d.ts +19 -0
  49. package/dist/bridges/schema/schema-sources.js +182 -0
  50. package/dist/bridges/schema/schema-types.d.ts +2 -2
  51. package/dist/bridges/schema/schema-types.js +20 -21
  52. package/dist/bridges/separation/api-presence.d.ts +3 -15
  53. package/dist/bridges/separation/api-presence.js +34 -85
  54. package/dist/bridges/separation/developer-docs.d.ts +6 -18
  55. package/dist/bridges/separation/developer-docs.js +100 -99
  56. package/dist/bridges/separation/docs-discovery.d.ts +28 -0
  57. package/dist/bridges/separation/docs-discovery.js +95 -0
  58. package/dist/bridges/separation/evidence-summary.d.ts +2 -0
  59. package/dist/bridges/separation/evidence-summary.js +67 -0
  60. package/dist/bridges/separation/index.d.ts +2 -19
  61. package/dist/bridges/separation/index.js +35 -39
  62. package/dist/bridges/separation/published-routes.d.ts +69 -0
  63. package/dist/bridges/separation/published-routes.js +271 -0
  64. package/dist/bridges/separation/sdk-references.d.ts +8 -3
  65. package/dist/bridges/separation/sdk-references.js +86 -61
  66. package/dist/bridges/separation/webhook-support.d.ts +3 -23
  67. package/dist/bridges/separation/webhook-support.js +61 -162
  68. package/dist/bridges/standards/a2a-agent-card.d.ts +0 -1
  69. package/dist/bridges/standards/a2a-agent-card.js +24 -9
  70. package/dist/bridges/standards/graphql.d.ts +3 -4
  71. package/dist/bridges/standards/graphql.js +70 -66
  72. package/dist/bridges/standards/index.d.ts +1 -2
  73. package/dist/bridges/standards/index.js +57 -47
  74. package/dist/bridges/standards/json-ld.d.ts +25 -11
  75. package/dist/bridges/standards/json-ld.js +114 -56
  76. package/dist/bridges/standards/llms-txt.d.ts +4 -2
  77. package/dist/bridges/standards/llms-txt.js +46 -32
  78. package/dist/bridges/standards/markdown-negotiation.d.ts +4 -1
  79. package/dist/bridges/standards/markdown-negotiation.js +16 -11
  80. package/dist/bridges/standards/mcp.d.ts +3 -12
  81. package/dist/bridges/standards/mcp.js +89 -132
  82. package/dist/bridges/standards/openapi.d.ts +7 -15
  83. package/dist/bridges/standards/openapi.js +657 -207
  84. package/dist/bridges/standards/probe-evidence.d.ts +30 -0
  85. package/dist/bridges/standards/probe-evidence.js +90 -0
  86. package/dist/bridges/standards/schema-org.d.ts +15 -9
  87. package/dist/bridges/standards/schema-org.js +38 -64
  88. package/dist/bridges/standards/sitemap.d.ts +2 -3
  89. package/dist/bridges/standards/sitemap.js +161 -169
  90. package/dist/bridges/standards/well-known.d.ts +3 -7
  91. package/dist/bridges/standards/well-known.js +28 -12
  92. package/dist/cli/index.d.ts +1 -1
  93. package/dist/cli/index.js +107 -22
  94. package/dist/cli/journey-commands.d.ts +3 -0
  95. package/dist/cli/journey-commands.js +35 -0
  96. package/dist/cli/read-report.d.ts +2 -0
  97. package/dist/cli/read-report.js +11 -0
  98. package/dist/core/bridge-output.d.ts +11 -0
  99. package/dist/core/bridge-output.js +86 -0
  100. package/dist/core/bridge-session.d.ts +28 -0
  101. package/dist/core/bridge-session.js +58 -0
  102. package/dist/core/bridge-worker.d.ts +1 -0
  103. package/dist/core/bridge-worker.js +66 -0
  104. package/dist/core/diff.d.ts +79 -0
  105. package/dist/core/diff.js +499 -0
  106. package/dist/core/explanations.d.ts +1 -3
  107. package/dist/core/explanations.js +36 -59
  108. package/dist/core/index.d.ts +4 -2
  109. package/dist/core/index.js +2 -3
  110. package/dist/core/scan-options.d.ts +0 -1
  111. package/dist/core/scan-options.js +14 -6
  112. package/dist/core/scan.d.ts +0 -1
  113. package/dist/core/scan.js +91 -41
  114. package/dist/core/scoring.d.ts +6 -0
  115. package/dist/core/scoring.js +27 -0
  116. package/dist/core/types.d.ts +97 -61
  117. package/dist/core/types.js +9 -3
  118. package/dist/core/validate-report.d.ts +5 -0
  119. package/dist/core/validate-report.js +95 -0
  120. package/dist/core/version.d.ts +0 -1
  121. package/dist/core/version.js +0 -1
  122. package/dist/index.d.ts +0 -1
  123. package/dist/index.js +0 -1
  124. package/dist/journey/body-worker.d.ts +27 -0
  125. package/dist/journey/body-worker.js +140 -0
  126. package/dist/journey/case.d.ts +74 -0
  127. package/dist/journey/case.js +187 -0
  128. package/dist/journey/cli.d.ts +14 -0
  129. package/dist/journey/cli.js +226 -0
  130. package/dist/journey/compare.d.ts +43 -0
  131. package/dist/journey/compare.js +83 -0
  132. package/dist/journey/contracts.d.ts +143 -0
  133. package/dist/journey/contracts.js +37 -0
  134. package/dist/journey/decision.d.ts +72 -0
  135. package/dist/journey/decision.js +121 -0
  136. package/dist/journey/demo.d.ts +36 -0
  137. package/dist/journey/demo.js +137 -0
  138. package/dist/journey/document.d.ts +8 -0
  139. package/dist/journey/document.js +113 -0
  140. package/dist/journey/excerpt.d.ts +6 -0
  141. package/dist/journey/excerpt.js +54 -0
  142. package/dist/journey/name-guidance.d.ts +2 -0
  143. package/dist/journey/name-guidance.js +41 -0
  144. package/dist/journey/providers.d.ts +34 -0
  145. package/dist/journey/providers.js +197 -0
  146. package/dist/journey/report-validation.d.ts +3 -0
  147. package/dist/journey/report-validation.js +457 -0
  148. package/dist/journey/runner.d.ts +12 -0
  149. package/dist/journey/runner.js +321 -0
  150. package/dist/journey/scope.d.ts +8 -0
  151. package/dist/journey/scope.js +50 -0
  152. package/dist/journey/transport.d.ts +3 -0
  153. package/dist/journey/transport.js +45 -0
  154. package/dist/journey/verify.d.ts +21 -0
  155. package/dist/journey/verify.js +213 -0
  156. package/dist/render/colors.d.ts +6 -7
  157. package/dist/render/colors.js +16 -25
  158. package/dist/render/discovery-guidance.d.ts +3 -0
  159. package/dist/render/discovery-guidance.js +66 -0
  160. package/dist/render/format-bridge.d.ts +1 -2
  161. package/dist/render/format-bridge.js +22 -17
  162. package/dist/render/format-diff.d.ts +2 -0
  163. package/dist/render/format-diff.js +169 -0
  164. package/dist/render/format-scan.d.ts +0 -1
  165. package/dist/render/format-scan.js +6 -4
  166. package/dist/render/format-verbose.d.ts +0 -1
  167. package/dist/render/format-verbose.js +7 -4
  168. package/dist/render/index.d.ts +0 -1
  169. package/dist/render/index.js +1 -2
  170. package/dist/render/oauth-observations.d.ts +4 -0
  171. package/dist/render/oauth-observations.js +27 -0
  172. package/dist/render/progress-bar.d.ts +1 -2
  173. package/dist/render/progress-bar.js +8 -6
  174. package/dist/render/robots-inventory.d.ts +3 -0
  175. package/dist/render/robots-inventory.js +38 -0
  176. package/dist/render/symbols.d.ts +4 -10
  177. package/dist/render/symbols.js +15 -17
  178. package/dist/render/terminal-text.d.ts +1 -3
  179. package/dist/render/terminal-text.js +1 -5
  180. package/dist/utils/analysis-worker-entry.d.ts +3 -0
  181. package/dist/utils/analysis-worker-entry.js +12 -0
  182. package/dist/utils/analysis-worker.d.ts +12 -0
  183. package/dist/utils/analysis-worker.js +54 -0
  184. package/dist/utils/html.d.ts +39 -0
  185. package/dist/utils/html.js +261 -0
  186. package/dist/utils/http-client.d.ts +24 -17
  187. package/dist/utils/http-client.js +166 -200
  188. package/dist/utils/http-types.d.ts +43 -0
  189. package/dist/utils/http-types.js +11 -0
  190. package/dist/utils/index.d.ts +0 -1
  191. package/dist/utils/index.js +0 -1
  192. package/dist/utils/package-registry.d.ts +11 -0
  193. package/dist/utils/package-registry.js +69 -0
  194. package/dist/utils/read-json-file.d.ts +3 -0
  195. package/dist/utils/read-json-file.js +41 -0
  196. package/dist/utils/record.d.ts +1 -0
  197. package/dist/utils/record.js +3 -0
  198. package/dist/utils/response-body.d.ts +7 -0
  199. package/dist/utils/response-body.js +71 -0
  200. package/dist/utils/ssrf.d.ts +11 -15
  201. package/dist/utils/ssrf.js +80 -44
  202. package/dist/utils/terminal-text.d.ts +2 -0
  203. package/dist/utils/terminal-text.js +4 -0
  204. package/dist/utils/url.d.ts +29 -1
  205. package/dist/utils/url.js +147 -17
  206. package/docs/examples/onboarding/account-claim.json +25 -0
  207. package/docs/examples/onboarding/pages/account-claim.html +3 -0
  208. package/docs/examples/onboarding/pages/production-activation.html +3 -0
  209. package/docs/examples/onboarding/pages/test-credential.html +3 -0
  210. package/docs/examples/onboarding/production-activation.json +25 -0
  211. package/docs/examples/onboarding/test-credential.json +25 -0
  212. package/docs/journey-qualification.md +46 -0
  213. package/docs/journeys.md +83 -0
  214. package/package.json +28 -8
  215. package/dist/bridges/context/agents-json.d.ts.map +0 -1
  216. package/dist/bridges/context/agents-json.js.map +0 -1
  217. package/dist/bridges/context/auth-clarity.d.ts.map +0 -1
  218. package/dist/bridges/context/auth-clarity.js.map +0 -1
  219. package/dist/bridges/context/auth-legibility.d.ts.map +0 -1
  220. package/dist/bridges/context/auth-legibility.js.map +0 -1
  221. package/dist/bridges/context/index.d.ts.map +0 -1
  222. package/dist/bridges/context/index.js.map +0 -1
  223. package/dist/bridges/context/rate-limits.d.ts.map +0 -1
  224. package/dist/bridges/context/rate-limits.js.map +0 -1
  225. package/dist/bridges/context/tos-contact.d.ts.map +0 -1
  226. package/dist/bridges/context/tos-contact.js.map +0 -1
  227. package/dist/bridges/context/versioning.d.ts.map +0 -1
  228. package/dist/bridges/context/versioning.js.map +0 -1
  229. package/dist/bridges/index.d.ts.map +0 -1
  230. package/dist/bridges/index.js.map +0 -1
  231. package/dist/bridges/reachability/crawler-policy.d.ts.map +0 -1
  232. package/dist/bridges/reachability/crawler-policy.js.map +0 -1
  233. package/dist/bridges/reachability/http-status.d.ts.map +0 -1
  234. package/dist/bridges/reachability/http-status.js.map +0 -1
  235. package/dist/bridges/reachability/https-check.d.ts.map +0 -1
  236. package/dist/bridges/reachability/https-check.js.map +0 -1
  237. package/dist/bridges/reachability/index.d.ts.map +0 -1
  238. package/dist/bridges/reachability/index.js.map +0 -1
  239. package/dist/bridges/reachability/meta-robots.d.ts.map +0 -1
  240. package/dist/bridges/reachability/meta-robots.js.map +0 -1
  241. package/dist/bridges/reachability/robots-parser.d.ts.map +0 -1
  242. package/dist/bridges/reachability/robots-parser.js.map +0 -1
  243. package/dist/bridges/reachability/robots-txt.d.ts.map +0 -1
  244. package/dist/bridges/reachability/robots-txt.js.map +0 -1
  245. package/dist/bridges/schema/descriptions.d.ts.map +0 -1
  246. package/dist/bridges/schema/descriptions.js.map +0 -1
  247. package/dist/bridges/schema/error-schemas.d.ts.map +0 -1
  248. package/dist/bridges/schema/error-schemas.js.map +0 -1
  249. package/dist/bridges/schema/index.d.ts.map +0 -1
  250. package/dist/bridges/schema/index.js.map +0 -1
  251. package/dist/bridges/schema/oas-types.d.ts.map +0 -1
  252. package/dist/bridges/schema/oas-types.js.map +0 -1
  253. package/dist/bridges/schema/operation-ids.d.ts.map +0 -1
  254. package/dist/bridges/schema/operation-ids.js.map +0 -1
  255. package/dist/bridges/schema/required-fields.d.ts.map +0 -1
  256. package/dist/bridges/schema/required-fields.js.map +0 -1
  257. package/dist/bridges/schema/schema-types.d.ts.map +0 -1
  258. package/dist/bridges/schema/schema-types.js.map +0 -1
  259. package/dist/bridges/separation/api-presence.d.ts.map +0 -1
  260. package/dist/bridges/separation/api-presence.js.map +0 -1
  261. package/dist/bridges/separation/developer-docs.d.ts.map +0 -1
  262. package/dist/bridges/separation/developer-docs.js.map +0 -1
  263. package/dist/bridges/separation/index.d.ts.map +0 -1
  264. package/dist/bridges/separation/index.js.map +0 -1
  265. package/dist/bridges/separation/sdk-references.d.ts.map +0 -1
  266. package/dist/bridges/separation/sdk-references.js.map +0 -1
  267. package/dist/bridges/separation/webhook-support.d.ts.map +0 -1
  268. package/dist/bridges/separation/webhook-support.js.map +0 -1
  269. package/dist/bridges/standards/a2a-agent-card.d.ts.map +0 -1
  270. package/dist/bridges/standards/a2a-agent-card.js.map +0 -1
  271. package/dist/bridges/standards/graphql.d.ts.map +0 -1
  272. package/dist/bridges/standards/graphql.js.map +0 -1
  273. package/dist/bridges/standards/index.d.ts.map +0 -1
  274. package/dist/bridges/standards/index.js.map +0 -1
  275. package/dist/bridges/standards/json-ld.d.ts.map +0 -1
  276. package/dist/bridges/standards/json-ld.js.map +0 -1
  277. package/dist/bridges/standards/llms-txt.d.ts.map +0 -1
  278. package/dist/bridges/standards/llms-txt.js.map +0 -1
  279. package/dist/bridges/standards/markdown-negotiation.d.ts.map +0 -1
  280. package/dist/bridges/standards/markdown-negotiation.js.map +0 -1
  281. package/dist/bridges/standards/mcp.d.ts.map +0 -1
  282. package/dist/bridges/standards/mcp.js.map +0 -1
  283. package/dist/bridges/standards/openapi.d.ts.map +0 -1
  284. package/dist/bridges/standards/openapi.js.map +0 -1
  285. package/dist/bridges/standards/schema-org.d.ts.map +0 -1
  286. package/dist/bridges/standards/schema-org.js.map +0 -1
  287. package/dist/bridges/standards/sitemap.d.ts.map +0 -1
  288. package/dist/bridges/standards/sitemap.js.map +0 -1
  289. package/dist/bridges/standards/well-known.d.ts.map +0 -1
  290. package/dist/bridges/standards/well-known.js.map +0 -1
  291. package/dist/cli/index.d.ts.map +0 -1
  292. package/dist/cli/index.js.map +0 -1
  293. package/dist/core/explanations.d.ts.map +0 -1
  294. package/dist/core/explanations.js.map +0 -1
  295. package/dist/core/index.d.ts.map +0 -1
  296. package/dist/core/index.js.map +0 -1
  297. package/dist/core/scan-options.d.ts.map +0 -1
  298. package/dist/core/scan-options.js.map +0 -1
  299. package/dist/core/scan.d.ts.map +0 -1
  300. package/dist/core/scan.js.map +0 -1
  301. package/dist/core/types.d.ts.map +0 -1
  302. package/dist/core/types.js.map +0 -1
  303. package/dist/core/version.d.ts.map +0 -1
  304. package/dist/core/version.js.map +0 -1
  305. package/dist/index.d.ts.map +0 -1
  306. package/dist/index.js.map +0 -1
  307. package/dist/render/colors.d.ts.map +0 -1
  308. package/dist/render/colors.js.map +0 -1
  309. package/dist/render/format-bridge.d.ts.map +0 -1
  310. package/dist/render/format-bridge.js.map +0 -1
  311. package/dist/render/format-scan.d.ts.map +0 -1
  312. package/dist/render/format-scan.js.map +0 -1
  313. package/dist/render/format-verbose.d.ts.map +0 -1
  314. package/dist/render/format-verbose.js.map +0 -1
  315. package/dist/render/index.d.ts.map +0 -1
  316. package/dist/render/index.js.map +0 -1
  317. package/dist/render/progress-bar.d.ts.map +0 -1
  318. package/dist/render/progress-bar.js.map +0 -1
  319. package/dist/render/symbols.d.ts.map +0 -1
  320. package/dist/render/symbols.js.map +0 -1
  321. package/dist/render/terminal-text.d.ts.map +0 -1
  322. package/dist/render/terminal-text.js.map +0 -1
  323. package/dist/utils/http-client.d.ts.map +0 -1
  324. package/dist/utils/http-client.js.map +0 -1
  325. package/dist/utils/index.d.ts.map +0 -1
  326. package/dist/utils/index.js.map +0 -1
  327. package/dist/utils/ssrf.d.ts.map +0 -1
  328. package/dist/utils/ssrf.js.map +0 -1
  329. package/dist/utils/url.d.ts.map +0 -1
  330. package/dist/utils/url.js.map +0 -1
@@ -0,0 +1,69 @@
1
+ /** Package registry patterns for SDK/package reference detection */
2
+ export const REGISTRY_PATTERNS = [
3
+ {
4
+ name: "npm",
5
+ urlPattern: /npmjs\.com\/package\//i,
6
+ installPattern: /\bnpm\s+install\s+\S/i,
7
+ },
8
+ {
9
+ name: "npm (CDN)",
10
+ urlPattern: /cdn\.jsdelivr\.net\/npm\/|unpkg\.com\//i,
11
+ },
12
+ {
13
+ name: "PyPI",
14
+ urlPattern: /pypi\.org\/project\//i,
15
+ installPattern: /\bpip\s+install\s+\S/i,
16
+ },
17
+ {
18
+ name: "Maven",
19
+ urlPattern: /search\.maven\.org|mvnrepository\.com/i,
20
+ },
21
+ {
22
+ name: "NuGet",
23
+ urlPattern: /nuget\.org\/packages\//i,
24
+ installPattern: /\bdotnet\s+add\s+package\s+\S/i,
25
+ },
26
+ {
27
+ name: "Go",
28
+ urlPattern: /pkg\.go\.dev\//i,
29
+ installPattern: /\bgo[ \t]+get[ \t]+(?:[\w-]+\.)+[\w-]+\/[\w./-]+/,
30
+ },
31
+ {
32
+ name: "RubyGems",
33
+ urlPattern: /rubygems\.org\/gems\//i,
34
+ installPattern: /\bgem\s+install\s+\S/i,
35
+ },
36
+ {
37
+ name: "Packagist",
38
+ urlPattern: /packagist\.org\/packages\//i,
39
+ installPattern: /\bcomposer\s+require\s+\S/i,
40
+ },
41
+ {
42
+ name: "Crates.io",
43
+ urlPattern: /crates\.io\/crates\//i,
44
+ installPattern: /\bcargo\s+add\s+\S/i,
45
+ },
46
+ ];
47
+ /** A target path on the actual registry host. Ordinary mentions keep their weaker, historical meaning. */
48
+ export function linkedRegistry(url) {
49
+ if (url.username || url.password || !["https:", "http:"].includes(url.protocol))
50
+ return;
51
+ const host = url.hostname.toLowerCase().replace(/^www\./, "");
52
+ const candidate = host + url.pathname;
53
+ for (const { name, urlPattern } of REGISTRY_PATTERNS) {
54
+ const match = urlPattern.exec(candidate);
55
+ if (!match || match.index !== 0 || match[0].split("/")[0].toLowerCase() !== host)
56
+ continue;
57
+ if (name === "Maven" && !/^\/artifact\/[^/]+\/[^/]+/.test(url.pathname))
58
+ continue;
59
+ if (name === "Packagist" && !/^\/packages\/[^/]+\/[^/]+/i.test(url.pathname))
60
+ continue;
61
+ if (name === "npm" && /^\/package\/@[^/]+\/?$/i.test(url.pathname))
62
+ continue;
63
+ if (name === "Go" && /^\/(search|about|license-policy)(\/|$)/i.test(url.pathname))
64
+ continue;
65
+ if (!candidate.slice(match[0].length).replace(/^\/+/, ""))
66
+ continue;
67
+ return name;
68
+ }
69
+ }
@@ -0,0 +1,3 @@
1
+ /** A named pipe must not hang validation, and a growing file must not defeat
2
+ * the input limit. Only parse complete regular files within the original size. */
3
+ export declare function readJsonFile(path: string, maxBytes: number): Promise<unknown>;
@@ -0,0 +1,41 @@
1
+ import { constants } from 'node:fs';
2
+ import { open } from 'node:fs/promises';
3
+ /** A named pipe must not hang validation, and a growing file must not defeat
4
+ * the input limit. Only parse complete regular files within the original size. */
5
+ export async function readJsonFile(path, maxBytes) {
6
+ let file;
7
+ try {
8
+ file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK);
9
+ }
10
+ catch (error) {
11
+ const errno = error.code;
12
+ throw new Error('could not open JSON file' + (errno && /^[A-Z0-9_]+$/.test(errno) ? ' (' + errno + ')' : ''));
13
+ }
14
+ try {
15
+ const stat = await file.stat();
16
+ const size = stat.size;
17
+ if (!stat.isFile() || size > maxBytes)
18
+ throw new Error('expected a regular JSON file within ' + maxBytes + ' bytes');
19
+ const bytes = Buffer.alloc(size + 1);
20
+ let offset = 0;
21
+ while (offset < bytes.length) {
22
+ const { bytesRead } = await file.read(bytes, offset, bytes.length - offset, offset);
23
+ if (!bytesRead)
24
+ break;
25
+ offset += bytesRead;
26
+ }
27
+ if (offset !== size)
28
+ throw new Error('JSON file changed during read');
29
+ try {
30
+ const encoding = bytes[0] === 0xff && bytes[1] === 0xfe ? 'utf-16le' :
31
+ bytes[0] === 0xfe && bytes[1] === 0xff ? 'utf-16be' : 'utf-8';
32
+ return JSON.parse(new TextDecoder(encoding, { fatal: true }).decode(bytes.subarray(0, size)));
33
+ }
34
+ catch {
35
+ throw new Error('invalid JSON or incomplete file');
36
+ }
37
+ }
38
+ finally {
39
+ await file.close();
40
+ }
41
+ }
@@ -0,0 +1 @@
1
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
@@ -0,0 +1,3 @@
1
+ export function isRecord(value) {
2
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3
+ }
@@ -0,0 +1,7 @@
1
+ import type { Response } from "undici";
2
+ /** A cancelled or truncated text read retains the observed prefix and marks it incomplete. */
3
+ export declare function readBodyStream(response: Response, maxBytes: number, signal: AbortSignal): Promise<{
4
+ body: string;
5
+ bodyIncomplete?: true;
6
+ }>;
7
+ export declare function readBodyBytes(response: Response, maxBytes: number, signal: AbortSignal): Promise<Uint8Array | null>;
@@ -0,0 +1,71 @@
1
+ /** Keep memory proportional to bytes read, including streams that deliver many small chunks. */
2
+ async function readBoundedBody(response, maxBytes, signal, binary) {
3
+ const reader = response.body?.getReader();
4
+ let bytes = new Uint8Array(0);
5
+ let length = 0;
6
+ let incomplete = false;
7
+ if (!reader)
8
+ return { bytes, incomplete };
9
+ const stop = () => { void reader.cancel().catch(() => { }); };
10
+ signal.addEventListener("abort", stop, { once: true });
11
+ try {
12
+ while (true) {
13
+ signal.throwIfAborted();
14
+ const { done, value } = await reader.read();
15
+ signal.throwIfAborted();
16
+ if (done)
17
+ break;
18
+ const take = Math.min(value.length, maxBytes - length);
19
+ const end = length + take;
20
+ if (end > bytes.length) {
21
+ const grown = new Uint8Array(Math.min(maxBytes, Math.max(end, bytes.length * 2, 1024)));
22
+ grown.set(bytes);
23
+ bytes = grown;
24
+ }
25
+ bytes.set(value.subarray(0, take), length);
26
+ length = end;
27
+ if (take < value.length) {
28
+ incomplete = true;
29
+ break;
30
+ }
31
+ }
32
+ }
33
+ catch (error) {
34
+ if (binary)
35
+ throw error;
36
+ incomplete = true;
37
+ }
38
+ finally {
39
+ signal.removeEventListener("abort", stop);
40
+ try {
41
+ await reader.cancel();
42
+ }
43
+ catch { /* already closed */ }
44
+ }
45
+ return { bytes: bytes.subarray(0, length), incomplete };
46
+ }
47
+ /** A cancelled or truncated text read retains the observed prefix and marks it incomplete. */
48
+ export async function readBodyStream(response, maxBytes, signal) {
49
+ const { bytes, incomplete } = await readBoundedBody(response, maxBytes, signal, false);
50
+ const declared = response.headers.get("content-type")?.match(/;\s*charset\s*=\s*["']?([^"';\s]+)/i)?.[1];
51
+ let charset = declared;
52
+ if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf)
53
+ charset = "utf-8";
54
+ if (bytes[0] === 0xff && bytes[1] === 0xfe)
55
+ charset = "utf-16le";
56
+ if (bytes[0] === 0xfe && bytes[1] === 0xff)
57
+ charset = "utf-16be";
58
+ let decoder;
59
+ try {
60
+ decoder = new TextDecoder(charset);
61
+ }
62
+ catch {
63
+ decoder = new TextDecoder();
64
+ }
65
+ const body = decoder.decode(bytes);
66
+ return incomplete ? { body, bodyIncomplete: true } : { body };
67
+ }
68
+ export async function readBodyBytes(response, maxBytes, signal) {
69
+ const { bytes, incomplete } = await readBoundedBody(response, maxBytes, signal, true);
70
+ return incomplete ? null : bytes;
71
+ }
@@ -1,23 +1,19 @@
1
- /** Scan-scoped DNS cache: hostname -> resolved IP */
2
- export type DnsCache = Map<string, string>;
1
+ /** Scan-scoped DNS cache: hostname -> validated addresses */
2
+ export type DnsCache = Map<string, readonly string[]>;
3
3
  /** SSRF validation result -- discriminated union */
4
4
  export type SsrfResult = {
5
5
  safe: true;
6
- ip: string;
6
+ addresses: readonly string[];
7
7
  } | {
8
8
  safe: false;
9
+ reason: "dns" | "timeout" | "cancelled" | "ssrf_blocked";
9
10
  error: string;
10
- ip?: string;
11
11
  };
12
12
  export declare function isPrivateIp(ip: string): boolean;
13
- /**
14
- * Validate that a hostname does not resolve to a private/reserved IP.
15
- *
16
- * - Reuses cached hostname lookups for the duration of a scan
17
- * - Skips DNS if hostname is already an IP literal
18
- * - Resolves ALL addresses and rejects if ANY is private
19
- * - Caches the first resolved IP on success
20
- * - Uses a 3-second DNS deadline
21
- */
22
- export declare function validateDns(hostname: string, cache: DnsCache): Promise<SsrfResult>;
23
- //# sourceMappingURL=ssrf.d.ts.map
13
+ /** Stricter public-unicast rule used only by Journey case and DNS validation. */
14
+ export declare function isNonPublicIp(ip: string): boolean;
15
+ /** Validate all records for every caller, including cache hits with a stricter policy. */
16
+ export declare function validateDns(hostname: string, cache: DnsCache, options?: {
17
+ signal?: AbortSignal;
18
+ publicOnly?: boolean;
19
+ }): Promise<SsrfResult>;
@@ -12,6 +12,7 @@ for (const [address, prefix] of [
12
12
  blocked.addSubnet(address, prefix, "ipv4");
13
13
  // The well-known NAT64 prefix embeds an IPv4 destination in the low 32 bits.
14
14
  blocked.addSubnet(`64:ff9b::${address}`, 96 + prefix, "ipv6");
15
+ blocked.addSubnet(`::ffff:0:${address}`, 96 + prefix, "ipv6");
15
16
  }
16
17
  for (const [address, prefix] of [
17
18
  ["::", 96], // Unspecified, loopback and IPv4-compatible addresses
@@ -32,57 +33,92 @@ export function isPrivateIp(ip) {
32
33
  return false;
33
34
  return blocked.check(ip, "ipv6");
34
35
  }
35
- function validateAddress(ip) {
36
+ // Journeys accepts public unicast destinations only. Keep the scanner's
37
+ // historical address policy intact for existing scan callers.
38
+ const nonPublic = new net.BlockList();
39
+ for (const [address, prefix] of [
40
+ ["192.0.0.0", 24], ["192.0.2.0", 24], ["192.88.99.0", 24],
41
+ ["198.51.100.0", 24], ["203.0.113.0", 24],
42
+ ])
43
+ nonPublic.addSubnet(address, prefix, "ipv4");
44
+ for (const [address, prefix] of [
45
+ ["2001::", 23], ["2001:db8::", 32], ["3fff::", 20],
46
+ ])
47
+ nonPublic.addSubnet(address, prefix, "ipv6");
48
+ const globalV6 = new net.BlockList();
49
+ globalV6.addSubnet("2000::", 3, "ipv6");
50
+ /** Stricter public-unicast rule used only by Journey case and DNS validation. */
51
+ export function isNonPublicIp(ip) {
36
52
  if (!net.isIP(ip))
37
- return { safe: false, error: "DNS resolution failed: invalid address" };
38
- if (isPrivateIp(ip)) {
39
- return { safe: false, error: `Hostname resolves to private address ${ip}`, ip };
53
+ return false;
54
+ const family = net.isIPv4(ip) ? "ipv4" : "ipv6";
55
+ return isPrivateIp(ip) || nonPublic.check(ip, family) ||
56
+ (family === "ipv6" && !globalV6.check(ip, "ipv6"));
57
+ }
58
+ function validateAddresses(addresses, publicOnly = false) {
59
+ if (!addresses.length || addresses.some(ip => !net.isIP(ip))) {
60
+ return { safe: false, reason: "dns", error: "DNS resolution failed: no valid addresses" };
61
+ }
62
+ if (addresses.some(publicOnly ? isNonPublicIp : isPrivateIp)) {
63
+ return { safe: false, reason: "ssrf_blocked", error: "Hostname resolves to a restricted address" };
40
64
  }
41
- return { safe: true, ip };
65
+ return { safe: true, addresses };
42
66
  }
43
- /**
44
- * Validate that a hostname does not resolve to a private/reserved IP.
45
- *
46
- * - Reuses cached hostname lookups for the duration of a scan
47
- * - Skips DNS if hostname is already an IP literal
48
- * - Resolves ALL addresses and rejects if ANY is private
49
- * - Caches the first resolved IP on success
50
- * - Uses a 3-second DNS deadline
51
- */
52
- export async function validateDns(hostname, cache) {
53
- // URL.hostname encloses IPv6 literals in brackets. A literal is the
54
- // socket destination even when a cached DNS entry happens to exist.
55
- const literal = hostname.startsWith("[") && hostname.endsWith("]")
56
- ? hostname.slice(1, -1)
57
- : hostname;
58
- if (net.isIP(literal))
59
- return validateAddress(literal);
60
- const cached = cache.get(hostname);
61
- if (cached !== undefined)
62
- return validateAddress(cached);
67
+ const pending = new WeakMap();
68
+ function resolveAddresses(hostname, cache) {
69
+ let lookups = pending.get(cache);
70
+ if (!lookups) {
71
+ lookups = new Map();
72
+ pending.set(cache, lookups);
73
+ }
74
+ const existing = lookups.get(hostname);
75
+ if (existing)
76
+ return existing;
63
77
  let timer;
78
+ const timeout = new Promise((_, reject) => {
79
+ timer = setTimeout(() => reject(new DOMException("DNS lookup timed out", "TimeoutError")), 3000);
80
+ });
81
+ const lookup = Promise.race([dns.lookup(hostname, { all: true }), timeout])
82
+ .then(records => records.map(record => record.address))
83
+ .finally(() => {
84
+ clearTimeout(timer);
85
+ lookups.delete(hostname);
86
+ });
87
+ lookups.set(hostname, lookup);
88
+ return lookup;
89
+ }
90
+ /** Validate all records for every caller, including cache hits with a stricter policy. */
91
+ export async function validateDns(hostname, cache, options) {
92
+ const signal = options?.signal;
93
+ let abort;
64
94
  try {
65
- const deadline = new Promise((_, reject) => {
66
- timer = setTimeout(() => reject(new Error("DNS lookup timed out")), 3000);
67
- });
68
- const records = await Promise.race([dns.lookup(hostname, { all: true }), deadline]);
69
- if (records.length === 0)
70
- return { safe: false, error: "DNS resolution failed: no addresses" };
71
- for (const record of records) {
72
- const result = validateAddress(record.address);
73
- if (!result.safe)
74
- return result;
75
- }
76
- const ip = records[0].address;
77
- cache.set(hostname, ip);
78
- return { safe: true, ip };
95
+ signal?.throwIfAborted();
96
+ const literal = hostname.startsWith("[") && hostname.endsWith("]") ? hostname.slice(1, -1) : hostname;
97
+ if (net.isIP(literal))
98
+ return validateAddresses([literal], options?.publicOnly);
99
+ const cached = cache.get(hostname);
100
+ if (cached)
101
+ return validateAddresses(cached, options?.publicOnly);
102
+ const lookup = resolveAddresses(hostname, cache);
103
+ const addresses = signal ? await Promise.race([lookup, new Promise((_, reject) => {
104
+ abort = () => reject(signal.reason);
105
+ signal.addEventListener("abort", abort, { once: true });
106
+ })]) : await lookup;
107
+ const result = validateAddresses(addresses, options?.publicOnly);
108
+ if (result.safe)
109
+ cache.set(hostname, addresses);
110
+ return result;
79
111
  }
80
- catch (err) {
81
- const message = err instanceof Error ? err.message : String(err);
82
- return { safe: false, error: `DNS resolution failed: ${message}` };
112
+ catch (error) {
113
+ if (signal?.aborted && !(error instanceof DOMException && error.name === "TimeoutError")) {
114
+ return { safe: false, reason: "cancelled", error: "DNS validation cancelled" };
115
+ }
116
+ const message = error instanceof Error ? error.message : String(error);
117
+ const reason = error instanceof DOMException && error.name === "TimeoutError" ? "timeout" : "dns";
118
+ return { safe: false, reason, error: `DNS resolution failed: ${message}` };
83
119
  }
84
120
  finally {
85
- clearTimeout(timer);
121
+ if (abort)
122
+ signal?.removeEventListener("abort", abort);
86
123
  }
87
124
  }
88
- //# sourceMappingURL=ssrf.js.map
@@ -0,0 +1,2 @@
1
+ /** Keep untrusted report fields on one line and prevent terminal control sequences. */
2
+ export declare function terminalText(value: string): string;
@@ -0,0 +1,4 @@
1
+ /** Keep untrusted report fields on one line and prevent terminal control sequences. */
2
+ export function terminalText(value) {
3
+ return value.replace(/[\p{Cc}\p{Cf}\p{Cs}\u2028\u2029]/gu, " ");
4
+ }
@@ -15,6 +15,25 @@ export interface NormalizeUrlErr {
15
15
  }
16
16
  /** Discriminated union result -- never throws */
17
17
  export type NormalizeUrlResult = NormalizeUrlOk | NormalizeUrlErr;
18
+ /**
19
+ * Longest URL a scan uses, measured after normalization. parseReference gives null for a longer one, so a check
20
+ * that reads a document's references neither requests, counts nor records it, and the HTTP client refuses one
21
+ * built any other way. Servers commonly refuse a longer request line, and a few copies of an unbounded one can
22
+ * outgrow a bridge report.
23
+ */
24
+ export declare const MAX_URL_LENGTH = 8192;
25
+ /** Parse a reference read from an untrusted document. */
26
+ export declare function parseReference(reference: string, base?: string): URL | null;
27
+ /**
28
+ * The base a `<base href>` gives a document's relative links. An href that does not parse leaves the document URL
29
+ * in place, as in HTML. One that parses to anything but an http(s) URL the scan can use gives no base (null): no
30
+ * link under it is one the scan follows, and resolving each link against it would read its whole length again.
31
+ *
32
+ * A base is usable when it fits up to the end of its path. No link inherits its fragment, and only an empty or
33
+ * fragment-only link inherits its query, so the fragment is dropped and a query that does not fit is cut just
34
+ * past the limit: such a link is still too long, as under the whole base, and every other link resolves as under it.
35
+ */
36
+ export declare function documentBase(href: string, documentUrl?: string): string | null | undefined;
18
37
  /** Only HTTP(S) requests without URL credentials are valid scan targets. */
19
38
  export declare function parseHttpUrl(input: string, base?: string): URL;
20
39
  /**
@@ -33,6 +52,14 @@ export declare function normalizeUrl(input: string): NormalizeUrlResult;
33
52
  * Throws on invalid URL -- caller must normalize first.
34
53
  */
35
54
  export declare function extractDomain(url: string): string;
55
+ /**
56
+ * Whether `url` is on the scan origin or its canonical twin: the same host with or without a
57
+ * leading `www.`, on the same port, over the same scheme or upgraded from http to https.
58
+ * Sites commonly redirect between these. Any other host is a different site.
59
+ */
60
+ export declare function sameSiteOrigin(url: URL, base: URL): boolean;
61
+ /** The origin a same-site homepage redirect landed on; otherwise the scan origin. */
62
+ export declare function effectiveOrigin(baseUrl: string, pageUrl: string | undefined): string;
36
63
  /** Result of successful redirect resolution */
37
64
  export interface ResolveRedirectOk {
38
65
  ok: true;
@@ -42,6 +69,8 @@ export interface ResolveRedirectOk {
42
69
  export interface ResolveRedirectErr {
43
70
  ok: false;
44
71
  error: string;
72
+ /** The target is a valid scan target in every respect but its length. */
73
+ tooLong?: true;
45
74
  }
46
75
  /** Discriminated union for redirect resolution */
47
76
  export type ResolveRedirectResult = ResolveRedirectOk | ResolveRedirectErr;
@@ -52,4 +81,3 @@ export type ResolveRedirectResult = ResolveRedirectOk | ResolveRedirectErr;
52
81
  * Returns a discriminated union -- never throws.
53
82
  */
54
83
  export declare function resolveRedirectUrl(locationHeader: string, currentUrl: string): ResolveRedirectResult;
55
- //# sourceMappingURL=url.d.ts.map
package/dist/utils/url.js CHANGED
@@ -1,12 +1,108 @@
1
- /** Only HTTP(S) requests without URL credentials are valid scan targets. */
2
- export function parseHttpUrl(input, base) {
3
- const url = new URL(input, base);
4
- if (url.protocol !== "https:" && url.protocol !== "http:") {
5
- throw new TypeError("Expected an HTTP or HTTPS URL");
1
+ /**
2
+ * Longest URL a scan uses, measured after normalization. parseReference gives null for a longer one, so a check
3
+ * that reads a document's references neither requests, counts nor records it, and the HTTP client refuses one
4
+ * built any other way. Servers commonly refuse a longer request line, and a few copies of an unbounded one can
5
+ * outgrow a bridge report.
6
+ */
7
+ export const MAX_URL_LENGTH = 8192;
8
+ /** Inspect only the authority of a special URL before Node runs its IDNA conversion. */
9
+ function hasOverlongHost(reference, base) {
10
+ if (reference.length <= 63)
11
+ return false;
12
+ const clean = reference.replace(/[\t\r\n]/g, "").replace(/^[\0-\x20]+/, "");
13
+ let end = clean.length;
14
+ while (end && clean.charCodeAt(end - 1) <= 0x20)
15
+ end--;
16
+ const input = clean.slice(0, end);
17
+ const scheme = /^(?:https?|wss?|ftp|file):/i.exec(input)?.[0].toLowerCase();
18
+ const rest = scheme ? input.slice(scheme.length) : input;
19
+ const slashes = /^[\\/]+/.exec(rest)?.[0].length ?? 0;
20
+ const baseScheme = /^[a-z]+:/i.exec(base ?? "")?.[0].toLowerCase();
21
+ const file = (scheme ?? baseScheme) === "file:";
22
+ // Same-scheme references without // resolve as paths. A file URL uses
23
+ // exactly two slashes before its authority (file:///path has no host).
24
+ if (file ? slashes !== 2 : slashes < 2 && (!scheme || scheme === baseScheme))
25
+ return false;
26
+ const authority = /^[^\\/?#]*/.exec(rest.slice(slashes))[0];
27
+ const hostPort = authority.slice(authority.lastIndexOf("@") + 1);
28
+ if (hostPort.startsWith("["))
29
+ return hostPort.indexOf("]") > 63;
30
+ let host = hostPort.split(":", 1)[0];
31
+ // Even a percent-encoded four-byte code point takes at most 12 characters.
32
+ if (host.length > 255 * 12)
33
+ return true;
34
+ if (host.includes("%")) {
35
+ try {
36
+ host = decodeURIComponent(host);
37
+ }
38
+ catch {
39
+ return true;
40
+ }
6
41
  }
7
- if (url.username || url.password) {
8
- throw new TypeError("URL credentials are unsupported");
42
+ const labels = host.replace(/[\u3002\uff0e\uff61]/g, ".").split(".");
43
+ return Array.from(host).length > 255 || labels.some(label => Array.from(label).length > 63);
44
+ }
45
+ function parseWithin(reference, base, maxLength) {
46
+ if (hasOverlongHost(reference, base))
47
+ return null;
48
+ const url = URL.parse(reference, base);
49
+ if (!url || !/^(?:https?|wss?|ftp|file):$/.test(url.protocol))
50
+ return url;
51
+ if (url.href.length > maxLength)
52
+ return null;
53
+ // IDNA conversion can lengthen even a short Unicode label.
54
+ if (url.hostname.length > 63 &&
55
+ (url.hostname.length > 255 || url.hostname.split(".").some(label => label.length > 63)))
56
+ return null;
57
+ return url;
58
+ }
59
+ /** Parse a reference read from an untrusted document. */
60
+ export function parseReference(reference, base) {
61
+ return parseWithin(reference, base, MAX_URL_LENGTH);
62
+ }
63
+ /**
64
+ * The base a `<base href>` gives a document's relative links. An href that does not parse leaves the document URL
65
+ * in place, as in HTML. One that parses to anything but an http(s) URL the scan can use gives no base (null): no
66
+ * link under it is one the scan follows, and resolving each link against it would read its whole length again.
67
+ *
68
+ * A base is usable when it fits up to the end of its path. No link inherits its fragment, and only an empty or
69
+ * fragment-only link inherits its query, so the fragment is dropped and a query that does not fit is cut just
70
+ * past the limit: such a link is still too long, as under the whole base, and every other link resolves as under it.
71
+ */
72
+ export function documentBase(href, documentUrl) {
73
+ const base = parseWithin(href, documentUrl, Infinity);
74
+ if (!base) {
75
+ // A host too long to be one was refused unparsed. Parsing it here to learn whether it is valid would cost as much.
76
+ return hasOverlongHost(href, documentUrl) || URL.canParse(href, documentUrl) ? null : documentUrl;
9
77
  }
78
+ if (base.protocol !== "https:" && base.protocol !== "http:")
79
+ return null;
80
+ if (base.href.length <= MAX_URL_LENGTH)
81
+ return base.href;
82
+ base.hash = "";
83
+ // "?" is escaped everywhere before the query of an http(s) URL.
84
+ const query = base.href.indexOf("?");
85
+ if ((query < 0 ? base.href.length : query) > MAX_URL_LENGTH)
86
+ return null;
87
+ // Keep at least one character of the query: an empty one may not be inherited at all.
88
+ return base.href.slice(0, Math.max(MAX_URL_LENGTH + 1, query + 2));
89
+ }
90
+ /** The scan target a reference names within a length, or why it names none. */
91
+ function scanTarget(input, base, maxLength) {
92
+ const url = parseWithin(input, base, maxLength);
93
+ if (!url)
94
+ return "Invalid URL";
95
+ if (url.protocol !== "https:" && url.protocol !== "http:")
96
+ return "Expected an HTTP or HTTPS URL";
97
+ if (url.username || url.password)
98
+ return "URL credentials are unsupported";
99
+ return url;
100
+ }
101
+ /** Only HTTP(S) requests without URL credentials are valid scan targets. */
102
+ export function parseHttpUrl(input, base) {
103
+ const url = scanTarget(input, base, MAX_URL_LENGTH);
104
+ if (typeof url === "string")
105
+ throw new TypeError(url);
10
106
  return url;
11
107
  }
12
108
  /**
@@ -25,9 +121,13 @@ export function normalizeUrl(input) {
25
121
  return { ok: false, error: "Empty URL" };
26
122
  }
27
123
  let raw = trimmed;
124
+ if (/^https?:/i.test(raw) && !/^https?:\/\//i.test(raw)) {
125
+ return { ok: false, error: "An HTTP or HTTPS scheme must be followed by //" };
126
+ }
28
127
  // Add protocol if missing
29
128
  const hasScheme = /^[a-z][a-z0-9+.-]*:/i.test(raw);
30
- const isHostWithPort = /^[^/?#:@]+:\d+(?:[/?#]|$)/.test(raw);
129
+ const portMatch = /^([^/?#:@]+):\d+(?:[/?#]|$)/.exec(raw);
130
+ const isHostWithPort = portMatch && (portMatch[1].includes(".") || portMatch[1].toLowerCase() === "localhost");
31
131
  if (!hasScheme || isHostWithPort) {
32
132
  // Strip leading // if present (protocol-relative)
33
133
  if (raw.startsWith("//")) {
@@ -45,7 +145,21 @@ export function normalizeUrl(input) {
45
145
  };
46
146
  }
47
147
  catch {
48
- return { ok: false, error: "Invalid URL. Provide an HTTP or HTTPS address without credentials." };
148
+ // A typo is not what to look for in a target refused only for its length.
149
+ const tooLong = { ok: false, error: `URL exceeds ${MAX_URL_LENGTH} characters in its encoded form.` };
150
+ if (typeof scanTarget(raw, undefined, Infinity) !== "string")
151
+ return tooLong;
152
+ // "staging:8443" parses as scheme "staging"; hint only when the https:// form it suggests is itself accepted.
153
+ const generic = "Invalid URL. Provide an HTTP or HTTPS address without credentials.";
154
+ if (!portMatch || isHostWithPort)
155
+ return { ok: false, error: generic };
156
+ const suggested = scanTarget("https://" + trimmed, undefined, Infinity);
157
+ if (typeof suggested === "string")
158
+ return { ok: false, error: generic };
159
+ // The hint would only lead to the form that is refused for its length.
160
+ if (suggested.href.length > MAX_URL_LENGTH)
161
+ return tooLong;
162
+ return { ok: false, error: `${generic.slice(0, -1)}; include the scheme for a host name without a dot, as in https://${trimmed}.` };
49
163
  }
50
164
  }
51
165
  /**
@@ -57,6 +171,23 @@ export function normalizeUrl(input) {
57
171
  export function extractDomain(url) {
58
172
  return new URL(url).hostname;
59
173
  }
174
+ /**
175
+ * Whether `url` is on the scan origin or its canonical twin: the same host with or without a
176
+ * leading `www.`, on the same port, over the same scheme or upgraded from http to https.
177
+ * Sites commonly redirect between these. Any other host is a different site.
178
+ */
179
+ export function sameSiteOrigin(url, base) {
180
+ const host = (value) => value.hostname.replace(/^www\./, "");
181
+ return (url.protocol === "https:" || url.protocol === "http:") &&
182
+ (url.protocol === base.protocol || base.protocol === "http:") &&
183
+ url.port === base.port && host(url) === host(base);
184
+ }
185
+ /** The origin a same-site homepage redirect landed on; otherwise the scan origin. */
186
+ export function effectiveOrigin(baseUrl, pageUrl) {
187
+ const base = new URL(baseUrl);
188
+ const page = pageUrl === undefined ? null : parseReference(pageUrl);
189
+ return page && sameSiteOrigin(page, base) ? page.origin : base.origin;
190
+ }
60
191
  /**
61
192
  * Resolve a Location header value against the current URL.
62
193
  *
@@ -68,12 +199,11 @@ export function resolveRedirectUrl(locationHeader, currentUrl) {
68
199
  if (trimmed === "") {
69
200
  return { ok: false, error: "Empty Location header" };
70
201
  }
71
- try {
72
- const resolved = parseHttpUrl(trimmed, currentUrl).href;
73
- return { ok: true, url: resolved };
74
- }
75
- catch {
76
- return { ok: false, error: "Invalid redirect URL" };
77
- }
202
+ const target = scanTarget(trimmed, currentUrl, MAX_URL_LENGTH);
203
+ if (typeof target !== "string")
204
+ return { ok: true, url: target.href };
205
+ // A target refused for its length alone may well exist: the scan declines to request it.
206
+ if (typeof scanTarget(trimmed, currentUrl, Infinity) !== "string")
207
+ return { ok: false, error: "Redirect URL too long", tooLong: true };
208
+ return { ok: false, error: "Invalid redirect URL" };
78
209
  }
79
- //# sourceMappingURL=url.js.map