@shieldaai/security-watch 0.1.0-alpha.0 → 1.0.0

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 (92) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/CONTRIBUTING.md +4 -2
  3. package/README.md +173 -48
  4. package/SECURITY.md +24 -9
  5. package/dist/assessment.d.ts +12 -1
  6. package/dist/assessment.js +223 -52
  7. package/dist/cli.js +340 -27
  8. package/dist/config.d.ts +62 -2
  9. package/dist/config.js +88 -5
  10. package/dist/coverage.d.ts +4 -0
  11. package/dist/coverage.js +11 -0
  12. package/dist/cve-now.d.ts +32 -2
  13. package/dist/cve-now.js +715 -126
  14. package/dist/cvss4.d.ts +3 -0
  15. package/dist/cvss4.js +39 -0
  16. package/dist/delivery.d.ts +34 -2
  17. package/dist/delivery.js +391 -98
  18. package/dist/ecosystems.d.ts +23 -0
  19. package/dist/ecosystems.js +88 -10
  20. package/dist/engine.d.ts +55 -1
  21. package/dist/engine.js +101 -20
  22. package/dist/everyday-words.d.ts +11 -0
  23. package/dist/everyday-words.js +256 -0
  24. package/dist/health.d.ts +7 -0
  25. package/dist/health.js +55 -3
  26. package/dist/http.d.ts +7 -0
  27. package/dist/http.js +31 -2
  28. package/dist/index.d.ts +22 -4
  29. package/dist/index.js +12 -4
  30. package/dist/inventory-evidence.d.ts +10 -0
  31. package/dist/inventory-evidence.js +206 -0
  32. package/dist/inventory.d.ts +273 -0
  33. package/dist/inventory.js +210 -17
  34. package/dist/maintenance.d.ts +5 -0
  35. package/dist/maintenance.js +73 -5
  36. package/dist/matching.d.ts +29 -0
  37. package/dist/matching.js +537 -0
  38. package/dist/models.d.ts +17 -4
  39. package/dist/models.js +359 -29
  40. package/dist/pilot-cases.d.ts +171 -0
  41. package/dist/pilot-cases.js +330 -0
  42. package/dist/pilot-input.d.ts +16 -0
  43. package/dist/pilot-input.js +125 -0
  44. package/dist/pilot-recall.d.ts +166 -0
  45. package/dist/pilot-recall.js +231 -0
  46. package/dist/pilot-report.d.ts +113 -0
  47. package/dist/pilot-report.js +279 -0
  48. package/dist/pilot-responses.d.ts +111 -0
  49. package/dist/pilot-responses.js +159 -0
  50. package/dist/python-version.d.ts +3 -0
  51. package/dist/python-version.js +30 -0
  52. package/dist/rehearsal.d.ts +440 -0
  53. package/dist/rehearsal.js +372 -0
  54. package/dist/sbom.d.ts +13 -0
  55. package/dist/sbom.js +193 -0
  56. package/dist/source-error.d.ts +17 -1
  57. package/dist/source-error.js +18 -3
  58. package/dist/sources.d.ts +2 -2
  59. package/dist/sources.js +699 -45
  60. package/dist/store.d.ts +38 -13
  61. package/dist/store.js +325 -23
  62. package/dist/types.d.ts +159 -2
  63. package/dist/util.d.ts +23 -0
  64. package/dist/util.js +81 -1
  65. package/dist/vendor/cvss4-reference.d.ts +2 -0
  66. package/dist/vendor/cvss4-reference.js +789 -0
  67. package/dist/word-filter.d.ts +3 -0
  68. package/dist/word-filter.js +3291 -0
  69. package/docs/alert-outcome-evaluation.md +150 -0
  70. package/docs/compatibility.md +35 -0
  71. package/docs/configuration.md +289 -29
  72. package/docs/cvss-v4-support.md +41 -0
  73. package/docs/offline-advisory-preview.md +114 -0
  74. package/docs/offline-rehearsal.md +44 -0
  75. package/docs/pilot-cases.md +58 -0
  76. package/docs/pilot-recall.md +124 -0
  77. package/docs/pilot-report.md +52 -0
  78. package/docs/validation/alert-outcome-evaluation-2026-11-05.json +2935 -0
  79. package/docs/validation/cvss-v4-reference-parity-2026-11-05.json +93 -0
  80. package/docs/validation/rehearsal-accepted-2026-11-05.json +175 -0
  81. package/docs/validation/rehearsal-unknown-2026-11-05.json +175 -0
  82. package/docs/vendor/cvss-v4-LICENSE.txt +22 -0
  83. package/docs/vendor/cvss-v4-provenance.json +38 -0
  84. package/examples/agent-advisories-2026.json +145 -0
  85. package/examples/agent-advisory-cases-2026.json +397 -0
  86. package/examples/libraries.example.txt +4 -2
  87. package/examples/libraries.example.yaml +2 -0
  88. package/examples/offline-advisory-preview.mjs +42 -0
  89. package/examples/rehearsal.json +75 -0
  90. package/examples/systems.example.yaml +4 -0
  91. package/package.json +23 -7
  92. package/docs/quality-review.md +0 -104
@@ -0,0 +1,537 @@
1
+ import { packageKey } from './ecosystems.js';
2
+ import { dictionaryName, everydayWord, properName } from './everyday-words.js';
3
+ const escape = (value) => value.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
4
+ /** Word/identifier boundaries prevent "express" matching "expressions" or another npm scope. */
5
+ const bounded = (pattern) => new RegExp(`(?<![\\p{L}\\p{N}_@/\\-])(?:${pattern})(?![\\p{L}\\p{N}_@/\\-])`, 'iu');
6
+ export function mentions(text, needle) {
7
+ if (needle.trim().length < 3)
8
+ return false;
9
+ return bounded(escape(needle)).test(text);
10
+ }
11
+ /**
12
+ * The registry of each ecosystem and its tools, as prose names them. A language name is not in
13
+ * this list: "the Python backdoor sends requests" is not about the `requests` package.
14
+ */
15
+ /** The install command of each ecosystem, as written in advisories and articles. */
16
+ const INSTALL = {
17
+ npm: '(?:npm (?:install|i|add)|yarn add|pnpm (?:add|install))',
18
+ PyPI: '(?:pip3? install|pipx install|uv (?:add|pip install)|poetry add)',
19
+ Packagist: 'composer require',
20
+ Go: 'go (?:get|install)',
21
+ Maven: '(?!)',
22
+ 'crates.io': 'cargo (?:add|install)',
23
+ RubyGems: '(?:gem install|bundle add)',
24
+ NuGet: '(?:dotnet add package|nuget install|Install-Package)',
25
+ Hex: 'mix (?:deps\\.get|archive\\.install)',
26
+ Pub: '(?:dart|flutter) pub add',
27
+ Hackage: 'cabal install',
28
+ SwiftURL: '(?!)',
29
+ };
30
+ const LANGUAGE_CONTEXT = {
31
+ npm: 'node\\.js|nodejs|javascript|typescript',
32
+ PyPI: 'python',
33
+ Packagist: 'php',
34
+ Go: 'golang|go',
35
+ Maven: 'java',
36
+ 'crates.io': 'rust',
37
+ RubyGems: 'ruby',
38
+ NuGet: '\\.net|dotnet',
39
+ Hex: 'elixir|erlang',
40
+ Pub: 'dart|flutter',
41
+ Hackage: 'haskell',
42
+ SwiftURL: 'swift',
43
+ };
44
+ const REGISTRY_CONTEXT = {
45
+ npm: 'npm|yarn|pnpm',
46
+ PyPI: 'pypi|pip',
47
+ Packagist: 'packagist|composer',
48
+ Go: 'go module|go modules',
49
+ Maven: 'maven|gradle',
50
+ 'crates.io': 'crates\\.io|cargo|crate|crates',
51
+ RubyGems: 'rubygems|gem|gems',
52
+ NuGet: 'nuget',
53
+ Hex: 'hex\\.pm',
54
+ Pub: 'pub\\.dev',
55
+ Hackage: 'hackage|cabal',
56
+ SwiftURL: 'swift package|swiftpm',
57
+ };
58
+ /**
59
+ * A test for English-word names that the text itself calls a package. The word "package" somewhere
60
+ * near is not enough: "the packages, which deliver a loader", "found three packages" and "a buffer
61
+ * overflow in the C library" are about other things. The name has to be named as one:
62
+ * - "the request package", "the requests library", "the entities npm package": the name, then
63
+ * "package", "library", "module", "dependency", "gem", "crate" or "plugin", in the singular;
64
+ * - "the npm package next", "PyPI package requests": a registry, the kind, then the name;
65
+ * - "a package called send", "a dependency named once": the kind, "called" or "named", the name;
66
+ * - "npm install send", "pip install requests", "npm:send": an install command or registry prefix;
67
+ * - "the npm packages chalk and debug": a registry, the kind in the plural, and a short list;
68
+ * - "the Python framework Tornado": the language, what the software is, the name with a capital.
69
+ */
70
+ function namedAsPackage(names, ecosystem, common) {
71
+ const unique = [...new Set([...names].map((name) => name.trim()).filter((name) => name.length >= 3))];
72
+ const registry = `(?:${REGISTRY_CONTEXT[ecosystem]})`;
73
+ // "module" is left out: kernel, PAM and web-server modules are not packages.
74
+ const kind = '(?:package|library|dependency|gem|crate|plugin)';
75
+ const kinds = '(?:packages|libraries|dependencies|gems|crates|plugins)';
76
+ const install = INSTALL[ecosystem];
77
+ // One entry of a list of package names. Words that join a sentence are never one: "npm packages
78
+ // that send", "PyPI packages which steal".
79
+ const joining = 'that|which|who|whose|to|are|were|was|is|be|been|being|have|has|had|and|or|but|with|from|for|in|on|of|the|a|an|this|these|those|not|no|it|its|they|their|as|by|at|into|than|then|so|such|also|now|designed|found|used|named|called|published|uploaded|removed';
80
+ const item = `(?!(?:${joining})(?![\\p{L}\\p{N}]))[\\p{L}\\p{N}@/._-]+`;
81
+ // A package named like one of those words is not taken from a list either, unless quoted.
82
+ const joiningWord = new RegExp(`^(?:${joining})$`, 'iu');
83
+ const quote = '["\'`‘’“”]?';
84
+ const { before, after } = boundary;
85
+ const patterns = [];
86
+ for (let offset = 0; offset < unique.length; offset += 400) {
87
+ const chunk = unique.slice(offset, offset + 400);
88
+ const name = `(?:${chunk.map(escape).join('|')})`;
89
+ const listed = chunk.filter((value) => !joiningWord.test(value));
90
+ // In a list a name must be quoted when it is one of the joining words.
91
+ const listName = listed.length
92
+ ? `(?:${quote}(?:${listed.map(escape).join('|')})${quote}|["'\`‘’“”]${name}["'\`‘’“”])`
93
+ : `(?:["'\`‘’“”]${name}["'\`‘’“”])`;
94
+ patterns.push(new RegExp([
95
+ // "the request package", "the requests library". For the commonest words ("which package
96
+ // was affected", "the standard library", "the next package update") the name has to be
97
+ // quoted or followed by the registry: "the 'request' package", "the request npm package".
98
+ common
99
+ ? `${before}(?:["'\`‘’“”]${name}["'\`‘’“”] (?:${registry} )?|${name} ${registry} )${kind}${after}`
100
+ : `${before}${quote}${name}${quote} (?:${registry} )?${kind}${after}`,
101
+ `${before}${registry} ${kind} ${quote}${name}${after}`,
102
+ `${before}${kind} (?:called|named) ${quote}${name}${after}`,
103
+ // The ecosystem's own install command: "pip install express" is not about npm.
104
+ `${before}${install} (?:-\\S+ )*${quote}${name}(?![\\p{L}\\p{N}_/\\-])`,
105
+ `${before}${registry}:${name}${after}`,
106
+ // A real list of names next to a registry and the kind in the plural, with a comma or "and"
107
+ // between the entries: "the npm packages chalk, colors and debug", "the npm libraries
108
+ // colors and faker", "Chalk and Debug npm Packages". One word after or before the plural
109
+ // is not a list: "npm packages that send", "six npm packages".
110
+ `${before}${registry} ${kinds} (?:${item}, ){0,4}${listName}(?:, ${item}){0,4},? and ${item}${after}`,
111
+ `${before}${registry} ${kinds} (?:${item}, ){0,4}${item},? and ${listName}${after}`,
112
+ `${before}(?:${item}, ){0,4}${listName}(?:, ${item}){0,4},? and ${item} ${registry} ${kinds}${after}`,
113
+ `${before}(?:${item}, ){0,4}${item},? and ${listName} ${registry} ${kinds}${after}`,
114
+ // "chalk, debug and 16 other npm packages": the commonest way a compromise report lists them.
115
+ `${before}(?:${item}, ){0,6}${listName}(?:, ${item}){0,6},? and \\d+ (?:other |more )?${registry} ${kinds}${after}`,
116
+ ].join('|'), 'iu'));
117
+ // The ecosystem's language, what the software is, then the name with a capital: "the Python
118
+ // framework Tornado", "the Python formatter Black".
119
+ patterns.push(new RegExp(`${before}(?i:${LANGUAGE_CONTEXT[ecosystem]}) (?:[\\p{Ll}-]+ )?(?:framework|library|package|module|formatter|linter|tool|client|server|parser|compiler|bundler|runtime) (?:${unique
120
+ .slice(offset, offset + 400)
121
+ .map(capitalised)
122
+ .join('|')})${after}`, 'u'));
123
+ }
124
+ return (text) => patterns.some((pattern) => pattern.test(text));
125
+ }
126
+ function nameKind(name) {
127
+ if (!dictionaryName(name))
128
+ return 'distinctive';
129
+ return everydayWord(name) ? 'common' : 'dictionary';
130
+ }
131
+ /**
132
+ * After a name: something only a release is written with. That is "@1.2", "v1.2" or a three-part
133
+ * version ("Requests 2.32.0"). A bare decimal is not enough: "send 1.5 million requests" and "the
134
+ * next 5.5 years" are quantities. Nor is an address: "IP address 203.0.113.7" has four parts.
135
+ */
136
+ const RELEASE_SUFFIX = '(?:@v?\\d+\\.\\d+| v\\d+\\.\\d+| \\d+\\.\\d+\\.\\d+(?!\\.\\d))';
137
+ /** Only the forms no prose writes: "through@1.2", "through v1.2". */
138
+ const STRICT_RELEASE_SUFFIX = '(?:@v?\\d+\\.\\d+| v\\d+\\.\\d+)';
139
+ /**
140
+ * Words that stand before a version in prose about version ranges: "7.0.0 through 7.0.16", "from
141
+ * 16.1.0", "versions up to 4.1.2". Packages with these names exist; a version after the word is
142
+ * not a release of them unless it is written "name@1.2" or "name v1.2".
143
+ */
144
+ const CONNECTORS = new Set(`through thru from after before until till to since between and or below above under over prior
145
+ including include includes inclusive exclusive version versions release releases build builds patch
146
+ patched update updated upgrade upgraded fixed fix fixes affected affects up down at in on of is are
147
+ was were be all any each every than then latest earliest older newer later earlier`.split(/\s+/));
148
+ const QUANTITY = '(?i:%|percent|thousand|million|billion|trillion|times|x|[kmgt]b|bytes|seconds?|minutes?|hours?|days?|weeks?|months?|years?|cvss|severity|score|rated|rating|out of|bn|usd|eur|gbp|jpy|euros?|pounds?|dollars?|btc|eth|xmr|usdt|ltc|bitcoins?|ether|monero)(?![\\p{L}\\p{N}])';
149
+ const boundary = { before: '(?<![\\p{L}\\p{N}_@/\\-])', after: '(?![\\p{L}\\p{N}_@/\\-])' };
150
+ /** A name with its first letter in upper case and the rest in either case. */
151
+ const capitalised = (name) => [...name.trim()]
152
+ .map((letter, index) => index === 0
153
+ ? escape(letter.toUpperCase())
154
+ : `[${escape(letter.toLowerCase())}${escape(letter.toUpperCase())}]`)
155
+ .join('');
156
+ /**
157
+ * A test for names written as a release. For npm that includes the way JavaScript libraries are
158
+ * called: "Next.js", "Express.js", "ExpressJS", with a capital. In lower case, "config.js" and
159
+ * "server.js" are file names.
160
+ */
161
+ function releaseTest(names, ecosystem) {
162
+ const all = [...new Set([...names].map((name) => name.trim()))];
163
+ const unique = all.filter((name) => name.length >= 3);
164
+ const patterns = [];
165
+ // A name of two characters ("ws", "qs", "ip") is too short to be told from anything else in
166
+ // prose. It counts only as `name@version`.
167
+ const short = all.filter((name) => name.length === 2);
168
+ for (let offset = 0; offset < short.length; offset += 400)
169
+ patterns.push(bounded(`(?:${short
170
+ .slice(offset, offset + 400)
171
+ .map(escape)
172
+ .join('|')})@v?\\d+\\.\\d+`));
173
+ // Or, in exactly its own spelling, right next to the word "package" or "library" ("module" is
174
+ // left out: "the send module" too often names a part of a product, not a package):
175
+ // "the ws library", "the npm package qs". "IP address" is not the package `ip`.
176
+ for (let offset = 0; offset < short.length; offset += 400) {
177
+ const alternatives = `(?:${short
178
+ .slice(offset, offset + 400)
179
+ .map(escape)
180
+ .join('|')})`;
181
+ const word = '(?:packages?|librar(?:y|ies))';
182
+ patterns.push(new RegExp(`${boundary.before}${alternatives} (?:[\\p{L}\\p{N}]+ )?${word}${boundary.after}|${boundary.before}${word} ${alternatives}${boundary.after}`, 'u'));
183
+ }
184
+ // "Rails 7.2", "Salt 3007.1": a two-part version after an English word written with a capital,
185
+ // unless a unit or a rating follows ("the Next 2.5 years", "Address 9.8 CVSS bug").
186
+ const named = unique.filter((name) => /^\p{L}+$/u.test(name) && nameKind(name) !== 'distinctive' && !CONNECTORS.has(name.toLowerCase()));
187
+ for (let offset = 0; offset < named.length; offset += 400)
188
+ patterns.push(new RegExp(`${boundary.before}(?:${named
189
+ .slice(offset, offset + 400)
190
+ .map(capitalised)
191
+ .join('|')}) \\d+\\.\\d+(?![\\p{L}\\p{N}_@/%\\-]|\\.\\d| ?${QUANTITY})`, 'u'));
192
+ for (let offset = 0; offset < unique.length; offset += 400) {
193
+ const chunk = unique.slice(offset, offset + 400);
194
+ const loose = chunk.filter((name) => !CONNECTORS.has(name.toLowerCase()));
195
+ const strict = chunk.filter((name) => CONNECTORS.has(name.toLowerCase()));
196
+ if (loose.length)
197
+ patterns.push(bounded(`(?:${loose.map(escape).join('|')})${RELEASE_SUFFIX}`));
198
+ if (strict.length)
199
+ patterns.push(bounded(`(?:${strict.map(escape).join('|')})${STRICT_RELEASE_SUFFIX}`));
200
+ // How a library is often called after its ecosystem: "node-tar", "Python-Markdown".
201
+ const prefix = ecosystem === 'npm' ? 'node-' : ecosystem === 'PyPI' ? 'python-' : undefined;
202
+ if (prefix)
203
+ patterns.push(new RegExp(`${boundary.before}${prefix}(?:${chunk.map(escape).join('|')})${boundary.after}`, 'iu'));
204
+ if (ecosystem === 'npm') {
205
+ // In lower case too, unless the word is one of the commonest: "validator.js" is the library,
206
+ // "config.js" and "server.js" are files.
207
+ const uncommon = chunk.filter((name) => nameKind(name) !== 'common');
208
+ if (uncommon.length)
209
+ patterns.push(bounded(`(?:${uncommon.map(escape).join('|')})\\.js`));
210
+ patterns.push(new RegExp(`${boundary.before}(?:${chunk.map(capitalised).join('|')})(?:\\.js|JS)${boundary.after}`, 'u'));
211
+ }
212
+ }
213
+ return (text) => patterns.some((pattern) => pattern.test(text));
214
+ }
215
+ /**
216
+ * Whether prose names this package. A name that is not an English word counts wherever it appears.
217
+ * An English word counts only when the text is about packages, names a release of it, or (for a
218
+ * word that is not among the commonest) writes it as a name. So "buffer overflow in a router" does
219
+ * not match the npm package `buffer`, "federal entities" does not match `entities`, "Next.js" does
220
+ * match `next`, and "a flaw in Express" does match `express`. A name written with a version, such
221
+ * as `send@0.19.0`, always counts.
222
+ */
223
+ export function packageMentioned(text, component) {
224
+ const name = component.name.trim();
225
+ if (name.length < 2)
226
+ return false;
227
+ // News names a Maven library by its artifact ("jackson-databind", "SnakeYAML"), not by its
228
+ // coordinates. An artifact name that is not English is the library wherever it appears.
229
+ const artifact = mavenArtifact(component);
230
+ if (artifact && packageMentioned(text, { ecosystem: 'Maven', name: artifact }))
231
+ return true;
232
+ // One story is compared with every component, and a story that cites many advisories is
233
+ // compared again for each of them: remember the answers for the texts seen last.
234
+ let seen = recent.get(text);
235
+ if (!seen) {
236
+ if (recent.size >= RECENT_TEXTS)
237
+ recent.clear();
238
+ const lower = text.toLowerCase();
239
+ seen = { lower, words: new Set(lower.match(/[a-z0-9]+/g) ?? []), answers: new Map() };
240
+ recent.set(text, seen);
241
+ }
242
+ const key = `${component.ecosystem}\n${name}`;
243
+ let answer = seen.answers.get(key);
244
+ if (answer === undefined) {
245
+ // Most components are not in most texts: a plain search settles that before any expression
246
+ // is built for the name.
247
+ // A name of plain letters and digits is looked up among the words of the text ("express", or
248
+ // "expressjs"); searching the whole text for every component costs too much for a lockfile of
249
+ // thousands. Any other name is searched for as it is.
250
+ const wanted = name.toLowerCase();
251
+ const present = /^[a-z0-9]+$/.test(wanted)
252
+ ? seen.words.has(wanted) || seen.words.has(`${wanted}js`)
253
+ : seen.lower.includes(wanted);
254
+ answer = present && nameTests(component.ecosystem, name)(text);
255
+ seen.answers.set(key, answer);
256
+ }
257
+ return answer;
258
+ }
259
+ /** The artifact of Maven coordinates, when news can name the library by it alone. */
260
+ function mavenArtifact(component) {
261
+ if (component.ecosystem !== 'Maven')
262
+ return undefined;
263
+ const artifact = component.name.trim().split(':')[1];
264
+ return artifact && artifact.length >= 5 && nameKind(artifact) === 'distinctive' ? artifact : undefined;
265
+ }
266
+ /** How many texts, and how many compiled names, are remembered before starting over. */
267
+ const RECENT_TEXTS = 32;
268
+ const COMPILED_NAMES = 50_000;
269
+ const recent = new Map();
270
+ const compiled = new Map();
271
+ /** The compiled test for one name; building its expressions once matters for large inventories. */
272
+ function nameTests(ecosystem, name) {
273
+ const key = `${ecosystem}\n${name}`;
274
+ let test = compiled.get(key);
275
+ if (!test) {
276
+ const release = releaseTest([name], ecosystem);
277
+ const mention = bounded(escape(name));
278
+ const kind = nameKind(name);
279
+ const named = kind === 'dictionary' ? writtenAsName([name]) : () => false;
280
+ const near = kind === 'distinctive' ? undefined : namedAsPackage([name], ecosystem, kind === 'common');
281
+ test = (text) => {
282
+ if (release(text))
283
+ return true;
284
+ if (name.length < 3)
285
+ return false;
286
+ // Named as a package, which may be written with a version ("npm install send@latest").
287
+ if (near?.(text))
288
+ return true;
289
+ if (!mention.test(text))
290
+ return false;
291
+ return !near || named(text);
292
+ };
293
+ if (compiled.size >= COMPILED_NAMES)
294
+ compiled.clear();
295
+ compiled.set(key, test);
296
+ }
297
+ return test;
298
+ }
299
+ /** A line set in title case: most of its longer words are capitalised, so a capital shows nothing. */
300
+ function titleCase(line) {
301
+ const words = line.match(/\p{L}{4,}/gu) ?? [];
302
+ if (words.length < 5)
303
+ return false;
304
+ return words.filter((word) => /^\p{Lu}/u.test(word)).length / words.length >= 0.6;
305
+ }
306
+ /**
307
+ * Technology named as what something is built with, not as the subject: "pages built with React",
308
+ * "written in Python or TypeScript", "Electron apps", "a TypeScript loader". These are written in
309
+ * lower case before the written-as-name test, so a capital there shows nothing.
310
+ */
311
+ const USED_WITH = /\b(?:built|written|developed|made|coded|implemented|based|powered|programmed|created)(?: (?:with|in|on|using|by))? \p{L}[\p{L}.+#-]*(?:(?:,| or| and|, and|, or) \p{L}[\p{L}.+#-]*)*/gu;
312
+ const USED_AS = /\p{Lu}[\p{L}.+#-]* (?:apps?|applications?|loaders?|sites?|websites?|pages?|projects?|developers?|stealers?|malware|scripts?|payloads?|backdoors?|droppers?)(?![\p{L}\p{N}])/gu;
313
+ function technologyInLowerCase(line) {
314
+ return line.replace(USED_WITH, (span) => span.toLowerCase()).replace(USED_AS, (span) => span.toLowerCase());
315
+ }
316
+ /**
317
+ * A test for English words written as names. Any of them counts when it has a capital straight
318
+ * after a word that has none and is not followed by another capitalised word ("a flaw in Express
319
+ * lets", "the Scheduler package"); "group Salt Typhoon" and "Windows Task Scheduler" are other
320
+ * names. A well-known library name also counts with a following capital ("in React Server
321
+ * Components"), when it opens a sentence that goes on in lower case ("Rails releases patches"),
322
+ * and as the second word of a sentence ("Critical Rails flaw", "The React team").
323
+ * Lines in title case are not considered.
324
+ */
325
+ /** The words after which the second word of a sentence may be a library's name. */
326
+ const SECOND_WORD_AFTER = '(?:The|A|An|This|That|These|Those|Its|New|Critical|Severe|Serious|Major|High|Latest|Recent|Another|' +
327
+ 'Popular|Malicious|Vulnerable|Unpatched|Patched|Outdated|Older|Several|Multiple|Many|Two|Three)';
328
+ /** A word saying what kind of software something is ("test" runner, "web" server, "HTTP" server). */
329
+ const SOFTWARE_KIND = '(?:web|Web|test|testing|http|HTTP|template|templating|build|javascript|JavaScript|js|JS|typescript|' +
330
+ 'TypeScript|python|Python|ruby|Ruby|rust|Rust|node(?:\\.js)?|Node(?:\\.js)?|css|CSS|orm|ORM|logging|' +
331
+ 'validation|parsing|parser|image|ui|UI|frontend|backend|server-side|open-source|npm|PyPI|pypi)';
332
+ /**
333
+ * Words that name a software library or its parts and count after a library named second in a
334
+ * sentence on their own: no company or malware is described with them.
335
+ */
336
+ const SOFTWARE_NOUN = '(?:team|core team|maintainers?|codebase|repository|ecosystem|librar(?:y|ies)|framework|packages?|modules?|plugins?|' +
337
+ 'extensions?|middleware|router|dependenc(?:y|ies)|gems?|crates?|runtime|runner|installer|' +
338
+ 'cli|CLI|sdk|SDK|api|API|versions?|releases?|patch(?:es)?|fix(?:es)?|advisor(?:y|ies))';
339
+ /**
340
+ * Words that also follow a company, product or malware name ("The Puma team", "The Nest patch",
341
+ * "The Cypress advisory", "The Mongoose components"): they count only in a sentence that itself
342
+ * speaks of a library (LIBRARY_CUE).
343
+ */
344
+ const SHARED_NOUN = '(?:devs|community|components?|issues?|' +
345
+ 'security (?:team|advisor(?:y|ies)|releases?|updates?|fix(?:es)?|patch(?:es)?))';
346
+ /**
347
+ * After a cue word, a hyphen keeps it a cue only before one of these ("plugin-based", "npm-hosted",
348
+ * "package-lock.json"); any other ("npm-themed lure", "package-delivery scam") makes it something
349
+ * else.
350
+ */
351
+ const NOT_LIBRARY_SUFFIX = '[-‑–](?!(?:based|hosted|published|level|lock|managed|installed|pinned|wide|scoped|only|registry|manager|audit|signing|specific|agnostic|federation|account|check|compatible|licensed|maintained)(?![\\p{L}]))';
352
+ /**
353
+ * Not a software version: one that follows "CVSS" ("CVSS v3.1", "CVSS: v3.1", "CVSS (v3.1)",
354
+ * "CVSS version 3.1", "CVSS-version 3.1", the second of "CVSS v3.1/v4.0"), or one that "CVSS" follows
355
+ * closely: only a CVSS version number (2.0, 2.1, 3.0, 3.1, 4.0, 4.1) is refused there ("9.8 (v3.1) on
356
+ * the CVSS scale"), so a library version with its rating ("fixed in v5.0.1 (CVSS 9.8)") still counts.
357
+ */
358
+ const NOT_CVSS = '(?<!cvss[:\\s(-]*(?:version[\\s-]*)?(?:v?\\d+(?:\\.\\d+)*\\s*/\\s*)?)';
359
+ const NOT_BEFORE_CVSS = '(?!(?:[^.]|\\.\\d){0,24}cvss)';
360
+ /** A CVSS version number closely after "CVSS" in the same sentence ("a CVSS score of 8.1 (version 3.1)"). */
361
+ const NOT_AFTER_CVSS = '(?<!cvss[^!?]{0,40})';
362
+ /** A version written as one, not followed by another digit group. */
363
+ const WRITTEN_VERSION = `(?:^|[^\\p{L}\\p{N}.])${NOT_CVSS}v(?:\\d+(?:\\.\\d+)+(?!\\.?\\d)(?<!v[234]\\.[01])|[234]\\.[01](?!\\.?\\d)${NOT_BEFORE_CVSS}${NOT_AFTER_CVSS})` +
364
+ `|(?:^|[^\\p{L}\\p{N}.])${NOT_CVSS}version (?:\\d+(?:\\.\\d+)+(?!\\.?\\d)(?<!version [234]\\.[01])|[234]\\.[01](?!\\.?\\d)${NOT_BEFORE_CVSS}${NOT_AFTER_CVSS})` +
365
+ '|@\\d+(?:\\.\\d+)+(?!\\.?\\d)' +
366
+ // Three or more parts, but not an IP address and not a date with a four-digit year.
367
+ '|(?:^|[^\\p{L}\\p{N}.])(?!\\d{1,2}\\.\\d{1,2}\\.(?:19|20)\\d\\d(?!\\.?\\d))(?!(?:19|20)\\d\\d\\.\\d{1,2}\\.\\d{1,2}(?!\\.?\\d))\\d+\\.\\d+\\.\\d+(?!\\.?\\d)';
368
+ /**
369
+ * A sign that a sentence is about a software library: a registry or an install command, a kind of
370
+ * package, or a version written as one ("v1.2", "version 1.2", "@1.2", "1.2.3"). Not a bare decimal
371
+ * ("a CVSS score of 9.8", "1.5 million"), a CVSS version ("CVSS v3.1"), an IP address or a date
372
+ * ("15.11.2026", "2026.11.15"). A date with a two-digit year ("15.11.26") cannot be told from
373
+ * a version and counts.
374
+ */
375
+ const LIBRARY_CUE = new RegExp('(?:^|[^\\p{L}])(?:npm|pypi|rubygems|gems?|crates?|crates\\.io|maven|nuget|(?:pip|gem|cargo|npm) install|' +
376
+ 'packages?|librar(?:y|ies)|frameworks?|modules?|plugins?|open[- ]source|maintainers?)(?![\\p{L}]|' +
377
+ NOT_LIBRARY_SUFFIX +
378
+ ')|' +
379
+ WRITTEN_VERSION, 'iu');
380
+ /**
381
+ * A strong sign, which also counts from the next sentence: a registry or an install command. Not a
382
+ * version there, which app, firmware and device news write the same way ("Firmware 4.21.3 fixes
383
+ * it."), and not "package", which a courier story uses too.
384
+ */
385
+ const STRONG_LIBRARY_CUE = new RegExp('(?:^|[^\\p{L}])(?:npm|pypi|rubygems|crates\\.io|maven|nuget|(?:pip|gem|cargo|npm) install)(?![\\p{L}]|' +
386
+ NOT_LIBRARY_SUFFIX +
387
+ ')', 'iu');
388
+ /**
389
+ * Where a sentence ends: after ".", "!" or "?" and before a capital letter or a digit, but not after
390
+ * a common abbreviation ("e.g.", "i.e.", "incl.", "vs.") or a single lower-case letter. After "etc." and
391
+ * initials ("the U.S. Package scams") it does end.
392
+ */
393
+ const SENTENCE_END = /(?<=[.!?])(?<!(?:^|[^\p{L}])(?:e\.g|i\.e|incl|vs|approx|cf|al|ca|no|nr|ver|v|\p{Ll})\.)\s+(?=[\p{Lu}\p{N}])/u;
394
+ /** Words that name a flaw. */
395
+ const FLAW_NOUN = '(?:flaws?|bugs?|vulnerabilit(?:y|ies)|escapes?|bypass(?:es)?|injections?)';
396
+ /** Words for the kind of a flaw that may come before it ("remote code execution flaw"). */
397
+ const FLAW_KIND = '(?:remote|code|command|execution|sandbox|deserialization|sql|path|traversal|prototype|pollution|' +
398
+ 'denial-of-service|denial of service|request|smuggling|cross-site|scripting|xss|XSS|ssrf|SSRF|csrf|CSRF|' +
399
+ 'xxe|XXE|SQL|RCE|rce|DoS|dos|ReDoS|TLS|SSL|authentication|auth|' +
400
+ 'authorization|privilege|escalation|buffer|overflow|memory|corruption|use-after-free|arbitrary|file|' +
401
+ 'upload|read|write|information|disclosure|open|redirect|header|cache|poisoning|type|confusion|' +
402
+ 'integer|timing|template|server-side|critical|severe|zero-day|regex|redos|security|input|validation|' +
403
+ 'race|condition|session|cookie|token|signature|verification|certificate|tls|ssl)';
404
+ /**
405
+ * What may follow a library named second in a sentence for it to be taken for the library: a word
406
+ * about software, possibly after one saying what kind ("The Mocha test runner"), a server or an app
407
+ * only after such a word ("The Puma web server"), or a flaw after up to three words saying what kind
408
+ * of flaw ("Critical Struts remote code execution flaw"). Words that also follow a brand or a malware
409
+ * name ("users", "code", "servers", "breach", "ransomware") are left out.
410
+ */
411
+ const SOFTWARE_WORD = `(?:${SOFTWARE_KIND} (?:servers?|apps?|applications?|clients?)|(?:${SOFTWARE_KIND} )?${SOFTWARE_NOUN}|` +
412
+ `(?:${FLAW_KIND} ){0,3}${FLAW_NOUN})`;
413
+ const SHARED_WORD = `(?:${SOFTWARE_KIND} )?${SHARED_NOUN}`;
414
+ function writtenAsName(names) {
415
+ const single = names.map((name) => name.trim()).filter((name) => /^\p{L}{3,}$/u.test(name));
416
+ const form = capitalised;
417
+ const end = '(?![\\p{L}\\p{N}_@/\\-])';
418
+ const after = "(?<=(?:^|[^\\p{L}\\p{N}])\\p{Ll}[\\p{L}\\p{N}'’-]*[,:]? )";
419
+ const patterns = [];
420
+ /** Patterns that count only in a text that also speaks of a library. */
421
+ const cued = [];
422
+ const add = (group, build, into = patterns) => {
423
+ for (let offset = 0; offset < group.length; offset += 400)
424
+ into.push(new RegExp(build(`(?:${group
425
+ .slice(offset, offset + 400)
426
+ .map(form)
427
+ .join('|')})`), 'u'));
428
+ };
429
+ add(single.filter((name) => !properName(name)), (alternatives) => `${after}${alternatives}${end}(?! \\p{Lu})`);
430
+ add(single.filter((name) => properName(name)), (alternatives) => `${after}${alternatives}${end}` +
431
+ // Opening a sentence that goes on in lower case: "Rails releases patches".
432
+ `|(?<=^|[.!?]\\s+)${alternatives}(?:['’]s)?${end}(?= \\p{Ll})` +
433
+ // Second word of a sentence, after an article or a word of severity or novelty and before a
434
+ // word about software: "Critical Rails flaw", "The React team", "New Express vulnerability".
435
+ // Not after any capitalised word ("American Express customers") nor before any word ("The
436
+ // Puma sportswear brand", "The Thor ransomware", "The Express reported").
437
+ `|(?<=(?:^|[.!?]\\s+)${SECOND_WORD_AFTER} )${alternatives}(?:['’]s)?${end}(?= ${SOFTWARE_WORD}(?![\\p{L}\\p{N}]))`);
438
+ add(single.filter((name) => properName(name)), (alternatives) => `(?<=(?:^|[.!?]\\s+)${SECOND_WORD_AFTER} )${alternatives}(?:['’]s)?${end}(?= ${SHARED_WORD}(?![\\p{L}\\p{N}]))`, cued);
439
+ if (!patterns.length)
440
+ return () => false;
441
+ return (text) => text.split('\n').some((line) => {
442
+ if (titleCase(line))
443
+ return false;
444
+ const read = technologyInLowerCase(line);
445
+ if (patterns.some((pattern) => pattern.test(read)))
446
+ return true;
447
+ // The shared words count only in a sentence that itself speaks of a library, or whose next
448
+ // sentence names a registry or an install command ("… disclosed a flaw. Run pip install -U
449
+ // celery."); a version there does not count.
450
+ if (!cued.length)
451
+ return false;
452
+ const sentences = read.split(SENTENCE_END);
453
+ return sentences.some((sentence, index) => cued.some((pattern) => pattern.test(sentence)) &&
454
+ (LIBRARY_CUE.test(sentence) || STRONG_LIBRARY_CUE.test(sentences[index + 1] ?? '')));
455
+ });
456
+ }
457
+ const matchers = new WeakMap();
458
+ /**
459
+ * A cheap description of what the matcher was built from. It changes when a system, component,
460
+ * product or keyword is added, removed or replaced, so a caller that edits the same inventory object
461
+ * between scans does not keep matching against the old names.
462
+ */
463
+ function shape(inventory) {
464
+ return inventory.systems
465
+ .map((system) => [
466
+ system.id,
467
+ system.components.length,
468
+ system.components.at(-1)?.name ?? '',
469
+ (system.products ?? []).map((product) => `${product.name}:${product.keywords.join(',')}`).join(';'),
470
+ (system.keywords ?? []).join(','),
471
+ ].join('|'))
472
+ .join('\n');
473
+ }
474
+ function anyOf(terms, suffix = '') {
475
+ const unique = [...new Set([...terms].map((term) => term.trim()).filter((term) => term.length >= 3))];
476
+ // One alternation per chunk keeps each expression small while testing every name in one pass.
477
+ const patterns = [];
478
+ for (let offset = 0; offset < unique.length; offset += 400)
479
+ patterns.push(bounded(`(?:${unique
480
+ .slice(offset, offset + 400)
481
+ .map(escape)
482
+ .join('|')})${suffix}`));
483
+ return (text) => patterns.some((pattern) => pattern.test(text));
484
+ }
485
+ /**
486
+ * Built once per loaded inventory; a scan compares thousands of records against the same names.
487
+ * Adding or removing entries on the same object rebuilds it. Renaming a component in place (other
488
+ * than the last one of a system) is not noticed: pass a new inventory object after such an edit.
489
+ */
490
+ export function inventoryMatcher(inventory) {
491
+ const current = shape(inventory);
492
+ const cached = matchers.get(inventory);
493
+ if (cached && cached.shape === current)
494
+ return cached.matcher;
495
+ const packages = new Set();
496
+ const declared = [];
497
+ /** Each package name once per ecosystem, with the words it is made of. */
498
+ const names = new Map();
499
+ for (const system of inventory.systems) {
500
+ for (const component of system.components) {
501
+ const key = packageKey(component);
502
+ if (key)
503
+ packages.add(key);
504
+ const name = component.name.trim();
505
+ const id = `${component.ecosystem}\n${name}`;
506
+ if (name.length >= 2 && !names.has(id)) {
507
+ // Maven coordinates are looked for by their artifact; `packageMentioned` tests both.
508
+ const artifact = mavenArtifact(component);
509
+ names.set(id, {
510
+ component: { ecosystem: component.ecosystem, name },
511
+ parts: (artifact ?? name).toLowerCase().match(/[a-z0-9]+/g) ?? [],
512
+ });
513
+ }
514
+ }
515
+ for (const product of system.products ?? [])
516
+ declared.push(product.name, ...product.keywords);
517
+ declared.push(...(system.keywords ?? []));
518
+ }
519
+ const candidates = [...names.values()];
520
+ const declaredTest = anyOf(declared);
521
+ const matcher = {
522
+ packages,
523
+ declared: declaredTest,
524
+ // The same rules as `packageMentioned`. A name can only be named where its words appear, so the
525
+ // words of the text are looked up first and only the names found there are tested: a long story
526
+ // compared with thousands of names costs one pass over the story.
527
+ packageNamed: (text) => {
528
+ const lower = text.toLowerCase();
529
+ const words = new Set(lower.match(/[a-z0-9]+/g) ?? []);
530
+ return candidates.some(({ component, parts }) => (parts.length
531
+ ? parts.every((part, index) => words.has(part) || (index === parts.length - 1 && words.has(`${part}js`)))
532
+ : lower.includes(component.name.toLowerCase())) && packageMentioned(text, component));
533
+ },
534
+ };
535
+ matchers.set(inventory, { shape: current, matcher });
536
+ return matcher;
537
+ }
package/dist/models.d.ts CHANGED
@@ -1,6 +1,19 @@
1
1
  import type { Assessment, AiAnalysis, Config, Evidence, HttpClient, System } from './types.js';
2
- export declare const PROMPT_VERSION = "security-watch-9";
3
- interface ModelState {
2
+ import type { Store } from './store.js';
3
+ export declare const PROMPT_VERSION = "security-watch-10";
4
+ interface Excerpt {
5
+ id: string;
6
+ text: string;
7
+ }
8
+ /** Whether an excerpt may be offered for citation: the quote contract counts 20 characters (code points). */
9
+ export declare function citable(text: string): boolean;
10
+ export declare function excerptsFor(evidence: Pick<Evidence, 'title' | 'description'>, index: number): Excerpt[];
11
+ /**
12
+ * What the analyzer keeps between calls: cached results and the daily budget. `Store` provides it.
13
+ * The three methods are worker internals and are absent from the published `Store` type, so the
14
+ * constructor names `Store` itself; this interface is for a caller that supplies its own state.
15
+ */
16
+ export interface ModelState {
4
17
  getMeta(key: string): string | undefined;
5
18
  setMeta(key: string, value: string): void;
6
19
  reserveBudget(day: string, maxRequests: number, maxTokens: number, maxUsd: number | undefined, tokens: number, usd: number | undefined): boolean;
@@ -8,12 +21,12 @@ interface ModelState {
8
21
  export declare function validateAnalysis(value: unknown, evidence: Evidence[]): AiAnalysis;
9
22
  export declare class ModelAnalyzer {
10
23
  private config;
11
- private store;
12
24
  private http;
13
25
  private now;
14
26
  private signal?;
15
27
  private env;
16
- constructor(config: Config, store: ModelState, http: HttpClient, now?: () => number, signal?: AbortSignal | undefined, env?: Readonly<Record<string, string | undefined>>);
28
+ constructor(config: Config, store: Store | ModelState, http: HttpClient, now?: () => number, signal?: AbortSignal | undefined, env?: Readonly<Record<string, string | undefined>>);
29
+ private readonly store;
17
30
  private call;
18
31
  analyze(assessment: Assessment, system: System, evidence: Evidence[]): Promise<Assessment>;
19
32
  }