@preventive/triage 1.0.0-alpha.81 → 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 (40) 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-5EAVJAD2.js → chunk-CE2FMDK3.js} +1 -1
  5. package/out/{chunk-5QWPKTCE.js → chunk-EIEUTJM4.js} +2 -2
  6. package/out/chunk-FNFWBAJO.js +3 -0
  7. package/out/chunk-KP2XM324.js +6 -0
  8. package/out/{chunk-H4FEC57K.js → chunk-NH2HDQ5E.js} +1 -1
  9. package/out/{chunk-PTFYDJUP.js → chunk-RAM3GDAD.js} +1 -1
  10. package/out/{chunk-WFBVS4QI.js → chunk-SUFRZ5U7.js} +1 -1
  11. package/out/chunk-UP3ADVQN.js +54 -0
  12. package/out/{chunk-5UJHJWFU.js → chunk-W2H4DBZW.js} +1 -1
  13. package/out/{chunk-PEE47ANR.js → chunk-WOCJFOXN.js} +1 -1
  14. package/out/{chunk-ITUKKCCK.js → chunk-WOLGZ2PE.js} +1 -1
  15. package/out/{chunk-7YO4QV5P.js → chunk-XHYX3Q34.js} +1 -1
  16. package/out/chunk-Z7KOFS2V.js +266 -0
  17. package/out/{chunk-LBD3M3J6.js → chunk-ZQQALNFP.js} +1 -1
  18. package/out/client-managed-import.js +1 -1
  19. package/out/client-managed.js +30 -30
  20. package/out/compare.js +10 -10
  21. package/out/dialogs.js +5 -5
  22. package/out/graph.js +1 -1
  23. package/out/index.html +9 -9
  24. package/out/prism.js +1 -1
  25. package/out/scan.js +1 -1
  26. package/out/view.css +1 -1
  27. package/out/view.js +8 -8
  28. package/package.json +2 -1
  29. package/server-managed/avatar-store.ts +8 -0
  30. package/server-managed/db-methods.ts +41 -11
  31. package/server-managed/db-neon.ts +5 -2
  32. package/server-managed/db-schema.ts +10 -2
  33. package/server-managed/db.ts +2 -1
  34. package/server-managed/http.ts +99 -16
  35. package/server-managed/repository-browser.ts +2 -2
  36. package/server-managed/team-icons.ts +50 -0
  37. package/out/chunk-563V5VVT.js +0 -266
  38. package/out/chunk-5M2X3QPK.js +0 -6
  39. package/out/chunk-DOYTKRIR.js +0 -53
  40. package/out/chunk-OAWQNDAO.js +0 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/triage",
3
- "version": "1.0.0-alpha.81",
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",
@@ -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'),
@@ -1112,11 +1132,14 @@ function prepareStatements(db: ManagedSql) {
1112
1132
  SELECT id, CASE WHEN EXISTS (SELECT 1 FROM managed_team WHERE slug = candidate.slug) THEN id ELSE slug END,
1113
1133
  ?, ?, ? FROM candidate`),
1114
1134
  deleteTeamStmt: db.prepare(`DELETE FROM managed_team WHERE id = ?`),
1115
- 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 = ?`),
1116
1136
  selectTeamByNameStmt: db.prepare(`SELECT id FROM managed_team WHERE name = ?`),
1117
1137
  renameTeamStmt: db.prepare(`UPDATE managed_team SET name = ?, updated_at = ? WHERE id = ?`),
1118
1138
  setTeamHiddenStmt: db.prepare(`UPDATE managed_team SET hidden = ?, updated_at = ? WHERE id = ?`),
1119
- 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`),
1120
1143
  selectTeamsForUserStmt: db.prepare(`${USER_TEAMS_SQL('?')} ORDER BY t.name ASC, t.id ASC`),
1121
1144
  selectUserTeamScopesStmt: db.prepare(`${USER_TEAM_SCOPES_SQL('?')} ORDER BY tr.team_id, tr.repo_id, tr.path`),
1122
1145
  selectUserTeamReportsStmt: db.prepare(`${USER_TEAM_REPORTS_SQL('?')} ORDER BY r.uploaded_at DESC, r.filename ASC, r.id ASC`),
@@ -1132,7 +1155,7 @@ function prepareStatements(db: ManagedSql) {
1132
1155
  WHERE s.id = ? AND s.expires_at > ?
1133
1156
  )
1134
1157
  SELECT v.id AS id, v.role AS role, v.catalog AS catalog, v.annotations AS annotations,
1135
- (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,
1136
1159
  'dependencies', x.dependencies, 'security', x.security) ORDER BY x.name ASC, x.id ASC)
1137
1160
  FROM (${USER_TEAMS_SQL('v.id')}) AS x) AS teams,
1138
1161
  (SELECT json_group_array(json_object('teamId', x.teamId, 'repoId', x.repoId, 'path', x.path, 'fullName', x.fullName)
@@ -1649,7 +1672,7 @@ function bundleMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedS
1649
1672
  }
1650
1673
  }
1651
1674
 
1652
- 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 }
1653
1676
  type TeamRepoRow = { teamId: string; repoId: number; fullName: string; path: string | null }
1654
1677
  type TeamMemberRow = { teamId: string; userId: string; login: string; viewDependencies: number; viewSecurity: number }
1655
1678
 
@@ -1658,7 +1681,7 @@ type TeamMemberRow = { teamId: string; userId: string; login: string; viewDepend
1658
1681
  // workspace has.
1659
1682
  function teamMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedSql) {
1660
1683
  const {
1661
- insertTeamStmt, selectTeamByNameStmt, renameTeamStmt, setTeamHiddenStmt, deleteTeamStmt, selectTeamStmt,
1684
+ insertTeamStmt, selectTeamByNameStmt, renameTeamStmt, setTeamHiddenStmt, setTeamIconStmt, selectUserTeamIconStmt, deleteTeamStmt, selectTeamStmt,
1662
1685
  selectUserRepoScopesStmt, selectTeamsStmt, selectTeamsForUserStmt, selectUserTeamReportsStmt, selectUserTeamBundlesStmt, selectReportReadableStmt,
1663
1686
  selectReportPermsStmt, selectUserOptionsStmt, selectTeamReposStmt, selectTeamMembersStmt,
1664
1687
  upsertTeamRepoStmt, deleteTeamRepoStmt, deleteTeamRepoPathStmt, upsertTeamMemberStmt, deleteTeamMemberStmt,
@@ -1681,9 +1704,15 @@ function teamMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedSql
1681
1704
  async setTeamHidden(id: string, hidden: boolean, now: number): Promise<boolean> {
1682
1705
  return anyChanged(await setTeamHiddenStmt.run(hidden ? 1 : 0, now, id))
1683
1706
  },
1684
- 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> {
1685
1714
  const row = (await selectTeamStmt.get(id)) as TeamRow | undefined
1686
- 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) }
1687
1716
  },
1688
1717
  async listUserOptions(): Promise<UserOption[]> {
1689
1718
  return ((await selectUserOptionsStmt.all()) as UserOption[]).map((u) => ({ id: u.id, login: u.login, name: u.name, role: u.role }))
@@ -1732,6 +1761,7 @@ function teamMethods(stmts: ReturnType<typeof prepareStatements>, db: ManagedSql
1732
1761
  return teams.map((t) => ({
1733
1762
  id: t.id, slug: t.slug, name: t.name,
1734
1763
  hidden: t.hidden === 1,
1764
+ ...teamIcon(t),
1735
1765
  repos: (reposByTeam.get(t.id) ?? []).map(r => ({ repoId: r.repoId, fullName: r.fullName, path: r.path })),
1736
1766
  members: (membersByTeam.get(t.id) ?? []).map(m => ({ userId: m.userId, login: m.login,
1737
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')
@@ -23,7 +23,8 @@
23
23
  // POST /api/reports/<id>/triage → write triage entries: admin, or ≥triage role + membership | 401/403/404
24
24
  // GET /api/reports/<id>/triage/history?finding=<fid> → one visible finding's triage trail, newest first | 400/401/404
25
25
  // GET /api/avatar/<id>[?own] → cached avatar bytes by user id, of the account chosen on their profile (`own`: the
26
- // sign-in account's), or by linked account id; `app-<id>` or `user-<id>`, an agent's GitHub App's or account's (GITHUB_AGENTS) | 401/404
26
+ // sign-in account's), or by linked account id; `app-<id>` or `user-<id>`, an agent's GitHub App's or account's (GITHUB_AGENTS);
27
+ // `org-<id>`, a GitHub organization's a team shows as its icon, for an admin or a member of that team (team-icons.ts) | 401/404
27
28
  // GET /api/admin/users → admin-only user list | 401/403
28
29
  // GET /api/admin/history → paginated activity (admin), team content activity (manage) | 401/403
29
30
  // POST /api/admin/set-role → admin sets another user's role | 401/403/404
@@ -116,6 +117,10 @@
116
117
  // POST /api/admin/teams/{set,remove}-member → admin links/unlinks a user (+perms) | 401/403/404
117
118
  // POST /api/admin/teams/set-dependency-review → admin toggles dependency review publication for a team | 400/401/403/404
118
119
  // POST /api/admin/teams/set-npm-scopes → admin replaces a team's npm scopes | 400/401/403/404
120
+ // GET /api/admin/teams/icons?teamId= → admin: the GitHub organizations owning a team's repositories, its icon's choices,
121
+ // and the owners GitHub could not be asked about | 400/401/403/404
122
+ // POST /api/admin/teams/set-icon → admin sets a team's icon to one of those organizations ({ teamId, organization: login }),
123
+ // or the default icon (organization null) | 400/401/403/404/502
119
124
  // GET/POST /api/npm/reviews → read private/team reviews; save, publish, revoke or continue a set; a patched version's
120
125
  // (patchHash) changed with where its patch is (patchRepoId, patchCommit, patchPath) | 400/401/403/404/409/422
121
126
  // POST /api/npm/reviews/discard → author discards an unpublished review and its file rows | 400/401/403/409
@@ -176,12 +181,12 @@ import { contentAccess } from './content-access.ts'
176
181
  import type { BundleStore } from './bundle-store.ts'
177
182
  import { Buffer } from 'node:buffer'
178
183
  import { createHash, randomUUID } from 'node:crypto'
179
- import type { AvatarStore, CachedAvatar } from './avatar-store.ts'
184
+ import { type AvatarStore, type CachedAvatar, type GithubAvatar, githubAvatarKey, githubAvatarUrl } from './avatar-store.ts'
180
185
  import type { BlobStore, OpenedBlob } from './blob-store.ts'
181
186
  import { bundleFilePrefix, bundleIntegrity, bundleKind, bundleRepo, reportBundleHashes } from './bundle.ts'
182
187
  import { ourRepositoryNames, resolveRepositoryImportLocation } from './repository-aliases.ts'
183
188
  import type { ManagedConfig } from './config.ts'
184
- import type { BundleBuildConditions, BundleProvenance, BundleReuse, ManagedBundle, ManagedDb, ManagedSession, ReportRecord, SelectedRepo, StoredUser, TriageEventRow } from './db.ts'
189
+ import type { AdminTeam, BundleBuildConditions, BundleProvenance, BundleReuse, ManagedBundle, ManagedDb, ManagedSession, ReportRecord, SelectedRepo, StoredUser, TriageEventRow } from './db.ts'
185
190
  import type { OriginGate } from '../server-common/origin.ts'
186
191
  import { isRole, roleAtLeast } from '../common/managed/roles.ts'
187
192
  import { VISIBILITY_PERMISSIONS, parseTeamUserPermissions } from '../common/managed/permissions.ts'
@@ -201,6 +206,7 @@ import { bundleCommitHash } from '../common/bundle-commit.js'
201
206
  import { collectRepos, fetchPublicRepository, installUrl, publicRepositoryName, repositoryInstallation } from './github-app.ts'
202
207
  import { type TaggedRead, keepTaggedReadsIn } from './github-requests.ts'
203
208
  import { SHA, timeOf } from './github-values.ts'
209
+ import { ORGANIZATION_AVATAR, isOrganizationLogin, teamOrganizations } from './team-icons.ts'
204
210
  import { GithubApiError, upstreamGithub } from './github-errors.ts'
205
211
  import { STASIS_CONFIG } from './stasis-config.ts'
206
212
  import { createClient } from '@preventive/upstream/github.js'
@@ -344,6 +350,8 @@ const TEAM_REMOVE_REPO_PATH = '/api/admin/teams/remove-repo'
344
350
  const TEAM_SET_MEMBER_PATH = '/api/admin/teams/set-member'
345
351
  const TEAM_REMOVE_MEMBER_PATH = '/api/admin/teams/remove-member'
346
352
  const TEAM_SET_NPM_SCOPES_PATH = '/api/admin/teams/set-npm-scopes'
353
+ const TEAM_ICONS_PATH = '/api/admin/teams/icons'
354
+ const TEAM_SET_ICON_PATH = '/api/admin/teams/set-icon'
347
355
  const NPM_PACKAGE_PATH = '/api/npm/package'
348
356
  const NPM_VERSIONS_PATH = '/api/npm/versions'
349
357
  const NPM_DOWNLOAD_PATH = '/api/npm/download'
@@ -561,9 +569,8 @@ function sendAvatar(req: IncomingMessage, res: ServerResponse, avatar: CachedAva
561
569
 
562
570
  // The avatars `/api/avatar/app-<id>` and `/api/avatar/user-<id>` serve, these
563
571
  // alone: those the app draws agents by (GITHUB_AGENTS), on the Agents tab and
564
- // wherever their work shows. Each is fetched from GitHub once and
565
- // kept, under a key no user's, a v4 UUID, can be: an app's, `…-0000-<id>`,
566
- // an account's, `…-0001-<id>`.
572
+ // wherever their work shows. Each is fetched from GitHub once and kept
573
+ // (githubAvatarKey).
567
574
  const AGENT_AVATARS: ReadonlySet<string> = new Set(Object.values(GITHUB_AGENTS).flatMap(agent => 'avatar' in agent ? [agent.avatar] : []))
568
575
  const AGENT_AVATAR = /^(app|user)-([1-9]\d{0,11})$/u
569
576
  // An agent's mark is a public GitHub image that never changes with anyone's
@@ -571,17 +578,24 @@ const AGENT_AVATAR = /^(app|user)-([1-9]\d{0,11})$/u
571
578
  // for it alone.
572
579
  const AGENT_AVATAR_CACHE = 'private, max-age=86400'
573
580
 
574
- async function serveAgentAvatar(req: IncomingMessage, res: ServerResponse, avatarStore: AvatarStore, avatar: string): Promise<void> {
575
- const [, kind, id] = AGENT_AVATAR.exec(avatar)!
576
- const key = `00000000-0000-0000-000${kind === 'app' ? 0 : 1}-${id!.padStart(12, '0')}`
577
- // Read once where it is kept; read again only past fetching it.
578
- const kept = await avatarStore.get(key)
579
- if (kept != null) { sendAvatar(req, res, kept, AGENT_AVATAR_CACHE); return }
580
- await cacheAvatar(avatarStore, key, `https://avatars.githubusercontent.com/${kind === 'app' ? 'in' : 'u'}/${id}`, globalThis.fetch)
581
- .catch((err) => { console.warn('managed: agent avatar caching failed:', err) })
582
- await serveAvatar(req, res, avatarStore, key, key, AGENT_AVATAR_CACHE)
581
+ // Keep the avatar GitHub serves of account `id` now, replacing what was
582
+ // kept; a failure is told the operator, never thrown.
583
+ function keepGithubAvatar(avatarStore: AvatarStore, kind: GithubAvatar, id: number | string): Promise<void> {
584
+ return cacheAvatar(avatarStore, githubAvatarKey(kind, id), githubAvatarUrl(kind, id), globalThis.fetch)
585
+ .catch((err) => { console.warn(`managed: ${kind} ${id} avatar caching failed:`, err) })
583
586
  }
584
587
 
588
+ // Account `id`'s avatar, as kept, else fetched from GitHub and kept then.
589
+ async function serveGithubAvatar(req: IncomingMessage, res: ServerResponse, avatarStore: AvatarStore, kind: GithubAvatar, id: number | string, cacheControl: string): Promise<void> {
590
+ const key = githubAvatarKey(kind, id)
591
+ sendAvatar(req, res, await avatarStore.get(key) ?? await keepGithubAvatar(avatarStore, kind, id).then(() => avatarStore.get(key)), cacheControl)
592
+ }
593
+
594
+ // What the generic path serves: a user's id, or a linked account's, each a v4
595
+ // UUID (randomUUID); never a GitHub account's kept avatar, served by its own
596
+ // path alone, an organization's to those whose team shows it.
597
+ const USER_AVATAR = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u
598
+
585
599
  const MAX_JSON_BODY_BYTES = 4096
586
600
 
587
601
  // Buffer the request body, aborting (and throwing 'too-large') once it exceeds
@@ -5171,6 +5185,58 @@ async function handleSetTeamNpmScopes(req: IncomingMessage, res: ServerResponse,
5171
5185
  sendJson(res, 200, { ok: true, scopes: (await deps.db.listTeamNpmScopes())[teamId] ?? [] })
5172
5186
  }
5173
5187
 
5188
+ // Team `team`'s repositories, each once, as GitHub is asked of them for its icon.
5189
+ async function teamIconRepos(deps: ManagedHttpDeps, team: AdminTeam): Promise<SelectedRepo[]> {
5190
+ const linked = new Set(team.repos.map(link => link.repoId))
5191
+ return (await deps.db.listAllRepos()).filter(repo => linked.has(repo.repoId))
5192
+ }
5193
+
5194
+ // GET /api/admin/teams/icons?teamId= — what team `teamId` may show as its
5195
+ // icon: the GitHub organizations owning its repositories, as GitHub tells them
5196
+ // now (`organizations`, each { id, login }), and the owners GitHub could not
5197
+ // be asked about (`unchecked`). Admin, read-only.
5198
+ async function handleTeamIcons(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, teamId: string | null): Promise<void> {
5199
+ const s = await readAdminSession(res, deps, cookie, { handed: true })
5200
+ if (s == null) return
5201
+ if (!teamId || teamId.length > 100) { sendJson(res, 400, { error: 'bad-request' }); return }
5202
+ const team = (await deps.db.listTeams()).find(row => row.id === teamId)
5203
+ if (team == null) { sendJson(res, 404, { error: 'no-team' }); return }
5204
+ sendJson(res, 200, await teamOrganizations(deps.config, await teamIconRepos(deps, team), globalThis.fetch))
5205
+ }
5206
+
5207
+ // POST /api/admin/teams/set-icon — a team's icon. Body { teamId, organization }:
5208
+ // the login of a GitHub organization owning one of its repositories, as GitHub
5209
+ // tells it now, its avatar fetched again; or null for the default icon.
5210
+ // 400 not-team-organization where none of its repositories is that
5211
+ // organization's; 502 github-unavailable where GitHub could not tell of one.
5212
+ async function handleSetTeamIcon(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
5213
+ const s = await adminMutation(req, res, deps, cookie, { handed: true })
5214
+ if (s == null) return
5215
+ const body = await readBodyFields(req, res)
5216
+ if (!body) return
5217
+ const { teamId, organization } = body
5218
+ if (typeof teamId !== 'string' || (organization !== null && !isOrganizationLogin(organization))) { sendJson(res, 400, { error: 'bad-request' }); return }
5219
+ const team = (await deps.db.listTeams()).find(row => row.id === teamId)
5220
+ if (team == null) { sendJson(res, 404, { error: 'no-team' }); return }
5221
+ let icon = null
5222
+ if (organization !== null) {
5223
+ const choices = await teamOrganizations(deps.config, await teamIconRepos(deps, team), globalThis.fetch)
5224
+ icon = choices.organizations.find(choice => choice.login.toLowerCase() === organization.toLowerCase()) ?? null
5225
+ if (icon == null) {
5226
+ if (choices.unchecked.length > 0) sendJson(res, 502, { error: 'github-unavailable' })
5227
+ else sendJson(res, 400, { error: 'not-team-organization' })
5228
+ return
5229
+ }
5230
+ await keepGithubAvatar(deps.avatarStore, 'user', icon.id)
5231
+ }
5232
+ if (await readAdminSession(res, deps, cookie) == null) return
5233
+ if (!(await deps.db.setTeamIcon(teamId, icon, Date.now()))) { sendJson(res, 404, { error: 'no-team' }); return }
5234
+ if (team.icon?.id !== icon?.id) {
5235
+ await activity(deps, s.user, 'access', icon ? `set team ${team.name}'s icon to ${icon.login}` : `reset team ${team.name}'s icon`)
5236
+ }
5237
+ sendJson(res, 200, { ok: true, icon })
5238
+ }
5239
+
5174
5240
  // Who reads npm packages now: a session with workspace access, its role and,
5175
5241
  // where they count for any of `names` it is asked about (npmScopesCount), the
5176
5242
  // npm scopes of its visible teams, else none: none are read for an unscoped
@@ -5983,7 +6049,16 @@ export function createManagedRequestHandler(deps: ManagedHttpDeps): Handler {
5983
6049
  if (path.startsWith(AVATAR_PREFIX)) {
5984
6050
  if (method !== 'GET') { send405(res, 'GET'); return }
5985
6051
  const id = path.slice(AVATAR_PREFIX.length)
5986
- if (AGENT_AVATARS.has(id) && AGENT_AVATAR.test(id)) { await serveAgentAvatar(req, res, avatarStore, id); return }
6052
+ const agent = AGENT_AVATARS.has(id) ? AGENT_AVATAR.exec(id) : null
6053
+ if (agent) { await serveGithubAvatar(req, res, avatarStore, agent[1] as GithubAvatar, agent[2]!, AGENT_AVATAR_CACHE); return }
6054
+ // A team's icon (team-icons.ts): any organization's for an admin, who
6055
+ // chooses them; one a team of theirs shows for anyone else.
6056
+ const organization = Number(ORGANIZATION_AVATAR.exec(id)?.[1])
6057
+ const user = workspaceSession!.user
6058
+ if (organization && (user.role === 'admin' || await db.userCanReadTeamIcon(user.id, organization))) {
6059
+ await serveGithubAvatar(req, res, avatarStore, 'user', organization, USER_AVATAR_CACHE); return
6060
+ }
6061
+ if (!USER_AVATAR.test(id)) { sendJson(res, 404, { error: 'no-avatar' }); return }
5987
6062
  await serveAvatar(req, res, avatarStore, id, url.searchParams.has('own') ? id : await db.getAvatarKey(id))
5988
6063
  return
5989
6064
  }
@@ -6239,6 +6314,14 @@ export function createManagedRequestHandler(deps: ManagedHttpDeps): Handler {
6239
6314
  if (method !== 'POST') { send405(res, 'POST'); return }
6240
6315
  await handleSetTeamNpmScopes(req, res, deps, cookie); return
6241
6316
  }
6317
+ if (path === TEAM_ICONS_PATH) {
6318
+ if (method !== 'GET') { send405(res, 'GET'); return }
6319
+ await handleTeamIcons(res, deps, cookie, url.searchParams.get('teamId')); return
6320
+ }
6321
+ if (path === TEAM_SET_ICON_PATH) {
6322
+ if (method !== 'POST') { send405(res, 'POST'); return }
6323
+ await handleSetTeamIcon(req, res, deps, cookie); return
6324
+ }
6242
6325
  if (path === '/api/npm/reviews/latest') {
6243
6326
  if (method !== 'GET') { send405(res, 'GET'); return }
6244
6327
  const s = workspaceSession!
@@ -65,7 +65,7 @@ function credentialFailure(err: unknown): err is GithubApiError {
65
65
  // that token (`userToken`, hashed), whichever credential reads it: a private
66
66
  // repository's was granted on who that token told GitHub they are. The next
67
67
  // check asks GitHub, falling back to the installation's or none as it does.
68
- type RepoMetadata = { id?: unknown; full_name?: unknown; private?: unknown; visibility?: unknown; default_branch?: unknown; archived?: unknown }
68
+ type RepoMetadata = { id?: unknown; full_name?: unknown; private?: unknown; visibility?: unknown; default_branch?: unknown; archived?: unknown; owner?: unknown }
69
69
  type AccessVerdict = { until: number; data: RepoMetadata; credential: 'user' | 'app' | 'none'; level: string | null; userToken: string | null }
70
70
  type VerdictCache = { get(): AccessVerdict | undefined; set(verdict: Omit<AccessVerdict, 'until' | 'userToken'>): void }
71
71
  const MAX_ACCESS_VERDICTS = 1000
@@ -176,7 +176,7 @@ type Access = { data: RepoMetadata; token: string | null; level: string | null }
176
176
  // github-moved) or names another repository by it since, by its id,
177
177
  // which neither changes. Where GitHub names it otherwise now, `repo` is named
178
178
  // so, and `renamed` told. Throws where GitHub tells of no repository of its id.
179
- async function currentMetadata(repo: SelectedRepo, metadata: (url: string) => Promise<unknown>, renamed: RepositoryRenamed | undefined): Promise<RepoMetadata> {
179
+ export async function currentMetadata(repo: SelectedRepo, metadata: (url: string) => Promise<unknown>, renamed: RepositoryRenamed | undefined): Promise<RepoMetadata> {
180
180
  let movedTo: number | null = null, named: RepoMetadata | null = null
181
181
  try { named = await metadata(repoApi(repo.fullName)) as RepoMetadata } catch (err) {
182
182
  if (!isGithubMoved(err)) throw err
@@ -0,0 +1,50 @@
1
+ // A team's icon: the avatar of a GitHub organization owning one of the
2
+ // team's repositories, chosen on Manage → Teams (POST /api/admin/teams/set-icon),
3
+ // or none, the default icon. A user's own account is never offered: only
4
+ // owners GitHub tells are organizations. The organization is kept by its
5
+ // numeric id, which survives a rename, and its login as it was when chosen.
6
+ // The icon stays until it is changed, though the team's repositories change.
7
+ // Its avatar is served as `/api/avatar/org-<id>` (http.ts).
8
+ import type { ManagedConfig } from './config.ts'
9
+ import type { SelectedRepo, TeamIcon } from './db-methods.ts'
10
+ import { accountOf } from './github-accounts.ts'
11
+ import { repoAccessToken } from './github-app.ts'
12
+ import { githubJson } from './github-requests.ts'
13
+ import { LOGIN } from './github-values.ts'
14
+ import { eachOf } from './queue.ts'
15
+ import { currentMetadata } from './repository-browser.ts'
16
+
17
+ // The organizations a team may show, by login, and the owners of its
18
+ // repositories GitHub could not be asked about, by their names' owner.
19
+ export interface TeamIconChoices { organizations: TeamIcon[]; unchecked: string[] }
20
+
21
+ // What `/api/avatar/org-<id>` names: an organization by its id.
22
+ export const ORGANIZATION_AVATAR = /^org-([1-9]\d{0,11})$/u
23
+ // A GitHub login, as a team's icon is asked for by (no App's `[bot]`).
24
+ export const isOrganizationLogin = (value: unknown): value is string => typeof value === 'string' && LOGIN.test(value) && !value.endsWith('[bot]')
25
+
26
+ const ownerOf = (fullName: string) => fullName.split('/', 1)[0]!.toLowerCase()
27
+ const GITHUB_REQUESTS_AT_ONCE = 4
28
+
29
+ // The organizations owning `repos` (a team's), each once, sorted by login, as
30
+ // GitHub tells each repository's owner now, one renamed or transferred since
31
+ // included (currentMetadata); and the owners, as the repositories are named,
32
+ // of those GitHub could not be asked about, past any it told of.
33
+ export async function teamOrganizations(config: ManagedConfig, repos: readonly SelectedRepo[], fetchImpl: typeof fetch): Promise<TeamIconChoices> {
34
+ const told = await eachOf([...repos], GITHUB_REQUESTS_AT_ONCE, async (repo) => {
35
+ try {
36
+ const token = await repoAccessToken(config, repo.installationId, fetchImpl)
37
+ const { owner } = await currentMetadata({ ...repo }, url => githubJson(url, token, fetchImpl), undefined)
38
+ const { id, login } = accountOf(owner as { id?: unknown; login?: unknown } | undefined)
39
+ return { repo, icon: id !== null && (owner as { type?: unknown }).type === 'Organization' ? { id, login: login! } : null }
40
+ } catch (err) {
41
+ console.warn(`managed: team icon owner of ${repo.fullName} unread:`, err instanceof Error ? err.message : err)
42
+ return { repo, icon: undefined }
43
+ }
44
+ })
45
+ const read = new Set(told.flatMap(({ repo, icon }) => icon === undefined ? [] : [ownerOf(repo.fullName)]))
46
+ return {
47
+ organizations: [...new Map(told.flatMap(({ icon }) => icon ? [[icon.id, icon] as const] : [])).values()].toSorted((a, b) => a.login.localeCompare(b.login)),
48
+ unchecked: [...new Set(told.flatMap(({ repo, icon }) => icon === undefined && !read.has(ownerOf(repo.fullName)) ? [ownerOf(repo.fullName)] : []))].toSorted(),
49
+ }
50
+ }