@preventive/triage 1.0.0-alpha.80 → 1.0.0-alpha.82

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 (50) hide show
  1. package/common/code-language.js +14 -0
  2. package/common/managed/routes.js +1 -1
  3. package/out/activity.js +2 -2
  4. package/out/chunk-6WMQVUT2.js +3 -0
  5. package/out/{chunk-5EAVJAD2.js → chunk-CE2FMDK3.js} +1 -1
  6. package/out/{chunk-5QWPKTCE.js → chunk-EIEUTJM4.js} +2 -2
  7. package/out/chunk-FNFWBAJO.js +3 -0
  8. package/out/chunk-KP2XM324.js +6 -0
  9. package/out/{chunk-OWSEQOL5.js → chunk-NH2HDQ5E.js} +1 -1
  10. package/out/{chunk-PTFYDJUP.js → chunk-RAM3GDAD.js} +1 -1
  11. package/out/{chunk-5CJKUV53.js → chunk-SUFRZ5U7.js} +1 -1
  12. package/out/chunk-UP3ADVQN.js +54 -0
  13. package/out/{chunk-JXBRWLMA.js → chunk-W2H4DBZW.js} +1 -1
  14. package/out/chunk-WOCJFOXN.js +1 -0
  15. package/out/{chunk-ITUKKCCK.js → chunk-WOLGZ2PE.js} +1 -1
  16. package/out/{chunk-7YO4QV5P.js → chunk-XHYX3Q34.js} +1 -1
  17. package/out/chunk-Z7KOFS2V.js +266 -0
  18. package/out/{chunk-LBD3M3J6.js → chunk-ZQQALNFP.js} +1 -1
  19. package/out/client-managed-import.js +1 -1
  20. package/out/client-managed.js +30 -30
  21. package/out/compare.js +10 -10
  22. package/out/dialogs.js +5 -5
  23. package/out/graph.js +1 -1
  24. package/out/index.html +10 -10
  25. package/out/prism.js +1 -1
  26. package/out/scan.js +1 -1
  27. package/out/view.css +1 -1
  28. package/out/view.js +8 -8
  29. package/package.json +3 -2
  30. package/risk/files/characters.js +13 -0
  31. package/risk/files/runs-code.js +13 -8
  32. package/risk/files/script.js +15 -7
  33. package/risk/npm/assess.js +1 -1
  34. package/server-managed/activity.ts +24 -2
  35. package/server-managed/avatar-store.ts +8 -0
  36. package/server-managed/db-methods.ts +42 -11
  37. package/server-managed/db-neon.ts +5 -2
  38. package/server-managed/db-schema.ts +10 -2
  39. package/server-managed/db.ts +2 -1
  40. package/server-managed/dependency-review-comments.ts +19 -4
  41. package/server-managed/http.ts +105 -19
  42. package/server-managed/pretty-format.js +1 -1
  43. package/server-managed/repository-browser.ts +2 -2
  44. package/server-managed/team-icons.ts +50 -0
  45. package/out/chunk-5M2X3QPK.js +0 -6
  46. package/out/chunk-DUS5ARE2.js +0 -53
  47. package/out/chunk-GBMAXAYK.js +0 -3
  48. package/out/chunk-MV66NL3G.js +0 -3
  49. package/out/chunk-VZPPX6MV.js +0 -1
  50. package/out/chunk-YKCRCNYZ.js +0 -266
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/triage",
3
- "version": "1.0.0-alpha.80",
3
+ "version": "1.0.0-alpha.82",
4
4
  "description": "Client & relay server for triaging of automated reports",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": {
@@ -238,6 +238,7 @@
238
238
  "server-managed/team-catalog.ts",
239
239
  "server-managed/team-feed.ts",
240
240
  "server-managed/team-npm-scopes.ts",
241
+ "server-managed/team-icons.ts",
241
242
  "server-managed/team-app.ts",
242
243
  "server-managed/team-app-summaries.ts",
243
244
  "server-managed/team-reports.ts",
@@ -457,7 +458,7 @@
457
458
  "@exodus/stasis": "1.0.0-rc.11",
458
459
  "@exodus/stasis-core": "1.0.0-rc.11",
459
460
  "@preventive/archive": "^1.5.0",
460
- "@preventive/compare": "^1.4.0",
461
+ "@preventive/compare": "^1.4.1",
461
462
  "@preventive/diff": "^1.1.1",
462
463
  "@preventive/lockfile": "^1.3.1",
463
464
  "@preventive/publishers": "^1.1.0",
@@ -274,6 +274,19 @@ function runEnd(run, text, at) {
274
274
  if (run.lastIndex - from < STRETCH) return run.lastIndex
275
275
  }
276
276
  }
277
+ // A pattern's loop over a run of `unit`s (a source, or what makes one where
278
+ // it holds such a loop) read so in one match, as one of alternatives runs
279
+ // out within Latin-1 too: whole stretches (a lookahead's, matched again by
280
+ // its name), then up to one more a unit at a time, at least one after any
281
+ // stretch, so each end is read one way, and what backtracks into it tries
282
+ // them in turn as the loop would. Its units each read one way, or another
283
+ // only to end the run (a string's `\` before CRLF), as a stretch short of
284
+ // its length tries every way. Each of its names its own.
285
+ let stretches = 0
286
+ export function stretched(unit) {
287
+ const name = `stretch${stretches++}`, source = typeof unit === 'function' ? unit : () => unit
288
+ return String.raw`(?:(?:(?=(?<${name}>(?:${source()}){${STRETCH}}))\k<${name}>)+(?:${source()}){1,${STRETCH}}|(?:${source()}){0,${STRETCH}})`
289
+ }
277
290
  // A word; one of `scripts` or of no script; and a passage of such words and
278
291
  // what lies between them.
279
292
  const WORD_RUN = new RegExp(`[${WORD}]{0,${STRETCH}}`, 'uy')
@@ -29,6 +29,7 @@
29
29
  // registry's host read from config), so a file without a label is not one
30
30
  // without them.
31
31
  import { NPM_MAX_FOUND, jsMatchAll, jsOffset, lineOf, npmIsScript } from './script.js'
32
+ import { stretched } from './characters.js'
32
33
 
33
34
  // What may come between a call's parts: blanks and comments
34
35
  // (`Function/* note */(…)`), each comment ending at its first `*/`.
@@ -320,13 +321,17 @@ const SHELL_SCRIPT = /(?:\.(?:sh|bash|zsh|ksh|mksh|dash|ash|csh|tcsh|fish|comman
320
321
  // string, `"<#"`, `"a <#"`, to the end where none closes); a batch file's, cmd's `::`
321
322
  // and `REM` (`@REM`, and `REM` after `&` or `||`, `echo ok & REM …`); as
322
323
  // none of its commands.
323
- const SHELL_COMMENT = /^[ \t]*#.*$|^((?:[^'"\n#\\]|\\.|'[^'\n]*'|"(?:[^"\n\\]|\\.)*")*?[ \t;&|])#.*$/gmu
324
+ const SHELL_COMMENT = new RegExp(String.raw`^(?:[ \t]*|(${stretched(() => String.raw`[^'"\n#\\]|\\.|'${stretched(String.raw`[^'\n]`)}'|"${stretched(String.raw`[^"\n\\]|\\.`)}"`)}[ \t;&|]))#${stretched('.')}$`, 'gmu')
324
325
  const POWERSHELL = /\.psm?1$/iu
325
- const POWERSHELL_HASHBANG = /^\uFEFF?#!\s*\S*\/(?:env\s+(?:(?:-\S+|\w+=\S*)\s+)*)?pwsh(?![\w-])/u
326
- const POWERSHELL_COMMENT = /^((?:[^'"\n#\u0060]|\u0060.|'[^'\n]*'|"(?:[^"\n\u0060]|\u0060.)*")*?)(?:(?<=^|[\s;({=,])<#[\s\S]*?(?:#>|(?![\s\S]))|(?<=^|[ \t;&|])#.*$)/gmu
326
+ // A hashbang to the shell it names, by its path or env's (SHELL_SCRIPT).
327
+ const HASHBANG = String.raw`^\uFEFF?#!\s*${stretched(String.raw`\S`)}\/(?:env\s+(?:(?:-\S${stretched(String.raw`\S`)}|\w+=${stretched(String.raw`\S`)})\s+)*)?`
328
+ const POWERSHELL_HASHBANG = new RegExp(String.raw`${HASHBANG}pwsh(?![\w-])`, 'u')
329
+ const POWERSHELL_COMMENT = new RegExp(String.raw`^(${stretched(() => String.raw`[^'"\n#\u0060]|\u0060.|'${stretched(String.raw`[^'\n]`)}'|"${stretched(String.raw`[^"\n\u0060]|\u0060.`)}"`)})`
330
+ + String.raw`(?:(?<=^|[\s;({=,])<#${stretched(String.raw`[^#]|#(?!>)`)}(?:#>|(?![\s\S]))|(?<=^|[ \t;&|])#${stretched('.')}$)`, 'gmu')
327
331
  const BATCH = /\.(?:bat|cmd)$/iu
328
- const BATCH_COMMENT = /^[ \t]*@?(?:::|rem(?![\w-])).*$|(?<=&|\|\|)[ \t]*@?rem(?![\w-]).*$/gimu
329
- const SHELL_HASHBANG = new RegExp(String.raw`^\uFEFF?#!\s*\S*\/(?:env\s+(?:(?:-\S+|\w+=\S*)\s+)*)?${SHELLS}(?![\w-])`, 'u')
332
+ // Its first group the command before a comment, as the others': none.
333
+ const BATCH_COMMENT = new RegExp(String.raw`()(?:^[ \t]*@?(?:::|rem(?![\w-]))|(?<=&|\|\|)[ \t]*@?rem(?![\w-]))${stretched('.')}$`, 'gimu')
334
+ const SHELL_HASHBANG = new RegExp(String.raw`${HASHBANG}${SHELLS}(?![\w-])`, 'u')
330
335
  // A directory and a file in it named apart, as path.join takes them
331
336
  // (`join(home, '.claude', 'settings.json')`): a place code runs from again
332
337
  // later where a file names both.
@@ -364,7 +369,7 @@ const METHOD = new RegExp(String.raw`\bmethod["']?${GAP}[:=]${GAP}$`, 'u')
364
369
  // line, its arguments' strings after its name, read as a shell command is, a
365
370
  // variable's or a property's value between (`['-o', output, 'https://…']`,
366
371
  // `outputs[i]`, `options?.out`), its first 20 arguments, however long.
367
- const COMMAND = /^(["'\u0060])(?:\S*[\\/]|[a-z]:[\\/][^\n]*[\\/])?(?:curl|wget|certutil|bitsadmin|powershell|pwsh|systemctl|gh)(?:\.exe)?\1$/iu
372
+ const COMMAND = new RegExp(String.raw`^(["'\u0060])(?:${stretched(String.raw`\S`)}[\\/]|[a-z]:[\\/]${stretched(String.raw`[^\n]`)}[\\/])?(?:curl|wget|certutil|bitsadmin|powershell|pwsh|systemctl|gh)(?:\.exe)?\1$`, 'iu')
368
373
  // An argument a shell would need quoted, its separators no command's end
369
374
  // (`'Cookie: a=b; c=d'`), its own double quotes single then.
370
375
  const SEPARATES = /[;|&]/u
@@ -429,9 +434,9 @@ export function npmRunsCode(path, text, nodeRuns = false) {
429
434
  }
430
435
  if (script) read(text, at)
431
436
  if (shell && SAYS_ANY.test(text)) {
432
- // Its comments blanked, its lines where they were.
437
+ // Its comments blanked, a space for each code unit, so each offset is where it was.
433
438
  const comments = BATCH.test(path) ? BATCH_COMMENT : POWERSHELL.test(path) || POWERSHELL_HASHBANG.test(text) ? POWERSHELL_COMMENT : SHELL_COMMENT
434
- const commands = text.replace(comments, (comment, command = '') => command + comment.slice(command.length).replaceAll(/[^\n]/gu, ' '))
439
+ const commands = text.replace(comments, (comment, command = '') => command + comment.slice(command.length).replaceAll(/[^\n]/gu, char => ' '.repeat(char.length)))
435
440
  for (const [kind, holds] of SHELL_HOLDS) for (const { index } of commands.matchAll(holds)) at(kind, index)
436
441
  }
437
442
  // A PUT request publishing where the file names the registry; a place
@@ -3,6 +3,7 @@
3
3
  // regular expressions and comments, set apart from their code, what of their
4
4
  // blanks a minifier drops, which files are scripts node runs, and each
5
5
  // offset's line.
6
+ import { stretched } from './characters.js'
6
7
 
7
8
  // Code minified into lines shorter than NPM_LONG_LINE: outside its strings and
8
9
  // comments (`/* @__PURE__ */`), its lines average more than anyone writes and
@@ -17,20 +18,27 @@ const MINIFIED_SPACES = .01
17
18
  const REGEX = '\uE000'
18
19
  // A template's text, after its backtick or a substitution's `}`, to its end
19
20
  // or the next substitution's `${`.
20
- const TEMPLATE_TEXT = String.raw`(?:[^\x60\\$]|\\(?:\r\n|[\s\S])|\$(?!\{))*(?:\x60|\$\{|(?![\s\S]))`
21
+ const TEMPLATE_TEXT = String.raw`${stretched(String.raw`[^\x60\\$]|\\[\s\S]|\$(?!\{)`)}(?:\x60|\$\{|(?![\s\S]))`
22
+ // A string, to its quote or its line's end; and a regular expression's part:
23
+ // a character, an escape or a class, to its `]` or as far as it goes (its
24
+ // line's end), so it ends one way.
25
+ const STRING = quote => String.raw`${quote}${stretched(String.raw`[^${quote}\\\n]|\\(?:\r\n|[\s\S])`)}(?:${quote}|$)`
26
+ const REGEX_PART = () => String.raw`[^/\\[\n]|\\.|\[${stretched(String.raw`[^\]\\\n]|\\.`)}(?:\]|(?![^\\\n]|\\.))`
21
27
  // JavaScript's strings, templates (to a substitution's `${`, as jsMatchAll
22
28
  // reads one) and regular expressions (the first group) and its comments, a
23
29
  // regular expression read where `context` (a lookbehind) says one starts.
24
30
  // A hashbang, the file's first line (`#!/usr/bin/env node`), a comment, after
25
31
  // a byte order mark too, which node's ES module loader drops first. A
26
32
  // string's or template's escape may be a line continuation (`\` before a line
27
- // break, CRLF's whole).
33
+ // break, CRLF's whole in a string, whose LF would end it).
28
34
  // Linear on any text: a regular expression's context looked back on only
29
35
  // before a `/`, a comment's leading blanks taken only from where they start,
30
36
  // and what is left open read to where it would end, a string or a regular
31
37
  // expression its line's end, a template or a comment the text's, rather than
32
- // tried again from each later quote or slash.
33
- const literalsSource = context => String.raw`((?=\/)${context}\/(?![/*])(?:[^/\\[\n]|\\.|\[(?:[^\]\\\n]|\\.)*(?:\]|(?=\\?$)))+(?:\/[a-z]*|(?=\\?$))|"(?:[^"\\\n]|\\(?:\r\n|[\s\S]))*(?:"|$)|'(?:[^'\\\n]|\\(?:\r\n|[\s\S]))*(?:'|$)|\x60${TEMPLATE_TEXT})|(?<![ \t])[ \t]*(?:\/\*[\s\S]*?(?:\*\/|(?![\s\S]))|\/\/.*|(?<![\s\S])\uFEFF?#!.*)[ \t]*`
38
+ // tried again from each later quote or slash; each run of their text read a
39
+ // stretch at a time (stretched), as one loop over megabytes runs out of stack.
40
+ const literalsSource = context => String.raw`((?=\/)${context}\/(?![/*])(?:${REGEX_PART()})${stretched(REGEX_PART)}(?:\/[a-z]*|(?=\\?$))|${STRING('"')}|${STRING("'")}|\x60${TEMPLATE_TEXT})`
41
+ + String.raw`|(?<![ \t])[ \t]*(?:\/\*${stretched(String.raw`[^*]|\*(?!\/)`)}(?:\*\/|(?![\s\S]))|\/\/${stretched('.')}|(?<![\s\S])\uFEFF?#!${stretched('.')})[ \t]*`
34
42
  // A regular expression first where a value starts (after `=>`, `...`, an
35
43
  // operator or a keyword, not a property: `x.default/2`, `this.#in/2`), so a
36
44
  // quote in it (`/["']/`) starts no string; after a `)` or `}` too where it
@@ -122,8 +130,8 @@ function startsLine(text, at) {
122
130
  // last the rest whole as a string's, template's or regular expression's
123
131
  // text, so nothing node runs is hidden whichever way it reads it. Linear, as
124
132
  // the literals of a kind never overlap.
125
- const ANY_LITERAL = /(?<!\\)("(?:[^"\\\n]|\\(?:\r\n|[\s\S]))*(?:"|$)|'(?:[^'\\\n]|\\(?:\r\n|[\s\S]))*(?:'|$)|\u0060(?:[^\u0060\\]|\\[\s\S])*(?:\u0060|(?![\s\S])))/gmu
126
- const REST = /([\s\S]*)/uy
133
+ const ANY_LITERAL = new RegExp(String.raw`(?<!\\)(${STRING('"')}|${STRING("'")}|\u0060${stretched(String.raw`[^\u0060\\]|\\[\s\S]`)}(?:\u0060|(?![\s\S])))`, 'gmu')
134
+ const REST = new RegExp(`(${stretched(String.raw`[\s\S]`)})`, 'uy')
127
135
  function* readAny(text, own, from) {
128
136
  const next = (pattern, at) => {
129
137
  if (pattern === null) return null
@@ -366,7 +374,7 @@ export function minifiedAverage(whole, { matchAll, droppable, needed }) {
366
374
  // extension), a byte order mark before it or not, as node runs one after it
367
375
  // as an ES module (in a `"type": "module"` package).
368
376
  const SCRIPT = /\.[cm]?[jt]sx?$/iu
369
- const NODE_HASHBANG = /^\uFEFF?#!.*\bnode\b/u
377
+ const NODE_HASHBANG = new RegExp(String.raw`^\uFEFF?#!${stretched('.')}\bnode\b`, 'u')
370
378
  // Whether a file (its path and text) is a script, as SCRIPT and NODE_HASHBANG
371
379
  // tell, or as node runs it whatever its name (`script`, npm/files.js
372
380
  // npmLoadedScripts).
@@ -19,7 +19,7 @@ import { npmRiskScore } from './score.js'
19
19
  // Which reading of a version an assessment kept (`risk/npm/assessments`) is:
20
20
  // one more whenever a heuristic changes what it finds, so one kept by an
21
21
  // older reading is read anew.
22
- const RISK_VERSION = 22
22
+ const RISK_VERSION = 23
23
23
 
24
24
  // How long an assessment kept may be as JSON, and what risk reads of either
25
25
  // version's files: a package past it, whose files name thousands of hosts or
@@ -5,6 +5,8 @@ import { randomUUID } from 'node:crypto'
5
5
  import type { DatabaseSync } from 'node:sqlite'
6
6
  import { type ManagedSql, sqliteTransaction } from './sql.ts'
7
7
  import { inUserTeamScope } from './db-schema.ts'
8
+ import { reviewsIn } from './dependency-reviews.ts'
9
+ import { REVIEW_VERDICTS } from '../common/dependency-reviews.js'
8
10
 
9
11
  export interface ActivityInput {
10
12
  kind: 'access' | 'repository' | 'visibility' | 'delete'
@@ -71,9 +73,26 @@ const commentFields = `'comment:' || e.seq AS id, 'triage' AS kind,
71
73
  // recorded.
72
74
  const recordedEvents = (fields: string, table: string) => `SELECT ${fields}, e.repo, e.report_id AS reportId, e.report, e.finding_id AS finding, e.at
73
75
  FROM ${table} e LEFT JOIN managed_user u ON u.id = e.actor_id`
76
+ // Package reviews as published, read of the reviews themselves, never copied
77
+ // into managed_activity: each once, when it was first published, by its author
78
+ // (their login as they reviewed, and who they are), with its final verdict and
79
+ // what it reviewed as its target; never its comments. Publishing it to more
80
+ // teams, or revoking it, adds no entry. `where` narrows them.
81
+ const reviewVerdict = `CASE r.status ${Object.entries(REVIEW_VERDICTS)
82
+ .map(([status, label]) => `WHEN '${status}' THEN '${label.replace(/ \(.*\)$/u, '')}'`).join(' ')} END`
83
+ const reviewedVersion = (name: string, version: string, patch: string) => `${name} || '@' || ${version} || CASE WHEN ${patch} <> '' THEN ' (patched)' ELSE '' END`
84
+ const reviewEvents = (where = '') => `SELECT 'review:' || r.id AS id, 'review' AS kind, r.user_login AS actor, r.user_id AS actorId,
85
+ 'published a review' || COALESCE(' (' || ${reviewVerdict} || ')', '') AS action,
86
+ NULL AS repo, NULL AS reportId,
87
+ ${reviewedVersion('r.package', 'r.version', 'r.patch_hash')} || CASE WHEN r.base_package = '' THEN ''
88
+ WHEN r.base_package = r.package THEN ' compared with ' || r.base_version || CASE WHEN r.base_patch_hash <> '' THEN ' (patched)' ELSE '' END
89
+ ELSE ' compared with ' || ${reviewedVersion('r.base_package', 'r.base_version', 'r.base_patch_hash')} END AS report,
90
+ NULL AS finding, r.published_at AS at
91
+ FROM managed_dependency_review r WHERE r.published_at IS NOT NULL${where}`
74
92
  const adminSource = `${recordedEvents(triageFields, 'managed_finding_triage_event')}
75
93
  UNION ALL ${recordedEvents(commentFields, 'managed_finding_comment_event')} UNION ALL
76
- SELECT id, kind, actor, actor_id AS actorId, action, repo, report_id AS reportId, report, NULL AS finding, at FROM managed_activity`
94
+ SELECT id, kind, actor, actor_id AS actorId, action, repo, report_id AS reportId, report, NULL AS finding, at FROM managed_activity
95
+ UNION ALL ${reviewEvents()}`
77
96
  // The events of the accessible findings in a finding trail (`table`), with
78
97
  // `fields` and the context the server gives each finding. Keep the finite
79
98
  // set of accessible findings outside the indexed event lookup. Scanning all
@@ -103,7 +122,10 @@ const managerSource = `${contextEvents(triageFields, 'managed_finding_triage_eve
103
122
  WHERE a.kind = 'delete' AND (a.report_id IS NOT NULL OR a.bundle_id IS NOT NULL)
104
123
  AND NOT EXISTS (SELECT 1 FROM managed_report WHERE id = a.report_id)
105
124
  AND NOT EXISTS (SELECT 1 FROM managed_bundle WHERE id = a.bundle_id)
106
- AND ${inUserTeamScope(':userId', 'a')}`
125
+ AND ${inUserTeamScope(':userId', 'a')}
126
+ UNION ALL ${reviewEvents(` AND (r.user_id = :userId OR EXISTS (SELECT 1 FROM managed_dependency_review_team rt
127
+ JOIN managed_team t ON t.id = rt.team_id JOIN managed_user u ON u.id = :userId
128
+ WHERE rt.review_id = r.id AND ${reviewsIn(false)}))`)}`
107
129
 
108
130
  export const ACTIVITY_SCHEMA = `
109
131
  CREATE TABLE IF NOT EXISTS managed_activity (
@@ -11,3 +11,11 @@ export interface AvatarStore {
11
11
  get(id: string): Promise<CachedAvatar | null>
12
12
  delete(id: string): Promise<void>
13
13
  }
14
+
15
+ // A GitHub account's avatar kept by its numeric id, not a user's: a GitHub
16
+ // App's (`app`) or an account's (`user`, an organization's too). Kept under a
17
+ // key no user's, a v4 UUID, can be (an app's `…-0000-<id>`, an account's
18
+ // `…-0001-<id>`), and fetched from where GitHub serves it.
19
+ export type GithubAvatar = 'app' | 'user'
20
+ export const githubAvatarKey = (kind: GithubAvatar, id: number | string) => `00000000-0000-0000-000${kind === 'app' ? 0 : 1}-${String(id).padStart(12, '0')}`
21
+ export const githubAvatarUrl = (kind: GithubAvatar, id: number | string) => `https://avatars.githubusercontent.com/${kind === 'app' ? 'in' : 'u'}/${id}`
@@ -327,12 +327,21 @@ export interface TeamMember extends TeamUserPermissions {
327
327
  login: string
328
328
  }
329
329
 
330
- // A team with its links inlined, for the "Manage teams" page.
330
+ // The GitHub organization whose avatar a team shows (team-icons.ts): its
331
+ // numeric id, and its login as it was when chosen.
332
+ export interface TeamIcon {
333
+ id: number
334
+ login: string
335
+ }
336
+
337
+ // A team with its links inlined, for the "Manage teams" page. `icon` only
338
+ // where one is chosen.
331
339
  export interface AdminTeam {
332
340
  id: string
333
341
  slug: string
334
342
  name: string
335
343
  hidden: boolean
344
+ icon?: TeamIcon
336
345
  repos: TeamRepoLink[]
337
346
  members: TeamMember[]
338
347
  }
@@ -377,6 +386,8 @@ export interface UserTeam {
377
386
  id: string
378
387
  slug: string
379
388
  name: string
389
+ // Only where one is chosen.
390
+ icon?: TeamIcon
380
391
  dependencyReview?: boolean
381
392
  permissions: TeamUserPermissions
382
393
  cacheKey?: string
@@ -555,7 +566,11 @@ export interface ManagedDb extends DependencyReviewStore, RepositoryDependencyRe
555
566
  // Hiding preserves links but disables all grants and workspace access.
556
567
  setTeamHidden(id: string, hidden: boolean, now: number): Promise<boolean>
557
568
  deleteTeam(id: string): Promise<boolean>
558
- getTeam(id: string): Promise<{ id: string; slug: string; name: string; hidden: boolean } | null>
569
+ getTeam(id: string): Promise<{ id: string; slug: string; name: string; hidden: boolean; icon?: TeamIcon } | null>
570
+ // Set the team's icon, or reset it to the default (null); false iff there is no such team.
571
+ setTeamIcon(id: string, icon: TeamIcon | null, now: number): Promise<boolean>
572
+ // Whether a non-hidden team of `userId` shows organization `githubId`'s avatar.
573
+ userCanReadTeamIcon(userId: string, githubId: number): Promise<boolean>
559
574
  listTeams(): Promise<AdminTeam[]>
560
575
  listUserOptions(): Promise<UserOption[]>
561
576
  // Current grants for manager content reads, writes, and repository pickers.
@@ -611,7 +626,7 @@ const BUNDLE_IN_TEAM_PATH_SQL = withinTeamPath('b.repo_directory')
611
626
  // `dependencyReview` where the user reviews dependencies in the team
612
627
  // (dependency-reviews.ts reviewsIn): one that reviews them, and a member
613
628
  // who manages, or triages and may see its dependencies; an admin in any.
614
- const USER_TEAMS_SQL = (user: string) => `SELECT t.id AS id, t.slug AS slug, t.name AS name,
629
+ const USER_TEAMS_SQL = (user: string) => `SELECT t.id AS id, t.slug AS slug, t.name AS name, t.icon_github_id AS iconId, t.icon_login AS iconLogin,
615
630
  CASE WHEN t.dependency_review = 1 AND (u.role IN ('admin', 'manage') OR (u.role = 'triage' AND tu.view_dependencies = 1))
616
631
  THEN 1 ELSE 0 END AS dependencyReview,
617
632
  tu.view_dependencies AS dependencies, tu.view_security AS security
@@ -656,7 +671,7 @@ const BUNDLE_RENAMED_SQL = `(:rename = 1 AND (provenance = 'upload' OR (:provena
656
671
 
657
672
  // The rows a user's team catalog is built of (USER_TEAMS_SQL and the rest).
658
673
  type UserTeamRows = {
659
- teams: { id: string; slug: string; name: string; dependencyReview: number; dependencies: number; security: number }[]
674
+ teams: { id: string; slug: string; name: string; iconId: number | null; iconLogin: string | null; dependencyReview: number; dependencies: number; security: number }[]
660
675
  scopes: { teamId: string; repoId: number; path: string; fullName: string }[]
661
676
  reports: {
662
677
  teamId: string; id: string; slug: string; filename: string; analyzer: string | null; sha256: string; bundleId: string | null; repoId: number
@@ -677,6 +692,10 @@ function reportCatalogKey(r: CatalogReportRow, role: string, links: string): str
677
692
  ])).digest('base64url')
678
693
  }
679
694
 
695
+ // A team row's icon, as a team carries it: none where none is chosen.
696
+ const teamIcon = (row: { iconId: number | null; iconLogin: string | null }): { icon?: TeamIcon } =>
697
+ row.iconId == null ? {} : { icon: { id: Number(row.iconId), login: row.iconLogin ?? '' } }
698
+
680
699
  // A user's team catalog from its rows, `links` the link reports' revision.
681
700
  function userTeams(teams: UserTeamRows['teams'], scopes: UserTeamRows['scopes'], links: string, reports: UserTeamRows['reports'], bundles: UserTeamRows['bundles']): UserTeam[] {
682
701
  const reportsByTeam = Map.groupBy(reports, r => r.teamId)
@@ -685,6 +704,7 @@ function userTeams(teams: UserTeamRows['teams'], scopes: UserTeamRows['scopes'],
685
704
  const teamScopes = scopes.filter(scope => scope.teamId === t.id)
686
705
  return {
687
706
  id: t.id, slug: t.slug, name: t.name,
707
+ ...teamIcon(t),
688
708
  ...(t.dependencyReview === 1 ? { dependencyReview: true } : {}),
689
709
  permissions: { dependencies: t.dependencies === 1, security: t.security === 1 },
690
710
  cacheKey: createHash('sha256').update(JSON.stringify([t.dependencies, t.security, links, teamScopes])).digest('base64url'),
@@ -799,6 +819,7 @@ function prepareStatements(db: ManagedSql) {
799
819
  SELECT MAX(e.at) AS at FROM managed_finding_triage_event e WHERE e.actor_id = u.id
800
820
  UNION ALL SELECT MAX(a.at) AS at FROM managed_activity a WHERE a.actor_id = u.id
801
821
  UNION ALL SELECT MAX(c.at) AS at FROM managed_finding_comment_event c WHERE c.actor_id = u.id
822
+ UNION ALL SELECT MAX(r.published_at) AS at FROM managed_dependency_review r WHERE r.user_id = u.id
802
823
  ) AS events) AS lastActivity
803
824
  FROM managed_user u ORDER BY u.created_at ASC, u.login ASC`,
804
825
  ),
@@ -1111,11 +1132,14 @@ function prepareStatements(db: ManagedSql) {
1111
1132
  SELECT id, CASE WHEN EXISTS (SELECT 1 FROM managed_team WHERE slug = candidate.slug) THEN id ELSE slug END,
1112
1133
  ?, ?, ? FROM candidate`),
1113
1134
  deleteTeamStmt: db.prepare(`DELETE FROM managed_team WHERE id = ?`),
1114
- selectTeamStmt: db.prepare(`SELECT id, slug, name, hidden FROM managed_team WHERE id = ?`),
1135
+ selectTeamStmt: db.prepare(`SELECT id, slug, name, hidden, icon_github_id AS iconId, icon_login AS iconLogin FROM managed_team WHERE id = ?`),
1115
1136
  selectTeamByNameStmt: db.prepare(`SELECT id FROM managed_team WHERE name = ?`),
1116
1137
  renameTeamStmt: db.prepare(`UPDATE managed_team SET name = ?, updated_at = ? WHERE id = ?`),
1117
1138
  setTeamHiddenStmt: db.prepare(`UPDATE managed_team SET hidden = ?, updated_at = ? WHERE id = ?`),
1118
- selectTeamsStmt: db.prepare(`SELECT id, slug, name, hidden FROM managed_team ORDER BY name ASC`),
1139
+ setTeamIconStmt: db.prepare(`UPDATE managed_team SET icon_github_id = ?, icon_login = ?, updated_at = ? WHERE id = ?`),
1140
+ selectUserTeamIconStmt: db.prepare(`SELECT 1 AS shown FROM managed_team_user tu JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
1141
+ WHERE tu.user_id = ? AND t.icon_github_id = ? LIMIT 1`),
1142
+ selectTeamsStmt: db.prepare(`SELECT id, slug, name, hidden, icon_github_id AS iconId, icon_login AS iconLogin FROM managed_team ORDER BY name ASC`),
1119
1143
  selectTeamsForUserStmt: db.prepare(`${USER_TEAMS_SQL('?')} ORDER BY t.name ASC, t.id ASC`),
1120
1144
  selectUserTeamScopesStmt: db.prepare(`${USER_TEAM_SCOPES_SQL('?')} ORDER BY tr.team_id, tr.repo_id, tr.path`),
1121
1145
  selectUserTeamReportsStmt: db.prepare(`${USER_TEAM_REPORTS_SQL('?')} ORDER BY r.uploaded_at DESC, r.filename ASC, r.id ASC`),
@@ -1131,7 +1155,7 @@ function prepareStatements(db: ManagedSql) {
1131
1155
  WHERE s.id = ? AND s.expires_at > ?
1132
1156
  )
1133
1157
  SELECT v.id AS id, v.role AS role, v.catalog AS catalog, v.annotations AS annotations,
1134
- (SELECT json_group_array(json_object('id', x.id, 'slug', x.slug, 'name', x.name, 'dependencyReview', x.dependencyReview,
1158
+ (SELECT json_group_array(json_object('id', x.id, 'slug', x.slug, 'name', x.name, 'iconId', x.iconId, 'iconLogin', x.iconLogin, 'dependencyReview', x.dependencyReview,
1135
1159
  'dependencies', x.dependencies, 'security', x.security) ORDER BY x.name ASC, x.id ASC)
1136
1160
  FROM (${USER_TEAMS_SQL('v.id')}) AS x) AS teams,
1137
1161
  (SELECT json_group_array(json_object('teamId', x.teamId, 'repoId', x.repoId, 'path', x.path, 'fullName', x.fullName)
@@ -1648,7 +1672,7 @@ function bundleMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedS
1648
1672
  }
1649
1673
  }
1650
1674
 
1651
- type TeamRow = { id: string; slug: string; name: string; hidden: number }
1675
+ type TeamRow = { id: string; slug: string; name: string; hidden: number; iconId: number | null; iconLogin: string | null }
1652
1676
  type TeamRepoRow = { teamId: string; repoId: number; fullName: string; path: string | null }
1653
1677
  type TeamMemberRow = { teamId: string; userId: string; login: string; viewDependencies: number; viewSecurity: number }
1654
1678
 
@@ -1657,7 +1681,7 @@ type TeamMemberRow = { teamId: string; userId: string; login: string; viewDepend
1657
1681
  // workspace has.
1658
1682
  function teamMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedSql) {
1659
1683
  const {
1660
- insertTeamStmt, selectTeamByNameStmt, renameTeamStmt, setTeamHiddenStmt, deleteTeamStmt, selectTeamStmt,
1684
+ insertTeamStmt, selectTeamByNameStmt, renameTeamStmt, setTeamHiddenStmt, setTeamIconStmt, selectUserTeamIconStmt, deleteTeamStmt, selectTeamStmt,
1661
1685
  selectUserRepoScopesStmt, selectTeamsStmt, selectTeamsForUserStmt, selectUserTeamReportsStmt, selectUserTeamBundlesStmt, selectReportReadableStmt,
1662
1686
  selectReportPermsStmt, selectUserOptionsStmt, selectTeamReposStmt, selectTeamMembersStmt,
1663
1687
  upsertTeamRepoStmt, deleteTeamRepoStmt, deleteTeamRepoPathStmt, upsertTeamMemberStmt, deleteTeamMemberStmt,
@@ -1680,9 +1704,15 @@ function teamMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedSql
1680
1704
  async setTeamHidden(id: string, hidden: boolean, now: number): Promise<boolean> {
1681
1705
  return anyChanged(await setTeamHiddenStmt.run(hidden ? 1 : 0, now, id))
1682
1706
  },
1683
- async getTeam(id: string): Promise<{ id: string; slug: string; name: string; hidden: boolean } | null> {
1707
+ async setTeamIcon(id: string, icon: TeamIcon | null, now: number): Promise<boolean> {
1708
+ return anyChanged(await setTeamIconStmt.run(icon?.id ?? null, icon?.login ?? null, now, id))
1709
+ },
1710
+ async userCanReadTeamIcon(userId: string, githubId: number): Promise<boolean> {
1711
+ return (await selectUserTeamIconStmt.get(userId, githubId)) != null
1712
+ },
1713
+ async getTeam(id: string): Promise<{ id: string; slug: string; name: string; hidden: boolean; icon?: TeamIcon } | null> {
1684
1714
  const row = (await selectTeamStmt.get(id)) as TeamRow | undefined
1685
- return row == null ? null : { id: row.id, slug: row.slug, name: row.name, hidden: row.hidden === 1 }
1715
+ return row == null ? null : { id: row.id, slug: row.slug, name: row.name, hidden: row.hidden === 1, ...teamIcon(row) }
1686
1716
  },
1687
1717
  async listUserOptions(): Promise<UserOption[]> {
1688
1718
  return ((await selectUserOptionsStmt.all()) as UserOption[]).map((u) => ({ id: u.id, login: u.login, name: u.name, role: u.role }))
@@ -1731,6 +1761,7 @@ function teamMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedSql
1731
1761
  return teams.map((t) => ({
1732
1762
  id: t.id, slug: t.slug, name: t.name,
1733
1763
  hidden: t.hidden === 1,
1764
+ ...teamIcon(t),
1734
1765
  repos: (reposByTeam.get(t.id) ?? []).map(r => ({ repoId: r.repoId, fullName: r.fullName, path: r.path })),
1735
1766
  members: (membersByTeam.get(t.id) ?? []).map(m => ({ userId: m.userId, login: m.login,
1736
1767
  dependencies: m.viewDependencies === 1, security: m.viewSecurity === 1 })),
@@ -8,7 +8,7 @@ import { AsyncLocalStorage } from 'node:async_hooks'
8
8
  import { WebSocket } from 'ws'
9
9
  import { type ManagedDb, type ManagedDbOptions, createManagedMethods } from './db-methods.ts'
10
10
  import { revisionSchema } from './revisions.ts'
11
- import { MANAGED_SCHEMA, REPORT_OPENING_COLUMNS, REPO_UPLOAD_INDEXES, VIEW_SESSION_INDEX } from './db-schema.ts'
11
+ import { MANAGED_SCHEMA, REPORT_OPENING_COLUMNS, REPO_UPLOAD_INDEXES, TEAM_ICON_COLUMNS, VIEW_SESSION_INDEX } from './db-schema.ts'
12
12
  import { STORAGE_SCHEMA } from './storage-db.ts'
13
13
  import { GITHUB_COMMIT_SCHEMA, GITHUB_METADATA_SCHEMA, GITHUB_STATE_REASON_COLUMN } from './github-metadata.ts'
14
14
  import { MANAGED_ISSUE_SCHEMA } from './managed-issues.ts'
@@ -40,7 +40,7 @@ const LOCK = 'SELECT pg_advisory_xact_lock(1937006964, 1835101793)'
40
40
  // Whether every version up to the latest is recorded, in one round trip at
41
41
  // a cold start: a database with no versions table yet (undefined_table) has
42
42
  // none. Outside a transaction, so the failed read aborts nothing.
43
- const SCHEMA_VERSIONS = 38
43
+ const SCHEMA_VERSIONS = 39
44
44
  async function currentSchema(db: PgConnection): Promise<boolean> {
45
45
  try {
46
46
  const { rows } = await db.query(`SELECT count(*) AS n FROM managed_schema_version WHERE version BETWEEN 1 AND ${SCHEMA_VERSIONS}`)
@@ -146,6 +146,9 @@ async function migrateFrom12(db: PgConnection): Promise<void> {
146
146
  // published before: a time in milliseconds, so BIGINT, as postgresSchema
147
147
  // makes SQLite's INTEGER.
148
148
  await migration(db, 38, postgresSchema(`ALTER TABLE managed_dependency_review ${addColumns(DEPENDENCY_REVIEW_COLUMNS)}`))
149
+ // A team's icon, none chosen for those created before: a GitHub id, so
150
+ // BIGINT, as postgresSchema makes SQLite's INTEGER.
151
+ await migration(db, 39, postgresSchema(`ALTER TABLE managed_team ${addColumns(TEAM_ICON_COLUMNS)}`))
149
152
  }
150
153
 
151
154
  async function initialize(db: PgConnection): Promise<void> {
@@ -27,6 +27,9 @@ export const inUserTeamScope = (user: string, row: string) => `EXISTS (SELECT 1
27
27
  JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
28
28
  WHERE tu.user_id = ${user} AND tr.repo_id = ${row}.repo_id AND ${withinTeamPath(`${row}.repo_directory`)})`
29
29
 
30
+ // A team's icon (team-icons.ts), added to databases created before it.
31
+ export const TEAM_ICON_COLUMNS = [['icon_github_id', 'INTEGER'], ['icon_login', 'TEXT']] as const
32
+
30
33
  // A report's opening (report-opening.ts), added to databases created before it.
31
34
  export const REPORT_OPENING_COLUMNS = [['confirmed_offered', 'INTEGER'], ['confirmed_default', 'INTEGER NOT NULL DEFAULT 0']] as const
32
35
 
@@ -224,7 +227,10 @@ CREATE INDEX IF NOT EXISTS finding_triage_event_finding_idx ON managed_finding_t
224
227
  CREATE INDEX IF NOT EXISTS finding_triage_event_actor_at_idx ON managed_finding_triage_event(actor_id, at);
225
228
 
226
229
  -- Teams group users + repos for access scoping. Hidden teams grant no access;
227
- -- the two link tables below carry the many-many relations.
230
+ -- the two link tables below carry the many-many relations. icon_github_id is
231
+ -- the GitHub organization whose avatar the team shows (team-icons.ts), one
232
+ -- owning a repository of the team when it was chosen; icon_login its login
233
+ -- then, for display. Both NULL for the default icon.
228
234
  CREATE TABLE IF NOT EXISTS managed_team (
229
235
  id TEXT PRIMARY KEY,
230
236
  slug TEXT NOT NULL,
@@ -232,7 +238,9 @@ CREATE TABLE IF NOT EXISTS managed_team (
232
238
  hidden INTEGER NOT NULL DEFAULT 0,
233
239
  dependency_review INTEGER NOT NULL DEFAULT 0,
234
240
  created_at INTEGER NOT NULL,
235
- updated_at INTEGER NOT NULL
241
+ updated_at INTEGER NOT NULL,
242
+ icon_github_id INTEGER,
243
+ icon_login TEXT
236
244
  ) STRICT;
237
245
 
238
246
  -- Team <-> repo, many-many, with an OPTIONAL path (a subpath of the repo the
@@ -7,7 +7,7 @@ import { migrateReportLocations } from './report-migration.ts'
7
7
  import { initCommentMethods } from './comments.ts'
8
8
  import { initActivityMethods } from './activity.ts'
9
9
  import { revisionSchema } from './revisions.ts'
10
- import { MANAGED_SCHEMA, REPORT_OPENING_COLUMNS, REPO_UPLOAD_INDEXES, VIEW_SESSION_INDEX } from './db-schema.ts'
10
+ import { MANAGED_SCHEMA, REPORT_OPENING_COLUMNS, REPO_UPLOAD_INDEXES, TEAM_ICON_COLUMNS, VIEW_SESSION_INDEX } from './db-schema.ts'
11
11
  import { GITHUB_LINK_USER_COLUMNS } from './github-links.ts'
12
12
  import { REPOSITORY_DEPENDENCY_REVIEW_COLUMNS } from './repository-dependency-reviews.ts'
13
13
  import { DEPENDENCY_REVIEW_COLUMNS, DEPENDENCY_REVIEW_INDEXES } from './dependency-reviews.ts'
@@ -125,6 +125,7 @@ export function openSqliteManagedDb(path: string, options: ManagedDbOptions = {}
125
125
  ensureColumn(db, 'managed_bundle', 'build_conditions', 'TEXT')
126
126
  ensureColumn(db, 'managed_team', 'hidden', 'INTEGER NOT NULL DEFAULT 0')
127
127
  ensureColumn(db, 'managed_team', 'dependency_review', 'INTEGER NOT NULL DEFAULT 0')
128
+ for (const [column, type] of TEAM_ICON_COLUMNS) ensureColumn(db, 'managed_team', column, type)
128
129
  ensureColumn(db, 'managed_finding_issue', 'auto_fix_url', 'TEXT')
129
130
  ensureColumn(db, 'managed_finding_issue', 'auto_fix_checked_at', 'INTEGER')
130
131
  ensureColumn(db, 'managed_finding_issue', 'duplicate_of_url', 'TEXT')
@@ -119,9 +119,13 @@ function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: str
119
119
  // `lookup` fails to answer of keeps its review. Where the host reads reviews
120
120
  // of comments (`parseComments`), what a review was compared with is its to
121
121
  // weigh, so one compared with any version is given.
122
+ // With it, the versions it is of (`versions`), as the client tells them:
123
+ // those wanting it, each once, by its name, version and patch, so that one
124
+ // listing them can tell whether it copies any it shows.
125
+ export interface CopiedVersion { name: string; version: string; patch?: { hash: string } }
122
126
  export async function formattedPull(reviewed: ReviewedDependencies | null, db: Pick<DependencyReviewStore, 'listOwnDependencyReviewsById'>, user: string,
123
127
  told: PullDependencies, state: RepoReviewState | null, pullRequest: { repository: string; number: number }, commented: PublishedReview[] = [],
124
- bases: Map<string, ReviewedBase> = new Map()): Promise<string | null> {
128
+ bases: Map<string, ReviewedBase> = new Map()): Promise<{ text: string; versions: CopiedVersion[] } | null> {
125
129
  if (!reviewed?.formatDependencyReviews || !state) return null
126
130
  const mine = ownOfPull(told, state.reviews, user, reviewed.parseComments !== undefined, bases)
127
131
  if (mine.size === 0) return null
@@ -135,9 +139,20 @@ export async function formattedPull(reviewed: ReviewedDependencies | null, db: P
135
139
  return stance.time > review.time && !ACCEPTING.has(stance.status) && ACCEPTING.has(review.status)
136
140
  && !made.some(one => one.time === stance.time && one.status === review.status)
137
141
  }
138
- const ids = [...mine].filter(([, { review, pkgs }]) => pkgs.some(pkg => !passed.has(askedOf(pkg)[0]) && !posted(review, pkg))).map(([id]) => id)
139
- if (ids.length === 0) return null
142
+ // Those wanting a comment of each review given, by its id.
143
+ const wanting = new Map([...mine].map(([id, { review, pkgs }]) => [id, pkgs.filter(pkg => !passed.has(askedOf(pkg)[0]) && !posted(review, pkg))] as const)
144
+ .filter(([, pkgs]) => pkgs.length > 0))
145
+ if (wanting.size === 0) return null
146
+ const ids = [...wanting.keys()]
140
147
  const reviews: DependencyReview[] = []
141
148
  for (let at = 0; at < ids.length; at += REVIEWS_AT_ONCE) reviews.push(...await db.listOwnDependencyReviewsById(user, ids.slice(at, at + REVIEWS_AT_ONCE)))
142
- return formatOwn(reviewed, user, reviews, pullRequest)
149
+ const text = await formatOwn(reviewed, user, reviews, pullRequest)
150
+ if (text === null) return null
151
+ const versions = new Map<string, CopiedVersion>()
152
+ for (const review of reviews.filter(one => ownPublished(one, user))) {
153
+ for (const pkg of wanting.get(review.id) ?? []) {
154
+ versions.set(`${pkg.name}@${pkg.version}\0${pkg.patchHash ?? ''}`, { name: pkg.name, version: pkg.version ?? '', ...pkg.patchHash ? { patch: { hash: pkg.patchHash } } : {} })
155
+ }
156
+ }
157
+ return { text, versions: [...versions.values()] }
143
158
  }