@preventive/triage 1.0.0-alpha.9 → 1.0.0-alpha.90
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE-APACHE +202 -0
- package/README.md +16 -0
- package/api/reap.ts +16 -78
- 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 +6 -0
- package/common/bundle-compare-diff.js +378 -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-imports.js +20 -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 +6 -0
- package/common/bundle-reasons.js +58 -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 +10 -0
- package/common/bundle-sources.js +374 -0
- package/common/bundle-stats.js +41 -0
- package/common/bundle-tabs.js +1 -0
- package/common/code-language.js +80 -0
- package/common/default-scan-models.ts +37 -0
- package/common/dependency-reviews.d.ts +19 -0
- package/common/dependency-reviews.js +67 -0
- package/common/finding-duplicates.js +63 -0
- package/common/finding-filters.js +313 -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 +3 -0
- package/common/github-issue-labels.js +42 -0
- package/common/github-pr.ts +56 -0
- package/common/gzip.js +59 -0
- package/common/line-diff.d.ts +15 -0
- package/common/line-diff.js +188 -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/dependency-routes.js +25 -0
- package/common/managed/directory-packages.ts +28 -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 +138 -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 +9 -0
- package/common/managed/npm-packages.js +63 -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/review-view-routes.js +23 -0
- package/common/managed/risk-routes.js +30 -0
- package/common/managed/roles.ts +48 -0
- package/common/managed/routes.d.ts +2 -0
- package/common/managed/routes.js +386 -0
- package/common/managed/scan-models.ts +6 -0
- package/common/managed/stasis-config.ts +7 -0
- package/common/managed/team-app.d.ts +19 -0
- package/common/managed/team-app.js +129 -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/npm-token.d.ts +2 -0
- package/common/npm-token.js +14 -0
- package/common/pretty-json.js +123 -0
- package/common/pretty-kinds.js +20 -0
- package/common/pretty-print.d.ts +7 -0
- package/common/pretty-print.js +41 -0
- package/common/pretty-sourcemap.js +70 -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/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/sourcemap-listing.js +78 -0
- package/common/sourcemap-mappings.js +136 -0
- package/common/sourcemap-unlist.js +85 -0
- package/common/stasis-files.d.ts +5 -0
- package/common/stasis-files.js +20 -0
- package/common/stasis-tgz.d.ts +6 -0
- package/common/stasis-tgz.js +27 -0
- package/common/utf8.d.ts +3 -0
- package/common/utf8.js +45 -0
- package/common/whitespace-insensitive.js +19 -0
- package/common/workspace-app.js +91 -0
- package/common/workspace-groups.js +176 -0
- package/out/activity.js +2 -0
- package/out/brotli-fallback.js +3 -3
- package/out/chunk-2XUEZHIP.js +28 -0
- package/out/chunk-3DOSBILK.js +4 -0
- package/out/chunk-55YIWY3H.js +5 -0
- package/out/chunk-5AVGKFMR.js +1 -0
- package/out/chunk-5PWEAEA5.js +1 -0
- package/out/chunk-6VOB5WXX.js +2 -0
- package/out/chunk-6Y6PZ2BU.js +9 -0
- package/out/chunk-74JZTGTO.js +11 -0
- package/out/chunk-7BKKYVWR.js +7 -0
- package/out/chunk-7C7DWL7I.js +1 -0
- package/out/chunk-7HP2VYIC.js +2 -0
- package/out/chunk-7YFJUT2P.js +1 -0
- package/out/chunk-A4BBBHQU.js +1 -0
- package/out/chunk-B64CTMVU.js +4 -0
- package/out/chunk-BEKYZCPX.js +14 -0
- package/out/chunk-BZJU5EEV.js +1 -0
- package/out/chunk-C4Z6ZBXV.js +10 -0
- package/out/chunk-CJVMNJDZ.js +3 -0
- package/out/chunk-CU3FPB3P.js +1 -0
- package/out/chunk-DEVAORP2.js +1 -0
- package/out/chunk-DUASGS2O.js +8 -0
- package/out/chunk-EEJA7JBI.js +13 -0
- package/out/chunk-ESXA7KID.js +1 -0
- package/out/chunk-FSU2PLJL.js +1 -0
- package/out/chunk-GO7FT4OD.js +1 -0
- package/out/chunk-GX5UXWT4.js +1 -0
- package/out/chunk-HGWFRZNC.js +267 -0
- package/out/chunk-IYPY47MC.js +1 -0
- package/out/chunk-JZAROLQT.js +40 -0
- package/out/chunk-K4XJHM2T.js +1 -0
- package/out/chunk-KP2XM324.js +6 -0
- package/out/chunk-LRWB6QVO.js +1 -0
- package/out/chunk-LVSLM7HB.js +1 -0
- package/out/chunk-LVW7WWV4.js +1 -0
- package/out/chunk-N57OWFKY.js +15 -0
- package/out/chunk-NRPC74AM.js +1 -0
- package/out/chunk-OOJM4CTU.js +1 -0
- package/out/chunk-PKLVXUEI.js +11 -0
- package/out/chunk-PLGH63UC.js +2 -0
- package/out/chunk-PNHBZGDD.js +1 -0
- package/out/chunk-PWFUOLZK.js +17 -0
- package/out/chunk-PXK7EU4V.js +1 -0
- package/out/chunk-QD3IBSF4.js +7 -0
- package/out/chunk-QI66YA4F.js +1 -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-RAM3GDAD.js +1 -0
- package/out/chunk-RPNO56H2.js +1 -0
- package/out/chunk-SMNFBOLO.js +10 -0
- package/out/chunk-SSPDMA6D.js +1 -0
- package/out/chunk-SZTCJVZJ.js +55 -0
- package/out/chunk-SZWPYLPC.js +1 -0
- package/out/chunk-TKPNRQNN.js +3 -0
- package/out/chunk-TUII34K2.js +1 -0
- package/out/chunk-UJP4PQJA.js +1 -0
- package/out/chunk-UJSJMXEG.js +1 -0
- package/out/chunk-UR4WYMIP.js +1 -0
- package/out/chunk-UTYWTUTC.js +1 -0
- package/out/chunk-VHEXSGGP.js +1 -0
- package/out/chunk-VYYUMYVW.js +9 -0
- package/out/chunk-WBK5ZN4K.js +3 -0
- package/out/chunk-WCDYSIKG.js +1 -0
- package/out/chunk-XM4RLC4A.js +2 -0
- package/out/chunk-XRAAYXPR.js +1 -0
- package/out/chunk-ZQHLECTI.js +1 -0
- package/out/client-managed-import.js +4 -0
- package/out/client-managed.js +35 -0
- package/out/client-sync.js +11 -17
- package/out/compare.js +26 -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 -5
- package/out/index.html +105 -25
- package/out/prism.js +14 -10
- package/out/scan.js +2 -0
- package/out/stasis.svg +20 -0
- package/out/terminal.js +367 -39
- package/out/view.css +1 -1
- package/out/view.js +19 -148
- package/package.json +416 -64
- package/risk/actions/findings.js +161 -0
- package/risk/actions/resolve.js +287 -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 +94 -0
- package/risk/actions/workflow.js +183 -0
- package/risk/files/characters.js +354 -0
- package/risk/files/hosts.js +206 -0
- package/risk/files/readability.js +185 -0
- package/risk/files/runs-code.js +568 -0
- package/risk/files/script.js +420 -0
- package/risk/files/source-map-link.js +43 -0
- package/risk/files/stamps.js +47 -0
- package/risk/index.d.ts +309 -0
- package/risk/index.js +12 -0
- package/risk/npm/assess.js +303 -0
- package/risk/npm/combined.js +68 -0
- package/risk/npm/compare.js +236 -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 +67 -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 +401 -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 +169 -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 +52 -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 +3 -3
- package/{server → server-e2e}/static.ts +18 -17
- package/{server → server-e2e}/sync-handlers.ts +56 -30
- package/{server → server-e2e}/ws-server.ts +20 -9
- package/server-managed/activity.ts +269 -0
- package/server-managed/agent-merges.ts +109 -0
- package/server-managed/app-agents.ts +23 -0
- package/server-managed/avatar-store.ts +21 -0
- package/server-managed/blob-store.ts +26 -0
- package/server-managed/brotli.ts +10 -0
- package/server-managed/bundle-advisories.ts +176 -0
- package/server-managed/bundle-advisory-inventory.ts +85 -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 +387 -0
- package/server-managed/bundle-build.ts +328 -0
- package/server-managed/bundle-cache.ts +261 -0
- package/server-managed/bundle-catalog.ts +29 -0
- package/server-managed/bundle-commits.ts +133 -0
- package/server-managed/bundle-dependency-reviews.ts +91 -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 +151 -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 +78 -0
- package/server-managed/comparison.ts +51 -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 +1950 -0
- package/server-managed/db-neon.ts +401 -0
- package/server-managed/db-schema.ts +271 -0
- package/server-managed/db-table-names.ts +22 -0
- package/server-managed/db.ts +150 -0
- package/server-managed/dependabot-access.ts +85 -0
- package/server-managed/dependabot-alerts.ts +197 -0
- package/server-managed/dependency-review-comments.ts +158 -0
- package/server-managed/dependency-reviews.ts +369 -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 +92 -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 +169 -0
- package/server-managed/github-link-oauth.ts +56 -0
- package/server-managed/github-links.ts +204 -0
- package/server-managed/github-metadata.ts +218 -0
- package/server-managed/github-oauth.ts +264 -0
- package/server-managed/github-pulls.ts +290 -0
- package/server-managed/github-requests.ts +181 -0
- package/server-managed/github-users.ts +53 -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 +6722 -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/known-listings.ts +112 -0
- package/server-managed/link-reports.ts +149 -0
- package/server-managed/listed-activity.ts +39 -0
- package/server-managed/locked-packages.ts +234 -0
- package/server-managed/lockfile-scope.ts +58 -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 +116 -0
- package/server-managed/npm-delta-worker.js +203 -0
- package/server-managed/npm-delta.ts +277 -0
- package/server-managed/npm-insights.ts +455 -0
- package/server-managed/npm-kept.ts +274 -0
- package/server-managed/npm-loads.ts +259 -0
- package/server-managed/npm-manifest.ts +117 -0
- package/server-managed/npm-packages.ts +477 -0
- package/server-managed/npm-patch-paths.ts +86 -0
- package/server-managed/npm-patch.ts +457 -0
- package/server-managed/npm-provenance.ts +127 -0
- package/server-managed/npm-risk.ts +310 -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 +127 -0
- package/server-managed/pretty-copies.ts +22 -0
- package/server-managed/pretty-format.d.ts +4 -0
- package/server-managed/pretty-format.js +27 -0
- package/server-managed/pretty-print.ts +444 -0
- package/server-managed/public-workspace.ts +242 -0
- package/server-managed/pull-comment-reviews.ts +161 -0
- package/server-managed/pull-dependencies.ts +370 -0
- package/server-managed/pull-dependency-reviews.ts +458 -0
- package/server-managed/pull-reviews.ts +202 -0
- package/server-managed/pulse-walk.ts +164 -0
- package/server-managed/queue.ts +54 -0
- package/server-managed/release-commits.ts +85 -0
- package/server-managed/rename-diff-worker.js +30 -0
- package/server-managed/rename-diff.ts +237 -0
- package/server-managed/repo-path.ts +21 -0
- package/server-managed/report-migration.ts +32 -0
- package/server-managed/report-opening.ts +77 -0
- package/server-managed/report-query.ts +10 -0
- package/server-managed/report-response.ts +16 -0
- package/server-managed/report-sources.ts +185 -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 +119 -0
- package/server-managed/repository-browser.ts +362 -0
- package/server-managed/repository-changes.ts +280 -0
- package/server-managed/repository-code.ts +222 -0
- package/server-managed/repository-dependency-reviews.ts +220 -0
- package/server-managed/repository-discovery.ts +83 -0
- package/server-managed/repository-history.ts +444 -0
- package/server-managed/repository-issues.ts +293 -0
- package/server-managed/repository-policy.ts +27 -0
- package/server-managed/repository-pulls.ts +207 -0
- package/server-managed/repository-pulse.ts +409 -0
- package/server-managed/repository-risk-assess.ts +179 -0
- package/server-managed/repository-risk-audit.ts +145 -0
- package/server-managed/repository-risk-caches.ts +56 -0
- package/server-managed/repository-risk-kept.ts +86 -0
- package/server-managed/repository-risk-read.ts +296 -0
- package/server-managed/repository-risk-stasis.ts +61 -0
- package/server-managed/repository-risk-turn.ts +97 -0
- package/server-managed/repository-risk.ts +528 -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 +170 -0
- package/server-managed/revisions.ts +35 -0
- package/server-managed/scan-downloads.ts +121 -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 +147 -0
- package/server-managed/stasis-dependencies.ts +280 -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 +57 -0
- package/server-managed/team-app.ts +162 -0
- package/server-managed/team-catalog.ts +7 -0
- package/server-managed/team-feed.ts +180 -0
- package/server-managed/team-icons.ts +50 -0
- package/server-managed/team-npm-scopes.ts +103 -0
- package/server-managed/team-progress.ts +77 -0
- package/server-managed/team-reports.ts +369 -0
- package/server-managed/triage-response.ts +16 -0
- package/server-managed/type-only-proof.js +181 -0
- package/server-managed/type-only-worker.js +31 -0
- package/server-managed/type-only.ts +135 -0
- package/server-managed/uploads.ts +106 -0
- package/server-managed/upstream-cache.ts +275 -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/strip-types-loader.js +13 -10
- 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,264 @@
|
|
|
1
|
+
import { type GithubFixResult, githubIssueClosedReason, isGithubRepoName, parseGithubFixUrl, parseGithubIssueUrl } from '../common/github-pr.ts'
|
|
2
|
+
import type { ManagedConfig } from './config.ts'
|
|
3
|
+
import type { ManagedDb, TeamReportAccessSnapshot } from './db.ts'
|
|
4
|
+
import type { IssueTracking, ManagedIssue } from './managed-issues.ts'
|
|
5
|
+
import { ensureUserAccessToken } from './github-oauth.ts'
|
|
6
|
+
import { GITHUB_API, USER_AGENT } from './github-requests.ts'
|
|
7
|
+
import { githubFixKey as jobKey } from './github-metadata.ts'
|
|
8
|
+
import { allowedRepositories, deadlineFetch, lookupFixes } from './github-pulls.ts'
|
|
9
|
+
import { isId } from './github-values.ts'
|
|
10
|
+
|
|
11
|
+
export type IssueFixUpdate = { findingId: string; issueUrl: string; previous: IssueTracking; next: IssueTracking; checkedAt: number }
|
|
12
|
+
type Pull = { number: number; title: string; body: string | null; state: string; isDraft: boolean; createdAt: string;
|
|
13
|
+
repository: { databaseId: number; nameWithOwner: string } }
|
|
14
|
+
type Connection = { nodes: Pull[]; pageInfo: { hasNextPage: boolean; endCursor: string | null } }
|
|
15
|
+
type RepositoryReference = { databaseId?: unknown; nameWithOwner?: unknown } | null | undefined
|
|
16
|
+
type IssueReference = { number?: unknown; repository?: RepositoryReference }
|
|
17
|
+
type Issue = { number: number; title: string; body: string | null; state: string; stateReason: string | null; closedByPullRequestsReferences?: Connection
|
|
18
|
+
duplicateOf?: IssueReference | null }
|
|
19
|
+
type Repository = TeamReportAccessSnapshot['repositories'][number]
|
|
20
|
+
// The issue a linked one was closed as a duplicate of, in a workspace
|
|
21
|
+
// repository: null for none (or one outside them, never followed or
|
|
22
|
+
// disclosed, as a pull request outside them isn't).
|
|
23
|
+
type Duplicate = { repo: Repository; number: number } | null
|
|
24
|
+
// `duplicateOf` is a linked issue's, from its last page read: undefined while
|
|
25
|
+
// none is, or where GitHub refused the reference.
|
|
26
|
+
type Job = { repo: Repository; kind: 'pull' | 'issue'; number: number; aliases: string[];
|
|
27
|
+
linked: boolean; cursor: string | null; pulls: Pull[]; complete: boolean; duplicateOf?: Duplicate | undefined }
|
|
28
|
+
type Metadata = Exclude<GithubFixResult, { error: string }>
|
|
29
|
+
// A batch's answer: each job's repository by its alias (metadataQuery).
|
|
30
|
+
type Page = Record<string, { databaseId: number; nameWithOwner: string; item: Issue | Pull } | null>
|
|
31
|
+
const pullFields = 'number title body state isDraft createdAt repository { databaseId nameWithOwner }'
|
|
32
|
+
// A linked issue's: the issue it was closed as a duplicate of, and a page of
|
|
33
|
+
// the pull requests linked to it.
|
|
34
|
+
const linkedFields = (cursor: string | null) => 'duplicateOf { number repository { databaseId nameWithOwner } } '
|
|
35
|
+
+ `closedByPullRequestsReferences(first: 100, includeClosedPrs: true, after: ${JSON.stringify(cursor)}) { nodes { ${pullFields} } pageInfo { hasNextPage endCursor } }`
|
|
36
|
+
// How many issues a saved one is followed through, each closed as a
|
|
37
|
+
// duplicate of the next: each is another request after the last.
|
|
38
|
+
const MAX_DUPLICATE_HOPS = 5
|
|
39
|
+
const issueUrlOf = (repo: Repository, number: number) => `https://github.com/${repo.github}/issues/${number}`
|
|
40
|
+
// Whether GitHub named a repository as one is: by its stable ID and a name.
|
|
41
|
+
const isRepositoryReference = (ref: RepositoryReference): ref is { databaseId: number; nameWithOwner: string } =>
|
|
42
|
+
Number.isSafeInteger(ref?.databaseId) && typeof ref?.nameWithOwner === 'string' && isGithubRepoName(ref.nameWithOwner)
|
|
43
|
+
// The workspace repository GitHub named, matching its name and stable ID
|
|
44
|
+
// both; none for one outside the workspace repository grants.
|
|
45
|
+
const workspaceRepository = (ref: { databaseId: number; nameWithOwner: string }, allowed: Map<string, Repository>) => {
|
|
46
|
+
const repo = allowed.get(ref.nameWithOwner.toLowerCase())
|
|
47
|
+
return repo?.repoId === ref.databaseId ? repo : null
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function metadataQuery(jobs: Job[]) {
|
|
51
|
+
return `{ ${jobs.map((job, index) => {
|
|
52
|
+
const [owner, name] = job.repo.github.split('/')
|
|
53
|
+
const fields = job.kind === 'pull' ? pullFields : `number title body state stateReason ${job.linked ? linkedFields(job.cursor) : ''}`
|
|
54
|
+
return `r${index}: repository(owner: ${JSON.stringify(owner)}, name: ${JSON.stringify(name)}) { databaseId nameWithOwner item: ${job.kind === 'pull' ? 'pullRequest' : 'issue'}(number: ${job.number}) { ${fields} } }`
|
|
55
|
+
}).join('\n')} }`
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function itemMetadata(item: Issue | Pull, kind: Job['kind']): Omit<Metadata, 'url'> | null {
|
|
59
|
+
if (!item || typeof item.title !== 'string' || !item.title.trim() || item.title.length > 1024
|
|
60
|
+
|| item.body != null && typeof item.body !== 'string' || !['OPEN', 'CLOSED', ...(kind === 'pull' ? ['MERGED'] : [])].includes(item.state)) return null
|
|
61
|
+
const status = item.state === 'MERGED' ? 'merged' : item.state === 'CLOSED' ? 'closed' : 'isDraft' in item && item.isDraft === true ? 'draft' : 'open'
|
|
62
|
+
const stateReason = kind === 'issue' && status === 'closed' ? githubIssueClosedReason(String((item as Issue).stateReason).toLowerCase()) : null
|
|
63
|
+
return { title: item.title, description: item.body ?? null, status, stateReason }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// The issue `issue` was closed as a duplicate of, where GitHub names one
|
|
67
|
+
// (Duplicate); undefined for a reference it gave malformed.
|
|
68
|
+
function duplicateOf(issue: Issue, allowed: Map<string, Repository>): Duplicate | undefined {
|
|
69
|
+
if (issue.state !== 'CLOSED' || issue.stateReason !== 'DUPLICATE' || issue.duplicateOf == null) return null
|
|
70
|
+
const { number, repository } = issue.duplicateOf
|
|
71
|
+
if (!isId(number) || !isRepositoryReference(repository)) return undefined
|
|
72
|
+
const repo = workspaceRepository(repository, allowed)
|
|
73
|
+
return repo ? { repo, number } : null
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// `refused`: GitHub answered with an error on the issue's duplicate alone,
|
|
77
|
+
// which, like a malformed one, leaves it shown but what it redirects to
|
|
78
|
+
// unknown.
|
|
79
|
+
function readPage(job: Job, item: Issue | Pull, metadata: Map<string, Metadata>, allowed: Map<string, Repository>, refused: boolean): boolean {
|
|
80
|
+
const details = itemMetadata(item, job.kind)
|
|
81
|
+
if (!details || item.number !== job.number) return false
|
|
82
|
+
for (const url of job.aliases) metadata.set(url, { url, ...details })
|
|
83
|
+
if (!job.linked) return false
|
|
84
|
+
const duplicate = refused ? undefined : duplicateOf(item as Issue, allowed)
|
|
85
|
+
if (duplicate === undefined) return false
|
|
86
|
+
const connection = (item as Issue).closedByPullRequestsReferences
|
|
87
|
+
if (!connection || !Array.isArray(connection.nodes) || typeof connection.pageInfo?.hasNextPage !== 'boolean'
|
|
88
|
+
|| connection.nodes.some(pr => !pr || !isId(pr.number) || typeof pr.createdAt !== 'string'
|
|
89
|
+
|| !Number.isFinite(Date.parse(pr.createdAt)) || !itemMetadata(pr, 'pull') || typeof pr.isDraft !== 'boolean'
|
|
90
|
+
|| !isRepositoryReference(pr.repository))) return false
|
|
91
|
+
job.duplicateOf = duplicate
|
|
92
|
+
job.pulls.push(...connection.nodes)
|
|
93
|
+
if (!connection.pageInfo.hasNextPage) { job.complete = true; return false }
|
|
94
|
+
if (typeof connection.pageInfo.endCursor !== 'string' || !connection.pageInfo.endCursor || connection.pageInfo.endCursor === job.cursor) return false
|
|
95
|
+
job.cursor = connection.pageInfo.endCursor
|
|
96
|
+
return true
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// A saved issue's job, then those of the issues it was closed as a duplicate
|
|
100
|
+
// of in turn, as far as this lookup has read them, a redirect followed rather
|
|
101
|
+
// than the saved issue replaced. `next` is null where the last names none
|
|
102
|
+
// further to follow (or one already in the chain, or past
|
|
103
|
+
// MAX_DUPLICATE_HOPS); the one it names where this lookup has no linked job
|
|
104
|
+
// for it; undefined where one is yet unread, or what it names unknown.
|
|
105
|
+
function duplicateChain(root: Job, jobs: Map<string, Job>): { chain: Job[]; next: Duplicate | undefined } {
|
|
106
|
+
const chain = [root]
|
|
107
|
+
for (let job = root; ;) {
|
|
108
|
+
const target = job.duplicateOf
|
|
109
|
+
if (!target || chain.length > MAX_DUPLICATE_HOPS) return { chain, next: target && null }
|
|
110
|
+
const next = jobs.get(jobKey(target.repo.repoId, 'issue', target.number))
|
|
111
|
+
if (next && chain.includes(next)) return { chain, next: null }
|
|
112
|
+
if (!next?.linked) return { chain, next: target }
|
|
113
|
+
chain.push(job = next)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// The issues saved ones were closed as duplicates of, which this lookup has
|
|
118
|
+
// yet to read with their linked pull requests: each made a linked job, as a
|
|
119
|
+
// saved issue's own is (one read without them never read further).
|
|
120
|
+
function duplicateJobs(jobs: Map<string, Job>, roots: Iterable<string>): Job[] {
|
|
121
|
+
const found: Job[] = []
|
|
122
|
+
for (const key of roots) {
|
|
123
|
+
const root = jobs.get(key)
|
|
124
|
+
const next = root && duplicateChain(root, jobs).next
|
|
125
|
+
if (!next) continue
|
|
126
|
+
const nextKey = jobKey(next.repo.repoId, 'issue', next.number), url = issueUrlOf(next.repo, next.number)
|
|
127
|
+
let job = jobs.get(nextKey)
|
|
128
|
+
if (!job) jobs.set(nextKey, job = { repo: next.repo, kind: 'issue', number: next.number, aliases: [], linked: true, cursor: null, pulls: [], complete: false })
|
|
129
|
+
job.linked = true
|
|
130
|
+
if (!job.aliases.includes(url)) job.aliases.push(url)
|
|
131
|
+
found.push(job)
|
|
132
|
+
}
|
|
133
|
+
return found
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// `byIssue`: the saved issues each job's issue is, by its key.
|
|
137
|
+
function issueUpdates(jobs: Map<string, Job>, byIssue: Map<string, ManagedIssue[]>, allowed: Map<string, Repository>, checkedAt: number, metadata: Map<string, Metadata>) {
|
|
138
|
+
const updates: IssueFixUpdate[] = []
|
|
139
|
+
for (const [key, saved] of byIssue) {
|
|
140
|
+
const root = jobs.get(key)
|
|
141
|
+
if (!root?.linked) continue
|
|
142
|
+
// The saved issue and every one it was closed as a duplicate of in turn,
|
|
143
|
+
// each read whole: the last is tracked, and the pull requests of all.
|
|
144
|
+
const { chain, next } = duplicateChain(root, jobs)
|
|
145
|
+
if (next !== null || !chain.every(job => job.complete)) continue
|
|
146
|
+
// "Last" means the newest PR by creation time, never its latest comment.
|
|
147
|
+
const latest = chain.flatMap(job => job.pulls).filter(pr => pr.state !== 'CLOSED')
|
|
148
|
+
.toSorted((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt) || b.number - a.number)[0]
|
|
149
|
+
const repo = latest && workspaceRepository(latest.repository, allowed)
|
|
150
|
+
// The viewer's token can have broader access than this workspace. Never
|
|
151
|
+
// persist or disclose a PR from outside the workspace repository grants:
|
|
152
|
+
// where the newest is one, the saved Fix stays. The duplicate, checked
|
|
153
|
+
// against the grants itself, is saved all the same.
|
|
154
|
+
const foreign = Boolean(latest && !repo)
|
|
155
|
+
const autoFix = latest && repo ? `https://github.com/${repo.github}/pull/${latest.number}` : null
|
|
156
|
+
if (latest && autoFix) metadata.set(autoFix, { url: autoFix, ...itemMetadata(latest, 'pull')! })
|
|
157
|
+
const last = chain.at(-1)!
|
|
158
|
+
const duplicate = chain.length > 1 ? issueUrlOf(last.repo, last.number) : null
|
|
159
|
+
// Only a changed derived Fix or duplicate is written: an unchanged one's
|
|
160
|
+
// check time alone would bump the annotations revision that every open
|
|
161
|
+
// team feed polls, for nothing they show. Changes still stamp it, so an
|
|
162
|
+
// older lookup never replaces a newer change (managed-issues.ts). An older
|
|
163
|
+
// lookup that differs can now land after a newer unchanged one, as it
|
|
164
|
+
// could already land before it (whose compare-and-set then fails); either
|
|
165
|
+
// way the next lookup finds the stored values differ, and writes the
|
|
166
|
+
// current ones.
|
|
167
|
+
for (const issue of saved) {
|
|
168
|
+
const tracking = { autoFix: foreign ? issue.autoFixUrl : autoFix, duplicateOf: duplicate }
|
|
169
|
+
if (issue.autoFixUrl !== tracking.autoFix || issue.duplicateOfUrl !== tracking.duplicateOf) {
|
|
170
|
+
updates.push({ findingId: issue.findingId, issueUrl: issue.issueUrl!, checkedAt,
|
|
171
|
+
previous: { autoFix: issue.autoFixUrl, duplicateOf: issue.duplicateOfUrl }, next: tracking })
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return updates
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// The jobs of `urls`, one for each pull request or issue of a workspace
|
|
179
|
+
// repository (`allowed`) they name, its URLs its aliases, and the saved
|
|
180
|
+
// `issues` by their issue's key (`byIssue`). Linked jobs are read with their
|
|
181
|
+
// linked pull requests: the saved issues', and the duplicates they were
|
|
182
|
+
// saved with.
|
|
183
|
+
function jobsOf(urls: string[], issues: ManagedIssue[], allowed: Map<string, Repository>) {
|
|
184
|
+
const jobs = new Map<string, Job>()
|
|
185
|
+
const byIssue = new Map<string, ManagedIssue[]>(), linked = new Set<string>()
|
|
186
|
+
for (const issue of issues) {
|
|
187
|
+
const ref = parseGithubIssueUrl(issue.issueUrl)
|
|
188
|
+
if (!ref) continue
|
|
189
|
+
const key = jobKey(issue.repoId, 'issue', ref.number)
|
|
190
|
+
byIssue.set(key, [...byIssue.get(key) ?? [], issue])
|
|
191
|
+
linked.add(key)
|
|
192
|
+
const duplicate = parseGithubIssueUrl(issue.duplicateOfUrl), repo = duplicate && allowed.get(duplicate.repo.toLowerCase())
|
|
193
|
+
if (duplicate && repo) linked.add(jobKey(repo.repoId, 'issue', duplicate.number))
|
|
194
|
+
}
|
|
195
|
+
for (const url of urls) {
|
|
196
|
+
const ref = parseGithubFixUrl(url), repo = ref && allowed.get(ref.repo.toLowerCase())
|
|
197
|
+
if (!ref || !repo) continue
|
|
198
|
+
const key = jobKey(repo.repoId, ref.kind, ref.number), previous = jobs.get(key)
|
|
199
|
+
if (previous) { previous.aliases.push(url); continue }
|
|
200
|
+
jobs.set(key, { repo, kind: ref.kind, number: ref.number, aliases: [url], linked: linked.has(key), cursor: null, pulls: [], complete: false })
|
|
201
|
+
}
|
|
202
|
+
return { jobs, byIssue }
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// GitHub's answer to `batch`'s query, asked with `token`: each job's
|
|
206
|
+
// repository by its alias, and the aliases whose duplicate alone GitHub
|
|
207
|
+
// refused (readPage); null where none was read, or what was is malformed.
|
|
208
|
+
async function readBatch(batch: Job[], token: string, fetchImpl: typeof fetch): Promise<{ data: Page; refused: Set<string> } | null> {
|
|
209
|
+
const query = metadataQuery(batch)
|
|
210
|
+
try {
|
|
211
|
+
const response = await fetchImpl(`${GITHUB_API}/graphql`, {
|
|
212
|
+
method: 'POST', redirect: 'error',
|
|
213
|
+
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', 'user-agent': USER_AGENT }, body: JSON.stringify({ query }),
|
|
214
|
+
})
|
|
215
|
+
if (!response.ok) return null
|
|
216
|
+
const body = await response.json() as { data?: Page; errors?: { path?: unknown[] }[] }
|
|
217
|
+
// Errors attached to an alias invalidate that whole job, including its
|
|
218
|
+
// connection. Other aliases can succeed even if one issue was deleted.
|
|
219
|
+
// One on the issue it duplicates alone, which the viewer may be unable
|
|
220
|
+
// to read, leaves its status, and only what it redirects to unknown.
|
|
221
|
+
if (!body?.data || body.errors != null && (!Array.isArray(body.errors)
|
|
222
|
+
|| body.errors.some(error => typeof error?.path?.[0] !== 'string' || !/^r\d+$/u.test(error.path[0])))) return null
|
|
223
|
+
const { data } = body, refused = new Set<string>()
|
|
224
|
+
for (const error of body.errors ?? []) {
|
|
225
|
+
const [alias, field, reference] = error.path! as string[]
|
|
226
|
+
if (field === 'item' && reference === 'duplicateOf') refused.add(alias!)
|
|
227
|
+
else data[alias!] = null
|
|
228
|
+
}
|
|
229
|
+
return { data, refused }
|
|
230
|
+
} catch { return null }
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// Fetch issue details, linked PR states and manual Fix metadata in one batch.
|
|
234
|
+
// Pagination, workspaces with over 200 distinct links, and issues closed as a
|
|
235
|
+
// duplicate of one not yet read need further batches. A duplicate saved last
|
|
236
|
+
// time is read in the first, as a redirect kept is: its URL among `urls`.
|
|
237
|
+
// Live GraphQL results prove this viewer's access; never publish them into the
|
|
238
|
+
// REST shared cache under an older public-visibility grant.
|
|
239
|
+
export async function lookupIssueLinks(config: ManagedConfig, db: ManagedDb, snapshot: TeamReportAccessSnapshot,
|
|
240
|
+
urls: string[], issues: ManagedIssue[], fetchImpl: typeof fetch = fetch): Promise<{ fixes: GithubFixResult[]; updates: IssueFixUpdate[] }> {
|
|
241
|
+
const checkedAt = Date.now(), signal = AbortSignal.timeout(10_000)
|
|
242
|
+
const allowed = allowedRepositories(snapshot)
|
|
243
|
+
const { jobs, byIssue } = jobsOf(urls, issues, allowed)
|
|
244
|
+
if (jobs.size === 0) return { fixes: [], updates: [] }
|
|
245
|
+
const withinDeadline = deadlineFetch(fetchImpl, signal)
|
|
246
|
+
const token = await ensureUserAccessToken(config, db, snapshot.user.id, checkedAt, withinDeadline)
|
|
247
|
+
if (!token) return { fixes: await lookupFixes(config, db, snapshot, urls, withinDeadline), updates: [] }
|
|
248
|
+
const metadata = new Map<string, Metadata>()
|
|
249
|
+
let pending = [...jobs.values()]
|
|
250
|
+
for (let page = 0; pending.length > 0 && page < 100 && !signal.aborted; page++) {
|
|
251
|
+
const batch = pending.slice(0, 200)
|
|
252
|
+
const answer = await readBatch(batch, token, withinDeadline)
|
|
253
|
+
if (!answer) break
|
|
254
|
+
pending = pending.slice(batch.length)
|
|
255
|
+
for (const [index, job] of batch.entries()) {
|
|
256
|
+
const repository = answer.data[`r${index}`]
|
|
257
|
+
if (repository?.databaseId !== job.repo.repoId || typeof repository.nameWithOwner !== 'string' || repository.nameWithOwner.toLowerCase() !== job.repo.github.toLowerCase()) continue
|
|
258
|
+
if (readPage(job, repository.item, metadata, allowed, answer.refused.has(`r${index}`))) pending.push(job)
|
|
259
|
+
}
|
|
260
|
+
for (const job of duplicateJobs(jobs, byIssue.keys())) if (!pending.includes(job)) pending.push(job)
|
|
261
|
+
}
|
|
262
|
+
const updates = issueUpdates(jobs, byIssue, allowed, checkedAt, metadata)
|
|
263
|
+
return { fixes: [...metadata.values()], updates }
|
|
264
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { ManagedConfig } from './config.ts'
|
|
2
|
+
import type { ManagedDb, ManagedSession } from './db.ts'
|
|
3
|
+
import { ISSUE_STATE_COOKIE, clearCookie, cookieName } from './session.ts'
|
|
4
|
+
import { OAuthError, exchangeCode, fetchIdentity, sessionAuthorization, sessionStateValid, stateCookieMatches } from './github-oauth.ts'
|
|
5
|
+
|
|
6
|
+
export const ISSUE_LOGIN_PATH = '/api/oauth/github/issues/login'
|
|
7
|
+
|
|
8
|
+
export function isIssueOAuthCallback(config: ManagedConfig, query: URLSearchParams, cookie: string | undefined): boolean {
|
|
9
|
+
return stateCookieMatches(config, ISSUE_STATE_COOKIE, query, cookie)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function issueLoginRedirect(config: ManagedConfig, session: ManagedSession, now = Date.now()) {
|
|
13
|
+
// Reauthorize the same app for the current account, without replacing the
|
|
14
|
+
// DeepView session or permitting an OAuth account switch during creation.
|
|
15
|
+
const { url, setCookie } = sessionAuthorization(config, ISSUE_STATE_COOKIE, session, now)
|
|
16
|
+
return { location: url.href, setCookie }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function issueOAuthCallback(config: ManagedConfig, db: ManagedDb, session: ManagedSession,
|
|
20
|
+
query: URLSearchParams, cookie: string | undefined, fetchImpl: typeof fetch = fetch, now = Date.now()) {
|
|
21
|
+
const code = query.get('code')
|
|
22
|
+
if (!code || !sessionStateValid(config, ISSUE_STATE_COOKIE, session, query, cookie, now)) throw new OAuthError(400, 'invalid-oauth-state')
|
|
23
|
+
const tokens = await exchangeCode(config, code, now, fetchImpl)
|
|
24
|
+
const identity = await fetchIdentity(tokens.accessToken, fetchImpl)
|
|
25
|
+
if (identity.githubUserId !== await db.getUserGithubId(session.userId)) throw new OAuthError(403, 'github-account-mismatch')
|
|
26
|
+
const current = await db.sessionWithUser(session.id, Date.now())
|
|
27
|
+
if (!current || current.user.role === 'none' || current.session.userId !== session.userId) throw new OAuthError(401, 'unauthenticated')
|
|
28
|
+
await db.setUserTokens(session.userId, tokens)
|
|
29
|
+
return { location: '/github-issue-authorized.html', setCookie: clearCookie(cookieName(config, ISSUE_STATE_COOKIE), config.cookieSecure) }
|
|
30
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import type { ManagedConfig } from './config.ts'
|
|
2
|
+
import type { ManagedDb, ManagedSession } from './db.ts'
|
|
3
|
+
import type { BlobStore } from './blob-store.ts'
|
|
4
|
+
import type { ManagedIssue } from './managed-issues.ts'
|
|
5
|
+
import { randomToken } from './crypto.ts'
|
|
6
|
+
import { githubIssueClosedReason } from '../common/github-pr.ts'
|
|
7
|
+
import { reportEntries, reportRepoGithub } from '@preventive/report'
|
|
8
|
+
import { issueLabelChoices, newIssueLabels } from '../common/github-issue-labels.js'
|
|
9
|
+
import { ignoresOwnRepo } from '../common/finding-repo.js'
|
|
10
|
+
import { appJwt, githubAppConfigured, installUrl, publicRepositoryName } from './github-app.ts'
|
|
11
|
+
import { ISSUE_LOGIN_PATH } from './github-issue-oauth.ts'
|
|
12
|
+
import { ensureUserAccessToken } from './github-oauth.ts'
|
|
13
|
+
import { GITHUB_API, encodedPath, githubHeaders } from './github-requests.ts'
|
|
14
|
+
import { isId } from './github-values.ts'
|
|
15
|
+
import { TeamReportsError, loadTeamReports, recheckTeam, teamSnapshot } from './team-reports.ts'
|
|
16
|
+
|
|
17
|
+
export const MAX_ISSUE_BODY_BYTES = 512_000
|
|
18
|
+
export class IssueError extends Error {
|
|
19
|
+
status: number
|
|
20
|
+
constructor(status: number, message: string) { super(message); this.status = status }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type Context = { reportId: string; findingId: string; repository: string }
|
|
24
|
+
export function parseIssueContext(raw: unknown): Context {
|
|
25
|
+
const value = raw as Partial<Context> | null
|
|
26
|
+
const repository = publicRepositoryName(value?.repository)
|
|
27
|
+
if (!repository || typeof value?.reportId !== 'string' || !value.reportId || value.reportId.length > 200
|
|
28
|
+
|| typeof value.findingId !== 'string' || !value.findingId || value.findingId.length > 4096) throw new IssueError(400, 'bad-request')
|
|
29
|
+
return { repository, reportId: value.reportId, findingId: value.findingId }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function github(path: string, token: string, fetchImpl: typeof fetch, payload?: unknown) {
|
|
33
|
+
let response: Response
|
|
34
|
+
try {
|
|
35
|
+
response = await fetchImpl(`${GITHUB_API}${path}`, {
|
|
36
|
+
method: payload === undefined ? 'GET' : 'POST', redirect: 'error', signal: AbortSignal.timeout(15_000),
|
|
37
|
+
headers: { ...githubHeaders(token), 'content-type': 'application/json' },
|
|
38
|
+
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
|
|
39
|
+
})
|
|
40
|
+
} catch { throw new IssueError(502, payload === undefined ? 'github-unavailable' : 'github-create-uncertain') }
|
|
41
|
+
return response
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function referenceResult(stored: ManagedIssue, repoIds: number[]) {
|
|
45
|
+
// A shared finding ID does not grant access to another team's repository.
|
|
46
|
+
if (!repoIds.includes(stored.repoId)) return { mode: 'unavailable' as const }
|
|
47
|
+
return stored.issueUrl ? { mode: 'existing' as const, url: stored.issueUrl }
|
|
48
|
+
: { mode: 'pending' as const, repositoryUrl: `https://github.com/${stored.repository}/issues` }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function issueDetails(raw: unknown, url: string, number: number, fallback: { title: string; body: string; labels: string[] }) {
|
|
52
|
+
const issue = raw as { title?: unknown; body?: unknown; state?: unknown; state_reason?: unknown;
|
|
53
|
+
user?: { login?: unknown }; labels?: ({ name?: unknown } | string)[] } | null
|
|
54
|
+
const status = issue?.state === 'closed' ? 'closed' : 'open'
|
|
55
|
+
return { url, number, title: typeof issue?.title === 'string' ? issue.title : fallback.title,
|
|
56
|
+
description: typeof issue?.body === 'string' ? issue.body : fallback.body, status,
|
|
57
|
+
stateReason: status === 'closed' ? githubIssueClosedReason(issue?.state_reason) : null,
|
|
58
|
+
author: typeof issue?.user?.login === 'string' ? issue.user.login : null,
|
|
59
|
+
labels: Array.isArray(issue?.labels) ? issue.labels.map(label => typeof label === 'string' ? label : label?.name).filter((label): label is string => typeof label === 'string') : fallback.labels }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Authorize before any upstream lookup, including installation/label discovery.
|
|
63
|
+
// Report filtering also supplies the full row/link isSecurity classification.
|
|
64
|
+
export async function prepareGithubIssue(config: ManagedConfig, db: ManagedDb, store: BlobStore,
|
|
65
|
+
session: ManagedSession, teamId: string, context: Context, fetchImpl: typeof fetch = fetch) {
|
|
66
|
+
const snapshot = await teamSnapshot(db, session.id, teamId, context.reportId)
|
|
67
|
+
if (!snapshot.reports.some(report => report.id === context.reportId)) throw new TeamReportsError(404, 'no-report')
|
|
68
|
+
const reports = await loadTeamReports(db, store, snapshot)
|
|
69
|
+
const report = reports.find(item => item.id === context.reportId)!
|
|
70
|
+
const findings = (reportEntries(report.data) ?? []).flat() as Record<string, unknown>[]
|
|
71
|
+
const finding = findings.find(item => item['id'] === context.findingId)
|
|
72
|
+
if (!finding) throw new TeamReportsError(404, 'no-finding')
|
|
73
|
+
const recheck = () => recheckTeam(db, session.id, snapshot)
|
|
74
|
+
await recheck()
|
|
75
|
+
const labels = newIssueLabels(finding, config.githubNewIssueLabels ?? '')
|
|
76
|
+
const repoIds = snapshot.repositories.map(repo => repo.repoId)
|
|
77
|
+
const stored = await db.getManagedIssue(context.findingId)
|
|
78
|
+
if (stored) return { ...referenceResult(stored, repoIds), labels, recheck }
|
|
79
|
+
// The target comes from this finding's own source, or the report's managed
|
|
80
|
+
// assignment. Team membership alone must not let a caller claim an unrelated
|
|
81
|
+
// repository's issue as the permanent reference for this finding. One on an
|
|
82
|
+
// advisory naming the advised package's repository as its own is the
|
|
83
|
+
// report's (common/finding-repo.js).
|
|
84
|
+
const findingRepo = (ignoresOwnRepo(finding, report.repo.github) ? null : finding['repo']) as { github?: unknown } | null | undefined
|
|
85
|
+
const targetRepository = publicRepositoryName(reportRepoGithub({ repo: { github: findingRepo?.github || report.repo.github } }))
|
|
86
|
+
if (!targetRepository || targetRepository.toLowerCase() !== context.repository.toLowerCase()) throw new IssueError(400, 'bad-issue-repository')
|
|
87
|
+
const repository = snapshot.repositories.find(repo => repo.github.toLowerCase() === targetRepository.toLowerCase())
|
|
88
|
+
if (!repository || !githubAppConfigured(config)) return { mode: 'form' as const, labels, recheck }
|
|
89
|
+
const path = `/repos/${encodedPath(targetRepository)}`
|
|
90
|
+
const installation = await github(`${path}/installation`, appJwt(config.githubAppId!, config.githubAppPrivateKey!), fetchImpl)
|
|
91
|
+
if (installation.status === 404) return { mode: 'form' as const, labels, recheck }
|
|
92
|
+
if (!installation.ok) throw new IssueError(502, 'github-unavailable')
|
|
93
|
+
let installed: { permissions?: { issues?: string } }
|
|
94
|
+
try { installed = await installation.json() } catch { throw new IssueError(502, 'github-unavailable') }
|
|
95
|
+
if (installed?.permissions?.issues !== 'write') return { mode: 'permissions' as const, authorizationPath: installUrl(config), labels, recheck }
|
|
96
|
+
const token = await ensureUserAccessToken(config, db, session.userId, Date.now(), fetchImpl)
|
|
97
|
+
if (!token) return { mode: 'authorize' as const, authorizationPath: ISSUE_LOGIN_PATH, labels, recheck }
|
|
98
|
+
// All requested labels are optional, including security and operator labels.
|
|
99
|
+
// Omit missing names rather than rejecting issue creation or creating labels.
|
|
100
|
+
// Of a choice's names, the first the repository has (`dependencies`, else
|
|
101
|
+
// `deps`), none once a label taken is among them; a name is read once.
|
|
102
|
+
const existingLabels: string[] = [], missing = new Set<string>()
|
|
103
|
+
const taken = (name: string) => existingLabels.some(label => label.toLowerCase() === name.toLowerCase())
|
|
104
|
+
for (const names of issueLabelChoices(finding, config.githubNewIssueLabels ?? '')) {
|
|
105
|
+
if (names.some(taken)) continue
|
|
106
|
+
for (const name of names) {
|
|
107
|
+
if (missing.has(name.toLowerCase())) continue
|
|
108
|
+
const label = await github(`${path}/labels/${encodeURIComponent(name)}`, token, fetchImpl)
|
|
109
|
+
if (label.status === 401) return { mode: 'authorize' as const, authorizationPath: ISSUE_LOGIN_PATH, labels, recheck }
|
|
110
|
+
if (label.status === 404) { missing.add(name.toLowerCase()); continue }
|
|
111
|
+
if (!label.ok) throw new IssueError(502, 'github-unavailable')
|
|
112
|
+
existingLabels.push(name)
|
|
113
|
+
break
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return { mode: 'api' as const, token, path, labels: existingLabels, recheck,
|
|
117
|
+
db, findingId: context.findingId, repoId: repository.repoId, repository: targetRepository, repoIds, userId: session.userId }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export async function createGithubIssue(prepared: Awaited<ReturnType<typeof prepareGithubIssue>>, input: unknown, fetchImpl: typeof fetch = fetch) {
|
|
121
|
+
if (prepared.mode !== 'api') throw new IssueError(409, 'github-authorization-required')
|
|
122
|
+
const { title, body, labels } = input as { title?: unknown; body?: unknown; labels?: unknown }
|
|
123
|
+
if (typeof title !== 'string' || !title.trim() || title.length > 256 || typeof body !== 'string' || body.length > 65_536
|
|
124
|
+
|| (labels !== undefined && (!Array.isArray(labels) || labels.length > 100 || !labels.every(label => typeof label === 'string')))) throw new IssueError(400, 'bad-issue')
|
|
125
|
+
// The labels the creator kept checked of those proposed, every one where
|
|
126
|
+
// it names none: a name not proposed is never asked for, so none is created.
|
|
127
|
+
const chosen = Array.isArray(labels) ? prepared.labels.filter(label => labels.includes(label)) : prepared.labels
|
|
128
|
+
const { db, findingId } = prepared
|
|
129
|
+
const requestId = randomToken()
|
|
130
|
+
if (!await db.claimManagedIssue({ findingId, repoId: prepared.repoId, repository: prepared.repository,
|
|
131
|
+
requestId, createdBy: prepared.userId, createdAt: Date.now() })) {
|
|
132
|
+
const stored = await db.getManagedIssue(findingId)
|
|
133
|
+
await prepared.recheck()
|
|
134
|
+
// The competing request may have released its reservation after a definite
|
|
135
|
+
// failure. Still return a listing, never a fresh creation form, for this race.
|
|
136
|
+
return stored ? referenceResult(stored, prepared.repoIds)
|
|
137
|
+
: { mode: 'pending' as const, repositoryUrl: `https://github.com/${prepared.repository}/issues` }
|
|
138
|
+
}
|
|
139
|
+
// The last awaited operation before the external write checks current access.
|
|
140
|
+
// Release only when we know no issue was created; unknown outcomes stay claimed.
|
|
141
|
+
try { await prepared.recheck() }
|
|
142
|
+
catch (error) { await db.releaseManagedIssue(findingId, requestId); throw error }
|
|
143
|
+
const response = await github(`${prepared.path}/issues`, prepared.token, fetchImpl, { title: title.trim(), body, labels: chosen })
|
|
144
|
+
if (response.status >= 400 && response.status < 500) await db.releaseManagedIssue(findingId, requestId)
|
|
145
|
+
if (response.status === 401) throw new IssueError(409, 'github-authorization-required')
|
|
146
|
+
if (response.status === 403) throw new IssueError(403, 'github-issue-forbidden')
|
|
147
|
+
if (!response.ok) throw new IssueError(response.status === 422 ? 422 : 502, response.status >= 500 ? 'github-create-uncertain' : 'github-create-failed')
|
|
148
|
+
let issue: { number?: unknown }
|
|
149
|
+
try { issue = await response.json() } catch { throw new IssueError(502, 'github-create-uncertain') }
|
|
150
|
+
if (!isId(issue?.number)) throw new IssueError(502, 'github-create-uncertain')
|
|
151
|
+
// Construct the URL from validated inputs, never an upstream redirect target.
|
|
152
|
+
const number = Number(issue.number), url = `https://github.com${prepared.path.slice('/repos'.length)}/issues/${issue.number}`
|
|
153
|
+
if (!await db.finishManagedIssue(findingId, requestId, url)) throw new IssueError(502, 'github-create-uncertain')
|
|
154
|
+
let details = issueDetails(issue, url, number, { title, body, labels: chosen }), detailsUnavailable = true
|
|
155
|
+
try {
|
|
156
|
+
const fetched = await github(`${prepared.path}/issues/${number}`, prepared.token, fetchImpl)
|
|
157
|
+
if (fetched.ok) {
|
|
158
|
+
details = issueDetails(await fetched.json(), url, number, { title, body, labels: chosen })
|
|
159
|
+
detailsUnavailable = false
|
|
160
|
+
}
|
|
161
|
+
} catch { /* Creation and its permanent reference succeeded; detail reads are best effort. */ }
|
|
162
|
+
try { await prepared.recheck() }
|
|
163
|
+
catch {
|
|
164
|
+
// The external write and permanent reference succeeded. Withhold details
|
|
165
|
+
// if current access cannot be confirmed, but never advertise a safe retry.
|
|
166
|
+
return { mode: 'created-unavailable' as const }
|
|
167
|
+
}
|
|
168
|
+
return { url, issue: details, detailsUnavailable }
|
|
169
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Linking another GitHub account to the signed-in user (github-links.ts): the
|
|
2
|
+
// App's user authorization again, completed by the account to link. GitHub is
|
|
3
|
+
// asked for its account picker, as the browser is usually signed in to the
|
|
4
|
+
// account the user signs in here with. The token GitHub grants reads the
|
|
5
|
+
// account's identity and avatar; it is never stored.
|
|
6
|
+
import type { AvatarStore } from './avatar-store.ts'
|
|
7
|
+
import type { ManagedConfig } from './config.ts'
|
|
8
|
+
import type { ManagedDb, ManagedSession } from './db.ts'
|
|
9
|
+
import { LINK_STATE_COOKIE, clearCookie, cookieName } from './session.ts'
|
|
10
|
+
import { OAuthError, cacheAvatar, exchangeCode, fetchIdentity, sessionAuthorization, sessionStateValid, stateCookieMatches } from './github-oauth.ts'
|
|
11
|
+
import { ManagedMutationError } from './management.ts'
|
|
12
|
+
|
|
13
|
+
export const LINK_LOGIN_PATH = '/api/oauth/github/link'
|
|
14
|
+
// The profile page, where linking starts and its callback lands.
|
|
15
|
+
const PROFILE_PATH = '/my/profile'
|
|
16
|
+
|
|
17
|
+
export function isLinkOAuthCallback(config: ManagedConfig, query: URLSearchParams, cookie: string | undefined): boolean {
|
|
18
|
+
return stateCookieMatches(config, LINK_STATE_COOKIE, query, cookie)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// The state is bound to the session that started linking, so the account
|
|
22
|
+
// links to the user who asked, never to whoever is signed in on return.
|
|
23
|
+
export function linkLoginRedirect(config: ManagedConfig, session: ManagedSession, now = Date.now()): { location: string; setCookie: string } {
|
|
24
|
+
const { url, setCookie } = sessionAuthorization(config, LINK_STATE_COOKIE, session, now)
|
|
25
|
+
url.searchParams.set('prompt', 'select_account')
|
|
26
|
+
return { location: url.href, setCookie }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Back from GitHub: link the account that authorized, then land on the
|
|
30
|
+
// profile, naming the refusal (`link-error`) when it was refused.
|
|
31
|
+
// `linked` is the login of an account linked anew.
|
|
32
|
+
export async function linkOAuthCallback(config: ManagedConfig, db: ManagedDb, session: ManagedSession,
|
|
33
|
+
query: URLSearchParams, cookie: string | undefined,
|
|
34
|
+
{ avatarStore, fetchImpl = fetch, now = Date.now() }: { avatarStore?: AvatarStore; fetchImpl?: typeof fetch; now?: number } = {},
|
|
35
|
+
): Promise<{ location: string; setCookie: string; linked: string | null }> {
|
|
36
|
+
const setCookie = clearCookie(cookieName(config, LINK_STATE_COOKIE), config.cookieSecure)
|
|
37
|
+
try {
|
|
38
|
+
if (!sessionStateValid(config, LINK_STATE_COOKIE, session, query, cookie, now)) throw new OAuthError(400, 'invalid-oauth-state')
|
|
39
|
+
const code = query.get('code')
|
|
40
|
+
// Declined on GitHub's side, which sends an error in place of a code.
|
|
41
|
+
if (!code) throw new OAuthError(400, query.get('error') ? 'github-authorization-declined' : 'invalid-oauth-state')
|
|
42
|
+
const tokens = await exchangeCode(config, code, now, fetchImpl)
|
|
43
|
+
const account = await fetchIdentity(tokens.accessToken, fetchImpl)
|
|
44
|
+
const link = await db.linkGithubAccount(session.id, account, now)
|
|
45
|
+
// Best-effort, as at sign-in: the avatar falls back to an initial.
|
|
46
|
+
if (avatarStore != null && account.avatarUrl != null) {
|
|
47
|
+
await cacheAvatar(avatarStore, link.id, account.avatarUrl, fetchImpl).catch((err) => {
|
|
48
|
+
console.warn('managed: linked avatar cache failed:', err)
|
|
49
|
+
})
|
|
50
|
+
}
|
|
51
|
+
return { location: PROFILE_PATH, setCookie, linked: link.created ? account.login : null }
|
|
52
|
+
} catch (err) {
|
|
53
|
+
if (!(err instanceof OAuthError || err instanceof ManagedMutationError)) throw err
|
|
54
|
+
return { location: `${PROFILE_PATH}?${new URLSearchParams({ 'link-error': err.message })}`, setCookie, linked: null }
|
|
55
|
+
}
|
|
56
|
+
}
|