@preventive/triage 1.0.0-alpha.6 → 1.0.0-alpha.61
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.
- package/LICENSE-APACHE +202 -0
- package/README.md +16 -0
- package/api/reap.ts +17 -0
- package/cli.js +6 -0
- package/client/dependency-paths.d.ts +3 -0
- package/client/dependency-paths.js +36 -0
- package/client/finding-link.js +305 -0
- package/client/linked-findings.d.ts +1 -0
- package/client/linked-findings.js +115 -0
- package/common/bundle-commit.d.ts +1 -0
- package/common/bundle-commit.js +4 -0
- package/common/bundle-compare-diff.d.ts +3 -0
- package/common/bundle-compare-diff.js +376 -0
- package/common/bundle-compare-inputs.d.ts +3 -0
- package/common/bundle-compare-inputs.js +141 -0
- package/common/bundle-compare-versions.js +172 -0
- package/common/bundle-comparison.d.ts +8 -0
- package/common/bundle-comparison.js +69 -0
- package/common/bundle-metadata.d.ts +15 -0
- package/common/bundle-metadata.js +226 -0
- package/common/bundle-pkg-of.d.ts +1 -0
- package/common/bundle-pkg-of.js +90 -0
- package/common/bundle-reasons.d.ts +2 -0
- package/common/bundle-reasons.js +21 -0
- package/common/bundle-source-links.d.ts +6 -0
- package/common/bundle-source-links.js +216 -0
- package/common/bundle-sourcemap.d.ts +10 -0
- package/common/bundle-sourcemap.js +100 -0
- package/common/bundle-sources.d.ts +7 -0
- package/common/bundle-sources.js +333 -0
- package/common/bundle-stats.js +41 -0
- package/common/bundle-tabs.js +1 -0
- package/common/code-language.js +65 -0
- package/common/default-scan-models.ts +36 -0
- package/common/dependency-reviews.d.ts +18 -0
- package/common/dependency-reviews.js +64 -0
- package/common/finding-duplicates.js +58 -0
- package/common/finding-filters.js +274 -0
- package/common/finding-id.js +47 -0
- package/common/finding-repo.d.ts +5 -0
- package/common/finding-repo.js +67 -0
- package/common/github-issue-labels.d.ts +1 -0
- package/common/github-issue-labels.js +11 -0
- package/common/github-pr.ts +56 -0
- package/common/gzip.js +59 -0
- package/common/line-diff.d.ts +8 -0
- package/common/line-diff.js +57 -0
- package/common/linked-workspace-groups.js +63 -0
- package/common/managed/agent-tasks.ts +292 -0
- package/common/managed/comments.ts +43 -0
- package/common/managed/finding-detail.d.ts +5 -0
- package/common/managed/finding-detail.js +75 -0
- package/common/managed/finding-values.d.ts +2 -0
- package/common/managed/finding-values.js +44 -0
- package/common/managed/github-agents.ts +114 -0
- package/common/managed/github-logins.ts +49 -0
- package/common/managed/lite-name.d.ts +2 -0
- package/common/managed/lite-name.js +20 -0
- package/common/managed/npm-packages.d.ts +7 -0
- package/common/managed/npm-packages.js +51 -0
- package/common/managed/permissions.ts +31 -0
- package/common/managed/report-content.ts +72 -0
- package/common/managed/report-filter.ts +120 -0
- package/common/managed/repository-alias.ts +65 -0
- package/common/managed/roles.ts +35 -0
- package/common/managed/routes.d.ts +2 -0
- package/common/managed/routes.js +363 -0
- package/common/managed/scan-models.ts +6 -0
- package/common/managed/team-app.d.ts +15 -0
- package/common/managed/team-app.js +100 -0
- package/common/managed/team-filters.js +26 -0
- package/common/managed/triage.ts +83 -0
- package/common/managed/upload-seal.ts +126 -0
- package/common/pretty-print.d.ts +5 -0
- package/common/pretty-print.js +24 -0
- package/common/repo-commit.d.ts +4 -0
- package/common/repo-commit.js +30 -0
- package/common/revalidation-conflicts.js +48 -0
- package/common/revalidation-input-groups.js +56 -0
- package/common/save-error-reason.ts +20 -7
- package/common/scan-server.ts +13 -0
- package/common/security-links.d.ts +5 -0
- package/common/security-links.js +33 -0
- package/common/server-info.ts +46 -0
- package/common/utf8.d.ts +3 -0
- package/common/utf8.js +45 -0
- package/common/workspace-app.js +71 -0
- package/common/workspace-groups.js +176 -0
- package/out/activity.js +4 -0
- package/out/brotli-fallback.js +3 -3
- package/out/chunk-2XUEZHIP.js +28 -0
- package/out/chunk-4EMM6UCD.js +1 -0
- package/out/chunk-4ISO5F7Y.js +7 -0
- package/out/chunk-4XIH7YTX.js +1 -0
- package/out/chunk-6CCSTJWB.js +1 -0
- package/out/chunk-74AEKRES.js +10 -0
- package/out/chunk-7BKKYVWR.js +7 -0
- package/out/chunk-7C7DWL7I.js +1 -0
- package/out/chunk-B3FNMHOE.js +1 -0
- package/out/chunk-BNH52UHC.js +2 -0
- package/out/chunk-BRO77PQY.js +42 -0
- package/out/chunk-C4Z6ZBXV.js +10 -0
- package/out/chunk-DEVAORP2.js +1 -0
- package/out/chunk-E3LFSUDJ.js +9 -0
- package/out/chunk-G3LY2FV4.js +1 -0
- package/out/chunk-GO7FT4OD.js +1 -0
- package/out/chunk-GRGIZOTP.js +4 -0
- package/out/chunk-HAZKDK4M.js +4 -0
- package/out/chunk-HOB3YPS5.js +1 -0
- package/out/chunk-IYPY47MC.js +1 -0
- package/out/chunk-IZ6MYRYB.js +3 -0
- package/out/chunk-J2FWBXFV.js +1 -0
- package/out/chunk-JCIIBLKR.js +1 -0
- package/out/chunk-JFL7WLRV.js +1 -0
- package/out/chunk-JJK5OZG2.js +15 -0
- package/out/chunk-JMG5DXII.js +2 -0
- package/out/chunk-JOXLZXMI.js +1 -0
- package/out/chunk-M37X4LCF.js +14 -0
- package/out/chunk-M3Y6SLC4.js +1 -0
- package/out/chunk-NRPC74AM.js +1 -0
- package/out/chunk-NXATZJQ2.js +1 -0
- package/out/chunk-OFZYEWBH.js +244 -0
- package/out/chunk-OIERSXON.js +1 -0
- package/out/chunk-OOJM4CTU.js +1 -0
- package/out/chunk-PAD2JHZT.js +1 -0
- package/out/chunk-PNHBZGDD.js +1 -0
- package/out/chunk-PTFQKLKO.js +1 -0
- package/out/chunk-PWFUOLZK.js +17 -0
- package/out/chunk-PXK7EU4V.js +1 -0
- package/out/chunk-QCOGVL37.js +52 -0
- package/out/chunk-QMVOEBWC.js +13 -0
- package/out/chunk-QRKFPLA4.js +80 -0
- package/out/chunk-R3NZFXVR.js +1 -0
- package/out/chunk-R5O6FAW4.js +2 -0
- package/out/chunk-RRBIJL2B.js +1 -0
- package/out/chunk-SYXT3SFP.js +2 -0
- package/out/chunk-TOXMUOIW.js +5 -0
- package/out/chunk-TUII34K2.js +1 -0
- package/out/chunk-UCP3JRE2.js +1 -0
- package/out/chunk-VFWMQ3LG.js +2 -0
- package/out/chunk-VRX2APNA.js +9 -0
- package/out/chunk-W3QFV4SP.js +3 -0
- package/out/chunk-W6VOKW2N.js +12 -0
- package/out/chunk-WCPJDAYA.js +10 -0
- package/out/chunk-WMFDQS2L.js +11 -0
- package/out/chunk-WREU7JAG.js +1 -0
- package/out/chunk-Y5ZHFNBD.js +2 -0
- package/out/chunk-YF4M5OCI.js +1 -0
- package/out/chunk-Z667U2UJ.js +1 -0
- package/out/chunk-ZQHLECTI.js +1 -0
- package/out/chunk-ZQNEWVGG.js +1 -0
- package/out/client-managed-import.js +4 -0
- package/out/client-managed.js +34 -0
- package/out/client-sync.js +11 -17
- package/out/compare.js +40 -0
- package/out/dialogs.js +40 -0
- package/out/github-issue-authorized.html +3 -0
- package/out/github-issue-authorized.js +1 -0
- package/out/graph.js +19 -4
- package/out/index.html +106 -8
- package/out/prism.js +14 -10
- package/out/scan.js +2 -0
- package/out/stasis.svg +20 -0
- package/out/terminal.js +366 -39
- package/out/view.css +1 -1
- package/out/view.js +19 -144
- package/package.json +383 -63
- package/risk/actions/findings.js +161 -0
- package/risk/actions/resolve.js +250 -0
- package/risk/actions/scripts/commands.js +182 -0
- package/risk/actions/scripts/grade.js +113 -0
- package/risk/actions/scripts/packages.js +123 -0
- package/risk/actions/scripts/shell.js +169 -0
- package/risk/actions/uses.js +76 -0
- package/risk/actions/workflow.js +110 -0
- package/risk/files/characters.js +196 -0
- package/risk/files/hosts.js +205 -0
- package/risk/files/readability.js +177 -0
- package/risk/files/runs-code.js +615 -0
- package/risk/files/script.js +118 -0
- package/risk/files/stamps.js +47 -0
- package/risk/index.d.ts +272 -0
- package/risk/index.js +11 -0
- package/risk/npm/assess.js +285 -0
- package/risk/npm/combined.js +68 -0
- package/risk/npm/compare.js +257 -0
- package/risk/npm/dependencies.js +172 -0
- package/risk/npm/diff.js +79 -0
- package/risk/npm/downloads.js +84 -0
- package/risk/npm/files.js +445 -0
- package/risk/npm/held.js +63 -0
- package/risk/npm/install-scripts.js +34 -0
- package/risk/npm/malware.js +38 -0
- package/risk/npm/manifest.js +65 -0
- package/risk/npm/new-dependency.js +60 -0
- package/risk/npm/old-version.js +108 -0
- package/risk/npm/registry.js +390 -0
- package/risk/npm/release.js +85 -0
- package/risk/npm/score.js +59 -0
- package/risk/npm/specs.js +124 -0
- package/risk/npm/tarball.js +96 -0
- package/server-common/database-config.ts +16 -0
- package/server-common/initialize.ts +18 -0
- package/server-common/npm-advisories.ts +101 -0
- package/{server → server-common}/origin.ts +5 -5
- package/server-common/reap.ts +48 -0
- package/server-common/scan-config.ts +19 -0
- package/server-common/standalone.ts +29 -0
- package/server-common/storage-crypto.ts +182 -0
- package/server-common/storage-log.ts +38 -0
- package/server-common/vercel-blob.ts +103 -0
- package/server-e2e/app.ts +487 -0
- package/{server → server-e2e}/bus-receiver.ts +2 -1
- package/{server → server-e2e}/cli.js +9 -4
- package/{server → server-e2e}/config.ts +50 -42
- package/{server → server-e2e}/db-neon.ts +2 -2
- package/{server → server-e2e}/db-revision-sql.ts +1 -1
- package/{server → server-e2e}/db-stmt.ts +2 -2
- package/{server → server-e2e}/db.ts +7 -7
- package/{server → server-e2e}/http.ts +44 -13
- package/{server → server-e2e}/hub.ts +40 -9
- package/server-e2e/index.ts +17 -0
- package/server-e2e/lifecycle.ts +95 -0
- package/{server → server-e2e}/neon-driver.ts +2 -2
- package/{server → server-e2e}/npm-proxy.ts +12 -145
- package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
- package/{server → server-e2e}/objstore/blob.ts +1 -1
- package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
- package/{server → server-e2e}/objstore/handlers.ts +9 -8
- package/{server → server-e2e}/objstore/init.ts +19 -27
- package/{server → server-e2e}/objstore/reaper.ts +1 -1
- package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
- package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
- package/{server → server-e2e}/objstore/rest.ts +3 -3
- package/{server → server-e2e}/objstore/store-neon.ts +6 -10
- package/{server → server-e2e}/objstore/store.ts +7 -7
- package/{server → server-e2e}/objstore/tokens.ts +2 -2
- package/{server → server-e2e}/pubsub.ts +12 -9
- package/{server → server-e2e}/sign.ts +4 -4
- package/{server → server-e2e}/sse-server.ts +60 -33
- package/{server → server-e2e}/static.ts +31 -21
- package/{server → server-e2e}/sync-handlers.ts +64 -30
- package/{server → server-e2e}/ws-server.ts +20 -9
- package/server-managed/activity.ts +238 -0
- package/server-managed/agent-merges.ts +109 -0
- package/server-managed/app-agents.ts +23 -0
- package/server-managed/avatar-store.ts +13 -0
- package/server-managed/blob-store.ts +26 -0
- package/server-managed/brotli.ts +10 -0
- package/server-managed/bundle-advisories.ts +103 -0
- package/server-managed/bundle-advisory-inventory.ts +77 -0
- package/server-managed/bundle-build-diagnostics.d.ts +10 -0
- package/server-managed/bundle-build-diagnostics.js +23 -0
- package/server-managed/bundle-build-leases.ts +41 -0
- package/server-managed/bundle-build-worker.js +238 -0
- package/server-managed/bundle-build.ts +240 -0
- package/server-managed/bundle-cache.ts +199 -0
- package/server-managed/bundle-catalog.ts +29 -0
- package/server-managed/bundle-commits.ts +133 -0
- package/server-managed/bundle-dependency-reviews.ts +68 -0
- package/server-managed/bundle-store.ts +24 -0
- package/server-managed/bundle-summary-cache.ts +139 -0
- package/server-managed/bundle-validation.ts +33 -0
- package/server-managed/bundle.ts +119 -0
- package/server-managed/cache-storage.ts +20 -0
- package/server-managed/cli.js +21 -0
- package/server-managed/combined.ts +43 -0
- package/server-managed/comments.ts +138 -0
- package/server-managed/commit-coauthors.ts +105 -0
- package/server-managed/commit-lockfiles.ts +77 -0
- package/server-managed/comparison.ts +50 -0
- package/server-managed/config.ts +163 -0
- package/server-managed/content-access.ts +15 -0
- package/server-managed/crypto.ts +25 -0
- package/server-managed/db-methods.ts +1877 -0
- package/server-managed/db-neon.ts +388 -0
- package/server-managed/db-schema.ts +253 -0
- package/server-managed/db-table-names.ts +22 -0
- package/server-managed/db.ts +146 -0
- package/server-managed/dependabot-access.ts +61 -0
- package/server-managed/dependabot-alerts.ts +180 -0
- package/server-managed/dependency-review-comments.ts +92 -0
- package/server-managed/dependency-reviews.ts +363 -0
- package/server-managed/github-accounts.ts +59 -0
- package/server-managed/github-actions.ts +71 -0
- package/server-managed/github-app.ts +347 -0
- package/server-managed/github-errors.ts +70 -0
- package/server-managed/github-graphql.ts +42 -0
- package/server-managed/github-issue-links.ts +264 -0
- package/server-managed/github-issue-oauth.ts +30 -0
- package/server-managed/github-issues.ts +157 -0
- package/server-managed/github-link-oauth.ts +56 -0
- package/server-managed/github-links.ts +204 -0
- package/server-managed/github-metadata.ts +213 -0
- package/server-managed/github-oauth.ts +264 -0
- package/server-managed/github-pulls.ts +257 -0
- package/server-managed/github-requests.ts +179 -0
- package/server-managed/github-users.ts +30 -0
- package/server-managed/github-values.ts +26 -0
- package/server-managed/history-windows.ts +172 -0
- package/server-managed/http-response.ts +76 -0
- package/server-managed/http.ts +5796 -0
- package/server-managed/import-triage.ts +51 -0
- package/server-managed/index.ts +204 -0
- package/server-managed/kept-briefly.ts +37 -0
- package/server-managed/kept.ts +28 -0
- package/server-managed/link-reports.ts +149 -0
- package/server-managed/listed-activity.ts +39 -0
- package/server-managed/locked-packages.ts +152 -0
- package/server-managed/lockfile-scope.ts +49 -0
- package/server-managed/lru.ts +30 -0
- package/server-managed/managed-issues.ts +92 -0
- package/server-managed/management-catalog.ts +45 -0
- package/server-managed/management.ts +110 -0
- package/server-managed/npm-delta-worker.js +23 -0
- package/server-managed/npm-delta.ts +159 -0
- package/server-managed/npm-insights.ts +455 -0
- package/server-managed/npm-kept.ts +234 -0
- package/server-managed/npm-loads.ts +259 -0
- package/server-managed/npm-manifest.ts +117 -0
- package/server-managed/npm-packages.ts +462 -0
- package/server-managed/npm-patch.ts +317 -0
- package/server-managed/npm-provenance.ts +127 -0
- package/server-managed/npm-risk.ts +287 -0
- package/server-managed/object-storage-disk.ts +147 -0
- package/server-managed/object-storage-vercel.ts +71 -0
- package/server-managed/object-storage.ts +82 -0
- package/server-managed/package-entry-points.ts +79 -0
- package/server-managed/pretty-print.ts +425 -0
- package/server-managed/public-workspace.ts +242 -0
- package/server-managed/pull-comment-reviews.ts +161 -0
- package/server-managed/pull-dependencies.ts +340 -0
- package/server-managed/pull-dependency-reviews.ts +327 -0
- package/server-managed/pull-reviews.ts +202 -0
- package/server-managed/queue.ts +53 -0
- package/server-managed/release-commits.ts +85 -0
- package/server-managed/rename-diff-worker.js +26 -0
- package/server-managed/rename-diff.ts +236 -0
- package/server-managed/repo-path.ts +21 -0
- package/server-managed/report-migration.ts +32 -0
- package/server-managed/report-query.ts +10 -0
- package/server-managed/report-response.ts +16 -0
- package/server-managed/report-sources.ts +181 -0
- package/server-managed/report-store.ts +77 -0
- package/server-managed/repository-actions.ts +220 -0
- package/server-managed/repository-agents.ts +422 -0
- package/server-managed/repository-aliases.ts +85 -0
- package/server-managed/repository-browser.ts +303 -0
- package/server-managed/repository-changes.ts +280 -0
- package/server-managed/repository-code.ts +215 -0
- package/server-managed/repository-dependency-reviews.ts +159 -0
- package/server-managed/repository-discovery.ts +83 -0
- package/server-managed/repository-history.ts +428 -0
- package/server-managed/repository-issues.ts +224 -0
- package/server-managed/repository-policy.ts +27 -0
- package/server-managed/repository-pulls.ts +207 -0
- package/server-managed/repository-pulse.ts +477 -0
- package/server-managed/repository-risk-assess.ts +108 -0
- package/server-managed/repository-risk-audit.ts +78 -0
- package/server-managed/repository-risk-read.ts +170 -0
- package/server-managed/repository-risk.ts +483 -0
- package/server-managed/repository-squashes.ts +160 -0
- package/server-managed/repository-stamp.ts +41 -0
- package/server-managed/request-timing.ts +63 -0
- package/server-managed/reviewed-dependencies.ts +149 -0
- package/server-managed/revisions.ts +35 -0
- package/server-managed/scan-downloads.ts +87 -0
- package/server-managed/session.ts +132 -0
- package/server-managed/slugs.ts +38 -0
- package/server-managed/solidity-entry-points.ts +71 -0
- package/server-managed/sql-postgres.ts +34 -0
- package/server-managed/sql.ts +107 -0
- package/server-managed/stasis-config.ts +55 -0
- package/server-managed/static.ts +28 -0
- package/server-managed/storage-command.ts +16 -0
- package/server-managed/storage-db.ts +183 -0
- package/server-managed/storage-encryption.ts +288 -0
- package/server-managed/storage-maintenance.ts +259 -0
- package/server-managed/storage-payload.ts +121 -0
- package/server-managed/storage-stores.ts +91 -0
- package/server-managed/storage.ts +82 -0
- package/server-managed/team-app-summaries.ts +54 -0
- package/server-managed/team-app.ts +154 -0
- package/server-managed/team-catalog.ts +7 -0
- package/server-managed/team-feed.ts +180 -0
- package/server-managed/team-npm-scopes.ts +103 -0
- package/server-managed/team-reports.ts +351 -0
- package/server-managed/triage-response.ts +16 -0
- package/server-managed/type-only-proof.js +108 -0
- package/server-managed/type-only-worker.js +31 -0
- package/server-managed/type-only.ts +115 -0
- package/server-managed/uploads.ts +106 -0
- package/server-managed/upstream-cache.ts +250 -0
- package/server-managed/view-as.ts +58 -0
- package/server-managed/worker-turns.ts +76 -0
- package/server-managed/workspace-shares.ts +170 -0
- package/server.ts +70 -0
- package/server/index.ts +0 -480
- package/server/lifecycle.ts +0 -208
- /package/{LICENSE → LICENSE-MIT} +0 -0
- /package/{server → server-e2e}/auth.ts +0 -0
- /package/{server → server-e2e}/config.example.json +0 -0
- /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
- /package/{server → server-e2e}/objstore/fs.ts +0 -0
- /package/{server → server-e2e}/objstore/sign.ts +0 -0
- /package/{server → server-e2e}/peer.ts +0 -0
- /package/{server → server-e2e}/sse-session.ts +0 -0
- /package/{server → server-e2e}/util.ts +0 -0
- /package/{server → server-e2e}/validation.ts +0 -0
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// Whether a pair of a comparison's files changed in types alone (type-only.ts),
|
|
2
|
+
// told in a worker (type-only-worker.js): each a file a side, `{ path, text }`,
|
|
3
|
+
// a side not there null, its path as it is, which says what a file is.
|
|
4
|
+
//
|
|
5
|
+
// typeOnlyStamped: as @preventive/compare's compareTrees stamps a change
|
|
6
|
+
// `typeOnly`. Two paths pair as one change wherever compareTrees takes them
|
|
7
|
+
// for a rename at all; where it doesn't, the pair is types only where each of
|
|
8
|
+
// its two changes is: the file gone erasing whole, and the one come erasing
|
|
9
|
+
// whole or leaving a single bare `export {}`, which nothing loaded before.
|
|
10
|
+
//
|
|
11
|
+
// typeOnlyRuns: one it doesn't stamp may still hold types alone but for what
|
|
12
|
+
// runs on each side, each side there a declaration file proveTypeOnly proves,
|
|
13
|
+
// its runtime what changed: a module load added, gone or another, or a file
|
|
14
|
+
// added or removed that loads one, as a zod schema's declarations do. Told
|
|
15
|
+
// then are the lines that hold what runs on each side (`runs` the base's,
|
|
16
|
+
// `otherRuns` the other's, none for a side not there), for the viewer to diff
|
|
17
|
+
// those alone with its types set aside: the hashbang, each statement Node's
|
|
18
|
+
// type stripping leaves to run (a module load, `export {}`, `export default`
|
|
19
|
+
// of a name), and each comment it keeps that may be one a tool reads (a
|
|
20
|
+
// triple-slash directive, a source map or source URL pragma), told wide of
|
|
21
|
+
// the proof's own grammar for them, so none it reads is ever set aside. A
|
|
22
|
+
// line holding any of it is told whole; a range is `[from, to)` of lines
|
|
23
|
+
// counted from zero, as the viewer splits a text at `\n`. None are told of
|
|
24
|
+
// a pair where a diff of those lines would not show what changed: a
|
|
25
|
+
// triple-slash comment that leads one side, where a directive steers, and
|
|
26
|
+
// stands below a statement on the other, where it is prose, its line the same
|
|
27
|
+
// on both (`moved`). Its diff is drawn whole, as one not proven is.
|
|
28
|
+
import { stripTypeScriptTypes } from 'node:module'
|
|
29
|
+
import { compareTrees, proveTypeOnly } from '@preventive/compare'
|
|
30
|
+
import { parseSync } from 'oxc-parser'
|
|
31
|
+
|
|
32
|
+
// A declaration file as compareTrees takes one: `.d.ts`, `.d.mts`, `.d.cts`,
|
|
33
|
+
// and `.d.css.ts` for a `.css` file's.
|
|
34
|
+
const DECLARATION = /\.d\.(?:[^./]+\.)?[cm]?ts$/u
|
|
35
|
+
// A comment that may be a directive (`/// <reference .../>`) or a pragma
|
|
36
|
+
// (`//# sourceMappingURL=`, and its legacy `//@` and block forms).
|
|
37
|
+
const STEERING = /^\/(?:\/\/|[/*][#@])/u
|
|
38
|
+
const BLANK = /^\s*$/u
|
|
39
|
+
|
|
40
|
+
const tree = file => (file ? [{ name: file.path, data: file.text }] : [])
|
|
41
|
+
|
|
42
|
+
export function typeOnlyStamped(from, to) {
|
|
43
|
+
const changes = compareTrees(tree(from), tree(to), { paths: 'keys', lines: false, renames: Number.MIN_VALUE })
|
|
44
|
+
return changes.length > 0 && changes.every(change => change.typeOnly === true)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// The lines of a text proven to hold types alone but for what runs that hold
|
|
48
|
+
// any of that, as merged ranges (`lines`), and its triple-slash comments, by
|
|
49
|
+
// whether each leads it (`leading`, `below`). Stripping blanks what it erases
|
|
50
|
+
// in place, each character to a blank, so a statement it leaves blank is
|
|
51
|
+
// erased and one it leaves anything of runs, as the proof found, and a comment
|
|
52
|
+
// it leaves is kept; what it reads starts past a byte order mark, and so do
|
|
53
|
+
// the offsets in its tree.
|
|
54
|
+
function runLines(text) {
|
|
55
|
+
const shift = text.startsWith('') ? 1 : 0
|
|
56
|
+
const body = text.slice(shift)
|
|
57
|
+
const code = stripTypeScriptTypes(body, { mode: 'strip' })
|
|
58
|
+
const { program, comments } = parseSync('file.ts', body, { lang: 'ts', sourceType: 'module' })
|
|
59
|
+
const kept = ({ start, end }) => code.slice(start, end)
|
|
60
|
+
const steering = comments.filter(comment => STEERING.test(kept(comment)))
|
|
61
|
+
const spans = [...program.hashbang ? [program.hashbang] : [], ...program.body.filter(statement => !BLANK.test(kept(statement))), ...steering]
|
|
62
|
+
const starts = [0]
|
|
63
|
+
for (let at = text.indexOf('\n'); at !== -1; at = text.indexOf('\n', at + 1)) starts.push(at + 1)
|
|
64
|
+
// The line an offset of the text is on: the last whose start is at most it.
|
|
65
|
+
const lineAt = offset => {
|
|
66
|
+
let high = starts.length - 1, low = 0
|
|
67
|
+
while (low < high) {
|
|
68
|
+
const mid = Math.ceil((low + high) / 2)
|
|
69
|
+
if (starts[mid] <= offset) low = mid
|
|
70
|
+
else high = mid - 1
|
|
71
|
+
}
|
|
72
|
+
return low
|
|
73
|
+
}
|
|
74
|
+
const ranges = []
|
|
75
|
+
for (const { start, end } of spans.toSorted((a, b) => a.start - b.start)) {
|
|
76
|
+
const from = lineAt(shift + start), to = lineAt(shift + Math.max(start, end - 1)) + 1
|
|
77
|
+
const last = ranges.at(-1)
|
|
78
|
+
if (last && from <= last[1]) last[1] = Math.max(last[1], to)
|
|
79
|
+
else ranges.push([from, to])
|
|
80
|
+
}
|
|
81
|
+
// Its triple-slash comments, by their text: those that lead it, before its
|
|
82
|
+
// first statement, where alone a directive steers, and those below one.
|
|
83
|
+
const first = program.body[0]?.start ?? Infinity
|
|
84
|
+
const slashed = leads => new Set(steering.filter(comment => (comment.start < first) === leads).map(kept).filter(comment => comment.startsWith('///')))
|
|
85
|
+
return { lines: ranges, leading: slashed(true), below: slashed(false) }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Whether a triple-slash comment that leads `one` side stands only below a
|
|
89
|
+
// statement on the `other`: a directive that steers on one alone, though its
|
|
90
|
+
// line reads the same on both.
|
|
91
|
+
const moved = (one, other) => [...one.leading].some(comment => !other.leading.has(comment) && other.below.has(comment))
|
|
92
|
+
|
|
93
|
+
// `{ runs, otherRuns }` where each side there is a declaration file proven to
|
|
94
|
+
// hold types alone but for what runs, and no directive steers on one side
|
|
95
|
+
// alone unseen (`moved`); else false, and where the proof throws, as no
|
|
96
|
+
// check should. Asked of a pair not stamped, which always runs some.
|
|
97
|
+
export function typeOnlyRuns(from, to) {
|
|
98
|
+
const sides = [from, to].filter(file => file !== null)
|
|
99
|
+
if (sides.length === 0 || !sides.every(file => DECLARATION.test(file.path))) return false
|
|
100
|
+
try {
|
|
101
|
+
if (!sides.every(file => proveTypeOnly(file.text).proven)) return false
|
|
102
|
+
const [base, other] = [from, to].map(file => (file ? runLines(file.text) : null))
|
|
103
|
+
if (base && other && (moved(base, other) || moved(other, base))) return false
|
|
104
|
+
return { runs: base?.lines ?? [], otherRuns: other?.lines ?? [] }
|
|
105
|
+
} catch {
|
|
106
|
+
return false
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Which of a comparison's pairs of files changed in types alone (type-only.ts),
|
|
2
|
+
// off the server's event loop, as type-only-proof.js tells each. Told first,
|
|
3
|
+
// `{ stamped }`, is whether each is stamped, by pair: what runs is worked out
|
|
4
|
+
// after, so that it cannot cost a stamp the worker's deadline, however long
|
|
5
|
+
// one file's takes. Then, where asked for (`runsUntil` a time, not null),
|
|
6
|
+
// what runs of each pair not stamped, `{ at, runs, otherRuns }` as each is
|
|
7
|
+
// found, the smallest files first, so that one that takes long keeps the
|
|
8
|
+
// fewest waiting, and none begun once `runsUntil` has come. Last, its answer,
|
|
9
|
+
// by pair: `true`, `{ runs, otherRuns }` for one that holds types alone but
|
|
10
|
+
// for what runs, or `false`, as for one not asked for or not come to.
|
|
11
|
+
import { parentPort, workerData } from 'node:worker_threads'
|
|
12
|
+
import { typeOnlyRuns, typeOnlyStamped } from './type-only-proof.js'
|
|
13
|
+
|
|
14
|
+
const { pairs, runsUntil } = workerData
|
|
15
|
+
// Node worker messages have no browser target origin.
|
|
16
|
+
// oxlint-disable-next-line unicorn/require-post-message-target-origin
|
|
17
|
+
const tell = told => parentPort.postMessage(told)
|
|
18
|
+
const answer = pairs.map(([from, to]) => typeOnlyStamped(from, to))
|
|
19
|
+
tell({ stamped: answer })
|
|
20
|
+
if (runsUntil !== null) {
|
|
21
|
+
const size = ([from, to]) => (from?.text.length ?? 0) + (to?.text.length ?? 0)
|
|
22
|
+
const rest = [...pairs.keys()].filter(at => !answer[at]).toSorted((a, b) => size(pairs[a]) - size(pairs[b]))
|
|
23
|
+
for (const at of rest) {
|
|
24
|
+
if (Date.now() >= runsUntil) break
|
|
25
|
+
const runs = typeOnlyRuns(...pairs[at])
|
|
26
|
+
if (!runs) continue
|
|
27
|
+
answer[at] = runs
|
|
28
|
+
tell({ at, ...runs })
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
tell(answer)
|
|
@@ -0,0 +1,115 @@
|
|
|
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. Asked with `runs=1`, those too that hold types alone but for
|
|
11
|
+
// a runtime the change does not leave as it was, each with the lines holding
|
|
12
|
+
// that runtime on either side (type-only-proof.js), as many as there is time
|
|
13
|
+
// left for once every file is stamped, which none of them costs a stamp: a
|
|
14
|
+
// viewer that does not ask takes every line for a change in types alone.
|
|
15
|
+
// Proven in a worker, off the event loop, a comparison at a time per process,
|
|
16
|
+
// for at most a minute; told a line each, `{ path, hash, otherPath,
|
|
17
|
+
// otherHash }`, a side not there null, and `runs` and `otherRuns` where those
|
|
18
|
+
// are told, which the viewer checks name the files it shows. Access is the
|
|
19
|
+
// caller's to check.
|
|
20
|
+
import { pathOrder } from './npm-packages.ts'
|
|
21
|
+
import { type ComparedSide, PrettyError, type PrettyRequest } from './pretty-print.ts'
|
|
22
|
+
import { comparedFiles } from './rename-diff.ts'
|
|
23
|
+
import { workerTurns } from './worker-turns.ts'
|
|
24
|
+
|
|
25
|
+
// TypeScript files, by extension as the pretty-print cache reads them: none
|
|
26
|
+
// other is asked about.
|
|
27
|
+
const TYPESCRIPT = new Set(['ts', 'mts', 'cts'])
|
|
28
|
+
// Comparisons proven at once per process, and those waiting their turn past
|
|
29
|
+
// them, any more refused; the longest one may take, its wait included.
|
|
30
|
+
const MAX_ACTIVE_PROOFS = 1
|
|
31
|
+
const MAX_WAITING_PROOFS = 16
|
|
32
|
+
const PROOF_TIMEOUT_MS = 60_000
|
|
33
|
+
// What runs is begun of no pair once this little of that is left, so the
|
|
34
|
+
// answer comes that long before the deadline but for the pair being worked
|
|
35
|
+
// out, which may take any time: a file of many module loads takes minutes
|
|
36
|
+
// (@preventive/compare's proof is quadratic in them). One still not done at
|
|
37
|
+
// the deadline costs what runs of it and of those after it, never a stamp.
|
|
38
|
+
const RUNS_MARGIN_MS = 15_000
|
|
39
|
+
|
|
40
|
+
type File = PrettyRequest & { text: string }
|
|
41
|
+
// A range of lines, `[from, to)`, counted from zero.
|
|
42
|
+
type Lines = [number, number]
|
|
43
|
+
export interface TypeOnlyLine { path: string | null; hash: string | null; otherPath: string | null; otherHash: string | null; runs?: Lines[]; otherRuns?: Lines[] }
|
|
44
|
+
type Proof = boolean | { runs: Lines[]; otherRuns: Lines[] }
|
|
45
|
+
|
|
46
|
+
// Whether a request asks for the files that hold types alone but for what runs too.
|
|
47
|
+
export const runsAsked = (params: URLSearchParams) => params.get('runs') === '1'
|
|
48
|
+
|
|
49
|
+
const workers = workerTurns({ what: 'type-only proof', active: MAX_ACTIVE_PROOFS, waiting: MAX_WAITING_PROOFS, error: PrettyError,
|
|
50
|
+
busy: 'proof-busy', timeout: 'proof-timeout', failed: 'unproven' })
|
|
51
|
+
|
|
52
|
+
const ranges = (told: unknown): told is Lines[] => Array.isArray(told)
|
|
53
|
+
&& told.every(range => Array.isArray(range) && range.length === 2 && range.every(Number.isSafeInteger) && range[0] >= 0 && range[0] < range[1])
|
|
54
|
+
const runsOf = (told: unknown): told is { runs: Lines[]; otherRuns: Lines[] } => typeof told === 'object' && told !== null
|
|
55
|
+
&& 'runs' in told && 'otherRuns' in told && ranges(told.runs) && ranges(told.otherRuns)
|
|
56
|
+
const proof = (told: unknown): told is Proof => typeof told === 'boolean' || runsOf(told)
|
|
57
|
+
|
|
58
|
+
// What a worker of `count` pairs told before its answer, as the answer to
|
|
59
|
+
// settle for should it be gone without one (type-only-worker.js): every stamp
|
|
60
|
+
// first, `{ stamped }`, then what runs of a pair it told as not stamped, `{
|
|
61
|
+
// at, runs, otherRuns }`, one at a time, each pair not come to as not stamped.
|
|
62
|
+
// A function of each thing it tells, as workers.run asks one: that answer so
|
|
63
|
+
// far, or null for what is neither, its own answer among it.
|
|
64
|
+
export function proofsSoFar(count: number): (told: unknown) => Proof[] | null {
|
|
65
|
+
let sofar: Proof[] | null = null
|
|
66
|
+
return told => {
|
|
67
|
+
if (typeof told !== 'object' || told === null) return null
|
|
68
|
+
if ('stamped' in told) {
|
|
69
|
+
const { stamped } = told
|
|
70
|
+
if (sofar !== null || !Array.isArray(stamped) || stamped.length !== count || !stamped.every(one => typeof one === 'boolean')) return null
|
|
71
|
+
sofar = [...stamped]
|
|
72
|
+
return sofar
|
|
73
|
+
}
|
|
74
|
+
if (sofar === null || !('at' in told) || typeof told.at !== 'number' || sofar[told.at] !== false || !runsOf(told)) return null
|
|
75
|
+
sofar[told.at] = { runs: told.runs, otherRuns: told.otherRuns }
|
|
76
|
+
return sofar
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Which of `pairs` compareTrees stamps types only, by index, and with `runs`
|
|
81
|
+
// which hold types alone but for what runs, with its lines, as many as there
|
|
82
|
+
// is time for, in a worker settled once it is gone; none where it fails, as
|
|
83
|
+
// no proof should. One gone before its answer, its deadline come on a file
|
|
84
|
+
// that takes long or its memory run out, is answered for as far as it told
|
|
85
|
+
// (proofsSoFar): what runs is worked out after every stamp, and costs none.
|
|
86
|
+
function proven(pairs: Array<[File | null, File | null]>, runs: boolean, deadline: number): Promise<Proof[]> {
|
|
87
|
+
return workers.run(new URL('./type-only-worker.js', import.meta.url), {
|
|
88
|
+
workerData: { pairs: pairs.map(sides => sides.map(file => file && { path: file.path, text: file.text })), runsUntil: runs ? deadline - RUNS_MARGIN_MS : null },
|
|
89
|
+
// Node's type stripping, which the proof holds oxc's tree to, warns it is experimental.
|
|
90
|
+
execArgv: ['--disable-warning=ExperimentalWarning'], resourceLimits: { maxOldGenerationSizeMb: 1024 },
|
|
91
|
+
}, (told): Proof[] | null => (Array.isArray(told) && told.length === pairs.length && told.every(proof) ? told : null), deadline, proofsSoFar(pairs.length))
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// The files that changed between a comparison's two sides in types alone,
|
|
95
|
+
// as the viewer pairs them, and with `runs` those in types alone but for what
|
|
96
|
+
// runs, a line each once all are proven, in path order.
|
|
97
|
+
export function typeOnlyFiles([base, other]: readonly [ComparedSide, ComparedSide], runs = false): AsyncGenerator<TypeOnlyLine> {
|
|
98
|
+
const typescript = ({ files }: ComparedSide) => new Map(files.filter(file => TYPESCRIPT.has(file.extension)).map(file => [file.path, file]))
|
|
99
|
+
const [olds, news] = [typescript(base), typescript(other)]
|
|
100
|
+
const { changed, onlyBase, onlyOther } = comparedFiles([base, other])
|
|
101
|
+
// A side there not a TypeScript file this reads leaves its pair out; one not there is null.
|
|
102
|
+
const pairs = [...changed.map(({ path, basePath = path }) => [olds.get(basePath), news.get(path)]),
|
|
103
|
+
...onlyBase.map(({ path, basePath = path }) => [olds.get(basePath), null]), ...onlyOther.map(({ path }) => [null, news.get(path)])]
|
|
104
|
+
.filter((sides): sides is [File | null, File | null] => sides.every(file => file !== undefined) && sides.some(file => file !== null) && sides[0]?.hash !== sides[1]?.hash)
|
|
105
|
+
.toSorted(([a, b], [c, d]) => pathOrder((b ?? a)!.path, (d ?? c)!.path))
|
|
106
|
+
return (async function* () {
|
|
107
|
+
if (pairs.length === 0) return
|
|
108
|
+
const deadline = Date.now() + PROOF_TIMEOUT_MS
|
|
109
|
+
const stamped = await workers.inTurn(deadline, () => proven(pairs, runs, deadline))
|
|
110
|
+
for (const [i, [from, to]] of pairs.entries()) {
|
|
111
|
+
const told = stamped[i]
|
|
112
|
+
if (told) yield { path: from?.path ?? null, hash: from?.hash ?? null, otherPath: to?.path ?? null, otherHash: to?.hash ?? null, ...told !== true && told }
|
|
113
|
+
}
|
|
114
|
+
})()
|
|
115
|
+
}
|
|
@@ -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 { isBlobId } from './object-storage.ts'
|
|
9
|
+
import { maxSealedBytes, openUpload } from '../common/managed/upload-seal.ts'
|
|
10
|
+
|
|
11
|
+
export const UPLOAD_CHUNK_BYTES = 3 * 1024 * 1024
|
|
12
|
+
export const MAX_UPLOAD_BYTES = 1024 * 1024 * 1024
|
|
13
|
+
// Staged parts may carry a sealed body, slightly larger than its content.
|
|
14
|
+
const MAX_STAGED_BYTES = maxSealedBytes(MAX_UPLOAD_BYTES)
|
|
15
|
+
const MAX_UPLOAD_PARTS = Math.ceil(MAX_STAGED_BYTES / UPLOAD_CHUNK_BYTES)
|
|
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 isBlobId(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 isBlobId(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,250 @@
|
|
|
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
|
+
// The statement keeping as many as `rows` at once. A slower concurrent audit
|
|
51
|
+
// cannot replace a newer listing with an older one.
|
|
52
|
+
const insert = (rows: number) => db.prepare(`INSERT INTO managed_upstream_cache (cache_key, value, cached_at) VALUES ${Array.from({ length: rows }, () => '(?, ?, ?)').join(', ')}
|
|
53
|
+
ON CONFLICT (cache_key) DO UPDATE SET value = excluded.value, cached_at = excluded.cached_at
|
|
54
|
+
WHERE managed_upstream_cache.cached_at <= excluded.cached_at`)
|
|
55
|
+
const set = insert(1)
|
|
56
|
+
const remove = db.prepare('DELETE FROM managed_upstream_cache WHERE cache_key LIKE ? AND cached_at < ?')
|
|
57
|
+
// setUpstreamCacheEntries's, by how many it keeps at once.
|
|
58
|
+
const setMany = new Map<number, ReturnType<ManagedSql['prepare']>>()
|
|
59
|
+
return {
|
|
60
|
+
async getUpstreamCacheEntry(key) {
|
|
61
|
+
const row = await get.get(key) as { value: string } | undefined
|
|
62
|
+
return row?.value ?? null
|
|
63
|
+
},
|
|
64
|
+
async getUpstreamCacheEntries(keys) {
|
|
65
|
+
if (keys.length === 0) return new Map()
|
|
66
|
+
const rows = await getMany.all(JSON.stringify(keys)) as { cache_key: string; value: string }[]
|
|
67
|
+
return new Map(rows.map(row => [row.cache_key, row.value]))
|
|
68
|
+
},
|
|
69
|
+
async getFirstUpstreamCacheEntries(first, then) {
|
|
70
|
+
if (first.length === 0 && then.length === 0) return { first: false, entries: new Map() }
|
|
71
|
+
const rows = await getFirst.all(JSON.stringify(first), JSON.stringify(then)) as { cache_key: string; value: string; in_first: number }[]
|
|
72
|
+
return { first: rows.some(row => Number(row.in_first) === 1), entries: new Map(rows.map(row => [row.cache_key, row.value])) }
|
|
73
|
+
},
|
|
74
|
+
async setUpstreamCacheEntry(key, value, cachedAt) {
|
|
75
|
+
await set.run(key, value, cachedAt)
|
|
76
|
+
},
|
|
77
|
+
async setUpstreamCacheEntries(entries, cachedAt) {
|
|
78
|
+
const rows = [...new Map(entries)]
|
|
79
|
+
if (rows.length === 0) return
|
|
80
|
+
let many = setMany.get(rows.length)
|
|
81
|
+
if (!many) setMany.set(rows.length, many = insert(rows.length))
|
|
82
|
+
await many.run(...rows.flatMap(([key, value]) => [key, value, cachedAt]))
|
|
83
|
+
},
|
|
84
|
+
async deleteUpstreamCacheEntries(prefix, before) {
|
|
85
|
+
return Number((await remove.run(`${prefix}%`, before)).changes)
|
|
86
|
+
},
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// An audit's `cache`: where the server has an upstream disk cache (off Vercel,
|
|
91
|
+
// set at startup), that keeps everything; else this store keeps listings and
|
|
92
|
+
// public names, those of `keys` (auditedKeys) read at once.
|
|
93
|
+
export function auditCache(cacheDir: string | null | undefined, db: UpstreamCacheStore, signal: AbortSignal, debug = false, keys: Iterable<string> = []): CacheStore | undefined {
|
|
94
|
+
return cacheDir ? undefined : upstreamCache(db, signal, debug, keys)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Only listings and public names are kept: upstream's other records (npm
|
|
98
|
+
// version documents, registries' repository lookups) read as misses and are
|
|
99
|
+
// not written.
|
|
100
|
+
const LISTINGS = 'github/advisories'
|
|
101
|
+
const PUBLIC_NAMES = 'npm/public'
|
|
102
|
+
const CACHED_TYPES = new Set([LISTINGS, PUBLIC_NAMES])
|
|
103
|
+
|
|
104
|
+
// What an audit of `packages` reads first, where it is already known: the
|
|
105
|
+
// listings of the repositories it knows, each `github` package, each `soldeer`
|
|
106
|
+
// package's given repository, and with `repoAdvisories`, every other
|
|
107
|
+
// package's, upstream looking up the rest itself; and whether each npm package
|
|
108
|
+
// is public, as upstream asks before it asks OSV of it. Each as upstream asks
|
|
109
|
+
// for it, a listing by its repository's lowercased name.
|
|
110
|
+
export function auditedKeys(packages: Iterable<Package>, repoAdvisories: boolean): string[] {
|
|
111
|
+
return [...new Set([...packages].flatMap(pkg => {
|
|
112
|
+
const repo = pkg.ecosystem === 'github' ? pkg.name : pkg.ecosystem === 'soldeer' || repoAdvisories ? pkg.github : undefined
|
|
113
|
+
return [...pkg.ecosystem === 'npm' ? [`${PUBLIC_NAMES}/${pkg.name}`] : [], ...repo === undefined ? [] : [`${LISTINGS}/${repo.toLowerCase()}`]]
|
|
114
|
+
}))]
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// The cache is an optimization: a database failure is a miss, never a failed
|
|
118
|
+
// audit. Upstream keeps listing after an abandoned audit; once `signal` aborts,
|
|
119
|
+
// the request's database work is over and the store is left alone.
|
|
120
|
+
// Upstream reads one listing at a time per repository, and whether a name is
|
|
121
|
+
// public eight at a time, and a request's queries share one connection (Neon),
|
|
122
|
+
// so a recheck of hundreds of packages would wait on as many round trips: the
|
|
123
|
+
// first read asks for every one of `keys` at once. Any other key, or all of
|
|
124
|
+
// them if that read fails, is read alone.
|
|
125
|
+
export function upstreamCache(db: UpstreamCacheStore, signal: AbortSignal, debug = false, keys: Iterable<string> = []): CacheStore {
|
|
126
|
+
const batched = new Set(keys)
|
|
127
|
+
let batch: Promise<Map<string, string> | null> | undefined
|
|
128
|
+
const readBatch = () => batch ??= db.getUpstreamCacheEntries([...batched]).catch((error: unknown) => {
|
|
129
|
+
if (debug) console.warn('managed: upstream cache read failed:', error)
|
|
130
|
+
return null
|
|
131
|
+
})
|
|
132
|
+
return {
|
|
133
|
+
async read(type, key) {
|
|
134
|
+
if (!CACHED_TYPES.has(type) || signal.aborted) return null
|
|
135
|
+
const cacheKey = `${type}/${key}`
|
|
136
|
+
try {
|
|
137
|
+
const found = batched.has(cacheKey) ? await readBatch() : null
|
|
138
|
+
const value = found ? found.get(cacheKey) ?? null : await db.getUpstreamCacheEntry(cacheKey)
|
|
139
|
+
return value === null ? null : JSON.parse(value) as unknown
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (debug) console.warn('managed: upstream cache read failed:', error)
|
|
142
|
+
return null
|
|
143
|
+
}
|
|
144
|
+
},
|
|
145
|
+
async write(type, key, value) {
|
|
146
|
+
if (!CACHED_TYPES.has(type) || signal.aborted) return
|
|
147
|
+
try { await db.setUpstreamCacheEntry(`${type}/${key}`, JSON.stringify(value), Date.now()) } catch (error) {
|
|
148
|
+
if (debug) console.warn('managed: upstream cache write failed:', error)
|
|
149
|
+
}
|
|
150
|
+
},
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// The file upstream keeps `file` in, under `dir` of its disk cache
|
|
155
|
+
// (setCacheDir), as its cachePath names it: `@babel+core@7.29.7.tgz`, a
|
|
156
|
+
// capital written `!` and the letter, and a Windows device name's first
|
|
157
|
+
// letter escaped.
|
|
158
|
+
export function upstreamCachePath(root: string, dir: string, file: string): string {
|
|
159
|
+
const name = encodeURIComponent(file.replaceAll(/[!A-Z]/gu, char => `!${char.toLowerCase()}`))
|
|
160
|
+
.replaceAll('%40', '@').replaceAll('%2F', '+')
|
|
161
|
+
.replace(/^(?=(?:con|prn|aux|nul|com\d|lpt\d)(?:\.|$))./u, char => `%${char.codePointAt(0)!.toString(16).toUpperCase()}`)
|
|
162
|
+
return join(root, dir, name)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// A kept file, where it is a regular file of at most `max` bytes, checked on
|
|
166
|
+
// the file as opened (a FIFO or device would block or never end), and read
|
|
167
|
+
// to the size it had then.
|
|
168
|
+
export async function readKeptFile(path: string, max: number): Promise<Uint8Array | null> {
|
|
169
|
+
const handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK).catch(() => null)
|
|
170
|
+
if (!handle) return null
|
|
171
|
+
try {
|
|
172
|
+
const stats = await handle.stat()
|
|
173
|
+
if (!stats.isFile() || stats.size > max) return null
|
|
174
|
+
const bytes = Buffer.allocUnsafe(stats.size)
|
|
175
|
+
for (let at = 0; at < bytes.length;) {
|
|
176
|
+
const { bytesRead } = await handle.read(bytes, at, bytes.length - at, at)
|
|
177
|
+
if (bytesRead === 0) return null
|
|
178
|
+
at += bytesRead
|
|
179
|
+
}
|
|
180
|
+
return bytes
|
|
181
|
+
} catch { return null }
|
|
182
|
+
finally { await handle.close() }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// `bytes` kept at `path`, written whole beside it first and then moved in, so a
|
|
186
|
+
// reader finds the old file or the new one, never part of one; a failure
|
|
187
|
+
// keeps nothing.
|
|
188
|
+
let tmpSeq = 0
|
|
189
|
+
export async function keepFile(path: string, bytes: Uint8Array) {
|
|
190
|
+
const tmp = `${path}.${process.pid}.${++tmpSeq}.tmp`
|
|
191
|
+
try {
|
|
192
|
+
await mkdir(dirname(path), { recursive: true })
|
|
193
|
+
await writeFile(tmp, bytes)
|
|
194
|
+
await rename(tmp, path)
|
|
195
|
+
} catch { await rm(tmp, { force: true }).catch(() => {}) }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const gunzipAsync = promisify(gunzip)
|
|
199
|
+
const gzipAsync = promisify(gzip)
|
|
200
|
+
|
|
201
|
+
// An upstream's JSON object kept with its ETag, gzipped, as keepJson keeps it:
|
|
202
|
+
// `{ etag, json }`, or null where none is kept, or what is can't be read
|
|
203
|
+
// within `limit` bytes.
|
|
204
|
+
export async function readKeptJson(path: string, limit: number): Promise<{ etag: string; json: Record<string, unknown> } | null> {
|
|
205
|
+
const bytes = await readKeptFile(path, limit)
|
|
206
|
+
if (!bytes) return null
|
|
207
|
+
const object = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === 'object' && !Array.isArray(value)
|
|
208
|
+
try {
|
|
209
|
+
const kept: unknown = JSON.parse((await gunzipAsync(bytes, { maxOutputLength: limit + 1024 })).toString('utf8'))
|
|
210
|
+
return object(kept) && typeof kept['etag'] === 'string' && object(kept['json']) ? { etag: kept['etag'], json: kept['json'] } : null
|
|
211
|
+
} catch { return null }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// `body`, an upstream's JSON object as it wrote it, kept with its `etag`.
|
|
215
|
+
export async function keepJson(path: string, etag: string, body: Buffer) {
|
|
216
|
+
await keepFile(path, await gzipAsync(Buffer.concat([Buffer.from(`{"etag":${JSON.stringify(etag)},"json":`), body, Buffer.from('}')])))
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// A kept listing is read to no more than this, gzipped or not: one runs to
|
|
220
|
+
// some hundreds of KiB.
|
|
221
|
+
const LISTING_BYTES = 64 * 1024 * 1024
|
|
222
|
+
|
|
223
|
+
// A repository's listing as last kept where audits keep them (auditCache),
|
|
224
|
+
// however old, for when GitHub can't be reached to refresh it: `at`, when it
|
|
225
|
+
// was kept, and `cache`, a store answering it to upstream as kept just now,
|
|
226
|
+
// so that upstream takes it rather than ask GitHub, and keeping nothing.
|
|
227
|
+
// Upstream checks it as it checks its own. Null where none is kept, or it
|
|
228
|
+
// can't be read.
|
|
229
|
+
export async function lastListing(cacheDir: string | null | undefined, db: UpstreamCacheStore, repo: string, debug = false): Promise<{ at: number; cache: CacheStore } | null> {
|
|
230
|
+
const key = repo.toLowerCase()
|
|
231
|
+
let kept: { at?: unknown } | null
|
|
232
|
+
try {
|
|
233
|
+
if (cacheDir) {
|
|
234
|
+
const bytes = await readKeptFile(upstreamCachePath(cacheDir, LISTINGS, `${key}.json.gz`), LISTING_BYTES)
|
|
235
|
+
kept = bytes && JSON.parse((await gunzipAsync(bytes, { maxOutputLength: LISTING_BYTES })).toString('utf8'))
|
|
236
|
+
} else {
|
|
237
|
+
const value = await db.getUpstreamCacheEntry(`${LISTINGS}/${key}`)
|
|
238
|
+
kept = value === null ? null : JSON.parse(value)
|
|
239
|
+
}
|
|
240
|
+
} catch (error) {
|
|
241
|
+
if (debug) console.warn('managed: kept listing read failed:', error)
|
|
242
|
+
return null
|
|
243
|
+
}
|
|
244
|
+
const at = kept?.at
|
|
245
|
+
if (typeof at !== 'number') return null
|
|
246
|
+
return { at, cache: {
|
|
247
|
+
read: (type, name) => Promise.resolve(type === LISTINGS && name === key ? { ...kept, at: Date.now() } : null),
|
|
248
|
+
write: () => Promise.resolve(),
|
|
249
|
+
} }
|
|
250
|
+
}
|