@preventive/triage 1.0.0-alpha.6 → 1.0.0-alpha.60

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 (406) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +17 -0
  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 +3 -0
  13. package/common/bundle-compare-diff.js +376 -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-metadata.d.ts +15 -0
  20. package/common/bundle-metadata.js +226 -0
  21. package/common/bundle-pkg-of.d.ts +1 -0
  22. package/common/bundle-pkg-of.js +90 -0
  23. package/common/bundle-reasons.d.ts +2 -0
  24. package/common/bundle-reasons.js +21 -0
  25. package/common/bundle-source-links.d.ts +6 -0
  26. package/common/bundle-source-links.js +216 -0
  27. package/common/bundle-sourcemap.d.ts +10 -0
  28. package/common/bundle-sourcemap.js +100 -0
  29. package/common/bundle-sources.d.ts +7 -0
  30. package/common/bundle-sources.js +333 -0
  31. package/common/bundle-stats.js +41 -0
  32. package/common/bundle-tabs.js +1 -0
  33. package/common/code-language.js +65 -0
  34. package/common/default-scan-models.ts +35 -0
  35. package/common/dependency-reviews.d.ts +18 -0
  36. package/common/dependency-reviews.js +64 -0
  37. package/common/finding-duplicates.js +58 -0
  38. package/common/finding-filters.js +274 -0
  39. package/common/finding-id.js +47 -0
  40. package/common/finding-repo.d.ts +5 -0
  41. package/common/finding-repo.js +67 -0
  42. package/common/github-issue-labels.d.ts +1 -0
  43. package/common/github-issue-labels.js +11 -0
  44. package/common/github-pr.ts +56 -0
  45. package/common/gzip.js +59 -0
  46. package/common/line-diff.d.ts +8 -0
  47. package/common/line-diff.js +57 -0
  48. package/common/linked-workspace-groups.js +63 -0
  49. package/common/managed/agent-tasks.ts +292 -0
  50. package/common/managed/comments.ts +34 -0
  51. package/common/managed/finding-detail.d.ts +5 -0
  52. package/common/managed/finding-detail.js +75 -0
  53. package/common/managed/finding-values.d.ts +2 -0
  54. package/common/managed/finding-values.js +44 -0
  55. package/common/managed/github-agents.ts +114 -0
  56. package/common/managed/github-logins.ts +49 -0
  57. package/common/managed/lite-name.d.ts +2 -0
  58. package/common/managed/lite-name.js +20 -0
  59. package/common/managed/npm-packages.d.ts +7 -0
  60. package/common/managed/npm-packages.js +51 -0
  61. package/common/managed/permissions.ts +31 -0
  62. package/common/managed/report-content.ts +72 -0
  63. package/common/managed/report-filter.ts +120 -0
  64. package/common/managed/repository-alias.ts +65 -0
  65. package/common/managed/roles.ts +35 -0
  66. package/common/managed/routes.d.ts +2 -0
  67. package/common/managed/routes.js +363 -0
  68. package/common/managed/scan-models.ts +6 -0
  69. package/common/managed/team-app.d.ts +15 -0
  70. package/common/managed/team-app.js +100 -0
  71. package/common/managed/team-filters.js +26 -0
  72. package/common/managed/triage.ts +83 -0
  73. package/common/managed/upload-seal.ts +126 -0
  74. package/common/pretty-print.d.ts +5 -0
  75. package/common/pretty-print.js +24 -0
  76. package/common/repo-commit.d.ts +4 -0
  77. package/common/repo-commit.js +30 -0
  78. package/common/revalidation-conflicts.js +48 -0
  79. package/common/revalidation-input-groups.js +56 -0
  80. package/common/save-error-reason.ts +20 -7
  81. package/common/scan-server.ts +13 -0
  82. package/common/security-links.d.ts +5 -0
  83. package/common/security-links.js +33 -0
  84. package/common/server-info.ts +46 -0
  85. package/common/utf8.d.ts +3 -0
  86. package/common/utf8.js +45 -0
  87. package/common/workspace-app.js +71 -0
  88. package/common/workspace-groups.js +176 -0
  89. package/out/activity.js +4 -0
  90. package/out/brotli-fallback.js +3 -3
  91. package/out/chunk-2SY4PYUQ.js +4 -0
  92. package/out/chunk-2XUEZHIP.js +28 -0
  93. package/out/chunk-4EMM6UCD.js +1 -0
  94. package/out/chunk-4HI2MSAV.js +17 -0
  95. package/out/chunk-4ISO5F7Y.js +7 -0
  96. package/out/chunk-4TQKM3JC.js +42 -0
  97. package/out/chunk-4XIH7YTX.js +1 -0
  98. package/out/chunk-6VDDCFHT.js +3 -0
  99. package/out/chunk-74AEKRES.js +10 -0
  100. package/out/chunk-7BKKYVWR.js +7 -0
  101. package/out/chunk-7C7DWL7I.js +1 -0
  102. package/out/chunk-C4Z6ZBXV.js +10 -0
  103. package/out/chunk-DEVAORP2.js +1 -0
  104. package/out/chunk-E3LFSUDJ.js +9 -0
  105. package/out/chunk-EEQHVKR3.js +1 -0
  106. package/out/chunk-G3LY2FV4.js +1 -0
  107. package/out/chunk-GO7FT4OD.js +1 -0
  108. package/out/chunk-HAZKDK4M.js +4 -0
  109. package/out/chunk-HNQNDNIE.js +12 -0
  110. package/out/chunk-HOB3YPS5.js +1 -0
  111. package/out/chunk-IYPY47MC.js +1 -0
  112. package/out/chunk-IZ6MYRYB.js +3 -0
  113. package/out/chunk-J2FWBXFV.js +1 -0
  114. package/out/chunk-JCIIBLKR.js +1 -0
  115. package/out/chunk-JFL7WLRV.js +1 -0
  116. package/out/chunk-JMG5DXII.js +2 -0
  117. package/out/chunk-JOXLZXMI.js +1 -0
  118. package/out/chunk-M37X4LCF.js +14 -0
  119. package/out/chunk-M3Y6SLC4.js +1 -0
  120. package/out/chunk-NRPC74AM.js +1 -0
  121. package/out/chunk-NXATZJQ2.js +1 -0
  122. package/out/chunk-OFPDMZJF.js +244 -0
  123. package/out/chunk-OOJM4CTU.js +1 -0
  124. package/out/chunk-OQRSIBSC.js +1 -0
  125. package/out/chunk-PAD2JHZT.js +1 -0
  126. package/out/chunk-PNHBZGDD.js +1 -0
  127. package/out/chunk-PTFQKLKO.js +1 -0
  128. package/out/chunk-PWFUOLZK.js +17 -0
  129. package/out/chunk-PXK7EU4V.js +1 -0
  130. package/out/chunk-QMVOEBWC.js +13 -0
  131. package/out/chunk-QRKFPLA4.js +80 -0
  132. package/out/chunk-R3NZFXVR.js +1 -0
  133. package/out/chunk-R5O6FAW4.js +2 -0
  134. package/out/chunk-RRBIJL2B.js +1 -0
  135. package/out/chunk-SYXT3SFP.js +2 -0
  136. package/out/chunk-TOXMUOIW.js +5 -0
  137. package/out/chunk-TUII34K2.js +1 -0
  138. package/out/chunk-TZS7KERJ.js +52 -0
  139. package/out/chunk-UCP3JRE2.js +1 -0
  140. package/out/chunk-VFWMQ3LG.js +2 -0
  141. package/out/chunk-VRX2APNA.js +9 -0
  142. package/out/chunk-VZJIHHTQ.js +1 -0
  143. package/out/chunk-WCPJDAYA.js +10 -0
  144. package/out/chunk-WMFDQS2L.js +11 -0
  145. package/out/chunk-WREU7JAG.js +1 -0
  146. package/out/chunk-Y5ZHFNBD.js +2 -0
  147. package/out/chunk-YF4M5OCI.js +1 -0
  148. package/out/chunk-YGRRXC2L.js +1 -0
  149. package/out/chunk-YTO6AQZM.js +2 -0
  150. package/out/chunk-Z667U2UJ.js +1 -0
  151. package/out/chunk-ZQHLECTI.js +1 -0
  152. package/out/client-managed-import.js +4 -0
  153. package/out/client-managed.js +34 -0
  154. package/out/client-sync.js +11 -17
  155. package/out/compare.js +35 -0
  156. package/out/dialogs.js +40 -0
  157. package/out/github-issue-authorized.html +3 -0
  158. package/out/github-issue-authorized.js +1 -0
  159. package/out/graph.js +19 -4
  160. package/out/index.html +106 -8
  161. package/out/prism.js +14 -10
  162. package/out/scan.js +2 -0
  163. package/out/stasis.svg +20 -0
  164. package/out/terminal.js +366 -39
  165. package/out/view.css +1 -1
  166. package/out/view.js +19 -144
  167. package/package.json +379 -62
  168. package/risk/actions/findings.js +161 -0
  169. package/risk/actions/resolve.js +250 -0
  170. package/risk/actions/scripts/commands.js +182 -0
  171. package/risk/actions/scripts/grade.js +113 -0
  172. package/risk/actions/scripts/packages.js +123 -0
  173. package/risk/actions/scripts/shell.js +169 -0
  174. package/risk/actions/uses.js +76 -0
  175. package/risk/actions/workflow.js +110 -0
  176. package/risk/files/characters.js +196 -0
  177. package/risk/files/hosts.js +205 -0
  178. package/risk/files/readability.js +177 -0
  179. package/risk/files/runs-code.js +615 -0
  180. package/risk/files/script.js +118 -0
  181. package/risk/files/stamps.js +47 -0
  182. package/risk/index.d.ts +272 -0
  183. package/risk/index.js +11 -0
  184. package/risk/npm/assess.js +285 -0
  185. package/risk/npm/combined.js +68 -0
  186. package/risk/npm/compare.js +257 -0
  187. package/risk/npm/dependencies.js +172 -0
  188. package/risk/npm/diff.js +79 -0
  189. package/risk/npm/downloads.js +84 -0
  190. package/risk/npm/files.js +445 -0
  191. package/risk/npm/held.js +63 -0
  192. package/risk/npm/install-scripts.js +34 -0
  193. package/risk/npm/malware.js +38 -0
  194. package/risk/npm/manifest.js +65 -0
  195. package/risk/npm/new-dependency.js +60 -0
  196. package/risk/npm/old-version.js +108 -0
  197. package/risk/npm/registry.js +390 -0
  198. package/risk/npm/release.js +85 -0
  199. package/risk/npm/score.js +59 -0
  200. package/risk/npm/specs.js +124 -0
  201. package/risk/npm/tarball.js +96 -0
  202. package/server-common/database-config.ts +16 -0
  203. package/server-common/initialize.ts +18 -0
  204. package/server-common/npm-advisories.ts +101 -0
  205. package/{server → server-common}/origin.ts +5 -5
  206. package/server-common/reap.ts +48 -0
  207. package/server-common/scan-config.ts +19 -0
  208. package/server-common/standalone.ts +29 -0
  209. package/server-common/storage-crypto.ts +182 -0
  210. package/server-common/storage-log.ts +38 -0
  211. package/server-common/vercel-blob.ts +103 -0
  212. package/server-e2e/app.ts +487 -0
  213. package/{server → server-e2e}/bus-receiver.ts +2 -1
  214. package/{server → server-e2e}/cli.js +9 -4
  215. package/{server → server-e2e}/config.ts +50 -42
  216. package/{server → server-e2e}/db-neon.ts +2 -2
  217. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  218. package/{server → server-e2e}/db-stmt.ts +2 -2
  219. package/{server → server-e2e}/db.ts +7 -7
  220. package/{server → server-e2e}/http.ts +44 -13
  221. package/{server → server-e2e}/hub.ts +40 -9
  222. package/server-e2e/index.ts +17 -0
  223. package/server-e2e/lifecycle.ts +95 -0
  224. package/{server → server-e2e}/neon-driver.ts +2 -2
  225. package/{server → server-e2e}/npm-proxy.ts +12 -145
  226. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  227. package/{server → server-e2e}/objstore/blob.ts +1 -1
  228. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  229. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  230. package/{server → server-e2e}/objstore/init.ts +19 -27
  231. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  232. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  233. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  234. package/{server → server-e2e}/objstore/rest.ts +3 -3
  235. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  236. package/{server → server-e2e}/objstore/store.ts +7 -7
  237. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  238. package/{server → server-e2e}/pubsub.ts +12 -9
  239. package/{server → server-e2e}/sign.ts +4 -4
  240. package/{server → server-e2e}/sse-server.ts +60 -33
  241. package/{server → server-e2e}/static.ts +31 -21
  242. package/{server → server-e2e}/sync-handlers.ts +64 -30
  243. package/{server → server-e2e}/ws-server.ts +20 -9
  244. package/server-managed/activity.ts +258 -0
  245. package/server-managed/agent-merges.ts +109 -0
  246. package/server-managed/app-agents.ts +23 -0
  247. package/server-managed/avatar-store.ts +13 -0
  248. package/server-managed/blob-store.ts +17 -0
  249. package/server-managed/brotli.ts +10 -0
  250. package/server-managed/bundle-advisories.ts +102 -0
  251. package/server-managed/bundle-advisory-inventory.ts +77 -0
  252. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  253. package/server-managed/bundle-build-diagnostics.js +23 -0
  254. package/server-managed/bundle-build-leases.ts +41 -0
  255. package/server-managed/bundle-build-worker.js +203 -0
  256. package/server-managed/bundle-build.ts +232 -0
  257. package/server-managed/bundle-cache.ts +211 -0
  258. package/server-managed/bundle-catalog.ts +29 -0
  259. package/server-managed/bundle-commits.ts +140 -0
  260. package/server-managed/bundle-dependency-reviews.ts +74 -0
  261. package/server-managed/bundle-store.ts +24 -0
  262. package/server-managed/bundle-summary-cache.ts +130 -0
  263. package/server-managed/bundle-validation.ts +32 -0
  264. package/server-managed/bundle.ts +119 -0
  265. package/server-managed/cache-storage.ts +20 -0
  266. package/server-managed/cli.js +21 -0
  267. package/server-managed/combined.ts +47 -0
  268. package/server-managed/comments.ts +151 -0
  269. package/server-managed/commit-coauthors.ts +106 -0
  270. package/server-managed/commit-lockfiles.ts +76 -0
  271. package/server-managed/comparison.ts +52 -0
  272. package/server-managed/config.ts +164 -0
  273. package/server-managed/content-access.ts +15 -0
  274. package/server-managed/crypto.ts +25 -0
  275. package/server-managed/db-methods.ts +1958 -0
  276. package/server-managed/db-neon.ts +484 -0
  277. package/server-managed/db-schema.ts +238 -0
  278. package/server-managed/db-table-names.ts +22 -0
  279. package/server-managed/db.ts +152 -0
  280. package/server-managed/dependabot-access.ts +60 -0
  281. package/server-managed/dependabot-alerts.ts +185 -0
  282. package/server-managed/dependency-review-comments.ts +98 -0
  283. package/server-managed/dependency-reviews.ts +364 -0
  284. package/server-managed/github-accounts.ts +60 -0
  285. package/server-managed/github-actions.ts +71 -0
  286. package/server-managed/github-app.ts +376 -0
  287. package/server-managed/github-errors.ts +70 -0
  288. package/server-managed/github-graphql.ts +39 -0
  289. package/server-managed/github-issue-links.ts +244 -0
  290. package/server-managed/github-issue-oauth.ts +47 -0
  291. package/server-managed/github-issues.ts +155 -0
  292. package/server-managed/github-link-oauth.ts +69 -0
  293. package/server-managed/github-links.ts +204 -0
  294. package/server-managed/github-metadata.ts +213 -0
  295. package/server-managed/github-oauth.ts +238 -0
  296. package/server-managed/github-pulls.ts +246 -0
  297. package/server-managed/github-requests.ts +166 -0
  298. package/server-managed/github-users.ts +30 -0
  299. package/server-managed/history-windows.ts +172 -0
  300. package/server-managed/http-response.ts +76 -0
  301. package/server-managed/http.ts +5855 -0
  302. package/server-managed/import-triage.ts +51 -0
  303. package/server-managed/index.ts +204 -0
  304. package/server-managed/kept-briefly.ts +37 -0
  305. package/server-managed/kept.ts +28 -0
  306. package/server-managed/link-reports.ts +162 -0
  307. package/server-managed/listed-activity.ts +39 -0
  308. package/server-managed/locked-packages.ts +152 -0
  309. package/server-managed/lockfile-scope.ts +49 -0
  310. package/server-managed/lru.ts +30 -0
  311. package/server-managed/managed-issues.ts +92 -0
  312. package/server-managed/management-catalog.ts +45 -0
  313. package/server-managed/management.ts +99 -0
  314. package/server-managed/npm-delta-worker.js +23 -0
  315. package/server-managed/npm-delta.ts +194 -0
  316. package/server-managed/npm-insights.ts +450 -0
  317. package/server-managed/npm-kept.ts +233 -0
  318. package/server-managed/npm-loads.ts +264 -0
  319. package/server-managed/npm-manifest.ts +115 -0
  320. package/server-managed/npm-packages.ts +454 -0
  321. package/server-managed/npm-patch.ts +325 -0
  322. package/server-managed/npm-provenance.ts +123 -0
  323. package/server-managed/npm-risk.ts +285 -0
  324. package/server-managed/object-storage-disk.ts +148 -0
  325. package/server-managed/object-storage-vercel.ts +67 -0
  326. package/server-managed/object-storage.ts +75 -0
  327. package/server-managed/package-entry-points.ts +79 -0
  328. package/server-managed/pretty-print.ts +436 -0
  329. package/server-managed/public-workspace.ts +238 -0
  330. package/server-managed/pull-comment-reviews.ts +161 -0
  331. package/server-managed/pull-dependencies.ts +351 -0
  332. package/server-managed/pull-dependency-reviews.ts +334 -0
  333. package/server-managed/pull-reviews.ts +205 -0
  334. package/server-managed/queue.ts +39 -0
  335. package/server-managed/release-commits.ts +84 -0
  336. package/server-managed/rename-diff-worker.js +26 -0
  337. package/server-managed/rename-diff.ts +279 -0
  338. package/server-managed/repo-path.ts +21 -0
  339. package/server-managed/report-migration.ts +35 -0
  340. package/server-managed/report-query.ts +10 -0
  341. package/server-managed/report-response.ts +16 -0
  342. package/server-managed/report-sources.ts +185 -0
  343. package/server-managed/report-store.ts +85 -0
  344. package/server-managed/repository-actions.ts +221 -0
  345. package/server-managed/repository-agents.ts +448 -0
  346. package/server-managed/repository-aliases.ts +91 -0
  347. package/server-managed/repository-browser.ts +301 -0
  348. package/server-managed/repository-changes.ts +284 -0
  349. package/server-managed/repository-code.ts +215 -0
  350. package/server-managed/repository-dependency-reviews.ts +166 -0
  351. package/server-managed/repository-discovery.ts +82 -0
  352. package/server-managed/repository-history.ts +432 -0
  353. package/server-managed/repository-issues.ts +195 -0
  354. package/server-managed/repository-policy.ts +27 -0
  355. package/server-managed/repository-pulls.ts +212 -0
  356. package/server-managed/repository-pulse.ts +471 -0
  357. package/server-managed/repository-risk-assess.ts +105 -0
  358. package/server-managed/repository-risk-audit.ts +78 -0
  359. package/server-managed/repository-risk-read.ts +170 -0
  360. package/server-managed/repository-risk.ts +491 -0
  361. package/server-managed/repository-squashes.ts +168 -0
  362. package/server-managed/repository-stamp.ts +41 -0
  363. package/server-managed/request-timing.ts +63 -0
  364. package/server-managed/reviewed-dependencies.ts +149 -0
  365. package/server-managed/revisions.ts +35 -0
  366. package/server-managed/scan-downloads.ts +87 -0
  367. package/server-managed/session.ts +132 -0
  368. package/server-managed/slugs.ts +38 -0
  369. package/server-managed/solidity-entry-points.ts +71 -0
  370. package/server-managed/sql-postgres.ts +34 -0
  371. package/server-managed/sql.ts +89 -0
  372. package/server-managed/stasis-config.ts +55 -0
  373. package/server-managed/static.ts +28 -0
  374. package/server-managed/storage-command.ts +16 -0
  375. package/server-managed/storage-db.ts +183 -0
  376. package/server-managed/storage-encryption.ts +290 -0
  377. package/server-managed/storage-maintenance.ts +259 -0
  378. package/server-managed/storage-payload.ts +121 -0
  379. package/server-managed/storage-stores.ts +91 -0
  380. package/server-managed/storage.ts +82 -0
  381. package/server-managed/team-app-summaries.ts +54 -0
  382. package/server-managed/team-app.ts +157 -0
  383. package/server-managed/team-catalog.ts +7 -0
  384. package/server-managed/team-feed.ts +180 -0
  385. package/server-managed/team-npm-scopes.ts +106 -0
  386. package/server-managed/team-reports.ts +351 -0
  387. package/server-managed/triage-response.ts +16 -0
  388. package/server-managed/type-only-worker.js +19 -0
  389. package/server-managed/type-only.ts +105 -0
  390. package/server-managed/uploads.ts +106 -0
  391. package/server-managed/upstream-cache.ts +252 -0
  392. package/server-managed/view-as.ts +58 -0
  393. package/server-managed/workspace-shares.ts +171 -0
  394. package/server.ts +70 -0
  395. package/server/index.ts +0 -480
  396. package/server/lifecycle.ts +0 -208
  397. /package/{LICENSE → LICENSE-MIT} +0 -0
  398. /package/{server → server-e2e}/auth.ts +0 -0
  399. /package/{server → server-e2e}/config.example.json +0 -0
  400. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  401. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  402. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  403. /package/{server → server-e2e}/peer.ts +0 -0
  404. /package/{server → server-e2e}/sse-session.ts +0 -0
  405. /package/{server → server-e2e}/util.ts +0 -0
  406. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,19 @@
1
+ // Which of a comparison's pairs of files changed in types alone (type-only.ts),
2
+ // as @preventive/compare's compareTrees stamps a change `typeOnly`, off the
3
+ // server's event loop: each pair a tree of a file a side, a side not there
4
+ // none, its paths as they are, which say what a file is. Two paths pair as one
5
+ // change wherever compareTrees takes them for a rename at all; where it
6
+ // doesn't, the pair is types only where each of its two changes is: the file
7
+ // gone erasing whole, and the one come erasing whole or leaving a single bare
8
+ // `export {}`, which nothing loaded before. `[true, false, ...]` by pair.
9
+ import { parentPort, workerData } from 'node:worker_threads'
10
+ import { compareTrees } from '@preventive/compare'
11
+
12
+ const tree = file => (file ? [{ name: file.path, data: file.text }] : [])
13
+ const answer = workerData.pairs.map(([from, to]) => {
14
+ const changes = compareTrees(tree(from), tree(to), { paths: 'keys', lines: false, renames: Number.MIN_VALUE })
15
+ return changes.length > 0 && changes.every(change => change.typeOnly === true)
16
+ })
17
+ // Node worker messages have no browser target origin.
18
+ // oxlint-disable-next-line unicorn/require-post-message-target-origin
19
+ parentPort.postMessage(answer)
@@ -0,0 +1,105 @@
1
+ // Compare's changes to TypeScript declaration files in types alone (GET
2
+ // /api/bundles/:id/type-only?other=, GET /api/npm/type-only): every file
3
+ // that changed between a comparison's two sides, added and removed ones too,
4
+ // paired as its viewer pairs them (rename-diff.ts comparedFiles), whose
5
+ // change @preventive/compare's compareTrees stamps
6
+ // `typeOnly` -- each side there a file named as a declaration file and
7
+ // proven to hold types alone but for a runtime, the module loads and
8
+ // `export {}` its stripping leaves, that the change leaves as it was, an
9
+ // added one's empty or a single bare `export {}` (proveTypeOnly) -- and
10
+ // nothing else. Proven in a worker, off the event loop, a comparison at a
11
+ // time per process, for at most a minute; told a line each, `{ path, hash,
12
+ // otherPath, otherHash }`, a side not there null, which the viewer checks
13
+ // name the files it shows. Access is the caller's to check.
14
+ import { Worker } from 'node:worker_threads'
15
+ import { type ComparedSide, PrettyError, type PrettyRequest } from './pretty-print.ts'
16
+ import { comparedFiles } from './rename-diff.ts'
17
+
18
+ // TypeScript files, by extension as the pretty-print cache reads them: none
19
+ // other is asked about.
20
+ const TYPESCRIPT = new Set(['ts', 'mts', 'cts'])
21
+ // Comparisons proven at once per process, and those waiting their turn past
22
+ // them, any more refused; the longest one may take, its wait included.
23
+ const MAX_ACTIVE_PROOFS = 1
24
+ const MAX_WAITING_PROOFS = 16
25
+ const PROOF_TIMEOUT_MS = 60_000
26
+
27
+ type File = PrettyRequest & { text: string }
28
+ export interface TypeOnlyLine { path: string | null; hash: string | null; otherPath: string | null; otherHash: string | null }
29
+
30
+ let active = 0
31
+ const waiting: Array<() => void> = []
32
+
33
+ async function turn(deadline: number): Promise<void> {
34
+ if (active < MAX_ACTIVE_PROOFS) { active++; return }
35
+ if (waiting.length >= MAX_WAITING_PROOFS) throw new PrettyError(429, 'proof-busy')
36
+ await new Promise<void>((resolve, reject) => {
37
+ const next = () => { clearTimeout(timer); resolve() }
38
+ const timer = setTimeout(() => {
39
+ waiting.splice(waiting.indexOf(next), 1)
40
+ reject(new PrettyError(504, 'proof-timeout'))
41
+ }, deadline - Date.now())
42
+ waiting.push(next)
43
+ })
44
+ }
45
+ function done() {
46
+ const next = waiting.shift()
47
+ if (next) next()
48
+ else active--
49
+ }
50
+
51
+ // Which of `pairs` compareTrees stamps types only, by index, in a worker
52
+ // settled once it is gone; none where it fails, as no proof should.
53
+ function proven(pairs: Array<[File | null, File | null]>, deadline: number): Promise<boolean[]> {
54
+ let worker: Worker
55
+ try {
56
+ worker = new Worker(new URL('./type-only-worker.js', import.meta.url), {
57
+ workerData: { pairs: pairs.map(sides => sides.map(file => file && { path: file.path, text: file.text })) },
58
+ // Node's type stripping, which the proof holds oxc's tree to, warns it is experimental.
59
+ execArgv: ['--disable-warning=ExperimentalWarning'], resourceLimits: { maxOldGenerationSizeMb: 1024 },
60
+ })
61
+ } catch (err) {
62
+ console.warn('managed: a type-only proof could not start:', err)
63
+ throw new PrettyError(503, 'unavailable')
64
+ }
65
+ return new Promise((resolve, reject) => {
66
+ let answer: boolean[] | null = null, failure = new PrettyError(422, 'unproven')
67
+ const timer = setTimeout(() => { failure = new PrettyError(504, 'proof-timeout'); void worker.terminate() }, deadline - Date.now())
68
+ worker.once('message', (told: unknown) => {
69
+ if (Array.isArray(told) && told.length === pairs.length && told.every(one => typeof one === 'boolean')) answer = told
70
+ void worker.terminate()
71
+ })
72
+ worker.once('error', err => { console.warn('managed: a type-only proof failed:', err) })
73
+ worker.once('exit', () => {
74
+ clearTimeout(timer)
75
+ if (answer) resolve(answer)
76
+ else reject(failure)
77
+ })
78
+ })
79
+ }
80
+
81
+ // The files that changed between a comparison's two sides in types alone,
82
+ // as the viewer pairs them, a line each once all are proven, in path order.
83
+ export function typeOnlyFiles([base, other]: readonly [ComparedSide, ComparedSide]): AsyncGenerator<TypeOnlyLine> {
84
+ const typescript = ({ files }: ComparedSide) => new Map(files.filter(file => TYPESCRIPT.has(file.extension)).map(file => [file.path, file]))
85
+ const [olds, news] = [typescript(base), typescript(other)]
86
+ const { changed, onlyBase, onlyOther } = comparedFiles([base, other])
87
+ // A side there not a TypeScript file this reads leaves its pair out; one not there is null.
88
+ const pairs = [...changed.map(({ path, basePath = path }) => [olds.get(basePath), news.get(path)]),
89
+ ...onlyBase.map(({ path, basePath = path }) => [olds.get(basePath), null]), ...onlyOther.map(({ path }) => [null, news.get(path)])]
90
+ .filter((sides): sides is [File | null, File | null] => sides.every(file => file !== undefined) && sides.some(file => file !== null) && sides[0]?.hash !== sides[1]?.hash)
91
+ .toSorted(([a, b], [c, d]) => {
92
+ const [x, y] = [(b ?? a)!.path, (d ?? c)!.path]
93
+ return x < y ? -1 : x > y ? 1 : 0
94
+ })
95
+ return (async function* () {
96
+ if (pairs.length === 0) return
97
+ const deadline = Date.now() + PROOF_TIMEOUT_MS
98
+ await turn(deadline)
99
+ let stamped
100
+ try { stamped = await proven(pairs, deadline) } finally { done() }
101
+ for (const [i, [from, to]] of pairs.entries()) {
102
+ if (stamped[i]) yield { path: from?.path ?? null, hash: from?.hash ?? null, otherPath: to?.path ?? null, otherHash: to?.hash ?? null }
103
+ }
104
+ })()
105
+ }
@@ -0,0 +1,106 @@
1
+ // Staging is shared storage, never process memory. Each part is bound to the
2
+ // authenticated session, destination and random upload ID. No bearer URL is
3
+ // exposed; all reads/writes still pass the managed role/origin/CSRF gates.
4
+ import { Buffer } from 'node:buffer'
5
+ import { createHash, generateKeyPairSync } from 'node:crypto'
6
+ import type { IncomingMessage } from 'node:http'
7
+ import type { BlobStore } from './blob-store.ts'
8
+ import { maxSealedBytes, openUpload } from '../common/managed/upload-seal.ts'
9
+
10
+ export const UPLOAD_CHUNK_BYTES = 3 * 1024 * 1024
11
+ export const MAX_UPLOAD_BYTES = 1024 * 1024 * 1024
12
+ // Staged parts may carry a sealed body, slightly larger than its content.
13
+ const MAX_STAGED_BYTES = maxSealedBytes(MAX_UPLOAD_BYTES)
14
+ const MAX_UPLOAD_PARTS = Math.ceil(MAX_STAGED_BYTES / UPLOAD_CHUNK_BYTES)
15
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u
16
+ export type UploadKind = 'reports' | 'bundles'
17
+
18
+ function partId(session: string, kind: UploadKind, id: string, index: number): string {
19
+ const hash = createHash('sha256').update(JSON.stringify([session, kind, id, index])).digest('hex').slice(0, 32)
20
+ return `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20)}`
21
+ }
22
+
23
+ export function validUploadPart(id: string, index: number, maxBytes: number): boolean {
24
+ return UUID.test(id) && Number.isSafeInteger(index) && index >= 0 && index < Math.ceil(Math.min(maxSealedBytes(maxBytes), MAX_STAGED_BYTES) / UPLOAD_CHUNK_BYTES)
25
+ }
26
+
27
+ export function validUpload(id: string, count: number): boolean {
28
+ return UUID.test(id) && Number.isSafeInteger(count) && count > 0
29
+ }
30
+
31
+ // Limit cleanup to indices that any configured server could have accepted,
32
+ // even if the request advertises an enormous count or the limit was lowered.
33
+ export async function deleteUpload(store: BlobStore, session: string, kind: UploadKind, id: string, count: number): Promise<void> {
34
+ if (!validUpload(id, count)) throw new Error('bad-upload')
35
+ const end = Math.min(count, MAX_UPLOAD_PARTS), errors = []
36
+ for (let start = 0; start < end; start += 8) {
37
+ const results = await Promise.allSettled(Array.from({ length: Math.min(8, end - start) },
38
+ (_, index) => store.delete(partId(session, kind, id, start + index))))
39
+ for (const result of results) if (result.status === 'rejected') errors.push(result.reason)
40
+ }
41
+ if (errors.length > 0) throw new AggregateError(errors, 'Upload cleanup failed')
42
+ }
43
+
44
+ export async function putUploadPart(store: BlobStore, session: string, kind: UploadKind, id: string, index: number, bytes: Buffer): Promise<void> {
45
+ await store.put(partId(session, kind, id, index), bytes)
46
+ }
47
+
48
+ // Parts read at once while an upload is put together.
49
+ const PARTS_READ_AT_ONCE = 6
50
+
51
+ // The staged upload `req` names, its parts read a few at a time into the one
52
+ // buffer it fills, each as long as its place in it. Its parts are deleted
53
+ // once read, or once it fails: awaited, unless `behind` takes that cleanup to
54
+ // go on past the response (http.ts), which staging maintenance backs up.
55
+ export async function readUpload(store: BlobStore, req: IncomingMessage, session: string, kind: UploadKind, maxBytes: number,
56
+ behind?: (cleanup: Promise<void>) => void): Promise<Buffer> {
57
+ const id = req.headers['x-upload-id']
58
+ const count = Number(req.headers['x-upload-parts']), size = Number(req.headers['x-upload-size'])
59
+ if (typeof id !== 'string' || !validUpload(id, count)) throw new Error('bad-upload')
60
+ try {
61
+ if (!Number.isSafeInteger(size) || size <= 0 || count !== Math.ceil(size / UPLOAD_CHUNK_BYTES)) throw new Error('bad-upload')
62
+ if (size > maxBytes || size > MAX_STAGED_BYTES) throw new Error('too-large')
63
+ // Every byte of it is written below before it is returned: each part
64
+ // must fill its place exactly, or the upload fails.
65
+ const body = Buffer.allocUnsafe(size)
66
+ let failed = false, next = 0
67
+ const readParts = async () => {
68
+ while (!failed && next < count) {
69
+ const index = next++
70
+ const bytes = await store.get(partId(session, kind, id, index))
71
+ const expected = Math.min(UPLOAD_CHUNK_BYTES, size - index * UPLOAD_CHUNK_BYTES)
72
+ if (!bytes || bytes.length !== expected) { failed = true; throw new Error('bad-upload') }
73
+ bytes.copy(body, index * UPLOAD_CHUNK_BYTES)
74
+ }
75
+ }
76
+ // Each read settled before its parts are deleted.
77
+ const results = await Promise.allSettled(Array.from({ length: Math.min(PARTS_READ_AT_ONCE, count) }, readParts))
78
+ const rejected = results.find(result => result.status === 'rejected')
79
+ if (rejected) throw rejected.reason
80
+ return body
81
+ } finally {
82
+ // These bytes can no longer be finalized. Failed/abandoned chunk uploads
83
+ // are also covered by automatic staging maintenance.
84
+ const cleanup = deleteUpload(store, session, kind, id, count).catch(err => console.warn('managed: upload cleanup failed:', err))
85
+ if (behind) behind(cleanup)
86
+ else await cleanup
87
+ }
88
+ }
89
+
90
+ // A session's upload key pair, stored as its private JWK.
91
+ export function newUploadKey(): string {
92
+ const { privateKey } = generateKeyPairSync('x25519')
93
+ const { kty, crv, x, d } = privateKey.export({ format: 'jwk' })
94
+ return JSON.stringify({ kty, crv, x, d })
95
+ }
96
+
97
+ // The raw public key (base64url) browsers seal this session's uploads to.
98
+ export function uploadPublicKey(key: string): string {
99
+ return (JSON.parse(key) as { x: string }).x
100
+ }
101
+
102
+ export async function openSessionUpload(key: string | null | undefined, sealed: Buffer, maxBytes: number): Promise<Buffer> {
103
+ if (!key) throw new Error('bad-upload')
104
+ const bytes = await openUpload(new Uint8Array(sealed.buffer as ArrayBuffer, sealed.byteOffset, sealed.byteLength), JSON.parse(key) as JsonWebKey, maxBytes)
105
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)
106
+ }
@@ -0,0 +1,252 @@
1
+ import { Buffer } from 'node:buffer'
2
+ import { constants } from 'node:fs'
3
+ import { mkdir, open, rename, rm, writeFile } from 'node:fs/promises'
4
+ import { dirname, join } from 'node:path'
5
+ import { promisify } from 'node:util'
6
+ import { gunzip, gzip } from 'node:zlib'
7
+ import type { CacheStore, Package } from '@preventive/upstream/advisories.js'
8
+ import type { ManagedSql } from './sql.ts'
9
+
10
+ // Records @preventive/upstream would otherwise keep in its disk cache, shared
11
+ // by every instance: each repository's published advisory listing, written by
12
+ // dependency audits that ask repositories, keyed `github/advisories/owner/name`,
13
+ // and each npm package npm's registry serves anyone, written by audits that ask
14
+ // OSV, keyed `npm/public/name`. Upstream stamps, validates and expires each
15
+ // value (90 minutes for a listing, a month for a public name); a refresh
16
+ // replaces the row, and there is one row per repository or name, so rows are
17
+ // not evicted. Only public repositories publish advisories, and only names
18
+ // anyone may read are kept: rows are shared across viewers.
19
+ export const UPSTREAM_CACHE_SCHEMA = `
20
+ CREATE TABLE IF NOT EXISTS managed_upstream_cache (
21
+ cache_key TEXT PRIMARY KEY,
22
+ value TEXT NOT NULL,
23
+ cached_at INTEGER NOT NULL
24
+ ) STRICT;
25
+ `
26
+
27
+ export interface UpstreamCacheStore {
28
+ getUpstreamCacheEntry(key: string): Promise<string | null>
29
+ // Key → value for those of `keys` that are kept.
30
+ getUpstreamCacheEntries(keys: string[]): Promise<Map<string, string>>
31
+ // Those of `first` that are kept; where none is, those of `then`, in the
32
+ // same statement (`first` whether they are `first`'s).
33
+ getFirstUpstreamCacheEntries(first: string[], then: string[]): Promise<{ first: boolean; entries: Map<string, string> }>
34
+ setUpstreamCacheEntry(key: string, value: string, cachedAt: number): Promise<void>
35
+ // Each of `entries` (key, value), as setUpstreamCacheEntry keeps one, in one
36
+ // statement: the last of a key given twice.
37
+ setUpstreamCacheEntries(entries: [key: string, value: string][], cachedAt: number): Promise<void>
38
+ // Removes those under `prefix` (no LIKE wildcard in it) kept before `before`;
39
+ // how many.
40
+ deleteUpstreamCacheEntries(prefix: string, before: number): Promise<number>
41
+ }
42
+
43
+ export function upstreamCacheMethods(db: ManagedSql): UpstreamCacheStore {
44
+ const get = db.prepare('SELECT value FROM managed_upstream_cache WHERE cache_key = ?')
45
+ const getMany = db.prepare('SELECT cache_key, value FROM managed_upstream_cache WHERE cache_key IN (SELECT value FROM json_each(?))')
46
+ const getFirst = db.prepare(`WITH found AS (SELECT cache_key, value FROM managed_upstream_cache WHERE cache_key IN (SELECT value FROM json_each(?)))
47
+ SELECT cache_key, value, 1 AS in_first FROM found
48
+ UNION ALL SELECT cache_key, value, 0 AS in_first FROM managed_upstream_cache
49
+ WHERE cache_key IN (SELECT value FROM json_each(?)) AND NOT EXISTS (SELECT 1 FROM found)`)
50
+ // A slower concurrent audit cannot replace a newer listing with an older one.
51
+ const set = db.prepare(`INSERT INTO managed_upstream_cache (cache_key, value, cached_at) VALUES (?, ?, ?)
52
+ ON CONFLICT (cache_key) DO UPDATE SET value = excluded.value, cached_at = excluded.cached_at
53
+ WHERE managed_upstream_cache.cached_at <= excluded.cached_at`)
54
+ const remove = db.prepare('DELETE FROM managed_upstream_cache WHERE cache_key LIKE ? AND cached_at < ?')
55
+ // setUpstreamCacheEntries's, by how many it keeps at once.
56
+ const setMany = new Map<number, ReturnType<ManagedSql['prepare']>>()
57
+ return {
58
+ async getUpstreamCacheEntry(key) {
59
+ const row = await get.get(key) as { value: string } | undefined
60
+ return row?.value ?? null
61
+ },
62
+ async getUpstreamCacheEntries(keys) {
63
+ if (keys.length === 0) return new Map()
64
+ const rows = await getMany.all(JSON.stringify(keys)) as { cache_key: string; value: string }[]
65
+ return new Map(rows.map(row => [row.cache_key, row.value]))
66
+ },
67
+ async getFirstUpstreamCacheEntries(first, then) {
68
+ if (first.length === 0 && then.length === 0) return { first: false, entries: new Map() }
69
+ const rows = await getFirst.all(JSON.stringify(first), JSON.stringify(then)) as { cache_key: string; value: string; in_first: number }[]
70
+ return { first: rows.some(row => Number(row.in_first) === 1), entries: new Map(rows.map(row => [row.cache_key, row.value])) }
71
+ },
72
+ async setUpstreamCacheEntry(key, value, cachedAt) {
73
+ await set.run(key, value, cachedAt)
74
+ },
75
+ async setUpstreamCacheEntries(entries, cachedAt) {
76
+ const rows = [...new Map(entries)]
77
+ if (rows.length === 0) return
78
+ let many = setMany.get(rows.length)
79
+ if (!many) {
80
+ setMany.set(rows.length, many = db.prepare(`INSERT INTO managed_upstream_cache (cache_key, value, cached_at) VALUES ${rows.map(() => '(?, ?, ?)').join(', ')}
81
+ ON CONFLICT (cache_key) DO UPDATE SET value = excluded.value, cached_at = excluded.cached_at
82
+ WHERE managed_upstream_cache.cached_at <= excluded.cached_at`))
83
+ }
84
+ await many.run(...rows.flatMap(([key, value]) => [key, value, cachedAt]))
85
+ },
86
+ async deleteUpstreamCacheEntries(prefix, before) {
87
+ return Number((await remove.run(`${prefix}%`, before)).changes)
88
+ },
89
+ }
90
+ }
91
+
92
+ // An audit's `cache`: where the server has an upstream disk cache (off Vercel,
93
+ // set at startup), that keeps everything; else this store keeps listings and
94
+ // public names, those of `keys` (auditedKeys) read at once.
95
+ export function auditCache(cacheDir: string | null | undefined, db: UpstreamCacheStore, signal: AbortSignal, debug = false, keys: Iterable<string> = []): CacheStore | undefined {
96
+ return cacheDir ? undefined : upstreamCache(db, signal, debug, keys)
97
+ }
98
+
99
+ // Only listings and public names are kept: upstream's other records (npm
100
+ // version documents, registries' repository lookups) read as misses and are
101
+ // not written.
102
+ const LISTINGS = 'github/advisories'
103
+ const PUBLIC_NAMES = 'npm/public'
104
+ const CACHED_TYPES = new Set([LISTINGS, PUBLIC_NAMES])
105
+
106
+ // What an audit of `packages` reads first, where it is already known: the
107
+ // listings of the repositories it knows, each `github` package, each `soldeer`
108
+ // package's given repository, and with `repoAdvisories`, every other
109
+ // package's, upstream looking up the rest itself; and whether each npm package
110
+ // is public, as upstream asks before it asks OSV of it. Each as upstream asks
111
+ // for it, a listing by its repository's lowercased name.
112
+ export function auditedKeys(packages: Iterable<Package>, repoAdvisories: boolean): string[] {
113
+ return [...new Set([...packages].flatMap(pkg => {
114
+ const repo = pkg.ecosystem === 'github' ? pkg.name : pkg.ecosystem === 'soldeer' || repoAdvisories ? pkg.github : undefined
115
+ return [...pkg.ecosystem === 'npm' ? [`${PUBLIC_NAMES}/${pkg.name}`] : [], ...repo === undefined ? [] : [`${LISTINGS}/${repo.toLowerCase()}`]]
116
+ }))]
117
+ }
118
+
119
+ // The cache is an optimization: a database failure is a miss, never a failed
120
+ // audit. Upstream keeps listing after an abandoned audit; once `signal` aborts,
121
+ // the request's database work is over and the store is left alone.
122
+ // Upstream reads one listing at a time per repository, and whether a name is
123
+ // public eight at a time, and a request's queries share one connection (Neon),
124
+ // so a recheck of hundreds of packages would wait on as many round trips: the
125
+ // first read asks for every one of `keys` at once. Any other key, or all of
126
+ // them if that read fails, is read alone.
127
+ export function upstreamCache(db: UpstreamCacheStore, signal: AbortSignal, debug = false, keys: Iterable<string> = []): CacheStore {
128
+ const batched = new Set(keys)
129
+ let batch: Promise<Map<string, string> | null> | undefined
130
+ const readBatch = () => batch ??= db.getUpstreamCacheEntries([...batched]).catch((error: unknown) => {
131
+ if (debug) console.warn('managed: upstream cache read failed:', error)
132
+ return null
133
+ })
134
+ return {
135
+ async read(type, key) {
136
+ if (!CACHED_TYPES.has(type) || signal.aborted) return null
137
+ const cacheKey = `${type}/${key}`
138
+ try {
139
+ const found = batched.has(cacheKey) ? await readBatch() : null
140
+ const value = found ? found.get(cacheKey) ?? null : await db.getUpstreamCacheEntry(cacheKey)
141
+ return value === null ? null : JSON.parse(value) as unknown
142
+ } catch (error) {
143
+ if (debug) console.warn('managed: upstream cache read failed:', error)
144
+ return null
145
+ }
146
+ },
147
+ async write(type, key, value) {
148
+ if (!CACHED_TYPES.has(type) || signal.aborted) return
149
+ try { await db.setUpstreamCacheEntry(`${type}/${key}`, JSON.stringify(value), Date.now()) } catch (error) {
150
+ if (debug) console.warn('managed: upstream cache write failed:', error)
151
+ }
152
+ },
153
+ }
154
+ }
155
+
156
+ // The file upstream keeps `file` in, under `dir` of its disk cache
157
+ // (setCacheDir), as its cachePath names it: `@babel+core@7.29.7.tgz`, a
158
+ // capital written `!` and the letter, and a Windows device name's first
159
+ // letter escaped.
160
+ export function upstreamCachePath(root: string, dir: string, file: string): string {
161
+ const name = encodeURIComponent(file.replaceAll(/[!A-Z]/gu, char => `!${char.toLowerCase()}`))
162
+ .replaceAll('%40', '@').replaceAll('%2F', '+')
163
+ .replace(/^(?=(?:con|prn|aux|nul|com\d|lpt\d)(?:\.|$))./u, char => `%${char.codePointAt(0)!.toString(16).toUpperCase()}`)
164
+ return join(root, dir, name)
165
+ }
166
+
167
+ // A kept file, where it is a regular file of at most `max` bytes, checked on
168
+ // the file as opened (a FIFO or device would block or never end), and read
169
+ // to the size it had then.
170
+ export async function readKeptFile(path: string, max: number): Promise<Uint8Array | null> {
171
+ const handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK).catch(() => null)
172
+ if (!handle) return null
173
+ try {
174
+ const stats = await handle.stat()
175
+ if (!stats.isFile() || stats.size > max) return null
176
+ const bytes = Buffer.allocUnsafe(stats.size)
177
+ for (let at = 0; at < bytes.length;) {
178
+ const { bytesRead } = await handle.read(bytes, at, bytes.length - at, at)
179
+ if (bytesRead === 0) return null
180
+ at += bytesRead
181
+ }
182
+ return bytes
183
+ } catch { return null }
184
+ finally { await handle.close() }
185
+ }
186
+
187
+ // `bytes` kept at `path`, written whole beside it first and then moved in, so a
188
+ // reader finds the old file or the new one, never part of one; a failure
189
+ // keeps nothing.
190
+ let tmpSeq = 0
191
+ export async function keepFile(path: string, bytes: Uint8Array) {
192
+ const tmp = `${path}.${process.pid}.${++tmpSeq}.tmp`
193
+ try {
194
+ await mkdir(dirname(path), { recursive: true })
195
+ await writeFile(tmp, bytes)
196
+ await rename(tmp, path)
197
+ } catch { await rm(tmp, { force: true }).catch(() => {}) }
198
+ }
199
+
200
+ const gunzipAsync = promisify(gunzip)
201
+ const gzipAsync = promisify(gzip)
202
+
203
+ // An upstream's JSON object kept with its ETag, gzipped, as keepJson keeps it:
204
+ // `{ etag, json }`, or null where none is kept, or what is can't be read
205
+ // within `limit` bytes.
206
+ export async function readKeptJson(path: string, limit: number): Promise<{ etag: string; json: Record<string, unknown> } | null> {
207
+ const bytes = await readKeptFile(path, limit)
208
+ if (!bytes) return null
209
+ const object = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === 'object' && !Array.isArray(value)
210
+ try {
211
+ const kept: unknown = JSON.parse((await gunzipAsync(bytes, { maxOutputLength: limit + 1024 })).toString('utf8'))
212
+ return object(kept) && typeof kept['etag'] === 'string' && object(kept['json']) ? { etag: kept['etag'], json: kept['json'] } : null
213
+ } catch { return null }
214
+ }
215
+
216
+ // `body`, an upstream's JSON object as it wrote it, kept with its `etag`.
217
+ export async function keepJson(path: string, etag: string, body: Buffer) {
218
+ await keepFile(path, await gzipAsync(Buffer.concat([Buffer.from(`{"etag":${JSON.stringify(etag)},"json":`), body, Buffer.from('}')])))
219
+ }
220
+
221
+ // A kept listing is read to no more than this, gzipped or not: one runs to
222
+ // some hundreds of KiB.
223
+ const LISTING_BYTES = 64 * 1024 * 1024
224
+
225
+ // A repository's listing as last kept where audits keep them (auditCache),
226
+ // however old, for when GitHub can't be reached to refresh it: `at`, when it
227
+ // was kept, and `cache`, a store answering it to upstream as kept just now,
228
+ // so that upstream takes it rather than ask GitHub, and keeping nothing.
229
+ // Upstream checks it as it checks its own. Null where none is kept, or it
230
+ // can't be read.
231
+ export async function lastListing(cacheDir: string | null | undefined, db: UpstreamCacheStore, repo: string, debug = false): Promise<{ at: number; cache: CacheStore } | null> {
232
+ const key = repo.toLowerCase()
233
+ let kept: { at?: unknown } | null
234
+ try {
235
+ if (cacheDir) {
236
+ const bytes = await readKeptFile(upstreamCachePath(cacheDir, LISTINGS, `${key}.json.gz`), LISTING_BYTES)
237
+ kept = bytes && JSON.parse((await gunzipAsync(bytes, { maxOutputLength: LISTING_BYTES })).toString('utf8'))
238
+ } else {
239
+ const value = await db.getUpstreamCacheEntry(`${LISTINGS}/${key}`)
240
+ kept = value === null ? null : JSON.parse(value)
241
+ }
242
+ } catch (error) {
243
+ if (debug) console.warn('managed: kept listing read failed:', error)
244
+ return null
245
+ }
246
+ const at = kept?.at
247
+ if (typeof at !== 'number') return null
248
+ return { at, cache: {
249
+ read: (type, name) => Promise.resolve(type === LISTINGS && name === key ? { ...kept, at: Date.now() } : null),
250
+ write: () => Promise.resolve(),
251
+ } }
252
+ }
@@ -0,0 +1,58 @@
1
+ // An administrator's read-only view as another user, for checking what that
2
+ // account can access. The view is a session row for the viewed user (so every
3
+ // access check applies that user's role, teams and permissions unchanged) tied
4
+ // to the admin's own session, carried in its own cookie beside the session
5
+ // cookie. Ending the admin session, or the admin role, ends the view.
6
+ //
7
+ // The router refuses writes for any request that carries the view cookie, and
8
+ // such requests never act with the viewed user's GitHub credentials: GitHub
9
+ // data that needs them is left out instead.
10
+ import { AsyncLocalStorage } from 'node:async_hooks'
11
+ import type { ManagedConfig } from './config.ts'
12
+ import type { ManagedDb, ManagedSession } from './db.ts'
13
+ import { hashToken, randomToken } from './crypto.ts'
14
+ import { VIEW_COOKIE, buildCookie, clearCookie, cookieName, parseCookies } from './session.ts'
15
+
16
+ export const VIEW_AS_PATH = '/api/auth/view-as'
17
+ export const VIEW_ONLY_ERROR = 'view-only'
18
+
19
+ function viewCookieName(config: ManagedConfig): string {
20
+ return cookieName(config, VIEW_COOKIE)
21
+ }
22
+
23
+ // The raw view token, or null when the request carries no view.
24
+ export function viewToken(config: ManagedConfig, cookieHeader: string | undefined): string | null {
25
+ const token = parseCookies(cookieHeader).get(viewCookieName(config))
26
+ return token == null || token === '' ? null : token
27
+ }
28
+
29
+ export function clearViewCookie(config: ManagedConfig): string {
30
+ return clearCookie(viewCookieName(config), config.cookieSecure)
31
+ }
32
+
33
+ // Open a view as `userId` from the admin's `session`, replacing any earlier
34
+ // view of that session. Null when the database refuses it (see createViewSession).
35
+ export async function startViewSession(config: ManagedConfig, db: ManagedDb, session: ManagedSession, userId: string, now: number): Promise<string | null> {
36
+ const token = randomToken()
37
+ const ok = await db.createViewSession({ id: hashToken(token), viewerSessionId: session.id, userId, csrfToken: randomToken() }, now)
38
+ if (!ok) return null
39
+ return buildCookie(viewCookieName(config), token, {
40
+ maxAgeS: Math.max(0, Math.floor((session.expiresAt - now) / 1000)), secure: config.cookieSecure, sameSite: 'Lax',
41
+ })
42
+ }
43
+
44
+ export async function endViewSession(config: ManagedConfig, db: ManagedDb, cookieHeader: string | undefined): Promise<void> {
45
+ const token = viewToken(config, cookieHeader)
46
+ if (token != null) await db.deleteSession(hashToken(token))
47
+ }
48
+
49
+ const viewing = new AsyncLocalStorage<boolean>()
50
+
51
+ export function runViewing<T>(active: boolean, work: () => T): T {
52
+ return active ? viewing.run(true, work) : work()
53
+ }
54
+
55
+ // Whether the current request is an admin's view as another user.
56
+ export function isViewing(): boolean {
57
+ return viewing.getStore() === true
58
+ }