@preventive/triage 1.0.0-alpha.4 → 1.0.0-alpha.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (311) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +17 -0
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +2 -0
  6. package/client/dependency-paths.js +24 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +112 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +3 -0
  13. package/common/bundle-compare-diff.js +522 -0
  14. package/common/bundle-compare-inputs.d.ts +2 -0
  15. package/common/bundle-compare-inputs.js +65 -0
  16. package/common/bundle-metadata.d.ts +14 -0
  17. package/common/bundle-metadata.js +226 -0
  18. package/common/bundle-pkg-of.d.ts +1 -0
  19. package/common/bundle-pkg-of.js +90 -0
  20. package/common/bundle-reasons.d.ts +2 -0
  21. package/common/bundle-reasons.js +21 -0
  22. package/common/bundle-source-links.d.ts +6 -0
  23. package/common/bundle-source-links.js +216 -0
  24. package/common/bundle-sourcemap.d.ts +10 -0
  25. package/common/bundle-sourcemap.js +100 -0
  26. package/common/bundle-sources.d.ts +7 -0
  27. package/common/bundle-sources.js +310 -0
  28. package/common/bundle-stats.js +41 -0
  29. package/common/bundle-tabs.js +1 -0
  30. package/common/code-language.js +65 -0
  31. package/common/default-scan-models.ts +31 -0
  32. package/common/dependency-reviews.d.ts +23 -0
  33. package/common/dependency-reviews.js +81 -0
  34. package/common/finding-duplicates.js +58 -0
  35. package/common/finding-filters.js +274 -0
  36. package/common/finding-id.js +47 -0
  37. package/common/github-issue-labels.d.ts +1 -0
  38. package/common/github-issue-labels.js +11 -0
  39. package/common/github-pr.ts +56 -0
  40. package/common/gzip.js +59 -0
  41. package/common/line-diff.d.ts +8 -0
  42. package/common/line-diff.js +56 -0
  43. package/common/linked-workspace-groups.js +63 -0
  44. package/common/managed/comments.ts +34 -0
  45. package/common/managed/npm-packages.d.ts +5 -0
  46. package/common/managed/npm-packages.js +34 -0
  47. package/common/managed/permissions.ts +31 -0
  48. package/common/managed/report-content.ts +72 -0
  49. package/common/managed/report-filter.ts +108 -0
  50. package/common/managed/repository-alias.ts +65 -0
  51. package/common/managed/roles.ts +28 -0
  52. package/common/managed/routes.d.ts +2 -0
  53. package/common/managed/routes.js +254 -0
  54. package/common/managed/scan-models.ts +6 -0
  55. package/common/managed/team-app.d.ts +2 -0
  56. package/common/managed/team-app.js +31 -0
  57. package/common/managed/triage.ts +83 -0
  58. package/common/managed/upload-seal.ts +126 -0
  59. package/common/pretty-print.d.ts +5 -0
  60. package/common/pretty-print.js +24 -0
  61. package/common/revalidation-conflicts.js +48 -0
  62. package/common/revalidation-input-groups.js +56 -0
  63. package/common/save-error-reason.ts +20 -7
  64. package/common/scan-server.ts +13 -0
  65. package/common/server-info.ts +35 -0
  66. package/common/utf8.d.ts +3 -0
  67. package/common/utf8.js +45 -0
  68. package/common/workspace-app.js +23 -0
  69. package/common/workspace-groups.js +176 -0
  70. package/out/brotli-fallback.js +3 -3
  71. package/out/chunk-2KBF5TZ7.js +2 -0
  72. package/out/chunk-2XUEZHIP.js +28 -0
  73. package/out/chunk-35VE6CDH.js +2 -0
  74. package/out/chunk-3BZ7JERB.js +1 -0
  75. package/out/chunk-4F6JSF57.js +3 -0
  76. package/out/chunk-4XCDFGDP.js +10 -0
  77. package/out/chunk-AQ75QITE.js +1 -0
  78. package/out/chunk-B2RQY6OP.js +2 -0
  79. package/out/chunk-C4Z6ZBXV.js +10 -0
  80. package/out/chunk-CMQA4DM6.js +1 -0
  81. package/out/chunk-CVVJAXVY.js +2 -0
  82. package/out/chunk-DIJJNTRH.js +10 -0
  83. package/out/chunk-GJ4IUCNS.js +1 -0
  84. package/out/chunk-GNXOKIGP.js +80 -0
  85. package/out/chunk-GZ4MS3TE.js +13 -0
  86. package/out/chunk-IISEF2BZ.js +1 -0
  87. package/out/chunk-IU3CCINR.js +3 -0
  88. package/out/chunk-K3X5EJBQ.js +2 -0
  89. package/out/chunk-KEX2ATEW.js +2 -0
  90. package/out/chunk-KYCNJVB7.js +1 -0
  91. package/out/chunk-MYDDTA7W.js +225 -0
  92. package/out/chunk-NRPC74AM.js +1 -0
  93. package/out/chunk-OOJM4CTU.js +1 -0
  94. package/out/chunk-PNHBZGDD.js +1 -0
  95. package/out/chunk-R5O6FAW4.js +2 -0
  96. package/out/chunk-RFZQQXSG.js +17 -0
  97. package/out/chunk-RSHMVYNS.js +1 -0
  98. package/out/chunk-TGANXVTA.js +1 -0
  99. package/out/chunk-TUII34K2.js +1 -0
  100. package/out/chunk-TZ5KB2Y5.js +10 -0
  101. package/out/chunk-UN5ZSYLE.js +1 -0
  102. package/out/chunk-UNTRGE26.js +2 -0
  103. package/out/chunk-UXNUAIIC.js +33 -0
  104. package/out/chunk-UYAXVRVL.js +1 -0
  105. package/out/chunk-V3ME6FI5.js +2 -0
  106. package/out/chunk-V5O7M2YT.js +1 -0
  107. package/out/chunk-VIHGO77Y.js +1 -0
  108. package/out/chunk-VQJCXGIY.js +7 -0
  109. package/out/chunk-W4J3MGLB.js +1 -0
  110. package/out/chunk-WGG7KQUH.js +1 -0
  111. package/out/chunk-WZDTZE64.js +1 -0
  112. package/out/chunk-XYDGU6BM.js +51 -0
  113. package/out/chunk-XYFXXB2G.js +10 -0
  114. package/out/chunk-YVZH5SHP.js +1 -0
  115. package/out/chunk-ZBBOBQ43.js +1 -0
  116. package/out/chunk-ZMQQCGF6.js +2 -0
  117. package/out/client-managed-import.js +4 -0
  118. package/out/client-managed.js +37 -0
  119. package/out/client-sync.js +10 -13
  120. package/out/github-issue-authorized.html +3 -0
  121. package/out/github-issue-authorized.js +1 -0
  122. package/out/graph.js +17 -4
  123. package/out/index.html +90 -8
  124. package/out/prism.js +6 -2
  125. package/out/stasis.svg +20 -0
  126. package/out/terminal.js +365 -39
  127. package/out/view.css +1 -1
  128. package/out/view.js +83 -117
  129. package/package.json +297 -59
  130. package/risk/files/characters.js +196 -0
  131. package/risk/files/hosts.js +205 -0
  132. package/risk/files/readability.js +171 -0
  133. package/risk/files/runs-code.js +358 -0
  134. package/risk/files/script.js +114 -0
  135. package/risk/files/stamps.js +46 -0
  136. package/risk/index.d.ts +142 -0
  137. package/risk/index.js +7 -0
  138. package/risk/npm/assess.js +219 -0
  139. package/risk/npm/combined.js +65 -0
  140. package/risk/npm/compare.js +228 -0
  141. package/risk/npm/dependencies.js +153 -0
  142. package/risk/npm/diff.js +43 -0
  143. package/risk/npm/downloads.js +84 -0
  144. package/risk/npm/files.js +34 -0
  145. package/risk/npm/held.js +60 -0
  146. package/risk/npm/install-scripts.js +34 -0
  147. package/risk/npm/malware.js +36 -0
  148. package/risk/npm/manifest.js +65 -0
  149. package/risk/npm/new-dependency.js +30 -0
  150. package/risk/npm/old-version.js +108 -0
  151. package/risk/npm/registry.js +282 -0
  152. package/risk/npm/release.js +85 -0
  153. package/risk/npm/specs.js +124 -0
  154. package/risk/npm/tarball.js +113 -0
  155. package/server-common/database-config.ts +16 -0
  156. package/server-common/initialize.ts +18 -0
  157. package/server-common/npm-advisories.ts +101 -0
  158. package/{server → server-common}/origin.ts +5 -5
  159. package/server-common/reap.ts +48 -0
  160. package/server-common/scan-config.ts +19 -0
  161. package/server-common/standalone.ts +29 -0
  162. package/server-common/storage-crypto.ts +182 -0
  163. package/server-common/storage-log.ts +38 -0
  164. package/server-common/vercel-blob.ts +103 -0
  165. package/server-e2e/app.ts +486 -0
  166. package/{server → server-e2e}/auth.ts +5 -1
  167. package/{server → server-e2e}/bus-receiver.ts +2 -1
  168. package/{server → server-e2e}/cli.js +9 -4
  169. package/{server → server-e2e}/config.ts +56 -35
  170. package/{server → server-e2e}/db-neon.ts +2 -2
  171. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  172. package/{server → server-e2e}/db-stmt.ts +2 -2
  173. package/{server → server-e2e}/db.ts +7 -7
  174. package/{server → server-e2e}/http.ts +116 -18
  175. package/{server → server-e2e}/hub.ts +40 -9
  176. package/server-e2e/index.ts +17 -0
  177. package/server-e2e/lifecycle.ts +95 -0
  178. package/{server → server-e2e}/neon-driver.ts +2 -2
  179. package/{server → server-e2e}/npm-proxy.ts +12 -145
  180. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  181. package/{server → server-e2e}/objstore/blob.ts +1 -1
  182. package/server-e2e/objstore/fetch-mint-guard.ts +74 -0
  183. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  184. package/{server → server-e2e}/objstore/init.ts +35 -18
  185. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  186. package/server-e2e/objstore/rest-deny.ts +28 -0
  187. package/server-e2e/objstore/rest-mint.ts +224 -0
  188. package/{server → server-e2e}/objstore/rest.ts +27 -26
  189. package/{server → server-e2e}/objstore/sign.ts +105 -0
  190. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  191. package/{server → server-e2e}/objstore/store.ts +7 -7
  192. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  193. package/{server → server-e2e}/pubsub.ts +12 -9
  194. package/{server → server-e2e}/sign.ts +4 -4
  195. package/{server → server-e2e}/sse-server.ts +102 -68
  196. package/{server → server-e2e}/sse-session.ts +28 -8
  197. package/{server → server-e2e}/static.ts +31 -21
  198. package/server-e2e/sync-handlers.ts +408 -0
  199. package/{server → server-e2e}/ws-server.ts +20 -9
  200. package/server-managed/activity.ts +245 -0
  201. package/server-managed/avatar-store.ts +12 -0
  202. package/server-managed/blob-store.ts +17 -0
  203. package/server-managed/brotli.ts +10 -0
  204. package/server-managed/bundle-advisories.ts +120 -0
  205. package/server-managed/bundle-advisory-inventory.ts +77 -0
  206. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  207. package/server-managed/bundle-build-diagnostics.js +23 -0
  208. package/server-managed/bundle-build-leases.ts +41 -0
  209. package/server-managed/bundle-build-worker.js +111 -0
  210. package/server-managed/bundle-build.ts +198 -0
  211. package/server-managed/bundle-cache.ts +199 -0
  212. package/server-managed/bundle-catalog.ts +29 -0
  213. package/server-managed/bundle-commits.ts +140 -0
  214. package/server-managed/bundle-store.ts +24 -0
  215. package/server-managed/bundle-summary-cache.ts +130 -0
  216. package/server-managed/bundle.ts +120 -0
  217. package/server-managed/cache-storage.ts +19 -0
  218. package/server-managed/cli.js +21 -0
  219. package/server-managed/combined.ts +46 -0
  220. package/server-managed/comments.ts +151 -0
  221. package/server-managed/config.ts +158 -0
  222. package/server-managed/content-access.ts +15 -0
  223. package/server-managed/crypto.ts +25 -0
  224. package/server-managed/db-methods.ts +1725 -0
  225. package/server-managed/db-neon.ts +367 -0
  226. package/server-managed/db-schema.ts +227 -0
  227. package/server-managed/db-table-names.ts +22 -0
  228. package/server-managed/db.ts +132 -0
  229. package/server-managed/dependency-reviews.ts +248 -0
  230. package/server-managed/github-app.ts +391 -0
  231. package/server-managed/github-errors.ts +68 -0
  232. package/server-managed/github-issue-links.ts +127 -0
  233. package/server-managed/github-issue-oauth.ts +47 -0
  234. package/server-managed/github-issues.ts +152 -0
  235. package/server-managed/github-metadata.ts +213 -0
  236. package/server-managed/github-oauth.ts +235 -0
  237. package/server-managed/github-pulls.ts +227 -0
  238. package/server-managed/http-response.ts +50 -0
  239. package/server-managed/http.ts +3472 -0
  240. package/server-managed/import-triage.ts +51 -0
  241. package/server-managed/index.ts +187 -0
  242. package/server-managed/kept.ts +28 -0
  243. package/server-managed/link-reports.ts +158 -0
  244. package/server-managed/locked-packages.ts +85 -0
  245. package/server-managed/lru.ts +30 -0
  246. package/server-managed/managed-issues.ts +75 -0
  247. package/server-managed/management-catalog.ts +45 -0
  248. package/server-managed/management.ts +99 -0
  249. package/server-managed/npm-insights.ts +440 -0
  250. package/server-managed/npm-kept.ts +65 -0
  251. package/server-managed/npm-loads.ts +167 -0
  252. package/server-managed/npm-manifest.ts +115 -0
  253. package/server-managed/npm-packages.ts +378 -0
  254. package/server-managed/npm-provenance.ts +123 -0
  255. package/server-managed/npm-risk.ts +177 -0
  256. package/server-managed/object-storage-disk.ts +148 -0
  257. package/server-managed/object-storage-vercel.ts +67 -0
  258. package/server-managed/object-storage.ts +74 -0
  259. package/server-managed/package-entry-points.ts +51 -0
  260. package/server-managed/pretty-print.ts +352 -0
  261. package/server-managed/public-workspace.ts +220 -0
  262. package/server-managed/rename-diff-worker.js +26 -0
  263. package/server-managed/rename-diff.ts +270 -0
  264. package/server-managed/repo-path.ts +21 -0
  265. package/server-managed/report-migration.ts +35 -0
  266. package/server-managed/report-query.ts +10 -0
  267. package/server-managed/report-response.ts +16 -0
  268. package/server-managed/report-sources.ts +178 -0
  269. package/server-managed/report-store.ts +47 -0
  270. package/server-managed/repository-aliases.ts +91 -0
  271. package/server-managed/repository-browser.ts +153 -0
  272. package/server-managed/repository-discovery.ts +82 -0
  273. package/server-managed/repository-policy.ts +27 -0
  274. package/server-managed/repository-risk.ts +418 -0
  275. package/server-managed/revisions.ts +35 -0
  276. package/server-managed/session.ts +92 -0
  277. package/server-managed/slugs.ts +38 -0
  278. package/server-managed/solidity-entry-points.ts +69 -0
  279. package/server-managed/sql-postgres.ts +31 -0
  280. package/server-managed/sql.ts +76 -0
  281. package/server-managed/static.ts +28 -0
  282. package/server-managed/storage-command.ts +16 -0
  283. package/server-managed/storage-db.ts +175 -0
  284. package/server-managed/storage-encryption.ts +279 -0
  285. package/server-managed/storage-maintenance.ts +256 -0
  286. package/server-managed/storage-payload.ts +103 -0
  287. package/server-managed/storage-stores.ts +85 -0
  288. package/server-managed/storage.ts +78 -0
  289. package/server-managed/team-app.ts +94 -0
  290. package/server-managed/team-catalog.ts +7 -0
  291. package/server-managed/team-feed.ts +173 -0
  292. package/server-managed/team-npm-scopes.ts +77 -0
  293. package/server-managed/team-reports.ts +228 -0
  294. package/server-managed/triage-response.ts +16 -0
  295. package/server-managed/type-only-worker.js +19 -0
  296. package/server-managed/type-only.ts +103 -0
  297. package/server-managed/uploads.ts +86 -0
  298. package/server-managed/upstream-cache.ts +215 -0
  299. package/server-managed/view-as.ts +58 -0
  300. package/server-managed/workspace-shares.ts +166 -0
  301. package/server.ts +50 -0
  302. package/server/index.ts +0 -477
  303. package/server/lifecycle.ts +0 -204
  304. package/server/sync-handlers.ts +0 -320
  305. /package/{LICENSE → LICENSE-MIT} +0 -0
  306. /package/{server → server-e2e}/config.example.json +0 -0
  307. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  308. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  309. /package/{server → server-e2e}/peer.ts +0 -0
  310. /package/{server → server-e2e}/util.ts +0 -0
  311. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,391 @@
1
+ // Repository discovery uses the signed-in user token and App installation
2
+ // tokens. Login and repository installation can use one GitHub App: user
3
+ // authorization requests account permissions, installation grants repository
4
+ // permissions. Discovery itself is read-only and skips archived repositories.
5
+ import { Buffer } from 'node:buffer'
6
+ import { createHash, createSign } from 'node:crypto'
7
+ import { createClient } from '@preventive/upstream/github.js'
8
+ import type { ManagedConfig } from './config.ts'
9
+ import { GithubApiError, githubUnreachable, throwGithubResponseError, upstreamGithub } from './github-errors.ts'
10
+
11
+ export { GithubApiError } from './github-errors.ts'
12
+
13
+ const GITHUB_API = 'https://api.github.com'
14
+ const API_VERSION = '2022-11-28'
15
+ const USER_AGENT = 'deepview-triage'
16
+ const PER_PAGE = 100
17
+ const INSTALLATION_TOKEN_TTL_MS = 5 * 60_000
18
+ const INSTALLATION_TOKEN_EXPIRY_MARGIN_MS = 60_000
19
+ const MAX_INSTALLATION_TOKENS = 256
20
+ interface InstallationTokenEntry { token: string | null; expiresAt: number; pending: Promise<string> | null }
21
+ // Credentials only: visibility, user identities, and permissions are never
22
+ // cached here. Bound memory per transport and separate App/key/install scopes.
23
+ const installationTokens = new WeakMap<typeof fetch, Map<string, InstallationTokenEntry>>()
24
+
25
+ function discardInstallationToken(token: string | null, fetchImpl: typeof fetch): void {
26
+ if (!token) return
27
+ const cache = installationTokens.get(fetchImpl)
28
+ if (!cache) return
29
+ for (const [key, entry] of cache) if (entry.token === token) cache.delete(key)
30
+ }
31
+
32
+ // One listed repository. Carries the context to read its contents later:
33
+ // `installationId` mints an App installation token (Contents: Read) for a repo
34
+ // reached through an installation — null for a public repo listed off the user
35
+ // token, readable without the App — and `defaultBranch` is the ref to read.
36
+ export interface ConnectedRepo {
37
+ id: number
38
+ fullName: string
39
+ private: boolean
40
+ visibility: 'public' | 'private' | 'internal' | null
41
+ htmlUrl: string
42
+ defaultBranch: string
43
+ installationId: number | null
44
+ }
45
+
46
+ // App installation credentials are configured (id + private key present) →
47
+ // private repos can be listed via its installation tokens.
48
+ export function githubAppConfigured(config: ManagedConfig): boolean {
49
+ return config.githubAppId != null && config.githubAppPrivateKey != null
50
+ }
51
+
52
+ // The install URL for the repositories App ("Connect a repository"), or null
53
+ // when no slug is set.
54
+ export function installUrl(config: ManagedConfig): string | null {
55
+ if (config.githubAppSlug == null) return null
56
+ return `https://github.com/apps/${encodeURIComponent(config.githubAppSlug)}/installations/new`
57
+ }
58
+
59
+ // Merge repo lists from every source, deduped by full name and sorted. Later
60
+ // sources win a collision (the handler lists private after public).
61
+ export function mergeRepos(...lists: ConnectedRepo[][]): ConnectedRepo[] {
62
+ const byName = new Map<string, ConnectedRepo>()
63
+ for (const list of lists) {
64
+ for (const repo of list) byName.set(repo.fullName, repo)
65
+ }
66
+ return [...byName.values()].toSorted((a, b) => a.fullName.localeCompare(b.fullName))
67
+ }
68
+
69
+ // One GitHub API call returning parsed JSON, optionally Bearer-authed by a
70
+ // user token, App JWT, or installation token. Network / non-2xx / malformed
71
+ // fold into a GithubApiError (401 passes through for the caller to handle).
72
+ export async function githubJson(url: string, token: string | null, fetchImpl: typeof fetch, method: 'GET' | 'POST' = 'GET'): Promise<unknown> {
73
+ let res: Response
74
+ const started = Date.now()
75
+ try {
76
+ res = await fetchImpl(url, {
77
+ method,
78
+ signal: AbortSignal.timeout(10_000),
79
+ redirect: 'error',
80
+ headers: {
81
+ ...(token == null ? {} : { authorization: `Bearer ${token}` }), 'accept': 'application/vnd.github+json',
82
+ 'user-agent': USER_AGENT, 'x-github-api-version': API_VERSION,
83
+ },
84
+ })
85
+ } catch (error) { throw githubUnreachable(error, started) }
86
+ if (res.status === 401) discardInstallationToken(token, fetchImpl)
87
+ if (!res.ok) await throwGithubResponseError(res)
88
+ // The answer's body is read within the same timeout: one not read whole is
89
+ // GitHub not reached, as one not answered is; only one that isn't JSON is
90
+ // malformed.
91
+ try { return await res.json() } catch (error) {
92
+ throw error instanceof SyntaxError ? new GithubApiError(502, 'github-malformed') : githubUnreachable(error, started)
93
+ }
94
+ }
95
+
96
+ // Validate one repo object into a ConnectedRepo (or null to skip), tagging it
97
+ // with the installation it was reached through (null for the user-token path). A
98
+ // missing numeric id or full name → skip (can't key/locate it). Archived repos
99
+ // are skipped — read-only history, not triage targets.
100
+ function parseRepo(raw: unknown, installationId: number | null): ConnectedRepo | null {
101
+ if (raw == null || typeof raw !== 'object') return null
102
+ if ((raw as { archived?: unknown }).archived === true) return null
103
+ const id = (raw as { id?: unknown }).id
104
+ const fullName = (raw as { full_name?: unknown }).full_name
105
+ if (typeof id !== 'number' || !Number.isSafeInteger(id) || id <= 0) return null
106
+ if (typeof fullName !== 'string' || fullName === '') return null
107
+ const htmlUrl = (raw as { html_url?: unknown }).html_url
108
+ const branch = (raw as { default_branch?: unknown }).default_branch
109
+ const visibility = (raw as { visibility?: unknown }).visibility
110
+ return {
111
+ id,
112
+ fullName,
113
+ private: (raw as { private?: unknown }).private === true,
114
+ visibility: visibility === 'public' || visibility === 'private' || visibility === 'internal' ? visibility : null,
115
+ htmlUrl: typeof htmlUrl === 'string' ? htmlUrl : '',
116
+ defaultBranch: typeof branch === 'string' ? branch : '',
117
+ installationId,
118
+ }
119
+ }
120
+
121
+ // Accept an owner/repo or exact GitHub repository URL, never an arbitrary API
122
+ // path. Reject traversal and encoded separators before constructing a fixed URL.
123
+ export function publicRepositoryName(raw: unknown): string | null {
124
+ if (typeof raw !== 'string') return null
125
+ const name = raw.trim().replace(/^https:\/\/github\.com\//iu, '').replace(/\/$/u, '')
126
+ if (!/^[a-z\d](?:[a-z\d-]{0,38})\/[a-z\d_.-]{1,100}$/iu.test(name)) return null
127
+ if (['.', '..'].includes(name.split('/')[1]!)) return null
128
+ return name
129
+ }
130
+
131
+ // Public additions must be readable by the server without the acting user's
132
+ // credentials. Require explicit public visibility and use GitHub's canonical
133
+ // metadata, never client-supplied ids, installation ids, or branches.
134
+ export async function fetchPublicRepository(fullName: string): Promise<ConnectedRepo> {
135
+ if (publicRepositoryName(fullName) !== fullName) throw new GithubApiError(400, 'bad-repository')
136
+ const repo = parseRepo(await upstreamGithub(() => createClient({ token: null, userAgent: USER_AGENT }).getRepo({ repo: fullName })), null)
137
+ if (repo == null || repo.private || repo.visibility !== 'public') throw new GithubApiError(409, 'repo-not-public')
138
+ if (publicRepositoryName(repo.fullName) !== repo.fullName || repo.fullName.toLowerCase() !== fullName.toLowerCase()) throw new GithubApiError(502, 'github-malformed')
139
+ return { ...repo, htmlUrl: `https://github.com/${repo.fullName}` }
140
+ }
141
+
142
+ // ── PUBLIC: the user's own repos via their login token ──
143
+
144
+ // List the authenticated user's repositories (GET /user/repos), paginated until
145
+ // a short page, deduped + sorted. With an identity-only token this returns the
146
+ // user's PUBLIC repos. READ-ONLY.
147
+ export async function listUserRepos(accessToken: string): Promise<ConnectedRepo[]> {
148
+ const byName = new Map<string, ConnectedRepo>()
149
+ const body = await upstreamGithub(() => createClient({ token: accessToken, userAgent: USER_AGENT }).listUserRepos())
150
+ for (const r of body) {
151
+ const repo = parseRepo(r, null)
152
+ if (repo != null) byName.set(repo.fullName, repo)
153
+ }
154
+ return [...byName.values()].toSorted((a, b) => a.fullName.localeCompare(b.fullName))
155
+ }
156
+
157
+ // ── PRIVATE: App installations via installation tokens ──
158
+
159
+ function base64url(input: Buffer | string): string {
160
+ return Buffer.from(input).toString('base64url')
161
+ }
162
+
163
+ // Mint a short-lived App JWT (RS256) for the repositories App. iat backdated 60s
164
+ // for clock skew; exp 8 min out (within GitHub's 10-min cap); iss = the App id.
165
+ export function appJwt(appId: string, privateKeyPem: string, now: number = Date.now()): string {
166
+ const seconds = Math.floor(now / 1000)
167
+ const iat = seconds - 60
168
+ const header = base64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }))
169
+ const payload = base64url(JSON.stringify({ iat, exp: seconds + 480, iss: appId }))
170
+ const signingInput = `${header}.${payload}`
171
+ return `${signingInput}.${base64url(createSign('RSA-SHA256').update(signingInput).sign(privateKeyPem))}`
172
+ }
173
+
174
+ // The repositories App's installation ids (one per org/user that installed it).
175
+ async function listInstallationIds(jwt: string, fetchImpl: typeof fetch): Promise<number[]> {
176
+ const ids: number[] = []
177
+ for (let page = 1; ; page++) {
178
+ const body = await githubJson(`${GITHUB_API}/app/installations?per_page=${PER_PAGE}&page=${page}`, jwt, fetchImpl)
179
+ if (!Array.isArray(body)) throw new GithubApiError(502, 'github-malformed')
180
+ for (const inst of body) {
181
+ const id = (inst as { id?: unknown }).id
182
+ if (typeof id === 'number' && Number.isSafeInteger(id) && id > 0) ids.push(id)
183
+ }
184
+ if (body.length < PER_PAGE) break
185
+ }
186
+ return ids
187
+ }
188
+
189
+ // Reuse installation credentials only in this process. Refresh well before
190
+ // expiry and coalesce concurrent mints; failed or undated tokens are not cached.
191
+ async function installationAccessToken(appId: string, privateKey: string, installId: number, fetchImpl: typeof fetch): Promise<string> {
192
+ let cache = installationTokens.get(fetchImpl)
193
+ if (!cache) { cache = new Map(); installationTokens.set(fetchImpl, cache) }
194
+ const now = Date.now()
195
+ for (const [key, entry] of cache) if (!entry.pending && entry.expiresAt <= now) cache.delete(key)
196
+ const key = JSON.stringify([appId, createHash('sha256').update(privateKey).digest('hex'), installId])
197
+ const cached = cache.get(key)
198
+ if (cached) {
199
+ cache.delete(key)
200
+ cache.set(key, cached)
201
+ if (cached.pending) return cached.pending
202
+ return cached.token!
203
+ }
204
+ const entry: InstallationTokenEntry = { token: null, expiresAt: 0, pending: null }
205
+ const pending = Promise.resolve().then(async () => {
206
+ try {
207
+ const jwt = appJwt(appId, privateKey)
208
+ const body = await githubJson(`${GITHUB_API}/app/installations/${installId}/access_tokens`, jwt, fetchImpl, 'POST') as { token?: unknown; expires_at?: unknown }
209
+ if (typeof body?.token !== 'string' || body.token === '') throw new GithubApiError(502, 'github-install-token-denied')
210
+ entry.token = body.token
211
+ const expiresAt = typeof body.expires_at === 'string' ? Date.parse(body.expires_at) : NaN
212
+ entry.expiresAt = Number.isFinite(expiresAt) ? Math.min(now + INSTALLATION_TOKEN_TTL_MS, expiresAt - INSTALLATION_TOKEN_EXPIRY_MARGIN_MS) : 0
213
+ if (entry.expiresAt <= Date.now() && cache.get(key) === entry) cache.delete(key)
214
+ return body.token
215
+ } catch (err) {
216
+ if (cache.get(key) === entry) cache.delete(key)
217
+ throw err
218
+ } finally { entry.pending = null }
219
+ })
220
+ entry.pending = pending
221
+ cache.set(key, entry)
222
+ if (cache.size > MAX_INSTALLATION_TOKENS) cache.delete(cache.keys().next().value!)
223
+ return await pending
224
+ }
225
+
226
+ // Resolve this exact repository with the App's identity, then confirm the
227
+ // installation token reaches the same numeric repository. A missing grant is
228
+ // actionable through installation; transport/auth/rate errors must stay errors.
229
+ export async function repositoryInstallation(config: ManagedConfig, repoId: number, fullName: string, fetchImpl: typeof fetch = globalThis.fetch): Promise<number | null> {
230
+ const { githubAppId, githubAppPrivateKey } = config
231
+ if (githubAppId == null || githubAppPrivateKey == null) throw new GithubApiError(503, 'github-app-not-configured')
232
+ if (publicRepositoryName(fullName) !== fullName) throw new GithubApiError(409, 'repo-identity-changed')
233
+ const path = fullName.split('/').map(encodeURIComponent).join('/')
234
+ const jwt = appJwt(githubAppId, githubAppPrivateKey)
235
+ let raw
236
+ try { raw = await githubJson(`${GITHUB_API}/repos/${path}/installation`, jwt, fetchImpl) } catch (err) {
237
+ if (err instanceof GithubApiError && err.status === 404) return null
238
+ throw err
239
+ }
240
+ const installation = raw as { id?: unknown; suspended_at?: unknown; permissions?: { contents?: unknown } } | null
241
+ const id = installation?.id
242
+ if (typeof id !== 'number' || !Number.isSafeInteger(id) || id <= 0) throw new GithubApiError(502, 'github-malformed')
243
+ if (installation?.suspended_at != null || !['read', 'write'].includes(String(installation?.permissions?.contents))) return null
244
+ const token = await installationAccessToken(githubAppId, githubAppPrivateKey, id, fetchImpl)
245
+ const repo = parseRepo(await githubJson(`${GITHUB_API}/repos/${path}`, token, fetchImpl), id)
246
+ if (repo == null || repo.id !== repoId || repo.fullName.toLowerCase() !== fullName.toLowerCase()) throw new GithubApiError(409, 'repo-identity-changed')
247
+ return id
248
+ }
249
+
250
+ // The `repositories` array of one /installation/repositories page → ConnectedRepo[],
251
+ // each tagged with the installation id that can read it.
252
+ function repoPage(body: unknown, installationId: number): ConnectedRepo[] {
253
+ const repositories = (body as { repositories?: unknown }).repositories
254
+ if (!Array.isArray(repositories)) return []
255
+ const out: ConnectedRepo[] = []
256
+ for (const r of repositories) {
257
+ const repo = parseRepo(r, installationId)
258
+ if (repo != null) out.push(repo)
259
+ }
260
+ return out
261
+ }
262
+
263
+ // Every repository one installation can read, paginated by the page count from
264
+ // `total_count` (avoids Link-header parsing).
265
+ async function listInstallationRepos(token: string, installationId: number, fetchImpl: typeof fetch): Promise<ConnectedRepo[]> {
266
+ const pageUrl = (page: number): string => `${GITHUB_API}/installation/repositories?per_page=${PER_PAGE}&page=${page}`
267
+ const first = await githubJson(pageUrl(1), token, fetchImpl) as { total_count?: unknown }
268
+ const repos = repoPage(first, installationId)
269
+ const total = typeof first.total_count === 'number' ? first.total_count : repos.length
270
+ const pages = Math.ceil(total / PER_PAGE)
271
+ for (let page = 2; page <= pages; page++) {
272
+ repos.push(...repoPage(await githubJson(pageUrl(page), token, fetchImpl), installationId))
273
+ }
274
+ return repos
275
+ }
276
+
277
+ // List every repo the repositories App is installed on, across installations
278
+ // (public + PRIVATE within those installs), deduped + sorted. Empty when the App
279
+ // isn't configured. READ-ONLY.
280
+ export async function listInstalledRepos(config: ManagedConfig, fetchImpl: typeof fetch = globalThis.fetch): Promise<ConnectedRepo[]> {
281
+ const { githubAppId, githubAppPrivateKey } = config
282
+ if (githubAppId == null || githubAppPrivateKey == null) return []
283
+ const jwt = appJwt(githubAppId, githubAppPrivateKey)
284
+ const lists = await mapGithubRequests(await listInstallationIds(jwt, fetchImpl), async (id) => {
285
+ const token = await installationAccessToken(githubAppId, githubAppPrivateKey, id, fetchImpl)
286
+ return listInstallationRepos(token, id, fetchImpl)
287
+ })
288
+ return mergeRepos(...lists)
289
+ }
290
+
291
+ // Bound fan-out while keeping independent installations/permission checks off
292
+ // one long serial critical path. Preserve input order for deterministic merges.
293
+ async function mapGithubRequests<T, U>(items: T[], work: (item: T) => Promise<U>): Promise<U[]> {
294
+ const results: U[] = []
295
+ let next = 0
296
+ await Promise.all(Array.from({ length: Math.min(4, items.length) }, async () => {
297
+ while (next < items.length) {
298
+ const index = next++
299
+ results[index] = await work(items[index]!)
300
+ }
301
+ }))
302
+ return results
303
+ }
304
+
305
+ // The login App and repository App are separate: /user/repos with the login
306
+ // token is not evidence of private-repo access. Ask the repository App for the
307
+ // user's effective GitHub permission (including teams/org/enterprise grants).
308
+ // This endpoint accepts installation tokens with Metadata: read; it does NOT
309
+ // require Administration permission (unlike collaborator mutation endpoints).
310
+ // https://docs.github.com/en/rest/collaborators/collaborators#get-repository-permissions-for-a-user
311
+ // Resolve the current login from /user so renamed handles cannot check someone
312
+ // else's access. All repo paths come from GitHub's installation catalogue.
313
+ export async function githubUserIdentity(userToken: string, fetchImpl: typeof fetch = globalThis.fetch): Promise<{ id: number; login: string }> {
314
+ const identity = await githubJson(`${GITHUB_API}/user`, userToken, fetchImpl) as { id?: unknown; login?: unknown }
315
+ if (typeof identity?.login !== 'string' || !identity.login || typeof identity.id !== 'number' || !Number.isSafeInteger(identity.id) || identity.id <= 0) throw new GithubApiError(502, 'github-malformed')
316
+ return { id: identity.id, login: identity.login }
317
+ }
318
+
319
+ export async function githubRepoReadPermission(fullName: string, token: string, identity: { id: number; login: string }, fetchImpl: typeof fetch = globalThis.fetch): Promise<boolean> {
320
+ const path = fullName.split('/').map(encodeURIComponent).join('/')
321
+ try {
322
+ const body = await githubJson(`${GITHUB_API}/repos/${path}/collaborators/${encodeURIComponent(identity.login)}/permission`, token, fetchImpl) as { permission?: unknown; user?: { id?: unknown } }
323
+ return body?.user?.id === identity.id && ['read', 'write', 'admin'].includes(String(body?.permission))
324
+ } catch (err) {
325
+ if (err instanceof GithubApiError && err.status === 404) return false
326
+ throw err // Never broaden access when GitHub cannot verify permission.
327
+ }
328
+ }
329
+
330
+ export async function filterInstalledRepos(config: ManagedConfig, repositories: ConnectedRepo[], userToken: string, fetchImpl: typeof fetch = globalThis.fetch): Promise<ConnectedRepo[]> {
331
+ const identity = await githubUserIdentity(userToken, fetchImpl)
332
+ const tokens = new Map<number, Promise<string | null>>()
333
+ const allowed = await mapGithubRequests(repositories, async (repo) => {
334
+ // Internal repos may have private=false; missing visibility is not proof
335
+ // of public access either. Only explicitly public repositories skip checks.
336
+ if (repo.visibility === 'public') return true
337
+ if (repo.installationId == null) return false
338
+ let token = tokens.get(repo.installationId)
339
+ if (!token) {
340
+ token = repoAccessToken(config, repo.installationId, fetchImpl)
341
+ tokens.set(repo.installationId, token)
342
+ }
343
+ const accessToken = await token
344
+ if (!accessToken) return false
345
+ return githubRepoReadPermission(repo.fullName, accessToken, identity, fetchImpl)
346
+ })
347
+ return repositories.filter((_, index) => allowed[index])
348
+ }
349
+
350
+ // Get a token to READ a selected repo's contents: an installation token (the
351
+ // App's Contents: Read) when the repo was reached through an installation, or
352
+ // null for a public repo readable unauthenticated. This is the whole point of
353
+ // persisting `installationId` — the stored context is enough to read.
354
+ export async function repoAccessToken(config: ManagedConfig, installationId: number | null, fetchImpl: typeof fetch = globalThis.fetch): Promise<string | null> {
355
+ const { githubAppId, githubAppPrivateKey } = config
356
+ if (installationId == null || githubAppId == null || githubAppPrivateKey == null) return null
357
+ return await installationAccessToken(githubAppId, githubAppPrivateKey, installationId, fetchImpl)
358
+ }
359
+
360
+ // ── merged listing ──
361
+
362
+ export interface RepoListing {
363
+ repositories: ConnectedRepo[]
364
+ tokenMissing: boolean
365
+ }
366
+
367
+ // Every repo a user can reach, merged (deduped + sorted): PUBLIC via their login
368
+ // token + PRIVATE via the App's installations. Each source is best-effort so one
369
+ // failing never blanks the other; `tokenMissing` flags a missing/stale user
370
+ // token (→ the page prompts re-login). A repo seen on both sides keeps the
371
+ // installation tag (private listed last → wins the merge).
372
+ export async function collectRepos(config: ManagedConfig, userToken: string | null, fetchImpl: typeof fetch = globalThis.fetch): Promise<RepoListing> {
373
+ let tokenMissing = userToken == null
374
+ const lists: ConnectedRepo[][] = []
375
+ if (userToken != null) {
376
+ try {
377
+ lists.push(await listUserRepos(userToken))
378
+ } catch (err) {
379
+ if (err instanceof GithubApiError && err.status === 401) tokenMissing = true
380
+ else console.warn('managed: public repo list failed:', err)
381
+ }
382
+ }
383
+ if (githubAppConfigured(config)) {
384
+ try {
385
+ lists.push(await listInstalledRepos(config, fetchImpl))
386
+ } catch (err) {
387
+ console.warn('managed: private repo list failed:', err)
388
+ }
389
+ }
390
+ return { repositories: mergeRepos(...lists), tokenMissing }
391
+ }
@@ -0,0 +1,68 @@
1
+ import { HttpError } from '@preventive/upstream/github.js'
2
+
3
+ // A failure carrying the HTTP status the router should surface. 401 passes
4
+ // through so the user-token path can map it to "log in again".
5
+ export class GithubApiError extends Error {
6
+ status: number
7
+ retryAfter: number | null
8
+ // What failed, where GitHub wasn't reached (githubUnreachable).
9
+ detail: string | null
10
+ constructor(status: number, message: string, retryAfter: number | null = null, detail: string | null = null) {
11
+ super(message)
12
+ this.name = 'GithubApiError'
13
+ this.status = status
14
+ this.retryAfter = retryAfter
15
+ this.detail = detail
16
+ }
17
+ }
18
+
19
+ // GitHub not reached, or its answer not read whole, `started` ms since the
20
+ // epoch: as `github-unreachable`, with what failed as the error and its causes
21
+ // tell it (a timeout, a connection closed, an answer too large) and after how
22
+ // long, for an admin's page to show (repository-risk.ts). Only the errors'
23
+ // names, codes and messages, never GitHub's text nor a request's headers.
24
+ export function githubUnreachable(error: unknown, started: number): GithubApiError {
25
+ const told: string[] = []
26
+ for (let at = error, depth = 0; at instanceof Error && depth < 4; at = at.cause, depth++) {
27
+ const code = 'code' in at && typeof at.code === 'string' && at.code !== at.name ? ` ${at.code}` : ''
28
+ told.push(`${at.name}${code}${at.message ? `: ${at.message.slice(0, 200)}` : ''}`)
29
+ }
30
+ const failed = told.length > 0 ? told.join('; ') : String(error).slice(0, 200)
31
+ return new GithubApiError(502, 'github-unreachable', null, `${failed}, after ${((Date.now() - started) / 1000).toFixed(1)}s`)
32
+ }
33
+
34
+ export async function throwGithubResponseError(res: Response): Promise<never> {
35
+ if (res.status === 403 || res.status === 429) {
36
+ const body = await res.json().catch(() => null) as { message?: unknown } | null
37
+ if (res.status === 429 || res.headers.get('x-ratelimit-remaining') === '0' || res.headers.has('retry-after')
38
+ || (typeof body?.message === 'string' && /rate limit|abuse detection/iu.test(body.message))) {
39
+ const retry = Number(res.headers.get('retry-after'))
40
+ const reset = Number(res.headers.get('x-ratelimit-reset')) * 1000
41
+ const wait = Math.max(Number.isFinite(retry) ? retry : 0, Number.isFinite(reset) ? (reset - Date.now()) / 1000 : 0)
42
+ throw new GithubApiError(429, 'github-rate-limited', Math.max(60, Math.ceil(wait)))
43
+ }
44
+ }
45
+ if (res.status === 401) throw new GithubApiError(401, 'github-unauthorized')
46
+ if (res.status === 404) throw new GithubApiError(404, 'github-not-found')
47
+ throw new GithubApiError(502, `github-status-${res.status}`)
48
+ }
49
+
50
+ export async function upstreamGithub<T>(request: () => Promise<T>): Promise<T> {
51
+ const started = Date.now()
52
+ try { return await request() } catch (error) {
53
+ if (error instanceof HttpError) {
54
+ // The upstream error includes GitHub's response text. Retain managed
55
+ // status handling, including rate limits, without exposing that text.
56
+ if (error.status === 401) throw new GithubApiError(401, 'github-unauthorized')
57
+ if (error.status === 404) throw new GithubApiError(404, 'github-not-found')
58
+ if (error.status === 429 || (error.status === 403 && /rate limit|abuse detection/iu.test(error.message))) {
59
+ throw new GithubApiError(429, 'github-rate-limited', 60)
60
+ }
61
+ throw new GithubApiError(502, `github-status-${error.status}`)
62
+ }
63
+ if (error instanceof Error && (error.name === 'AssertionError' || error.cause instanceof SyntaxError)) {
64
+ throw new GithubApiError(502, 'github-malformed')
65
+ }
66
+ throw githubUnreachable(error, started)
67
+ }
68
+ }
@@ -0,0 +1,127 @@
1
+ import { type GithubFixResult, githubIssueClosedReason, isGithubRepoName, parseGithubFixUrl } from '../common/github-pr.ts'
2
+ import type { ManagedConfig } from './config.ts'
3
+ import type { ManagedDb, TeamReportAccessSnapshot } from './db.ts'
4
+ import type { ManagedIssue } from './managed-issues.ts'
5
+ import { ensureUserAccessToken } from './github-oauth.ts'
6
+ import { lookupFixes } from './github-pulls.ts'
7
+
8
+ export type IssueFixUpdate = { findingId: string; issueUrl: string; previous: string | null; next: string | null; checkedAt: number }
9
+ type Pull = { number: number; title: string; body: string | null; state: string; isDraft: boolean; createdAt: string;
10
+ repository: { databaseId: number; nameWithOwner: string } }
11
+ type Connection = { nodes: Pull[]; pageInfo: { hasNextPage: boolean; endCursor: string | null } }
12
+ type Issue = { number: number; title: string; body: string | null; state: string; stateReason: string | null; closedByPullRequestsReferences?: Connection }
13
+ type Repository = TeamReportAccessSnapshot['repositories'][number]
14
+ type Job = { repo: Repository; kind: 'pull' | 'issue'; number: number; aliases: string[];
15
+ linked: boolean; cursor: string | null; pulls: Pull[]; complete: boolean }
16
+ type Metadata = Exclude<GithubFixResult, { error: string }>
17
+ const pullFields = 'number title body state isDraft createdAt repository { databaseId nameWithOwner }'
18
+
19
+ function metadataQuery(jobs: Job[]) {
20
+ return `{ ${jobs.map((job, index) => {
21
+ const [owner, name] = job.repo.github.split('/')
22
+ const fields = job.kind === 'pull' ? pullFields : `number title body state stateReason ${job.linked
23
+ ? `closedByPullRequestsReferences(first: 100, includeClosedPrs: true, after: ${JSON.stringify(job.cursor)}) { nodes { ${pullFields} } pageInfo { hasNextPage endCursor } }` : ''}`
24
+ return `r${index}: repository(owner: ${JSON.stringify(owner)}, name: ${JSON.stringify(name)}) { databaseId nameWithOwner item: ${job.kind === 'pull' ? 'pullRequest' : 'issue'}(number: ${job.number}) { ${fields} } }`
25
+ }).join('\n')} }`
26
+ }
27
+
28
+ function itemMetadata(item: Issue | Pull, kind: Job['kind']): Omit<Metadata, 'url'> | null {
29
+ if (!item || typeof item.title !== 'string' || !item.title.trim() || item.title.length > 1024
30
+ || item.body != null && typeof item.body !== 'string' || !['OPEN', 'CLOSED', ...(kind === 'pull' ? ['MERGED'] : [])].includes(item.state)) return null
31
+ const status = item.state === 'MERGED' ? 'merged' : item.state === 'CLOSED' ? 'closed' : 'isDraft' in item && item.isDraft === true ? 'draft' : 'open'
32
+ const stateReason = kind === 'issue' && status === 'closed' ? githubIssueClosedReason(String((item as Issue).stateReason).toLowerCase()) : null
33
+ return { title: item.title, description: item.body ?? null, status, stateReason }
34
+ }
35
+
36
+ function readPage(job: Job, item: Issue | Pull, metadata: Map<string, Metadata>): boolean {
37
+ const details = itemMetadata(item, job.kind)
38
+ if (!details || item.number !== job.number) return false
39
+ for (const url of job.aliases) metadata.set(url, { url, ...details })
40
+ if (!job.linked) return false
41
+ const connection = (item as Issue).closedByPullRequestsReferences
42
+ if (!connection || !Array.isArray(connection.nodes) || typeof connection.pageInfo?.hasNextPage !== 'boolean'
43
+ || connection.nodes.some(pr => !pr || !Number.isSafeInteger(pr.number) || pr.number <= 0 || typeof pr.createdAt !== 'string'
44
+ || !Number.isFinite(Date.parse(pr.createdAt)) || !itemMetadata(pr, 'pull') || typeof pr.isDraft !== 'boolean'
45
+ || !Number.isSafeInteger(pr.repository?.databaseId) || typeof pr.repository?.nameWithOwner !== 'string' || !isGithubRepoName(pr.repository.nameWithOwner))) return false
46
+ job.pulls.push(...connection.nodes)
47
+ if (!connection.pageInfo.hasNextPage) { job.complete = true; return false }
48
+ if (typeof connection.pageInfo.endCursor !== 'string' || !connection.pageInfo.endCursor || connection.pageInfo.endCursor === job.cursor) return false
49
+ job.cursor = connection.pageInfo.endCursor
50
+ return true
51
+ }
52
+
53
+ function issueUpdates(jobs: Job[], issues: ManagedIssue[], allowed: Map<string, Repository>, checkedAt: number, metadata: Map<string, Metadata>) {
54
+ const updates: IssueFixUpdate[] = []
55
+ for (const job of jobs) {
56
+ if (!job.linked || !job.complete) continue
57
+ // "Last" means the newest PR by creation time, never its latest comment.
58
+ const latest = job.pulls.filter(pr => pr.state !== 'CLOSED').toSorted((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt) || b.number - a.number)[0]
59
+ const repo = latest && allowed.get(latest.repository.nameWithOwner.toLowerCase())
60
+ // The viewer's token can have broader access than this workspace. Never
61
+ // persist or disclose a PR from outside the workspace repository grants.
62
+ if (latest && (!repo || repo.repoId !== latest.repository.databaseId)) continue
63
+ const next = latest ? `https://github.com/${repo!.github}/pull/${latest.number}` : null
64
+ if (latest && next) metadata.set(next, { url: next, ...itemMetadata(latest, 'pull')! })
65
+ for (const issue of issues) {
66
+ const ref = parseGithubFixUrl(issue.issueUrl)
67
+ if (ref?.kind === 'issue' && ref.number === job.number && issue.repoId === job.repo.repoId) {
68
+ updates.push({ findingId: issue.findingId, issueUrl: issue.issueUrl!, previous: issue.autoFixUrl, next, checkedAt })
69
+ }
70
+ }
71
+ }
72
+ return updates
73
+ }
74
+
75
+ // Fetch issue details, linked PR states and manual Fix metadata in one batch.
76
+ // Pagination and workspaces with over 200 distinct links need further batches.
77
+ // Live GraphQL results prove this viewer's access; never publish them into the
78
+ // REST shared cache under an older public-visibility grant.
79
+ export async function lookupIssueLinks(config: ManagedConfig, db: ManagedDb, snapshot: TeamReportAccessSnapshot,
80
+ urls: string[], issues: ManagedIssue[], fetchImpl: typeof fetch = fetch): Promise<{ fixes: GithubFixResult[]; updates: IssueFixUpdate[] }> {
81
+ const checkedAt = Date.now(), signal = AbortSignal.timeout(10_000)
82
+ const allowed = new Map(snapshot.repositories.filter(repo => isGithubRepoName(repo.github)).map(repo => [repo.github.toLowerCase(), repo]))
83
+ const jobs = new Map<string, Job>()
84
+ const linked = new Set(issues.filter(issue => issue.issueUrl).map(issue => {
85
+ const ref = parseGithubFixUrl(issue.issueUrl)
86
+ return ref?.kind === 'issue' ? `${issue.repoId}:issue:${ref.number}` : ''
87
+ }))
88
+ for (const url of urls) {
89
+ const ref = parseGithubFixUrl(url), repo = ref && allowed.get(ref.repo.toLowerCase())
90
+ if (!ref || !repo) continue
91
+ const key = `${repo.repoId}:${ref.kind}:${ref.number}`, previous = jobs.get(key)
92
+ if (previous) { previous.aliases.push(url); continue }
93
+ jobs.set(key, { repo, kind: ref.kind, number: ref.number, aliases: [url], linked: linked.has(key), cursor: null, pulls: [], complete: false })
94
+ }
95
+ if (jobs.size === 0) return { fixes: [], updates: [] }
96
+ const withinDeadline: typeof fetch = (input, init) => { signal.throwIfAborted(); return fetchImpl(input, { ...init, signal }) }
97
+ const token = await ensureUserAccessToken(config, db, snapshot.user.id, checkedAt, withinDeadline)
98
+ if (!token) return { fixes: await lookupFixes(config, db, snapshot, urls, withinDeadline), updates: [] }
99
+ const metadata = new Map<string, Metadata>(), selected = [...jobs.values()]
100
+ let pending = selected
101
+ for (let page = 0; pending.length > 0 && page < 100 && !signal.aborted; page++) {
102
+ const batch = pending.slice(0, 200), query = metadataQuery(batch)
103
+ let data: Record<string, { databaseId: number; nameWithOwner: string; item: Issue | Pull } | null>
104
+ try {
105
+ const response = await withinDeadline('https://api.github.com/graphql', {
106
+ method: 'POST', redirect: 'error',
107
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', 'user-agent': 'deepview-triage' }, body: JSON.stringify({ query }),
108
+ })
109
+ if (!response.ok) break
110
+ const body = await response.json() as { data?: typeof data; errors?: { path?: unknown[] }[] }
111
+ // Errors attached to an alias invalidate that whole job, including its
112
+ // connection. Other aliases can succeed even if one issue was deleted.
113
+ if (!body?.data || body.errors != null && (!Array.isArray(body.errors)
114
+ || body.errors.some(error => typeof error?.path?.[0] !== 'string' || !/^r\d+$/u.test(error.path[0])))) break
115
+ data = body.data
116
+ for (const error of body.errors ?? []) data[error.path![0] as string] = null
117
+ } catch { break }
118
+ pending = pending.slice(batch.length)
119
+ for (const [index, job] of batch.entries()) {
120
+ const repository = data[`r${index}`]
121
+ if (repository?.databaseId !== job.repo.repoId || typeof repository.nameWithOwner !== 'string' || repository.nameWithOwner.toLowerCase() !== job.repo.github.toLowerCase()) continue
122
+ if (readPage(job, repository.item, metadata)) pending.push(job)
123
+ }
124
+ }
125
+ const updates = issueUpdates(selected, issues, allowed, checkedAt, metadata)
126
+ return { fixes: [...metadata.values()], updates }
127
+ }
@@ -0,0 +1,47 @@
1
+ import type { ManagedConfig } from './config.ts'
2
+ import type { ManagedDb, ManagedSession } from './db.ts'
3
+ import { randomToken, safeEqual } from './crypto.ts'
4
+ import { ISSUE_STATE_COOKIE, buildCookie, clearCookie, cookieName, parseCookies } from './session.ts'
5
+ import { OAuthError, ensureUserAccessToken, exchangeCode, fetchIdentity } from './github-oauth.ts'
6
+
7
+ export const ISSUE_LOGIN_PATH = '/api/oauth/github/issues/login'
8
+
9
+ export function isIssueOAuthCallback(config: ManagedConfig, query: URLSearchParams, cookie: string | undefined): boolean {
10
+ const expected = parseCookies(cookie).get(cookieName(config, ISSUE_STATE_COOKIE))?.split('.')[0]
11
+ return !!expected && safeEqual(query.get('state') ?? '', expected)
12
+ }
13
+
14
+ export function issueLoginRedirect(config: ManagedConfig, session: ManagedSession, now = Date.now()) {
15
+ const state = randomToken()
16
+ const url = new URL('https://github.com/login/oauth/authorize')
17
+ url.searchParams.set('client_id', config.githubClientId)
18
+ url.searchParams.set('redirect_uri', config.oauthCallbackUrl)
19
+ url.searchParams.set('state', state)
20
+ url.searchParams.set('allow_signup', 'false')
21
+ // Reauthorize the same app for the current account, without replacing the
22
+ // DeepView session or permitting an OAuth account switch during creation.
23
+ const value = `${state}.${session.id}.${now}`
24
+ return { location: url.href, setCookie: buildCookie(cookieName(config, ISSUE_STATE_COOKIE), value,
25
+ { secure: config.cookieSecure, maxAgeS: 600, sameSite: 'Lax' }) }
26
+ }
27
+
28
+ export async function issueOAuthCallback(config: ManagedConfig, db: ManagedDb, session: ManagedSession,
29
+ query: URLSearchParams, cookie: string | undefined, fetchImpl: typeof fetch = fetch, now = Date.now()) {
30
+ const [expected, sessionId, timestamp] = (parseCookies(cookie).get(cookieName(config, ISSUE_STATE_COOKIE)) ?? '').split('.')
31
+ const code = query.get('code'), state = query.get('state')
32
+ if (!code || !state || !expected || !safeEqual(state, expected) || sessionId !== session.id
33
+ || !timestamp || !Number.isFinite(Number(timestamp)) || now < Number(timestamp) || now - Number(timestamp) > 600_000) {
34
+ throw new OAuthError(400, 'invalid-oauth-state')
35
+ }
36
+ const tokens = await exchangeCode(config, code, now, fetchImpl)
37
+ const identity = await fetchIdentity(tokens.accessToken, fetchImpl)
38
+ if (identity.githubUserId !== await db.getUserGithubId(session.userId)) throw new OAuthError(403, 'github-account-mismatch')
39
+ const current = await db.sessionWithUser(session.id, Date.now())
40
+ if (!current || current.user.role === 'none' || current.session.userId !== session.userId) throw new OAuthError(401, 'unauthenticated')
41
+ await db.setUserTokens(session.userId, tokens)
42
+ return { location: '/github-issue-authorized.html', setCookie: clearCookie(cookieName(config, ISSUE_STATE_COOKIE), config.cookieSecure) }
43
+ }
44
+
45
+ export function issueUserToken(config: ManagedConfig, db: ManagedDb, userId: string, fetchImpl: typeof fetch = fetch) {
46
+ return ensureUserAccessToken(config, db, userId, Date.now(), fetchImpl)
47
+ }