@preventive/triage 1.0.0-alpha.74 → 1.0.0-alpha.75

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 (49) hide show
  1. package/common/finding-duplicates.js +4 -4
  2. package/common/finding-filters.js +11 -13
  3. package/common/managed/roles.ts +6 -0
  4. package/common/managed/routes.js +4 -3
  5. package/common/managed/team-app.d.ts +2 -0
  6. package/common/managed/team-app.js +31 -14
  7. package/out/activity.js +1 -1
  8. package/out/{chunk-VRAJCPV5.js → chunk-EYTPAODY.js} +2 -2
  9. package/out/chunk-ITUKKCCK.js +10 -0
  10. package/out/{chunk-BLPHP4U3.js → chunk-IVDE66N5.js} +1 -1
  11. package/out/{chunk-VS7RV24Z.js → chunk-NMC7P5AA.js} +2 -2
  12. package/out/chunk-O6FA2R5G.js +53 -0
  13. package/out/{chunk-YI4D6XVX.js → chunk-RHOQDAU4.js} +1 -1
  14. package/out/{chunk-GV5U7OLP.js → chunk-SZHJZVBL.js} +1 -1
  15. package/out/{chunk-2IHCVA3Y.js → chunk-T6EXDRB7.js} +1 -1
  16. package/out/chunk-VOJBPNPL.js +255 -0
  17. package/out/{chunk-C6OPCPCA.js → chunk-VSVFMSGI.js} +1 -1
  18. package/out/chunk-WGQ7D5DB.js +1 -0
  19. package/out/client-managed-import.js +1 -1
  20. package/out/client-managed.js +30 -30
  21. package/out/compare.js +4 -4
  22. package/out/dialogs.js +1 -1
  23. package/out/graph.js +1 -1
  24. package/out/index.html +8 -8
  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 +4 -4
  29. package/package.json +1 -1
  30. package/risk/files/characters.js +142 -8
  31. package/risk/files/hosts.js +4 -3
  32. package/risk/files/readability.js +18 -13
  33. package/risk/files/runs-code.js +41 -80
  34. package/risk/files/script.js +210 -48
  35. package/risk/index.d.ts +4 -2
  36. package/risk/npm/assess.js +1 -1
  37. package/risk/npm/tarball.js +35 -19
  38. package/server-managed/http.ts +64 -23
  39. package/server-managed/locked-packages.ts +62 -5
  40. package/server-managed/npm-packages.ts +7 -5
  41. package/server-managed/repository-code.ts +3 -2
  42. package/server-managed/repository-risk-read.ts +19 -13
  43. package/server-managed/team-app-summaries.ts +3 -1
  44. package/server-managed/team-app.ts +4 -2
  45. package/server-managed/team-reports.ts +8 -3
  46. package/out/chunk-5YP7P5KA.js +0 -1
  47. package/out/chunk-74AEKRES.js +0 -10
  48. package/out/chunk-DQJEVHRE.js +0 -52
  49. package/out/chunk-ESJZZF2Y.js +0 -255
@@ -15,9 +15,12 @@ export const MINIFIED_AVERAGE = 110
15
15
  const MINIFIED_SPACES = .01
16
16
  // What a regular expression set aside holds.
17
17
  const REGEX = '\uE000'
18
- // JavaScript's strings, templates and regular expressions (the first group)
19
- // and its comments, a regular expression read where `context` (a lookbehind)
20
- // says one starts.
18
+ // A template's text, after its backtick or a substitution's `}`, to its end
19
+ // or the next substitution's `${`.
20
+ const TEMPLATE_TEXT = String.raw`(?:[^\x60\\$]|\\(?:\r\n|[\s\S])|\$(?!\{))*(?:\x60|\$\{|(?![\s\S]))`
21
+ // JavaScript's strings, templates (to a substitution's `${`, as jsMatchAll
22
+ // reads one) and regular expressions (the first group) and its comments, a
23
+ // regular expression read where `context` (a lookbehind) says one starts.
21
24
  // A hashbang, the file's first line (`#!/usr/bin/env node`), a comment, after
22
25
  // a byte order mark too, which node's ES module loader drops first. A
23
26
  // string's or template's escape may be a line continuation (`\` before a line
@@ -27,21 +30,31 @@ const REGEX = '\uE000'
27
30
  // and what is left open read to where it would end, a string or a regular
28
31
  // expression its line's end, a template or a comment the text's, rather than
29
32
  // tried again from each later quote or slash.
30
- const literalsSource = context => String.raw`((?=\/)${context}\/(?![/*])(?:[^/\\[\n]|\\.|\[(?:[^\]\\\n]|\\.)*(?:\]|(?=\\?$)))+(?:\/[a-z]*|(?=\\?$))|"(?:[^"\\\n]|\\(?:\r\n|[\s\S]))*(?:"|$)|'(?:[^'\\\n]|\\(?:\r\n|[\s\S]))*(?:'|$)|\x60(?:[^\x60\\]|\\(?:\r\n|[\s\S]))*(?:\x60|(?![\s\S])))|(?<![ \t])[ \t]*(?:\/\*[\s\S]*?(?:\*\/|(?![\s\S]))|\/\/.*|(?<![\s\S])\uFEFF?#!.*)[ \t]*`
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]*`
31
34
  // A regular expression first where a value starts (after `=>`, `...`, an
32
35
  // operator or a keyword, not a property: `x.default/2`, `this.#in/2`), so a
33
- // quote in it (`/["']/`) starts no string; after a `)` too where it closes a
34
- // control-flow statement's condition, as jsMatchAll reads one. A `++` or `--`
35
- // is a postfix one, as JavaScript reads them in pairs, after which `/` divides
36
- // (`i++ / 2`); an odd run of them ends in an operator (`a + /x/`, `a +++ /x/`).
37
- 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]*)`
36
+ // quote in it (`/["']/`) starts no string; after a `)` or `}` too where it
37
+ // closes a control-flow statement's condition or a block, as jsMatchAll reads
38
+ // one. A `++` or `--` is a postfix one, as JavaScript reads them in pairs,
39
+ // after which `/` divides (`i++ / 2`); an odd run of them ends in an operator
40
+ // (`a + /x/`, `a +++ /x/`).
41
+ 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]*)`
38
42
  // JavaScript's strings and regular expressions (the first group) and its
39
43
  // comments, for a reader that sets them aside (runs-code.js, hosts.js), read
40
- // through jsMatchAll, which tells a regular expression after a `)` from a
41
- // division.
44
+ // through jsMatchAll, which tells a regular expression after a `)` or `}`
45
+ // from a division.
42
46
  export const JS_STRING_OR_COMMENT = new RegExp(literalsSource(VALUE_STARTS), 'gmu')
43
47
  const JS = {
44
- matchAll: text => jsMatchAll(text),
48
+ // Its literals, what one holds aside: a template's substitutions', and
49
+ // what is read both ways past a `}` (jsMatchAll).
50
+ * matchAll(text) {
51
+ let end = 0
52
+ for (const found of jsMatchAll(text)) {
53
+ if (found.index < end) continue
54
+ end = found.index + found[0].length
55
+ yield found
56
+ }
57
+ },
45
58
  // Beside punctuation (`a, b`, `x = 1`), not between two words, as
46
59
  // JavaScript tells a word's characters (`return a`, `var π`, `var \u03c0`),
47
60
  droppable: /(?<![\p{ID_Continue}$\\\u200C\u200D])[ \t]+|[ \t]+(?![\p{ID_Continue}$\\\u200C\u200D])/gu,
@@ -66,12 +79,69 @@ const CSS = {
66
79
  && (depth > 0 || /^\s*--[^:]*:/u.test(code.slice(Math.max(...['{', ';', '}'].map(end => code.lastIndexOf(end, index))) + 1, index))),
67
80
  }
68
81
 
69
- // A `/` after a `)`, blanks between or none, that starts no comment: a regular
70
- // expression's where the `)` closes a control-flow statement's condition (`if
71
- // (x) /["]/.test(s)`, `while (i--) /'/.test(s)`), else a division's (`(a) /
72
- // b`), told apart by the parentheses before it, which no lookbehind can
73
- // match. Its group the last.
74
- const AFTER_PARENTHESIS = String.raw`(?=\/)(?<=\)[ \t]*)(\/)(?![/*])`
82
+ // A `/` after a `)` or `}`, blanks between or none, that starts no comment: a
83
+ // regular expression's where the `)` closes a control-flow statement's
84
+ // condition (`if (x) /["]/.test(s)`, `while (i--) /'/.test(s)`) or the `}` a
85
+ // block, else a division's (`(a) / b`, `x = {} / 1`), told apart by the
86
+ // parentheses and braces before it, which no lookbehind can match.
87
+ const AFTER_CLOSE = String.raw`(?=\/)(?<=[)}][ \t]*)(\/)(?![/*])`
88
+ // A template's text after a substitution's `}` (the first group).
89
+ const TEMPLATE_REST = new RegExp(String.raw`(\}${TEMPLATE_TEXT})`, 'uy')
90
+ // What a `{` opens, by the code before it, blanks aside: a BLOCK (after `;`,
91
+ // `}`, `=>`, a condition's `)`, `else`, `do`, `try` or `finally`, in a block
92
+ // or first in the text), after which `/` starts a regular expression; a
93
+ // VALUE, an object literal (after an operator, `...`, a keyword on its line
94
+ // taking a value, or first in a substitution), after which it divides; or
95
+ // EITHER, as a function's, class's or label's body may be, as only a parse
96
+ // tells, TypeScript's after `>` or `void` among them (`(): Promise<void> {`,
97
+ // `extends A<B> {`, `(): void {`).
98
+ const BLOCK = 'block', EITHER = 'either', VALUE = 'value'
99
+ const BLOCK_AFTER = /(?:[;}]|=>|(?<![\p{ID_Continue}$#])(?:else|do|try|finally))$/u
100
+ const VALUE_AFTER = /(?:[=([,?!~%^&|*/<]|\.\.\.|(?<!\+)(?:\+\+)*\+|(?<!-)(?:--)*-)$/u
101
+ const KEYWORD_AFTER = /(?<![\p{ID_Continue}$#.])(?:typeof|delete|in|instanceof|new|case|return|throw)$/u
102
+ function braceKind(text, at, read, closed, enclosing) {
103
+ let code = at
104
+ while (code > read && /\s/u.test(text[code - 1])) code--
105
+ if (code === read) return read === 0 ? BLOCK : read === enclosing?.code ? VALUE : EITHER
106
+ const before = text.slice(Math.max(read, code - 11), code)
107
+ if (BLOCK_AFTER.test(before) || (closed && before.endsWith(')')) || (enclosing === BLOCK && before.endsWith('{'))) return BLOCK
108
+ return VALUE_AFTER.test(before) || (KEYWORD_AFTER.test(before) && !text.slice(code, at).includes('\n')) ? VALUE : EITHER
109
+ }
110
+ // Whether only blanks are before `at` on its line, where a regular
111
+ // expression may follow a `}` on a line before.
112
+ const LINE_START = /(?<=^[ \t]*)/muy
113
+ function startsLine(text, at) {
114
+ LINE_START.lastIndex = at
115
+ return LINE_START.test(text)
116
+ }
117
+ // Past a `/` after a `}` that is EITHER's, where a string, template or
118
+ // regular expression one reading holds the other may read as code: the rest
119
+ // read as any reading may, each of a reader's own matches in it (`own`), each
120
+ // string and template from each quote or backtick no backslash escapes to the
121
+ // next of its kind (ANY_LITERAL, a string to its line's end at most), and
122
+ // last the rest whole as a string's, template's or regular expression's
123
+ // text, so nothing node runs is hidden whichever way it reads it. Linear, as
124
+ // 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
127
+ function* readAny(text, own, from) {
128
+ const next = (pattern, at) => {
129
+ if (pattern === null) return null
130
+ pattern.lastIndex = at
131
+ return pattern.exec(text)
132
+ }
133
+ for (let literal = next(ANY_LITERAL, from), mine = next(own, from); literal !== null || mine !== null;) {
134
+ if (mine === null || (literal !== null && literal.index <= mine.index)) {
135
+ yield literal
136
+ literal = next(ANY_LITERAL, literal.index + 1)
137
+ } else {
138
+ yield mine
139
+ mine = next(own, mine.index + Math.max(mine[0].length, 1))
140
+ }
141
+ }
142
+ REST.lastIndex = from
143
+ yield REST.exec(text)
144
+ }
75
145
  // A `(` opening a condition: after `if`, `while`, `for` (`for await` too) or
76
146
  // `with` (its first group, the blanks after it its second), a word of its own
77
147
  // (not `elif(`), not a property's name, blanks after its dot or none (`x.if(`,
@@ -85,46 +155,103 @@ const COMMENT = /^[ \t]*(?:\/[/*]|\uFEFF?#!)/u
85
155
  const DOT_BEFORE = /(?<=\.\s*)/uy
86
156
  // The first character that is no blank.
87
157
  const CODE = /\S/gu
158
+ // A template literal read (piece's `template`) as a match: from its start to
159
+ // `end`, its first group its pieces' text, each substitution's code left out
160
+ // (`/proc/${pid}/mem` read as `/proc/${}/mem`), and where each piece starts,
161
+ // there and in the text (`pieces`, as jsOffset reads them).
162
+ const templateFound = (text, { index, pieces, text: pieced }, end) => Object.assign([text.slice(index, end), pieced], { index, pieces })
163
+ // A template's piece (`found`, to a `${` or from a substitution's `}`, of
164
+ // `template` or the first of one): its text added to the template's, and
165
+ // where that ends, the template put in its place before what its
166
+ // substitutions hold (`templates.held`), all given back once none is open.
167
+ function* piece(text, found, template, { open, held }, braces) {
168
+ const end = found.index + found[0].length
169
+ if (template === null) {
170
+ template = { index: found.index, text: '', pieces: [], slot: held.length }
171
+ open.push(template)
172
+ held.push(null)
173
+ }
174
+ template.pieces.push([template.text.length, found.index])
175
+ template.text += found[1]
176
+ if (found[1].endsWith('${')) braces.push({ code: end, template })
177
+ else {
178
+ held[template.slot] = templateFound(text, open.pop(), end)
179
+ if (open.length === 0) yield* held.splice(0)
180
+ }
181
+ }
182
+ // What is held for the templates open where the text, or the reading of it,
183
+ // ends, each read to there.
184
+ function* ended(text, { open, held }) {
185
+ for (const template of open) held[template.slot] = templateFound(text, template, text.length)
186
+ yield* held
187
+ }
188
+ // Where `within` a literal's text (jsMatchAll's first group) is in the text:
189
+ // a template's, its substitutions' code left out, by where its pieces are.
190
+ export function jsOffset({ index, pieces }, within) {
191
+ if (pieces === undefined) return index + within
192
+ let high = pieces.length, low = 0
193
+ while (low < high) {
194
+ const middle = (low + high) >> 1
195
+ if (pieces[middle][0] <= within) low = middle + 1
196
+ else high = middle
197
+ }
198
+ return pieces[low - 1][1] + within - pieces[low - 1][0]
199
+ }
88
200
  // How jsMatchAll reads a text for a reader's alternatives (a pattern's
89
- // source): by JS_STRING_OR_COMMENT's, theirs, and AFTER_PARENTHESIS last
90
- // (`scan`, its group `slash`); and at that `/`, by the same with a regular
91
- // expression read wherever one starts (`regex`). Each made once.
201
+ // source): by JS_STRING_OR_COMMENT's, theirs, AFTER_CLOSE and a brace last
202
+ // (`scan`, their groups `slash` and `brace`); at that `/`, by the same with a
203
+ // regular expression read wherever one starts (`regex`); and past it, by
204
+ // theirs alone (`own`, no first group). Each made once.
92
205
  const READERS = new Map()
93
206
  function readerOf(alternatives) {
94
207
  let reader = READERS.get(alternatives)
95
208
  if (!reader) {
96
209
  const theirs = alternatives === '' ? '' : `|${alternatives}`
97
- const scan = new RegExp(`${JS_STRING_OR_COMMENT.source}${theirs}|${AFTER_PARENTHESIS}`, 'gmu')
98
- reader = { scan, slash: new RegExp(`${scan.source}|`, 'u').exec('').length - 1, regex: new RegExp(`${literalsSource('')}${theirs}`, 'muy') }
210
+ const scan = new RegExp(`${JS_STRING_OR_COMMENT.source}${theirs}|${AFTER_CLOSE}|([{}])`, 'gmu')
211
+ const groups = new RegExp(`${scan.source}|`, 'u').exec('').length
212
+ reader = { scan, slash: groups - 2, brace: groups - 1, regex: new RegExp(`${literalsSource('')}${theirs}`, 'muy'),
213
+ own: alternatives === '' ? null : new RegExp(`(?!)()${theirs}`, 'gmu') }
99
214
  READERS.set(alternatives, reader)
100
215
  }
101
216
  return reader
102
217
  }
103
218
  // Each of JavaScript's strings, regular expressions and comments in a text, as
104
- // JS_STRING_OR_COMMENT matches them (the first group a string's, a template's
105
- // or a regular expression's), and each match of a reader's `alternatives` (a
106
- // pattern's source, read with JS_STRING_OR_COMMENT's flags) in its code, in
107
- // order from `from` on, as matchAll finds them; but a regular expression
108
- // after the `)` closing a control-flow statement's condition read as one, by
109
- // the parentheses in the code before it (AFTER_PARENTHESIS), a reader's own
110
- // matches' among them, a string's, a regular expression's or a comment's not.
219
+ // JS_STRING_OR_COMMENT matches them (the first group a string's, a
220
+ // template's, its substitutions' code left out (templateFound), or a
221
+ // regular expression's), and each match of a reader's `alternatives` (a
222
+ // pattern's source, read with JS_STRING_OR_COMMENT's flags) in its code, a
223
+ // substitution's too, in order, as matchAll finds them, a template before
224
+ // what its substitutions hold; but a regular expression after the `)`
225
+ // closing a control-flow statement's condition or the `}` closing a block
226
+ // read as one, by the parentheses and braces in the code before it
227
+ // (AFTER_CLOSE, a regular expression at a line's start too after a `}`), a
228
+ // reader's own matches' among them, a string's, a regular expression's or a
229
+ // comment's not; and past a `}` that may close either (braceKind's EITHER),
230
+ // the rest as readAny reads it, out of order.
111
231
  // Linear on any text as JS_STRING_OR_COMMENT is: what is matched is never
112
- // matched again, nor the code between read twice.
113
- export function* jsMatchAll(text, alternatives = '', from = 0) {
114
- const { scan, slash, regex } = readerOf(alternatives)
232
+ // matched again, nor the code between read twice, but by readAny, once.
233
+ export function* jsMatchAll(text, alternatives = '') {
234
+ const { scan, slash, brace, regex, own } = readerOf(alternatives)
115
235
  // Whether each parenthesis open opens a condition and whether the last one
116
- // closed did; and how far the code is read.
117
- const open = []
118
- let closed = false, read = from
236
+ // closed did; what each brace open opens (braceKind), a substitution's where
237
+ // its code starts; what the last `}` closed and where, while only blanks
238
+ // and comments follow it; and how far the code is read.
239
+ const braces = [], open = []
240
+ let after = null, closed = false, read = 0
241
+ // Each template open, and what is read while one is, held for it to come
242
+ // first.
243
+ const templates = { held: [], open: [] }
119
244
  // The last comment read: whether a property's dot is before it, blanks and
120
245
  // comments between, and where what follows it starts, blanks aside.
121
246
  let comment = { dot: false, next: -1 }
122
- for (let at = from; ;) {
247
+ for (let at = 0; ;) {
123
248
  scan.lastIndex = at
124
249
  const match = scan.exec(text)
125
- if (match === null) return
126
- // The parentheses in the code before it, a reader's own match's among it,
127
- // sought in that code alone, so a reader started anywhere reads no further.
250
+ if (match === null) {
251
+ yield* ended(text, templates)
252
+ return
253
+ }
254
+ // The parentheses in the code before it, a reader's own match's among it.
128
255
  const code = text.slice(read, match.index)
129
256
  for (let closes = code.indexOf(')'), opens = code.indexOf('('); opens !== -1 || closes !== -1;) {
130
257
  if (closes === -1 || (opens !== -1 && opens < closes)) {
@@ -140,29 +267,64 @@ export function* jsMatchAll(text, alternatives = '', from = 0) {
140
267
  closes = code.indexOf(')', closes + 1)
141
268
  }
142
269
  }
270
+ if (after !== null && /\S/u.test(code.slice(read < after.end ? 1 : 0))) after = null
271
+ const opened = match[brace] === '{' ? braceKind(text, match.index, read, closed, braces.at(-1)) : null
143
272
  read = match.index
144
- let found = match
145
- if (match[slash] !== undefined) {
273
+ let found = match, template = null
274
+ if (opened !== null) {
275
+ braces.push(opened)
276
+ at = match.index + 1
277
+ continue
278
+ }
279
+ if (match[brace] !== undefined) {
280
+ // What it closes; a substitution's end, its template's text next.
281
+ const kind = braces.pop() ?? EITHER
282
+ at = match.index + 1
283
+ if (typeof kind === 'string') {
284
+ after = { kind, end: at }
285
+ continue
286
+ }
287
+ TEMPLATE_REST.lastIndex = match.index
288
+ found = TEMPLATE_REST.exec(text)
289
+ template = kind.template
290
+ } else if (match[slash] !== undefined || (after !== null && match[1]?.[0] === '/' && startsLine(text, match.index))) {
291
+ // A value's `}` divides on its line alone: past it, it may end a
292
+ // statement, as a type's does in TypeScript (`type T = {}`).
293
+ const kind = match[slash] === undefined && after.kind !== BLOCK ? EITHER : after?.kind ?? (closed ? BLOCK : VALUE)
294
+ if (kind === EITHER) {
295
+ yield* ended(text, templates)
296
+ yield* readAny(text, own, match.index + 1)
297
+ return
298
+ }
146
299
  regex.lastIndex = match.index
147
- found = closed ? regex.exec(text) : null
300
+ found = kind === VALUE ? null : match[slash] === undefined ? match : regex.exec(text)
148
301
  }
149
302
  // A division, its `/` code.
150
303
  if (found === null) {
151
304
  at = match.index + 1
152
305
  continue
153
306
  }
154
- // A string's, a regular expression's or a comment's text no code.
307
+ // A string's, a regular expression's or a comment's text no code; a
308
+ // template's to a substitution's `${`, its code next, the template
309
+ // whole where it ends, before what its substitutions hold.
155
310
  const end = found.index + found[0].length
156
- if (found[1] !== undefined) read = end
157
- else if (COMMENT.test(found[0])) {
311
+ if (found[1] !== undefined) {
312
+ read = at = end
313
+ after = null
314
+ if (template !== null || (found[1][0] === '\u0060' && found[1].endsWith('${'))) {
315
+ yield* piece(text, found, template, templates, braces)
316
+ continue
317
+ }
318
+ } else if (COMMENT.test(found[0])) {
158
319
  // As the comment before it says where only blanks are between them.
159
320
  DOT_BEFORE.lastIndex = found.index
160
321
  const dot = comment.next === found.index + found[0].search(/\S/u) ? comment.dot : DOT_BEFORE.test(text)
161
322
  CODE.lastIndex = end
162
323
  comment = { dot, next: CODE.exec(text)?.index ?? text.length }
163
324
  read = end
164
- }
165
- yield found
325
+ } else after = null
326
+ if (templates.open.length > 0) templates.held.push(found)
327
+ else yield found
166
328
  at = Math.max(end, found.index + 1)
167
329
  }
168
330
  }
package/risk/index.d.ts CHANGED
@@ -195,10 +195,12 @@ export const NPM_SYMLINKS_ABOVE: number
195
195
  // component, whatever that is, and a file under no directory at its name, as
196
196
  // pnpm installs it; a hard link is the file it names again, a symlink its
197
197
  // target as stored (`link`), a file with an execute bit `executable`. `refuse` is called, and throws, with
198
- // `tarball-conflict` where the files conflict (two at one path that differ, a
198
+ // `tarball-conflict` where the files conflict (two at one path that differ,
199
+ // or at two paths one on macOS or Windows unless `foldPaths` is false, a
199
200
  // file within another), and with `package-too-large` past `maxFiles` files or
200
201
  // `maxBytes` bytes.
201
- export function npmTarLayout(entries: Iterable<Pick<Entry, 'name' | 'storedName' | 'type' | 'data' | 'linkname' | 'mode'>>, bounds: { maxFiles: number; maxBytes: number },
202
+ export function npmTarLayout(entries: Iterable<Pick<Entry, 'name' | 'storedName' | 'type' | 'data' | 'linkname' | 'mode'>>,
203
+ reading: { maxFiles: number; maxBytes: number; foldPaths?: boolean },
202
204
  refuse: (code: 'tarball-conflict' | 'package-too-large') => never): Map<string, { bytes: Uint8Array; link?: string; executable?: true }>
203
205
 
204
206
  // GitHub Actions (actions/), a workflow GitHub can't run thrown as
@@ -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 = 21
22
+ const RISK_VERSION = 22
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
@@ -38,6 +38,32 @@ const sameBytes = (a, b) => a.length === b.length && a.every((byte, at) => byte
38
38
  const sameFile = (a, b) => a.link === b.link && a.executable === b.executable && sameBytes(a.bytes, b.bytes)
39
39
  const encoder = new TextEncoder()
40
40
 
41
+ // Two paths macOS or Windows may take as one, as they compare names in
42
+ // either case and macOS normalized too, are one under some fold: NFC, lower,
43
+ // upper, or lower then upper case, as JavaScript has no full case folding
44
+ // (`ß` upper is `SS`, and `ẞ` lower is `ß`), then NFC again.
45
+ const FOLDS = [path => path.normalize().toLowerCase().normalize(), path => path.normalize().toUpperCase().normalize(),
46
+ path => path.normalize().toLowerCase().toUpperCase().normalize()]
47
+
48
+ // Lays `file` at `path` in `tree`, each name a file or a directory's Map, so
49
+ // each path is walked once to find a file and a directory at one place, and
50
+ // gives the file already there, if any. `tarball-conflict` where it lies past
51
+ // a file, or a directory or a file that differs (sameFile) is there.
52
+ function laidAt(tree, path, file, refuse) {
53
+ const segments = path.split('/')
54
+ let at = tree
55
+ for (let i = 0; i < segments.length - 1; i++) {
56
+ let next = at.get(segments[i])
57
+ if (next === undefined) at.set(segments[i], next = new Map())
58
+ else if (!(next instanceof Map)) refuse('tarball-conflict')
59
+ at = next
60
+ }
61
+ const seen = at.get(segments.at(-1))
62
+ if (seen === undefined) at.set(segments.at(-1), file)
63
+ else if (seen instanceof Map || seen !== file && !sameFile(seen, file)) refuse('tarball-conflict')
64
+ return seen
65
+ }
66
+
41
67
  // Every file a tar archive holds, by package path (npmTarPath): `{ bytes }`,
42
68
  // whether or not an installer installs it, `executable` where its mode has an
43
69
  // execute bit; a symlink `{ bytes, link }`, its target as stored and that
@@ -48,15 +74,17 @@ const encoder = new TextEncoder()
48
74
  // files at one path, unless their bytes are the same (npm and pnpm install the
49
75
  // last, so a file under another top directory, or at the top, replaces one
50
76
  // under `package/` there); and a file where another lies within it, as in a
51
- // directory (npm keeps the file, pnpm the directory). Directories and devices
52
- // hold no bytes of their own.
77
+ // directory (npm keeps the file, pnpm the directory). Unless `foldPaths` is
78
+ // false, as for a repository's directory, so too where paths are one on macOS
79
+ // or Windows (FOLDS), as `a.js` and `A.js` are; the same file at both is read
80
+ // at both. Directories and devices hold no bytes of their own.
53
81
  // Past `maxFiles` files or `maxBytes` bytes, `package-too-large`.
54
82
  // `refuse(code)` throws.
55
- export function npmTarLayout(entries, { maxFiles, maxBytes }, refuse) {
83
+ export function npmTarLayout(entries, { maxFiles, maxBytes, foldPaths = true }, refuse) {
56
84
  const files = new Map()
57
- // The paths laid out as a tree, each name a file or a directory's
58
- // Map, so each path is walked once to find a file and a directory at one place.
85
+ // The paths laid out as a tree (laidAt), and again as folded (FOLDS).
59
86
  const root = new Map()
87
+ const folded = new Map()
60
88
  // Each file by its name in the archive, which a hard link names.
61
89
  const named = new Map()
62
90
  let total = 0
@@ -66,20 +94,8 @@ export function npmTarLayout(entries, { maxFiles, maxBytes }, refuse) {
66
94
  if (file === undefined) continue
67
95
  named.set(name, file)
68
96
  const path = npmTarPath(storedName) || name
69
- const segments = path.split('/')
70
- let at = root
71
- for (let i = 0; i < segments.length - 1; i++) {
72
- let next = at.get(segments[i])
73
- if (next === undefined) at.set(segments[i], next = new Map())
74
- else if (!(next instanceof Map)) refuse('tarball-conflict')
75
- at = next
76
- }
77
- const seen = at.get(segments.at(-1))
78
- if (seen !== undefined) {
79
- if (seen instanceof Map || !sameFile(seen, file)) refuse('tarball-conflict')
80
- continue
81
- }
82
- at.set(segments.at(-1), file)
97
+ if (laidAt(root, path, file, refuse) !== undefined) continue
98
+ if (foldPaths) for (const fold of FOLDS) laidAt(folded, fold(path), file, refuse)
83
99
  files.set(path, file)
84
100
  total += file.bytes.length
85
101
  if (files.size > maxFiles || total > maxBytes) refuse('package-too-large')
@@ -67,11 +67,14 @@
67
67
  // name are (github-users.ts), by login
68
68
  // POST /api/admin/repositories/remove → admin permanently removes a repo
69
69
  // GET /api/admin/repositories/risk[?team=|?repo=] → admin: each connected repo's npm lockfiles, or a team's or one repo's,
70
- // their packages and what risk tells of each, Brotli-encoded ndjson as each is found; the reader leaving stops it | 400/401/403/404
71
- // GET /api/admin/repositories/risk/stasis?repoId=&commit=&path=… → admin: what Stasis reaches of a repo's stasis.config.json
72
- // files at a commit, each built as its dependency review builds it, a build still to be made asked for again | 400/401/403/404
73
- // GET /api/admin/repositories/risk/lockfile?repoId=&commit=&path= → admin: an npm lockfile of a repo at a commit, as a scan
74
- // read it, and the package.json beside a yarn.lock, for what depends on a package it locks | 400/401/403/404/429/502
70
+ // their packages and what risk tells of each, Brotli-encoded ndjson as each is found; the reader leaving stops it; a manager:
71
+ // a team's they are a member of alone (readRiskSession) | 400/401/403/404
72
+ // GET /api/admin/repositories/risk/stasis?repoId=&commit=&path=…[&team=] → admin, or a manager of `team`: what Stasis reaches
73
+ // of a repo's stasis.config.json files at a commit, each built as its dependency review builds it, a build still to be made
74
+ // asked for again; with `team`, of its repos and directories alone | 400/401/403/404
75
+ // GET /api/admin/repositories/risk/lockfile?repoId=&commit=&path=[&team=] → admin, or a manager of `team`: an npm lockfile of
76
+ // a repo at a commit, as a scan read it, and the package.json beside a yarn.lock, for what depends on a package it locks;
77
+ // with `team`, of its repos and directories alone | 400/401/403/404/429/502
75
78
  // GET /api/admin/reports → admin|manage list of uploaded reports | 401/403
76
79
  // POST /api/admin/reports → admin|manage uploads a report (raw body) | 401/403/413
77
80
  // GET /api/admin/reports/<id> → admin|manage downloads a stored report | 401/403/404
@@ -203,7 +206,7 @@ import type { ConnectedRepo } from './github-app.ts'
203
206
  import { canAddAnyPublicRepository, canAddRepositories, passesPublicRepositorySafeguard } from './repository-policy.ts'
204
207
  import { RepositoryDiscovery } from './repository-discovery.ts'
205
208
  import { RISK_KEPT_MS, SCAN_READ_KEPT_MS, type ScanProgress, repositoryRiskLines } from './repository-risk.ts'
206
- import { stasisConfigRow } from './repository-risk-read.ts'
209
+ import { lockfileOf, stasisConfigRow } from './repository-risk-read.ts'
207
210
  import { WORKFLOWS_DIR } from './repository-actions.ts'
208
211
  import { githubActionsSource } from './github-actions.ts'
209
212
  import { type RepositoryEntry, createRepositoryBrowser, repositoryTreeFiles, scopedDirectory } from './repository-browser.ts'
@@ -3523,9 +3526,10 @@ async function sendEncoded(req: IncomingMessage, res: ServerResponse, blob: Open
3523
3526
  }
3524
3527
 
3525
3528
 
3526
- // How often a scan of repositories' risk checks again that its reader is
3527
- // still an admin, between the lines it sends; and how long its connection may
3528
- // go idle, unread or with no line to send, before the scan is stopped.
3529
+ // How often a scan of repositories' risk checks again that its reader may
3530
+ // still read it (mayReadRisk), between the lines it sends; and how long its
3531
+ // connection may go idle, unread or with no line to send, before the scan
3532
+ // is stopped.
3529
3533
  const REPO_RISK_RECHECK_MS = 10_000
3530
3534
  const REPO_RISK_IDLE_MS = 5 * 60_000
3531
3535
  // A scan's part on a serverless deployment, within its function's 300s
@@ -3560,6 +3564,36 @@ async function riskRepositories(db: ManagedDb, query: URLSearchParams): Promise<
3560
3564
  })
3561
3565
  }
3562
3566
 
3567
+ // Who reads repositories' risk, of the scope `query` names: an admin, any;
3568
+ // or a manager, a team's alone (`team`), one they are a member of and not
3569
+ // hidden, as its Risk tab scans it (ui/view/workspace-content.js). Null,
3570
+ // answered, for anyone else.
3571
+ async function readRiskSession(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams, { handed = false } = {}) {
3572
+ const s = await readManageSession(res, deps, cookie, { handed })
3573
+ if (!s) return null
3574
+ if (await mayReadRisk(deps.db, s.user, query)) return s
3575
+ sendJson(res, 403, { error: 'forbidden' })
3576
+ return null
3577
+ }
3578
+
3579
+ // Whether `user` may read risk of the scope `query` names (readRiskSession).
3580
+ async function mayReadRisk(db: ManagedDb, user: StoredUser, query: URLSearchParams): Promise<boolean> {
3581
+ if (user.role === 'admin') return true
3582
+ const teamId = query.get('team')
3583
+ if (user.role !== 'manage' || teamId === null || query.has('repo')) return false
3584
+ const team = (await db.listTeams()).find(item => item.id === teamId)
3585
+ return team !== undefined && !team.hidden && team.members.some(member => member.userId === user.id)
3586
+ }
3587
+
3588
+ // Repository `repoId` as a scan of `query`'s scope reads it: connected, and
3589
+ // where `query` names a team, the team's, with its directories in it; null
3590
+ // where it isn't.
3591
+ async function riskRepository(db: ManagedDb, query: URLSearchParams, repoId: number): Promise<(SelectedRepo & { paths?: string[] }) | null> {
3592
+ const teamId = query.get('team')
3593
+ const repos: (SelectedRepo & { paths?: string[] })[] | null = teamId === null ? await db.listSelectedRepos() : await riskRepositories(db, new URLSearchParams({ team: teamId }))
3594
+ return repos?.find(item => item.repoId === repoId) ?? null
3595
+ }
3596
+
3563
3597
  // What Stasis reaches of the stasis.config.json at `config` of `repo` at
3564
3598
  // `commit`, as its dependency review's reader has it (stasisReader): the
3565
3599
  // same builds, in the same worker, kept the same way. One not kept yet is
@@ -3583,18 +3617,20 @@ async function riskStasis(deps: ManagedHttpDeps, repo: { repoId: number; fullNam
3583
3617
  // them (repository-risk-read.ts StasisConfigRow), for its page to ask again
3584
3618
  // while builds of them are still to be made, every 30 seconds as a dependency
3585
3619
  // review's page asks: each asked for again (riskStasis), lest it lapse
3586
- // (stasis-dependencies.ts). For admins, with their own GitHub access, as the
3587
- // scan reads the repository; a path naming no stasis.config.json in the
3588
- // commit's tree told so (`no-config`).
3620
+ // (stasis-dependencies.ts). For admins, or managers of the team it names
3621
+ // (`team`, of whose repositories and directories alone: riskRepository),
3622
+ // with their own GitHub access, as the scan reads the repository; a path
3623
+ // naming no stasis.config.json in the commit's tree told so (`no-config`).
3589
3624
  const MAX_RISK_STASIS = 50
3590
3625
  async function handleRepositoryRiskStasis(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
3591
- const s = await readAdminSession(res, deps, cookie)
3626
+ const s = await readRiskSession(res, deps, cookie, query)
3592
3627
  if (!s) return
3593
3628
  const commit = query.get('commit') ?? '', paths = query.getAll('path'), repoId = askedRepoId(query)
3594
3629
  if (repoId === null || !/^[\da-f]{40}$/u.test(commit) || paths.length === 0 || paths.length > MAX_RISK_STASIS || new Set(paths).size < paths.length
3595
3630
  || !paths.every(isStasisConfig)) { sendJson(res, 400, { error: 'bad-request' }); return }
3596
- const repo = (await deps.db.listSelectedRepos()).find(item => item.repoId === repoId)
3631
+ const repo = await riskRepository(deps.db, query, repoId)
3597
3632
  if (!repo) { sendJson(res, 404, { error: 'no-repository' }); return }
3633
+ if (!paths.every(path => lockfileOf(path, repo.paths))) { sendJson(res, 403, { error: 'forbidden' }); return }
3598
3634
  try {
3599
3635
  const reader = await repositoryReader(deps, s.user.id, repo)
3600
3636
  const token = reader.readToken()
@@ -3612,16 +3648,19 @@ async function handleRepositoryRiskStasis(res: ServerResponse, deps: ManagedHttp
3612
3648
  // GET /api/admin/repositories/risk/lockfile?repoId=&commit=&path=: a lockfile
3613
3649
  // a risk scan reads (locked-packages.ts) at `commit`, for its page to show
3614
3650
  // what depends on a package in it: its text, and the package.json beside a
3615
- // yarn.lock, which its reader there takes (null for none). For admins, with
3616
- // their own GitHub access, as the scan reads the repository.
3651
+ // yarn.lock, which its reader there takes (null for none). For admins, or
3652
+ // managers of the team it names (`team`, of whose repositories and
3653
+ // directories alone: riskRepository), with their own GitHub access, as the
3654
+ // scan reads the repository.
3617
3655
  const RISK_LOCKFILE = /^(?:(?!\.\.?\/)[^/]+\/)*(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock)$/u
3618
3656
  async function handleRepositoryRiskLockfile(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
3619
- const s = await readAdminSession(res, deps, cookie)
3657
+ const s = await readRiskSession(res, deps, cookie, query)
3620
3658
  if (!s) return
3621
3659
  const commit = query.get('commit') ?? '', path = query.get('path') ?? '', repoId = askedRepoId(query)
3622
3660
  if (repoId === null || !/^[\da-f]{40}$/u.test(commit) || !RISK_LOCKFILE.test(path)) { sendJson(res, 400, { error: 'bad-request' }); return }
3623
- const repo = (await deps.db.listSelectedRepos()).find(item => item.repoId === repoId)
3661
+ const repo = await riskRepository(deps.db, query, repoId)
3624
3662
  if (!repo) { sendJson(res, 404, { error: 'no-repository' }); return }
3663
+ if (!lockfileOf(path, repo.paths)) { sendJson(res, 403, { error: 'forbidden' }); return }
3625
3664
  try {
3626
3665
  const client = createClient({ token: (await repositoryReader(deps, s.user.id, repo)).readToken() })
3627
3666
  const file = (at: string) => upstreamGithub(() => client.getRepoFile({ repo: repo.fullName, path: at, ref: commit }))
@@ -3658,11 +3697,12 @@ function scanProgress(deps: ManagedHttpDeps, key: string, scan: string | null) {
3658
3697
  // GitHub (dependabot-access.ts); and its GitHub Actions, the references they
3659
3698
  // make resolved with the admin's own GitHub token (github-actions.ts); and
3660
3699
  // what Stasis reaches of each of its stasis.config.json files, as its
3661
- // dependency review has them built (riskStasis). The
3662
- // reader leaving, losing their admin role or
3663
- // the server shutting down stops it.
3700
+ // dependency review has them built (riskStasis). Read by an admin, or by a
3701
+ // manager of the team it names (readRiskSession), each alike, with their
3702
+ // own access. The reader leaving, losing what let them read it or the
3703
+ // server shutting down stops it.
3664
3704
  async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
3665
- const s = await readAdminSession(res, deps, cookie, { handed: true })
3705
+ const s = await readRiskSession(res, deps, cookie, query, { handed: true })
3666
3706
  if (!s) return
3667
3707
  const repos = await riskRepositories(deps.db, query)
3668
3708
  if (!repos) {
@@ -3766,7 +3806,8 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
3766
3806
  await sendLines(res, lines, async () => {
3767
3807
  if (deps.isShuttingDown()) return false
3768
3808
  if (Date.now() - checked < REPO_RISK_RECHECK_MS) return true
3769
- if ((await readSession(deps.config, deps.db, cookie, Date.now()))?.user.role !== 'admin') return false
3809
+ const current = await readSession(deps.config, deps.db, cookie, Date.now())
3810
+ if (current?.user.id !== s.user.id || !await mayReadRisk(deps.db, current.user, query)) return false
3770
3811
  checked = Date.now()
3771
3812
  return true
3772
3813
  })