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
@@ -1,4 +1,9 @@
1
+ import { parseReference, sameSiteOrigin } from "../../utils/url.js";
2
+ import { mediaType } from "../../utils/http-types.js";
3
+ import { CORE_SCHEMA, EVENT_ALIAS, EVENT_DOCUMENT, EVENT_MAPPING, EVENT_POP, EVENT_SEQUENCE, YAMLException, constructFromEvents, defineMappingTag, parseEvents, } from "js-yaml";
4
+ import { JSON_MAX_CONTAINERS, OVERSIZED, authDenied, isRecord, missingControl, readJson, spelledWord, unmeasured, } from "./probe-evidence.js";
1
5
  import { httpGet } from "../../utils/http-client.js";
6
+ import { collectOperations } from "../schema/oas-types.js";
2
7
  // ---------------------------------------------------------------------------
3
8
  // Constants
4
9
  // ---------------------------------------------------------------------------
@@ -24,13 +29,13 @@ const SPEC_PATHS = [
24
29
  ];
25
30
  /** Doc UI paths -- expect HTML with embedded spec URL */
26
31
  const DOC_UI_PATHS = [
27
- "/",
28
32
  "/swagger-ui.html",
29
33
  "/swagger-ui/",
30
34
  "/docs",
31
35
  "/redoc",
32
36
  "/api/docs",
33
37
  "/documentation",
38
+ "/",
34
39
  ];
35
40
  /** All paths combined */
36
41
  const ALL_PATHS = [...SPEC_PATHS, ...DOC_UI_PATHS];
@@ -44,98 +49,401 @@ const YAML_TYPES = new Set([
44
49
  // ---------------------------------------------------------------------------
45
50
  // Helpers
46
51
  // ---------------------------------------------------------------------------
47
- /** Extract the media type portion of a Content-Type header (before ;) */
48
- function mediaType(headers) {
49
- return (headers["content-type"] ?? "").split(";")[0].trim().toLowerCase();
50
- }
51
52
  function validVersion(specType, version) {
52
53
  if (specType === "swagger")
53
54
  return version === "2.0";
54
55
  return typeof version === "string" && /^3\.\d+\.\d+(?:-[\w.-]+)?$/.test(version);
55
56
  }
56
- /** Parse a JSON spec once for detection and the downstream schema checks. */
57
- function extractJsonInfo(body) {
58
- try {
59
- const parsed = JSON.parse(body);
60
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
61
- return null;
62
- const specType = "openapi" in parsed ? "openapi" : "swagger";
63
- const version = parsed[specType];
64
- if (!validVersion(specType, version))
65
- return null;
66
- if (parsed.paths !== undefined && (!parsed.paths || typeof parsed.paths !== "object" || Array.isArray(parsed.paths)))
67
- return null;
68
- const endpointCount = Object.keys(parsed.paths ?? {}).filter(path => path.startsWith("/")).length;
69
- // OpenAPI 3.1+ top-level webhooks
70
- const hasWebhooks = parsed.webhooks != null &&
71
- typeof parsed.webhooks === "object" &&
72
- Object.keys(parsed.webhooks).length > 0;
73
- // OpenAPI 3.0+ callbacks in any operation
74
- let hasCallbacks = false;
75
- if (parsed.paths && typeof parsed.paths === "object") {
76
- for (const pathItem of Object.values(parsed.paths)) {
77
- if (!pathItem || typeof pathItem !== "object")
78
- continue;
79
- for (const op of Object.values(pathItem)) {
80
- if (op && typeof op === "object" && "callbacks" in op) {
81
- hasCallbacks = true;
82
- break;
83
- }
84
- }
85
- if (hasCallbacks)
86
- break;
57
+ function partialBody(response) {
58
+ return response.bodyIncomplete === true || response.status === 206 || response.headers["content-range"] !== undefined;
59
+ }
60
+ /** Detection's cheap gate, shared by every reader so all agree on what claims to be a spec. */
61
+ function specClaim(spec) {
62
+ if (!isRecord(spec))
63
+ return null;
64
+ const specType = "openapi" in spec ? "openapi" : "swagger";
65
+ const version = spec[specType];
66
+ return validVersion(specType, version) && (spec.paths === undefined || isRecord(spec.paths)) ? { specType, version } : null;
67
+ }
68
+ /** A document that claims to be a spec but is too large or too deeply nested to inspect. */
69
+ const UNINSPECTABLE = Symbol("uninspectable");
70
+ /** Every document specClaim accepts names one of its keys, so a body without either word is not parsed. */
71
+ const SPEC_KEY = new RegExp(`${spelledWord("openapi")}|${spelledWord("swagger")}`);
72
+ const SPEC_CLAIM = /^[ \t]*(?:\{[ \t]*)?["']?(?:openapi["']?[ \t]*:[ \t]*["']?3\.\d+\.\d+(?:-[\w.-]+)?|swagger["']?[ \t]*:[ \t]*(?:["']?2\.0|2))["']?(?=[ \t]*(?:$|#|[,}]))/m;
73
+ /** Nesting bound for both formats: the root is level 1. js-yaml stops some styles one level sooner. */
74
+ const SPEC_MAX_DEPTH = 100;
75
+ /** Container bound for both formats. A body within the response size limit passes it only by opening one about every 21 characters. */
76
+ const SPEC_MAX_CONTAINERS = JSON_MAX_CONTAINERS;
77
+ /** Characters of JSON a spec read from YAML may come to: the most a JSON spec can be within the response size limit. */
78
+ const SPEC_MAX_TEXT = 5 * 1024 * 1024;
79
+ /**
80
+ * YAML is bounded in nodes: a key, a value, a list entry or a collection, an anchored one counting twice. js-yaml
81
+ * holds about 128 bytes of parser events for each and has no bound of its own, so a body is parsed only when an
82
+ * estimate from its text is within the first bound, and its document built only when the parser's own count is
83
+ * within the second. A spec of ordinary shape reaches the second at about 5 MiB.
84
+ */
85
+ const YAML_MAX_ESTIMATE = 524_288;
86
+ const YAML_MAX_NODES = 393_216;
87
+ /**
88
+ * True past either bound. A subtree shared through YAML aliases counts on every visit, so the walk ends within the
89
+ * container bound and its recursion within the depth bound.
90
+ */
91
+ function exceedsBounds(root) {
92
+ let containers = 0;
93
+ function exceeds(value, level) {
94
+ if (level > SPEC_MAX_DEPTH)
95
+ return true;
96
+ if (value === null || typeof value !== "object")
97
+ return false;
98
+ if (++containers > SPEC_MAX_CONTAINERS)
99
+ return true;
100
+ if (Array.isArray(value)) {
101
+ for (let i = 0; i < value.length; i++)
102
+ if (exceeds(value[i], level + 1))
103
+ return true;
104
+ return false;
105
+ }
106
+ for (const key in value)
107
+ if (exceeds(value[key], level + 1))
108
+ return true;
109
+ return false;
110
+ }
111
+ return exceeds(root, 1);
112
+ }
113
+ /** True when following children from `root` returns to one of its own ancestors. */
114
+ function hasCycle(root) {
115
+ const ancestors = new Set();
116
+ const done = new WeakSet();
117
+ // An explicit stack: alias jumps chain parsed nesting into paths of thousands of objects, deeper than the call stack allows.
118
+ const stack = [];
119
+ const enter = (value) => {
120
+ if (value === null || typeof value !== "object" || done.has(value))
121
+ return false;
122
+ if (ancestors.has(value))
123
+ return true;
124
+ ancestors.add(value);
125
+ stack.push([value, Object.values(value)]);
126
+ return false;
127
+ };
128
+ if (enter(root))
129
+ return true;
130
+ while (stack.length > 0) {
131
+ const [node, children] = stack[stack.length - 1];
132
+ if (children.length > 0) {
133
+ if (enter(children.pop()))
134
+ return true;
135
+ }
136
+ else {
137
+ stack.pop();
138
+ ancestors.delete(node);
139
+ done.add(node);
140
+ }
141
+ }
142
+ return false;
143
+ }
144
+ /** Unquoted, `swagger: 2.0` is a number in YAML. True when the document held one and now holds the version. */
145
+ function quoteSwagger(document, prefix = "") {
146
+ if (!isRecord(document) || prefix + "openapi" in document || document[prefix + "swagger"] !== 2)
147
+ return false;
148
+ document[prefix + "swagger"] = "2.0";
149
+ return true;
150
+ }
151
+ /** Characters of its own members a root may hold and still be read for its claim. No spec's root comes near it. */
152
+ const ROOT_MAX = 65_536;
153
+ /**
154
+ * The root object of a JSON body with its members' collections emptied and its long strings blanked: what a body
155
+ * too large to parse claims to be, read from the text.
156
+ */
157
+ function jsonRoot(body) {
158
+ let root = "";
159
+ let from = 0;
160
+ let depth = 0;
161
+ for (let i = 0; i < body.length && root.length <= ROOT_MAX; i++) {
162
+ const code = body.charCodeAt(i);
163
+ if (code === 34) {
164
+ const start = i;
165
+ for (i++; i < body.length && body.charCodeAt(i) !== 34; i++)
166
+ if (body.charCodeAt(i) === 92)
167
+ i++;
168
+ if (depth === 1 && i - start > 256) {
169
+ root += body.slice(from, start) + '""';
170
+ from = i + 1;
171
+ }
172
+ }
173
+ else if (code === 123 || code === 91) {
174
+ if (depth++ === 1) {
175
+ root += body.slice(from, i + 1);
176
+ // Nothing of the member's collection is copied, closed or not.
177
+ from = body.length;
87
178
  }
88
179
  }
89
- return { version, specType, endpointCount, hasWebhooks, hasCallbacks, parsedSpec: parsed };
180
+ else if ((code === 125 || code === 93) && --depth === 1) {
181
+ from = i;
182
+ }
183
+ }
184
+ return root.length + body.length - from > ROOT_MAX ? "" : root + body.slice(from);
185
+ }
186
+ /** A body that opens with a brace, read as JSON. Null when it is not JSON or claims nothing while too large to parse. */
187
+ function readJsonSpec(body, yaml) {
188
+ let spec;
189
+ try {
190
+ spec = readJson(body);
191
+ if (spec === OVERSIZED) {
192
+ const root = JSON.parse(jsonRoot(body));
193
+ if (yaml)
194
+ quoteSwagger(root);
195
+ return specClaim(root) ? UNINSPECTABLE : null;
196
+ }
90
197
  }
91
198
  catch {
92
199
  return null;
93
200
  }
201
+ return yaml && quoteSwagger(spec) ? { spec, text: JSON.stringify(spec) } : { spec, text: body };
202
+ }
203
+ /**
204
+ * At least the nodes js-yaml would read from the text, counted as YAML_MAX_NODES counts them, without parsing it.
205
+ * Every node fills a place that an indicator opens, so indicators are counted wherever they stand, in quoted text
206
+ * and comments too: an overestimate there, and nowhere an underestimate.
207
+ */
208
+ function yamlNodes(body) {
209
+ const blank = (code) => code === 32 || code === 9 || code === 10 || code === 13 || Number.isNaN(code);
210
+ // The first document and its root.
211
+ let nodes = 2;
212
+ // What a comma opens: a list entry, or a key and its value once a flow mapping can be open.
213
+ let entry = 1;
214
+ for (let i = 0; i < body.length; i++) {
215
+ const code = body.charCodeAt(i);
216
+ const next = body.charCodeAt(i + 1);
217
+ switch (code) {
218
+ case 58:
219
+ nodes += 2;
220
+ break; // `:` a key and its value
221
+ case 44:
222
+ nodes += entry;
223
+ break;
224
+ case 91:
225
+ if (next !== 93)
226
+ nodes++;
227
+ break; // `[` its first entry
228
+ case 123:
229
+ if (next !== 125)
230
+ nodes += (entry = 2);
231
+ break; // `{` its first key and value
232
+ case 63:
233
+ if (blank(next))
234
+ nodes += 2;
235
+ break; // `? ` a key and its value
236
+ case 38:
237
+ nodes++;
238
+ break; // `&` an anchor
239
+ case 37:
240
+ nodes += 2;
241
+ break; // `%` a tag directive, which js-yaml keeps
242
+ case 45:
243
+ case 46: // `- ` a list entry; `---` or `...` another document and its root
244
+ if (code === 45 && blank(next))
245
+ nodes++;
246
+ if (next === code && body.charCodeAt(i + 2) === code)
247
+ nodes += 2;
248
+ }
249
+ }
250
+ return nodes;
251
+ }
252
+ // js-yaml's own mapping assigns each key to a plain object, where a key that is a small integer, as '200' is under
253
+ // `responses`, reserves an array of up to 4 KB: a spec of 30,000 operations came to more than the heap. Here every
254
+ // key takes a prefix, so none is an index, and the document is written out as JSON text instead of kept.
255
+ const KEY = "\0";
256
+ const SPEC_SCHEMA = CORE_SCHEMA.withTags(defineMappingTag("tag:yaml.org,2002:map", {
257
+ create: () => ({}),
258
+ addPair(mapping, key, value) {
259
+ if (key !== null && typeof key === "object")
260
+ return "a mapping key must be a scalar";
261
+ mapping[KEY + String(key)] = value;
262
+ return "";
263
+ },
264
+ has: (mapping, key) => (key === null || typeof key !== "object") && Object.hasOwn(mapping, KEY + String(key)),
265
+ keys: mapping => Object.keys(mapping).map(key => key.slice(KEY.length)),
266
+ get: (mapping, key) => mapping[KEY + String(key)] ?? null,
267
+ identify: () => false,
268
+ }));
269
+ /**
270
+ * The JSON text of a document built with SPEC_SCHEMA, or undefined past a bound. A subtree shared through aliases
271
+ * is written, and counted, on every visit: text has no other way to hold it.
272
+ */
273
+ function writeJson(root, bodyLength) {
274
+ const seen = new WeakSet();
275
+ const chunks = [];
276
+ const parts = [];
277
+ let length = 0;
278
+ let containers = 0;
279
+ let visited = 0;
280
+ let expandedAlias = false;
281
+ let within = true;
282
+ function put(part) {
283
+ within &&= (length += part.length) <= SPEC_MAX_TEXT;
284
+ // Joined a few thousand at a time: held to the end, the parts of a large document outweigh its text several times.
285
+ if (parts.push(part) === 4096)
286
+ chunks.push(parts.splice(0).join(""));
287
+ }
288
+ function write(value, level) {
289
+ visited++;
290
+ if (value === null || typeof value !== "object") {
291
+ within &&= level <= SPEC_MAX_DEPTH && !(expandedAlias && visited > Math.max(100_000, bodyLength));
292
+ return put(JSON.stringify(value));
293
+ }
294
+ expandedAlias ||= seen.has(value);
295
+ seen.add(value);
296
+ // Plain YAML cannot hold more nodes than bytes, so aliases get no more budget than an alias-free body of the same size.
297
+ within &&= level <= SPEC_MAX_DEPTH && ++containers <= SPEC_MAX_CONTAINERS && !(expandedAlias && visited > Math.max(100_000, bodyLength));
298
+ let separator = "";
299
+ if (Array.isArray(value)) {
300
+ put("[");
301
+ for (let i = 0; within && i < value.length; i++) {
302
+ put(separator);
303
+ separator = ",";
304
+ write(value[i], level + 1);
305
+ }
306
+ put("]");
307
+ }
308
+ else {
309
+ put("{");
310
+ for (const key in value) {
311
+ if (!within)
312
+ break;
313
+ put(separator + JSON.stringify(key.slice(KEY.length)) + ":");
314
+ separator = ",";
315
+ write(value[key], level + 1);
316
+ }
317
+ put("}");
318
+ }
319
+ }
320
+ write(root, 1);
321
+ return within ? chunks.join("") + parts.join("") : undefined;
94
322
  }
95
- /** Extract version, spec type, and endpoint count from YAML via regex */
96
- function extractYamlInfo(body) {
97
- const versionMatch = body.match(/^(openapi|swagger):[ \t]*["']?([\w.-]+)["']?[ \t]*(?:#.*)?\r?$/m);
98
- if (!versionMatch || !validVersion(versionMatch[1], versionMatch[2]))
323
+ /** A YAML body as JSON text. Null when it is not a spec; UNINSPECTABLE when it claims to be one past a bound. */
324
+ function yamlAsJson(body) {
325
+ // Nothing was built past these bounds, so only the raw text can show what the body claimed to be.
326
+ // Best effort: a line-anchored regex cannot see YAML structure, so a nested or quoted look-alike also matches,
327
+ // and a key that is tagged, anchored, escaped or explicit does not.
328
+ const refused = () => SPEC_CLAIM.test(body) ? UNINSPECTABLE : null;
329
+ if (yamlNodes(body) > YAML_MAX_ESTIMATE)
330
+ return refused();
331
+ let document;
332
+ try {
333
+ const events = parseEvents(body, { maxDepth: SPEC_MAX_DEPTH });
334
+ let nodes = 0;
335
+ let collections = 0;
336
+ let documents = 0;
337
+ for (const event of events) {
338
+ if (event.type === EVENT_DOCUMENT)
339
+ documents++;
340
+ else if (event.type !== EVENT_POP) {
341
+ nodes += event.type !== EVENT_ALIAS && event.anchorStart !== -1 ? 2 : 1;
342
+ if (event.type === EVENT_SEQUENCE || event.type === EVENT_MAPPING)
343
+ collections++;
344
+ }
345
+ }
346
+ // A spec is one document.
347
+ if (documents !== 1)
348
+ return null;
349
+ if (nodes > YAML_MAX_NODES || collections > SPEC_MAX_CONTAINERS)
350
+ return refused();
351
+ // The constructor reads each event once, in order. Letting each go as it is read keeps the events and the
352
+ // document from standing in the heap together, which at the node bound is 35 MiB more than either alone.
353
+ const once = new Proxy(events, {
354
+ get(target, key) {
355
+ const value = Reflect.get(target, key);
356
+ if (typeof value === "object")
357
+ Reflect.set(target, key, undefined);
358
+ return value;
359
+ },
360
+ });
361
+ [document] = constructFromEvents(once, { source: body, schema: SPEC_SCHEMA, maxAliases: 64 });
362
+ }
363
+ catch (error) {
364
+ // Anchored on the reason: the message quotes the lines around the error and other reasons quote tag names, all site-controlled.
365
+ if (error instanceof YAMLException && /^(?:aliases exceeded maxAliases|nesting exceeded maxDepth) /.test(error.reason))
366
+ return refused();
99
367
  return null;
100
- // Count paths in YAML (lines that start with / at indent level 2)
101
- const pathMatches = body.match(/^ {2}\/\S+:/gm);
102
- // Top-level webhooks key (OpenAPI 3.1+)
103
- const hasWebhooks = /^webhooks:/m.test(body);
104
- // Callbacks nested under operations (indented 6+ spaces)
105
- const hasCallbacks = /^ {6,}callbacks:/m.test(body);
106
- return {
107
- version: versionMatch[2],
108
- specType: versionMatch[1],
109
- endpointCount: pathMatches?.length ?? 0,
110
- hasWebhooks,
111
- hasCallbacks,
112
- };
368
+ }
369
+ quoteSwagger(document, KEY);
370
+ const root = isRecord(document)
371
+ ? Object.fromEntries(["openapi", "swagger", "paths"].filter(key => KEY + key in document).map(key => [key, document[KEY + key]]))
372
+ : null;
373
+ if (!specClaim(root))
374
+ return null;
375
+ // A cycle has no JSON form, so it is not a spec. Other bounds only stop inspection of a claimed spec.
376
+ return writeJson(document, body.length) ?? (hasCycle(document) ? null : UNINSPECTABLE);
113
377
  }
114
- function detectSpec(response, path) {
378
+ function readYamlSpec(body) {
379
+ const text = yamlAsJson(body);
380
+ if (typeof text !== "string")
381
+ return text;
382
+ // Parsed only here, with the document js-yaml built out of reach: the two together are more than a bridge should hold.
383
+ // Counted as a JSON body is. The document kept no key as an index, and its text holds a subtree at every alias,
384
+ // so maps keyed by whole numbers and repeated through aliases would parse to more than a bridge's heap.
385
+ const spec = readJson(text);
386
+ return spec === OVERSIZED ? UNINSPECTABLE : { spec, text };
387
+ }
388
+ /** Whether a spec-path response is read with the YAML parser. */
389
+ function readAsYaml(response, path) {
115
390
  const ct = mediaType(response.headers);
116
- if (HTML_TYPES.has(ct))
391
+ return YAML_TYPES.has(ct) || ct.endsWith("+yaml") || /\.ya?ml$/i.test(path);
392
+ }
393
+ function detectSpec(response, path) {
394
+ if (partialBody(response) || HTML_TYPES.has(mediaType(response.headers)))
117
395
  return null;
396
+ const yaml = readAsYaml(response, path);
118
397
  const json = response.body.trimStart().startsWith("{");
119
- const info = json ? extractJsonInfo(response.body) : YAML_TYPES.has(ct) ? extractYamlInfo(response.body) : null;
120
- if (!info)
398
+ if (!yaml && !json)
399
+ return null;
400
+ // One parse of a dense body can hold over 20 times its size, and a catch-all site serves one at every spec path.
401
+ if (!SPEC_KEY.test(response.body))
121
402
  return null;
122
- const { version, specType, endpointCount, hasWebhooks, hasCallbacks } = info;
403
+ // JSON is read as JSON at a YAML path too, to the bounds it has at a JSON path. What is not JSON is YAML there.
404
+ const read = (json ? readJsonSpec(response.body, yaml) : null) ?? (yaml ? readYamlSpec(response.body) : null);
405
+ if (read === null || read === UNINSPECTABLE)
406
+ return read;
407
+ const { spec } = read;
408
+ const claim = specClaim(spec);
409
+ if (!claim || !isRecord(spec))
410
+ return null;
411
+ // Unbounded, the spec could exceed what the bridges that read it can hold.
412
+ if (exceedsBounds(spec))
413
+ return UNINSPECTABLE;
414
+ const { specType, version } = claim;
415
+ const document = new URL(response.url);
416
+ const chain = [...response.redirects, response.url].map(raw => new URL(raw));
417
+ const safeIdentity = (u) => ["https:", "http:"].includes(u.protocol) && !u.username && !u.password && !u.search;
418
+ const verifiedDocumentUrls = (chain.every(safeIdentity) ? chain : [document].filter(safeIdentity))
419
+ .map(u => u.origin + u.pathname);
420
+ const paths = spec.paths ?? {};
421
+ const endpointCount = Object.keys(paths).filter(path => path.startsWith("/")).length;
422
+ const hasWebhooks = isRecord(spec.webhooks) && Object.keys(spec.webhooks).length > 0;
423
+ const hasCallbacks = specType === "openapi" && collectOperations(spec).some(([, , op]) => "callbacks" in op && isRecord(op.callbacks) && Object.keys(op.callbacks).length > 0);
123
424
  return {
124
425
  check: {
125
- id: "openapi_spec", label: "OpenAPI Spec", status: json ? "pass" : "partial",
126
- detail: json ? `OpenAPI ${version} found with ${endpointCount} endpoints` : `OpenAPI ${version} found (YAML format)`,
127
- data: { version, specType, endpointCount, path },
426
+ id: "openapi_spec", label: "OpenAPI Spec", status: "pass",
427
+ detail: `OpenAPI ${version} found with ${endpointCount} endpoints`,
428
+ data: {
429
+ version, specType, endpointCount, path,
430
+ documentUrl: document.origin + document.pathname,
431
+ ...(document.search ? { documentHasQuery: true } : {}),
432
+ },
128
433
  },
129
- detected: true, hasWebhooks, hasCallbacks,
130
- parsedSpec: "parsedSpec" in info ? info.parsedSpec : null,
434
+ detected: true, hasWebhooks, hasCallbacks, specText: read.text, verifiedDocumentUrls,
131
435
  };
132
436
  }
133
- /** Patterns that extract spec URLs from HTML or JS content */
437
+ /**
438
+ * Patterns that extract spec URLs from HTML or JS content. A pattern whose scan can fail far from its
439
+ * start ends with a capture-free alternative that consumes the scanned span: every later start inside
440
+ * that span would fail the same way, and rescanning it from each start is quadratic in the body size.
441
+ */
134
442
  const SPEC_URL_PATTERNS = [
135
443
  // 1. Swagger UI initializer: SwaggerUIBundle({ url: "/openapi.json" })
136
- /SwaggerUI(?:Bundle|Standalone)?\s*\(\s*\{[^}]*url\s*:\s*["']([^"']+)["']/g,
444
+ /SwaggerUI(?:Bundle|Standalone)?\s*\(\s*\{(?:[^}]*url\s*:\s*["']([^"']+)["']|[^}]*)/g,
137
445
  // 2. Swagger UI configUrl: SwaggerUIBundle({ configUrl: "/swagger-config" })
138
- /SwaggerUI(?:Bundle|Standalone)?\s*\(\s*\{[^}]*configUrl\s*:\s*["']([^"']+)["']/g,
446
+ /SwaggerUI(?:Bundle|Standalone)?\s*\(\s*\{(?:[^}]*configUrl\s*:\s*["']([^"']+)["']|[^}]*)/g,
139
447
  // 3. Swagger UI swaggerUrl (older): swaggerUrl: "/api/swagger.json"
140
448
  /swaggerUrl\s*:\s*["']([^"']+)["']/g,
141
449
  // 4. ReDoc spec-url attribute: <redoc spec-url="/api/openapi.json">
@@ -147,81 +455,156 @@ const SPEC_URL_PATTERNS = [
147
455
  // 7. fetch() call to JSON/YAML (Flasgger pattern): fetch("/spec.json")
148
456
  /fetch\(\s*["']([^"']+\.(?:json|yaml))["']\s*\)/g,
149
457
  // 8. Unquoted spec URLs in JS (template literals, config strings)
150
- /(https?:\/\/[^\s,`"'<>]+(?:openapi|swagger)\.(?:json|yaml))/g,
458
+ /(https?:\/\/[^\s,`"'<>]+(?:openapi|swagger)\.(?:json|yaml))|https?:\/\/[^\s,`"'<>]*/g,
151
459
  ];
152
- const SCRIPT_URL_PATTERNS = [/<script[^<>]+src=["']([^"']*swagger[^"']*\.js)["']/gi];
460
+ // The quoted value runs to the next quote, so testing it for "swagger" once avoids nested backtracking.
461
+ const SCRIPT_URL_PATTERNS = [/<script[^<>]+src=["']((?=[^"']*swagger)[^"']*\.js)["']/gi];
153
462
  const MAX_CANDIDATES = 3;
154
- /** Keep only same-origin candidates that might actually be fetched. */
155
- function collectCandidates(body, pageUrl, patterns, candidates, excluded) {
463
+ /** Whether the URL is the counterpart origin's copy of a URL the scan origin was already probed at. */
464
+ function repeatsProbe(url, base, probed) {
465
+ return probed.has(base.origin + url.href.slice(url.origin.length));
466
+ }
467
+ /** Keep only same-site candidates that might actually be fetched. */
468
+ function collectCandidates(body, pageUrl, base, patterns, candidates, excluded, repeats) {
156
469
  if (candidates.size >= MAX_CANDIDATES)
157
470
  return;
158
- const origin = new URL(pageUrl).origin;
159
471
  for (const pattern of patterns) {
160
472
  for (const match of body.matchAll(pattern)) {
161
- const url = URL.parse(match[1], pageUrl);
162
- if (url?.origin !== origin || url.username || url.password || excluded?.has(url.href))
473
+ if (match[1] === undefined)
163
474
  continue;
164
- candidates.add(url.href);
475
+ const url = parseReference(match[1], pageUrl);
476
+ if (!url || !sameSiteOrigin(url, base) || url.username || url.password)
477
+ continue;
478
+ url.hash = "";
479
+ if (excluded?.has(url.href))
480
+ continue;
481
+ (repeats && excluded && repeatsProbe(url, base, excluded) ? repeats : candidates).add(url.href);
165
482
  if (candidates.size >= MAX_CANDIDATES)
166
483
  return;
167
484
  }
168
485
  }
169
486
  }
170
- /** Returns true if response is a 401/403 HTTP error (not bot-protected) */
171
- function isProtectedResponse(response) {
172
- if (response.ok)
173
- return false;
174
- const { error } = response;
175
- return (error.kind === "http_error" &&
176
- error.statusCode !== undefined &&
177
- (error.statusCode === 401 || error.statusCode === 403));
487
+ /** Read only machine-description targets from an RFC 9727 JSON Linkset. OVERSIZED for a catalog too large to parse. */
488
+ function catalogCandidates(response, excluded) {
489
+ if (mediaType(response.headers) !== "application/linkset+json")
490
+ return [];
491
+ let catalog;
492
+ try {
493
+ catalog = readJson(response.body);
494
+ }
495
+ catch {
496
+ return [];
497
+ }
498
+ if (catalog === OVERSIZED)
499
+ return catalog;
500
+ if (!isRecord(catalog) || !Array.isArray(catalog.linkset))
501
+ return [];
502
+ const catalogUrl = new URL(response.url);
503
+ const candidates = new Set();
504
+ for (const context of catalog.linkset) {
505
+ if (!isRecord(context) || !Array.isArray(context["service-desc"]))
506
+ continue;
507
+ for (const link of context["service-desc"]) {
508
+ if (!isRecord(link) || typeof link.href !== "string" || !link.href.trim())
509
+ continue;
510
+ if (link.type !== undefined) {
511
+ if (typeof link.type !== "string")
512
+ continue;
513
+ const type = link.type.split(";")[0].trim().toLowerCase();
514
+ if (type !== "application/json" && !YAML_TYPES.has(type) && !/\+(json|yaml)$/.test(type))
515
+ continue;
516
+ }
517
+ const url = parseReference(link.href, response.url);
518
+ if (!url || url.protocol !== catalogUrl.protocol || url.origin !== catalogUrl.origin || url.username || url.password)
519
+ continue;
520
+ url.hash = "";
521
+ if (excluded.has(url.href))
522
+ continue;
523
+ candidates.add(url.href);
524
+ if (candidates.size >= MAX_CANDIDATES)
525
+ return [...candidates];
526
+ }
527
+ }
528
+ return [...candidates];
529
+ }
530
+ async function probeSpecCandidates(get, detect, urls, timeout, catalogUrl) {
531
+ // Each candidate is read as it arrives and its body let go: the first in the list that is a spec still wins,
532
+ // and the others are not held beside the one being parsed.
533
+ let hit;
534
+ await Promise.all(urls.map(async (url, index) => {
535
+ const response = await get(url, {
536
+ timeout,
537
+ ...(catalogUrl ? { maxRedirects: 0 } : {}),
538
+ headers: { Accept: "application/json, application/yaml, */*" },
539
+ });
540
+ if (!response.ok || (hit && hit.index < index))
541
+ return;
542
+ const spec = detect(response, new URL(url).pathname);
543
+ if (spec)
544
+ hit = { index, spec };
545
+ }));
546
+ if (!hit)
547
+ return null;
548
+ const { index, spec } = hit;
549
+ if (catalogUrl) {
550
+ const catalog = new URL(catalogUrl);
551
+ const published = new URL(urls[index]);
552
+ const target = published.origin + published.pathname;
553
+ const safe = !catalog.search && !catalog.username && !catalog.password &&
554
+ !published.search && !published.username && !published.password && spec.verifiedDocumentUrls?.includes(target);
555
+ spec.check.data = { ...spec.check.data, source: "api-catalog",
556
+ ...(safe ? { catalogRoute: { source: catalog.origin + catalog.pathname, target } } : {}) };
557
+ }
558
+ return spec;
178
559
  }
179
- // ---------------------------------------------------------------------------
180
560
  // APIs.guru Registry Lookup
181
561
  // ---------------------------------------------------------------------------
182
562
  /**
183
563
  * Look up the domain in the APIs.guru public registry.
184
564
  *
185
565
  * Uses the lightweight provider endpoint (~550 bytes compressed).
186
- * Returns the swaggerUrl for the preferred API version, or null if not found.
566
+ * Returns the first advertised HTTP(S) spec URL, null for a miss, or undefined if the registry could not be read.
187
567
  *
188
568
  * This catches companies like Stripe that publish their OpenAPI spec on GitHub
189
569
  * rather than self-hosting it at a standard path on their own domain.
190
570
  */
191
- async function lookupApisGuru(domain, timeout) {
192
- const result = await httpGet(`https://api.apis.guru/v2/${domain}.json`, {
193
- timeout,
571
+ async function lookupApisGuru(get, domain, timeout) {
572
+ const result = await get(`https://api.apis.guru/v2/${domain}.json`, {
573
+ timeout, retry: false, maxRedirects: 0,
194
574
  headers: { Accept: "application/json" },
195
575
  });
196
- if (!result.ok) {
197
- return { specUrl: null, budgetDenied: result.error.kind === "request_budget_exhausted" };
198
- }
576
+ if (!result.ok)
577
+ return missingControl(result) ? null : undefined;
578
+ if (unmeasured(result))
579
+ return undefined;
199
580
  try {
200
- const parsed = JSON.parse(result.body);
201
- const apis = parsed?.apis;
202
- if (!apis || typeof apis !== "object")
203
- return { specUrl: null, budgetDenied: false };
204
- // Take the first API entry (most providers have exactly one)
205
- const firstApi = Object.values(apis)[0];
206
- if (!firstApi)
207
- return { specUrl: null, budgetDenied: false };
208
- return {
209
- specUrl: firstApi.swaggerUrl ??
210
- firstApi.swaggerYamlUrl ??
211
- null,
212
- budgetDenied: false,
213
- };
214
- }
215
- catch {
216
- return { specUrl: null, budgetDenied: false };
581
+ const parsed = readJson(result.body);
582
+ if (!isRecord(parsed) || !isRecord(parsed.apis))
583
+ return undefined;
584
+ const entries = Object.values(parsed.apis);
585
+ if (!entries.length)
586
+ return null;
587
+ for (const api of entries) {
588
+ if (!isRecord(api))
589
+ continue;
590
+ for (const value of [api.swaggerUrl, api.swaggerYamlUrl]) {
591
+ if (typeof value !== "string")
592
+ continue;
593
+ const url = parseReference(value);
594
+ if (url && ["https:", "http:"].includes(url.protocol) && !url.username && !url.password)
595
+ return url.href;
596
+ }
597
+ }
217
598
  }
599
+ catch { /* An unreadable registry response cannot establish absence. */ }
600
+ return undefined;
218
601
  }
219
602
  // ---------------------------------------------------------------------------
220
603
  // Public API
221
604
  // ---------------------------------------------------------------------------
222
605
  /**
223
- * Probe 24 common OpenAPI / Swagger spec and doc-UI paths in parallel, then try
224
- * extracting spec URLs from HTML doc pages, and finally detect protected specs.
606
+ * Inspect common spec and UI paths, same-site UI/sitemap candidates, and the API catalog.
607
+ * Check path-specific authentication before consulting the optional external registry.
225
608
  *
226
609
  * Optionally accepts sitemap-discovered API URLs as additional candidates
227
610
  * to probe in Phase 3b (secondary validation).
@@ -229,147 +612,192 @@ async function lookupApisGuru(domain, timeout) {
229
612
  * Returns a Check with id "openapi_spec" and a boolean indicating whether
230
613
  * any valid spec was detected (for ctx.shared.openApiDetected).
231
614
  */
232
- export async function checkOpenApi(baseUrl, timeout, sitemapCandidateUrls = []) {
615
+ async function discoverSelfHosted(baseUrl, timeout, sitemapCandidateUrls = [], homepage) {
233
616
  const id = "openapi_spec";
234
617
  const label = "OpenAPI Spec";
235
- // Phase 1: Fire all 24 probes in parallel (17 spec paths + 7 doc UI paths)
236
- const responses = await Promise.all([
237
- ...SPEC_PATHS.map((path) => httpGet(new URL(path, baseUrl).href, {
238
- timeout,
239
- headers: { Accept: "application/json, application/yaml, */*" },
618
+ // Every discovery wave contributes to coverage. A timeout, blocked fetch,
619
+ // server failure or truncated body cannot establish a missing contract.
620
+ let budgetDenied = false;
621
+ let unavailable = false;
622
+ const get = async (url, options) => {
623
+ const response = await httpGet(url, options);
624
+ if (!response.ok && response.error.kind === "request_budget_exhausted")
625
+ budgetDenied = true;
626
+ else
627
+ unavailable ||= unmeasured(response);
628
+ return response;
629
+ };
630
+ // A readable spec elsewhere still wins over a candidate too large to inspect.
631
+ let uninspectable = false;
632
+ const detect = (response, path) => {
633
+ const result = detectSpec(response, path);
634
+ if (result !== UNINSPECTABLE)
635
+ return result;
636
+ uninspectable = true;
637
+ return null;
638
+ };
639
+ const rootUrl = new URL("/", baseUrl).href;
640
+ const reusableHomepage = homepage && homepage.status === 200 && !partialBody(homepage) &&
641
+ !homepage.redirects.length && URL.parse(homepage.url)?.href === rootUrl && HTML_TYPES.has(mediaType(homepage.headers));
642
+ const base = new URL(baseUrl);
643
+ const standardUrls = new Set(ALL_PATHS.map((p) => new URL(p, baseUrl).href));
644
+ const allProbedUrls = new Set(standardUrls);
645
+ // A standard path redirected to the same path on another origin is that origin's standard path, already probed.
646
+ // Any other redirect target stays a candidate: its body was not necessarily read as a spec.
647
+ const recordLanding = (response, path) => {
648
+ const landed = URL.parse(response.ok ? response.url : response.error.url);
649
+ if (landed && landed.href === URL.parse(path, landed.origin)?.href)
650
+ allProbedUrls.add(landed.href);
651
+ };
652
+ // Landings are not all known while pages settle. A landing is a standard path, so it can only be sorted as a repeat.
653
+ const pageCandidates = (response) => {
654
+ const spec = new Set();
655
+ const repeats = new Set();
656
+ const scripts = new Set();
657
+ // Relative references resolve against the document after redirects; candidates stay on the scanned site.
658
+ collectCandidates(response.body, response.url, base, SPEC_URL_PATTERNS, spec, standardUrls, repeats);
659
+ if (!spec.size)
660
+ collectCandidates(response.body, response.url, base, SCRIPT_URL_PATTERNS, scripts);
661
+ return { spec, repeats, scripts };
662
+ };
663
+ // Fetch the candidate paths concurrently, reusing a complete HTML homepage when available. Each response is
664
+ // reduced as it settles: on a catch-all site every probe returns the same page, and holding them all can exhaust the heap.
665
+ // Phase 2: the lowest-index spec-path hit wins, so a path after an earlier hit need not be parsed.
666
+ let specHit;
667
+ const [specPathDenied, docUiCandidates] = await Promise.all([
668
+ Promise.all(SPEC_PATHS.map(async (path, index) => {
669
+ const response = await get(new URL(path, baseUrl).href, {
670
+ timeout,
671
+ headers: { Accept: "application/json, application/yaml, */*" },
672
+ });
673
+ recordLanding(response, path);
674
+ if (response.ok && (!specHit || index < specHit.index)) {
675
+ const result = detect(response, path);
676
+ if (result)
677
+ specHit = { index, result };
678
+ }
679
+ return authDenied(response);
240
680
  })),
241
- ...DOC_UI_PATHS.map((path) => httpGet(new URL(path, baseUrl).href, {
242
- timeout,
243
- headers: { Accept: "text/html, */*" },
681
+ Promise.all(DOC_UI_PATHS.map(async (path) => {
682
+ const response = path === "/" && reusableHomepage ? homepage : await get(new URL(path, baseUrl).href, {
683
+ timeout,
684
+ headers: { Accept: "text/html, */*" },
685
+ });
686
+ recordLanding(response, path);
687
+ return response.ok && HTML_TYPES.has(mediaType(response.headers)) ? pageCandidates(response) : undefined;
244
688
  })),
245
689
  ]);
246
- const specPathResponses = responses.slice(0, SPEC_PATHS.length);
247
- const docUiResponses = responses.slice(SPEC_PATHS.length);
248
- // Track budget denials across EVERY fetch wave (primary probes, script
249
- // fetches, secondary candidates, registry lookup) — a denied probe is not
250
- // evidence the spec is absent.
251
- let budgetDenied = responses.some((r) => !r.ok && r.error.kind === "request_budget_exhausted");
252
- // Phase 2: Check spec-path responses for direct spec hits
253
- for (let i = 0; i < specPathResponses.length; i++) {
254
- const response = specPathResponses[i];
255
- if (!response.ok)
256
- continue;
257
- const result = detectSpec(response, SPEC_PATHS[i]);
258
- if (result)
259
- return result;
260
- }
261
- // Phase 3: Check doc-UI-path responses for HTML with extractable spec URLs
262
- const origin = new URL(baseUrl).origin;
263
- const allProbedUrls = new Set(ALL_PATHS.map((p) => new URL(p, baseUrl).href));
690
+ if (specHit)
691
+ return specHit.result;
692
+ // Phase 3: Merge spec URLs extracted from doc-UI HTML in path order
264
693
  const specCandidates = new Set();
694
+ // The counterpart's copy of a probed path most likely repeats that probe, so it takes only a slot nothing else needs.
695
+ const repeatCandidates = new Set();
265
696
  const scriptCandidates = new Set();
266
- for (let i = 0; i < docUiResponses.length; i++) {
267
- const response = docUiResponses[i];
268
- if (!response.ok)
269
- continue;
270
- const ct = mediaType(response.headers);
271
- if (!HTML_TYPES.has(ct))
697
+ for (const page of docUiCandidates) {
698
+ if (!page)
272
699
  continue;
273
- const pageUrl = new URL(DOC_UI_PATHS[i], baseUrl).href;
274
- // Extract spec URLs directly from HTML
275
- collectCandidates(response.body, pageUrl, SPEC_URL_PATTERNS, specCandidates, allProbedUrls);
700
+ for (const url of page.spec)
701
+ if (specCandidates.size < MAX_CANDIDATES)
702
+ specCandidates.add(url);
703
+ for (const url of page.repeats)
704
+ if (!allProbedUrls.has(url))
705
+ repeatCandidates.add(url);
276
706
  if (!specCandidates.size)
277
- collectCandidates(response.body, pageUrl, SCRIPT_URL_PATTERNS, scriptCandidates);
707
+ for (const url of page.scripts)
708
+ if (scriptCandidates.size < MAX_CANDIDATES)
709
+ scriptCandidates.add(url);
278
710
  }
279
711
  // Phase 3a: Fetch external Swagger UI config scripts and extract spec URLs from them
280
712
  if (!specCandidates.size && scriptCandidates.size) {
281
- const scriptUrls = [...scriptCandidates];
282
- const scriptResponses = await Promise.all(scriptUrls.map((url) => httpGet(url, {
283
- timeout,
284
- headers: { Accept: "*/*" },
285
- })));
286
- budgetDenied ||= scriptResponses.some((r) => !r.ok && r.error.kind === "request_budget_exhausted");
287
- for (let i = 0; i < scriptResponses.length; i++) {
288
- const response = scriptResponses[i];
289
- if (!response.ok)
290
- continue;
291
- collectCandidates(response.body, scriptUrls[i], SPEC_URL_PATTERNS, specCandidates, allProbedUrls);
713
+ // Each script is read as it arrives and its body let go; what it names is merged in the scripts' order.
714
+ const named = await Promise.all([...scriptCandidates].map(async (url) => {
715
+ const response = await get(url, { timeout, headers: { Accept: "*/*" } });
716
+ const spec = new Set();
717
+ const repeats = new Set();
718
+ if (response.ok)
719
+ collectCandidates(response.body, response.url, base, SPEC_URL_PATTERNS, spec, allProbedUrls, repeats);
720
+ return { spec, repeats };
721
+ }));
722
+ for (const script of named) {
723
+ for (const url of script.spec)
724
+ if (specCandidates.size < MAX_CANDIDATES)
725
+ specCandidates.add(url);
726
+ for (const url of script.repeats)
727
+ repeatCandidates.add(url);
292
728
  }
293
729
  }
294
730
  for (const candidate of sitemapCandidateUrls) {
295
731
  if (specCandidates.size >= MAX_CANDIDATES)
296
732
  break;
297
- const url = URL.parse(candidate);
298
- if (url?.origin === origin && !url.username && !url.password && !allProbedUrls.has(url.href))
299
- specCandidates.add(url.href);
733
+ const url = parseReference(candidate);
734
+ if (!url || !sameSiteOrigin(url, base) || url.username || url.password)
735
+ continue;
736
+ url.hash = "";
737
+ if (!allProbedUrls.has(url.href))
738
+ (repeatsProbe(url, base, allProbedUrls) ? repeatCandidates : specCandidates).add(url.href);
300
739
  }
301
740
  // Phase 3b: Fetch candidate spec URLs and validate
302
- if (specCandidates.size) {
303
- const specCandidateUrls = [...specCandidates];
304
- const secondaryResponses = await Promise.all(specCandidateUrls.map((url) => httpGet(url, {
305
- timeout,
306
- headers: { Accept: "application/json, application/yaml, */*" },
307
- })));
308
- budgetDenied ||= secondaryResponses.some((r) => !r.ok && r.error.kind === "request_budget_exhausted");
309
- for (let i = 0; i < secondaryResponses.length; i++) {
310
- const response = secondaryResponses[i];
311
- if (!response.ok)
312
- continue;
313
- const result = detectSpec(response, new URL(specCandidateUrls[i]).pathname);
314
- if (result)
315
- return result;
741
+ const candidates = [...specCandidates, ...repeatCandidates].slice(0, MAX_CANDIDATES);
742
+ const secondary = await probeSpecCandidates(get, detect, candidates, timeout);
743
+ if (secondary)
744
+ return secondary;
745
+ // A catalog is a pointer, so only a validated document can earn credit.
746
+ const catalogUrl = new URL("/.well-known/api-catalog", baseUrl).href;
747
+ const catalog = await get(catalogUrl, {
748
+ timeout, maxRedirects: 0, headers: { Accept: "application/linkset+json" },
749
+ });
750
+ if (catalog.ok) {
751
+ const excluded = new Set([...allProbedUrls, ...scriptCandidates, ...candidates, catalogUrl]);
752
+ const listed = catalogCandidates(catalog, excluded);
753
+ // A catalog too large to parse may still point to a spec.
754
+ if (listed === OVERSIZED)
755
+ unavailable = true;
756
+ else {
757
+ const discovered = await probeSpecCandidates(get, detect, listed, timeout, catalog.url);
758
+ if (discovered)
759
+ return discovered;
316
760
  }
317
761
  }
318
762
  // Phase 4: Check spec-path responses for 401/403 (not bot_protected)
319
- for (let i = 0; i < specPathResponses.length; i++) {
320
- const response = specPathResponses[i];
321
- if (isProtectedResponse(response)) {
763
+ const protectedIndex = specPathDenied.indexOf(true);
764
+ if (protectedIndex !== -1) {
765
+ const control = await get(new URL("milieu-openapi-control" + (SPEC_PATHS[protectedIndex].match(/\.[a-z]+$/)?.[0] ?? ""), new URL(SPEC_PATHS[protectedIndex], baseUrl)).href, {
766
+ timeout, headers: { Accept: "application/json, application/yaml, */*" },
767
+ });
768
+ if (missingControl(control)) {
322
769
  return {
323
770
  check: {
324
771
  id,
325
772
  label,
326
773
  status: "partial",
327
774
  detail: "OpenAPI spec appears to exist but requires authentication",
328
- data: { protected: true, path: SPEC_PATHS[i] },
775
+ data: { protected: true, path: SPEC_PATHS[protectedIndex] },
329
776
  },
330
777
  detected: true,
331
778
  hasWebhooks: false,
332
779
  hasCallbacks: false,
333
- parsedSpec: null,
780
+ specText: null,
334
781
  };
335
782
  }
336
783
  }
337
- // Phase 5: APIs.guru public registry lookup
338
- // Catches companies like Stripe that publish specs on GitHub rather than
339
- // self-hosting at a standard path on their own domain.
340
- const domain = new URL(baseUrl).hostname;
341
- const registry = await lookupApisGuru(domain, timeout);
342
- budgetDenied ||= registry.budgetDenied;
343
- if (registry.specUrl) {
344
- return {
345
- check: {
346
- id,
347
- label,
348
- status: "partial",
349
- detail: "OpenAPI spec found via APIs.guru registry (not self-hosted on domain)",
350
- data: { specUrl: registry.specUrl, registry: "apis.guru" },
351
- why: "The spec exists but isn't directly discoverable from your domain — AI agents navigating your site won't find it without going through an external registry.",
352
- },
353
- detected: true,
354
- hasWebhooks: false,
355
- hasCallbacks: false,
356
- parsedSpec: null,
357
- };
358
- }
359
784
  // Phase 6: Budget starvation is not evidence of absence — probes that
360
785
  // never ran cannot prove the spec is missing.
361
- if (budgetDenied) {
786
+ if (uninspectable || budgetDenied || unavailable) {
362
787
  return {
363
788
  check: {
364
789
  id,
365
790
  label,
366
791
  status: "error",
367
- detail: "OpenAPI discovery incomplete: scan request budget exhausted",
792
+ data: { measured: false },
793
+ detail: uninspectable ? "OpenAPI spec candidate found but too large or too deeply nested to inspect"
794
+ : budgetDenied ? "OpenAPI discovery incomplete: scan request budget exhausted"
795
+ : "OpenAPI discovery incomplete: one or more sources could not be fully read",
368
796
  },
369
797
  detected: false,
370
798
  hasWebhooks: false,
371
799
  hasCallbacks: false,
372
- parsedSpec: null,
800
+ specText: null,
373
801
  };
374
802
  }
375
803
  // Phase 7: No valid spec found at any path
@@ -379,11 +807,33 @@ export async function checkOpenApi(baseUrl, timeout, sitemapCandidateUrls = [])
379
807
  label,
380
808
  status: "fail",
381
809
  detail: "No OpenAPI spec found",
810
+ data: { measured: true },
382
811
  },
383
812
  detected: false,
384
813
  hasWebhooks: false,
385
814
  hasCallbacks: false,
386
- parsedSpec: null,
815
+ specText: null,
387
816
  };
388
817
  }
389
- //# sourceMappingURL=openapi.js.map
818
+ export async function withRegistry(local, baseUrl, timeout, enabled = true) {
819
+ if (local.detected)
820
+ return local;
821
+ const specUrl = enabled ? await lookupApisGuru(httpGet, new URL(baseUrl).hostname, timeout) : undefined;
822
+ if (!specUrl) {
823
+ const registryState = !enabled ? "disabled" : specUrl === null ? "unlisted" : "unavailable";
824
+ const data = { ...local.check.data, registryState };
825
+ return { ...local, check: { ...local.check, data } };
826
+ }
827
+ return {
828
+ ...local, detected: true,
829
+ check: { id: "openapi_spec", label: "OpenAPI Spec", status: "partial",
830
+ detail: "OpenAPI spec found via APIs.guru registry (not self-hosted on domain)",
831
+ data: { specUrl, registry: "apis.guru", registryState: "listed" },
832
+ why: "The registry lists an API description. Publishing a link on the product makes that description discoverable to visiting agents.",
833
+ },
834
+ };
835
+ }
836
+ export async function checkOpenApi(baseUrl, timeout, sitemapCandidateUrls = [], registryLookup = true, homepage) {
837
+ const local = await discoverSelfHosted(baseUrl, timeout, sitemapCandidateUrls, homepage);
838
+ return withRegistry(local, baseUrl, timeout, registryLookup);
839
+ }