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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/common/default-scan-models.ts +6 -5
  2. package/common/managed/comments.ts +9 -0
  3. package/out/activity.js +1 -1
  4. package/out/chunk-6CCSTJWB.js +1 -0
  5. package/out/{chunk-VZJIHHTQ.js → chunk-B3FNMHOE.js} +1 -1
  6. package/out/chunk-BNH52UHC.js +2 -0
  7. package/out/chunk-BRO77PQY.js +42 -0
  8. package/out/chunk-GRGIZOTP.js +4 -0
  9. package/out/chunk-JJK5OZG2.js +15 -0
  10. package/out/chunk-OFZYEWBH.js +244 -0
  11. package/out/{chunk-YGRRXC2L.js → chunk-OIERSXON.js} +1 -1
  12. package/out/{chunk-TZS7KERJ.js → chunk-QCOGVL37.js} +1 -1
  13. package/out/{chunk-6VDDCFHT.js → chunk-W3QFV4SP.js} +1 -1
  14. package/out/chunk-W6VOKW2N.js +12 -0
  15. package/out/chunk-ZQNEWVGG.js +1 -0
  16. package/out/client-managed.js +2 -2
  17. package/out/compare.js +19 -14
  18. package/out/dialogs.js +38 -38
  19. package/out/graph.js +12 -12
  20. package/out/index.html +5 -5
  21. package/out/scan.js +1 -1
  22. package/out/terminal.js +12 -12
  23. package/out/view.css +1 -1
  24. package/out/view.js +4 -4
  25. package/package.json +9 -6
  26. package/server-managed/activity.ts +23 -43
  27. package/server-managed/agent-merges.ts +2 -2
  28. package/server-managed/blob-store.ts +10 -1
  29. package/server-managed/bundle-advisories.ts +3 -2
  30. package/server-managed/bundle-advisory-inventory.ts +1 -1
  31. package/server-managed/bundle-build-worker.js +41 -6
  32. package/server-managed/bundle-build.ts +18 -10
  33. package/server-managed/bundle-cache.ts +29 -41
  34. package/server-managed/bundle-catalog.ts +11 -11
  35. package/server-managed/bundle-commits.ts +9 -16
  36. package/server-managed/bundle-dependency-reviews.ts +5 -11
  37. package/server-managed/bundle-summary-cache.ts +23 -14
  38. package/server-managed/bundle-validation.ts +2 -1
  39. package/server-managed/combined.ts +1 -5
  40. package/server-managed/comments.ts +15 -28
  41. package/server-managed/commit-coauthors.ts +4 -5
  42. package/server-managed/commit-lockfiles.ts +6 -5
  43. package/server-managed/comparison.ts +3 -5
  44. package/server-managed/config.ts +1 -2
  45. package/server-managed/db-methods.ts +163 -244
  46. package/server-managed/db-neon.ts +82 -178
  47. package/server-managed/db-schema.ts +15 -0
  48. package/server-managed/db.ts +5 -11
  49. package/server-managed/dependabot-access.ts +2 -1
  50. package/server-managed/dependabot-alerts.ts +7 -12
  51. package/server-managed/dependency-review-comments.ts +7 -13
  52. package/server-managed/dependency-reviews.ts +14 -15
  53. package/server-managed/github-accounts.ts +4 -5
  54. package/server-managed/github-actions.ts +6 -6
  55. package/server-managed/github-app.ts +19 -48
  56. package/server-managed/github-graphql.ts +5 -2
  57. package/server-managed/github-issue-links.ts +62 -42
  58. package/server-managed/github-issue-oauth.ts +7 -24
  59. package/server-managed/github-issues.ts +9 -7
  60. package/server-managed/github-link-oauth.ts +7 -20
  61. package/server-managed/github-oauth.ts +38 -12
  62. package/server-managed/github-pulls.ts +37 -26
  63. package/server-managed/github-requests.ts +21 -8
  64. package/server-managed/github-values.ts +26 -0
  65. package/server-managed/history-windows.ts +7 -7
  66. package/server-managed/http.ts +495 -554
  67. package/server-managed/index.ts +6 -6
  68. package/server-managed/link-reports.ts +6 -19
  69. package/server-managed/lockfile-scope.ts +1 -1
  70. package/server-managed/management.ts +14 -3
  71. package/server-managed/npm-delta.ts +22 -57
  72. package/server-managed/npm-insights.ts +31 -26
  73. package/server-managed/npm-kept.ts +9 -8
  74. package/server-managed/npm-loads.ts +2 -7
  75. package/server-managed/npm-manifest.ts +6 -4
  76. package/server-managed/npm-packages.ts +17 -9
  77. package/server-managed/npm-patch.ts +8 -16
  78. package/server-managed/npm-provenance.ts +12 -8
  79. package/server-managed/npm-risk.ts +9 -7
  80. package/server-managed/object-storage-disk.ts +2 -3
  81. package/server-managed/object-storage-vercel.ts +15 -11
  82. package/server-managed/object-storage.ts +7 -0
  83. package/server-managed/pretty-print.ts +8 -19
  84. package/server-managed/public-workspace.ts +50 -46
  85. package/server-managed/pull-comment-reviews.ts +2 -2
  86. package/server-managed/pull-dependencies.ts +20 -31
  87. package/server-managed/pull-dependency-reviews.ts +17 -24
  88. package/server-managed/pull-reviews.ts +4 -7
  89. package/server-managed/queue.ts +14 -0
  90. package/server-managed/release-commits.ts +9 -8
  91. package/server-managed/rename-diff.ts +17 -60
  92. package/server-managed/report-migration.ts +5 -8
  93. package/server-managed/report-sources.ts +6 -10
  94. package/server-managed/report-store.ts +2 -10
  95. package/server-managed/repository-actions.ts +7 -8
  96. package/server-managed/repository-agents.ts +31 -57
  97. package/server-managed/repository-aliases.ts +3 -9
  98. package/server-managed/repository-browser.ts +18 -16
  99. package/server-managed/repository-changes.ts +33 -37
  100. package/server-managed/repository-code.ts +5 -5
  101. package/server-managed/repository-dependency-reviews.ts +6 -13
  102. package/server-managed/repository-discovery.ts +2 -1
  103. package/server-managed/repository-history.ts +47 -51
  104. package/server-managed/repository-issues.ts +59 -30
  105. package/server-managed/repository-pulls.ts +7 -12
  106. package/server-managed/repository-pulse.ts +51 -45
  107. package/server-managed/repository-risk-assess.ts +5 -2
  108. package/server-managed/repository-risk-audit.ts +1 -1
  109. package/server-managed/repository-risk-read.ts +6 -6
  110. package/server-managed/repository-risk.ts +32 -40
  111. package/server-managed/repository-squashes.ts +7 -15
  112. package/server-managed/request-timing.ts +1 -1
  113. package/server-managed/sql.ts +18 -0
  114. package/server-managed/storage-encryption.ts +5 -7
  115. package/server-managed/team-app.ts +4 -7
  116. package/server-managed/team-npm-scopes.ts +5 -8
  117. package/server-managed/team-reports.ts +15 -15
  118. package/server-managed/type-only-proof.js +108 -0
  119. package/server-managed/type-only-worker.js +26 -14
  120. package/server-managed/type-only.ts +72 -62
  121. package/server-managed/uploads.ts +3 -3
  122. package/server-managed/upstream-cache.ts +5 -7
  123. package/server-managed/worker-turns.ts +76 -0
  124. package/server-managed/workspace-shares.ts +1 -2
  125. package/out/chunk-2SY4PYUQ.js +0 -4
  126. package/out/chunk-4HI2MSAV.js +0 -17
  127. package/out/chunk-4TQKM3JC.js +0 -42
  128. package/out/chunk-EEQHVKR3.js +0 -1
  129. package/out/chunk-HNQNDNIE.js +0 -12
  130. package/out/chunk-OFPDMZJF.js +0 -244
  131. package/out/chunk-OQRSIBSC.js +0 -1
  132. package/out/chunk-YTO6AQZM.js +0 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/triage",
3
- "version": "1.0.0-alpha.60",
3
+ "version": "1.0.0-alpha.61",
4
4
  "description": "Client & relay server for triaging of automated reports",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": {
@@ -140,6 +140,7 @@
140
140
  "server-managed/github-link-oauth.ts",
141
141
  "server-managed/github-links.ts",
142
142
  "server-managed/github-users.ts",
143
+ "server-managed/github-values.ts",
143
144
  "server-managed/github-oauth.ts",
144
145
  "server-managed/github-pulls.ts",
145
146
  "server-managed/github-requests.ts",
@@ -233,10 +234,12 @@
233
234
  "server-managed/team-reports.ts",
234
235
  "server-managed/triage-response.ts",
235
236
  "server-managed/type-only.ts",
237
+ "server-managed/type-only-proof.js",
236
238
  "server-managed/type-only-worker.js",
237
239
  "server-managed/uploads.ts",
238
240
  "server-managed/view-as.ts",
239
241
  "server-managed/upstream-cache.ts",
242
+ "server-managed/worker-turns.ts",
240
243
  "server-managed/workspace-shares.ts",
241
244
  "server-common/database-config.ts",
242
245
  "server-common/initialize.ts",
@@ -424,16 +427,16 @@
424
427
  "typescript": "^7.0.2"
425
428
  },
426
429
  "dependencies": {
427
- "@exodus/stasis": "1.0.0-rc.1",
428
- "@exodus/stasis-core": "1.0.0-rc.1",
430
+ "@exodus/stasis": "1.0.0-rc.3",
431
+ "@exodus/stasis-core": "1.0.0-rc.3",
429
432
  "@preventive/archive": "^1.4.1",
430
433
  "@preventive/compare": "^1.2.11",
431
- "@preventive/diff": "^1.1.0",
434
+ "@preventive/diff": "^1.1.1",
432
435
  "@preventive/lockfile": "^1.3.0",
433
436
  "@preventive/publishers": "^1.1.0",
434
437
  "@preventive/report": "^1.0.1",
435
438
  "@preventive/sourcemap": "1.0.0-alpha.1",
436
- "@preventive/upstream": "^1.7.0",
439
+ "@preventive/upstream": "^1.8.0",
437
440
  "css-tree": "^3.2.1",
438
441
  "oxc-minify": "^0.152.0",
439
442
  "oxc-parser": "^0.152.0",
@@ -457,5 +460,5 @@
457
460
  "optional": true
458
461
  }
459
462
  },
460
- "packageManager": "pnpm@10.33.4+sha512.1c67b3b359b2d408119ba1ed289f34b8fc3c6873412bec6fd264fbdc82489e510fcbecb9ce9d22dae7f3b76269d8441046014bdca53b9979cd7a561ad631b800"
463
+ "packageManager": "pnpm@12.17.0+sha512.b8d223ebec04b580a89ed206daa71d1bccb6a1ee1d52efa95cc3b0db75271561df8f0d8e2c43add39c5ec08018af7a8a95108e7090f95a29f88727b7a40fd53d"
461
464
  }
@@ -3,7 +3,8 @@
3
3
  // legacy entries. Never copy annotation bodies or credentials into this feed.
4
4
  import { randomUUID } from 'node:crypto'
5
5
  import type { DatabaseSync } from 'node:sqlite'
6
- import type { ManagedSql } from './sql.ts'
6
+ import { type ManagedSql, sqliteTransaction } from './sql.ts'
7
+ import { inUserTeamScope } from './db-schema.ts'
7
8
 
8
9
  export interface ActivityInput {
9
10
  kind: 'access' | 'repository' | 'visibility' | 'delete'
@@ -60,57 +61,45 @@ const triageFields = `'triage:' || e.seq AS id, 'triage' AS kind,
60
61
  COALESCE(u.login, e.actor_login) AS actor, e.actor_id AS actorId,
61
62
  CASE WHEN e.color IS NULL AND e.triage IS NULL AND e.comment IS NULL AND e.fix IS NULL AND e.flagged IS NULL
62
63
  THEN 'cleared triage' ELSE 'updated triage' END AS action`
63
- const triage = `SELECT ${triageFields}, e.repo, e.report_id AS reportId, e.report, e.finding_id AS finding, e.at
64
- FROM managed_finding_triage_event e LEFT JOIN managed_user u ON u.id = e.actor_id`
65
64
  const commentFields = `'comment:' || e.seq AS id, 'triage' AS kind,
66
65
  COALESCE(u.login, e.actor_login) AS actor, e.actor_id AS actorId, e.action`
67
- const comments = `SELECT ${commentFields}, e.repo, e.report_id AS reportId, e.report, e.finding_id AS finding, e.at
68
- FROM managed_finding_comment_event e LEFT JOIN managed_user u ON u.id = e.actor_id`
69
- const adminSource = `${triage} UNION ALL ${comments} UNION ALL
66
+ // The events of a finding trail (`table`), with `fields` and the context each
67
+ // recorded.
68
+ const recordedEvents = (fields: string, table: string) => `SELECT ${fields}, e.repo, e.report_id AS reportId, e.report, e.finding_id AS finding, e.at
69
+ FROM ${table} e LEFT JOIN managed_user u ON u.id = e.actor_id`
70
+ const adminSource = `${recordedEvents(triageFields, 'managed_finding_triage_event')}
71
+ UNION ALL ${recordedEvents(commentFields, 'managed_finding_comment_event')} UNION ALL
70
72
  SELECT id, kind, actor, actor_id AS actorId, action, repo, report_id AS reportId, report, NULL AS finding, at FROM managed_activity`
71
- // Keep the finite set of accessible findings outside the indexed event
72
- // lookup. Scanning all events against json_each for every row is quadratic.
73
- const managerSource = `SELECT ${triageFields},
73
+ // The events of the accessible findings in a finding trail (`table`), with
74
+ // `fields` and the context the server gives each finding. Keep the finite
75
+ // set of accessible findings outside the indexed event lookup. Scanning all
76
+ // events against json_each for every row is quadratic.
77
+ const contextEvents = (fields: string, table: string) => `SELECT ${fields},
74
78
  json_extract(c.value, '$.repo') AS repo, json_extract(c.value, '$.reportId') AS reportId,
75
79
  json_extract(c.value, '$.report') AS report, e.finding_id AS finding, e.at
76
80
  FROM json_each(:contexts) c
77
- CROSS JOIN managed_finding_triage_event e ON e.finding_id = json_extract(c.value, '$.finding')
78
- LEFT JOIN managed_user u ON u.id = e.actor_id
79
- UNION ALL SELECT ${commentFields},
80
- json_extract(c.value, '$.repo') AS repo, json_extract(c.value, '$.reportId') AS reportId,
81
- json_extract(c.value, '$.report') AS report, e.finding_id AS finding, e.at
82
- FROM json_each(:contexts) c
83
- CROSS JOIN managed_finding_comment_event e ON e.finding_id = json_extract(c.value, '$.finding')
84
- LEFT JOIN managed_user u ON u.id = e.actor_id
81
+ CROSS JOIN ${table} e ON e.finding_id = json_extract(c.value, '$.finding')
82
+ LEFT JOIN managed_user u ON u.id = e.actor_id`
83
+ const managerSource = `${contextEvents(triageFields, 'managed_finding_triage_event')}
84
+ UNION ALL ${contextEvents(commentFields, 'managed_finding_comment_event')}
85
85
  UNION ALL SELECT a.id, a.kind, a.actor, a.actor_id AS actorId,
86
86
  CASE WHEN a.kind = 'repository' THEN 'changed a report repository assignment' ELSE a.action END AS action,
87
87
  p.full_name AS repo, r.id AS reportId, r.filename AS report, NULL AS finding, a.at
88
88
  FROM managed_activity a JOIN managed_report r ON r.id = a.report_id
89
89
  LEFT JOIN managed_selected_repo p ON p.repo_id = r.repo_id
90
- WHERE EXISTS (
91
- SELECT 1 FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
92
- JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
93
- WHERE tu.user_id = :userId AND tr.repo_id = r.repo_id AND ${withinTeamPath('r.repo_directory')}
94
- )
90
+ WHERE ${inUserTeamScope(':userId', 'r')}
95
91
  UNION ALL SELECT a.id, a.kind, a.actor, a.actor_id AS actorId,
96
92
  CASE WHEN a.kind = 'repository' THEN 'changed a bundle repository assignment' ELSE a.action END AS action,
97
93
  p.full_name AS repo, NULL AS reportId, b.filename AS report, NULL AS finding, a.at
98
94
  FROM managed_activity a JOIN managed_bundle b ON b.id = a.bundle_id
99
95
  LEFT JOIN managed_selected_repo p ON p.repo_id = b.repo_id
100
- WHERE a.report_id IS NULL AND EXISTS (
101
- SELECT 1 FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
102
- JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
103
- WHERE tu.user_id = :userId AND tr.repo_id = b.repo_id AND ${withinTeamPath('b.repo_directory')}
104
- )
96
+ WHERE a.report_id IS NULL AND ${inUserTeamScope(':userId', 'b')}
105
97
  UNION ALL SELECT a.id, a.kind, a.actor, a.actor_id AS actorId, a.action, a.repo, a.report_id AS reportId,
106
98
  a.report, NULL AS finding, a.at FROM managed_activity a
107
99
  WHERE a.kind = 'delete' AND (a.report_id IS NOT NULL OR a.bundle_id IS NOT NULL)
108
100
  AND NOT EXISTS (SELECT 1 FROM managed_report WHERE id = a.report_id)
109
101
  AND NOT EXISTS (SELECT 1 FROM managed_bundle WHERE id = a.bundle_id)
110
- AND EXISTS (SELECT 1 FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
111
- JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
112
- WHERE tu.user_id = :userId AND tr.repo_id = a.repo_id
113
- AND ${withinTeamPath('a.repo_directory')})`
102
+ AND ${inUserTeamScope(':userId', 'a')}`
114
103
 
115
104
  export const ACTIVITY_SCHEMA = `
116
105
  CREATE TABLE IF NOT EXISTS managed_activity (
@@ -160,9 +149,7 @@ export function activityMethods(db: ManagedSql): ActivityStore {
160
149
  const manager = activityStatements(db, managerSource)
161
150
  const reports = db.prepare(`SELECT r.id AS reportId, r.filename AS report, p.full_name AS repo
162
151
  FROM managed_report r JOIN managed_selected_repo p ON p.repo_id = r.repo_id
163
- WHERE EXISTS (SELECT 1 FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
164
- JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
165
- WHERE tu.user_id = ? AND tr.repo_id = r.repo_id AND ${withinTeamPath('r.repo_directory')})
152
+ WHERE ${inUserTeamScope('?', 'r')}
166
153
  ORDER BY r.uploaded_at DESC, r.id`)
167
154
  return {
168
155
  async recordActivity(entry, at) {
@@ -226,17 +213,11 @@ function activityStatements(db: ManagedSql, source: string) {
226
213
  }
227
214
  }
228
215
 
229
- // Literal path comparison preserves separators, case and SQL wildcard chars.
230
- function withinTeamPath(path: string): string {
231
- return `(tr.path IS NULL OR tr.path = '' OR ${path} = tr.path OR substr(${path}, 1, length(tr.path) + 1) = tr.path || '/')`
232
- }
233
-
234
216
  function migrateActivityScope(db: DatabaseSync): void {
235
217
  const columns = new Set((db.prepare('PRAGMA table_info(managed_activity)').all() as { name: string }[]).map(column => column.name))
236
218
  const missing = [['bundle_id', 'TEXT'], ['repo_id', 'INTEGER'], ['repo_directory', 'TEXT'], ['actor_id', 'TEXT']].filter(([name]) => !columns.has(name!))
237
219
  if (missing.length === 0) return
238
- db.exec('BEGIN')
239
- try {
220
+ sqliteTransaction(db, 'BEGIN', () => {
240
221
  for (const [name, type] of missing) db.exec(`ALTER TABLE managed_activity ADD COLUMN ${name} ${type}`)
241
222
  if (!columns.has('bundle_id') || !columns.has('actor_id')) {
242
223
  db.exec('DROP TRIGGER IF EXISTS managed_report_activity; DROP TRIGGER IF EXISTS managed_bundle_activity;')
@@ -253,6 +234,5 @@ function migrateActivityScope(db: DatabaseSync): void {
253
234
  }
254
235
  // Legacy deletions/assignments without a durable target/scope remain
255
236
  // admin-only; neither filenames nor repository names authorize access.
256
- db.exec('COMMIT')
257
- } catch (err) { db.exec('ROLLBACK'); throw err }
237
+ })
258
238
  }
@@ -19,8 +19,8 @@ const REBASE_SKEW_MS = 10 * 60_000
19
19
  // Commits tab tells those squashed too, http.ts pulseMerges; none of one
20
20
  // kept before numbers were), and one rebased so (`pullRebases`), for the
21
21
  // commits pushed to the branch directly to be told (directCommits).
22
- export interface AgentMerges { merges: [string, number][]; rebases: Rebase[]; through: number | null; reach?: number
23
- next: { after: string; from: number; stop: number; read: number; to?: number } | null; pulls?: [sha: string, at: number, number?: number][]; pullRebases?: Rebase[] }
22
+ export interface AgentMerges extends Pick<PullList, 'through' | 'reach' | 'next'> { merges: [string, number][]; rebases: Rebase[]
23
+ pulls?: [sha: string, at: number, number?: number][]; pullRebases?: Rebase[] }
24
24
  // A pull request rebased onto the branch: its last commit there, when it was
25
25
  // merged, its latest commits' subjects, the oldest first, and how many more
26
26
  // it had than those read (`more`).
@@ -1,5 +1,5 @@
1
1
  // Logical upload-store interfaces shared by disk and Vercel storage.
2
- import type { Buffer } from 'node:buffer'
2
+ import { Buffer } from 'node:buffer'
3
3
  import type { Readable } from 'node:stream'
4
4
 
5
5
  export interface OpenedBlob {
@@ -15,3 +15,12 @@ export interface BlobStore {
15
15
  open(id: string): Promise<OpenedBlob | null>
16
16
  delete(id: string): Promise<void>
17
17
  }
18
+
19
+ // A blob's bytes whole, its stream closed however the read ends.
20
+ export async function readBytes(stored: OpenedBlob): Promise<Buffer> {
21
+ const parts: Buffer[] = []
22
+ try {
23
+ for await (const part of stored.stream) parts.push(Buffer.from(part))
24
+ return Buffer.concat(parts)
25
+ } finally { stored.stream.destroy() }
26
+ }
@@ -1,10 +1,11 @@
1
1
  import { type Advisory, type CacheStore, type Package, advisories } from '@preventive/upstream/advisories.js'
2
2
  import { type Client, HttpError, createClient } from '@preventive/upstream/github.js'
3
+ import { USER_AGENT } from './github-requests.ts'
3
4
 
4
5
  export const ADVISORIES_TIMEOUT_MS = 30_000
5
6
 
6
7
  function advisoryGithubClient(token: string | null, signal: AbortSignal): Client {
7
- const authenticated = createClient({ token, userAgent: 'deepview-triage' })
8
+ const authenticated = createClient({ token, userAgent: USER_AGENT })
8
9
  let client = authenticated
9
10
  // Published advisories, and whether a repository is public, remain
10
11
  // readable after a token is revoked. Reuse anonymous access for subsequent
@@ -14,7 +15,7 @@ function advisoryGithubClient(token: string | null, signal: AbortSignal): Client
14
15
  try { return await ask(current) } catch (error) {
15
16
  if (token === null || current !== authenticated || !(error instanceof HttpError) || error.status !== 401) throw error
16
17
  signal.throwIfAborted()
17
- if (client === authenticated) client = createClient({ token: null, userAgent: 'deepview-triage' })
18
+ if (client === authenticated) client = createClient({ token: null, userAgent: USER_AGENT })
18
19
  return await ask(client)
19
20
  }
20
21
  }
@@ -3,7 +3,7 @@ import { packageRepo } from '@exodus/stasis-core/bundle-util'
3
3
  import type { Package } from '@preventive/upstream/advisories.js'
4
4
  import type { BundleDetails } from '../common/bundle-metadata.js'
5
5
 
6
- export interface SkippedAdvisoryPackage {
6
+ interface SkippedAdvisoryPackage {
7
7
  ecosystem: string
8
8
  name: string
9
9
  version: string
@@ -86,7 +86,7 @@ async function projectDirectory(input, github, client) {
86
86
  // Input validation permits either JS/TS entries or Solidity entries, never a mix.
87
87
  const manifests = input.entries[0].endsWith('.sol') ? ['foundry.toml', 'soldeer.toml', 'soldeer.lock'] : ['package.json']
88
88
  if (!input.directory) return ''
89
- for (let directory = input.directory; ; directory = posix.dirname(directory).replace(/^\.$/u, '')) {
89
+ for (let directory = input.directory; ; directory = parentOf(directory)) {
90
90
  const entries = await directoryListing(input, github, client, directory)
91
91
  if (entries?.some(entry => manifests.includes(entry.path) && regularFile(entry))) return directory
92
92
  if (!directory) return input.directory
@@ -104,15 +104,24 @@ async function packageName(input, github, project, bundle, client) {
104
104
  return typeof name === 'string' ? name : null
105
105
  }
106
106
 
107
- export async function buildStasisBundle({ input, github, token, maxBytes, scopes, cacheDir = null }, client = createClient({ token }), progress = () => {}) {
107
+ // `note` is told what the build log keeps of a build beside its stages: the
108
+ // directory Stasis builds from (`project`), and each tree it downloads of the
109
+ // repo (`download`), the whole repo's or a directory's, and its bytes.
110
+ export async function buildStasisBundle({ input, github, token, maxBytes, scopes, cacheDir = null }, client = createClient({ token }), progress = () => {}, note = () => {}) {
108
111
  const allowed = path => scopes.some(scope => !scope || path === scope || path.startsWith(scope + '/'))
109
112
  // Reuse these immutable listings when Stasis discovers the lockfile root.
110
113
  const listings = new Map()
114
+ const downloaded = (tree, read) => async options => {
115
+ const bytes = await read(options)
116
+ note('download', { tree, bytes: bytes.length })
117
+ return bytes
118
+ }
111
119
  const buildClient = { ...client, listRepoDir(options) {
112
120
  const key = JSON.stringify([options.repo, options.sha, options.directory ?? ''])
113
121
  if (!listings.has(key)) listings.set(key, client.listRepoDir(options))
114
122
  return listings.get(key)
115
- } }
123
+ }, getRepoTarball: downloaded('repo', options => client.getRepoTarball(options)),
124
+ getRepoTreeTarball: downloaded('directory', options => client.getRepoTreeTarball(options)) }
116
125
  // Upstream's disk cache keeps the npm tarballs and version documents, and
117
126
  // the repo's tree, in `cacheDir`; without one (Vercel), nothing is kept on
118
127
  // disk. This fresh worker inherits no application credentials but NPM_TOKEN.
@@ -134,6 +143,7 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
134
143
  // config's generatePrisma leaves it.
135
144
  const { packageManager, ...options } = input.options
136
145
  const named = packageManager !== undefined && !namesLockfiles(await configText(project) ?? '{}')
146
+ note('project', { project, configured: configured !== null, ...(named && { packageManager }) })
137
147
  const { bundle } = await buildGitHubBundle({
138
148
  github, sha: input.commit, directory: project || undefined,
139
149
  entries: input.entries.map(entry => posix.relative(project || '.', entry)),
@@ -169,7 +179,10 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
169
179
  // the config's or an entry's, is the policy's; one it can't read, build with
170
180
  // its options, or lay out the lockfiles it names of, is the config's. A build
171
181
  // the repository's stasis.lock.json disagrees with, or that its lock mode
172
- // holds to one that isn't there, is the stasis.lock.json's.
182
+ // holds to one that isn't there, is the stasis.lock.json's. A commit Stasis
183
+ // finds in the history of none of the repo's branches or tags (a fork's,
184
+ // which GitHub serves through the repo's name too), or can't tell of past its
185
+ // branches compared, isn't the repo's own.
173
186
  export function buildErrorCode(error, message) {
174
187
  if (['build-scope', 'too-large', 'bad-conditions', 'config-invalid', 'config-mixed', 'config-conditions'].includes(message)) return message
175
188
  if (error instanceof HttpError) return error.status === 429 ? 'github-rate-limited' : 'github-build-failed'
@@ -178,19 +191,39 @@ export function buildErrorCode(error, message) {
178
191
  if (/\bstasis\.config\.json(?:: entries .*?)?: (?:allowed|disallowed)(?:Paths|Modules) (?:refuses|does not allow|allows none of) /u.test(message)) return 'config-policy'
179
192
  if (/\bstasis\.config\.json(?: is not valid JSON|: |'s lockfiles )/u.test(message)) return 'config-invalid'
180
193
  if (/\bstasis\.lock\.json(?::| isn't there,| \(lock = )/u.test(message)) return 'stasis-lock'
194
+ if (/ is in the history of no branch or tag of | is at no tag or branch head of .+ nor in its default branch's history/u.test(message)) return 'commit-not-own'
181
195
  return /no packageManager given|lockfile installs|no (?:pnpm-lock\.yaml|yarn\.lock|package-lock\.json|soldeer\.lock) found in /u.test(message) ? 'build-lockfile' : 'build-failed'
182
196
  }
183
197
 
198
+ // The status a failed build answers with, by its code: 422 for any other.
199
+ const FAILED_STATUS = new Map([['too-large', 413], ['build-scope', 403], ['bad-conditions', 400]])
200
+
201
+ // The worker's memory as the build log keeps it, in MiB: the process's
202
+ // resident set (the server's with it), and this worker's own heap, used (what
203
+ // is garbage not yet collected among it) and held, what is bound to its
204
+ // objects outside it, and its ArrayBuffers.
205
+ const MEMORY_EVERY_MS = 5000
206
+ function memoryOf() {
207
+ const { rss, heapUsed, heapTotal, external, arrayBuffers } = process.memoryUsage()
208
+ const mib = bytes => Math.round(bytes / 1024 ** 2)
209
+ return { rssMib: mib(rss), heapUsedMib: mib(heapUsed), heapTotalMib: mib(heapTotal), externalMib: mib(external), arrayBuffersMib: mib(arrayBuffers) }
210
+ }
211
+
184
212
  if (parentPort && workerData?.type === 'managed-bundle-build') {
185
213
  // Send diagnostics to the request's parent thread, which writes them before
186
214
  // returning the HTTP response. Worker stdout can be lost on termination.
215
+ // Its memory too, at each stage and every MEMORY_EVERY_MS, so that the log
216
+ // tells where it grew of a worker terminated past its heap.
187
217
  const send = (message, transfer = []) => {
188
218
  // Node worker messages have no browser target origin.
189
219
  // oxlint-disable-next-line unicorn/require-post-message-target-origin
190
220
  parentPort.postMessage(message, transfer)
191
221
  }
222
+ const reporting = setInterval(() => send({ type: 'memory', memory: memoryOf() }), MEMORY_EVERY_MS)
223
+ reporting.unref()
192
224
  try {
193
- const built = await buildStasisBundle(workerData, undefined, stage => send({ type: 'progress', stage }))
225
+ const built = await buildStasisBundle(workerData, undefined, stage => send({ type: 'progress', stage, memory: memoryOf() }),
226
+ (event, details) => send({ type: 'note', event, details }))
194
227
  // The bytes handed over rather than copied, where they alone fill their
195
228
  // buffer (a small one may share Node's pool, which can't be moved).
196
229
  const { bytes } = built
@@ -198,6 +231,8 @@ if (parentPort && workerData?.type === 'managed-bundle-build') {
198
231
  } catch (error) {
199
232
  const diagnostic = bundleBuildDiagnostic(error, workerData.token)
200
233
  const code = buildErrorCode(error, diagnostic.message)
201
- send({ error: code, status: code === 'too-large' ? 413 : code === 'build-scope' ? 403 : code === 'bad-conditions' ? 400 : 422, diagnostic })
234
+ send({ error: code, status: FAILED_STATUS.get(code) ?? 422, diagnostic, memory: memoryOf() })
235
+ } finally {
236
+ clearInterval(reporting)
202
237
  }
203
238
  }
@@ -13,7 +13,7 @@ export class BundleBuildError extends Error {
13
13
  constructor(status: number, code: string) { super(code); this.status = status; this.code = code }
14
14
  }
15
15
 
16
- export interface BundleBuildInput {
16
+ interface BundleBuildInput {
17
17
  repoId: number
18
18
  commit: string
19
19
  entries: string[]
@@ -105,8 +105,8 @@ export function githubBundleFilename(github: string, directory: string, commit:
105
105
  return `${repo}.${dir}${tail}`
106
106
  }
107
107
 
108
- export interface BuiltBundle { bytes: Buffer; directory: string; filename: string }
109
- export interface BuildRequest {
108
+ interface BuiltBundle { bytes: Buffer; directory: string; filename: string }
109
+ interface BuildRequest {
110
110
  input: BundleBuildInput; github: string; token: string | null; maxBytes: number; scopes: (string | null)[]
111
111
  // Upstream's disk cache for what a build fetches (setCacheDir), or null for
112
112
  // none, as on Vercel. Resolved here: the worker's env holds NPM_TOKEN alone.
@@ -128,7 +128,8 @@ const MAX_ACTIVE_BUILDS = 1
128
128
  // terminates the worker (build-memory), not the process.
129
129
  const RESERVED_MIB = 512
130
130
  const MIN_BUILD_HEAP_MIB = 512
131
- export function buildHeapLimitMib(memory = Math.min(process.constrainedMemory() || Infinity, totalmem())): number {
131
+ const processMemory = () => Math.min(process.constrainedMemory() || Infinity, totalmem())
132
+ export function buildHeapLimitMib(memory = processMemory()): number {
132
133
  return Math.max(MIN_BUILD_HEAP_MIB, Math.floor(memory / 1024 ** 2) - RESERVED_MIB)
133
134
  }
134
135
 
@@ -171,8 +172,11 @@ export async function buildRepositoryBundle(userId: string, request: BuildReques
171
172
  let stage: BundleBuildStage = 'worker-start'
172
173
  const buildId = randomUUID(), started = performance.now()
173
174
  const heapLimitMib = buildHeapLimitMib()
175
+ // How this Node was built, as it decides what a heap holds the same objects in.
176
+ const { v8_enable_pointer_compression: pointerCompression, v8_enable_sandbox: v8Sandbox } = process.config.variables as Record<string, unknown>
174
177
  const context = { buildId, repoId: request.input.repoId, github: request.github, commit: request.input.commit,
175
- directory: request.input.directory, entryCount: request.input.entries.length, node: process.version, heapLimitMib }
178
+ directory: request.input.directory, entryCount: request.input.entries.length, node: process.version, v8: process.versions.v8, pointerCompression, v8Sandbox,
179
+ memoryMib: Math.round(processMemory() / 1024 ** 2), heapLimitMib }
176
180
  const log = (event: string, details: Record<string, unknown> = {}) => {
177
181
  const write = event === 'failed' ? console.error : console.info
178
182
  write('managed-bundle-build:', JSON.stringify({ ...context, workerUrl: workerUrl?.href, event, stage, elapsedMs: Math.round(performance.now() - started), ...details }))
@@ -199,13 +203,17 @@ export async function buildRepositoryBundle(userId: string, request: BuildReques
199
203
  reject(new BundleBuildError(status, code))
200
204
  }
201
205
  const timer = setTimeout(() => fail(504, 'build-timeout'), BUNDLE_BUILD_TIMEOUT_MS)
202
- const abort = () => fail(signal.reason instanceof BundleBuildError ? signal.reason.status : 499,
203
- signal.reason instanceof BundleBuildError ? signal.reason.code : 'build-cancelled')
206
+ const abort = () => signal.reason instanceof BundleBuildError ? fail(signal.reason.status, signal.reason.code) : fail(499, 'build-cancelled')
204
207
  signal.addEventListener('abort', abort, { once: true })
205
- running.on('message', (message: Omit<BuiltBundle, 'bytes'> & { bytes: Uint8Array; type?: string; stage?: BundleBuildStage; error?: string; status?: number; diagnostic?: BundleBuildDiagnostic }) => {
208
+ // The worker's memory and notes are the log's alone: the response tells
209
+ // the bundle, or the error's code, and nothing of them.
210
+ running.on('message', (message: Omit<BuiltBundle, 'bytes'> & { bytes: Uint8Array; type?: string; stage?: BundleBuildStage; error?: string; status?: number;
211
+ diagnostic?: BundleBuildDiagnostic; memory?: Record<string, number>; event?: string; details?: Record<string, unknown> }) => {
206
212
  if (settled) return
207
- if (message.type === 'progress' && message.stage) { stage = message.stage; log('progress'); return }
208
- if (message.error) { fail(message.status ?? 422, message.error, { diagnostic: message.diagnostic }); return }
213
+ if (message.type === 'progress' && message.stage) { stage = message.stage; log('progress', { memory: message.memory }); return }
214
+ if (message.type === 'memory') { log('memory', { memory: message.memory }); return }
215
+ if (message.type === 'note' && typeof message.event === 'string') { log(message.event, message.details ?? {}); return }
216
+ if (message.error) { fail(message.status ?? 422, message.error, { diagnostic: message.diagnostic, memory: message.memory }); return }
209
217
  settled = true
210
218
  cleanup()
211
219
  log('completed', { byteSize: message.bytes.length })
@@ -9,12 +9,12 @@ import { bundleReasons } from '../common/bundle-reasons.js'
9
9
  import { sourcemapEdges } from '../common/bundle-sourcemap.js'
10
10
  import { type BundleAdvisoryInventory, bundleAdvisoryInventory } from './bundle-advisory-inventory.ts'
11
11
  import { decodeUtf8 } from '../common/utf8.js'
12
- import type { OpenedBlob } from './blob-store.ts'
12
+ import { type OpenedBlob, readBytes } from './blob-store.ts'
13
13
  import type { BundleStore } from './bundle-store.ts'
14
14
  import { encodeBrotli } from './brotli.ts'
15
15
  import type { ManagedBundle, ManagedDb } from './db.ts'
16
16
  import { CacheMissError } from './cache-storage.ts'
17
- import { SUMMARY_FILENAME, createBundleSummaryCache } from './bundle-summary-cache.ts'
17
+ import { SUMMARY_FILENAME, createBundleSummaryCache, readCachedBytes } from './bundle-summary-cache.ts'
18
18
 
19
19
  const decompress = promisify(brotliDecompress)
20
20
  const MAX_DECODED_BYTES = 512 * 1024 * 1024
@@ -60,28 +60,25 @@ function encodePackageInventory(details: BundleDetails): Buffer {
60
60
  parts.push(part)
61
61
  return true
62
62
  }
63
- function entries(rows: unknown[]) {
64
- if (!append('[')) return false
63
+ // `items` as `write` writes each, a comma apart, between `open` and
64
+ // `close`: false once past the budget, as `append` is.
65
+ function list<T>(open: string, items: Iterable<T>, write: (item: T) => boolean, close: string) {
66
+ if (!append(open)) return false
65
67
  let first = true
66
- for (const row of rows) {
67
- if (!append(`${first ? '' : ','}${JSON.stringify(row)}`)) return false
68
+ for (const item of items) {
69
+ if (!append(first ? '' : ',') || !write(item)) return false
68
70
  first = false
69
71
  }
70
- return append(']')
72
+ return append(close)
71
73
  }
74
+ const rows = (items: unknown[]) => list('[', items, row => append(JSON.stringify(row)), ']')
72
75
  function inventory(paths: Set<string> | null) {
73
76
  const { packages, skipped } = bundleAdvisoryInventory(details, paths)
74
- return append('{"packages":') && entries(packages) && append(',"skipped":') && entries(skipped) && append('}')
77
+ return append('{"packages":') && rows(packages) && append(',"skipped":') && rows(skipped) && append('}')
75
78
  }
76
- append('{"all":')
77
- if (!inventory(null) || !append(',"reasons":{')) return Buffer.from('null')
78
- let first = true
79
- for (const [reason, paths] of bundleReasons(details)) {
80
- if (!append(`${first ? '' : ','}${JSON.stringify(reason)}:`) || !inventory(paths)) return Buffer.from('null')
81
- first = false
82
- }
83
- if (!append('}}')) return Buffer.from('null')
84
- return Buffer.from(parts.join(''))
79
+ const whole = append('{"all":') && inventory(null)
80
+ && list(',"reasons":{', bundleReasons(details), ([reason, paths]) => append(`${JSON.stringify(reason)}:`) && inventory(paths), '}}')
81
+ return Buffer.from(whole ? parts.join('') : 'null')
85
82
  }
86
83
 
87
84
  // What a catalog sends of a bundle before it opens. A Stasis bundle's
@@ -104,9 +101,15 @@ function readSourcemapEdges(details: BundleDetails) {
104
101
  catch (err) { console.warn('managed: sourcemap edges failed:', err) }
105
102
  }
106
103
 
107
- async function build(record: BundleCacheRecord, storage: BundleCacheStorage, db: ManagedDb, store: BundleStore) {
104
+ // As readBundleDetails, thrown where the bundle's bytes are gone.
105
+ async function storedDetails(record: BundleCacheRecord, store: BundleStore) {
108
106
  const details = await readBundleDetails(record, store)
109
107
  if (!details) throw new Error('Bundle bytes unavailable')
108
+ return details
109
+ }
110
+
111
+ async function build(record: BundleCacheRecord, storage: BundleCacheStorage, db: ManagedDb, store: BundleStore) {
112
+ const details = await storedDetails(record, store)
110
113
  readSourcemapEdges(details)
111
114
  const metadata = { ...await createBundleMetadata(details), id: record.id, filename: record.filename }
112
115
  const body = await encodeBrotli(Buffer.from(JSON.stringify(metadata)))
@@ -134,11 +137,7 @@ export function createBundleCache(storage: BundleCacheStorage, db: ManagedDb, st
134
137
  const pending = new Map<string, Promise<void>>()
135
138
  // The database deduplicates by integrity, so each hash has one persistent
136
139
  // bundle/cache directory, shared across teams and repeated uploads.
137
- const summaries = createBundleSummaryCache(storage, async record => {
138
- const details = await readBundleDetails(record, store)
139
- if (!details) throw new Error('Bundle bytes unavailable')
140
- return bundleSummary(details)
141
- }, id => db.getBundle(id))
140
+ const summaries = createBundleSummaryCache(storage, async record => bundleSummary(await storedDetails(record, store)), id => db.getBundle(id))
142
141
  let queue = Promise.resolve()
143
142
  async function ensure(record: BundleCacheRecord): Promise<void> {
144
143
  const existing = pending.get(record.id)
@@ -175,29 +174,18 @@ export function createBundleCache(storage: BundleCacheStorage, db: ManagedDb, st
175
174
  // A sourcemap's edges as its metadata keeps them, read with the parser
176
175
  // once, for a derivative that reads the bundle itself (report previews).
177
176
  async sourcemapEdges(record: ManagedBundle): Promise<BundleDetails['edges']> {
178
- const cached = await openCached(record, filename)
179
- const chunks: Buffer[] = []
180
- try { for await (const chunk of cached.stream) chunks.push(Buffer.from(chunk)) }
181
- finally { cached.stream.destroy() }
182
- const decoded = await decompress(Buffer.concat(chunks), { maxOutputLength: MAX_DECODED_BYTES })
177
+ const decoded = await decompress(await readBytes(await openCached(record, filename)), { maxOutputLength: MAX_DECODED_BYTES })
183
178
  return parseBundleMetadata(JSON.parse(decodeUtf8(decoded)), record.integrity).edges
184
179
  },
185
180
  async advisoryInventory(record: ManagedBundle, reason = ''): Promise<BundleAdvisoryInventory | null | undefined> {
186
181
  if (record.kind !== 'stasis') return { packages: [], skipped: [] }
187
182
  const cached = await openCached(record, packagesFilename)
188
- try {
189
- if (cached.size != null && cached.size > MAX_PACKAGE_INVENTORY_BYTES) return null
190
- const chunks: Buffer[] = []
191
- let size = 0
192
- for await (const chunk of cached.stream) {
193
- size += chunk.length
194
- if (size > MAX_PACKAGE_INVENTORY_BYTES) return null
195
- chunks.push(Buffer.from(chunk))
196
- }
197
- const inventory = JSON.parse(decodeUtf8(Buffer.concat(chunks)))
198
- if (inventory === null) return null
199
- return reason ? (Object.hasOwn(inventory.reasons, reason) ? inventory.reasons[reason] : undefined) : inventory.all
200
- } finally { cached.stream.destroy() }
183
+ if (cached.size != null && cached.size > MAX_PACKAGE_INVENTORY_BYTES) { cached.stream.destroy(); return null }
184
+ const bytes = await readCachedBytes(cached, MAX_PACKAGE_INVENTORY_BYTES)
185
+ if (!bytes) return null
186
+ const inventory = JSON.parse(decodeUtf8(bytes))
187
+ if (inventory === null) return null
188
+ return reason ? (Object.hasOwn(inventory.reasons, reason) ? inventory.reasons[reason] : undefined) : inventory.all
201
189
  },
202
190
  async delete(id: string) {
203
191
  // Call after deleting the row. Waiting prevents an in-flight builder
@@ -1,29 +1,29 @@
1
1
  import type { BundleCache, BundleSummary } from './bundle-cache.ts'
2
2
  import type { AdminBundle, UserTeamBundle } from './db.ts'
3
+ import { eachOf } from './queue.ts'
3
4
 
4
5
  const SUMMARY_READ_CONCURRENCY = 8
6
+ type ListedBundle = AdminBundle | UserTeamBundle
7
+
8
+ // The bundles, one of each content hash.
9
+ const byIntegrity = (bundles: readonly ListedBundle[]) => [...new Map(bundles.map(bundle => [bundle.integrity, bundle])).values()]
5
10
 
6
11
  // Read only existing summaries: cold/malformed bundles must never trigger
7
12
  // parsing or wait for metadata builds before the catalog response is sent.
8
- export async function bundleSummaries(bundles: readonly (AdminBundle | UserTeamBundle)[], cache?: BundleCache) {
13
+ export async function bundleSummaries(bundles: readonly ListedBundle[], cache?: BundleCache) {
9
14
  const summaries = new Map<string, { summary: BundleSummary | null; summaryRetryAt: number | null }>()
10
15
  if (cache) {
11
- const unique = [...new Map(bundles.map(bundle => [bundle.integrity, bundle])).values()]
12
- let next = 0
13
16
  // Cold reads may each access remote storage. Bound those requests as well
14
17
  // as the subsequent backfill, without dropping entries from large catalogs.
15
- await Promise.all(Array.from({ length: Math.min(SUMMARY_READ_CONCURRENCY, unique.length) }, async () => {
16
- while (next < unique.length) {
17
- const bundle = unique[next++]!
18
- summaries.set(bundle.integrity, await cache.summaryStatus(bundle).catch(() => ({ summary: null, summaryRetryAt: null })))
19
- }
20
- }))
18
+ await eachOf(byIntegrity(bundles), SUMMARY_READ_CONCURRENCY, async bundle => {
19
+ summaries.set(bundle.integrity, await cache.summaryStatus(bundle).catch(() => ({ summary: null, summaryRetryAt: null })))
20
+ })
21
21
  }
22
22
  return summaries
23
23
  }
24
24
 
25
25
  // Called after sending the response. Each cache permits one small batch at a
26
26
  // time, deduplicated by content hash, and skips persisted retry-backoff markers.
27
- export async function backfillBundleSummaries(bundles: readonly (AdminBundle | UserTeamBundle)[], cache?: BundleCache) {
28
- await cache?.backfillSummaries([...new Map(bundles.map(bundle => [bundle.integrity, bundle])).values()])
27
+ export async function backfillBundleSummaries(bundles: readonly ListedBundle[], cache?: BundleCache) {
28
+ await cache?.backfillSummaries(byIntegrity(bundles))
29
29
  }