@shieldaai/security-watch 1.2.0 → 1.3.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.
@@ -0,0 +1,297 @@
1
+ /**
2
+ * What an advisory publishes beyond its text that helps someone write a fix or a temporary runtime
3
+ * shield: typed links, the commits that fixed it, weakness (CWE) identifiers and public exploit code.
4
+ *
5
+ * These parsers never throw. A malformed link is dropped; it must never cost the advisory itself.
6
+ * The fields are kept out of the evidence content hash and the analysis basis (see `evidenceContent`),
7
+ * so an upgrade that starts reading them neither records new evidence revisions nor asks a model again,
8
+ * and they are never sent to a model.
9
+ */
10
+ export const MAX_REFERENCES = 40;
11
+ export const MAX_FIX_COMMITS = 20;
12
+ export const MAX_WEAKNESSES = 20;
13
+ const MAX_URL = 2_048;
14
+ /** Evidence without its fetch time and without the shield inputs: what revisions and analysis compare. */
15
+ export function evidenceContent(evidence) {
16
+ const { fetched_at: _fetched, references: _references, fix_commits: _commits, weaknesses: _weaknesses, exploit_sources: _exploits, ...content } = evidence;
17
+ return content;
18
+ }
19
+ function isRecord(value) {
20
+ return !!value && typeof value === 'object' && !Array.isArray(value);
21
+ }
22
+ /** Names that only resolve inside a network: never a public advisory link. */
23
+ const PRIVATE_NAME = /(?:^|\.)(?:localhost|localdomain|local|internal|intranet|lan|home|corp|private|test|invalid|example|arpa)$/i;
24
+ /** Names that resolve to the address written inside them (10.0.0.1.nip.io), or to this machine. */
25
+ const ADDRESS_NAME = /(?:^|[.-])(?:\d{1,3}[.-]){3}\d{1,3}(?:[.-]|$)|(?:^|\.)(?:nip\.io|sslip\.io|xip\.io|localtest\.me|lvh\.me)$/i;
26
+ /**
27
+ * An https URL to a public name, without credentials, of bounded length, or nothing. These links are
28
+ * handed to people and agents that may open them, so an address inside a network (an IP literal in any
29
+ * notation, a private name) is dropped, and so is a value with whitespace or control characters
30
+ * inside it, which a URL parser would silently remove, keeping a different address.
31
+ */
32
+ export function safeHttpsUrl(value) {
33
+ if (typeof value !== 'string' || !value || value.length > MAX_URL)
34
+ return undefined;
35
+ const text = value.trim();
36
+ if (/[\s\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(text))
37
+ return undefined;
38
+ let url;
39
+ try {
40
+ url = new URL(text);
41
+ }
42
+ catch {
43
+ return undefined;
44
+ }
45
+ // The parser normalises 0x7f.1, 2130706433 and [::1] to literal addresses; a trailing dot is dropped.
46
+ const host = url.hostname.replace(/\.$/, '');
47
+ if (url.protocol !== 'https:' ||
48
+ url.username ||
49
+ url.password ||
50
+ !host.includes('.') ||
51
+ host.startsWith('[') ||
52
+ /^[\d.]+$/.test(host) ||
53
+ PRIVATE_NAME.test(host) ||
54
+ ADDRESS_NAME.test(host))
55
+ return undefined;
56
+ url.hostname = host;
57
+ // A fragment points inside the same page: one link, not two.
58
+ url.hash = '';
59
+ return url.href.length > MAX_URL ? undefined : url.href;
60
+ }
61
+ /** At most this many entries of a source list are looked at; the rest cannot add anything kept. */
62
+ const MAX_SCANNED = 1_000;
63
+ /**
64
+ * Runs a parser and returns an empty list if it throws. The inputs are optional extras: a malformed
65
+ * or hostile value (a nesting or a list too deep or long for the runtime) must never cost the advisory.
66
+ */
67
+ function neverThrows(parse) {
68
+ return (...args) => {
69
+ try {
70
+ return parse(...args);
71
+ }
72
+ catch {
73
+ return [];
74
+ }
75
+ };
76
+ }
77
+ function firstItems(value) {
78
+ return Array.isArray(value) ? value.slice(0, MAX_SCANNED) : [];
79
+ }
80
+ /** Repositories of advisory databases: a change there records the problem, it does not fix it. */
81
+ const ADVISORY_DATABASES = /^\/(?:github\/advisory-database|pypa\/advisory-database|rustsec\/advisory-db|golang\/vulndb|nodejs\/security-wg|google\/osv\.dev|ossf\/malicious-packages|FriendsOfPHP\/security-advisories|rubysec\/ruby-advisory-db|CVEProject\/cvelist(?:V5)?)\//i;
82
+ /** A link that is a code change: a commit, a pull or merge request, a compare view or a patch file. */
83
+ export function codeChangeUrl(url) {
84
+ let parsed;
85
+ try {
86
+ parsed = new URL(url);
87
+ }
88
+ catch {
89
+ return false;
90
+ }
91
+ const path = parsed.pathname;
92
+ if (ADVISORY_DATABASES.test(path))
93
+ return false;
94
+ const query = parsed.search;
95
+ return (/\/commits?\/[0-9a-f]{7,64}\/?$/i.test(path) ||
96
+ /\/pull\/\d+(?:\/(?:commits|files)(?:\/[0-9a-f]{7,64})?)?\/?$/i.test(path) ||
97
+ /\/-\/merge_requests\/\d+(?:\/diffs)?\/?$/i.test(path) ||
98
+ // Bitbucket pull requests and commits.
99
+ /\/pull-requests\/\d+(?:\/(?:diff|commits))?\/?$/i.test(path) ||
100
+ // A compare of two releases or commits, not of two branches.
101
+ /\/compare\/[^/]*\d[^/]*\.\.\.?[^/]*\d[^/]*$/i.test(path) ||
102
+ /\.(?:patch|diff)$/i.test(path) ||
103
+ // googlesource (Android, Chromium): /+/<commit>.
104
+ /\/\+\/[0-9a-f]{7,64}(?:%5E!)?\/?$/i.test(path) ||
105
+ // Mercurial.
106
+ /\/rev\/[0-9a-f]{12,40}\/?$/i.test(path) ||
107
+ // cgit and gitweb, as used by kernel.org, sourceware and savannah, and kernel.org's short links.
108
+ (/\/commit\/?$/i.test(path) && /^[0-9a-f]{7,64}$/i.test(parsed.searchParams.get('id') ?? '')) ||
109
+ (/(?:^\?|;|&)a=commit(?:diff)?(?:;|&|$)/i.test(query) &&
110
+ /(?:^\?|;|&)h=[0-9a-f]{7,64}(?:;|&|$)/i.test(query)) ||
111
+ (parsed.hostname === 'git.kernel.org' && /^\/(?:stable|linus)\/c\/[0-9a-f]{7,64}\/?$/i.test(path)));
112
+ }
113
+ const OSV_TYPES = {
114
+ FIX: 'fix',
115
+ ADVISORY: 'advisory',
116
+ REPORT: 'report',
117
+ EVIDENCE: 'evidence',
118
+ PACKAGE: 'package',
119
+ ARTICLE: 'web',
120
+ WEB: 'web',
121
+ DISCUSSION: 'web',
122
+ DETECTION: 'detection',
123
+ INTRODUCED: 'introduced',
124
+ GIT: 'source',
125
+ };
126
+ /** The more specific of two kinds for the same link: a fix outranks a generic web page. */
127
+ const TYPE_RANK = {
128
+ fix: 0,
129
+ evidence: 1,
130
+ advisory: 2,
131
+ report: 3,
132
+ detection: 4,
133
+ introduced: 5,
134
+ package: 6,
135
+ source: 7,
136
+ web: 8,
137
+ };
138
+ function merged(references) {
139
+ const byUrl = new Map();
140
+ for (const reference of references) {
141
+ const known = byUrl.get(reference.url);
142
+ if (!known || TYPE_RANK[reference.type] < TYPE_RANK[known.type])
143
+ byUrl.set(reference.url, reference);
144
+ }
145
+ return [...byUrl.values()].sort((a, b) => TYPE_RANK[a.type] - TYPE_RANK[b.type]).slice(0, MAX_REFERENCES);
146
+ }
147
+ /**
148
+ * OSV `references`: typed. A code-change link typed only as a web page is a fix link; one the
149
+ * advisory types as evidence, a report or an advisory (a proof-of-concept commit, say) keeps its type.
150
+ */
151
+ export const osvReferences = neverThrows((raw) => {
152
+ const references = [];
153
+ for (const item of firstItems(raw)) {
154
+ if (!isRecord(item))
155
+ continue;
156
+ const url = safeHttpsUrl(item.url);
157
+ if (!url)
158
+ continue;
159
+ const given = typeof item.type === 'string' ? OSV_TYPES[item.type.toUpperCase()] : undefined;
160
+ const code = codeChangeUrl(url);
161
+ // A fix link is a code change. A page typed FIX that is not one (a vendor bulletin, release notes,
162
+ // a change to an advisory database) describes the fix; it is kept as an advisory.
163
+ const type = given === 'fix'
164
+ ? code
165
+ ? 'fix'
166
+ : 'advisory'
167
+ : given === undefined || given === 'web'
168
+ ? code
169
+ ? 'fix'
170
+ : 'web'
171
+ : given;
172
+ references.push({ type, url });
173
+ }
174
+ return merged(references);
175
+ });
176
+ /** GitHub's `references`: plain URLs. Code changes are fix links, advisory databases are advisories. */
177
+ export const githubReferences = neverThrows((raw) => {
178
+ const references = [];
179
+ for (const item of firstItems(raw)) {
180
+ const url = safeHttpsUrl(isRecord(item) ? item.url : item);
181
+ if (!url)
182
+ continue;
183
+ const host = new URL(url).hostname;
184
+ const type = codeChangeUrl(url)
185
+ ? 'fix'
186
+ : host === 'nvd.nist.gov' || /\/advisories\/GHSA-/i.test(url) || /\/security\/advisories\//i.test(url)
187
+ ? 'advisory'
188
+ : 'web';
189
+ references.push({ type, url });
190
+ }
191
+ return merged(references);
192
+ });
193
+ /** The commits OSV records as fixing the problem: `GIT` ranges with a repository and `fixed` events. */
194
+ export const osvFixCommits = neverThrows((affected) => {
195
+ const commits = new Map();
196
+ for (const entry of firstItems(affected)) {
197
+ if (!isRecord(entry))
198
+ continue;
199
+ for (const range of firstItems(entry.ranges)) {
200
+ if (!isRecord(range) || range.type !== 'GIT')
201
+ continue;
202
+ const repo = safeHttpsUrl(range.repo);
203
+ if (!repo)
204
+ continue;
205
+ for (const event of firstItems(range.events)) {
206
+ if (!isRecord(event) || typeof event.fixed !== 'string')
207
+ continue;
208
+ const commit = event.fixed.trim().toLowerCase();
209
+ if (!/^[0-9a-f]{7,64}$/.test(commit))
210
+ continue;
211
+ commits.set(`${repo} ${commit}`, { repo, commit });
212
+ if (commits.size >= MAX_FIX_COMMITS)
213
+ return [...commits.values()];
214
+ }
215
+ }
216
+ }
217
+ return [...commits.values()];
218
+ });
219
+ function weakness(value) {
220
+ if (typeof value !== 'string' || value.length > 20)
221
+ return undefined;
222
+ const match = value.trim().match(/^CWE-(\d{1,5})$/i);
223
+ return match ? `CWE-${Number(match[1])}` : undefined;
224
+ }
225
+ function weaknessList(values) {
226
+ const found = new Set();
227
+ for (const value of values) {
228
+ const item = weakness(value);
229
+ if (item)
230
+ found.add(item);
231
+ if (found.size >= MAX_WEAKNESSES)
232
+ break;
233
+ }
234
+ return [...found];
235
+ }
236
+ /** OSV: `database_specific.cwe_ids`, as GitHub-reviewed records carry, on the record or an entry. */
237
+ export const osvWeaknesses = neverThrows((data) => {
238
+ const values = [];
239
+ const collect = (specific) => {
240
+ if (isRecord(specific))
241
+ for (const value of firstItems(specific.cwe_ids))
242
+ values.push(value);
243
+ };
244
+ collect(data.database_specific);
245
+ for (const entry of firstItems(data.affected))
246
+ if (isRecord(entry))
247
+ collect(entry.database_specific);
248
+ return weaknessList(values);
249
+ });
250
+ /** GitHub: `cwes: [{cwe_id, name}]`. */
251
+ export const githubWeaknesses = neverThrows((raw) => weaknessList(firstItems(raw).map((item) => (isRecord(item) ? item.cwe_id : item))));
252
+ const CVE_NOW_EXPLOITS = [
253
+ ['exploitDb', 'exploit-db'],
254
+ ['metasploit', 'metasploit'],
255
+ ['nuclei', 'nuclei'],
256
+ ['githubPoc', 'github-poc'],
257
+ ];
258
+ const PLACEHOLDER = /^(?:false|no|none|null|n\/a|na|0|-|unknown)$/i;
259
+ /**
260
+ * Whether a cve.now entry names an exploit: a non-empty list (`{"ids": [...]}`, `{"modules": [...]}`),
261
+ * a link or name, or a positive count. A flag or a date beside an empty list (`{"ids": [], "checked":
262
+ * true}`) names nothing, and neither do placeholders such as "none". cve.now nests two levels; deeper
263
+ * values are not looked at.
264
+ */
265
+ function present(value, depth = 0) {
266
+ if (typeof value === 'string')
267
+ return value.trim() !== '' && !PLACEHOLDER.test(value.trim());
268
+ if (typeof value === 'number')
269
+ return Number.isFinite(value) && value > 0;
270
+ if (value === true)
271
+ return depth === 0;
272
+ if (depth >= 3)
273
+ return false;
274
+ if (Array.isArray(value))
275
+ return firstItems(value).some((item) => present(item, depth + 1) || isRecord(item));
276
+ if (isRecord(value))
277
+ return Object.values(value).some((item) => Array.isArray(item) || typeof item === 'number' ? present(item, depth + 1) : false);
278
+ return false;
279
+ }
280
+ /**
281
+ * cve.now's public exploit entries: Exploit-DB, Metasploit, Nuclei and GitHub proof-of-concept code.
282
+ * Published code, not exploitation in the wild; that is `exploited` (the KEV catalog).
283
+ */
284
+ export const cveNowExploitSources = neverThrows((exploitation) => {
285
+ if (!isRecord(exploitation))
286
+ return [];
287
+ return CVE_NOW_EXPLOITS.filter(([key]) => present(exploitation[key])).map(([, label]) => label);
288
+ });
289
+ /** The shield inputs to spread into an Evidence record; empty lists are left out. */
290
+ export function shieldInputs(parts) {
291
+ return {
292
+ ...(parts.references?.length ? { references: parts.references } : {}),
293
+ ...(parts.fix_commits?.length ? { fix_commits: parts.fix_commits } : {}),
294
+ ...(parts.weaknesses?.length ? { weaknesses: parts.weaknesses } : {}),
295
+ ...(parts.exploit_sources?.length ? { exploit_sources: parts.exploit_sources } : {}),
296
+ };
297
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Copies the SBOMs of Shirudo's images from its SBOM store (`<image_id>/<image_version>/<root>/
3
+ * sbom.cdx.json`, a `file://` store) into Security Watch's SBOM folder, one file per image.
4
+ *
5
+ * The system ID is the image ID, so it stays the same across upgrades and a finding is not reported
6
+ * again for each new version. With a `node_vulns` export, the versions machines run are read; when
7
+ * several run (a rolling upgrade, a canary), their SBOMs are merged so the old version stays watched
8
+ * until it is gone. Without one, the newest version is taken.
9
+ *
10
+ * Only files this command wrote are replaced or removed; it marks them with a property. Nothing is
11
+ * written unless `apply` is set.
12
+ */
13
+ export declare const WRITTEN_BY = "shirudo-sboms";
14
+ export interface ShirudoSyncOptions {
15
+ /** The store's directory (a `file://` store; sync an `s3://` store to a directory first). */
16
+ store: string;
17
+ /** The SBOM folder that the inventory's `sbom_directory` names. */
18
+ output: string;
19
+ /** A JSON Lines export of `shirudo.node_vulns` with `image_id`, `image_version` and `node_id`. */
20
+ exposure?: string;
21
+ apply?: boolean;
22
+ now?: number;
23
+ /** System IDs the inventory describes by hand: an image with one of these IDs is not written. */
24
+ reserved?: readonly string[];
25
+ /** Allow a run to remove more than half of the images it watches. */
26
+ allowRemovals?: boolean;
27
+ }
28
+ export interface ShirudoSyncImage {
29
+ image_id: string;
30
+ file: string;
31
+ /** The versions in the SBOM, with the hosts running each when an export was given. */
32
+ versions: {
33
+ version: string;
34
+ hosts?: number;
35
+ }[];
36
+ action: 'write' | 'unchanged';
37
+ }
38
+ export interface ShirudoSyncPlan {
39
+ store: string;
40
+ output: string;
41
+ applied: boolean;
42
+ /** Whether the versions came from an export of the machines (`running`) or the newest in the store. */
43
+ selection: 'running' | 'newest';
44
+ images: ShirudoSyncImage[];
45
+ /** Files this command wrote earlier for images that are no longer selected. */
46
+ remove: string[];
47
+ /**
48
+ * What could not be done, in plain words. An image with a problem is left as it is: its earlier
49
+ * file, if any, is kept, never removed.
50
+ */
51
+ problems: string[];
52
+ }
53
+ /** Natural order: 2026.11.10 after 2026.11.9, 1.10 after 1.9; text parts compare as text. */
54
+ export declare function compareVersions(a: string, b: string): number;
55
+ type Json = Record<string, unknown>;
56
+ /**
57
+ * One document from the SBOMs of the running versions. Components with the same package URL are kept
58
+ * once; references are prefixed per version; dependency entries are kept where both ends survive.
59
+ */
60
+ export declare function mergeCycloneDx(documents: Json[]): Json;
61
+ export declare function syncShirudoSboms(options: ShirudoSyncOptions): ShirudoSyncPlan;
62
+ export {};