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

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 (150) hide show
  1. package/common/default-scan-models.ts +6 -5
  2. package/common/managed/comments.ts +9 -0
  3. package/out/activity.js +3 -3
  4. package/out/brotli-fallback.js +1 -1
  5. package/out/chunk-4ISO5F7Y.js +1 -1
  6. package/out/chunk-65PLAG3I.js +12 -0
  7. package/out/chunk-6CCSTJWB.js +1 -0
  8. package/out/chunk-7GJNLCXF.js +15 -0
  9. package/out/chunk-BZP3CT2V.js +244 -0
  10. package/out/{chunk-TZS7KERJ.js → chunk-DCBXCBLL.js} +2 -2
  11. package/out/chunk-E3LFSUDJ.js +1 -1
  12. package/out/chunk-EQ5EQXV5.js +1 -0
  13. package/out/chunk-F3UI65ZI.js +42 -0
  14. package/out/chunk-FAG6E5RC.js +3 -0
  15. package/out/chunk-HAZKDK4M.js +1 -1
  16. package/out/chunk-IZ6MYRYB.js +1 -1
  17. package/out/{chunk-VZJIHHTQ.js → chunk-K2QJLP3E.js} +1 -1
  18. package/out/chunk-NXATZJQ2.js +1 -1
  19. package/out/chunk-OBNHCORJ.js +2 -0
  20. package/out/chunk-OGNTXZYM.js +4 -0
  21. package/out/chunk-QRKFPLA4.js +2 -2
  22. package/out/chunk-QVKFY4FA.js +1 -0
  23. package/out/chunk-TOXMUOIW.js +2 -2
  24. package/out/chunk-WMFDQS2L.js +2 -2
  25. package/out/chunk-Y5ZHFNBD.js +1 -1
  26. package/out/client-managed-import.js +1 -1
  27. package/out/client-managed.js +7 -7
  28. package/out/client-sync.js +3 -3
  29. package/out/compare.js +19 -14
  30. package/out/dialogs.js +38 -38
  31. package/out/graph.js +12 -12
  32. package/out/index.html +5 -5
  33. package/out/prism.js +2 -2
  34. package/out/scan.js +2 -2
  35. package/out/terminal.js +150 -148
  36. package/out/view.css +1 -1
  37. package/out/view.js +5 -5
  38. package/package.json +21 -18
  39. package/risk/files/runs-code.js +2 -2
  40. package/server-e2e/static.ts +1 -1
  41. package/server-managed/activity.ts +23 -43
  42. package/server-managed/agent-merges.ts +2 -2
  43. package/server-managed/blob-store.ts +10 -1
  44. package/server-managed/bundle-advisories.ts +3 -2
  45. package/server-managed/bundle-advisory-inventory.ts +1 -1
  46. package/server-managed/bundle-build-worker.js +41 -6
  47. package/server-managed/bundle-build.ts +26 -14
  48. package/server-managed/bundle-cache.ts +29 -41
  49. package/server-managed/bundle-catalog.ts +11 -11
  50. package/server-managed/bundle-commits.ts +9 -16
  51. package/server-managed/bundle-dependency-reviews.ts +5 -11
  52. package/server-managed/bundle-summary-cache.ts +23 -14
  53. package/server-managed/bundle-validation.ts +2 -1
  54. package/server-managed/combined.ts +1 -5
  55. package/server-managed/comments.ts +15 -28
  56. package/server-managed/commit-coauthors.ts +4 -5
  57. package/server-managed/commit-lockfiles.ts +6 -5
  58. package/server-managed/comparison.ts +3 -5
  59. package/server-managed/config.ts +1 -2
  60. package/server-managed/db-methods.ts +163 -244
  61. package/server-managed/db-neon.ts +82 -178
  62. package/server-managed/db-schema.ts +15 -0
  63. package/server-managed/db.ts +5 -11
  64. package/server-managed/dependabot-access.ts +2 -1
  65. package/server-managed/dependabot-alerts.ts +7 -12
  66. package/server-managed/dependency-review-comments.ts +7 -13
  67. package/server-managed/dependency-reviews.ts +14 -15
  68. package/server-managed/github-accounts.ts +4 -5
  69. package/server-managed/github-actions.ts +6 -6
  70. package/server-managed/github-app.ts +19 -48
  71. package/server-managed/github-graphql.ts +5 -2
  72. package/server-managed/github-issue-links.ts +62 -42
  73. package/server-managed/github-issue-oauth.ts +7 -24
  74. package/server-managed/github-issues.ts +9 -7
  75. package/server-managed/github-link-oauth.ts +7 -20
  76. package/server-managed/github-oauth.ts +38 -12
  77. package/server-managed/github-pulls.ts +37 -26
  78. package/server-managed/github-requests.ts +21 -8
  79. package/server-managed/github-values.ts +26 -0
  80. package/server-managed/history-windows.ts +7 -7
  81. package/server-managed/http.ts +495 -554
  82. package/server-managed/index.ts +6 -6
  83. package/server-managed/link-reports.ts +6 -19
  84. package/server-managed/lockfile-scope.ts +1 -1
  85. package/server-managed/management.ts +14 -3
  86. package/server-managed/npm-delta.ts +22 -57
  87. package/server-managed/npm-insights.ts +31 -26
  88. package/server-managed/npm-kept.ts +9 -8
  89. package/server-managed/npm-loads.ts +2 -7
  90. package/server-managed/npm-manifest.ts +6 -4
  91. package/server-managed/npm-packages.ts +17 -9
  92. package/server-managed/npm-patch.ts +8 -16
  93. package/server-managed/npm-provenance.ts +12 -8
  94. package/server-managed/npm-risk.ts +9 -7
  95. package/server-managed/object-storage-disk.ts +2 -3
  96. package/server-managed/object-storage-vercel.ts +15 -11
  97. package/server-managed/object-storage.ts +7 -0
  98. package/server-managed/pretty-print.ts +8 -19
  99. package/server-managed/public-workspace.ts +50 -46
  100. package/server-managed/pull-comment-reviews.ts +2 -2
  101. package/server-managed/pull-dependencies.ts +20 -31
  102. package/server-managed/pull-dependency-reviews.ts +17 -24
  103. package/server-managed/pull-reviews.ts +4 -7
  104. package/server-managed/queue.ts +14 -0
  105. package/server-managed/release-commits.ts +9 -8
  106. package/server-managed/rename-diff.ts +17 -60
  107. package/server-managed/report-migration.ts +5 -8
  108. package/server-managed/report-sources.ts +6 -10
  109. package/server-managed/report-store.ts +2 -10
  110. package/server-managed/repository-actions.ts +7 -8
  111. package/server-managed/repository-agents.ts +31 -57
  112. package/server-managed/repository-aliases.ts +3 -9
  113. package/server-managed/repository-browser.ts +18 -16
  114. package/server-managed/repository-changes.ts +33 -37
  115. package/server-managed/repository-code.ts +5 -5
  116. package/server-managed/repository-dependency-reviews.ts +6 -13
  117. package/server-managed/repository-discovery.ts +2 -1
  118. package/server-managed/repository-history.ts +47 -51
  119. package/server-managed/repository-issues.ts +59 -30
  120. package/server-managed/repository-pulls.ts +7 -12
  121. package/server-managed/repository-pulse.ts +51 -45
  122. package/server-managed/repository-risk-assess.ts +5 -2
  123. package/server-managed/repository-risk-audit.ts +1 -1
  124. package/server-managed/repository-risk-read.ts +6 -6
  125. package/server-managed/repository-risk.ts +32 -40
  126. package/server-managed/repository-squashes.ts +7 -15
  127. package/server-managed/request-timing.ts +1 -1
  128. package/server-managed/sql.ts +18 -0
  129. package/server-managed/storage-encryption.ts +5 -7
  130. package/server-managed/team-app.ts +4 -7
  131. package/server-managed/team-npm-scopes.ts +5 -8
  132. package/server-managed/team-reports.ts +15 -15
  133. package/server-managed/type-only-proof.js +108 -0
  134. package/server-managed/type-only-worker.js +26 -14
  135. package/server-managed/type-only.ts +90 -60
  136. package/server-managed/uploads.ts +3 -3
  137. package/server-managed/upstream-cache.ts +5 -7
  138. package/server-managed/worker-turns.ts +76 -0
  139. package/server-managed/workspace-shares.ts +1 -2
  140. package/strip-types-loader.js +13 -10
  141. package/out/chunk-2SY4PYUQ.js +0 -4
  142. package/out/chunk-4HI2MSAV.js +0 -17
  143. package/out/chunk-4TQKM3JC.js +0 -42
  144. package/out/chunk-6VDDCFHT.js +0 -3
  145. package/out/chunk-EEQHVKR3.js +0 -1
  146. package/out/chunk-HNQNDNIE.js +0 -12
  147. package/out/chunk-OFPDMZJF.js +0 -244
  148. package/out/chunk-OQRSIBSC.js +0 -1
  149. package/out/chunk-YGRRXC2L.js +0 -1
  150. package/out/chunk-YTO6AQZM.js +0 -2
@@ -142,7 +142,11 @@ async function assembleManagedApp(config: ManagedConfig, { ui = true, ...options
142
142
  return { handleRequest, reap, isShuttingDown, stop, close }
143
143
  }
144
144
 
145
- export function logManagedStartup(config: ManagedConfig, port: number, mode = 'managed'): void {
145
+ // The startup lines, once `server` listens: its port, the configured one
146
+ // where its address gives none.
147
+ export function logManagedStartup(config: ManagedConfig, server: Server, mode = 'managed'): void {
148
+ const address = server.address()
149
+ const port = typeof address === 'object' && address ? address.port : config.port
146
150
  console.log([
147
151
  `DeepView managed server (${mode}):`,
148
152
  ` HTTP: http://${config.host}:${port}/`,
@@ -184,11 +188,7 @@ export async function init(config = loadManagedConfig(), options: Pick<ManagedAp
184
188
  function onClose(): void {
185
189
  if (!disposal) void dispose().catch(err => { console.error('Managed server cleanup failed:', err) })
186
190
  }
187
- function onListening(): void {
188
- const address = server.address()
189
- const port = typeof address === 'object' && address ? address.port : config.port
190
- logManagedStartup(config, port)
191
- }
191
+ function onListening(): void { logManagedStartup(config, server) }
192
192
  server.on('error', onError)
193
193
  server.once('close', onClose)
194
194
  server.on('listening', onListening)
@@ -5,7 +5,7 @@ import { createHash, randomUUID } from 'node:crypto'
5
5
  import { type StorageKey, unwrapStorageValue, wrapStorageValue } from '../server-common/storage-crypto.ts'
6
6
  import { parseLinkedFindings } from '../client/linked-findings.js'
7
7
  import type { ManagedSql } from './sql.ts'
8
- import { ManagedMutationError } from './management.ts'
8
+ import { ManagedMutationError, sessionAdmin } from './management.ts'
9
9
 
10
10
  export const LINK_REPORT_SCHEMA = `
11
11
  CREATE TABLE IF NOT EXISTS managed_link_report (
@@ -58,13 +58,6 @@ function parseLinkReport(content: string) {
58
58
  }
59
59
  export function linkReportMethods(db: ManagedSql, key: StorageKey | null): LinkReportStore {
60
60
  const map = (row: Omit<LinkReport, 'enabled'> & { enabled: number }): LinkReport => ({ ...row, enabled: row.enabled === 1 })
61
- async function authorize(sessionId: string) {
62
- const user = await db.prepare(`SELECT u.id, u.login, u.role FROM managed_session s JOIN managed_user u ON u.id = s.user_id
63
- WHERE s.id = ? AND s.expires_at > ?`).get(sessionId, Date.now()) as { id: string; login: string; role: string } | undefined
64
- if (!user) throw new ManagedMutationError(401, 'unauthenticated')
65
- if (user.role !== 'admin') throw new ManagedMutationError(403, 'forbidden')
66
- return user
67
- }
68
61
  return {
69
62
  async listLegacyLinkReports() {
70
63
  return await db.prepare("SELECT id, filename FROM managed_report WHERE analyzer = 'links' ORDER BY id").all() as { id: string; filename: string }[]
@@ -95,7 +88,7 @@ export function linkReportMethods(db: ManagedSql, key: StorageKey | null): LinkR
95
88
  return (await db.prepare(`SELECT ${columns} FROM managed_link_report ORDER BY uploaded_at DESC, id`).all() as Parameters<typeof map>[0][]).map(map)
96
89
  },
97
90
  async getLinkReport(sessionId, id) {
98
- await authorize(sessionId)
91
+ await sessionAdmin(db, sessionId)
99
92
  const row = await db.prepare(`SELECT ${columns}, encrypted_groups AS payload FROM managed_link_report WHERE id = ?`).get(id) as (Parameters<typeof map>[0] & { payload: string }) | undefined
100
93
  if (!row) throw new ManagedMutationError(404, 'no-link-report')
101
94
  const { payload, ...report } = row
@@ -109,7 +102,7 @@ export function linkReportMethods(db: ManagedSql, key: StorageKey | null): LinkR
109
102
  return rows.flatMap(row => decryptGroups(key, row.id, row.payload))
110
103
  },
111
104
  async importLinkReport(sessionId, filename, content) {
112
- const user = await authorize(sessionId)
105
+ const user = await sessionAdmin(db, sessionId)
113
106
  if (!key) throw new ManagedMutationError(503, 'storage-encryption-required')
114
107
  const parsed = parseLinkReport(content)
115
108
  if (!parsed || parsed.skipped) throw new ManagedMutationError(400, 'invalid-link-report')
@@ -127,7 +120,7 @@ export function linkReportMethods(db: ManagedSql, key: StorageKey | null): LinkR
127
120
  } finally { plain.fill(0) }
128
121
  },
129
122
  async setLinkReportEnabled(sessionId, id, enabled) {
130
- await authorize(sessionId)
123
+ await sessionAdmin(db, sessionId)
131
124
  if (!(await db.prepare('UPDATE managed_link_report SET enabled = ? WHERE id = ?').run(+enabled, id)).changes) throw new ManagedMutationError(404, 'no-link-report')
132
125
  },
133
126
  }
@@ -151,12 +144,6 @@ export function mergeLinkGroups(groups: readonly string[][], present?: ReadonlyS
151
144
  const first = root(ids[0]!)
152
145
  for (const id of ids.slice(1)) { const other = root(id); if (other !== first) parents.set(other, first) }
153
146
  }
154
- const merged = new Map<string, string[]>()
155
- for (const id of parents.keys()) {
156
- if (present && !present.has(id)) continue
157
- const key = root(id)
158
- const ids = merged.get(key) ?? []
159
- ids.push(id); merged.set(key, ids)
160
- }
161
- return [...merged.values()].filter(ids => ids.length >= 2)
147
+ const shown = [...parents.keys()].filter(id => !present || present.has(id))
148
+ return [...Map.groupBy(shown, root).values()].filter(ids => ids.length >= 2)
162
149
  }
@@ -8,7 +8,7 @@
8
8
  // failing the review where it couldn't be read.
9
9
  export interface LockfileScope { mode: 'exclude' | 'include'; paths: string[] }
10
10
  export const EVERY_LOCKFILE: LockfileScope = { mode: 'exclude', paths: [] }
11
- export const MAX_SCOPED_LOCKFILES = 100
11
+ const MAX_SCOPED_LOCKFILES = 100
12
12
  const MAX_PATH = 300
13
13
 
14
14
  // A path as one is named: relative, of `/`-separated names none of which is
@@ -1,17 +1,28 @@
1
1
  import type { AdminReport, BundleReuse, ManagedBundle, ManagedDb, ManagedRepo, RepoDataItem, RepoReportItem, ReportRecord, StoredUser } from './db-methods.ts'
2
2
  import { roleAtLeast } from '../common/managed/roles.ts'
3
+ import type { ManagedSql } from './sql.ts'
3
4
 
4
5
  export class ManagedMutationError extends Error {
5
6
  status: number
6
7
  constructor(status: number, message: string) { super(message); this.status = status }
7
8
  }
8
9
 
10
+ // The admin whose live session `sessionId` is, read in the caller's
11
+ // transaction (link-reports.ts, repository-aliases.ts, team-npm-scopes.ts):
12
+ // none refused 401, any other role 403.
13
+ export async function sessionAdmin(db: ManagedSql, sessionId: string): Promise<{ id: string; login: string; role: string }> {
14
+ const user = await db.prepare(`SELECT u.id, u.login, u.role FROM managed_session s JOIN managed_user u ON u.id = s.user_id
15
+ WHERE s.id = ? AND s.expires_at > ?`).get(sessionId, Date.now()) as { id: string; login: string; role: string } | undefined
16
+ if (!user) throw new ManagedMutationError(401, 'unauthenticated')
17
+ if (user.role !== 'admin') throw new ManagedMutationError(403, 'forbidden')
18
+ return user
19
+ }
20
+
9
21
  export type ContentMutation = { type: 'delete' } | { type: 'repo'; repoId: number | null; directory: string } | { type: 'visibility'; visible: boolean }
10
- export type ReportMutation = ContentMutation
11
22
  type RemovalRepo = Pick<ManagedRepo, 'repoId' | 'fullName' | 'addedAt'>
12
23
  type RemovalAnnotations = { reports: string; ids: string[] }
13
24
  export interface ManagementStore {
14
- mutateReport(sessionId: string, id: string, change: ReportMutation): Promise<{ report: ReportRecord; user: StoredUser }>
25
+ mutateReport(sessionId: string, id: string, change: ContentMutation): Promise<{ report: ReportRecord; user: StoredUser }>
15
26
  mutateBundle(sessionId: string, id: string, change: ContentMutation): Promise<{ bundle: ManagedBundle; user: StoredUser }>
16
27
  // A repeated upload/build of stored bytes (see reuseBundle). Renames need the
17
28
  // access other bundle mutations need; a server build labels the row anyway.
@@ -47,7 +58,7 @@ export function managementMethods(db: ManagementDb): ManagementStore {
47
58
  if (user.role !== 'admin' && !await db.userCanReadRepoPath(user.id, change.repoId, change.directory)) throw new ManagedMutationError(403, 'repo-forbidden')
48
59
  }
49
60
  return {
50
- async mutateReport(sessionId: string, id: string, change: ReportMutation) {
61
+ async mutateReport(sessionId: string, id: string, change: ContentMutation) {
51
62
  const user = await authorize(sessionId, 'manage')
52
63
  const report = await db.getReport(id)
53
64
  if (!report || (user.role !== 'admin' && report.uploadedBy !== user.id && !await db.userCanReadReport(user.id, id))) throw new ManagedMutationError(404, 'no-report')
@@ -16,11 +16,11 @@
16
16
  // first's; and kept by both sides' integrities, in this instance and beyond
17
17
  // it (`kept`), what a version holds never changing. Access is the caller's
18
18
  // to check.
19
- import { Worker } from 'node:worker_threads'
20
19
  import { createHash } from 'node:crypto'
21
20
  import type { KeptStore } from './npm-kept.ts'
22
21
  import { type Lru, lru } from './lru.ts'
23
22
  import { NpmPackageError, type NpmPackageFile, npmFileText } from './npm-packages.ts'
23
+ import { workerTurns } from './worker-turns.ts'
24
24
 
25
25
  export interface NpmDelta { additions: number; deletions: number; typeless: { additions: number; deletions: number } | null; binary: boolean }
26
26
 
@@ -32,34 +32,18 @@ const MAX_TEXT_LENGTH = 64 * 1024 * 1024
32
32
 
33
33
  const deltas: Lru<NpmDelta> = lru(20_000)
34
34
  const working = new Map<string, Promise<NpmDelta>>()
35
- let active = 0
36
- const waiting: Array<() => void> = []
37
-
38
- async function turn(deadline: number): Promise<void> {
39
- if (active < MAX_ACTIVE) { active++; return }
40
- if (waiting.length >= MAX_WAITING) throw new NpmPackageError(429, 'delta-busy')
41
- await new Promise<void>((resolve, reject) => {
42
- const next = () => { clearTimeout(timer); resolve() }
43
- const timer = setTimeout(() => {
44
- waiting.splice(waiting.indexOf(next), 1)
45
- reject(new NpmPackageError(504, 'delta-timeout'))
46
- }, deadline - Date.now())
47
- waiting.push(next)
48
- })
49
- }
50
- function done() {
51
- const next = waiting.shift()
52
- if (next) next()
53
- else active--
54
- }
35
+ const workers = workerTurns({ what: 'package delta', active: MAX_ACTIVE, waiting: MAX_WAITING, error: NpmPackageError,
36
+ busy: 'delta-busy', timeout: 'delta-timeout', failed: 'delta-failed' })
55
37
 
56
38
  const lines = (told: unknown): told is { additions: number; deletions: number } => typeof told === 'object' && told !== null
57
39
  && Number.isSafeInteger((told as { additions?: unknown }).additions) && Number.isSafeInteger((told as { deletions?: unknown }).deletions)
58
40
  // A delta as kept, none where it isn't one, or was kept before it told of
59
41
  // binary files.
60
- const deltaOf = (told: unknown): NpmDelta | null => lines(told) && ((told as NpmDelta).typeless === null || lines((told as NpmDelta).typeless))
61
- && typeof (told as NpmDelta).binary === 'boolean' ? { additions: told.additions, deletions: told.deletions, typeless: (told as NpmDelta).typeless,
62
- binary: (told as NpmDelta).binary } : null
42
+ function deltaOf(told: unknown): NpmDelta | null {
43
+ if (!lines(told)) return null
44
+ const { typeless, binary } = told as { typeless?: unknown; binary?: unknown }
45
+ return (typeless === null || lines(typeless)) && typeof binary === 'boolean' ? { additions: told.additions, deletions: told.deletions, typeless, binary } : null
46
+ }
63
47
 
64
48
  type Counted = { additions: number; deletions: number; typeAdditions: number; typeDeletions: number; typeFiles: number }
65
49
  const isCounted = (told: unknown): told is Counted => typeof told === 'object' && told !== null
@@ -67,29 +51,9 @@ const isCounted = (told: unknown): told is Counted => typeof told === 'object' &
67
51
 
68
52
  // What the worker counts of `base` against `other`, each its text files' paths and texts.
69
53
  function counted(base: [string, string][], other: [string, string][], deadline: number): Promise<Counted> {
70
- let worker: Worker
71
- try {
72
- worker = new Worker(new URL('./npm-delta-worker.js', import.meta.url), {
73
- workerData: { base, other }, execArgv: ['--disable-warning=ExperimentalWarning'], resourceLimits: { maxOldGenerationSizeMb: 1536 },
74
- })
75
- } catch (err) {
76
- console.warn('managed: a package delta could not start:', err)
77
- throw new NpmPackageError(503, 'unavailable')
78
- }
79
- return new Promise((resolve, reject) => {
80
- let answer: Counted | null = null, failure = new NpmPackageError(422, 'delta-failed')
81
- const timer = setTimeout(() => { failure = new NpmPackageError(504, 'delta-timeout'); void worker.terminate() }, deadline - Date.now())
82
- worker.once('message', (told: unknown) => {
83
- if (isCounted(told)) answer = told
84
- void worker.terminate()
85
- })
86
- worker.once('error', err => { console.warn('managed: a package delta failed:', err) })
87
- worker.once('exit', () => {
88
- clearTimeout(timer)
89
- if (answer) resolve(answer)
90
- else reject(failure)
91
- })
92
- })
54
+ return workers.run(new URL('./npm-delta-worker.js', import.meta.url), {
55
+ workerData: { base, other }, execArgv: ['--disable-warning=ExperimentalWarning'], resourceLimits: { maxOldGenerationSizeMb: 1536 },
56
+ }, told => (isCounted(told) ? told : null), deadline)
93
57
  }
94
58
 
95
59
  // A side's text files, by path, how long their texts are, and its other,
@@ -137,6 +101,9 @@ function binaryChanged(olds: NpmPackageFile[], news: NpmPackageFile[]): boolean
137
101
  }
138
102
 
139
103
  type Side = { integrity: string; files: () => Promise<NpmPackageFile[]> }
104
+ // A delta's key: the integrities of the version it is against, or none, and
105
+ // of the version.
106
+ export const deltaKey = (base: string | null, other: string) => `${base ?? '(empty)'}\0${other}`
140
107
 
141
108
  // The delta of `other` (its integrity, and how to read its files) against
142
109
  // `base`, or none, as held, else shared with one asked before it, else
@@ -144,7 +111,7 @@ type Side = { integrity: string; files: () => Promise<NpmPackageFile[]> }
144
111
  // it is looked for, lest those asked together each look, find none, and work
145
112
  // it out.
146
113
  export function npmDelta(base: Side | null, other: Side, kept: KeptStore<NpmDelta> | null = null): Promise<NpmDelta> {
147
- const key = `${base?.integrity ?? '(empty)'}\0${other.integrity}`
114
+ const key = deltaKey(base?.integrity ?? null, other.integrity)
148
115
  const known = deltas.get(key)
149
116
  if (known) return Promise.resolve(known)
150
117
  const shared = working.get(key)
@@ -158,7 +125,7 @@ export function npmDelta(base: Side | null, other: Side, kept: KeptStore<NpmDelt
158
125
  // against, or none, and of the version) held or kept, by their keys
159
126
  // (npmDelta's), in one read of `kept` for those not held: none worked out.
160
127
  export async function keptNpmDeltas(sides: [string | null, string][], kept: KeptStore<NpmDelta>): Promise<Map<string, NpmDelta>> {
161
- const keys = [...new Set(sides.map(([base, other]) => `${base ?? '(empty)'}\0${other}`))]
128
+ const keys = [...new Set(sides.map(([base, other]) => deltaKey(base, other)))]
162
129
  const found = new Map(keys.flatMap(key => { const known = deltas.get(key); return known ? [[key, known] as const] : [] }))
163
130
  const unheld = keys.filter(key => !found.has(key))
164
131
  for (const [key, row] of unheld.length > 0 ? await kept.readMany(unheld) : []) {
@@ -174,20 +141,18 @@ export async function keptNpmDeltas(sides: [string | null, string][], kept: Kept
174
141
  async function worked(key: string, base: Side | null, other: Side, kept: KeptStore<NpmDelta> | null): Promise<NpmDelta> {
175
142
  const known = deltaOf((await kept?.read(key))?.value)
176
143
  if (known) { deltas.set(key, known); return known }
177
- await turn(Date.now() + DELTA_TIMEOUT_MS)
178
- let binary, told
179
- try {
144
+ const delta = await workers.inTurn(Date.now() + DELTA_TIMEOUT_MS, async (): Promise<NpmDelta> => {
180
145
  // Its turn held till both sides are read, or have failed.
181
146
  const [baseRead, otherRead] = await Promise.allSettled([base ? base.files() : Promise.resolve(null), other.files()])
182
147
  if (baseRead.status === 'rejected') throw baseRead.reason
183
148
  if (otherRead.status === 'rejected') throw otherRead.reason
184
149
  const [olds, news] = [texts(baseRead.value), texts(otherRead.value)]
185
150
  if (olds.length + news.length > MAX_TEXT_LENGTH) throw new NpmPackageError(413, 'package-too-large')
186
- binary = binaryChanged(olds.binaries, news.binaries)
187
- told = await counted(olds.read, news.read, Date.now() + DELTA_TIMEOUT_MS)
188
- } finally { done() }
189
- const delta = { additions: told.additions, deletions: told.deletions,
190
- typeless: told.typeFiles > 0 ? { additions: told.additions - told.typeAdditions, deletions: told.deletions - told.typeDeletions } : null, binary }
151
+ const binary = binaryChanged(olds.binaries, news.binaries)
152
+ const told = await counted(olds.read, news.read, Date.now() + DELTA_TIMEOUT_MS)
153
+ return { additions: told.additions, deletions: told.deletions,
154
+ typeless: told.typeFiles > 0 ? { additions: told.additions - told.typeAdditions, deletions: told.deletions - told.typeDeletions } : null, binary }
155
+ })
191
156
  deltas.set(key, delta)
192
157
  await kept?.write(key, delta, Date.now())
193
158
  return delta
@@ -15,9 +15,11 @@ import type { Advisory, CacheStore } from '@preventive/upstream/advisories.js'
15
15
  import { type Client, HttpError, createClient } from '@preventive/upstream/github.js'
16
16
  import { ADVISORIES_TIMEOUT_MS, fetchBundleAdvisories } from './bundle-advisories.ts'
17
17
  import { isExactVersion } from '@preventive/upstream/semver.js'
18
+ import { USER_AGENT, repoApi } from './github-requests.ts'
18
19
  import { kept } from './kept.ts'
19
20
  import { type NpmProvenance, keptNpmProvenance } from './npm-provenance.ts'
20
- import { NpmPackageError, askUpstreamJson, plainObject, readLimited } from './npm-packages.ts'
21
+ import { plainObject } from './npm-manifest.ts'
22
+ import { NpmPackageError, askUpstreamJson, readLimited } from './npm-packages.ts'
21
23
 
22
24
  const DOWNLOADS_API = 'https://api.npmjs.org/downloads/range'
23
25
  // What npm's range API may answer for each package asked: a year of days is
@@ -33,6 +35,7 @@ const API_TIMEOUT_MS = 30_000
33
35
  const API_BYTES = 1024 * 1024
34
36
  const DAY_MS = 24 * 60 * 60_000
35
37
  const SEVERITY_RANK: Record<string, number> = { critical: 0, high: 1, moderate: 2, low: 3 }
38
+ const rank = (severity: string | undefined) => SEVERITY_RANK[severity ?? ''] ?? 4
36
39
 
37
40
  const count = (value: unknown) => Number.isSafeInteger(value) && (value as number) >= 0 ? value as number : 0
38
41
  const isDay = (value: unknown): value is string => typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/u.test(value) && !Number.isNaN(Date.parse(value))
@@ -168,11 +171,10 @@ export interface NpmGithubStats {
168
171
  // How many pull requests a repository has open: the last page of their list,
169
172
  // one a page, as its Link header names it, or the one page's length.
170
173
  async function countOpenPulls(repo: string, token: string | null): Promise<number | null> {
171
- const path = repo.split('/').map(encodeURIComponent).join('/')
172
174
  let res: Response
173
175
  try {
174
- res = await fetch(`https://api.github.com/repos/${path}/pulls?state=open&per_page=1`, {
175
- headers: { accept: 'application/vnd.github+json', 'user-agent': 'deepview-triage', ...token && { authorization: `Bearer ${token}` } },
176
+ res = await fetch(`${repoApi(repo)}/pulls?state=open&per_page=1`, {
177
+ headers: { accept: 'application/vnd.github+json', 'user-agent': USER_AGENT, ...token && { authorization: `Bearer ${token}` } },
176
178
  redirect: 'error', signal: AbortSignal.timeout(API_TIMEOUT_MS),
177
179
  })
178
180
  } catch { return null }
@@ -198,7 +200,7 @@ const NONE = new Set([301, 302, 307, 308, 404])
198
200
  // again next time. Public is `visibility: 'public'`, as github-app.ts
199
201
  // requires: an internal repository answers `private: false`.
200
202
  async function publicRepo(repo: string, token: string | null): Promise<{ json: Record<string, unknown> & { full_name: string }; auth: string | null } | null> {
201
- const ask = (auth: string | null) => createClient({ token: auth, userAgent: 'deepview-triage' }).getRepo({ repo, followRedirect: true }) as Promise<unknown>
203
+ const ask = (auth: string | null) => createClient({ token: auth, userAgent: USER_AGENT }).getRepo({ repo, followRedirect: true }) as Promise<unknown>
202
204
  let auth = token, json: unknown
203
205
  try { json = await ask(token) }
204
206
  catch (error) {
@@ -254,7 +256,7 @@ async function askTags(repo: string, sha: string, version: string, token: string
254
256
  const [owner, name] = repo.split('/')
255
257
  const json = await askUpstreamJson(GITHUB_GRAPHQL, {
256
258
  method: 'POST', limit: API_BYTES, absent: [],
257
- headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', 'user-agent': 'deepview-triage' },
259
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', 'user-agent': USER_AGENT },
258
260
  body: JSON.stringify({ query: TAGS_QUERY, variables: { owner, name, query: version } }),
259
261
  })
260
262
  const data = plainObject(json) ? json['data'] : null
@@ -268,8 +270,10 @@ async function askTags(repo: string, sha: string, version: string, token: string
268
270
  .filter(node => taggedCommit(node.target) === sha).map(node => node.name).toSorted()
269
271
  }
270
272
 
271
- // Null where no token asked: nothing to keep for a reader who has one.
273
+ // Null where no token asked: nothing to keep for a reader who has one; kept
274
+ // by the repository, the commit and the version asked.
272
275
  const commitTags = kept<string[] | null>(500, tags => tags !== null)
276
+ const tagsKey = (repo: string, sha: string, version: string) => `${repo.toLowerCase()}\0${sha}\0${version}`
273
277
 
274
278
  // The tags of a public repository (owner/name) that point to `sha`, a
275
279
  // version's publish commit, among those naming its `version` (`v1.2.3`,
@@ -277,7 +281,7 @@ const commitTags = kept<string[] | null>(500, tags => tags !== null)
277
281
  // a token: the reader's own (`githubToken`, asked for only where the tags
278
282
  // aren't kept), where they have one; without, none are asked.
279
283
  export async function npmCommitTags(repo: string, sha: string, version: string, githubToken: () => Promise<string | null>): Promise<string[]> {
280
- return await commitTags(`${repo.toLowerCase()}\0${sha}\0${version}`, async () => {
284
+ return await commitTags(tagsKey(repo, sha, version), async () => {
281
285
  const token = await githubToken()
282
286
  return token === null ? null : askTags(repo, sha, version, token)
283
287
  }) ?? []
@@ -349,7 +353,7 @@ async function askAdvisories(name: string, versions: string[], { githubToken, re
349
353
  const unreached = github ?? named
350
354
  const last = unreached === null ? null : await lastListing(unreached)
351
355
  let untaken = false
352
- const offline: Client = { ...createClient({ token: null, userAgent: 'deepview-triage' }),
356
+ const offline: Client = { ...createClient({ token: null, userAgent: USER_AGENT }),
353
357
  listRepoAdvisories: () => { untaken = true; return Promise.reject(new Error('GitHub can\'t be reached')) } }
354
358
  const listed = last && await ask(unreached, () => last.cache, { github: offline })
355
359
  if (last && listed?.status === 200) {
@@ -362,18 +366,23 @@ async function askAdvisories(name: string, versions: string[], { githubToken, re
362
366
  }
363
367
  }
364
368
  if (result.status !== 200) throw new NpmPackageError(502, 'upstream-unavailable')
369
+ return { versions, repository, ...keptAt && { keptAt }, advisories: mergedAdvisories(result.body, versions) }
370
+ }
371
+
372
+ // Upstream's advisories as NpmAdvisory tells them, those covering none of
373
+ // `versions` left out, the worst first. npm's registry answers an advisory
374
+ // once a range it covers, and upstream answers the versions OSV's record of
375
+ // it, or its repository, covers beyond npm's under the same id, in a row of
376
+ // their own (as hermes-engine's GHSA-f5x2-xv93-4p23: npm's `<=0.4.3`, OSV's
377
+ // fixed in 0.5.2): here it is one row, the first's (npm's, then OSV's, then
378
+ // the repository's, as upstream orders them) with what it lacks taken from
379
+ // the rest, its ranges joined as semver joins them, the versions and CWEs
380
+ // they cover together, and the worst severity and highest score of them: a
381
+ // version only the repository reports keeps the severity it gives.
382
+ function mergedAdvisories(rows: Advisory[], versions: string[]): NpmAdvisory[] {
365
383
  const index = new Map(versions.map((version, i) => [version, i]))
366
- // npm's registry answers an advisory once a range it covers, and upstream
367
- // answers the versions OSV's record of it, or its repository, covers beyond
368
- // npm's under the same id, in a row of their own (as hermes-engine's
369
- // GHSA-f5x2-xv93-4p23: npm's `<=0.4.3`, OSV's fixed in 0.5.2): here it is
370
- // one row, the first's (npm's, then OSV's, then the repository's, as
371
- // upstream orders them) with what it lacks taken from the rest, its ranges
372
- // joined as semver joins them, the versions and CWEs they cover together,
373
- // and the worst severity and highest score of them: a version only the
374
- // repository reports keeps the severity it gives.
375
384
  const merged = new Map<string, NpmAdvisory>()
376
- for (const row of result.body) {
385
+ for (const row of rows) {
377
386
  const affected = row.versions.map(version => index.get(version)).filter(at => at !== undefined)
378
387
  const own: NpmAdvisory = {
379
388
  id: row.id, source: row.source, ...row.ghsa && { ghsa: row.ghsa }, ...row.url && { url: row.url }, ...row.title && { title: row.title },
@@ -387,16 +396,12 @@ async function askAdvisories(name: string, versions: string[], { githubToken, re
387
396
  }
388
397
  const range = [known.range, row.range].filter(Boolean).join(' || ')
389
398
  const cvss = Math.max(known.cvss ?? -1, row.cvss ?? -1)
390
- const rank = (severity: string | undefined) => SEVERITY_RANK[severity ?? ''] ?? 4
391
399
  const severity = rank(row.severity) < rank(known.severity) ? row.severity : known.severity
392
400
  merged.set(row.id, { ...own, ...known, ...range && { range }, ...severity && { severity }, ...cvss >= 0 && { cvss }, cwe: [...new Set([...known.cwe, ...row.cwe])],
393
401
  affected: [...known.affected, ...affected] })
394
402
  }
395
- return {
396
- versions, repository, ...keptAt && { keptAt },
397
- advisories: [...merged.values()].map(row => ({ ...row, affected: [...new Set(row.affected)].toSorted((a, b) => a - b) })).filter(row => row.affected.length > 0)
398
- .toSorted((a, b) => (SEVERITY_RANK[a.severity ?? ''] ?? 4) - (SEVERITY_RANK[b.severity ?? ''] ?? 4) || a.id.localeCompare(b.id)),
399
- }
403
+ return [...merged.values()].map(row => ({ ...row, affected: [...new Set(row.affected)].toSorted((a, b) => a - b) })).filter(row => row.affected.length > 0)
404
+ .toSorted((a, b) => rank(a.severity) - rank(b.severity) || a.id.localeCompare(b.id))
400
405
  }
401
406
 
402
407
  const ADVISORY_LISTS = 100
@@ -440,7 +445,7 @@ export function npmKnown(name: string, version: string, isPrivate: boolean, repo
440
445
  const key = advisoryKeys.get(name)
441
446
  const list = key === undefined ? undefined : advisoryLists.peek(key)
442
447
  if (list?.versions.includes(version)) known.advisories = { name, ...list }
443
- const tags = repo === null || sha === null ? [] : commitTags.peek(`${repo.toLowerCase()}\0${sha}\0${version}`)
448
+ const tags = repo === null || sha === null ? [] : commitTags.peek(tagsKey(repo, sha, version))
444
449
  if (tags) known.tags = { name, version, tags }
445
450
  const socket = isPrivate ? null : socketReports.peek(`${name}@${version}`)
446
451
  if (socket !== undefined) known.socket = { name, version, socket }
@@ -74,21 +74,22 @@ function keptStore<T>(db: UpstreamCacheStore, type: string, keptMs: number, debu
74
74
  const kept: unknown = JSON.parse(row ?? 'null')
75
75
  return plainObject(kept) && typeof kept['at'] === 'number' && 'value' in kept ? { at: kept['at'], value: kept['value'] as T } : null
76
76
  }
77
+ // Those of `keys` kept among `rows`, by key.
78
+ const found = (keys: string[], rows: Map<string, string>) =>
79
+ new Map(keys.flatMap(key => { const kept = valueOf(rows.get(keyOf(key))); return kept ? [[key, kept] as const] : [] }))
77
80
  return {
78
81
  async read(key) {
79
82
  try { return valueOf(await db.getUpstreamCacheEntry(keyOf(key))) } catch (error) { warn('read', error); return null }
80
83
  },
81
84
  async readMany(keys) {
82
85
  try {
83
- const rows = await db.getUpstreamCacheEntries(keys.map(keyOf))
84
- return new Map(keys.flatMap(key => { const kept = valueOf(rows.get(keyOf(key))); return kept ? [[key, kept] as const] : [] }))
86
+ return found(keys, await db.getUpstreamCacheEntries(keys.map(keyOf)))
85
87
  } catch (error) { warn('read', error); return new Map() }
86
88
  },
87
89
  async readFirst(first, then) {
88
90
  try {
89
91
  const { first: answered, entries } = await db.getFirstUpstreamCacheEntries(first.map(keyOf), then.map(keyOf))
90
- const asked = answered ? first : then
91
- return { first: answered, found: new Map(asked.flatMap(key => { const kept = valueOf(entries.get(keyOf(key))); return kept ? [[key, kept] as const] : [] })) }
92
+ return { first: answered, found: found(answered ? first : then, entries) }
92
93
  } catch (error) { warn('read', error); return { first: false, found: new Map() } }
93
94
  },
94
95
  async write(key, value, at) {
@@ -160,7 +161,7 @@ export const githubTagStore = <T>(db: UpstreamCacheStore, debug = false): KeptSt
160
161
  // Pages of a repository's history (repository-history.ts historyFrom), by its
161
162
  // id and the commit each starts at, which never change: kept a month after
162
163
  // they were last read from GitHub.
163
- export const HISTORY_PAGE_KEPT_MS = 30 * 24 * 60 * 60_000
164
+ const HISTORY_PAGE_KEPT_MS = 30 * 24 * 60 * 60_000
164
165
  export const historyPageStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/history', HISTORY_PAGE_KEPT_MS, debug)
165
166
  // The pull requests squashed into a repository's commits, by the commit
166
167
  // (repository-squashes.ts squashedPulls): kept as its history's pages are.
@@ -210,13 +211,13 @@ export const codeHeadStore = (db: UpstreamCacheStore, debug = false): KeptStore<
210
211
  // (pull-dependencies.ts), by the commits of its base and head, which never
211
212
  // change: kept as its history's pages are.
212
213
  export const pullDependencyStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/pull-dependencies', HISTORY_PAGE_KEPT_MS, debug)
214
+ // The lines a version changes against another, or none (npm-delta.ts), by
215
+ // both sides' integrities, each kept HISTORY_PAGE_KEPT_MS.
216
+ export const npmDeltaStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'npm/deltas', HISTORY_PAGE_KEPT_MS, debug)
213
217
  // The versions a repository's lockfiles locked at the commit its dependencies
214
218
  // are reviewed since (pull-dependency-reviews.ts reviewBaseline), by the
215
219
  // commit, which never change: kept as its history's pages are, never stored
216
220
  // as reviews.
217
- // The lines a version changes against another, or none (npm-delta.ts), by
218
- // both sides' integrities, each kept HISTORY_PAGE_KEPT_MS.
219
- export const npmDeltaStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'npm/deltas', HISTORY_PAGE_KEPT_MS, debug)
220
221
  export const reviewBaselineStore = (db: UpstreamCacheStore, debug = false): KeptStore<{ versions: string[]; unread: string[] }> =>
221
222
  keptStore<{ versions: string[]; unread: string[] }>(db, 'repository/review-baselines', HISTORY_PAGE_KEPT_MS, debug)
222
223
  // What a repository's dependency review read of GitHub (pull-dependencies.ts
@@ -79,7 +79,7 @@ export function sharedLoad<T>(key: string, work: () => Promise<T>, busy: string,
79
79
  if (!load) {
80
80
  if (!slots.has(slot) && placesTaken() + places > MAX_ACTIVE_LOADS) return refused(429, busy)
81
81
  const created: Load = { job: work(), readers: 0, settled: false, slot }
82
- const finish = () => { settle(key, created) }
82
+ const finish = () => { created.settled = true; done(key, created) }
83
83
  created.job.then(finish, finish)
84
84
  loads.set(key, created)
85
85
  const taken = slots.get(slot)
@@ -100,11 +100,6 @@ export function sharedLoad<T>(key: string, work: () => Promise<T>, busy: string,
100
100
  }
101
101
  }
102
102
 
103
- function settle(key: string, load: Load) {
104
- load.settled = true
105
- done(key, load)
106
- }
107
-
108
103
  // A load gone from the active ones, and its place with it, once its work is
109
104
  // done and its readers have released it.
110
105
  function done(key: string, load: Load) {
@@ -164,7 +159,7 @@ async function downloadTarball(url: string, isPrivate: boolean): Promise<Buffer>
164
159
  // document names are the tarball that reader may download, wherever they
165
160
  // were kept and whoever fetched them.
166
161
  async function readTarball(doc: NpmVersionDocument): Promise<Uint8Array> {
167
- const expected = sha512Of(doc.dist.integrity), shasum = doc.dist.shasum ?? null, url = doc.dist.tarball
162
+ const expected = sha512Of(doc.dist.integrity), shasum = doc.dist.shasum, url = doc.dist.tarball
168
163
  if (!url.startsWith(`${NPM_REGISTRY}/${doc.name}/-/`) || URL.parse(url)?.href !== url || expected === null
169
164
  || (shasum !== null && !/^[\da-f]{40}$/u.test(shasum))) throw new NpmPackageError(502, 'upstream-invalid')
170
165
  const kept = tarballCache === null ? null : upstreamCachePath(tarballCache, 'npm/tarballs', `${doc.name}@${doc.version}.tgz`)
@@ -74,12 +74,11 @@ export function npmManifest(json: Record<string, unknown>): Record<string, unkno
74
74
  if (record && Object.keys(record).length > 0) pick[key] = record
75
75
  }
76
76
  if (json['hasInstallScript'] === true) pick['hasInstallScript'] = true
77
- // Whether npm keeps a provenance statement for it (npm-provenance.ts).
78
- if (plainObject(json['dist']) && plainObject(json['dist']['attestations']) && plainObject(json['dist']['attestations']['provenance'])) pick['provenance'] = true
77
+ if (hasProvenance(json['dist'])) pick['provenance'] = true
79
78
  // The scripts npm runs installing it from the registry; not `prepare`,
80
79
  // which runs only for a local or git install.
81
80
  const scripts = stringRecord(json['scripts'])
82
- const install = scripts ? ['preinstall', 'install', 'postinstall'].filter(script => script in scripts) : []
81
+ const install = scripts ? INSTALL_SCRIPTS.filter(script => script in scripts) : []
83
82
  if (install.length > 0) pick['installScripts'] = Object.fromEntries(install.map(script => [script, scripts![script]]))
84
83
  // A GitLab project it names, as its provenance's source is matched with
85
84
  // the repository it names, GitHub's below.
@@ -105,10 +104,13 @@ const VERSION_FIELDS = ['name', 'version', 'description', 'license', 'homepage',
105
104
  const DIST_FIELDS = ['tarball', 'integrity', 'shasum', 'unpackedSize', 'fileCount']
106
105
  const INSTALL_SCRIPTS = ['preinstall', 'install', 'postinstall']
107
106
  const picked = (json: Record<string, unknown>, keys: string[]) => Object.fromEntries(keys.filter(key => Object.hasOwn(json, key)).map(key => [key, json[key]]))
107
+ // Whether a version's `dist` tells of a provenance statement npm keeps for it
108
+ // (npm-provenance.ts).
109
+ const hasProvenance = (dist: unknown) => plainObject(dist) && plainObject(dist['attestations']) && plainObject(dist['attestations']['provenance'])
108
110
 
109
111
  export function npmVersionFields(json: Record<string, unknown>): Record<string, unknown> {
110
112
  const dist = plainObject(json['dist']) ? json['dist'] : {}
111
- const provenance = plainObject(dist['attestations']) && plainObject(dist['attestations']['provenance'])
113
+ const provenance = hasProvenance(dist)
112
114
  const scripts = picked(stringRecord(json['scripts']) ?? {}, INSTALL_SCRIPTS)
113
115
  return { ...picked(json, VERSION_FIELDS), dist: { ...picked(dist, DIST_FIELDS), ...provenance && { attestations: { provenance: {} } } },
114
116
  ...Object.keys(scripts).length > 0 && { scripts } }
@@ -21,8 +21,6 @@ import type { Role } from '../common/managed/roles.ts'
21
21
  import { npmManifest, npmVersionFields, plainObject, stringRecord } from './npm-manifest.ts'
22
22
  import { keepJson, readKeptJson, upstreamCachePath } from './upstream-cache.ts'
23
23
 
24
- export { npmManifest, plainObject }
25
-
26
24
  export const NPM_REGISTRY = 'https://registry.npmjs.org'
27
25
  const VERSION_DOCUMENT_BYTES = 8 * 1024 * 1024
28
26
  // Abbreviated packuments of packages with thousands of versions run to tens of MiB.
@@ -117,14 +115,22 @@ export async function readLimited(res: Response, limit: number): Promise<Buffer>
117
115
  return Buffer.concat(chunks)
118
116
  }
119
117
 
118
+ // A registry document as npm wrote it, read as the JSON object it is: a 502
119
+ // `upstream-invalid` where it isn't one.
120
+ function documentOf(body: Buffer): Record<string, unknown> {
121
+ let json: unknown
122
+ try { json = JSON.parse(body.toString('utf8')) } catch { throw new NpmPackageError(502, 'upstream-invalid') }
123
+ if (!plainObject(json)) throw new NpmPackageError(502, 'upstream-invalid')
124
+ return json
125
+ }
126
+
120
127
  // A registry document, or null where the registry has none for this caller:
121
128
  // 404, or 401/403 as it answers some private packages asked anonymously.
122
129
  // Credentials go only with `token`; nothing is cached on either side, but for
123
130
  // public whole documents (publicWholeDocument).
124
131
  async function registryDocument(url: string, { token, accept, limit, signal }: { token: string | null; accept: string; limit: number; signal: AbortSignal }): Promise<Record<string, unknown> | null> {
125
- const json = await askUpstreamJson(url, { headers: { accept, ...(token ? { authorization: `Bearer ${token}` } : {}) }, limit, signal, absent: [401, 403, 404] })
126
- if (json === null || plainObject(json)) return json
127
- throw new NpmPackageError(502, 'upstream-invalid')
132
+ const body = await askUpstream(url, { headers: { accept, ...(token ? { authorization: `Bearer ${token}` } : {}) }, limit, signal, absent: [401, 403, 404] })
133
+ return body === null ? null : documentOf(body)
128
134
  }
129
135
 
130
136
  // Where public packages' whole documents are kept, off Vercel: the upstream
@@ -147,9 +153,7 @@ async function publicWholeDocument(name: string, url: string, { limit, signal }:
147
153
  if (path !== null && kept) await rm(path, { force: true }).catch(() => {})
148
154
  return null
149
155
  }
150
- let json: unknown
151
- try { json = JSON.parse(body.toString('utf8')) } catch { throw new NpmPackageError(502, 'upstream-invalid') }
152
- if (!plainObject(json)) throw new NpmPackageError(502, 'upstream-invalid')
156
+ const json = documentOf(body)
153
157
  if (path !== null && etag !== null) await keepJson(path, etag, body)
154
158
  return json
155
159
  }
@@ -377,6 +381,10 @@ export function npmPublishTime(doc: Pick<NpmVersionDocument, 'name' | 'version'
377
381
 
378
382
  export interface NpmPackageFile { path: string; bytes: Uint8Array }
379
383
 
384
+ // Paths in the order a package's files are read in (readNpmTar), and
385
+ // Compare's: by their UTF-16 code units, as a plain sort orders them.
386
+ export const pathOrder = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0
387
+
380
388
  // How a tar stream is read (readNpmTar): how far its symlinks may climb above
381
389
  // it, and the entries, files and bytes it may hold, a package's unless given.
382
390
  export interface TarReading { symlinksAbove?: number; maxEntries?: number; maxFiles?: number; maxBytes?: number }
@@ -408,7 +416,7 @@ export function readNpmTar(tar: Uint8Array, { symlinksAbove = 0, maxEntries = MA
408
416
  files.set(path, data)
409
417
  if (files.size > maxFiles || total > maxBytes) throw new NpmPackageError(413, 'package-too-large')
410
418
  }
411
- return [...files].map(([path, bytes]) => ({ path, bytes })).toSorted((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
419
+ return [...files].map(([path, bytes]) => ({ path, bytes })).toSorted((a, b) => pathOrder(a.path, b.path))
412
420
  }
413
421
 
414
422
  const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })