@preventive/triage 1.0.0-alpha.9 → 1.0.0-alpha.90

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 (448) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +16 -78
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +3 -0
  6. package/client/dependency-paths.js +36 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +115 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +6 -0
  13. package/common/bundle-compare-diff.js +378 -0
  14. package/common/bundle-compare-inputs.d.ts +3 -0
  15. package/common/bundle-compare-inputs.js +141 -0
  16. package/common/bundle-compare-versions.js +172 -0
  17. package/common/bundle-comparison.d.ts +8 -0
  18. package/common/bundle-comparison.js +69 -0
  19. package/common/bundle-imports.js +20 -0
  20. package/common/bundle-metadata.d.ts +15 -0
  21. package/common/bundle-metadata.js +226 -0
  22. package/common/bundle-pkg-of.d.ts +1 -0
  23. package/common/bundle-pkg-of.js +90 -0
  24. package/common/bundle-reasons.d.ts +6 -0
  25. package/common/bundle-reasons.js +58 -0
  26. package/common/bundle-source-links.d.ts +6 -0
  27. package/common/bundle-source-links.js +216 -0
  28. package/common/bundle-sourcemap.d.ts +10 -0
  29. package/common/bundle-sourcemap.js +100 -0
  30. package/common/bundle-sources.d.ts +10 -0
  31. package/common/bundle-sources.js +374 -0
  32. package/common/bundle-stats.js +41 -0
  33. package/common/bundle-tabs.js +1 -0
  34. package/common/code-language.js +80 -0
  35. package/common/default-scan-models.ts +37 -0
  36. package/common/dependency-reviews.d.ts +19 -0
  37. package/common/dependency-reviews.js +67 -0
  38. package/common/finding-duplicates.js +63 -0
  39. package/common/finding-filters.js +313 -0
  40. package/common/finding-id.js +47 -0
  41. package/common/finding-repo.d.ts +5 -0
  42. package/common/finding-repo.js +67 -0
  43. package/common/github-issue-labels.d.ts +3 -0
  44. package/common/github-issue-labels.js +42 -0
  45. package/common/github-pr.ts +56 -0
  46. package/common/gzip.js +59 -0
  47. package/common/line-diff.d.ts +15 -0
  48. package/common/line-diff.js +188 -0
  49. package/common/linked-workspace-groups.js +63 -0
  50. package/common/managed/agent-tasks.ts +292 -0
  51. package/common/managed/comments.ts +43 -0
  52. package/common/managed/dependency-routes.js +25 -0
  53. package/common/managed/directory-packages.ts +28 -0
  54. package/common/managed/finding-detail.d.ts +5 -0
  55. package/common/managed/finding-detail.js +75 -0
  56. package/common/managed/finding-values.d.ts +2 -0
  57. package/common/managed/finding-values.js +138 -0
  58. package/common/managed/github-agents.ts +114 -0
  59. package/common/managed/github-logins.ts +49 -0
  60. package/common/managed/lite-name.d.ts +2 -0
  61. package/common/managed/lite-name.js +20 -0
  62. package/common/managed/npm-packages.d.ts +9 -0
  63. package/common/managed/npm-packages.js +63 -0
  64. package/common/managed/permissions.ts +31 -0
  65. package/common/managed/report-content.ts +72 -0
  66. package/common/managed/report-filter.ts +120 -0
  67. package/common/managed/repository-alias.ts +65 -0
  68. package/common/managed/review-view-routes.js +23 -0
  69. package/common/managed/risk-routes.js +30 -0
  70. package/common/managed/roles.ts +48 -0
  71. package/common/managed/routes.d.ts +2 -0
  72. package/common/managed/routes.js +386 -0
  73. package/common/managed/scan-models.ts +6 -0
  74. package/common/managed/stasis-config.ts +7 -0
  75. package/common/managed/team-app.d.ts +19 -0
  76. package/common/managed/team-app.js +129 -0
  77. package/common/managed/team-filters.js +26 -0
  78. package/common/managed/triage.ts +83 -0
  79. package/common/managed/upload-seal.ts +126 -0
  80. package/common/npm-token.d.ts +2 -0
  81. package/common/npm-token.js +14 -0
  82. package/common/pretty-json.js +123 -0
  83. package/common/pretty-kinds.js +20 -0
  84. package/common/pretty-print.d.ts +7 -0
  85. package/common/pretty-print.js +41 -0
  86. package/common/pretty-sourcemap.js +70 -0
  87. package/common/repo-commit.d.ts +4 -0
  88. package/common/repo-commit.js +30 -0
  89. package/common/revalidation-conflicts.js +48 -0
  90. package/common/revalidation-input-groups.js +56 -0
  91. package/common/scan-server.ts +13 -0
  92. package/common/security-links.d.ts +5 -0
  93. package/common/security-links.js +33 -0
  94. package/common/server-info.ts +46 -0
  95. package/common/sourcemap-listing.js +78 -0
  96. package/common/sourcemap-mappings.js +136 -0
  97. package/common/sourcemap-unlist.js +85 -0
  98. package/common/stasis-files.d.ts +5 -0
  99. package/common/stasis-files.js +20 -0
  100. package/common/stasis-tgz.d.ts +6 -0
  101. package/common/stasis-tgz.js +27 -0
  102. package/common/utf8.d.ts +3 -0
  103. package/common/utf8.js +45 -0
  104. package/common/whitespace-insensitive.js +19 -0
  105. package/common/workspace-app.js +91 -0
  106. package/common/workspace-groups.js +176 -0
  107. package/out/activity.js +2 -0
  108. package/out/brotli-fallback.js +3 -3
  109. package/out/chunk-2XUEZHIP.js +28 -0
  110. package/out/chunk-3DOSBILK.js +4 -0
  111. package/out/chunk-55YIWY3H.js +5 -0
  112. package/out/chunk-5AVGKFMR.js +1 -0
  113. package/out/chunk-5PWEAEA5.js +1 -0
  114. package/out/chunk-6VOB5WXX.js +2 -0
  115. package/out/chunk-6Y6PZ2BU.js +9 -0
  116. package/out/chunk-74JZTGTO.js +11 -0
  117. package/out/chunk-7BKKYVWR.js +7 -0
  118. package/out/chunk-7C7DWL7I.js +1 -0
  119. package/out/chunk-7HP2VYIC.js +2 -0
  120. package/out/chunk-7YFJUT2P.js +1 -0
  121. package/out/chunk-A4BBBHQU.js +1 -0
  122. package/out/chunk-B64CTMVU.js +4 -0
  123. package/out/chunk-BEKYZCPX.js +14 -0
  124. package/out/chunk-BZJU5EEV.js +1 -0
  125. package/out/chunk-C4Z6ZBXV.js +10 -0
  126. package/out/chunk-CJVMNJDZ.js +3 -0
  127. package/out/chunk-CU3FPB3P.js +1 -0
  128. package/out/chunk-DEVAORP2.js +1 -0
  129. package/out/chunk-DUASGS2O.js +8 -0
  130. package/out/chunk-EEJA7JBI.js +13 -0
  131. package/out/chunk-ESXA7KID.js +1 -0
  132. package/out/chunk-FSU2PLJL.js +1 -0
  133. package/out/chunk-GO7FT4OD.js +1 -0
  134. package/out/chunk-GX5UXWT4.js +1 -0
  135. package/out/chunk-HGWFRZNC.js +267 -0
  136. package/out/chunk-IYPY47MC.js +1 -0
  137. package/out/chunk-JZAROLQT.js +40 -0
  138. package/out/chunk-K4XJHM2T.js +1 -0
  139. package/out/chunk-KP2XM324.js +6 -0
  140. package/out/chunk-LRWB6QVO.js +1 -0
  141. package/out/chunk-LVSLM7HB.js +1 -0
  142. package/out/chunk-LVW7WWV4.js +1 -0
  143. package/out/chunk-N57OWFKY.js +15 -0
  144. package/out/chunk-NRPC74AM.js +1 -0
  145. package/out/chunk-OOJM4CTU.js +1 -0
  146. package/out/chunk-PKLVXUEI.js +11 -0
  147. package/out/chunk-PLGH63UC.js +2 -0
  148. package/out/chunk-PNHBZGDD.js +1 -0
  149. package/out/chunk-PWFUOLZK.js +17 -0
  150. package/out/chunk-PXK7EU4V.js +1 -0
  151. package/out/chunk-QD3IBSF4.js +7 -0
  152. package/out/chunk-QI66YA4F.js +1 -0
  153. package/out/chunk-QRKFPLA4.js +80 -0
  154. package/out/chunk-R3NZFXVR.js +1 -0
  155. package/out/chunk-R5O6FAW4.js +2 -0
  156. package/out/chunk-RAM3GDAD.js +1 -0
  157. package/out/chunk-RPNO56H2.js +1 -0
  158. package/out/chunk-SMNFBOLO.js +10 -0
  159. package/out/chunk-SSPDMA6D.js +1 -0
  160. package/out/chunk-SZTCJVZJ.js +55 -0
  161. package/out/chunk-SZWPYLPC.js +1 -0
  162. package/out/chunk-TKPNRQNN.js +3 -0
  163. package/out/chunk-TUII34K2.js +1 -0
  164. package/out/chunk-UJP4PQJA.js +1 -0
  165. package/out/chunk-UJSJMXEG.js +1 -0
  166. package/out/chunk-UR4WYMIP.js +1 -0
  167. package/out/chunk-UTYWTUTC.js +1 -0
  168. package/out/chunk-VHEXSGGP.js +1 -0
  169. package/out/chunk-VYYUMYVW.js +9 -0
  170. package/out/chunk-WBK5ZN4K.js +3 -0
  171. package/out/chunk-WCDYSIKG.js +1 -0
  172. package/out/chunk-XM4RLC4A.js +2 -0
  173. package/out/chunk-XRAAYXPR.js +1 -0
  174. package/out/chunk-ZQHLECTI.js +1 -0
  175. package/out/client-managed-import.js +4 -0
  176. package/out/client-managed.js +35 -0
  177. package/out/client-sync.js +11 -17
  178. package/out/compare.js +26 -0
  179. package/out/dialogs.js +40 -0
  180. package/out/github-issue-authorized.html +3 -0
  181. package/out/github-issue-authorized.js +1 -0
  182. package/out/graph.js +19 -5
  183. package/out/index.html +105 -25
  184. package/out/prism.js +14 -10
  185. package/out/scan.js +2 -0
  186. package/out/stasis.svg +20 -0
  187. package/out/terminal.js +367 -39
  188. package/out/view.css +1 -1
  189. package/out/view.js +19 -148
  190. package/package.json +416 -64
  191. package/risk/actions/findings.js +161 -0
  192. package/risk/actions/resolve.js +287 -0
  193. package/risk/actions/scripts/commands.js +182 -0
  194. package/risk/actions/scripts/grade.js +113 -0
  195. package/risk/actions/scripts/packages.js +123 -0
  196. package/risk/actions/scripts/shell.js +169 -0
  197. package/risk/actions/uses.js +94 -0
  198. package/risk/actions/workflow.js +183 -0
  199. package/risk/files/characters.js +354 -0
  200. package/risk/files/hosts.js +206 -0
  201. package/risk/files/readability.js +185 -0
  202. package/risk/files/runs-code.js +568 -0
  203. package/risk/files/script.js +420 -0
  204. package/risk/files/source-map-link.js +43 -0
  205. package/risk/files/stamps.js +47 -0
  206. package/risk/index.d.ts +309 -0
  207. package/risk/index.js +12 -0
  208. package/risk/npm/assess.js +303 -0
  209. package/risk/npm/combined.js +68 -0
  210. package/risk/npm/compare.js +236 -0
  211. package/risk/npm/dependencies.js +172 -0
  212. package/risk/npm/diff.js +79 -0
  213. package/risk/npm/downloads.js +84 -0
  214. package/risk/npm/files.js +445 -0
  215. package/risk/npm/held.js +67 -0
  216. package/risk/npm/install-scripts.js +34 -0
  217. package/risk/npm/malware.js +38 -0
  218. package/risk/npm/manifest.js +65 -0
  219. package/risk/npm/new-dependency.js +60 -0
  220. package/risk/npm/old-version.js +108 -0
  221. package/risk/npm/registry.js +401 -0
  222. package/risk/npm/release.js +85 -0
  223. package/risk/npm/score.js +59 -0
  224. package/risk/npm/specs.js +124 -0
  225. package/risk/npm/tarball.js +169 -0
  226. package/server-common/database-config.ts +16 -0
  227. package/server-common/initialize.ts +18 -0
  228. package/server-common/npm-advisories.ts +101 -0
  229. package/{server → server-common}/origin.ts +5 -5
  230. package/server-common/reap.ts +48 -0
  231. package/server-common/scan-config.ts +19 -0
  232. package/server-common/standalone.ts +29 -0
  233. package/server-common/storage-crypto.ts +182 -0
  234. package/server-common/storage-log.ts +38 -0
  235. package/server-common/vercel-blob.ts +103 -0
  236. package/server-e2e/app.ts +487 -0
  237. package/{server → server-e2e}/bus-receiver.ts +2 -1
  238. package/{server → server-e2e}/cli.js +9 -4
  239. package/{server → server-e2e}/config.ts +52 -42
  240. package/{server → server-e2e}/db-neon.ts +2 -2
  241. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  242. package/{server → server-e2e}/db-stmt.ts +2 -2
  243. package/{server → server-e2e}/db.ts +7 -7
  244. package/{server → server-e2e}/http.ts +44 -13
  245. package/{server → server-e2e}/hub.ts +40 -9
  246. package/server-e2e/index.ts +17 -0
  247. package/server-e2e/lifecycle.ts +95 -0
  248. package/{server → server-e2e}/neon-driver.ts +2 -2
  249. package/{server → server-e2e}/npm-proxy.ts +12 -145
  250. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  251. package/{server → server-e2e}/objstore/blob.ts +1 -1
  252. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  253. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  254. package/{server → server-e2e}/objstore/init.ts +19 -27
  255. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  256. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  257. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  258. package/{server → server-e2e}/objstore/rest.ts +3 -3
  259. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  260. package/{server → server-e2e}/objstore/store.ts +7 -7
  261. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  262. package/{server → server-e2e}/pubsub.ts +12 -9
  263. package/{server → server-e2e}/sign.ts +4 -4
  264. package/{server → server-e2e}/sse-server.ts +3 -3
  265. package/{server → server-e2e}/static.ts +18 -17
  266. package/{server → server-e2e}/sync-handlers.ts +56 -30
  267. package/{server → server-e2e}/ws-server.ts +20 -9
  268. package/server-managed/activity.ts +269 -0
  269. package/server-managed/agent-merges.ts +109 -0
  270. package/server-managed/app-agents.ts +23 -0
  271. package/server-managed/avatar-store.ts +21 -0
  272. package/server-managed/blob-store.ts +26 -0
  273. package/server-managed/brotli.ts +10 -0
  274. package/server-managed/bundle-advisories.ts +176 -0
  275. package/server-managed/bundle-advisory-inventory.ts +85 -0
  276. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  277. package/server-managed/bundle-build-diagnostics.js +23 -0
  278. package/server-managed/bundle-build-leases.ts +41 -0
  279. package/server-managed/bundle-build-worker.js +387 -0
  280. package/server-managed/bundle-build.ts +328 -0
  281. package/server-managed/bundle-cache.ts +261 -0
  282. package/server-managed/bundle-catalog.ts +29 -0
  283. package/server-managed/bundle-commits.ts +133 -0
  284. package/server-managed/bundle-dependency-reviews.ts +91 -0
  285. package/server-managed/bundle-store.ts +24 -0
  286. package/server-managed/bundle-summary-cache.ts +139 -0
  287. package/server-managed/bundle-validation.ts +33 -0
  288. package/server-managed/bundle.ts +151 -0
  289. package/server-managed/cache-storage.ts +20 -0
  290. package/server-managed/cli.js +21 -0
  291. package/server-managed/combined.ts +43 -0
  292. package/server-managed/comments.ts +138 -0
  293. package/server-managed/commit-coauthors.ts +105 -0
  294. package/server-managed/commit-lockfiles.ts +78 -0
  295. package/server-managed/comparison.ts +51 -0
  296. package/server-managed/config.ts +163 -0
  297. package/server-managed/content-access.ts +15 -0
  298. package/server-managed/crypto.ts +25 -0
  299. package/server-managed/db-methods.ts +1950 -0
  300. package/server-managed/db-neon.ts +401 -0
  301. package/server-managed/db-schema.ts +271 -0
  302. package/server-managed/db-table-names.ts +22 -0
  303. package/server-managed/db.ts +150 -0
  304. package/server-managed/dependabot-access.ts +85 -0
  305. package/server-managed/dependabot-alerts.ts +197 -0
  306. package/server-managed/dependency-review-comments.ts +158 -0
  307. package/server-managed/dependency-reviews.ts +369 -0
  308. package/server-managed/github-accounts.ts +59 -0
  309. package/server-managed/github-actions.ts +71 -0
  310. package/server-managed/github-app.ts +347 -0
  311. package/server-managed/github-errors.ts +92 -0
  312. package/server-managed/github-graphql.ts +42 -0
  313. package/server-managed/github-issue-links.ts +264 -0
  314. package/server-managed/github-issue-oauth.ts +30 -0
  315. package/server-managed/github-issues.ts +169 -0
  316. package/server-managed/github-link-oauth.ts +56 -0
  317. package/server-managed/github-links.ts +204 -0
  318. package/server-managed/github-metadata.ts +218 -0
  319. package/server-managed/github-oauth.ts +264 -0
  320. package/server-managed/github-pulls.ts +290 -0
  321. package/server-managed/github-requests.ts +181 -0
  322. package/server-managed/github-users.ts +53 -0
  323. package/server-managed/github-values.ts +26 -0
  324. package/server-managed/history-windows.ts +172 -0
  325. package/server-managed/http-response.ts +76 -0
  326. package/server-managed/http.ts +6722 -0
  327. package/server-managed/import-triage.ts +51 -0
  328. package/server-managed/index.ts +204 -0
  329. package/server-managed/kept-briefly.ts +37 -0
  330. package/server-managed/kept.ts +28 -0
  331. package/server-managed/known-listings.ts +112 -0
  332. package/server-managed/link-reports.ts +149 -0
  333. package/server-managed/listed-activity.ts +39 -0
  334. package/server-managed/locked-packages.ts +234 -0
  335. package/server-managed/lockfile-scope.ts +58 -0
  336. package/server-managed/lru.ts +30 -0
  337. package/server-managed/managed-issues.ts +92 -0
  338. package/server-managed/management-catalog.ts +45 -0
  339. package/server-managed/management.ts +116 -0
  340. package/server-managed/npm-delta-worker.js +203 -0
  341. package/server-managed/npm-delta.ts +277 -0
  342. package/server-managed/npm-insights.ts +455 -0
  343. package/server-managed/npm-kept.ts +274 -0
  344. package/server-managed/npm-loads.ts +259 -0
  345. package/server-managed/npm-manifest.ts +117 -0
  346. package/server-managed/npm-packages.ts +477 -0
  347. package/server-managed/npm-patch-paths.ts +86 -0
  348. package/server-managed/npm-patch.ts +457 -0
  349. package/server-managed/npm-provenance.ts +127 -0
  350. package/server-managed/npm-risk.ts +310 -0
  351. package/server-managed/object-storage-disk.ts +147 -0
  352. package/server-managed/object-storage-vercel.ts +71 -0
  353. package/server-managed/object-storage.ts +82 -0
  354. package/server-managed/package-entry-points.ts +127 -0
  355. package/server-managed/pretty-copies.ts +22 -0
  356. package/server-managed/pretty-format.d.ts +4 -0
  357. package/server-managed/pretty-format.js +27 -0
  358. package/server-managed/pretty-print.ts +444 -0
  359. package/server-managed/public-workspace.ts +242 -0
  360. package/server-managed/pull-comment-reviews.ts +161 -0
  361. package/server-managed/pull-dependencies.ts +370 -0
  362. package/server-managed/pull-dependency-reviews.ts +458 -0
  363. package/server-managed/pull-reviews.ts +202 -0
  364. package/server-managed/pulse-walk.ts +164 -0
  365. package/server-managed/queue.ts +54 -0
  366. package/server-managed/release-commits.ts +85 -0
  367. package/server-managed/rename-diff-worker.js +30 -0
  368. package/server-managed/rename-diff.ts +237 -0
  369. package/server-managed/repo-path.ts +21 -0
  370. package/server-managed/report-migration.ts +32 -0
  371. package/server-managed/report-opening.ts +77 -0
  372. package/server-managed/report-query.ts +10 -0
  373. package/server-managed/report-response.ts +16 -0
  374. package/server-managed/report-sources.ts +185 -0
  375. package/server-managed/report-store.ts +77 -0
  376. package/server-managed/repository-actions.ts +220 -0
  377. package/server-managed/repository-agents.ts +422 -0
  378. package/server-managed/repository-aliases.ts +119 -0
  379. package/server-managed/repository-browser.ts +362 -0
  380. package/server-managed/repository-changes.ts +280 -0
  381. package/server-managed/repository-code.ts +222 -0
  382. package/server-managed/repository-dependency-reviews.ts +220 -0
  383. package/server-managed/repository-discovery.ts +83 -0
  384. package/server-managed/repository-history.ts +444 -0
  385. package/server-managed/repository-issues.ts +293 -0
  386. package/server-managed/repository-policy.ts +27 -0
  387. package/server-managed/repository-pulls.ts +207 -0
  388. package/server-managed/repository-pulse.ts +409 -0
  389. package/server-managed/repository-risk-assess.ts +179 -0
  390. package/server-managed/repository-risk-audit.ts +145 -0
  391. package/server-managed/repository-risk-caches.ts +56 -0
  392. package/server-managed/repository-risk-kept.ts +86 -0
  393. package/server-managed/repository-risk-read.ts +296 -0
  394. package/server-managed/repository-risk-stasis.ts +61 -0
  395. package/server-managed/repository-risk-turn.ts +97 -0
  396. package/server-managed/repository-risk.ts +528 -0
  397. package/server-managed/repository-squashes.ts +160 -0
  398. package/server-managed/repository-stamp.ts +41 -0
  399. package/server-managed/request-timing.ts +63 -0
  400. package/server-managed/reviewed-dependencies.ts +170 -0
  401. package/server-managed/revisions.ts +35 -0
  402. package/server-managed/scan-downloads.ts +121 -0
  403. package/server-managed/session.ts +132 -0
  404. package/server-managed/slugs.ts +38 -0
  405. package/server-managed/solidity-entry-points.ts +71 -0
  406. package/server-managed/sql-postgres.ts +34 -0
  407. package/server-managed/sql.ts +107 -0
  408. package/server-managed/stasis-config.ts +147 -0
  409. package/server-managed/stasis-dependencies.ts +280 -0
  410. package/server-managed/static.ts +28 -0
  411. package/server-managed/storage-command.ts +16 -0
  412. package/server-managed/storage-db.ts +183 -0
  413. package/server-managed/storage-encryption.ts +288 -0
  414. package/server-managed/storage-maintenance.ts +259 -0
  415. package/server-managed/storage-payload.ts +121 -0
  416. package/server-managed/storage-stores.ts +91 -0
  417. package/server-managed/storage.ts +82 -0
  418. package/server-managed/team-app-summaries.ts +57 -0
  419. package/server-managed/team-app.ts +162 -0
  420. package/server-managed/team-catalog.ts +7 -0
  421. package/server-managed/team-feed.ts +180 -0
  422. package/server-managed/team-icons.ts +50 -0
  423. package/server-managed/team-npm-scopes.ts +103 -0
  424. package/server-managed/team-progress.ts +77 -0
  425. package/server-managed/team-reports.ts +369 -0
  426. package/server-managed/triage-response.ts +16 -0
  427. package/server-managed/type-only-proof.js +181 -0
  428. package/server-managed/type-only-worker.js +31 -0
  429. package/server-managed/type-only.ts +135 -0
  430. package/server-managed/uploads.ts +106 -0
  431. package/server-managed/upstream-cache.ts +275 -0
  432. package/server-managed/view-as.ts +58 -0
  433. package/server-managed/worker-turns.ts +76 -0
  434. package/server-managed/workspace-shares.ts +170 -0
  435. package/server.ts +70 -0
  436. package/strip-types-loader.js +13 -10
  437. package/server/index.ts +0 -480
  438. package/server/lifecycle.ts +0 -208
  439. /package/{LICENSE → LICENSE-MIT} +0 -0
  440. /package/{server → server-e2e}/auth.ts +0 -0
  441. /package/{server → server-e2e}/config.example.json +0 -0
  442. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  443. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  444. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  445. /package/{server → server-e2e}/peer.ts +0 -0
  446. /package/{server → server-e2e}/sse-session.ts +0 -0
  447. /package/{server → server-e2e}/util.ts +0 -0
  448. /package/{server → server-e2e}/validation.ts +0 -0
@@ -71,8 +71,8 @@ export type ObjstoreRestDeps = {
71
71
  // Cross-instance pub/sub for objstore-deleted — fired alongside the local
72
72
  // `broadcast` after a successful REST delete mint, so peers on OTHER
73
73
  // instances drop the resource in real time. Carries (tag, resourceTag,
74
- // version) inline (the row is gone post-delete). SQLite mode passes a no-op.
75
- publishObjDeleted: (tag: string, resourceTag: string, version: number) => void
74
+ // version, incarnation) inline (the row is gone post-delete). SQLite mode passes a no-op.
75
+ publishObjDeleted: (tag: string, resourceTag: string, version: number, incarnation: string) => void
76
76
  // New-workspace operator gate for the REST put-begin mint — the
77
77
  // connection-independent analog of the WS path's `authGate`. Returns
78
78
  // `true` to DENY (a password is configured AND the workspace is
@@ -105,7 +105,7 @@ export type ObjstoreRestDeps = {
105
105
  // concurrent same-token PUT is rejected (409) before it can open a
106
106
  // second writer. The slot is held only across body + commit, released
107
107
  // in a `finally`, and bounded by the REST idle-body timeout in
108
- // server/http.ts so a slow-loris can't pin it. NOT a commit lock —
108
+ // server-e2e/http.ts so a slow-loris can't pin it. NOT a commit lock —
109
109
  // commits stay lock-free on the version-CAS above. Per-process: the
110
110
  // Vercel multi-replica path leans on `allowOverwrite: true` + the
111
111
  // commit CAS + content-addressing for cross-replica correctness (a
@@ -4,7 +4,7 @@
4
4
  // dialect on the wire.
5
5
  //
6
6
  // `@neondatabase/serverless` is an OPTIONAL peer dep — selected by
7
- // the `DATABASE_URL` branch in `server/index.ts`. The peer dep
7
+ // the configured database URL branch in `server-e2e/index.ts`. The peer dep
8
8
  // itself is loaded lazily inside `openNeonObjstore` below. A single
9
9
  // Neon project / database holds both `workspace_revision` and the
10
10
  // two objstore tables; each plane opens its own stateless
@@ -13,14 +13,10 @@
13
13
  // release.
14
14
  //
15
15
  // Byte plane: passed in as a `BlobBackend` (./blob.ts). The
16
- // supported pairings selected by server/index.ts are:
17
- // - Neon + Vercel Blob Private Storage (multi-replica, the only
18
- // pairing that survives a replica restart without local-disk
19
- // coordination). Activated by setting BLOB_READ_WRITE_TOKEN
20
- // alongside DATABASE_URL.
21
- // - Neon + local FS (development / operator escape hatch — bytes
22
- // still need to live on a shared filesystem if you run more
23
- // than one replica).
16
+ // supported Neon pairing selected by server-e2e/index.ts is Vercel
17
+ // Blob Private Storage. DATABASE_URL or E2E_DATABASE_URL plus BLOB_READ_WRITE_TOKEN
18
+ // is required; the launcher never selects Neon + local FS. Tests
19
+ // can inject a local-FS backend directly through this adapter.
24
20
 
25
21
  import type { BlobBackend } from './blob.ts'
26
22
  import type { AllStmt, GetStmt, RunStmt } from '../db-stmt.ts'
@@ -309,7 +305,7 @@ export async function openNeonObjstore(connectionString: string, blob: BlobBacke
309
305
  // local `../neon-driver.ts` re-export wrapper so the peer dep stays
310
306
  // optional AND tests can mock the driver (a local path is always
311
307
  // resolvable; the bare specifier isn't when the dep is absent). See
312
- // `server/neon-driver.ts`. Cast through `unknown` because the
308
+ // `server-e2e/neon-driver.ts`. Cast through `unknown` because the
313
309
  // wrapper's `export *` re-exports a `@ts-ignore`'d module.
314
310
  const mod = (await import('../neon-driver.ts')) as unknown as { neon: (url: string) => NeonSql }
315
311
  const sql: NeonSql = mod.neon(connectionString)
@@ -1,5 +1,5 @@
1
1
  // SQLite + filesystem-backed object store for the v1.objstore
2
- // protocol extension. Sibling of `server/db.ts`; shares the
2
+ // protocol extension. Sibling of `server-e2e/db.ts`; shares the
3
3
  // underlying DatabaseSync handle but keeps its own tables.
4
4
  //
5
5
  // workspace_object — one row per LIVE resource (no
@@ -150,7 +150,7 @@ export type DeleteResult =
150
150
  | { ok: true; deletedVersion: number }
151
151
  | { ok: false; reason: 'not-found' | 'conflict'; conflict?: ObjectRow }
152
152
 
153
- // Async statement shapes are shared with server/db.ts via
153
+ // Async statement shapes are shared with server-e2e/db.ts via
154
154
  // ../db-stmt.ts — same `.get/.all/.run` → Promise contract across
155
155
  // both planes.
156
156
 
@@ -186,7 +186,7 @@ export type Handle = {
186
186
  db?: DatabaseSync
187
187
  // Byte-plane backend (local FS or Vercel Blob). All bytes-side
188
188
  // operations go through this — there is no direct fs.* call in
189
- // store / rest / reaper. Selected at boot in server/index.ts.
189
+ // store / rest / reaper. Selected at boot in server-e2e/index.ts.
190
190
  blob: BlobBackend
191
191
  // Storage root for the FS backend — set only when `blob` was
192
192
  // constructed from `openFsBlobBackend(dir)`. Production code
@@ -247,7 +247,7 @@ export type Handle = {
247
247
  // returned. The reaper passes `Date.now() - stagingTtlMs` so the
248
248
  // index `workspace_object_staging_begun_at_idx` is used and the
249
249
  // sweep is O(stale-rows) instead of O(in-flight-uploads-cluster-
250
- // wide). DB-layout audit `server/objstore/store.ts:312`.
250
+ // wide). DB-layout audit `server-e2e/objstore/store.ts:312`.
251
251
  listAllStaging: AllStmt<[number], { workspace_tag: string; resource_tag: string; staging_id: string; begun_at: number }>
252
252
  listLiveTags: AllStmt<[], { workspace_tag: string }>
253
253
  countLive: GetStmt<[string], { c: number }>
@@ -255,7 +255,7 @@ export type Handle = {
255
255
 
256
256
  // Narrowing alias for the SQLite-backed Handle: `db` is guaranteed
257
257
  // to be set. `openObjstore` returns this so call sites (production
258
- // shutdown plumbing in `server/index.ts` + the entire SQLite-only
258
+ // shutdown plumbing in `server-e2e/index.ts` + the entire SQLite-only
259
259
  // test suite in `tests/server-objstore.test.js`) can reach
260
260
  // `handle.db.prepare(...)` without an optional-chain or non-null
261
261
  // assertion. A Neon-backed Handle (`openNeonObjstore`) keeps the
@@ -352,7 +352,7 @@ export function openObjstore(db: DatabaseSync, dir: string): SqliteHandle {
352
352
  mkdirSync(dir, { recursive: true })
353
353
  db.exec(SCHEMA)
354
354
  // Fail-loud on a pre-existing non-STRICT table — same rationale as
355
- // server/db.ts: `CREATE TABLE IF NOT EXISTS … STRICT` doesn't
355
+ // server-e2e/db.ts: `CREATE TABLE IF NOT EXISTS … STRICT` doesn't
356
356
  // upgrade an existing non-STRICT table, and dropping strict type
357
357
  // affinity opens an operator-attack path. PR #4 review F3.
358
358
  for (const name of ['workspace_object', 'workspace_object_staging']) {
@@ -362,7 +362,7 @@ export function openObjstore(db: DatabaseSync, dir: string): SqliteHandle {
362
362
  const blob = openFsBlobBackend(dir)
363
363
  // No `close` method on the returned Handle: the underlying
364
364
  // `DatabaseSync` is owned by the caller (in production, the
365
- // workspace_revision handle in `server/db.ts`, closed from
365
+ // workspace_revision handle in `server-e2e/db.ts`, closed from
366
366
  // `shutdown()`; tests close their own DB). A `close()` here would
367
367
  // mislead — it could only no-op or leak, never close the caller-
368
368
  // owned connection.
@@ -24,7 +24,7 @@
24
24
  import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
25
25
  import { Buffer } from 'node:buffer'
26
26
 
27
- export const DEFAULT_TOKEN_TTL_MS = 5 * 60 * 1000
27
+ const DEFAULT_TOKEN_TTL_MS = 5 * 60 * 1000
28
28
 
29
29
  export type PutTokenPayload = {
30
30
  op: 'put'
@@ -119,7 +119,7 @@ function isValidPayload(v: unknown): v is TokenPayload {
119
119
  // different actual value, or — for `exp` — claim a
120
120
  // `Number.MAX_SAFE_INTEGER + 1` expiry that compares ambiguously near
121
121
  // the IEEE-754 boundary. Matches the codebase's other safe-int gates
122
- // (server/objstore/sign.ts, rest.ts, handlers.ts).
122
+ // (server-e2e/objstore/sign.ts, rest.ts, handlers.ts).
123
123
  if (!Number.isSafeInteger(o['exp']) || (o['exp'] as number) < 0) return false
124
124
  if (o['op'] === 'put') {
125
125
  return typeof o['sid'] === 'string'
@@ -1,5 +1,5 @@
1
1
  // Cross-instance pub/sub for real-time WS broadcasts. The triage-sync
2
- // fan-out is an in-memory subscriber map (server/hub.ts) by design — it
2
+ // fan-out is an in-memory subscriber map (server-e2e/hub.ts) by design — it
3
3
  // routes a commit only to peers on the SAME instance. A multi-instance
4
4
  // deployment behind a load balancer needs commit-landed-on-A to reach
5
5
  // peers-on-B with the same latency the hub gives same-instance peers.
@@ -57,15 +57,15 @@ function newSenderId(): string {
57
57
  // - 'objput': objstore-put broadcast. `res` is the resource tag; the
58
58
  // receiver SELECTs the live row by (tag, res) for the rest of the
59
59
  // metadata fields.
60
- // - 'objdel': objstore-deleted broadcast. `ver` is the deleted version
61
- // — inline because the row is gone from workspace_object after the
62
- // delete commit.
60
+ // - 'objdel': objstore-deleted broadcast. `ver` and `incarnation` identify
61
+ // the deleted row, which is gone from workspace_object after commit.
62
+ // Incarnation is optional only for messages from older relay instances.
63
63
  export type BusMessage =
64
64
  | { kind: 'rev'; tag: string; id: string }
65
65
  | { kind: 'objput'; tag: string; res: string }
66
- | { kind: 'objdel'; tag: string; res: string; ver: number }
66
+ | { kind: 'objdel'; tag: string; res: string; ver: number; incarnation?: string }
67
67
 
68
- // Receiver wired up by the hub layer (see server/index.ts). Each handler
68
+ // Receiver wired up by the hub layer (see server-e2e/index.ts). Each handler
69
69
  // runs once per remote message; failures are logged but don't crash the
70
70
  // LISTEN loop — a missed broadcast surfaces to clients on reconnect
71
71
  // (chain re-pull). Async because the workspace-revision handler does a
@@ -164,7 +164,7 @@ type NeonState = {
164
164
  // In-flight bus-message handler promises. `dispatchNotification`
165
165
  // fires handlers fire-and-forget, but `stop()` awaits this set before
166
166
  // returning so the lifecycle's `handle.close()` (which runs after
167
- // `pubsub.stop()` — see closeDb in server/index.ts) can't race a
167
+ // `pubsub.stop()` — see closeDb in server-e2e/index.ts) can't race a
168
168
  // handler mid-`handle.revisionById.get` / `getLive`.
169
169
  pendingHandlers: Set<Promise<void>>
170
170
  }
@@ -333,7 +333,7 @@ export function createNeonPubSub(deps: NeonPubSubDeps): PubSub {
333
333
  if (state.connectAttempt) { try { await state.connectAttempt } catch {} }
334
334
  // Drain in-flight bus-message handlers BEFORE returning. The
335
335
  // lifecycle teardown runs `pubsub.stop()` and THEN
336
- // `handle.close()` (see closeDb in server/index.ts); a handler
336
+ // `handle.close()` (see closeDb in server-e2e/index.ts); a handler
337
337
  // still in `handle.revisionById.get` / `getLive` would otherwise
338
338
  // throw against a closed DB. `allSettled` so one handler's
339
339
  // rejection doesn't abort the drain.
@@ -388,7 +388,10 @@ function parseBusMessage(raw: Record<string, unknown>): BusMessage | null {
388
388
  const ver = raw['ver']
389
389
  if (typeof res !== 'string') return null
390
390
  if (typeof ver !== 'number' || !Number.isSafeInteger(ver)) return null
391
- return { kind: 'objdel', tag, res, ver }
391
+ const incarnation = raw['incarnation']
392
+ if (incarnation === undefined) return { kind: 'objdel', tag, res, ver }
393
+ if (typeof incarnation !== 'string' || incarnation.length === 0) return null
394
+ return { kind: 'objdel', tag, res, ver, incarnation }
392
395
  }
393
396
  return null
394
397
  }
@@ -92,7 +92,7 @@ export function canonicalSave(
92
92
  // confusing diff in the canonical bytes rather than a clean drop.
93
93
  // Mirrors the `isSafeNonNegativeInt` rigor that the objstore
94
94
  // canonical builders apply. Input-validation audit
95
- // `server/sign.ts:88`.
95
+ // `server-e2e/sign.ts:88`.
96
96
  if (typeof workspaceTag !== 'string') throw new TypeError('canonicalSave: workspaceTag must be string')
97
97
  if (typeof nonce !== 'string') throw new TypeError('canonicalSave: nonce must be string')
98
98
  if (typeof ciphertext !== 'string') throw new TypeError('canonicalSave: ciphertext must be string')
@@ -122,7 +122,7 @@ function canonicalSubscribe(
122
122
  return encodeUtf8([SUBSCRIBE_DOMAIN, workspaceTag as string, fromStr, connectionNonce].join('\n'))
123
123
  }
124
124
 
125
- // Exported because the v1.objstore signing module (server/objstore/sign.ts)
125
+ // Exported because the v1.objstore signing module (server-e2e/objstore/sign.ts)
126
126
  // reuses it for its four verifiers — same workspaceTag-as-pubkey contract,
127
127
  // same domain-separated canonical bytes. Keeping the WebCrypto plumbing
128
128
  // in one place avoids drift between the triage-sync and objstore verify
@@ -157,7 +157,7 @@ export async function verifyEd25519(
157
157
  // `{ ok: false, canonical: null }` on bad shape / bad sig;
158
158
  // `{ ok: true, canonical: <bytes> }` on success.
159
159
  //
160
- // NOT used by `server/index.ts handleSave`. Production composes
160
+ // NOT used by `server-e2e/sync-handlers.ts handleSave`. Production composes
161
161
  // the smaller helpers (`canonicalSave`, `computeRevisionIdFromCanonical`,
162
162
  // `verifyEd25519`) separately so the dup-precheck via
163
163
  // `revisionExists` can fire BEFORE Ed25519-verify and skip the
@@ -204,7 +204,7 @@ export async function computeRevisionIdFromCanonical(canonical: Uint8Array<Array
204
204
 
205
205
  // `connectionNonce` is the per-socket challenge the server issued
206
206
  // to the originating connection (see `Peer.challenge` in
207
- // server/peer.ts). The client signs a canonical that includes the
207
+ // server-e2e/peer.ts). The client signs a canonical that includes the
208
208
  // nonce; verifying against the SAME nonce here is what blocks
209
209
  // cross-connection replay of a captured subscribe frame. Audit
210
210
  // round-9 H2.
@@ -57,7 +57,7 @@ import { type PeerConnectionDeps, setupPeerConnection } from './ws-server.ts'
57
57
  import { SseSession } from './sse-session.ts'
58
58
  import { errMsg, randomId } from './util.ts'
59
59
 
60
- // Same prefix the WS upgrade lives under (server/http.ts WS_UPGRADE_PATH
60
+ // Same prefix the WS upgrade lives under (server-e2e/http.ts WS_UPGRADE_PATH
61
61
  // = '/api/sync'); subroute keeps the SSE plane sibling to the upgrade
62
62
  // path so the same `location` block routes both.
63
63
  export const SSE_OPEN_PATH = '/api/sync/sse'
@@ -85,7 +85,7 @@ export type SseServerDeps = {
85
85
  // transport into it. Closure over the same handler / hub / objstore
86
86
  // / track / debug surface the WS path uses.
87
87
  peerDeps: PeerConnectionDeps
88
- // Shutdown gate. Mirror of the REST + WS branches in server/http.ts:
88
+ // Shutdown gate. Mirror of the REST + WS branches in server-e2e/http.ts:
89
89
  // an SSE POST arriving on an existing keep-alive socket after
90
90
  // SIGTERM should be rejected, not dispatched against a draining DB.
91
91
  isShuttingDown: () => boolean
@@ -93,7 +93,7 @@ export type SseServerDeps = {
93
93
  // 503 the open request. Caps the SSE-side equivalent of `wss.clients`.
94
94
  maxSessions: number
95
95
  // Max body size for one POST. Matches the WS `maxPayload` in
96
- // server/index.ts so the SSE plane can't accept frames the WS plane
96
+ // server-e2e/index.ts so the SSE plane can't accept frames the WS plane
97
97
  // would reject. The POST body envelope can hold multiple frames so
98
98
  // the per-frame budget is the same as the WS plane after the
99
99
  // dispatcher splits them.
@@ -6,8 +6,8 @@
6
6
  // `join(staticDir, dirent.name)` from `readdirSync` at boot — the
7
7
  // request URL is only used as a Map key, never joined with the
8
8
  // filesystem — so the handler has no path-traversal surface at all:
9
- // `..`, percent-encoded slashes, nested subpaths and absolute-form
10
- // URIs all just produce a key that isn't in the map and 404.
9
+ // `..`, percent-encoded slashes and absolute-form URIs all just
10
+ // produce a key that isn't in the map and 404.
11
11
  //
12
12
  // Compression: every entry whose extension is in COMPRESSIBLE gets
13
13
  // pre-computed brotli + gzip at boot. The handler picks brotli over
@@ -38,6 +38,7 @@ import { readFileSync, readdirSync } from 'node:fs'
38
38
  import { createHash } from 'node:crypto'
39
39
  import { brotliCompressSync, gzipSync, constants as zlibConstants } from 'node:zlib'
40
40
  import { extname, join } from 'node:path'
41
+ import { scanServerHtml } from '../server-common/scan-config.ts'
41
42
 
42
43
  // MIME types for extensions the production UI bundle currently
43
44
  // emits. Anything else falls through to `application/octet-stream`
@@ -102,8 +103,10 @@ export type StaticHandler = (req: HttpRequest, res: ServerResponse) => boolean
102
103
  // caller falls through to its next route. Missing `staticDir`
103
104
  // (pre-build case) logs a warning and returns a handler that always
104
105
  // answers false; the API/WS planes are unaffected.
105
- export function loadStatic(staticDir: string): StaticHandler {
106
- const files = readStaticFiles(staticDir)
106
+ type StaticOptions = { transformIndex?: (html: string) => string, indexOnly?: boolean }
107
+
108
+ export function loadStatic(staticDir: string, deepviewScanServer: string | null = null, options: StaticOptions = {}): StaticHandler {
109
+ const files = readStaticFiles(staticDir, deepviewScanServer, options)
107
110
  return function handleStatic(req: HttpRequest, res: ServerResponse): boolean {
108
111
  if (req.method !== 'GET' && req.method !== 'HEAD') return false
109
112
  if (typeof req.url !== 'string') return false
@@ -151,7 +154,7 @@ export function loadStatic(staticDir: string): StaticHandler {
151
154
  }
152
155
  }
153
156
 
154
- function readStaticFiles(staticDir: string): ReadonlyMap<string, StaticEntry> {
157
+ function readStaticFiles(staticDir: string, deepviewScanServer: string | null, options: StaticOptions): ReadonlyMap<string, StaticEntry> {
155
158
  const files = new Map<string, StaticEntry>()
156
159
  let entries
157
160
  try { entries = readdirSync(staticDir, { withFileTypes: true }) } catch (err) {
@@ -165,18 +168,17 @@ function readStaticFiles(staticDir: string): ReadonlyMap<string, StaticEntry> {
165
168
  throw err
166
169
  }
167
170
  for (const entry of entries) {
168
- // `isFile()` filters subdirectories, symlinks, FIFOs etc. The
169
- // build emits a flat tree; dropping anything else keeps the
170
- // surface minimal even if a stray non-file sneaks in.
171
- if (!entry.isFile()) continue
172
- files.set(entry.name, buildEntry(staticDir, entry.name))
171
+ // Exclude subdirectories, symlinks and non-file entries.
172
+ if (!entry.isFile() || (options.indexOnly && entry.name !== 'index.html')) continue
173
+ files.set(entry.name, buildEntry(staticDir, entry.name, deepviewScanServer, options.transformIndex))
173
174
  }
174
175
  return files
175
176
  }
176
177
 
177
- function buildEntry(staticDir: string, name: string): StaticEntry {
178
+ function buildEntry(staticDir: string, name: string, deepviewScanServer: string | null = null, transformIndex: (html: string) => string = html => html): StaticEntry {
178
179
  const ext = extname(name)
179
- const raw = readFileSync(join(staticDir, name))
180
+ const source = readFileSync(join(staticDir, name))
181
+ const raw = name === 'index.html' ? Buffer.from(transformIndex(scanServerHtml(source.toString('utf8'), deepviewScanServer))) : source
180
182
  const type = CONTENT_TYPE[ext] ?? 'application/octet-stream'
181
183
  // HTML: lift `<link rel="(module)preload" …>` into a Link header and
182
184
  // drop the tags from the served body. ETag + compression run against
@@ -192,13 +194,12 @@ function buildEntry(staticDir: string, name: string): StaticEntry {
192
194
  // collision-resistance against the ~tens of files we load.
193
195
  const etag = `"${createHash('sha256').update(identity).digest('hex').slice(0, 32)}"`
194
196
  const isCompressible = COMPRESSIBLE.has(ext)
195
- // Brotli quality 11 is the maximum — slow at compress time but
196
- // we pay it once at boot and ship the smaller bytes on every
197
- // request thereafter. text mode tells the encoder we're working
197
+ // Brotli quality 9 limits boot-time compression work, including on
198
+ // serverless cold starts. Text mode tells the encoder we're working
198
199
  // on UTF-8 text (every COMPRESSIBLE entry is text-shaped).
199
200
  const br = isCompressible ? brotliCompressSync(identity, {
200
201
  params: {
201
- [zlibConstants.BROTLI_PARAM_QUALITY]: 11,
202
+ [zlibConstants.BROTLI_PARAM_QUALITY]: 9,
202
203
  [zlibConstants.BROTLI_PARAM_MODE]: zlibConstants.BROTLI_MODE_TEXT,
203
204
  },
204
205
  }) : null
@@ -243,7 +244,7 @@ function extractPreloadLinks(html: string): { html: string, link: string | null
243
244
  // when we keep a non-preload tag the whitespace is restored via
244
245
  // `return match` (HTML layout preserved).
245
246
  const tagRe = /<link\b[^>]*>\s*/giu
246
- const stripped = html.replace(tagRe, (match, offset: number) => {
247
+ const stripped = html.replaceAll(tagRe, (match, offset: number) => {
247
248
  if (inAnyRange(offset, skip)) return match
248
249
  const attrs = parseLinkAttrs(match)
249
250
  const rel = (attrs['rel'] ?? '').toLowerCase()
@@ -26,6 +26,8 @@ type WireRevision = {
26
26
  signature: string
27
27
  }
28
28
 
29
+ type SubscriptionLookup = { resume: () => void }
30
+
29
31
  // Structured result of the shared save pipeline (`commitSave`), rendered
30
32
  // per transport: WS → protocol frames; REST → JSON + HTTP status.
31
33
  type SaveOutcome =
@@ -79,6 +81,7 @@ export type SyncHandlersDeps = {
79
81
  // payload budget. Optional: a SQLite deployment passes a no-op.
80
82
  publishRevision: (tag: string, revisionId: string) => void
81
83
  subscribe: (socket: WebSocket, tag: string) => void
84
+ pauseBroadcasts: (socket: WebSocket) => () => void
82
85
  getNonce: (socket: WebSocket) => string | undefined
83
86
  requiresAuth: (socket: WebSocket) => boolean
84
87
  // Whether an operator password is configured. The REST save plane's
@@ -101,7 +104,7 @@ export type SyncHandlersDeps = {
101
104
  export type SyncHandlers = {
102
105
  handleSave: (socket: WebSocket, msg: SaveMsg) => Promise<void>
103
106
  // Session-independent REST save plane (`POST /api/sync/save`), wired into
104
- // the HTTP dispatcher in server/http.ts. Runs the same pipeline as
107
+ // the HTTP dispatcher in server-e2e/http.ts. Runs the same pipeline as
105
108
  // `handleSave` and renders the outcome as a JSON response.
106
109
  handleSaveRest: (req: IncomingMessage, res: ServerResponse) => Promise<void>
107
110
  handleSubscribe: (socket: WebSocket, msg: SubscribeMsg) => Promise<void>
@@ -112,6 +115,9 @@ export type SyncHandlers = {
112
115
 
113
116
  export function createSyncHandlers(deps: SyncHandlersDeps): SyncHandlers {
114
117
  const { handle, send, broadcast, publishRevision, subscribe, getNonce, requiresAuth, passwordConfigured, sendUnauthorized, workspaceExists, objstoreResources, debug } = deps
118
+ // Only the newest lookup for a socket/tag may publish a snapshot.
119
+ // Versions cannot order different object incarnations (or deletions).
120
+ const subscriptionLookups = new WeakMap<WebSocket, Map<string, SubscriptionLookup>>()
115
121
 
116
122
  // Typed wrapper for the three `workspace-save-error` emit sites
117
123
  // (too-large at handleSave, stale-base after the catch-up, busy at
@@ -299,7 +305,7 @@ export function createSyncHandlers(deps: SyncHandlersDeps): SyncHandlers {
299
305
  // maps the outcome to a JSON + HTTP status the client switches on. SSE-mode
300
306
  // clients POST here so a save doesn't take over their event-stream; a 401
301
307
  // routes them to the in-band frame (which runs the operator auth flow).
302
- // Mounted + gated (same-origin, shutdown, idle-timeout) in server/http.ts.
308
+ // Mounted + gated (same-origin, shutdown, idle-timeout) in server-e2e/http.ts.
303
309
  async function handleSaveRest(req: IncomingMessage, res: ServerResponse): Promise<void> {
304
310
  const body = await readSaveBody(req)
305
311
  if (!body || typeof body !== 'object') { respondJson(res, 400, { reason: 'bad-request' }); return }
@@ -348,34 +354,54 @@ export function createSyncHandlers(deps: SyncHandlersDeps): SyncHandlers {
348
354
  return
349
355
  }
350
356
  const tag = msg.workspaceTag
351
- subscribe(socket, tag)
352
- // Explicit ack — distinguishes "the server processed my subscribe
353
- // and registered me as a peer" from "the WebSocket is open". A
354
- // client that sent a malformed / bad-sig subscribe never gets this;
355
- // a client that did gets one before the chain arrives. Lets the UI
356
- // surface a `connecting → online` transition based on real handshake
357
- // completion, not just socket state.
358
- //
359
- // The ack also carries the objstore inventory snapshot: the same
360
- // subscribe that registers this socket for objstore-put / -deleted
361
- // broadcasts seeds the client's initial inventory in one handshake.
362
- // The client keeps it live thereafter from those broadcasts.
363
- // Returns [] for a triage-only workspace. A failing inventory
364
- // lookup must NOT sink the subscribe — degrade to an empty snapshot
365
- // (broadcasts will fill it in) so the ack + chain still go out.
366
- let resources: object[] = []
367
- try { resources = await objstoreResources(tag) }
368
- catch (err) { if (debug) console.warn('subscribe: objstore inventory lookup failed', debugTag(tag), err) }
369
- send(socket, { type: 'workspace-subscribed', workspaceTag: tag, resources })
370
- // `from` is the last revision id the client claims to have applied —
371
- // now a base64url string, not an integer. We send only revisions
372
- // after that. Client lying about `from` just means they get a
373
- // smaller catch-up — their subsequent saves will reveal stale state
374
- // on the usual base-mismatch path. Null / missing → full chain.
375
- const fromId = typeof msg.from === 'string' ? msg.from : null
376
- const revisions = chainForWire(await chainFrom(handle, tag, fromId))
377
- if (debug) console.log(`subscribe ${debugTag(tag)} from=${fromId?.slice(0, 8) ?? 'null'} → chain ${revisions.length}`)
378
- send(socket, { type: 'workspace-state', workspaceTag: tag, revisions })
357
+ const lookups = subscriptionLookups.get(socket) ?? new Map<string, SubscriptionLookup>()
358
+ subscriptionLookups.set(socket, lookups)
359
+ const previous = lookups.get(tag)
360
+ const resume = deps.pauseBroadcasts(socket)
361
+ const lookup = { resume }
362
+ lookups.set(tag, lookup)
363
+ // Acquire the replacement's pause before releasing its predecessor so
364
+ // buffered broadcasts cannot overtake the replacement snapshot. A hung
365
+ // obsolete read must not keep the whole socket paused. The hub's release
366
+ // is idempotent, so the old finally can still call it when the read ends.
367
+ previous?.resume()
368
+ try {
369
+ subscribe(socket, tag)
370
+ // Explicit ack — distinguishes "the server processed my subscribe
371
+ // and registered me as a peer" from "the WebSocket is open". A
372
+ // client that sent a malformed / bad-sig subscribe never gets this;
373
+ // a client that did gets one before the chain arrives. Lets the UI
374
+ // surface a `connecting → online` transition based on real handshake
375
+ // completion, not just socket state.
376
+ //
377
+ // The ack also carries the objstore inventory snapshot: the same
378
+ // subscribe that registers this socket for objstore-put / -deleted
379
+ // broadcasts seeds the client's initial inventory in one handshake.
380
+ // The client keeps it live thereafter from those broadcasts.
381
+ // Returns [] for a triage-only workspace. A lookup failure is NOT an
382
+ // empty inventory: clients interpret absent resources as deletions.
383
+ // Reconnect to retry the complete handshake on either transport.
384
+ const resources = await objstoreResources(tag)
385
+ if (socket.readyState !== socket.OPEN || lookups.get(tag) !== lookup) return
386
+ // `from` is the last revision id the client claims to have applied —
387
+ // now a base64url string, not an integer. We send only revisions
388
+ // after that. Client lying about `from` just means they get a
389
+ // smaller catch-up — their subsequent saves will reveal stale state
390
+ // on the usual base-mismatch path. Null / missing → full chain.
391
+ const fromId = typeof msg.from === 'string' ? msg.from : null
392
+ const revisions = chainForWire(await chainFrom(handle, tag, fromId))
393
+ if (socket.readyState !== socket.OPEN || lookups.get(tag) !== lookup) return
394
+ if (debug) console.log(`subscribe ${debugTag(tag)} from=${fromId?.slice(0, 8) ?? 'null'} → chain ${revisions.length}`)
395
+ send(socket, { type: 'workspace-subscribed', workspaceTag: tag, resources })
396
+ send(socket, { type: 'workspace-state', workspaceTag: tag, revisions })
397
+ } catch (err) {
398
+ if (lookups.get(tag) !== lookup) return
399
+ if (debug) console.warn('subscribe: snapshot lookup failed', debugTag(tag), err)
400
+ socket.close(1011, 'subscription unavailable')
401
+ } finally {
402
+ if (lookups.get(tag) === lookup) lookups.delete(tag)
403
+ resume()
404
+ }
379
405
  }
380
406
 
381
407
  return { handleSave, handleSaveRest, handleSubscribe, sendSaveError }
@@ -16,6 +16,7 @@ import { Buffer } from 'node:buffer'
16
16
  import type { IncomingMessage as HttpRequest } from 'node:http'
17
17
  import { decodeUtf8 } from '../common/utf8.js'
18
18
  import type { SaveErrorReason } from '../common/save-error-reason.ts'
19
+ import type { ServerInfo } from '../common/server-info.ts'
19
20
  import { Peer, type PeerRegistry } from './peer.ts'
20
21
  import { errMsg, errStack, randomId } from './util.ts'
21
22
  import type { SaveMsg, SubscribeMsg } from './sign.ts'
@@ -36,6 +37,9 @@ type IncomingMessage = {
36
37
  // SSE path doesn't need them.
37
38
  export type PeerConnectionDeps = {
38
39
  peers: PeerRegistry
40
+ // The mode this server advertises, emitted as the first `server-info`
41
+ // frame on every connection (see setupPeerConnection).
42
+ serverInfo: ServerInfo
39
43
  send: (socket: WebSocket, msg: object) => void
40
44
  unsubscribeAll: (socket: WebSocket) => void
41
45
  handleSave: (socket: WebSocket, msg: SaveMsg) => Promise<void>
@@ -60,7 +64,7 @@ export type WsServerDeps = PeerConnectionDeps & {
60
64
  // `as unknown as WebSocket`; only the subset both expose is used.
61
65
  export function setupPeerConnection(socket: WebSocket, req: HttpRequest, deps: PeerConnectionDeps): void {
62
66
  const {
63
- peers, send, unsubscribeAll, handleSave, handleSubscribe, handleAuthenticate,
67
+ peers, serverInfo, send, unsubscribeAll, handleSave, handleSubscribe, handleAuthenticate,
64
68
  sendSaveError, objstore, track, isShuttingDown, maxInflightPerSocket, debug,
65
69
  } = deps
66
70
  if (debug) console.log(`connect from ${req.socket.remoteAddress}`)
@@ -71,13 +75,20 @@ export function setupPeerConnection(socket: WebSocket, req: HttpRequest, deps: P
71
75
  const peer = new Peer(randomId())
72
76
  peers.set(socket, peer)
73
77
  socket.on('pong', () => { peer.alive = true })
74
- // Issue the per-connection challenge nonce BEFORE the client can
75
- // send anything that needs it. The client signs it into every
76
- // `workspace-subscribe` (see canonicalSubscribe in server/sign.ts);
77
- // a captured subscribe frame can't be replayed from a different
78
- // connection because that connection's nonce differs and the
78
+ // Issue the per-connection challenge nonce FIRST — before the client can
79
+ // send anything that needs it, AND as frame #0 so clients/tests that
80
+ // positionally read the first frame as the challenge keep working. The
81
+ // client signs it into every `workspace-subscribe` (see canonicalSubscribe
82
+ // in server-e2e/sign.ts); a captured subscribe frame can't be replayed from
83
+ // a different connection because that connection's nonce differs and the
79
84
  // signature won't verify against the new canonical bytes. Round-9 H2.
80
85
  send(socket, { type: 'challenge', nonce: peer.challenge })
86
+ // Then advertise the sync protocol (the mode probe), right after the
87
+ // challenge — the WS plane and the SSE fallback share this path. A client
88
+ // uses it to detect the mode, cache it, and refuse a cross-mode switch.
89
+ // Unauthenticated + mode-agnostic; an older client ignores it (predicate
90
+ // readers skip it; the workspaceTag demux drops it).
91
+ send(socket, { type: 'server-info', ...serverInfo })
81
92
  // Per-socket handlers are DELIBERATELY NOT serialized (vs the
82
93
  // client-side `messageQueue = messageQueue.then(...)` Promise
83
94
  // chain inside `client/triage-sync.ts:onTransportMessage`).
@@ -86,10 +97,10 @@ export function setupPeerConnection(socket: WebSocket, req: HttpRequest, deps: P
86
97
  // boundaries inside the handlers. Per-resource correctness needs
87
98
  // no in-process lock: `commitRevision` resolves concurrent saves
88
99
  // via its single gated INSERT (one snapshot + the
89
- // `UNIQUE(workspace_tag, seq)` PK — see `server/db.ts`), and the
100
+ // `UNIQUE(workspace_tag, seq)` PK — see `server-e2e/db.ts`), and the
90
101
  // objstore handlers (`commitPut` / `beginPut` / `deleteObject`)
91
102
  // via the version compare-and-set + content-addressing (see
92
- // `server/objstore/store.ts`), backed by post-await
103
+ // `server-e2e/objstore/store.ts`), backed by post-await
93
104
  // `readyState === OPEN` rechecks in every objstore handler. The
94
105
  // unbounded fan-out is capped by `maxInflightPerSocket` (see
95
106
  // also the `'busy'` NACK at the cap below). Concurrent dispatch
@@ -129,7 +140,7 @@ export function setupPeerConnection(socket: WebSocket, req: HttpRequest, deps: P
129
140
  // shedding load. Pings go through a fast inline `send(pong)`
130
141
  // path BELOW that doesn't bump the per-socket inflight counter,
131
142
  // so a ping-spam at the cap can't outrun the gate. Transport
132
- // audit `server/index.ts:590` + post-#58 audit follow-up.
143
+ // audit `server-e2e/index.ts:590` + post-#58 audit follow-up.
133
144
  if (parsed.type === 'ping') {
134
145
  send(socket, { type: 'pong' })
135
146
  return