@preventive/triage 1.0.0-alpha.71 → 1.0.0-alpha.73

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 (145) hide show
  1. package/common/bundle-sources.d.ts +2 -0
  2. package/common/bundle-sources.js +19 -2
  3. package/common/finding-duplicates.js +5 -0
  4. package/common/finding-filters.js +45 -4
  5. package/common/line-diff.d.ts +2 -2
  6. package/common/line-diff.js +20 -8
  7. package/common/managed/finding-detail.js +1 -1
  8. package/common/managed/review-view-routes.js +23 -0
  9. package/common/managed/risk-routes.js +30 -0
  10. package/common/managed/routes.js +11 -6
  11. package/common/managed/team-app.d.ts +8 -6
  12. package/common/managed/team-app.js +15 -3
  13. package/common/stasis-files.d.ts +5 -0
  14. package/common/stasis-files.js +20 -0
  15. package/common/stasis-tgz.d.ts +6 -0
  16. package/common/stasis-tgz.js +27 -0
  17. package/common/workspace-app.js +20 -0
  18. package/out/activity.js +2 -4
  19. package/out/{chunk-2F3CYNPZ.js → chunk-2IHCVA3Y.js} +1 -1
  20. package/out/{chunk-HAZKDK4M.js → chunk-2V6Q4ZOZ.js} +1 -1
  21. package/out/{chunk-RRBIJL2B.js → chunk-4IW3VD3H.js} +1 -1
  22. package/out/chunk-4YZOXAXR.js +2 -0
  23. package/out/chunk-5NUDNLJA.js +6 -0
  24. package/out/chunk-5YP7P5KA.js +1 -0
  25. package/out/chunk-6VOB5WXX.js +2 -0
  26. package/out/chunk-74JZTGTO.js +11 -0
  27. package/out/chunk-7YFJUT2P.js +1 -0
  28. package/out/chunk-A4BBBHQU.js +1 -0
  29. package/out/{chunk-4ISO5F7Y.js → chunk-ADMVRLNP.js} +1 -1
  30. package/out/chunk-BIWPZT4E.js +52 -0
  31. package/out/{chunk-HETCVNO4.js → chunk-BLPHP4U3.js} +1 -1
  32. package/out/{chunk-Y5ZHFNBD.js → chunk-BXQCCW7F.js} +1 -1
  33. package/out/{chunk-JFL7WLRV.js → chunk-CU3FPB3P.js} +1 -1
  34. package/out/chunk-CXVBTUK3.js +4 -0
  35. package/out/{chunk-M37X4LCF.js → chunk-EXQQ5VQJ.js} +1 -1
  36. package/out/{chunk-NXATZJQ2.js → chunk-GSNSP3EF.js} +1 -1
  37. package/out/chunk-GV5U7OLP.js +40 -0
  38. package/out/{chunk-JOXLZXMI.js → chunk-GX5UXWT4.js} +1 -1
  39. package/out/{chunk-YF4M5OCI.js → chunk-I6UQQKAH.js} +1 -1
  40. package/out/{chunk-UCP3JRE2.js → chunk-LVW7WWV4.js} +1 -1
  41. package/out/chunk-NEFCZAIY.js +11 -0
  42. package/out/{chunk-TOXMUOIW.js → chunk-OQS2USZM.js} +1 -1
  43. package/out/chunk-PQPKHAI5.js +15 -0
  44. package/out/chunk-PX5DLFSD.js +1 -0
  45. package/out/chunk-QBFT2DDR.js +1 -0
  46. package/out/{chunk-GZ46SSTF.js → chunk-RGNF4OH6.js} +1 -1
  47. package/out/chunk-RLLA4GHZ.js +1 -0
  48. package/out/chunk-ROHACH7V.js +3 -0
  49. package/out/chunk-ROWUGPID.js +1 -0
  50. package/out/{chunk-QMVOEBWC.js → chunk-S2ZIKK45.js} +1 -1
  51. package/out/chunk-SSPDMA6D.js +1 -0
  52. package/out/chunk-TD7RVUTT.js +2 -0
  53. package/out/{chunk-4XIH7YTX.js → chunk-UH6NZBSU.js} +1 -1
  54. package/out/{chunk-M3Y6SLC4.js → chunk-UJP4PQJA.js} +1 -1
  55. package/out/{chunk-PAD2JHZT.js → chunk-UJSJMXEG.js} +1 -1
  56. package/out/{chunk-E3LFSUDJ.js → chunk-VYYUMYVW.js} +1 -1
  57. package/out/{chunk-VRX2APNA.js → chunk-XVKDPU4D.js} +1 -1
  58. package/out/chunk-Y2XGV3RC.js +8 -0
  59. package/out/chunk-YCEMQETS.js +255 -0
  60. package/out/client-managed-import.js +3 -3
  61. package/out/client-managed.js +30 -27
  62. package/out/compare.js +16 -25
  63. package/out/dialogs.js +38 -38
  64. package/out/graph.js +14 -14
  65. package/out/index.html +32 -52
  66. package/out/scan.js +2 -2
  67. package/out/terminal.js +239 -240
  68. package/out/view.css +1 -1
  69. package/out/view.js +15 -15
  70. package/package.json +21 -13
  71. package/risk/actions/resolve.js +56 -19
  72. package/risk/actions/uses.js +27 -9
  73. package/risk/actions/workflow.js +75 -2
  74. package/risk/files/characters.js +11 -0
  75. package/risk/files/hosts.js +4 -4
  76. package/risk/files/readability.js +5 -2
  77. package/risk/files/runs-code.js +12 -25
  78. package/risk/files/script.js +141 -19
  79. package/risk/files/source-map-link.js +43 -0
  80. package/risk/index.d.ts +24 -7
  81. package/risk/index.js +1 -0
  82. package/risk/npm/assess.js +1 -1
  83. package/risk/npm/compare.js +9 -30
  84. package/risk/npm/diff.js +1 -1
  85. package/risk/npm/held.js +6 -2
  86. package/risk/npm/registry.js +5 -2
  87. package/risk/npm/tarball.js +79 -22
  88. package/server-managed/bundle-advisories.ts +12 -36
  89. package/server-managed/bundle-build-worker.js +29 -11
  90. package/server-managed/bundle-build.ts +4 -3
  91. package/server-managed/bundle-cache.ts +53 -13
  92. package/server-managed/bundle.ts +45 -13
  93. package/server-managed/comparison.ts +3 -3
  94. package/server-managed/db-methods.ts +54 -17
  95. package/server-managed/db-neon.ts +9 -2
  96. package/server-managed/db-schema.ts +12 -2
  97. package/server-managed/db.ts +4 -1
  98. package/server-managed/dependency-reviews.ts +8 -5
  99. package/server-managed/github-errors.ts +22 -0
  100. package/server-managed/github-requests.ts +4 -2
  101. package/server-managed/http.ts +336 -76
  102. package/server-managed/management.ts +10 -4
  103. package/server-managed/npm-delta.ts +17 -2
  104. package/server-managed/npm-kept.ts +6 -0
  105. package/server-managed/npm-packages.ts +30 -29
  106. package/server-managed/npm-patch.ts +9 -9
  107. package/server-managed/package-entry-points.ts +54 -6
  108. package/server-managed/pull-dependencies.ts +4 -1
  109. package/server-managed/rename-diff-worker.js +11 -7
  110. package/server-managed/rename-diff.ts +5 -4
  111. package/server-managed/report-opening.ts +77 -0
  112. package/server-managed/report-sources.ts +2 -1
  113. package/server-managed/repository-aliases.ts +34 -0
  114. package/server-managed/repository-browser.ts +87 -32
  115. package/server-managed/repository-code.ts +6 -3
  116. package/server-managed/repository-dependency-reviews.ts +21 -0
  117. package/server-managed/repository-issues.ts +15 -9
  118. package/server-managed/repository-risk-read.ts +50 -4
  119. package/server-managed/repository-risk.ts +9 -2
  120. package/server-managed/stasis-config.ts +97 -5
  121. package/server-managed/stasis-dependencies.ts +7 -4
  122. package/server-managed/team-reports.ts +5 -3
  123. package/server-managed/type-only-proof.js +26 -4
  124. package/server-managed/upstream-cache.ts +18 -12
  125. package/server-managed/workspace-shares.ts +4 -4
  126. package/out/chunk-2HGKTQ5Q.js +0 -52
  127. package/out/chunk-45HTR22K.js +0 -4
  128. package/out/chunk-4RS3NDOG.js +0 -1
  129. package/out/chunk-7GJNLCXF.js +0 -15
  130. package/out/chunk-CGRIZ5M5.js +0 -1
  131. package/out/chunk-CQIT5UNK.js +0 -1
  132. package/out/chunk-D6NVKGGG.js +0 -10
  133. package/out/chunk-DTAR2BB6.js +0 -247
  134. package/out/chunk-MPXVKVPF.js +0 -3
  135. package/out/chunk-NB4JBTKK.js +0 -2
  136. package/out/chunk-QPGM3DTI.js +0 -42
  137. package/out/chunk-VFWMQ3LG.js +0 -2
  138. package/out/chunk-VG5RH6KN.js +0 -2
  139. package/out/chunk-WFDXHPT2.js +0 -12
  140. package/out/chunk-WMFDQS2L.js +0 -11
  141. package/out/chunk-WREU7JAG.js +0 -1
  142. /package/out/{chunk-JMG5DXII.js → chunk-7HP2VYIC.js} +0 -0
  143. /package/out/{chunk-HOB3YPS5.js → chunk-K4XJHM2T.js} +0 -0
  144. /package/out/{chunk-4EMM6UCD.js → chunk-QI66YA4F.js} +0 -0
  145. /package/out/{chunk-G3LY2FV4.js → chunk-WCDYSIKG.js} +0 -0
@@ -15,18 +15,33 @@ 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.
21
+ // A hashbang, the file's first line (`#!/usr/bin/env node`), a comment, after
22
+ // a byte order mark too, which node's ES module loader drops first. A
23
+ // string's or template's escape may be a line continuation (`\` before a line
24
+ // break, CRLF's whole).
25
+ // Linear on any text: a regular expression's context looked back on only
26
+ // before a `/`, a comment's leading blanks taken only from where they start,
27
+ // and what is left open read to where it would end, a string or a regular
28
+ // expression its line's end, a template or a comment the text's, rather than
29
+ // 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]*`
31
+ // A regular expression first where a value starts (after `=>`, `...`, an
32
+ // 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]*)`
38
+ // JavaScript's strings and regular expressions (the first group) and its
39
+ // 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.
42
+ export const JS_STRING_OR_COMMENT = new RegExp(literalsSource(VALUE_STARTS), 'gmu')
18
43
  const JS = {
19
- // A hashbang, the file's first line (`#!/usr/bin/env node`), a comment,
20
- // after a byte order mark too, which node's ES module loader drops first.
21
- // A string's or template's escape may be a line continuation (`\` before a
22
- // line break, CRLF's whole).
23
- // Linear on any text: a regular expression's context looked back on only
24
- // before a `/`, a comment's leading blanks taken only from where they
25
- // start, and what is left open read to where it would end, a string or a
26
- // regular expression its line's end, a template or a comment the text's,
27
- // rather than tried again from each later quote or slash.
28
- // A regular expression first where a value starts (after `=>`, `...`, an operator or a keyword, not a property: `x.default/2`, `this.#in/2`), so a quote in it (`/["']/`) starts no string.
29
- stringOrComment: /((?=\/)(?<=(?:^|\.\.\.|[(,=:[!&|?{};>+\-*/%^<~]|(?<![\p{ID_Continue}$.#])(?:await|case|default|delete|do|else|extends|in|instanceof|new|of|return|throw|typeof|void|yield))[ \t]*)\/(?![/*])(?:[^/\\[\n]|\\.|\[(?:[^\]\\\n]|\\.)*(?:\]|(?=\\?$)))+(?:\/[a-z]*|(?=\\?$))|"(?:[^"\\\n]|\\(?:\r\n|[\s\S]))*(?:"|$)|'(?:[^'\\\n]|\\(?:\r\n|[\s\S]))*(?:'|$)|`(?:[^`\\]|\\(?:\r\n|[\s\S]))*(?:`|(?![\s\S])))|(?<![ \t])[ \t]*(?:\/\*[\s\S]*?(?:\*\/|(?![\s\S]))|\/\/.*|(?<![\s\S])\uFEFF?#!.*)[ \t]*/gmu,
44
+ matchAll: text => jsMatchAll(text),
30
45
  // Beside punctuation (`a, b`, `x = 1`), not between two words, as
31
46
  // JavaScript tells a word's characters (`return a`, `var π`, `var \u03c0`),
32
47
  droppable: /(?<![\p{ID_Continue}$\\\u200C\u200D])[ \t]+|[ \t]+(?![\p{ID_Continue}$\\\u200C\u200D])/gu,
@@ -35,9 +50,12 @@ const JS = {
35
50
  needed: (code, index, run) => ('+-/'.includes(code[index - 1]) && code[index + run.length] === code[index - 1])
36
51
  || (code[index - 2] === REGEX && /[\p{ID_Continue}$\\\u200C\u200D]/u.test(code[index + run.length])),
37
52
  }
53
+ // A stylesheet's strings (the first group) and comments: no `//` comments, so
54
+ // `url(https://…)` is code. A string's escape may be a line continuation (`\`
55
+ // before a line break, CRLF's whole).
56
+ const CSS_STRING_OR_COMMENT = /("(?:[^"\\\n]|\\(?:\r\n|[\s\S]))*"|'(?:[^'\\\n]|\\(?:\r\n|[\s\S]))*')|[ \t]*\/\*[\s\S]*?\*\/[ \t]*/gu
38
57
  const CSS = {
39
- // No `//` comments, so `url(https://…)` is code.
40
- stringOrComment: /("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*')|[ \t]*\/\*[\s\S]*?\*\/[ \t]*/gu,
58
+ matchAll: text => text.matchAll(CSS_STRING_OR_COMMENT),
41
59
  // Beside braces, `;`, `,`, `>`, parentheses, after `:` (`a { color: red }`)
42
60
  // and beside a selector's `+` or `~` (`.a + .b`), not those a selector or a
43
61
  // value needs (`.a .b`, `1px solid #fff`, `a :hover`),
@@ -47,9 +65,107 @@ const CSS = {
47
65
  needed: (code, index, run, depth) => /[+~]/u.test(code[index - 1] + code[index + run.length])
48
66
  && (depth > 0 || /^\s*--[^:]*:/u.test(code.slice(Math.max(...['{', ';', '}'].map(end => code.lastIndexOf(end, index))) + 1, index))),
49
67
  }
50
- // JavaScript's strings and regular expressions (the first group) and its
51
- // comments, for a reader that sets them aside (runs-code.js, hosts.js).
52
- export const JS_STRING_OR_COMMENT = JS.stringOrComment
68
+
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]*)(\/)(?![/*])`
75
+ // A `(` opening a condition: after `if`, `while`, `for` (`for await` too) or
76
+ // `with` (its first group, the blanks after it its second), a word of its own
77
+ // (not `elif(`), not a property's name, blanks after its dot or none (`x.if(`,
78
+ // `x. if(`), nor one after a comment there (`x./* c */if(`), as jsMatchAll
79
+ // tells by the comment before it.
80
+ const CONDITION = /(?<=(?<![\p{ID_Continue}$#])(?<!\.\s*)(if|while|with|for(?:\s+await)?)(\s*))\(/uy
81
+ // What a match that is neither a string nor a reader's own starts with: a
82
+ // comment's `//` or `/*`, or a hashbang, blanks before it.
83
+ const COMMENT = /^[ \t]*(?:\/[/*]|\uFEFF?#!)/u
84
+ // A property's dot before where it is looked back from, blanks between.
85
+ const DOT_BEFORE = /(?<=\.\s*)/uy
86
+ // The first character that is no blank.
87
+ const CODE = /\S/gu
88
+ // 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.
92
+ const READERS = new Map()
93
+ function readerOf(alternatives) {
94
+ let reader = READERS.get(alternatives)
95
+ if (!reader) {
96
+ 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') }
99
+ READERS.set(alternatives, reader)
100
+ }
101
+ return reader
102
+ }
103
+ // 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.
111
+ // 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)
115
+ // 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
119
+ // The last comment read: whether a property's dot is before it, blanks and
120
+ // comments between, and where what follows it starts, blanks aside.
121
+ let comment = { dot: false, next: -1 }
122
+ for (let at = from; ;) {
123
+ scan.lastIndex = at
124
+ 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.
128
+ const code = text.slice(read, match.index)
129
+ for (let closes = code.indexOf(')'), opens = code.indexOf('('); opens !== -1 || closes !== -1;) {
130
+ if (closes === -1 || (opens !== -1 && opens < closes)) {
131
+ const next = read + opens
132
+ CONDITION.lastIndex = next
133
+ const keyword = CONDITION.exec(text)
134
+ // Not where its keyword starts right after a comment following a
135
+ // property's dot.
136
+ open.push(keyword !== null && !(comment.dot && comment.next === next - keyword[2].length - keyword[1].length))
137
+ opens = code.indexOf('(', opens + 1)
138
+ } else {
139
+ closed = open.pop() === true
140
+ closes = code.indexOf(')', closes + 1)
141
+ }
142
+ }
143
+ read = match.index
144
+ let found = match
145
+ if (match[slash] !== undefined) {
146
+ regex.lastIndex = match.index
147
+ found = closed ? regex.exec(text) : null
148
+ }
149
+ // A division, its `/` code.
150
+ if (found === null) {
151
+ at = match.index + 1
152
+ continue
153
+ }
154
+ // A string's, a regular expression's or a comment's text no code.
155
+ const end = found.index + found[0].length
156
+ if (found[1] !== undefined) read = end
157
+ else if (COMMENT.test(found[0])) {
158
+ // As the comment before it says where only blanks are between them.
159
+ DOT_BEFORE.lastIndex = found.index
160
+ const dot = comment.next === found.index + found[0].search(/\S/u) ? comment.dot : DOT_BEFORE.test(text)
161
+ CODE.lastIndex = end
162
+ comment = { dot, next: CODE.exec(text)?.index ?? text.length }
163
+ read = end
164
+ }
165
+ yield found
166
+ at = Math.max(end, found.index + 1)
167
+ }
168
+ }
53
169
  // A stylesheet's by its name, else JavaScript's for a script by its name, or
54
170
  // for any other where node runs it as one (`script`).
55
171
  export const minifiable = (path, script = false) => /\.css$/iu.test(path) ? CSS : script || /\.[cm]?js$/iu.test(path) ? JS : null
@@ -59,13 +175,19 @@ export const minifiable = (path, script = false) => /\.css$/iu.test(path) ? CSS
59
175
  const MINIFIED_READ = 4 * 1024 * 1024
60
176
  // Its code's lines' average length where they are minified into short ones,
61
177
  // else 0, told by its first MINIFIED_READ characters.
62
- export function minifiedAverage(whole, { stringOrComment, droppable, needed }) {
178
+ export function minifiedAverage(whole, { matchAll, droppable, needed }) {
63
179
  const text = whole.length > MINIFIED_READ ? whole.slice(0, whole.lastIndexOf('\n', MINIFIED_READ) + 1 || MINIFIED_READ) : whole
64
180
  // Its lines of code alone, as long as what is on them: a comment set aside
65
181
  // leaves nothing but its line breaks, a string or template `""` and its, a
66
182
  // regular expression `/REGEX/`, so the code either side stays apart.
67
- const lines = text.replaceAll(stringOrComment, (match, string) => (string === undefined ? '' : string[0] === '/' ? `/${REGEX}/` : '""') + match.replaceAll(/[^\n]/gu, ''))
68
- .replaceAll(/^[ \t]+/gmu, '')
183
+ const parts = []
184
+ let from = 0
185
+ for (const { 0: match, 1: string, index } of matchAll(text)) {
186
+ parts.push(text.slice(from, index), string === undefined ? '' : string[0] === '/' ? `/${REGEX}/` : '""', match.replaceAll(/[^\n]/gu, ''))
187
+ from = index + match.length
188
+ }
189
+ parts.push(text.slice(from))
190
+ const lines = parts.join('').replaceAll(/^[ \t]+/gmu, '')
69
191
  .split('\n').filter(line => line.trim() !== '')
70
192
  const code = lines.join('\n'), length = code.length - (lines.length - 1)
71
193
  // Counted by character: a run aligning `=` is as many spaces as it is wide.
@@ -0,0 +1,43 @@
1
+ // How a built file names its source map, and what a source map is: read
2
+ // alike where a version's map is told rebuilt with its file (npm/compare.js
3
+ // rebuiltWithMap) and where a map's listing is of the file beside it that
4
+ // names it (common/pretty-sourcemap.js).
5
+
6
+ // A `sourceMappingURL` comment and no more, on a file's last line.
7
+ const SOURCE_MAP_FILE = /^\s*(?:\/\/[#@] sourceMappingURL=(\S+)|\/\*[#@] sourceMappingURL=(\S+?)\s*\*\/)\s*$/u
8
+ // A map name a build writes (`a.js.map`, `../maps/a.map`): segments of
9
+ // letters, digits and `._~@+-`, as a browser reads them alike. One at a URL,
10
+ // from a site's root, or with an escape or a backslash names none.
11
+ const MAP_NAME = /^(?:[\w.~@+-]+\/)*[\w.~@+-]+\.map$/u
12
+
13
+ // The map a file's text names on its last line by a plain path from the
14
+ // file's own (MAP_NAME), or null: none named, or one named otherwise (a data:
15
+ // URL, a site's).
16
+ export function mapNamed(text) {
17
+ if (typeof text !== 'string') return null
18
+ const trimmed = text.trimEnd()
19
+ const directive = SOURCE_MAP_FILE.exec(trimmed.slice(trimmed.lastIndexOf('\n') + 1))
20
+ const name = directive?.[1] ?? directive?.[2]
21
+ return name && MAP_NAME.test(name) ? name : null
22
+ }
23
+
24
+ // The path `name` names from beside `file`, or null for one above the root.
25
+ export function besideFile(file, name) {
26
+ const parts = file.split('/').slice(0, -1)
27
+ for (const part of name.split('/')) {
28
+ if (part === '..' && parts.length === 0) return null
29
+ if (part === '..') parts.pop()
30
+ else if (part !== '.') parts.push(part)
31
+ }
32
+ return parts.join('/')
33
+ }
34
+
35
+ // Whether a text is a source map: JSON with `mappings`, or each of an
36
+ // indexed map's `sections` with its own.
37
+ export function isSourceMap(text) {
38
+ try {
39
+ const json = JSON.parse(text)
40
+ return typeof json?.mappings === 'string'
41
+ || (Array.isArray(json?.sections) && json.sections.length > 0 && json.sections.every(section => typeof section?.map?.mappings === 'string'))
42
+ } catch { return false }
43
+ }
package/risk/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  // Hand-written against index.js; a change to either belongs with the other.
2
2
  import type { CacheStore } from '@preventive/upstream/npm.js'
3
+ import type { Entry } from '@preventive/archive/tar.js'
3
4
 
4
5
  // How severe a stamp or a finding is, the most first: `critical` red, `high`
5
6
  // a warning's orange, `moderate` yellow, `low`, and a `notice`.
@@ -13,11 +14,12 @@ export const DEFAULT_MINIMUM_RELEASE_AGE: number
13
14
 
14
15
  // npm has no such package or version (`package-not-found`,
15
16
  // `version-not-found`), a tarball unpacks past risk's bounds
16
- // (`package-too-large`), npm asked to be asked later (`upstream-busy`, a 429,
17
- // for a caller to wait on and ask again), or npm couldn't be asked
18
- // (`upstream-unavailable`), answered past them (`upstream-too-large`) or
19
- // answered what can't be read (`upstream-invalid`). `message` tells which
20
- // request and why.
17
+ // (`package-too-large`) or would install other than one set of files
18
+ // (`tarball-conflict`, npmTarLayout), npm asked to be asked later
19
+ // (`upstream-busy`, a 429, for a caller to wait on and ask again), or npm
20
+ // couldn't be asked (`upstream-unavailable`), answered past them
21
+ // (`upstream-too-large`) or answered what can't be read (`upstream-invalid`).
22
+ // `message` tells which request and why.
21
23
  export class NpmRiskError extends Error {
22
24
  code: string
23
25
  }
@@ -185,6 +187,20 @@ export function npmMalwareAdvisory(advisory: { id?: string | undefined; aliases?
185
187
 
186
188
  export function npmFileRisk(path: string, text: string | null, bytes?: number, script?: boolean): unknown
187
189
 
190
+ // How many levels up a package's symlinks may point: any (npm/tarball.js).
191
+ export const NPM_SYMLINKS_ABOVE: number
192
+
193
+ // Every file a tar archive's entries hold, by package path, as npm and pnpm
194
+ // lay them out (npm/tarball.js): each entry's name as stored past its first
195
+ // component, whatever that is, and a file under no directory at its name, as
196
+ // pnpm installs it; a hard link is the file it names again, a symlink its
197
+ // target as stored (`link`). `refuse` is called, and throws, with
198
+ // `tarball-conflict` where the files conflict (two at one path that differ, a
199
+ // file within another), and with `package-too-large` past `maxFiles` files or
200
+ // `maxBytes` bytes.
201
+ export function npmTarLayout(entries: Iterable<Pick<Entry, 'name' | 'storedName' | 'type' | 'data' | 'linkname'>>, bounds: { maxFiles: number; maxBytes: number },
202
+ refuse: (code: 'tarball-conflict' | 'package-too-large') => never): Map<string, { bytes: Uint8Array; link?: string }>
203
+
188
204
  // GitHub Actions (actions/), a workflow GitHub can't run thrown as
189
205
  // @preventive/lockfile's YamlError. A finding of a workflow's, its `line` from 1; of a reference's own code,
190
206
  // with the `file` it is in.
@@ -194,8 +210,9 @@ export interface ActionsFinding extends Finding {
194
210
  }
195
211
 
196
212
  // What a `uses:` names: an action's or a reusable workflow's, by its `key`,
197
- // or the repository's own.
198
- export type ActionUses = { kind: 'action' | 'workflow'; uses: string; repo: string; path: string; ref: string; pin: 'sha' | 'short-sha' | 'ref' | 'expression'; comment: string | null; key?: string; line?: number | null }
213
+ // or the repository's own. `checkout`, a ref a checkout put a `./` action
214
+ // at, looked for as a branch before a tag.
215
+ export type ActionUses = { kind: 'action' | 'workflow'; uses: string; repo: string; path: string; ref: string; pin: 'sha' | 'short-sha' | 'ref' | 'expression'; comment: string | null; checkout?: true; key?: string; line?: number | null }
199
216
  export type Uses = ActionUses | { kind: 'local'; uses: string; path: string; self?: true; job?: true; line?: number | null }
200
217
 
201
218
  export interface ScanOptions {
package/risk/index.js CHANGED
@@ -5,6 +5,7 @@ export { assessNpm } from './npm/assess.js'
5
5
  export { npmMalwareAdvisory } from './npm/malware.js'
6
6
  export { DEFAULT_MINIMUM_RELEASE_AGE } from './npm/release.js'
7
7
  export { NpmRiskError, npmReadyDownload, npmReadyDownloads } from './npm/registry.js'
8
+ export { NPM_SYMLINKS_ABOVE, npmTarLayout } from './npm/tarball.js'
8
9
  export { SEVERITIES, npmFileRisk } from './files/stamps.js'
9
10
  export { ownFilesOf, scanWorkflow } from './actions/findings.js'
10
11
  export { dockerfileFindings, keptSource, resolveAction } from './actions/resolve.js'
@@ -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 = 18
22
+ const RISK_VERSION = 20
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
@@ -7,12 +7,13 @@
7
7
  // known), and `files` how they differ (diff.js npmFilesDiff): `onlyOther`, the
8
8
  // files the open version adds, and `changed`, those it changes, each `{ path,
9
9
  // renamedFrom?, modified? }`, by its path in the open version.
10
- import { bundleFileSizes, bundleFilesAsMap } from '../../common/bundle-sources.js'
10
+ import { bundleFileLink, bundleFileSizes, bundleFilesAsMap } from '../../common/bundle-sources.js'
11
11
  import { npmLoadedScripts, npmVersionFileRisk, npmVersionHosts } from './files.js'
12
12
  import { npmHostFinding } from './held.js'
13
13
  import { HOST_TAGS, npmHostSeverity, npmHostsTagged } from '../files/hosts.js'
14
14
  import { npmBecameUnreadable, npmBinaryCode, npmLargeCode, npmUnreadable } from '../files/readability.js'
15
15
  import { npmIsScript } from '../files/script.js'
16
+ import { besideFile, isSourceMap, mapNamed } from '../files/source-map-link.js'
16
17
  import { SEVERITIES } from '../files/stamps.js'
17
18
  import { CREDENTIAL_TAGS, npmFoundAdded, npmRunsCodeFlags, npmRunsCodeTagged, npmRunsCodeWithout } from '../files/runs-code.js'
18
19
  import { npmDependencySpecs } from './dependencies.js'
@@ -49,7 +50,7 @@ function npmWokenFiles(base, other, files) {
49
50
  // an obfuscator's fingerprint where the one compared with had none
50
51
  // (`obfuscated`); and a code file it adds or changes that isn't text, where
51
52
  // the one compared with's was text, or no code, or none (npmBinaryCode,
52
- // `binary-code`). Then in orange what any of its files runs beyond itself that
53
+ // `binary-code`), never a symlink (held.js). Then in orange what any of its files runs beyond itself that
53
54
  // `runs-code` doesn't name, kept from the version compared with
54
55
  // (`kept-runs-code`, `kept-credentials`). A renamed file by its old path; one renamed alone,
55
56
  // unchanged, holds what it held. A file become unreadable calls for less
@@ -68,6 +69,7 @@ function npmFileFindings(base, other, files, major) {
68
69
  const woken = npmWokenFiles(base, other, files)
69
70
  const touched = [...new Set([...files.onlyOther, ...changed, ...woken])]
70
71
  const sizes = bundleFileSizes(other)
72
+ const binaryCode = (version, path, readability) => bundleFileLink(version, path) === undefined && npmBinaryCode(path, readability, npmLoadedScripts(version).has(path))
71
73
  // The files that hold what they didn't before, each with that.
72
74
  const gained = key => touched.map(row => ({ path: row.path, added: npmFoundAdded(after(row)[key], before(row)?.[key] ?? null) })).filter(row => row.added)
73
75
  const exfiltration = gained('exfiltration'), runsCode = gained('runsCode')
@@ -90,8 +92,8 @@ function npmFileFindings(base, other, files, major) {
90
92
  ...rebuiltWithMap(base, other, row.path, row.renamedFrom ?? row.path) ? { rebuilt: true } : {} }))) },
91
93
  { id: 'obfuscated', severity: 'critical', files: touched.filter(row => after(row).readability.obfuscation && !before(row)?.readability.obfuscation)
92
94
  .map(row => ({ path: row.path, obfuscation: after(row).readability.obfuscation })) },
93
- { id: 'binary-code', severity: 'critical', files: touched.filter(row => npmBinaryCode(row.path, after(row).readability, npmLoadedScripts(other).has(row.path))
94
- && !npmBinaryCode(row.renamedFrom ?? row.path, before(row)?.readability, npmLoadedScripts(base).has(row.renamedFrom ?? row.path)))
95
+ { id: 'binary-code', severity: 'critical', files: touched.filter(row => binaryCode(other, row.path, after(row).readability)
96
+ && !binaryCode(base, row.renamedFrom ?? row.path, before(row)?.readability))
95
97
  .map(row => ({ path: row.path, bytes: sizes.get(row.path) })) },
96
98
  { id: 'kept-runs-code', severity: 'high', files: ofKinds(kept, 'found', npmRunsCodeWithout) },
97
99
  { id: 'kept-credentials', severity: 'high', files: ofKinds(kept, 'found', npmRunsCodeTagged) },
@@ -126,40 +128,17 @@ function npmMajorRelease(was, now) {
126
128
  // Whether the open version's file at `path` (`basePath` in the one compared
127
129
  // with) had its source map rebuilt with it: its last line, a
128
130
  // `sourceMappingURL` comment and no more, names a map file of the package by
129
- // a plain path from the file's own (MAP_NAME), a source map
131
+ // a plain path from the file's own (source-map-link.js mapNamed), a source map
130
132
  // (its `mappings`, or each of an indexed map's `sections`, told), new or
131
133
  // changed from the one at its path, or beside the file's own before it was
132
134
  // renamed, as a build writes them together. An attack editing a built file
133
135
  // leaves its map as it was.
134
- const SOURCE_MAP_FILE = /^\s*(?:\/\/[#@] sourceMappingURL=(\S+)|\/\*[#@] sourceMappingURL=(\S+?)\s*\*\/)\s*$/u
135
- // A map name a build writes (`a.js.map`, `../maps/a.map`): segments of
136
- // letters, digits and `._~@+-`, as a browser reads them alike. One at a URL,
137
- // from a site's root, or with an escape or a backslash names none.
138
- const MAP_NAME = /^(?:[\w.~@+-]+\/)*[\w.~@+-]+\.map$/u
139
- function besideFile(file, name) {
140
- const parts = file.split('/').slice(0, -1)
141
- for (const part of name.split('/')) {
142
- if (part === '..' && parts.length === 0) return null
143
- if (part === '..') parts.pop()
144
- else if (part !== '.') parts.push(part)
145
- }
146
- return parts.join('/')
147
- }
148
136
  function rebuiltWithMap(base, other, path, basePath) {
149
- const text = bundleFilesAsMap(other).get(path)
150
- const directive = typeof text === 'string' ? SOURCE_MAP_FILE.exec(text.trimEnd().split('\n').at(-1)) : null
151
- const name = directive?.[1] ?? directive?.[2]
152
- if (!name || !MAP_NAME.test(name)) return false
137
+ const name = mapNamed(bundleFilesAsMap(other).get(path))
138
+ if (!name) return false
153
139
  const [map, was] = [bundleFilesAsMap(other).get(besideFile(path, name)), bundleFilesAsMap(base)]
154
140
  return isSourceMap(map) && map !== was.get(besideFile(path, name)) && map !== was.get(besideFile(basePath, name))
155
141
  }
156
- const isSourceMap = text => {
157
- try {
158
- const json = JSON.parse(text)
159
- return typeof json?.mappings === 'string'
160
- || (Array.isArray(json?.sections) && json.sections.length > 0 && json.sections.every(section => typeof section?.map?.mappings === 'string'))
161
- } catch { return false }
162
- }
163
142
 
164
143
  // The files become unreadable as a finding says them: red, but orange in a
165
144
  // major release, or where each had its source map rebuilt with it.
package/risk/npm/diff.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // How two versions' files differ, as Compare's diff has them
2
- // (ui/view/bundle-compare-diff.js computeBundleDiff), for risk's findings
2
+ // (common/bundle-compare-diff.js computeBundleDiff), for risk's findings
3
3
  // (compare.js): the files the open version adds, and those it changes, a
4
4
  // build's content-hashed file paired with the one it replaces by its name
5
5
  // (hashedKey), and a file moved to another path with its old one by content,
package/risk/npm/held.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // it: what npm says of it and when it was published (npmVersionFindings),
3
3
  // and what it holds that calls for a look whatever came before it
4
4
  // (npmHeldFindings), as Compare's findings (compare.js) say what changed.
5
- import { bundleFilesAsMap } from '../../common/bundle-sources.js'
5
+ import { bundleFileLink, bundleFilesAsMap, symlinkTarget } from '../../common/bundle-sources.js'
6
6
  import { npmDownloadTier, npmTierLevel, npmTierLow } from './downloads.js'
7
7
  import { npmInstallScripts } from './install-scripts.js'
8
8
  import { npmTooNew } from './release.js'
@@ -44,17 +44,21 @@ export function npmVersionFindings({ deprecated, published, minimumReleaseAge, n
44
44
  // `held-credentials`), name a service under one of the hosts' tags, at the
45
45
  // tag's severity (hosts.js HOST_TAGS: `held-exfiltration` red, `held-remote`
46
46
  // orange, `held-ip-lookup` yellow), or bear an obfuscator's fingerprint
47
- // (`held-obfuscated`).
47
+ // (`held-obfuscated`). Then its symlinks, which Yarn installs (npm and pnpm
48
+ // skip them), red where one points out of the package (`held-symlinks`).
48
49
  export function npmHeldFindings(version) {
49
50
  const scripts = npmInstallScripts(version.npm.manifest, version.json?.sources)
50
51
  const reads = [...bundleFilesAsMap(version).keys()].map(path => ({ path, read: npmVersionFileRisk(version, path) }))
51
52
  const holding = of => reads.map(({ path, read }) => ({ path, found: of(read) })).filter(row => row.found)
53
+ const links = reads.map(({ path }) => ({ path, link: bundleFileLink(version, path) })).filter(row => row.link !== undefined)
54
+ .map(row => symlinkTarget(row.path, row.link) === null ? { ...row, outside: true } : row)
52
55
  return [
53
56
  ...scripts.length > 0 ? [{ id: 'held-install-scripts', severity: 'high', scripts }] : [],
54
57
  { id: 'held-runs-code', severity: 'high', files: holding(read => npmRunsCodeWithout(read.runsCode, CREDENTIAL_TAGS)) },
55
58
  { id: 'held-credentials', severity: 'high', files: holding(read => npmRunsCodeTagged(read.runsCode, CREDENTIAL_TAGS)) },
56
59
  ...[...HOST_TAGS].map(([tag, severity]) => ({ id: `held-${npmHostFinding(tag)}`, severity, files: holding(read => npmHostsTagged(read.exfiltration, tag)) })),
57
60
  { id: 'held-obfuscated', severity: 'high', files: holding(read => read.readability.obfuscation) },
61
+ { id: 'held-symlinks', severity: links.some(row => row.outside) ? 'critical' : 'high', files: links },
58
62
  ].filter(finding => !finding.files || finding.files.length > 0)
59
63
  }
60
64
 
@@ -30,7 +30,9 @@
30
30
  // of npm to; else a tarball is upstream's getTarball's, bounded as upstream
31
31
  // bounds it. What risk asks npm itself is given up on after 30 seconds, and
32
32
  // read no further than its bounds, `upstream-too-large` past them, as is a
33
- // tarball unpacking past tarball.js's, `package-too-large`.
33
+ // tarball unpacking past tarball.js's, `package-too-large`; one installers
34
+ // would install other than one set of files from (tarball.js npmTarLayout)
35
+ // is `tarball-conflict`.
34
36
  import { advisories } from '@preventive/upstream/advisories.js'
35
37
  import { getTarball } from '@preventive/upstream/npm.js'
36
38
  import { compareVersions, satisfies, validRange } from '@preventive/upstream/semver.js'
@@ -261,7 +263,8 @@ export async function npmVersionFiles(name, version, { manifest, published, dist
261
263
  throw signal?.aborted ? error : new NpmRiskError('upstream-unavailable', `npm's tarball of ${what} couldn't be had: ${error.message}`)
262
264
  })
263
265
  try { return { npm: { name, version, manifest, published }, ...await npmTarballVersion(tarball) } } catch (error) {
264
- throw new NpmRiskError(error.message === 'package-too-large' ? 'package-too-large' : 'upstream-invalid', `npm's tarball of ${what}: ${error.message}`)
266
+ const code = error.message === 'package-too-large' || error.message === 'tarball-conflict' ? error.message : 'upstream-invalid'
267
+ throw new NpmRiskError(code, `npm's tarball of ${what}: ${error.message}`)
265
268
  }
266
269
  }
267
270
 
@@ -1,8 +1,8 @@
1
1
  // A package's files from its tarball, as it holds them, whatever installs it
2
2
  // (npm renames a .gitignore .npmignore, pnpm and yarn keep it): gunzipped and
3
3
  // read as a tar archive by @preventive/archive, which refuses one malformed, a
4
- // name or a symlink that would climb out of it, and a name repeated as another
5
- // entry; each file by its path there, its first component dropped; a text
4
+ // name that would climb out of it, an absolute symlink, and a name repeated as another
5
+ // entry; each file at the path installers put it (npmTarLayout); a text
6
6
  // where it is UTF-8 with no NUL, else null. Held to the npm viewer's bounds
7
7
  // (server-managed/npm-packages.ts readNpmTar).
8
8
  import { CompressionError, decompress } from '@preventive/archive/compression.js'
@@ -17,31 +17,88 @@ export const MAX_TAR_ENTRIES = 2 * MAX_PACKAGE_FILES
17
17
  // files, as npm-loads.ts bounds it (MAX_TAR_BYTES).
18
18
  export const MAX_TAR_BYTES = 96 * 1024 * 1024
19
19
 
20
+ // A symlink is read for where it points, never followed, so it may point any number of levels up.
21
+ export const NPM_SYMLINKS_ABOVE = Number.MAX_SAFE_INTEGER
22
+
20
23
  const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
21
24
 
22
- // The files of a tar archive, by path: their bytes. A file at its top is not
23
- // extracted, and one under another top directory at the same path replaces
24
- // an earlier one, as extraction would. Past MAX_TAR_ENTRIES it is given up on
25
- // as `package-too-large`, before any more of it is read.
25
+ // Where npm and pnpm install a tar entry's file in its package: its name as
26
+ // stored past its first component, whatever that is (`package/`, a release's
27
+ // own `ejs-v3.1.10/`, `.` where it was packed from within the package), its
28
+ // `.` segments dropped, as each drops one component of the name it reads; a
29
+ // file under no directory at that name, as pnpm installs it (npm leaves it
30
+ // out, and fails on a tarball of such files alone, its package.json gone).
31
+ // '' where no name is left, the package's own place.
32
+ export function npmTarPath(storedName) {
33
+ const segments = storedName.split('/')
34
+ return segments.length === 1 ? storedName : segments.slice(1).filter(segment => segment !== '.').join('/')
35
+ }
36
+
37
+ const sameBytes = (a, b) => a.length === b.length && a.every((byte, at) => byte === b[at])
38
+ const sameFile = (a, b) => a.link === b.link && sameBytes(a.bytes, b.bytes)
39
+ const encoder = new TextEncoder()
40
+
41
+ // Every file a tar archive holds, by package path (npmTarPath): `{ bytes }`,
42
+ // whether or not an installer installs it; a symlink `{ bytes, link }`, its
43
+ // target as stored and that target's UTF-8 (Yarn installs it; npm, pnpm and
44
+ // bun skip it). A hard link is the file it names again, as tar has it (npm and pnpm 12 skip it, pnpm 10 and 11
45
+ // write it empty); a file at the package's own place (`package/.`) sits at
46
+ // its name in the archive. Where the archive's own files conflict, it is
47
+ // refused as `tarball-conflict`, rather than read as one installer does: two
48
+ // files at one path, unless their bytes are the same (npm and pnpm install the
49
+ // last, so a file under another top directory, or at the top, replaces one
50
+ // 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.
53
+ // Past `maxFiles` files or `maxBytes` bytes, `package-too-large`.
54
+ // `refuse(code)` throws.
55
+ export function npmTarLayout(entries, { maxFiles, maxBytes }, refuse) {
56
+ 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.
59
+ const root = new Map()
60
+ // Each file by its name in the archive, which a hard link names.
61
+ const named = new Map()
62
+ let total = 0
63
+ for (const { name, storedName, type, data, linkname } of entries) {
64
+ const file = type === 'hardlink' ? named.get(linkname) : type === 'file' || type === 'contiguous-file' ? { bytes: data }
65
+ : type === 'symlink' ? { bytes: encoder.encode(linkname), link: linkname } : undefined
66
+ if (file === undefined) continue
67
+ named.set(name, file)
68
+ 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)
83
+ files.set(path, file)
84
+ total += file.bytes.length
85
+ if (files.size > maxFiles || total > maxBytes) refuse('package-too-large')
86
+ }
87
+ return files
88
+ }
89
+
90
+ // The files of a tar archive, by path: their bytes, as installers lay them
91
+ // out (npmTarLayout). Past MAX_TAR_ENTRIES it is given up on as
92
+ // `package-too-large`, before any more of it is read.
26
93
  function npmTarFiles(tar) {
27
94
  let entries
28
95
  try {
29
- entries = unpack(tar, { maxEntries: MAX_TAR_ENTRIES })
96
+ entries = unpack(tar, { maxEntries: MAX_TAR_ENTRIES, symlinksAbove: NPM_SYMLINKS_ABOVE })
30
97
  } catch (error) {
31
98
  if (error instanceof ArchiveError && error.limited) throw new Error('package-too-large', { cause: error })
32
99
  throw error
33
100
  }
34
- const files = new Map()
35
- let total = 0
36
- for (const { name, type, data } of entries) {
37
- const slash = name.indexOf('/')
38
- if ((type !== 'file' && type !== 'contiguous-file') || slash === -1) continue
39
- const path = name.slice(slash + 1)
40
- total += data.length - (files.get(path)?.length ?? 0)
41
- files.set(path, data)
42
- if (files.size > MAX_PACKAGE_FILES || total > MAX_PACKAGE_BYTES) throw new Error('package-too-large')
43
- }
44
- return files
101
+ return npmTarLayout(entries, { maxFiles: MAX_PACKAGE_FILES, maxBytes: MAX_PACKAGE_BYTES }, code => { throw new Error(code) })
45
102
  }
46
103
 
47
104
  // A file's text: UTF-8 with no NUL, else null.
@@ -86,11 +143,11 @@ const sha256 = async bytes => `sha256-${btoa(String.fromCodePoint(...new Uint8Ar
86
143
  // map listing them (`kind: 'sourcemap'`): `json.sources` their paths, sorted,
87
144
  // `json.sourcesContent` their texts, `fileSizes` by path, and `npmBinaries`,
88
145
  // those that aren't text, `{ size, digest, runnable }` by path (npmRunnable),
89
- // which compare.js and
146
+ // a symlink's with its `link`, which compare.js and
90
147
  // diff.js tell them by.
91
148
  export async function npmTarballVersion(gzipped) {
92
149
  const files = [...npmTarFiles(await gunzip(gzipped))].toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
93
- const texts = files.map(([, bytes]) => npmFileText(bytes))
94
- const binaries = await Promise.all(files.filter((_, at) => texts[at] === null).map(async ([path, bytes]) => [path, { size: bytes.length, digest: await sha256(bytes), runnable: npmRunnable(bytes) }]))
95
- return { kind: 'sourcemap', json: { version: 3, sources: files.map(([path]) => path), sourcesContent: texts }, fileSizes: new Map(files.map(([path, bytes]) => [path, bytes.length])), npmBinaries: new Map(binaries) }
150
+ const texts = files.map(([, { bytes, link }]) => link === undefined ? npmFileText(bytes) : null)
151
+ const binaries = await Promise.all(files.filter((_, at) => texts[at] === null).map(async ([path, { bytes, link }]) => [path, { size: bytes.length, digest: await sha256(bytes), runnable: link === undefined && npmRunnable(bytes), ...link === undefined ? {} : { link } }]))
152
+ return { kind: 'sourcemap', json: { version: 3, sources: files.map(([path]) => path), sourcesContent: texts }, fileSizes: new Map(files.map(([path, { bytes }]) => [path, bytes.length])), npmBinaries: new Map(binaries) }
96
153
  }