@preventive/triage 1.0.0-alpha.85 → 1.0.0-alpha.87

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 (44) hide show
  1. package/common/bundle-compare-diff.js +3 -2
  2. package/common/dependency-reviews.d.ts +1 -0
  3. package/common/dependency-reviews.js +3 -0
  4. package/common/github-issue-labels.d.ts +3 -1
  5. package/common/github-issue-labels.js +37 -6
  6. package/common/managed/roles.ts +7 -0
  7. package/common/managed/routes.js +7 -6
  8. package/out/activity.js +2 -2
  9. package/out/{chunk-ULI2BIWN.js → chunk-3TJCEPHF.js} +1 -1
  10. package/out/chunk-5LY6QSPD.js +265 -0
  11. package/out/chunk-7PXMWWTQ.js +1 -0
  12. package/out/{chunk-ZQQALNFP.js → chunk-BZJU5EEV.js} +1 -1
  13. package/out/{chunk-YU3IUQY6.js → chunk-PSS7UX5T.js} +1 -1
  14. package/out/chunk-Q2NFBTNH.js +1 -0
  15. package/out/{chunk-CE2FMDK3.js → chunk-TKPNRQNN.js} +1 -1
  16. package/out/{chunk-ZJDDTEL2.js → chunk-WKXQOUNH.js} +2 -2
  17. package/out/{chunk-XHYX3Q34.js → chunk-XRAAYXPR.js} +1 -1
  18. package/out/{chunk-R7HUX4PF.js → chunk-ZKJ7COEH.js} +1 -1
  19. package/out/chunk-ZPIUN4FW.js +55 -0
  20. package/out/client-managed-import.js +1 -1
  21. package/out/client-managed.js +28 -28
  22. package/out/compare.js +13 -13
  23. package/out/dialogs.js +38 -38
  24. package/out/graph.js +1 -1
  25. package/out/index.html +8 -8
  26. package/out/scan.js +2 -2
  27. package/out/view.css +1 -1
  28. package/out/view.js +8 -8
  29. package/package.json +2 -2
  30. package/risk/files/script.js +19 -9
  31. package/server-e2e/config.ts +3 -1
  32. package/server-managed/dependabot-access.ts +41 -17
  33. package/server-managed/dependabot-alerts.ts +19 -2
  34. package/server-managed/github-issues.ts +26 -14
  35. package/server-managed/github-users.ts +23 -0
  36. package/server-managed/http.ts +271 -123
  37. package/server-managed/npm-patch.ts +3 -1
  38. package/server-managed/repository-browser.ts +3 -2
  39. package/server-managed/repository-risk-assess.ts +10 -0
  40. package/out/chunk-7I6SZIJU.js +0 -1
  41. package/out/chunk-EZ62FJ5T.js +0 -266
  42. package/out/chunk-V4U7URJF.js +0 -54
  43. package/out/chunk-WOCJFOXN.js +0 -1
  44. /package/out/{chunk-6WMQVUT2.js → chunk-3YPZ7UBC.js} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/triage",
3
- "version": "1.0.0-alpha.85",
3
+ "version": "1.0.0-alpha.87",
4
4
  "description": "Client & relay server for triaging of automated reports",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": {
@@ -462,7 +462,7 @@
462
462
  "@exodus/stasis": "1.0.0-rc.11",
463
463
  "@exodus/stasis-core": "1.0.0-rc.11",
464
464
  "@preventive/archive": "^1.5.0",
465
- "@preventive/compare": "^1.4.1",
465
+ "@preventive/compare": "^1.5.0",
466
466
  "@preventive/diff": "^1.1.1",
467
467
  "@preventive/lockfile": "^1.3.1",
468
468
  "@preventive/publishers": "^1.1.0",
@@ -39,6 +39,11 @@ const REGEX_PART = () => String.raw`[^/\\[\n]|\\.|\[${stretched(String.raw`[^\]\
39
39
  // stretch at a time (stretched), as one loop over megabytes runs out of stack.
40
40
  const literalsSource = context => String.raw`((?=\/)${context}\/(?![/*])(?:${REGEX_PART()})${stretched(REGEX_PART)}(?:\/[a-z]*|(?=\\?$))|${STRING('"')}|${STRING("'")}|\x60${TEMPLATE_TEXT})`
41
41
  + String.raw`|(?<![ \t])[ \t]*(?:\/\*${stretched(String.raw`[^*]|\*(?!\/)`)}(?:\*\/|(?![\s\S]))|\/\/${stretched('.')}|(?<![\s\S])\uFEFF?#!${stretched('.')})[ \t]*`
42
+ // Where a keyword starts as a word of its own: after no character of a name
43
+ // (`elif`, `$if`, `#in`), nor a braced Unicode escape, which writes one
44
+ // (`a\u{61}if` is the name `aaif`), however many digits it has; looked back
45
+ // on only where a keyword is.
46
+ const WORD_STARTS = String.raw`(?<![\p{ID_Continue}$#])(?<!\\u\{[\da-fA-F]+\})`
42
47
  // A regular expression first where a value starts (after `=>`, `...`, an
43
48
  // operator or a keyword, not a property: `x.default/2`, `this.#in/2`), so a
44
49
  // quote in it (`/["']/`) starts no string; after a `)` or `}` too where it
@@ -46,7 +51,7 @@ const literalsSource = context => String.raw`((?=\/)${context}\/(?![/*])(?:${REG
46
51
  // one. A `++` or `--` is a postfix one, as JavaScript reads them in pairs,
47
52
  // after which `/` divides (`i++ / 2`); an odd run of them ends in an operator
48
53
  // (`a + /x/`, `a +++ /x/`).
49
- const VALUE_STARTS = String.raw`(?<=(?:^|\.\.\.|[(,=:[!&|?{;>*/%^<~]|(?<!\+)(?:\+\+)*\+|(?<!-)(?:--)*-|(?<![\p{ID_Continue}$.#])(?:await|case|default|delete|do|else|extends|in|instanceof|new|of|return|throw|typeof|void|yield))[ \t]*)`
54
+ const VALUE_STARTS = String.raw`(?<=(?:^|\.\.\.|[(,=:[!&|?{;>*/%^<~]|(?<!\+)(?:\+\+)*\+|(?<!-)(?:--)*-|(?<!\.)${WORD_STARTS}(?:await|case|default|delete|do|else|extends|in|instanceof|new|of|return|throw|typeof|void|yield))[ \t]*)`
50
55
  // JavaScript's strings and regular expressions (the first group) and its
51
56
  // comments, for a reader that sets them aside (runs-code.js, hosts.js), read
52
57
  // through jsMatchAll, which tells a regular expression after a `)` or `}`
@@ -104,16 +109,21 @@ const TEMPLATE_REST = new RegExp(String.raw`(\}${TEMPLATE_TEXT})`, 'uy')
104
109
  // tells, TypeScript's after `>` or `void` among them (`(): Promise<void> {`,
105
110
  // `extends A<B> {`, `(): void {`).
106
111
  const BLOCK = 'block', EITHER = 'either', VALUE = 'value'
107
- const BLOCK_AFTER = /(?:[;}]|=>|(?<![\p{ID_Continue}$#])(?:else|do|try|finally))$/u
112
+ // Its keywords looked back on in the whole text, as WORD_STARTS reads one.
113
+ const BLOCK_AFTER = new RegExp(String.raw`(?<=[;}]|=>|${WORD_STARTS}(?:else|do|try|finally))`, 'uy')
108
114
  const VALUE_AFTER = /(?:[=([,?!~%^&|*/<]|\.\.\.|(?<!\+)(?:\+\+)*\+|(?<!-)(?:--)*-)$/u
109
- const KEYWORD_AFTER = /(?<![\p{ID_Continue}$#.])(?:typeof|delete|in|instanceof|new|case|return|throw)$/u
115
+ const KEYWORD_AFTER = new RegExp(String.raw`(?<=(?<!\.)${WORD_STARTS}(?:typeof|delete|in|instanceof|new|case|return|throw))`, 'uy')
116
+ const ends = (pattern, text, at) => {
117
+ pattern.lastIndex = at
118
+ return pattern.test(text)
119
+ }
110
120
  function braceKind(text, at, read, closed, enclosing) {
111
121
  let code = at
112
122
  while (code > read && /\s/u.test(text[code - 1])) code--
113
123
  if (code === read) return read === 0 ? BLOCK : read === enclosing?.code ? VALUE : EITHER
114
124
  const before = text.slice(Math.max(read, code - 11), code)
115
- if (BLOCK_AFTER.test(before) || (closed && before.endsWith(')')) || (enclosing === BLOCK && before.endsWith('{'))) return BLOCK
116
- return VALUE_AFTER.test(before) || (KEYWORD_AFTER.test(before) && !text.slice(code, at).includes('\n')) ? VALUE : EITHER
125
+ if (ends(BLOCK_AFTER, text, code) || (closed && before.endsWith(')')) || (enclosing === BLOCK && before.endsWith('{'))) return BLOCK
126
+ return VALUE_AFTER.test(before) || (ends(KEYWORD_AFTER, text, code) && !text.slice(code, at).includes('\n')) ? VALUE : EITHER
117
127
  }
118
128
  // Whether only blanks are before `at` on its line, where a regular
119
129
  // expression may follow a `}` on a line before.
@@ -152,10 +162,10 @@ function* readAny(text, own, from) {
152
162
  }
153
163
  // A `(` opening a condition: after `if`, `while`, `for` (`for await` too) or
154
164
  // `with` (its first group, the blanks after it its second), a word of its own
155
- // (not `elif(`), not a property's name, blanks after its dot or none (`x.if(`,
156
- // `x. if(`), nor one after a comment there (`x./* c */if(`), as jsMatchAll
157
- // tells by the comment before it.
158
- const CONDITION = /(?<=(?<![\p{ID_Continue}$#])(?<!\.\s*)(if|while|with|for(?:\s+await)?)(\s*))\(/uy
165
+ // (WORD_STARTS: not `elif(`, `a\u{61}if(`), not a property's name, blanks
166
+ // after its dot or none (`x.if(`, `x. if(`), nor one after a comment there
167
+ // (`x./* c */if(`), as jsMatchAll tells by the comment before it.
168
+ const CONDITION = new RegExp(String.raw`(?<=${WORD_STARTS}(?<!\.\s*)(if|while|with|for(?:\s+await)?)(\s*))\(`, 'uy')
159
169
  // What a match that is neither a string nor a reader's own starts with: a
160
170
  // comment's `//` or `/*`, or a hashbang, blanks before it.
161
171
  const COMMENT = /^[ \t]*(?:\/[/*]|\uFEFF?#!)/u
@@ -56,7 +56,9 @@ Environment:
56
56
  Unset by default (no external scan service).
57
57
  GITHUB_NEW_ISSUE_LABELS optional comma-separated labels for the client's
58
58
  prefilled GitHub issue form, in addition to
59
- deepview and security (for security findings).
59
+ deepview, security (for security findings) and
60
+ dependencies and deps (for findings on an
61
+ advisory).
60
62
  Advertised in /api/config and sync connections.
61
63
  DB_PATH sqlite file (default: server-e2e/data/data.db);
62
64
  ignored when an e2e database URL is set
@@ -3,24 +3,29 @@
3
3
  // GitHub, as doc/bundles.md's repository risk scan section tells.
4
4
  import type { ManagedConfig } from './config.ts'
5
5
  import type { SelectedRepo } from './db.ts'
6
- import { type DependabotAlert, dependabotAlerts } from './dependabot-alerts.ts'
6
+ import { type DependabotAlert, dependabotAlerts, listsAlerts } from './dependabot-alerts.ts'
7
7
  import { type GithubIdentity, githubRepoPermission, repoAccessToken, repositoryInstallation } from './github-app.ts'
8
8
  import { GithubApiError } from './github-errors.ts'
9
9
 
10
10
  // The levels GitHub lets see a repository's Dependabot alerts by default
11
- // (maintain's reads `write`).
11
+ // (maintain's reads `write`). Others may see them too, by a role the level
12
+ // doesn't tell, as the security manager's: GitHub is asked of those
13
+ // (appDependabotAlerts).
12
14
  const SEES_ALERTS: ReadonlySet<string> = new Set(['admin', 'write'])
13
15
  // Failures of verifying the sign-in that are the sign-in's own: no token, or
14
16
  // one of another account (repository-browser.ts getIdentity), or one GitHub no
15
17
  // longer takes. Any other, as GitHub failing to answer, is told as it is.
16
18
  const UNVERIFIED: ReadonlySet<string> = new Set(['no-repository', 'github-unauthorized'])
19
+ const unverified = (error: unknown) => error instanceof GithubApiError && UNVERIFIED.has(error.message) ? new GithubApiError(403, 'dependabot-unverified') : error
17
20
 
18
21
  // What of a repository's reader (repository-browser.ts) the alerts are asked
19
- // with: the user's verified identity, and their permission level where its
20
- // access gate asked GitHub of it already.
22
+ // with: the user's verified identity, their permission level where its
23
+ // access gate asked GitHub of it already, and their own token, of the App's
24
+ // user authorization, whose account `identity` verifies (null for none).
21
25
  export interface AlertsReader {
22
26
  identity(): Promise<GithubIdentity>
23
27
  permission(): string | null
28
+ userToken(): string | null
24
29
  }
25
30
 
26
31
  // Alerts read, and their `recheck`: the user's access to them checked again,
@@ -31,12 +36,16 @@ export interface AlertsRead { alerts: DependabotAlert[]; recheck(): Promise<void
31
36
  // `repo`'s Dependabot alerts (dependabot-alerts.ts), read with the token of
32
37
  // the App's installation GitHub tells covers it now, its token checked to read
33
38
  // it (github-app.ts repositoryInstallation), never the one its connection
34
- // keeps, which may no longer cover it, once the user's own permission on it
35
- // lets them see them; else refused, the alerts not asked:
36
- // `dependabot-not-installed`, `dependabot-unverified`, or
37
- // `dependabot-forbidden`, naming their permission. The token is asked each
38
- // time of repoAccessToken, which renews it before it expires, as the recheck
39
- // may come long after the alerts are read.
39
+ // keeps, which may no longer cover it, once the user's own access to it lets
40
+ // them see them: their permission level, or else, as a security manager or a
41
+ // custom role isn't told by it, whether GitHub lists the alerts to their own
42
+ // token (listsAlerts), asked only of those their level refuses; else
43
+ // refused, the alerts not asked: `dependabot-not-installed`,
44
+ // `dependabot-unverified`, or `dependabot-forbidden`, naming their
45
+ // permission. The recheck asks GitHub as access was found, by their level or
46
+ // by their own token alone, one request as before. The installation's token
47
+ // is asked each time of repoAccessToken, which renews it before it expires,
48
+ // as the recheck may come long after the alerts are read.
40
49
  export async function appDependabotAlerts(config: ManagedConfig, repo: Pick<SelectedRepo, 'repoId' | 'fullName'>, reader: AlertsReader,
41
50
  fetchImpl: typeof fetch = globalThis.fetch): Promise<AlertsRead> {
42
51
  const id = await repositoryInstallation(config, repo.repoId, repo.fullName, fetchImpl)
@@ -47,15 +56,30 @@ export async function appDependabotAlerts(config: ManagedConfig, repo: Pick<Sele
47
56
  }
48
57
  const token = await tokenNow()
49
58
  let who
50
- try { who = await reader.identity() } catch (error) {
51
- throw error instanceof GithubApiError && UNVERIFIED.has(error.message) ? new GithubApiError(403, 'dependabot-unverified') : error
52
- }
53
- const seen = (permission: string) => {
54
- if (!SEES_ALERTS.has(permission)) {
59
+ try { who = await reader.identity() } catch (error) { throw unverified(error) }
60
+ const own = reader.userToken()
61
+ // Whether GitHub lists them to the user's own token, else refused, naming
62
+ // their level.
63
+ const listed = async (permission: string) => {
64
+ let found = false
65
+ if (own != null) {
66
+ try { found = await listsAlerts(repo.fullName, own, fetchImpl) } catch (error) { throw unverified(error) }
67
+ }
68
+ if (!found) {
55
69
  throw new GithubApiError(403, 'dependabot-forbidden', null, `@${who.login}'s access to this repository (${permission}) doesn't let them see its Dependabot alerts on GitHub`)
56
70
  }
57
71
  }
58
- seen(reader.permission() ?? await githubRepoPermission(repo.fullName, token, who, fetchImpl))
72
+ // Whether access was found by their own token, the level they had then.
73
+ let byOwnToken: string | null = null
74
+ const seen = async (permission: string) => {
75
+ if (SEES_ALERTS.has(permission)) return
76
+ await listed(permission)
77
+ byOwnToken = permission
78
+ }
79
+ await seen(reader.permission() ?? await githubRepoPermission(repo.fullName, token, who, fetchImpl))
59
80
  const alerts = await dependabotAlerts(repo.fullName, token, fetchImpl)
60
- return { alerts, recheck: async () => { seen(await githubRepoPermission(repo.fullName, await tokenNow(), who, fetchImpl)) } }
81
+ return { alerts, recheck: async () => {
82
+ if (byOwnToken == null) await seen(await githubRepoPermission(repo.fullName, await tokenNow(), who, fetchImpl))
83
+ else await listed(byOwnToken)
84
+ } }
61
85
  }
@@ -51,6 +51,8 @@ const PER_PAGE = 100
51
51
  const MAX_PAGES = 20
52
52
  // A page holds each advisory's whole text: given longer than githubJson's.
53
53
  const PAGE_TIMEOUT_MS = 20_000
54
+ // Whether one is listed (listsAlerts): as long as githubJson gives a read.
55
+ const LISTED_TIMEOUT_MS = 10_000
54
56
  const GHSA = /^GHSA(?:-[23456789cfghjmpqrvwx]{4}){3}$/u
55
57
  const SEVERITIES = new Map([['critical', 'critical'], ['high', 'high'], ['medium', 'moderate'], ['moderate', 'moderate'], ['low', 'low']])
56
58
  // A path from a repository's root, as git takes one: no empty, `.` or `..`
@@ -113,11 +115,11 @@ function nextPage(link: string | null): [string, string] | null {
113
115
  // (`dependabot-disabled`) or not to be read by the App's installation
114
116
  // (`dependabot-app-permission`), as a 404 is, the repository found just
115
117
  // before; the rest as githubJson tells them.
116
- async function askPage(url: string, token: string, fetchImpl: typeof fetch): Promise<{ alerts: unknown[]; link: string | null }> {
118
+ async function askPage(url: string, token: string, fetchImpl: typeof fetch, timeoutMs = PAGE_TIMEOUT_MS): Promise<{ alerts: unknown[]; link: string | null }> {
117
119
  const started = Date.now()
118
120
  let res: Response
119
121
  try {
120
- res = await fetchImpl(url, { signal: AbortSignal.timeout(PAGE_TIMEOUT_MS), redirect: 'error', headers: githubHeaders(token) })
122
+ res = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs), redirect: 'error', headers: githubHeaders(token) })
121
123
  } catch (error) { throw githubUnreachable(error, started) }
122
124
  if (res.status === 403) {
123
125
  const message = (await res.clone().json().catch(() => null) as { message?: unknown } | null)?.message
@@ -135,6 +137,21 @@ async function askPage(url: string, token: string, fetchImpl: typeof fetch): Pro
135
137
  return { alerts: body, link: res.headers.get('link') }
136
138
  }
137
139
 
140
+ // Whether GitHub lists `fullName`'s Dependabot alerts to `token`, a signed-in
141
+ // user's own token of the App's user authorization (dependabot-access.ts), as
142
+ // it does to anyone it lets see them: a security manager, or one whose custom
143
+ // or organization role grants it, as well as one with write, where the App
144
+ // may read them too. A 403 or 404 that isn't a rate limit is a no, but that
145
+ // they are off (`dependabot-disabled`); the rest as askPage tells them. One
146
+ // alert asked, never read.
147
+ export async function listsAlerts(fullName: string, token: string, fetchImpl: typeof fetch = globalThis.fetch): Promise<boolean> {
148
+ try { await askPage(`${repoApi(fullName)}/dependabot/alerts?per_page=1`, token, fetchImpl, LISTED_TIMEOUT_MS) } catch (error) {
149
+ if (error instanceof GithubApiError && error.message === 'dependabot-app-permission') return false
150
+ throw error
151
+ }
152
+ return true
153
+ }
154
+
138
155
  // `fullName`'s alerts in `states`, MAX_PAGES at most, in GitHub's order (the
139
156
  // newest first), and whether that is all of them.
140
157
  async function listAlerts(fullName: string, states: readonly string[], token: string, fetchImpl: typeof fetch) {
@@ -5,7 +5,7 @@ import type { ManagedIssue } from './managed-issues.ts'
5
5
  import { randomToken } from './crypto.ts'
6
6
  import { githubIssueClosedReason } from '../common/github-pr.ts'
7
7
  import { reportEntries, reportRepoGithub } from '@preventive/report'
8
- import { newIssueLabels } from '../common/github-issue-labels.js'
8
+ import { issueLabelChoices, newIssueLabels } from '../common/github-issue-labels.js'
9
9
  import { ignoresOwnRepo } from '../common/finding-repo.js'
10
10
  import { appJwt, githubAppConfigured, installUrl, publicRepositoryName } from './github-app.ts'
11
11
  import { ISSUE_LOGIN_PATH } from './github-issue-oauth.ts'
@@ -72,7 +72,7 @@ export async function prepareGithubIssue(config: ManagedConfig, db: ManagedDb, s
72
72
  if (!finding) throw new TeamReportsError(404, 'no-finding')
73
73
  const recheck = () => recheckTeam(db, session.id, snapshot)
74
74
  await recheck()
75
- const labels = newIssueLabels(finding['isSecurity'] === true, config.githubNewIssueLabels ?? '')
75
+ const labels = newIssueLabels(finding, config.githubNewIssueLabels ?? '')
76
76
  const repoIds = snapshot.repositories.map(repo => repo.repoId)
77
77
  const stored = await db.getManagedIssue(context.findingId)
78
78
  if (stored) return { ...referenceResult(stored, repoIds), labels, recheck }
@@ -97,13 +97,21 @@ export async function prepareGithubIssue(config: ManagedConfig, db: ManagedDb, s
97
97
  if (!token) return { mode: 'authorize' as const, authorizationPath: ISSUE_LOGIN_PATH, labels, recheck }
98
98
  // All requested labels are optional, including security and operator labels.
99
99
  // Omit missing names rather than rejecting issue creation or creating labels.
100
- const existingLabels: string[] = []
101
- for (const name of labels) {
102
- const label = await github(`${path}/labels/${encodeURIComponent(name)}`, token, fetchImpl)
103
- if (label.status === 401) return { mode: 'authorize' as const, authorizationPath: ISSUE_LOGIN_PATH, labels, recheck }
104
- if (label.status === 404) continue
105
- if (!label.ok) throw new IssueError(502, 'github-unavailable')
106
- existingLabels.push(name)
100
+ // Of a choice's names, the first the repository has (`dependencies`, else
101
+ // `deps`), none once a label taken is among them; a name is read once.
102
+ const existingLabels: string[] = [], missing = new Set<string>()
103
+ const taken = (name: string) => existingLabels.some(label => label.toLowerCase() === name.toLowerCase())
104
+ for (const names of issueLabelChoices(finding, config.githubNewIssueLabels ?? '')) {
105
+ if (names.some(taken)) continue
106
+ for (const name of names) {
107
+ if (missing.has(name.toLowerCase())) continue
108
+ const label = await github(`${path}/labels/${encodeURIComponent(name)}`, token, fetchImpl)
109
+ if (label.status === 401) return { mode: 'authorize' as const, authorizationPath: ISSUE_LOGIN_PATH, labels, recheck }
110
+ if (label.status === 404) { missing.add(name.toLowerCase()); continue }
111
+ if (!label.ok) throw new IssueError(502, 'github-unavailable')
112
+ existingLabels.push(name)
113
+ break
114
+ }
107
115
  }
108
116
  return { mode: 'api' as const, token, path, labels: existingLabels, recheck,
109
117
  db, findingId: context.findingId, repoId: repository.repoId, repository: targetRepository, repoIds, userId: session.userId }
@@ -111,8 +119,12 @@ export async function prepareGithubIssue(config: ManagedConfig, db: ManagedDb, s
111
119
 
112
120
  export async function createGithubIssue(prepared: Awaited<ReturnType<typeof prepareGithubIssue>>, input: unknown, fetchImpl: typeof fetch = fetch) {
113
121
  if (prepared.mode !== 'api') throw new IssueError(409, 'github-authorization-required')
114
- const { title, body } = input as { title?: unknown; body?: unknown }
115
- if (typeof title !== 'string' || !title.trim() || title.length > 256 || typeof body !== 'string' || body.length > 65_536) throw new IssueError(400, 'bad-issue')
122
+ const { title, body, labels } = input as { title?: unknown; body?: unknown; labels?: unknown }
123
+ if (typeof title !== 'string' || !title.trim() || title.length > 256 || typeof body !== 'string' || body.length > 65_536
124
+ || (labels !== undefined && (!Array.isArray(labels) || labels.length > 100 || !labels.every(label => typeof label === 'string')))) throw new IssueError(400, 'bad-issue')
125
+ // The labels the creator kept checked of those proposed, every one where
126
+ // it names none: a name not proposed is never asked for, so none is created.
127
+ const chosen = Array.isArray(labels) ? prepared.labels.filter(label => labels.includes(label)) : prepared.labels
116
128
  const { db, findingId } = prepared
117
129
  const requestId = randomToken()
118
130
  if (!await db.claimManagedIssue({ findingId, repoId: prepared.repoId, repository: prepared.repository,
@@ -128,7 +140,7 @@ export async function createGithubIssue(prepared: Awaited<ReturnType<typeof prep
128
140
  // Release only when we know no issue was created; unknown outcomes stay claimed.
129
141
  try { await prepared.recheck() }
130
142
  catch (error) { await db.releaseManagedIssue(findingId, requestId); throw error }
131
- const response = await github(`${prepared.path}/issues`, prepared.token, fetchImpl, { title: title.trim(), body, labels: prepared.labels })
143
+ const response = await github(`${prepared.path}/issues`, prepared.token, fetchImpl, { title: title.trim(), body, labels: chosen })
132
144
  if (response.status >= 400 && response.status < 500) await db.releaseManagedIssue(findingId, requestId)
133
145
  if (response.status === 401) throw new IssueError(409, 'github-authorization-required')
134
146
  if (response.status === 403) throw new IssueError(403, 'github-issue-forbidden')
@@ -139,11 +151,11 @@ export async function createGithubIssue(prepared: Awaited<ReturnType<typeof prep
139
151
  // Construct the URL from validated inputs, never an upstream redirect target.
140
152
  const number = Number(issue.number), url = `https://github.com${prepared.path.slice('/repos'.length)}/issues/${issue.number}`
141
153
  if (!await db.finishManagedIssue(findingId, requestId, url)) throw new IssueError(502, 'github-create-uncertain')
142
- let details = issueDetails(issue, url, number, { title, body, labels: prepared.labels }), detailsUnavailable = true
154
+ let details = issueDetails(issue, url, number, { title, body, labels: chosen }), detailsUnavailable = true
143
155
  try {
144
156
  const fetched = await github(`${prepared.path}/issues/${number}`, prepared.token, fetchImpl)
145
157
  if (fetched.ok) {
146
- details = issueDetails(await fetched.json(), url, number, { title, body, labels: prepared.labels })
158
+ details = issueDetails(await fetched.json(), url, number, { title, body, labels: chosen })
147
159
  detailsUnavailable = false
148
160
  }
149
161
  } catch { /* Creation and its permanent reference succeeded; detail reads are best effort. */ }
@@ -18,6 +18,29 @@ export interface AppAgentUser { agent: GithubAgentId }
18
18
  // `answer` with the app's users and agents its accounts are (`users`, by
19
19
  // login), as a new object: what was kept of it, every reader's, is left as
20
20
  // it was. A login it names by more than one account is no one's.
21
+ // The app's users and agents `logins` are, by login, as withAppUsers tells
22
+ // those an answer names, for one naming accounts by login alone under keys
23
+ // of its own (a Dependabot alert's dismisser, repository-risk.ts).
24
+ export async function appUsersOf(db: ManagedDb, logins: Iterable<string>): Promise<Record<string, AppUser | AppAgentUser>> {
25
+ const accounts: { login: string; githubId: null }[] = [], agents: Record<string, AppAgentUser> = {}
26
+ for (const login of new Set(logins)) {
27
+ const agent = githubAgent(login, null)
28
+ if (agent) agents[login] = { agent }
29
+ else accounts.push({ login, githubId: null })
30
+ }
31
+ return { ...accounts.length > 0 ? await db.listUsersByAccount(accounts) : {}, ...agents }
32
+ }
33
+
34
+ // `lines` as each is sent, each naming logins (`loginsOf`) with the app's
35
+ // users and agents they are (`users`, appUsersOf), never kept with it: a
36
+ // scan's Dependabot lines and their alerts' dismissers.
37
+ export async function* withLineUsers<T extends object>(db: ManagedDb, lines: AsyncIterable<T>, loginsOf: (line: T) => string[]): AsyncGenerator<T | (T & { users: Record<string, AppUser | AppAgentUser> })> {
38
+ for await (const line of lines) {
39
+ const logins = loginsOf(line)
40
+ yield logins.length > 0 ? { ...line, users: await appUsersOf(db, logins) } : line
41
+ }
42
+ }
43
+
21
44
  export async function withAppUsers<T extends object>(db: ManagedDb, answer: T): Promise<T & { users: Record<string, AppUser | AppAgentUser> }> {
22
45
  const agents: Record<string, AppAgentUser> = {}
23
46
  const accounts = [...namedAccounts(answer)].flatMap(([login, githubId]) => {