literally-aeo 0.2.0 → 0.2.2

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 (272) hide show
  1. package/README.md +29 -1
  2. package/dist/author-tools.js +479 -397
  3. package/dist/cli.mjs +808 -386
  4. package/dist/lib/access/schema.js +6 -6
  5. package/dist/lib/agents/author-schema.js +10 -10
  6. package/dist/lib/agents/author-validation.js +20 -18
  7. package/dist/lib/agents/copy-validation.js +22 -21
  8. package/dist/lib/agents/copywriter-input.js +23 -8
  9. package/dist/lib/agents/facts.js +22 -7
  10. package/dist/lib/agents/narrative-facts.js +20 -2
  11. package/dist/lib/agents/verifier.js +25 -24
  12. package/dist/lib/analysis/domain-classifier.js +19 -20
  13. package/dist/lib/analysis/domain-labels.js +10 -10
  14. package/dist/lib/analysis/progress-schema.js +2 -2
  15. package/dist/lib/analysis/progress.js +18 -19
  16. package/dist/lib/analysis/retrieval.js +20 -3
  17. package/dist/lib/analysis/scoring.js +20 -3
  18. package/dist/lib/analysis/search-analyzer.js +19 -5
  19. package/dist/lib/analysis/sentiment.js +16 -17
  20. package/dist/lib/author/examples.js +11 -11
  21. package/dist/lib/bundle/contracts.js +14 -12
  22. package/dist/lib/bundle/export.js +27 -27
  23. package/dist/lib/bundle/isolation.js +2 -2
  24. package/dist/lib/bundle/journal.js +13 -13
  25. package/dist/lib/bundle/project-journal.js +17 -17
  26. package/dist/lib/bundle/project.js +25 -25
  27. package/dist/lib/bundle/read.js +28 -28
  28. package/dist/lib/bundle/recorder.js +15 -15
  29. package/dist/lib/bundle/redact.js +13 -13
  30. package/dist/lib/bundle/trace-coverage.js +13 -13
  31. package/dist/lib/bundle/verify-integrity.js +15 -15
  32. package/dist/lib/bundle/verify-measurement.js +21 -21
  33. package/dist/lib/bundle/verify-report.js +29 -29
  34. package/dist/lib/bundle/verify.js +37 -37
  35. package/dist/lib/capture-manifest.js +12 -12
  36. package/dist/lib/checks/crawler-access.js +4 -1
  37. package/dist/lib/checks/money-pages.js +13 -0
  38. package/dist/lib/checks/renderability.js +5 -1
  39. package/dist/lib/checks/run-checks.js +21 -18
  40. package/dist/lib/chunks/{chunk-BSRKN6FU.js → chunk-2FOKEIIN.js} +1 -1
  41. package/dist/lib/chunks/{chunk-JXMDOAKA.js → chunk-2KH7LNK7.js} +11 -11
  42. package/dist/lib/chunks/{chunk-D3GE3OCB.js → chunk-3CMPR6ZZ.js} +1 -1
  43. package/dist/lib/chunks/{chunk-TJQ5OPLQ.js → chunk-3OE4UQIB.js} +7 -7
  44. package/dist/lib/chunks/{chunk-Y4OGZ3Q5.js → chunk-46PVVQYR.js} +1 -1
  45. package/dist/lib/chunks/{chunk-OU73OUX4.js → chunk-4GLW3ZRO.js} +67 -7
  46. package/dist/lib/chunks/{chunk-EV4DRS5M.js → chunk-4XIAXX7K.js} +1 -1
  47. package/dist/lib/chunks/{chunk-IBOWGKN7.js → chunk-52F5XYOW.js} +1 -1
  48. package/dist/lib/chunks/{chunk-FFOVLI3U.js → chunk-66T7JC57.js} +12 -10
  49. package/dist/lib/chunks/{chunk-IE7NAL6B.js → chunk-6HMHXSCS.js} +2 -2
  50. package/dist/lib/chunks/chunk-75DMLOQ7.js +127 -0
  51. package/dist/lib/chunks/{chunk-6G25V4CF.js → chunk-7CW6U5WJ.js} +1 -1
  52. package/dist/lib/chunks/{chunk-CUYVHXHI.js → chunk-7DNLRXEY.js} +3 -3
  53. package/dist/lib/chunks/{chunk-622NMXN6.js → chunk-7HM6IZ3L.js} +2 -2
  54. package/dist/lib/chunks/{chunk-F4W5YHDZ.js → chunk-7WO3FFPS.js} +2 -2
  55. package/dist/lib/chunks/{chunk-ULRXHSJL.js → chunk-7YDXD4MD.js} +9 -6
  56. package/dist/lib/chunks/{chunk-UEMZYHYJ.js → chunk-7YZPEX3T.js} +2 -2
  57. package/dist/lib/chunks/{chunk-OBXAHX3L.js → chunk-AASWJR7Q.js} +1 -5
  58. package/dist/lib/chunks/{chunk-NCXSNHXX.js → chunk-AJO7XVXK.js} +12 -12
  59. package/dist/lib/chunks/{chunk-2GU6CNQI.js → chunk-AT3XMGES.js} +5 -5
  60. package/dist/lib/chunks/{chunk-MNWO7EHC.js → chunk-BFWK3TBN.js} +2 -2
  61. package/dist/lib/chunks/{chunk-BGOIPHJZ.js → chunk-BGAHZIL3.js} +18 -12
  62. package/dist/lib/chunks/{chunk-ZCOI3HE2.js → chunk-BRENK356.js} +1 -1
  63. package/dist/lib/chunks/{chunk-KJMU5KH4.js → chunk-BXF4OC74.js} +18 -9
  64. package/dist/lib/chunks/{chunk-5JPYM4MD.js → chunk-BYHXNFWN.js} +1 -1
  65. package/dist/lib/chunks/{chunk-NCLFZOZU.js → chunk-CH7OCYDL.js} +1 -1
  66. package/dist/lib/chunks/{chunk-OKL7GN2F.js → chunk-DL6YQDTE.js} +31 -5
  67. package/dist/lib/chunks/{chunk-PDS5KWO3.js → chunk-E2YTTB6Q.js} +56 -42
  68. package/dist/lib/chunks/{chunk-SDWYZM64.js → chunk-EDQTINTL.js} +5 -1
  69. package/dist/lib/chunks/{chunk-4PD65FRJ.js → chunk-EOO5RBUW.js} +3 -3
  70. package/dist/lib/chunks/chunk-ESEMYWUH.js +257 -0
  71. package/dist/lib/chunks/{chunk-YHS5IEVZ.js → chunk-F2NSJ6PG.js} +12 -8
  72. package/dist/lib/chunks/{chunk-BLKLPUYR.js → chunk-F7DBTXKG.js} +6 -6
  73. package/dist/lib/chunks/{chunk-EE26FNSY.js → chunk-FDM2YNQL.js} +1 -1
  74. package/dist/lib/chunks/{chunk-RJ5R6YYA.js → chunk-FJL2V6P5.js} +6 -6
  75. package/dist/lib/chunks/chunk-FK2JQHAX.js +30 -0
  76. package/dist/lib/chunks/{chunk-QHUDJVPJ.js → chunk-GLUGYZQO.js} +7 -7
  77. package/dist/lib/chunks/{chunk-GNMFJ2OK.js → chunk-HCUJ2J7P.js} +8 -8
  78. package/dist/lib/chunks/{chunk-2ROXN2EC.js → chunk-HGGOGCPX.js} +10 -10
  79. package/dist/lib/chunks/{chunk-VPZQGND4.js → chunk-HGGRPOSA.js} +3 -3
  80. package/dist/lib/chunks/{chunk-EJ655TVU.js → chunk-I3UE52ZV.js} +2 -2
  81. package/dist/lib/chunks/{chunk-ML4W6KC6.js → chunk-J5NPHPXY.js} +5 -4
  82. package/dist/lib/chunks/{chunk-HFRAHG5C.js → chunk-J7QKT5E7.js} +17 -17
  83. package/dist/lib/chunks/{chunk-V7OAPKNF.js → chunk-JBOOD6MU.js} +10 -9
  84. package/dist/lib/chunks/{chunk-YAAUWCJ4.js → chunk-JKPBXPCW.js} +3 -3
  85. package/dist/lib/chunks/{chunk-5HT55QYX.js → chunk-JQDQVG3D.js} +1 -1
  86. package/dist/lib/chunks/{chunk-GESHTTSA.js → chunk-JYCVBFH5.js} +2 -2
  87. package/dist/lib/chunks/{chunk-W2VGLWTS.js → chunk-K2FZFESR.js} +10 -10
  88. package/dist/lib/chunks/{chunk-DC6PN7QJ.js → chunk-K4Y5NT4M.js} +11 -7
  89. package/dist/lib/chunks/chunk-K7YFL5KB.js +182 -0
  90. package/dist/lib/chunks/{chunk-EBUQPCKB.js → chunk-KFAT65P7.js} +1 -1
  91. package/dist/lib/chunks/{chunk-ZYSPTOKK.js → chunk-KQCRJIEG.js} +1 -1
  92. package/dist/lib/chunks/{chunk-R6XDZWUL.js → chunk-LR27H2HZ.js} +11 -11
  93. package/dist/lib/chunks/{chunk-FUAUPNRO.js → chunk-LTCDLURT.js} +7 -7
  94. package/dist/lib/chunks/{chunk-KZR25REO.js → chunk-LTI2YYU3.js} +1 -1
  95. package/dist/lib/chunks/{chunk-EPQHVILQ.js → chunk-MA27TFEY.js} +5 -3
  96. package/dist/lib/chunks/{chunk-UZJSTJFP.js → chunk-MENTBQGB.js} +6 -5
  97. package/dist/lib/chunks/chunk-MPJCZN4G.js +155 -0
  98. package/dist/lib/chunks/{chunk-BE4ENGUY.js → chunk-OOLWU667.js} +6 -6
  99. package/dist/lib/chunks/{chunk-QSJ4IKUF.js → chunk-PIF3GL62.js} +5 -5
  100. package/dist/lib/chunks/{chunk-W5X7WJYL.js → chunk-PIFTG6YW.js} +3 -3
  101. package/dist/lib/chunks/{chunk-YRBIC5QH.js → chunk-PKNODC6Y.js} +1 -1
  102. package/dist/lib/chunks/{chunk-SHUMCKCS.js → chunk-PWOYEIPF.js} +4 -4
  103. package/dist/lib/chunks/{chunk-RR46EDDR.js → chunk-QD3JXA3Y.js} +25 -25
  104. package/dist/lib/chunks/{chunk-7ZOJE6BH.js → chunk-QGZ4QSUE.js} +8 -7
  105. package/dist/lib/chunks/{chunk-D2INDP5W.js → chunk-R5UPOEWE.js} +9 -8
  106. package/dist/lib/chunks/{chunk-VKM6MMA4.js → chunk-RIJERFGU.js} +34 -3
  107. package/dist/lib/chunks/{chunk-5B3RNVZ6.js → chunk-RK57YZKM.js} +1 -1
  108. package/dist/lib/chunks/{chunk-GDKGZQ3T.js → chunk-RXSHKWZJ.js} +3 -3
  109. package/dist/lib/chunks/{chunk-NGHAP2P5.js → chunk-S6QOXJAL.js} +4 -4
  110. package/dist/lib/chunks/{chunk-6GHHNPFJ.js → chunk-SIJOQRRK.js} +1 -1
  111. package/dist/lib/chunks/{chunk-663HABKP.js → chunk-T6XZQOXS.js} +8 -8
  112. package/dist/lib/chunks/{chunk-EYKINDNK.js → chunk-TAPVCSCR.js} +1 -1
  113. package/dist/lib/chunks/{chunk-ISN6MBNB.js → chunk-U5USH2HB.js} +7 -7
  114. package/dist/lib/chunks/{chunk-MRL5RUP7.js → chunk-U6BW6LGX.js} +10 -3
  115. package/dist/lib/chunks/{chunk-L7MEIRJB.js → chunk-UNCUG2YS.js} +15 -6
  116. package/dist/lib/chunks/{chunk-3JO5TXBA.js → chunk-UYDQXXDQ.js} +4 -4
  117. package/dist/lib/chunks/{chunk-LOBXOZ2R.js → chunk-V5JJEEBT.js} +1 -1
  118. package/dist/lib/chunks/{chunk-XR44YSHT.js → chunk-VHKHYAC5.js} +30 -9
  119. package/dist/lib/chunks/{chunk-Z7V63UZA.js → chunk-VXDMOB7O.js} +4 -4
  120. package/dist/lib/chunks/{chunk-G62E525I.js → chunk-VXYQWE45.js} +2 -2
  121. package/dist/lib/chunks/{chunk-W5DC23OP.js → chunk-WCLKIPJV.js} +1 -1
  122. package/dist/lib/chunks/{chunk-7XO3SQAX.js → chunk-WDT2Y7D7.js} +1 -1
  123. package/dist/lib/chunks/{chunk-OVUCZLH2.js → chunk-WIBMVNIH.js} +2 -2
  124. package/dist/lib/chunks/{chunk-5T3V6XJS.js → chunk-WNIXDMJL.js} +1 -1
  125. package/dist/lib/chunks/{chunk-HTOD4W4E.js → chunk-WZGI7UVM.js} +2 -2
  126. package/dist/lib/chunks/{chunk-HQG63ZKO.js → chunk-XA27KAUV.js} +17 -17
  127. package/dist/lib/chunks/{chunk-I3XGRGXE.js → chunk-XAN4CRFP.js} +33 -41
  128. package/dist/lib/chunks/{chunk-AYY4MYTW.js → chunk-XFUYEFQP.js} +1 -1
  129. package/dist/lib/chunks/{chunk-FOCJ7HPC.js → chunk-XSER7WEB.js} +11 -11
  130. package/dist/lib/chunks/{chunk-WVACVWBL.js → chunk-YEUCAPKP.js} +6 -4
  131. package/dist/lib/chunks/{chunk-7Z27HQWL.js → chunk-YGLWQFKL.js} +3 -3
  132. package/dist/lib/chunks/{chunk-D7GEQVLL.js → chunk-YKJHFD64.js} +1 -1
  133. package/dist/lib/chunks/{chunk-OQU5IXAJ.js → chunk-ZOGIJGU3.js} +10 -10
  134. package/dist/lib/chunks/{chunk-5ZITQDVE.js → chunk-ZQ3ER7JD.js} +12 -13
  135. package/dist/lib/cli/bundle-commands.js +91 -88
  136. package/dist/lib/cli/run-commands.js +110 -105
  137. package/dist/lib/cli/status-command.js +77 -74
  138. package/dist/lib/codex-workflow/aggregate.js +21 -22
  139. package/dist/lib/codex-workflow/author-search.js +4 -3
  140. package/dist/lib/codex-workflow/author-tools.js +17 -15
  141. package/dist/lib/codex-workflow/author.js +38 -34
  142. package/dist/lib/codex-workflow/capture.js +25 -25
  143. package/dist/lib/codex-workflow/checkpoint.js +13 -13
  144. package/dist/lib/codex-workflow/checks.js +15 -16
  145. package/dist/lib/codex-workflow/copy-editor.js +31 -30
  146. package/dist/lib/codex-workflow/copy-recovery.js +11 -11
  147. package/dist/lib/codex-workflow/copy.js +28 -27
  148. package/dist/lib/codex-workflow/finish.js +34 -34
  149. package/dist/lib/codex-workflow/loop.js +65 -62
  150. package/dist/lib/codex-workflow/quality.js +11 -11
  151. package/dist/lib/codex-workflow/run-inputs.js +12 -12
  152. package/dist/lib/codex-workflow/run-source.js +26 -23
  153. package/dist/lib/codex-workflow/schemas.js +11 -11
  154. package/dist/lib/codex-workflow/session.js +14 -14
  155. package/dist/lib/codex-workflow/stage.js +45 -41
  156. package/dist/lib/codex-workflow/workdir.js +13 -13
  157. package/dist/lib/engine/audit-file.js +16 -11
  158. package/dist/lib/engine/author.js +53 -49
  159. package/dist/lib/engine/cost-estimate.js +18 -16
  160. package/dist/lib/engine/local-run.js +76 -73
  161. package/dist/lib/engine/preflight.js +12 -12
  162. package/dist/lib/engine/rejudge.js +82 -79
  163. package/dist/lib/engine/run-status.js +77 -74
  164. package/dist/lib/engine/templates.js +17 -12
  165. package/dist/lib/grounding/chromium-guard.js +13 -0
  166. package/dist/lib/grounding/controller.js +11 -10
  167. package/dist/lib/grounding/extract.js +10 -9
  168. package/dist/lib/grounding/fetch.js +4 -7
  169. package/dist/lib/grounding/file-store.js +5 -5
  170. package/dist/lib/grounding/grounding-runtime.js +32 -31
  171. package/dist/lib/grounding/guarded-request.js +18 -0
  172. package/dist/lib/grounding/model.js +9 -8
  173. package/dist/lib/grounding/profile.js +4 -4
  174. package/dist/lib/grounding/recorded-tools.js +16 -16
  175. package/dist/lib/grounding/session.js +3 -3
  176. package/dist/lib/grounding/tools.js +4 -3
  177. package/dist/lib/grounding/validation.js +2 -2
  178. package/dist/lib/harness/report/artifacts.js +11 -11
  179. package/dist/lib/harness/report/capture-coverage.js +4 -4
  180. package/dist/lib/lib/checkpoint.js +10 -10
  181. package/dist/lib/lib/progress-comparison.js +2 -2
  182. package/dist/lib/models/batching.js +3 -3
  183. package/dist/lib/models/structured.js +2 -2
  184. package/dist/lib/models/supported-models.js +1 -1
  185. package/dist/lib/pipeline.js +20 -21
  186. package/dist/lib/probes/agent-clis.js +10 -10
  187. package/dist/lib/probes/probes.js +12 -12
  188. package/dist/lib/probes/web-tool-guard.js +3 -3
  189. package/dist/lib/report/contracts.js +4 -4
  190. package/dist/lib/report/core/progress-comparison.js +2 -2
  191. package/dist/lib/report/core/progress-schema.js +2 -2
  192. package/dist/lib/report/core/schema.js +2 -4
  193. package/dist/lib/report/core/surfaces.js +1 -3
  194. package/dist/lib/runner.js +23 -24
  195. package/dist/lib/schema.js +19 -13
  196. package/dist/lib/section-result.js +14 -15
  197. package/dist/lib/stores/artifacts.js +17 -17
  198. package/dist/lib/stores/files.js +31 -31
  199. package/dist/lib/stores/local-versions.js +10 -10
  200. package/dist/lib/stores/memory.js +33 -33
  201. package/dist/lib/stores/publication.js +23 -22
  202. package/dist/lib/surfaces.js +1 -3
  203. package/dist/lib/viewer/server.js +38 -38
  204. package/dist/lib/workflow/schema.js +8 -8
  205. package/dist/types/agents/author-schema.d.ts +3 -3
  206. package/dist/types/analysis/scoring.d.ts +2 -2
  207. package/dist/types/bundle/contracts.d.ts +3 -2
  208. package/dist/types/checks/crawler-access.d.ts +3 -2
  209. package/dist/types/checks/money-pages.d.ts +19 -0
  210. package/dist/types/checks/renderability.d.ts +8 -1
  211. package/dist/types/codex-workflow/author-tools.d.ts +3 -3
  212. package/dist/types/codex-workflow/run-inputs.d.ts +3 -0
  213. package/dist/types/codex-workflow/schemas.d.ts +6 -6
  214. package/dist/types/engine/audit-file.d.ts +6 -1
  215. package/dist/types/engine/preflight.d.ts +2 -0
  216. package/dist/types/grounding/chromium-guard.d.ts +41 -0
  217. package/dist/types/grounding/fetch.d.ts +0 -10
  218. package/dist/types/grounding/guarded-request.d.ts +76 -0
  219. package/dist/types/harness/report/artifacts.d.ts +1 -0
  220. package/dist/types/lib/checkpoint.d.ts +5 -6
  221. package/dist/types/pipeline.d.ts +2 -1
  222. package/dist/types/probes/probes.d.ts +2 -1
  223. package/dist/types/report/contracts.d.ts +2 -0
  224. package/dist/types/report/core/schema.d.ts +3 -1
  225. package/dist/types/report/core/surfaces.d.ts +0 -1
  226. package/dist/types/schema.d.ts +22 -0
  227. package/dist/types/section-result.d.ts +1 -1
  228. package/package.json +1 -1
  229. package/resources/guide/OPERATOR.md +12 -3
  230. package/src/agents/author-schema.ts +13 -1
  231. package/src/agents/author-validation.ts +24 -6
  232. package/src/agents/facts.ts +8 -8
  233. package/src/agents/narrative-facts.ts +9 -20
  234. package/src/agents/verifier.ts +2 -2
  235. package/src/analysis/progress.ts +1 -0
  236. package/src/analysis/scoring.ts +9 -13
  237. package/src/bundle/contracts.ts +7 -2
  238. package/src/bundle/verify.ts +3 -3
  239. package/src/capture-manifest.ts +4 -0
  240. package/src/checks/crawler-access.ts +70 -50
  241. package/src/checks/money-pages.ts +48 -0
  242. package/src/checks/renderability.ts +113 -87
  243. package/src/checks/run-checks.ts +16 -3
  244. package/src/cli/run-commands.ts +2 -0
  245. package/src/codex-workflow/aggregate.ts +1 -0
  246. package/src/codex-workflow/author-tools.ts +39 -60
  247. package/src/codex-workflow/capture.ts +1 -0
  248. package/src/codex-workflow/copy-editor.ts +3 -3
  249. package/src/codex-workflow/loop.ts +2 -2
  250. package/src/engine/audit-file.ts +79 -2
  251. package/src/engine/guide/OPERATOR.md +12 -3
  252. package/src/engine/preflight.ts +50 -0
  253. package/src/grounding/chromium-guard.ts +273 -0
  254. package/src/grounding/controller.ts +1 -1
  255. package/src/grounding/fetch.ts +39 -276
  256. package/src/grounding/guarded-request.ts +428 -0
  257. package/src/grounding/tools.ts +2 -1
  258. package/src/grounding/validation.ts +1 -1
  259. package/src/lib/checkpoint.ts +15 -16
  260. package/src/models/supported-models.ts +3 -3
  261. package/src/pipeline.ts +13 -7
  262. package/src/probes/agent-clis.ts +2 -3
  263. package/src/probes/probes.ts +24 -10
  264. package/src/report/core/schema.ts +4 -1
  265. package/src/report/core/surfaces.ts +4 -8
  266. package/src/runner.ts +1 -0
  267. package/src/schema.ts +68 -4
  268. package/src/section-result.ts +6 -5
  269. package/dist/lib/chunks/chunk-6EH4N3EU.js +0 -113
  270. package/dist/lib/chunks/chunk-SWJ7KQSL.js +0 -318
  271. package/dist/lib/chunks/{chunk-CO5T6WU5.js → chunk-OD36HUXA.js} +3 -3
  272. package/dist/lib/chunks/{chunk-XI5H46DF.js → chunk-SASE7U6E.js} +3 -3
@@ -0,0 +1,273 @@
1
+ import type { LookupAddress } from 'node:dns';
2
+ import { createServer } from 'node:http';
3
+ import { connect, type Socket } from 'node:net';
4
+ import type { Duplex } from 'node:stream';
5
+ import type { BrowserContext, Page, Request } from 'playwright';
6
+ import {
7
+ resolvePublicAddress,
8
+ validateResearchUrl,
9
+ type LookupAll,
10
+ } from './guarded-request';
11
+
12
+ // ============================================================================
13
+ // Chromium behind the guard (specs/aeo-checks-and-reach-spec.md §3.2). A
14
+ // route handler alone does not hold: it sees only the first URL of a
15
+ // redirect, never resolves subresource host names, and WebSockets and
16
+ // service workers pass beside it. So the browser's every connection goes
17
+ // through a forward proxy on 127.0.0.1 that applies guardedRequest's rule
18
+ // per connection: port 443, a public host, every DNS answer public, the
19
+ // socket pinned to the checked address. The proxy tunnels TLS; it never
20
+ // sees page content.
21
+ // ============================================================================
22
+
23
+ const connectTimeoutInMs = 15_000;
24
+
25
+ export type ConnectionCounts = { allowed: number; refused: number };
26
+
27
+ export type GuardingProxyOptions = {
28
+ /** Test seam: the DNS answers for a host. */
29
+ lookupHost?: LookupAll;
30
+ /** Test seam: where an allowed connection is dialled. */
31
+ dial?: (address: LookupAddress) => Socket;
32
+ };
33
+
34
+ export type GuardingProxy = {
35
+ server: string;
36
+ counts: () => ConnectionCounts;
37
+ close: () => Promise<void>;
38
+ };
39
+
40
+ const dialPublicAddress = (address: LookupAddress): Socket => {
41
+ return connect({ host: address.address, port: 443, family: address.family });
42
+ };
43
+
44
+ /** The CONNECT authority as a guarded https URL, or undefined if refused. */
45
+ const toConnectTarget = (authority: string): URL | undefined => {
46
+ const separator = authority.lastIndexOf(':');
47
+
48
+ if (separator < 0 || authority.slice(separator + 1) !== '443') {
49
+ return undefined;
50
+ }
51
+
52
+ try {
53
+ return validateResearchUrl(`https://${authority.slice(0, separator)}/`);
54
+ } catch {
55
+ return undefined;
56
+ }
57
+ };
58
+
59
+ /** startGuardingProxy listens on a free loopback port until closed. */
60
+ export const startGuardingProxy = async (
61
+ options: GuardingProxyOptions = {},
62
+ ): Promise<GuardingProxy> => {
63
+ const { lookupHost, dial = dialPublicAddress } = options;
64
+ const counts: ConnectionCounts = { allowed: 0, refused: 0 };
65
+ const sockets = new Set<Duplex>();
66
+
67
+ const refuse = (client: Duplex) => {
68
+ counts.refused += 1;
69
+ client.end('HTTP/1.1 403 Forbidden\r\n\r\n');
70
+ };
71
+
72
+ // Only CONNECT tunnels are served: a plain http request is refused.
73
+ const server = createServer((_request, response) => {
74
+ counts.refused += 1;
75
+ response.writeHead(403).end();
76
+ });
77
+
78
+ const tunnel = async (authority: string, client: Duplex, head: Buffer) => {
79
+ const target = toConnectTarget(authority);
80
+
81
+ if (!target) {
82
+ refuse(client);
83
+
84
+ return;
85
+ }
86
+
87
+ let address: LookupAddress;
88
+
89
+ try {
90
+ address = await resolvePublicAddress(
91
+ target.hostname,
92
+ AbortSignal.timeout(connectTimeoutInMs),
93
+ lookupHost,
94
+ );
95
+ } catch {
96
+ refuse(client);
97
+
98
+ return;
99
+ }
100
+
101
+ counts.allowed += 1;
102
+
103
+ const upstream = dial(address);
104
+
105
+ sockets.add(upstream);
106
+ upstream.setTimeout(connectTimeoutInMs, () => {
107
+ upstream.destroy();
108
+ });
109
+ upstream.once('connect', () => {
110
+ upstream.setTimeout(0);
111
+ client.write('HTTP/1.1 200 Connection Established\r\n\r\n');
112
+ upstream.write(head);
113
+ upstream.pipe(client);
114
+ client.pipe(upstream);
115
+ });
116
+ upstream.once('error', () => {
117
+ client.end('HTTP/1.1 502 Bad Gateway\r\n\r\n');
118
+ });
119
+ upstream.once('close', () => {
120
+ sockets.delete(upstream);
121
+ client.destroy();
122
+ });
123
+ client.once('close', () => {
124
+ upstream.destroy();
125
+ });
126
+ };
127
+
128
+ server.on('connection', (socket: Socket) => {
129
+ sockets.add(socket);
130
+ socket.once('close', () => {
131
+ sockets.delete(socket);
132
+ });
133
+ });
134
+ server.on('connect', (request, client: Duplex, head: Buffer) => {
135
+ client.on('error', () => {
136
+ client.destroy();
137
+ });
138
+ void tunnel(request.url ?? '', client, head);
139
+ });
140
+ // A ws:// upgrade asked of the proxy itself, not tunnelled.
141
+ server.on('upgrade', (_request, client: Duplex) => {
142
+ refuse(client);
143
+ });
144
+
145
+ await new Promise<void>((resolve, reject) => {
146
+ server.once('error', reject);
147
+ server.listen(0, '127.0.0.1', resolve);
148
+ });
149
+
150
+ const address = server.address();
151
+
152
+ if (address === null || typeof address === 'string') {
153
+ throw new Error('The guarding proxy did not bind a TCP port.');
154
+ }
155
+
156
+ return {
157
+ server: `http://127.0.0.1:${address.port}`,
158
+ counts: () => ({ ...counts }),
159
+ close: async () => {
160
+ for (const socket of sockets) {
161
+ socket.destroy();
162
+ }
163
+
164
+ await new Promise<void>((resolve) => {
165
+ server.close(() => {
166
+ resolve();
167
+ });
168
+ });
169
+ },
170
+ };
171
+ };
172
+
173
+ const chromiumArgs = [
174
+ // Playwright proxies loopback too unless an environment variable turns
175
+ // that off; this flag comes last and keeps it on regardless.
176
+ '--proxy-bypass-list=<-loopback>',
177
+ // QUIC and WebRTC over UDP would leave beside an HTTP proxy.
178
+ '--disable-quic',
179
+ '--force-webrtc-ip-handling-policy=disable_non_proxied_udp',
180
+ ];
181
+
182
+ /** What a guarded page may request at all, before the proxy decides. */
183
+ const isAllowedRequest = (request: Request): boolean => {
184
+ const url = new URL(request.url());
185
+
186
+ return (
187
+ url.protocol === 'https:' &&
188
+ url.port === '' &&
189
+ request.resourceType() !== 'media'
190
+ );
191
+ };
192
+
193
+ /**
194
+ * withBoundedPage runs `use` on a new page of the context, then closes it.
195
+ * A page that freezes its main thread never answers evaluate() or content(),
196
+ * and no Playwright timeout covers those calls; closing the page makes them
197
+ * fail. So past the deadline the page is closed and the render refused,
198
+ * instead of holding the run, and the host's turn in the pacer, forever.
199
+ */
200
+ export const withBoundedPage = async <T>(
201
+ context: Pick<BrowserContext, 'newPage'>,
202
+ deadlineInMs: number,
203
+ use: (page: Page) => Promise<T>,
204
+ ): Promise<T> => {
205
+ const page = await context.newPage();
206
+ const deadline = AbortSignal.timeout(deadlineInMs);
207
+ // The pending call fails with the closed page; that failure is reported.
208
+ const closePage = () => {
209
+ void page.close().catch(() => undefined);
210
+ };
211
+
212
+ deadline.addEventListener('abort', closePage, { once: true });
213
+
214
+ try {
215
+ return await use(page);
216
+ } catch (error) {
217
+ if (deadline.aborted) {
218
+ throw new Error(
219
+ `The page did not finish rendering within ${deadlineInMs / 1000} s.`,
220
+ { cause: error },
221
+ );
222
+ }
223
+
224
+ throw error;
225
+ } finally {
226
+ deadline.removeEventListener('abort', closePage);
227
+ await page.close();
228
+ }
229
+ };
230
+
231
+ /**
232
+ * withGuardedChromium runs `use` in a fresh browser context whose every
233
+ * connection passes the guarding proxy, then closes both. Downloads are
234
+ * refused, service workers blocked and media never loaded.
235
+ */
236
+ export const withGuardedChromium = async <T>(
237
+ use: (context: BrowserContext) => Promise<T>,
238
+ options: { userAgent?: string; proxy?: GuardingProxyOptions } = {},
239
+ ): Promise<{ result: T; connections: ConnectionCounts }> => {
240
+ const proxy = await startGuardingProxy(options.proxy);
241
+
242
+ try {
243
+ const { chromium } = await import('playwright');
244
+ const browser = await chromium.launch({
245
+ proxy: { server: proxy.server },
246
+ args: chromiumArgs,
247
+ });
248
+
249
+ try {
250
+ const context = await browser.newContext({
251
+ acceptDownloads: false,
252
+ serviceWorkers: 'block',
253
+ ...(options.userAgent !== undefined && {
254
+ userAgent: options.userAgent,
255
+ }),
256
+ });
257
+
258
+ await context.route('**/*', (route) => {
259
+ return isAllowedRequest(route.request())
260
+ ? route.continue()
261
+ : route.abort();
262
+ });
263
+
264
+ const result = await use(context);
265
+
266
+ return { result, connections: proxy.counts() };
267
+ } finally {
268
+ await browser.close();
269
+ }
270
+ } finally {
271
+ await proxy.close();
272
+ }
273
+ };
@@ -4,7 +4,7 @@ import {
4
4
  ModelBudgetError,
5
5
  type ModelCallAccounting,
6
6
  } from '../models/accounting';
7
- import { SourceRetrievalError } from './fetch';
7
+ import { SourceRetrievalError } from './guarded-request';
8
8
  import { proposedAssessmentSchema } from './model';
9
9
  import {
10
10
  adjudicationVersion,
@@ -1,9 +1,10 @@
1
- import { lookup } from 'node:dns/promises';
2
- import { isIP } from 'node:net';
3
- import { request } from 'node:https';
4
1
  import { load } from 'cheerio';
5
2
  import { contentHash } from '../stores/content-hash';
6
- import { isPublicAddress } from '../workflow/callbacks';
3
+ import {
4
+ guardedRequest,
5
+ SourceRetrievalError,
6
+ validateResearchUrl,
7
+ } from './guarded-request';
7
8
  import { sourceExtractionVersion, type GroundingSource } from './schema';
8
9
 
9
10
  export const sourceLimits = {
@@ -13,74 +14,6 @@ export const sourceLimits = {
13
14
  redirects: 3,
14
15
  } as const;
15
16
 
16
- export type SourceRetrievalReason =
17
- | 'unsafe_destination'
18
- | 'timeout'
19
- | 'too_large'
20
- | 'unsupported_content'
21
- | 'http_error'
22
- | 'empty_content'
23
- | 'network_error';
24
-
25
- export class SourceRetrievalError extends Error {
26
- readonly reason: SourceRetrievalReason;
27
- readonly status: number | undefined;
28
-
29
- constructor(
30
- reason: SourceRetrievalReason,
31
- message: string,
32
- { status, cause }: { status?: number; cause?: unknown } = {},
33
- ) {
34
- super(message, cause === undefined ? undefined : { cause });
35
- this.name = 'SourceRetrievalError';
36
- this.reason = reason;
37
- this.status = status;
38
- }
39
- }
40
-
41
- export const validateResearchUrl = (value: string): URL => {
42
- let url: URL;
43
-
44
- try {
45
- url = new URL(value);
46
- } catch {
47
- throw new SourceRetrievalError(
48
- 'unsafe_destination',
49
- `Invalid source URL: ${value}.`,
50
- );
51
- }
52
-
53
- if (
54
- url.protocol !== 'https:' ||
55
- url.username ||
56
- url.password ||
57
- url.port ||
58
- url.hostname === 'localhost' ||
59
- url.hostname.endsWith('.localhost') ||
60
- url.hostname.endsWith('.local') ||
61
- url.hostname.endsWith('.internal') ||
62
- url.hostname === 'metadata.google.internal'
63
- ) {
64
- throw new SourceRetrievalError(
65
- 'unsafe_destination',
66
- `Source must use public HTTPS with no credentials: ${url.hostname}.`,
67
- );
68
- }
69
-
70
- const host = url.hostname.replace(/^\[|\]$/g, '');
71
-
72
- if (isIP(host) && !isPublicAddress(host)) {
73
- throw new SourceRetrievalError(
74
- 'unsafe_destination',
75
- `Private source destination: ${host}.`,
76
- );
77
- }
78
-
79
- url.hash = '';
80
-
81
- return url;
82
- };
83
-
84
17
  /**
85
18
  * canonicalResearchUrl returns a URL as research receipts compare it: no
86
19
  * hash, lowercase host, no trailing slash on a path. The author's journal, its
@@ -99,155 +32,6 @@ export const canonicalResearchUrl = (value: string): string => {
99
32
  return url.href;
100
33
  };
101
34
 
102
- const withAbort = <T>(promise: Promise<T>, signal: AbortSignal): Promise<T> => {
103
- signal.throwIfAborted();
104
-
105
- return new Promise((resolve, reject) => {
106
- const aborted = () => {
107
- // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- AbortSignal.reason is typed any; rejecting with it keeps the caller's abort error.
108
- reject(signal.reason);
109
- };
110
-
111
- signal.addEventListener('abort', aborted, { once: true });
112
-
113
- promise.then(resolve, reject).finally(() => {
114
- signal.removeEventListener('abort', aborted);
115
- });
116
- });
117
- };
118
-
119
- const requestDocument = async (
120
- url: URL,
121
- signal: AbortSignal,
122
- ): Promise<{
123
- status: number;
124
- location?: string;
125
- contentType: string;
126
- body: string;
127
- }> => {
128
- const host = url.hostname.replace(/^\[|\]$/g, '');
129
- const addresses = await withAbort(lookup(host, { all: true }), signal);
130
-
131
- if (
132
- addresses.length === 0 ||
133
- addresses.some(({ address }) => !isPublicAddress(address))
134
- ) {
135
- throw new SourceRetrievalError(
136
- 'unsafe_destination',
137
- `Source DNS must resolve exclusively to public addresses: ${host}.`,
138
- );
139
- }
140
-
141
- const [firstAddress] = addresses;
142
-
143
- if (!firstAddress) {
144
- throw new SourceRetrievalError(
145
- 'unsafe_destination',
146
- `Source DNS returned no address: ${host}.`,
147
- );
148
- }
149
-
150
- signal.throwIfAborted();
151
-
152
- return new Promise((resolve, reject) => {
153
- const req = request(
154
- url,
155
- {
156
- method: 'GET',
157
- signal,
158
- headers: {
159
- 'accept': 'text/html,text/plain',
160
- 'accept-encoding': 'identity',
161
- 'user-agent': 'Literally-AEO-Research/1',
162
- },
163
- lookup: (_host, options, callback) => {
164
- if (options.all) {
165
- callback(null, [firstAddress]);
166
- } else {
167
- callback(null, firstAddress.address, firstAddress.family);
168
- }
169
- },
170
- },
171
- (response) => {
172
- const status = response.statusCode ?? 0;
173
- const contentType = response.headers['content-type'] ?? '';
174
-
175
- if (status >= 300 && status < 400) {
176
- response.destroy();
177
- resolve({
178
- status,
179
- location: response.headers.location,
180
- contentType,
181
- body: '',
182
- });
183
-
184
- return;
185
- }
186
-
187
- if (status < 200 || status >= 300) {
188
- response.destroy();
189
- reject(
190
- new SourceRetrievalError('http_error', `Source HTTP ${status}.`, {
191
- status,
192
- }),
193
- );
194
-
195
- return;
196
- }
197
-
198
- if (
199
- !/^(text\/html|text\/plain|application\/xhtml\+xml)(;|$)/i.test(
200
- contentType,
201
- ) ||
202
- (response.headers['content-encoding'] &&
203
- response.headers['content-encoding'] !== 'identity')
204
- ) {
205
- response.destroy();
206
- reject(
207
- new SourceRetrievalError(
208
- 'unsupported_content',
209
- `Unsupported source content: ${contentType}.`,
210
- ),
211
- );
212
-
213
- return;
214
- }
215
-
216
- const chunks: Buffer[] = [];
217
- let bytes = 0;
218
- response.on('data', (chunk: Buffer) => {
219
- bytes += chunk.length;
220
-
221
- if (bytes > sourceLimits.receivedBytes) {
222
- response.destroy();
223
- reject(
224
- new SourceRetrievalError(
225
- 'too_large',
226
- `Source response exceeds byte limit: ${bytes} bytes.`,
227
- ),
228
- );
229
-
230
- return;
231
- }
232
-
233
- chunks.push(chunk);
234
- });
235
-
236
- response.once('error', reject);
237
- response.once('end', () => {
238
- resolve({
239
- status,
240
- contentType,
241
- body: Buffer.concat(chunks).toString('utf8'),
242
- });
243
- });
244
- },
245
- );
246
- req.once('error', reject);
247
- req.end();
248
- });
249
- };
250
-
251
35
  /**
252
36
  * boundedUtf8 returns the longest prefix of the text within the byte budget,
253
37
  * never ending inside a multibyte character.
@@ -382,67 +166,46 @@ export const fetchGroundingSource = async (args: {
382
166
  /** Body bytes received for the final document. */
383
167
  bytes: number;
384
168
  }> => {
385
- const signal = AbortSignal.any([
386
- AbortSignal.timeout(sourceLimits.timeoutMs),
387
- ...(args.signal ? [args.signal] : []),
388
- ]);
389
- let url = validateResearchUrl(args.url);
390
-
391
- try {
392
- for (
393
- let redirects = 0;
394
- redirects <= sourceLimits.redirects;
395
- redirects += 1
396
- ) {
169
+ const response = await guardedRequest({
170
+ url: args.url,
171
+ timeoutInMs: sourceLimits.timeoutMs,
172
+ signal: args.signal,
173
+ userAgent: 'Literally-AEO-Research/1',
174
+ accept: 'text/html,text/plain',
175
+ redirects: sourceLimits.redirects,
176
+ body: {
177
+ contentTypes: /^(text\/html|text\/plain|application\/xhtml\+xml)(;|$)/i,
178
+ maxBytes: sourceLimits.receivedBytes,
179
+ oversize: 'refuse',
180
+ },
181
+ pace: async (_url, send) => {
397
182
  await args.beforeRequest?.();
398
- signal.throwIfAborted();
399
-
400
- const response = await requestDocument(url, signal);
401
-
402
- if (response.status >= 300 && response.status < 400) {
403
- if (!response.location || redirects === sourceLimits.redirects) {
404
- throw new SourceRetrievalError(
405
- 'http_error',
406
- `Source redirect limit exceeded: ${url.href}.`,
407
- );
408
- }
409
183
 
410
- url = validateResearchUrl(new URL(response.location, url).href);
411
-
412
- continue;
413
- }
414
-
415
- return {
416
- ...extractSourceDocument({
417
- requestedUrl: args.url,
418
- finalUrl: url.href,
419
- body: response.body,
420
- contentType: response.contentType,
421
- fetchedAt: new Date().toISOString(),
422
- firstPartyHosts: args.firstPartyHosts,
423
- }),
424
- requestCount: redirects + 1,
425
- bytes: Buffer.byteLength(response.body),
426
- };
427
- }
184
+ return send();
185
+ },
186
+ });
428
187
 
188
+ if (response.status < 200 || response.status >= 300) {
429
189
  throw new SourceRetrievalError(
430
190
  'http_error',
431
- `Source redirect limit exceeded: ${url.href}.`,
191
+ `Source HTTP ${response.status}.`,
192
+ { status: response.status },
432
193
  );
433
- } catch (error) {
434
- if (args.signal?.aborted) {
435
- throw args.signal.reason;
436
- }
194
+ }
437
195
 
438
- if (error instanceof SourceRetrievalError) {
439
- throw error;
440
- }
196
+ const body = response.body?.toString('utf8') ?? '';
197
+ const document = extractSourceDocument({
198
+ requestedUrl: args.url,
199
+ finalUrl: response.url,
200
+ body,
201
+ contentType: response.contentType,
202
+ fetchedAt: new Date().toISOString(),
203
+ firstPartyHosts: args.firstPartyHosts,
204
+ });
441
205
 
442
- throw new SourceRetrievalError(
443
- signal.aborted ? 'timeout' : 'network_error',
444
- `Source retrieval failed: ${url.href}.`,
445
- { cause: error },
446
- );
447
- }
206
+ return {
207
+ ...document,
208
+ requestCount: response.hops.length,
209
+ bytes: Buffer.byteLength(body),
210
+ };
448
211
  };