@shieldaai/security-watch 0.0.0-stage → 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.
- package/CHANGELOG.md +170 -0
- package/CONTRIBUTING.md +92 -0
- package/LICENSE +202 -0
- package/README.md +394 -2
- package/SECURITY.md +62 -0
- package/dist/assessment.d.ts +16 -0
- package/dist/assessment.js +569 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +1105 -0
- package/dist/config.d.ts +302 -0
- package/dist/config.js +381 -0
- package/dist/coverage.d.ts +4 -0
- package/dist/coverage.js +11 -0
- package/dist/cve-now.d.ts +35 -0
- package/dist/cve-now.js +1002 -0
- package/dist/cvss4.d.ts +3 -0
- package/dist/cvss4.js +39 -0
- package/dist/delivery.d.ts +58 -0
- package/dist/delivery.js +687 -0
- package/dist/ecosystems.d.ts +48 -0
- package/dist/ecosystems.js +332 -0
- package/dist/engine.d.ts +80 -0
- package/dist/engine.js +388 -0
- package/dist/everyday-words.d.ts +11 -0
- package/dist/everyday-words.js +256 -0
- package/dist/health.d.ts +24 -0
- package/dist/health.js +122 -0
- package/dist/heartbeat.d.ts +13 -0
- package/dist/heartbeat.js +74 -0
- package/dist/http.d.ts +15 -0
- package/dist/http.js +280 -0
- package/dist/index.d.ts +36 -0
- package/dist/index.js +23 -0
- package/dist/inventory-evidence.d.ts +10 -0
- package/dist/inventory-evidence.js +206 -0
- package/dist/inventory.d.ts +276 -0
- package/dist/inventory.js +336 -0
- package/dist/lock.d.ts +3 -0
- package/dist/lock.js +112 -0
- package/dist/maintenance.d.ts +48 -0
- package/dist/maintenance.js +295 -0
- package/dist/matching.d.ts +29 -0
- package/dist/matching.js +537 -0
- package/dist/models.d.ts +33 -0
- package/dist/models.js +932 -0
- package/dist/operations.d.ts +17 -0
- package/dist/operations.js +117 -0
- package/dist/pilot-cases.d.ts +171 -0
- package/dist/pilot-cases.js +330 -0
- package/dist/pilot-input.d.ts +16 -0
- package/dist/pilot-input.js +125 -0
- package/dist/pilot-recall.d.ts +166 -0
- package/dist/pilot-recall.js +231 -0
- package/dist/pilot-report.d.ts +113 -0
- package/dist/pilot-report.js +279 -0
- package/dist/pilot-responses.d.ts +111 -0
- package/dist/pilot-responses.js +159 -0
- package/dist/providers.d.ts +209 -0
- package/dist/providers.js +459 -0
- package/dist/python-version.d.ts +3 -0
- package/dist/python-version.js +30 -0
- package/dist/rehearsal.d.ts +440 -0
- package/dist/rehearsal.js +372 -0
- package/dist/sbom.d.ts +13 -0
- package/dist/sbom.js +193 -0
- package/dist/setup.d.ts +113 -0
- package/dist/setup.js +100 -0
- package/dist/source-error.d.ts +38 -0
- package/dist/source-error.js +71 -0
- package/dist/sources.d.ts +3 -0
- package/dist/sources.js +1725 -0
- package/dist/store.d.ts +96 -0
- package/dist/store.js +953 -0
- package/dist/types.d.ts +404 -0
- package/dist/types.js +1 -0
- package/dist/util.d.ts +29 -0
- package/dist/util.js +94 -0
- package/dist/vendor/cvss4-reference.d.ts +2 -0
- package/dist/vendor/cvss4-reference.js +789 -0
- package/dist/vendor-sources.d.ts +24 -0
- package/dist/vendor-sources.js +56 -0
- package/dist/word-filter.d.ts +3 -0
- package/dist/word-filter.js +3291 -0
- package/docs/alert-outcome-evaluation.md +150 -0
- package/docs/compatibility.md +35 -0
- package/docs/configuration.md +666 -0
- package/docs/cvss-v4-support.md +41 -0
- package/docs/offline-advisory-preview.md +114 -0
- package/docs/offline-rehearsal.md +44 -0
- package/docs/pilot-cases.md +58 -0
- package/docs/pilot-recall.md +124 -0
- package/docs/pilot-report.md +52 -0
- package/docs/validation/alert-outcome-evaluation-2026-11-05.json +2935 -0
- package/docs/validation/cvss-v4-reference-parity-2026-11-05.json +93 -0
- package/docs/validation/rehearsal-accepted-2026-11-05.json +175 -0
- package/docs/validation/rehearsal-unknown-2026-11-05.json +175 -0
- package/docs/vendor/cvss-v4-LICENSE.txt +22 -0
- package/docs/vendor/cvss-v4-provenance.json +38 -0
- package/examples/advisories.json +17 -0
- package/examples/agent-advisories-2026.json +145 -0
- package/examples/agent-advisory-cases-2026.json +397 -0
- package/examples/common-systems.yaml +243 -0
- package/examples/libraries.example.txt +18 -0
- package/examples/libraries.example.yaml +40 -0
- package/examples/library-watch.example.yaml +27 -0
- package/examples/offline-advisory-preview.mjs +42 -0
- package/examples/rehearsal.json +75 -0
- package/examples/security-watch.example.yaml +86 -0
- package/examples/systems.example.yaml +35 -0
- package/package.json +85 -4
package/dist/engine.js
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { cvssV4BaseScore } from './cvss4.js';
|
|
4
|
+
import { assess, decide } from './assessment.js';
|
|
5
|
+
import { collectSources } from './sources.js';
|
|
6
|
+
import { attachLocation, attachRemediation, compareInventories } from './inventory-evidence.js';
|
|
7
|
+
import { ModelAnalyzer, PROMPT_VERSION } from './models.js';
|
|
8
|
+
import { Store } from './store.js';
|
|
9
|
+
import { safeHttp } from './http.js';
|
|
10
|
+
import { missingCredentials } from './config.js';
|
|
11
|
+
import { canonicalHash, hash, severityRank, timestamp } from './util.js';
|
|
12
|
+
export const evidenceSchema = z
|
|
13
|
+
.object({
|
|
14
|
+
id: z.string().min(1),
|
|
15
|
+
source: z.string().min(1),
|
|
16
|
+
kind: z.enum(['advisory', 'news', 'kev', 'health']),
|
|
17
|
+
title: z.string(),
|
|
18
|
+
url: z.string(),
|
|
19
|
+
description: z.string(),
|
|
20
|
+
aliases: z.array(z.string()),
|
|
21
|
+
severity: z.enum(['unknown', 'low', 'medium', 'high', 'critical']),
|
|
22
|
+
cvss_v4: z
|
|
23
|
+
.strictObject({
|
|
24
|
+
base_scores: z
|
|
25
|
+
.array(z
|
|
26
|
+
.strictObject({
|
|
27
|
+
vector: z.string().max(1024),
|
|
28
|
+
base_vector: z.string().max(1024),
|
|
29
|
+
score: z.number().min(0).max(10),
|
|
30
|
+
context_removed: z.boolean(),
|
|
31
|
+
})
|
|
32
|
+
.refine((item) => {
|
|
33
|
+
const actual = cvssV4BaseScore(item.vector);
|
|
34
|
+
return (actual?.score === item.score &&
|
|
35
|
+
actual.base_vector === item.base_vector &&
|
|
36
|
+
actual.context_removed === item.context_removed);
|
|
37
|
+
}, 'Invalid CVSS v4 base projection'))
|
|
38
|
+
.max(32),
|
|
39
|
+
unsupported_vectors: z.number().int().min(0).max(32),
|
|
40
|
+
})
|
|
41
|
+
.refine((value) => value.base_scores.length + value.unsupported_vectors <= 32, 'CVSS v4 candidate limit exceeded')
|
|
42
|
+
.optional(),
|
|
43
|
+
modified_at: z.iso.datetime(),
|
|
44
|
+
fetched_at: z.iso.datetime(),
|
|
45
|
+
published_at: z.iso.datetime().optional(),
|
|
46
|
+
content_status: z.enum(['full', 'excerpt', 'unavailable']).optional(),
|
|
47
|
+
packages: z.array(z
|
|
48
|
+
.object({
|
|
49
|
+
ecosystem: z.string(),
|
|
50
|
+
name: z.string(),
|
|
51
|
+
range: z.string().optional(),
|
|
52
|
+
versions: z.array(z.string()).optional(),
|
|
53
|
+
matched_versions: z.array(z.string()).optional(),
|
|
54
|
+
fixed: z.string().optional(),
|
|
55
|
+
})
|
|
56
|
+
.strict()),
|
|
57
|
+
withdrawn: z.boolean().optional(),
|
|
58
|
+
exploited: z.boolean().optional(),
|
|
59
|
+
malware: z.boolean().optional(),
|
|
60
|
+
})
|
|
61
|
+
.strict();
|
|
62
|
+
export function readFixture(path) {
|
|
63
|
+
const stat = statSync(path);
|
|
64
|
+
if (!stat.isFile() || stat.size > 8_388_608)
|
|
65
|
+
throw new Error('Fixture must be a file of at most 8 MiB');
|
|
66
|
+
return z
|
|
67
|
+
.array(evidenceSchema)
|
|
68
|
+
.max(5000)
|
|
69
|
+
.parse(JSON.parse(readFileSync(path, 'utf8')));
|
|
70
|
+
}
|
|
71
|
+
export function healthFinding(source, message, now = Date.now()) {
|
|
72
|
+
return {
|
|
73
|
+
id: `health-${hash(source).slice(0, 20)}`,
|
|
74
|
+
event_id: `health:${source}`,
|
|
75
|
+
system_id: 'monitor',
|
|
76
|
+
category: 'health',
|
|
77
|
+
applicability: 'unknown',
|
|
78
|
+
source_severity: 'high',
|
|
79
|
+
priority: 'high',
|
|
80
|
+
title: `Monitoring needs attention: ${source}`,
|
|
81
|
+
summary: message,
|
|
82
|
+
reasons: ['Monitoring is incomplete; this is not a clean security result.'],
|
|
83
|
+
evidence_ids: [],
|
|
84
|
+
urls: [],
|
|
85
|
+
exploited: false,
|
|
86
|
+
updated_at: timestamp(now),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function checkCancellation(signal) {
|
|
90
|
+
if (signal?.aborted)
|
|
91
|
+
throw new DOMException('Scan canceled', 'AbortError');
|
|
92
|
+
}
|
|
93
|
+
function canRetainPriority(previous, current) {
|
|
94
|
+
return Boolean(previous &&
|
|
95
|
+
previous.active !== false &&
|
|
96
|
+
current.applicability !== 'not_affected' &&
|
|
97
|
+
!current.withdrawn &&
|
|
98
|
+
(previous.applicability === current.applicability ||
|
|
99
|
+
current.applicability === 'unknown' ||
|
|
100
|
+
current.applicability === 'conflicting') &&
|
|
101
|
+
severityRank[previous.priority] > severityRank[current.priority]);
|
|
102
|
+
}
|
|
103
|
+
function generalNews(assessment) {
|
|
104
|
+
return Boolean(assessment?.active !== false &&
|
|
105
|
+
assessment?.ai?.status === 'complete' &&
|
|
106
|
+
assessment.news_analysis?.classification === 'general_news' &&
|
|
107
|
+
assessment.news_analysis.impact === 'not_applicable');
|
|
108
|
+
}
|
|
109
|
+
// An exclusion rests on the version ranges of its own advisory records. While they were read
|
|
110
|
+
// within the last two poll intervals it holds, whatever else a source missed; after that the
|
|
111
|
+
// assessment treats them as stale evidence and the finding becomes `unknown` (assessment.ts).
|
|
112
|
+
/** When stored evidence was last collected: the start of the last scan, or its newest fetch time. */
|
|
113
|
+
function lastCollection(store, cached) {
|
|
114
|
+
try {
|
|
115
|
+
const started = Date.parse(JSON.parse(store.getMeta('last_scan') ?? '{}').started_at ?? '');
|
|
116
|
+
if (Number.isFinite(started))
|
|
117
|
+
return started;
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
/* An unreadable record falls back to the evidence itself. */
|
|
121
|
+
}
|
|
122
|
+
return cached.reduce((latest, item) => {
|
|
123
|
+
const fetched = Date.parse(item.fetched_at);
|
|
124
|
+
return Number.isFinite(fetched) && fetched > latest ? fetched : latest;
|
|
125
|
+
}, 0);
|
|
126
|
+
}
|
|
127
|
+
export async function runScan(options) {
|
|
128
|
+
const { config, inventory, store, signal } = options;
|
|
129
|
+
checkCancellation(signal);
|
|
130
|
+
const now = options.now ?? Date.now();
|
|
131
|
+
const transport = options.http ?? safeHttp;
|
|
132
|
+
const http = (url, request) => {
|
|
133
|
+
checkCancellation(signal);
|
|
134
|
+
return transport(url, { ...request, ...(signal ? { signal } : {}) });
|
|
135
|
+
};
|
|
136
|
+
const priorInventory = store.getMeta('inventory:baseline');
|
|
137
|
+
const drift = compareInventories(priorInventory ? JSON.parse(priorInventory) : undefined, inventory);
|
|
138
|
+
const previousById = new Map(store.findings().map((a) => [a.id, a]));
|
|
139
|
+
// Events of findings still reported keep their identifier when a record gains an alias.
|
|
140
|
+
const knownEvents = new Set([...previousById.values()]
|
|
141
|
+
.filter((finding) => finding.active !== false && finding.category !== 'health')
|
|
142
|
+
.map((finding) => finding.event_id));
|
|
143
|
+
const knownFindings = new Set([...previousById.values()].filter((finding) => finding.active !== false).map((finding) => finding.id));
|
|
144
|
+
const decisions = {};
|
|
145
|
+
let remediationEvidence = store.evidence();
|
|
146
|
+
const persist = (assessment) => {
|
|
147
|
+
assessment = attachLocation(attachRemediation(assessment, inventory, remediationEvidence, config, now), inventory);
|
|
148
|
+
const decision = decide(assessment, config);
|
|
149
|
+
decisions[assessment.id] = decision;
|
|
150
|
+
store.saveAssessment(assessment, decision, now, config.digest_interval_hours * 3_600_000, decision.review
|
|
151
|
+
? canonicalHash({
|
|
152
|
+
system: reviewSystemHashes.get(assessment.system_id),
|
|
153
|
+
models: config.models,
|
|
154
|
+
policy: config.policy.ai_dismissals ?? config.policy.review_before_news_suppression ?? 'review',
|
|
155
|
+
})
|
|
156
|
+
: undefined);
|
|
157
|
+
};
|
|
158
|
+
const retire = (assessment) => {
|
|
159
|
+
store.saveAssessment({
|
|
160
|
+
...assessment,
|
|
161
|
+
active: false,
|
|
162
|
+
updated_at: timestamp(now),
|
|
163
|
+
reasons: [
|
|
164
|
+
...assessment.reasons,
|
|
165
|
+
'No longer in the current assessment. This does not establish remediation.',
|
|
166
|
+
],
|
|
167
|
+
}, {
|
|
168
|
+
action: 'record',
|
|
169
|
+
channels: [],
|
|
170
|
+
reason: 'No current inventory/evidence match or monitoring issue recovered',
|
|
171
|
+
}, now);
|
|
172
|
+
};
|
|
173
|
+
// Notes and the owner say where to look. They are shown in notifications and never reach a model,
|
|
174
|
+
// so they are left out of everything that decides analysis reuse, reviews, revisions or alerts.
|
|
175
|
+
const context = (system) => {
|
|
176
|
+
const { updated_at: _updated, note: _note, owner: _owner, ...rest } = system;
|
|
177
|
+
return {
|
|
178
|
+
...rest,
|
|
179
|
+
components: system.components.map(({ note: _componentNote, ...component }) => component),
|
|
180
|
+
products: system.products.map(({ note: _productNote, ...product }) => product),
|
|
181
|
+
};
|
|
182
|
+
};
|
|
183
|
+
const systemHashes = new Map(inventory.systems.map((system) => [system.id, hash(context(system))]));
|
|
184
|
+
const reviewSystemHashes = new Map(inventory.systems.map((system) => [system.id, canonicalHash(context(system))]));
|
|
185
|
+
const basis = (finding, evidenceById, evidenceAsOf = now) => {
|
|
186
|
+
const { updated_at: _updated, ...assessment } = finding;
|
|
187
|
+
return hash({
|
|
188
|
+
assessment,
|
|
189
|
+
system: systemHashes.get(finding.system_id),
|
|
190
|
+
analysis: {
|
|
191
|
+
model: config.models.analysis,
|
|
192
|
+
verification: config.models.verification,
|
|
193
|
+
prompt: PROMPT_VERSION,
|
|
194
|
+
max_input_chars: config.models.max_input_chars,
|
|
195
|
+
},
|
|
196
|
+
evidence: finding.evidence_ids.map((id) => {
|
|
197
|
+
const item = evidenceById.get(id);
|
|
198
|
+
if (!item)
|
|
199
|
+
return null;
|
|
200
|
+
const { fetched_at: _fetched, ...content } = item;
|
|
201
|
+
const fetched = Date.parse(item.fetched_at);
|
|
202
|
+
return {
|
|
203
|
+
...content,
|
|
204
|
+
fresh: generalNews(previousById.get(finding.id)) ||
|
|
205
|
+
(Number.isFinite(fetched) &&
|
|
206
|
+
fetched <= now + 300_000 &&
|
|
207
|
+
evidenceAsOf - fetched <= Math.max(120_000, config.poll_interval_minutes * 120_000)),
|
|
208
|
+
};
|
|
209
|
+
}),
|
|
210
|
+
});
|
|
211
|
+
};
|
|
212
|
+
const interim = (finding, basisHash) => {
|
|
213
|
+
const previous = previousById.get(finding.id);
|
|
214
|
+
if (!config.models.enabled || !previous || previous.active === false)
|
|
215
|
+
return finding;
|
|
216
|
+
if (store.getMeta(`assessment-basis:${finding.id}`) === basisHash && previous.ai) {
|
|
217
|
+
// Retain unchanged analysis until reassessment; don't alternate record/digest/notify on every scan.
|
|
218
|
+
return {
|
|
219
|
+
...finding,
|
|
220
|
+
priority: previous.priority,
|
|
221
|
+
applicability: previous.applicability,
|
|
222
|
+
...(previous.relevance ? { relevance: previous.relevance } : {}),
|
|
223
|
+
...(previous.news_analysis ? { news_analysis: previous.news_analysis } : {}),
|
|
224
|
+
summary: previous.summary,
|
|
225
|
+
reasons: previous.reasons,
|
|
226
|
+
ai: previous.ai,
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
return canRetainPriority(previous, finding) ? { ...finding, priority: previous.priority } : finding;
|
|
230
|
+
};
|
|
231
|
+
const cached = store.evidence();
|
|
232
|
+
if (!options.fixture && previousById.size) {
|
|
233
|
+
// Apply known inventory changes before yielding to network I/O. The worker can deliver concurrently.
|
|
234
|
+
const cachedById = new Map(cached.map((e) => [e.id, e]));
|
|
235
|
+
// This pass applies inventory changes to evidence that is about to be refreshed. Judge the age
|
|
236
|
+
// of that evidence as of the last collection: time that passed while the monitor was stopped
|
|
237
|
+
// must not turn an exclusion into an urgent "unknown" that the refresh then takes back.
|
|
238
|
+
const collectedAt = Math.min(now, lastCollection(store, cached));
|
|
239
|
+
const current = assess(inventory, cached, config, now, collectedAt, knownEvents, knownFindings);
|
|
240
|
+
const ids = new Set(current.map((a) => a.id));
|
|
241
|
+
for (const finding of current)
|
|
242
|
+
if (previousById.has(finding.id))
|
|
243
|
+
persist(interim(finding, basis(finding, cachedById, collectedAt)));
|
|
244
|
+
for (const previous of previousById.values())
|
|
245
|
+
if (previous.category !== 'health' && previous.active !== false && !ids.has(previous.id))
|
|
246
|
+
retire(previous);
|
|
247
|
+
}
|
|
248
|
+
const result = options.fixture
|
|
249
|
+
? { evidence: options.fixture, errors: [], checkpoints: {}, coverage: [] }
|
|
250
|
+
: await collectSources(inventory, config, store.checkpoints(), http, now, cached, JSON.parse(store.getMeta('source:coverage') ?? '[]'));
|
|
251
|
+
checkCancellation(signal);
|
|
252
|
+
store.saveEvidence(result.evidence, result.checkpoints);
|
|
253
|
+
const evidence = store.evidence();
|
|
254
|
+
remediationEvidence = evidence;
|
|
255
|
+
const evidenceById = new Map(evidence.map((e) => [e.id, e]));
|
|
256
|
+
const findings = assess(inventory, evidence, config, now, now, knownEvents, knownFindings);
|
|
257
|
+
const bases = new Map(findings.map((a) => [a.id, basis(a, evidenceById)]));
|
|
258
|
+
const errors = [
|
|
259
|
+
...result.errors,
|
|
260
|
+
...(inventory.import_warnings ?? []).map((message) => ({ source: 'inventory:sbom', message })),
|
|
261
|
+
];
|
|
262
|
+
const notices = [...(inventory.name_notices ?? [])];
|
|
263
|
+
if (!options.fixture && missingCredentials(config).length)
|
|
264
|
+
errors.push({
|
|
265
|
+
source: 'credentials',
|
|
266
|
+
message: 'Configured model or delivery credentials are missing. Structured advisory matching continues; run doctor to see required variable names.',
|
|
267
|
+
});
|
|
268
|
+
if (!inventory.systems.length)
|
|
269
|
+
errors.push({
|
|
270
|
+
source: 'inventory',
|
|
271
|
+
message: 'Inventory is empty; add systems before enabling monitoring.',
|
|
272
|
+
});
|
|
273
|
+
if (!config.sources.cve_now &&
|
|
274
|
+
!config.sources.hacker_news &&
|
|
275
|
+
!config.sources.osv &&
|
|
276
|
+
!config.sources.github &&
|
|
277
|
+
!config.sources.kev &&
|
|
278
|
+
!config.sources.feeds.length &&
|
|
279
|
+
!config.sources.vendor_feeds?.length &&
|
|
280
|
+
!options.fixture)
|
|
281
|
+
errors.push({ source: 'sources', message: 'All sources are disabled.' });
|
|
282
|
+
if (!options.fixture &&
|
|
283
|
+
(config.sources.hacker_news || config.sources.feeds.length || config.sources.vendor_feeds?.length) &&
|
|
284
|
+
!config.models.enabled)
|
|
285
|
+
// Running without a model is a supported setup, not a fault: say what it means and carry on.
|
|
286
|
+
notices.push('AI is disabled. System news receives candidate matching only; enable an analysis model to distinguish vulnerability impact from general system coverage.');
|
|
287
|
+
for (const system of inventory.systems) {
|
|
288
|
+
const updated = Date.parse(system.updated_at);
|
|
289
|
+
if (!Number.isFinite(updated) ||
|
|
290
|
+
updated > now + 300_000 ||
|
|
291
|
+
now - updated > config.inventory_stale_days * 86_400_000)
|
|
292
|
+
errors.push({
|
|
293
|
+
source: `inventory:${system.id}`,
|
|
294
|
+
message: 'Inventory timestamp is stale or in the future; verify installed versions and deployment context.',
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
// Reconcile every finding before delivery, including exclusions, withdrawals and removals.
|
|
298
|
+
// Otherwise an old pending alert could be sent while unrelated AI analysis is running.
|
|
299
|
+
findings.forEach((finding) => persist(interim(finding, bases.get(finding.id))));
|
|
300
|
+
const currentIds = new Set(findings.map((a) => a.id));
|
|
301
|
+
for (const previous of store.findings())
|
|
302
|
+
if (previous.category !== 'health' && previous.active !== false && !currentIds.has(previous.id))
|
|
303
|
+
retire(previous);
|
|
304
|
+
if (options.onUrgent) {
|
|
305
|
+
try {
|
|
306
|
+
await options.onUrgent();
|
|
307
|
+
}
|
|
308
|
+
catch {
|
|
309
|
+
checkCancellation(signal);
|
|
310
|
+
errors.push({
|
|
311
|
+
source: 'delivery',
|
|
312
|
+
message: 'Urgent delivery did not complete. The scan continued; inspect deliveries before retrying.',
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
checkCancellation(signal);
|
|
317
|
+
const analyzer = new ModelAnalyzer(config, store, http, options.now === undefined ? Date.now : () => now, signal);
|
|
318
|
+
const analyzed = [];
|
|
319
|
+
for (const finding of findings.sort((a, b) => severityRank[b.priority] - severityRank[a.priority])) {
|
|
320
|
+
checkCancellation(signal);
|
|
321
|
+
const system = inventory.systems.find((s) => s.id === finding.system_id);
|
|
322
|
+
// An unchanged conference/announcement does not become a vulnerability just
|
|
323
|
+
// because it leaves the rolling RSS window. Inventory/content changes still
|
|
324
|
+
// invalidate its basis; affected/excluded impact claims always check freshness.
|
|
325
|
+
const keepGeneral = config.models.enabled &&
|
|
326
|
+
generalNews(previousById.get(finding.id)) &&
|
|
327
|
+
store.getMeta(`assessment-basis:${finding.id}`) === bases.get(finding.id);
|
|
328
|
+
let enriched = keepGeneral && !options.fixture
|
|
329
|
+
? interim(finding, bases.get(finding.id))
|
|
330
|
+
: system && !options.fixture
|
|
331
|
+
? await analyzer.analyze(finding, system, evidence)
|
|
332
|
+
: finding;
|
|
333
|
+
checkCancellation(signal);
|
|
334
|
+
const previous = previousById.get(finding.id);
|
|
335
|
+
if ((enriched.ai?.status === 'unavailable' || enriched.ai?.status === 'conflicting') &&
|
|
336
|
+
canRetainPriority(previous, enriched)) {
|
|
337
|
+
enriched = {
|
|
338
|
+
...enriched,
|
|
339
|
+
priority: previous.priority,
|
|
340
|
+
reasons: [...enriched.reasons, 'Previous priority retained pending valid AI reassessment.'],
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
if (enriched.ai?.status === 'unavailable' || enriched.ai?.status === 'conflicting') {
|
|
344
|
+
const code = enriched.reasons.find((r) => r.startsWith('MODEL_'))?.split(';')[0] ?? 'Analysis disagreement';
|
|
345
|
+
if (!errors.some((e) => e.source === 'models' && e.message === code))
|
|
346
|
+
errors.push({ source: 'models', message: code });
|
|
347
|
+
}
|
|
348
|
+
enriched = attachRemediation(enriched, inventory, evidence, config, now);
|
|
349
|
+
analyzed.push(enriched);
|
|
350
|
+
persist(enriched);
|
|
351
|
+
store.setMeta(`assessment-basis:${finding.id}`, bases.get(finding.id));
|
|
352
|
+
}
|
|
353
|
+
const groupedErrors = new Map();
|
|
354
|
+
for (const error of errors)
|
|
355
|
+
groupedErrors.set(error.source, [...(groupedErrors.get(error.source) ?? []), error.message]);
|
|
356
|
+
const healthFindings = [...groupedErrors].map(([source, messages]) => healthFinding(source, [...new Set(messages)].join(' '), now));
|
|
357
|
+
healthFindings.forEach(persist);
|
|
358
|
+
const active = new Set([...analyzed, ...healthFindings].map((a) => a.id));
|
|
359
|
+
for (const previous of store.findings())
|
|
360
|
+
if (!active.has(previous.id) && previous.active !== false)
|
|
361
|
+
retire(previous);
|
|
362
|
+
const report = {
|
|
363
|
+
at: timestamp(now),
|
|
364
|
+
completed_at: timestamp(options.now ?? Date.now()),
|
|
365
|
+
findings: [...analyzed, ...healthFindings],
|
|
366
|
+
decisions,
|
|
367
|
+
degraded: errors.length > 0,
|
|
368
|
+
errors,
|
|
369
|
+
notices,
|
|
370
|
+
evidence_count: evidence.length,
|
|
371
|
+
coverage: result.coverage,
|
|
372
|
+
inventory_drift: drift,
|
|
373
|
+
};
|
|
374
|
+
store.setMeta('inventory:baseline', JSON.stringify(inventory));
|
|
375
|
+
store.setMeta('inventory:last_drift', JSON.stringify(drift));
|
|
376
|
+
store.setMeta('source:coverage', JSON.stringify(result.coverage));
|
|
377
|
+
store.setMeta('last_scan', JSON.stringify({
|
|
378
|
+
at: report.completed_at,
|
|
379
|
+
started_at: report.at,
|
|
380
|
+
completed_at: report.completed_at,
|
|
381
|
+
degraded: report.degraded,
|
|
382
|
+
errors: report.errors,
|
|
383
|
+
findings: report.findings.length,
|
|
384
|
+
coverage: report.coverage,
|
|
385
|
+
inventory_drift: report.inventory_drift,
|
|
386
|
+
}));
|
|
387
|
+
return report;
|
|
388
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Whether a name is one of the commonest words of security prose ("send", "buffer", "next"). */
|
|
2
|
+
export declare function everydayWord(name: string): boolean;
|
|
3
|
+
/** Whether a dictionary word is also the name of a well-known library, written with a capital. */
|
|
4
|
+
export declare function properName(name: string): boolean;
|
|
5
|
+
/**
|
|
6
|
+
* Whether a package name reads as ordinary English: one word ("entities", "scheduler", "immediate")
|
|
7
|
+
* or a compound that prose writes with a hyphen ("side-channel", "one-time", "stack-trace"). Prose uses such a name in its
|
|
8
|
+
* ordinary sense far more often than it names the package, so a mention of it needs more than the
|
|
9
|
+
* word itself. A name that is not English ("axios", "lodash", "webpack") does not.
|
|
10
|
+
*/
|
|
11
|
+
export declare function dictionaryName(name: string): boolean;
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { WORD_FILTER_BITS, WORD_FILTER_DATA, WORD_FILTER_HASHES } from './word-filter.js';
|
|
2
|
+
/**
|
|
3
|
+
* Words that ordinary security prose uses in their everyday sense and that are also package names
|
|
4
|
+
* ("send a crafted request", "buffer overflow", "session cookie", "the next release"). A package
|
|
5
|
+
* with one of these names is matched in a news story only when the story is about packages or
|
|
6
|
+
* names a release of it; see `packageMentioned` in matching.ts.
|
|
7
|
+
*
|
|
8
|
+
* These are the commonest words. Any other English word is recognised by the dictionary filter
|
|
9
|
+
* below and treated a little more leniently; a name that is not English ("axios", "django",
|
|
10
|
+
* "webpack") is the software wherever it appears. Add a word here when it produces unrelated matches.
|
|
11
|
+
*/
|
|
12
|
+
const WORDS = `
|
|
13
|
+
able about above accept accepts access account accounts across action actions active activity actor
|
|
14
|
+
actors actual add added address addresses admin advisory affect affected after again against agent
|
|
15
|
+
agents alert alerts alias all allow allowed allows almost alone along already also always among amount
|
|
16
|
+
analysis and another answer any anyone anything app appear application applications apply approach
|
|
17
|
+
archive area argument arguments around array arrive article ask assert asset assets attach attack
|
|
18
|
+
attacker attackers attacks attempt attribute attributes audit auth author auto available avoid away
|
|
19
|
+
back backup bad banner base based basic batch because become been before begin behavior being below
|
|
20
|
+
best better between big binary bind bit bits black blank block blocks blue board body boolean boot
|
|
21
|
+
both bottom bound box branch break bridge brief bring broken browser buffer buffers bug bugs build
|
|
22
|
+
builder built bundle bus business but button bypass byte bytes cache call callback called caller calls
|
|
23
|
+
can cannot capture card care case cases cast catch cause caused causes center central certain chain
|
|
24
|
+
chains chalk chance change changes channel channels char character characters chart check checks child
|
|
25
|
+
children choice choose chunk circle class classes clean clear click client clients clock clone close
|
|
26
|
+
closed cloud cluster code codes collect collection color colors column columns combine come command
|
|
27
|
+
commands comment comments commit common community company compare compile complete component
|
|
28
|
+
components compress compute concat concern condition config configuration configure confirm connect
|
|
29
|
+
connection connections console constant constants contact contain container contains content contents
|
|
30
|
+
context continue control controls convert cookie cookies copy core correct cost could count counter
|
|
31
|
+
country course cover crash crawl create created credential credentials critical cross crypto
|
|
32
|
+
cryptography current cursor custom customer customers cut cycle daily damage dark dash data database
|
|
33
|
+
date dates day days dead deal debug decode deep default defaults define defined delay delete deliver
|
|
34
|
+
delivery demand demo deny depend depends deploy depth describe design desktop destroy detail details
|
|
35
|
+
detect develop developer developers device devices dialog diff different digest direct directory
|
|
36
|
+
disable discover disk dispatch display distance does doing domain domains done door double down
|
|
37
|
+
download draft draw drive driver drop due dump during each early easy echo edge edit editor effect
|
|
38
|
+
either element elements else email embed emit empty enable encode encoding end endpoint endpoints
|
|
39
|
+
engine enough ensure enter entire entity entry enum env environment equal equals error errors escape
|
|
40
|
+
even event events ever every everyone everything exact example except exception exchange exec execute
|
|
41
|
+
execution exist exists exit expand expect explain exploit exploits export expose exposed extend
|
|
42
|
+
extension extensions extra extract face fact fail failed fails failure fall false family far fast
|
|
43
|
+
fault feature features feed feedback fetch few field fields figure file files fill filter filters final
|
|
44
|
+
find finding fire firewall first fit five fix fixed fixes flag flags flash flat flaw flaws flex flight
|
|
45
|
+
float flood floor flow flush focus folder follow font food foo force foreign forget fork form format
|
|
46
|
+
forms forward found four frame framework free fresh friend from front full function functions future
|
|
47
|
+
gain game gate gateway general generate generic get gets give given glob global goal goes going gone
|
|
48
|
+
good got grant graph gray great green grid ground group groups grow guard guess guest guide hack half
|
|
49
|
+
hand handle handler handlers hang happen hard hardware has hash have head header headers health heap
|
|
50
|
+
hear heart heavy held help helper here hidden hide high history hit hold hole home hook hooks host
|
|
51
|
+
hosts hot hour hours house how however html http https hub huge human hundred icon idea identity idle
|
|
52
|
+
ignore image images impact implement import important improve include includes index info inform
|
|
53
|
+
information inherit inherits init initial inject injection inline inner input inputs insert inside
|
|
54
|
+
inspect install installed instance instead integer intent interface internal internet into invalid
|
|
55
|
+
invoke issue issues item items its itself job jobs join jump just keep kernel key keys kill kind know
|
|
56
|
+
known label labels lack language large last late later latest launch layer layout lazy lead leak leaks
|
|
57
|
+
learn least leave left legacy length less let letter level levels library license life light like
|
|
58
|
+
limit limits line lines link links list listen lists little live load loader local locale location
|
|
59
|
+
lock locks log logger logging logic login logs long look lookup loop loose lose loss lost lot low lower
|
|
60
|
+
machine made magic mail main maintain major make maker makes malicious malware manage manager manual
|
|
61
|
+
many map mapping maps mark marked market mask master match matches material matter may mean means
|
|
62
|
+
measure media meet member members memory menu merge message messages meta method methods metric
|
|
63
|
+
metrics middle might mime mind minimum minor minute minutes mirror miss missing mix mobile mock mode
|
|
64
|
+
model models modern modify module modules moment money monitor month months more most mount mouse move
|
|
65
|
+
much multi multiple must name named names native nature near need needs negative nest net network
|
|
66
|
+
networks never new news next nice night node nodes noise none normal not note notes nothing notice
|
|
67
|
+
notify now null number numbers object objects observe obtain occur off offer office offset often old
|
|
68
|
+
once one online only open opened opens operation operations operator option optional options order
|
|
69
|
+
origin original other others our out outer output outputs over overflow override own owner pack
|
|
70
|
+
package packages packet packets pad page pages paint pair panel paper param parameter parameters params
|
|
71
|
+
parent parse parser part parts party pass passed password passwords past patch patched patches path
|
|
72
|
+
paths pattern patterns pause pay payload payment peak peer pending people per perform period permit
|
|
73
|
+
person phase phone photo pick picture piece ping pipe pipeline pixel place plain plan platform play
|
|
74
|
+
player please plugin plugins point pointer points policy poll pool pop popular port ports position
|
|
75
|
+
positive possible post power prefer prefix prepare present press pretty prevent preview previous price
|
|
76
|
+
primary print printer prior priority privacy private privilege privileges probe problem proceed
|
|
77
|
+
process processes produce product products profile program progress project projects promise prompt
|
|
78
|
+
proof proper properties property protect protocol prove provide provider proxy public publish pull
|
|
79
|
+
pump purge purpose push put quality query question queue quick quiet quite quote race radio raise
|
|
80
|
+
random range rank rate rather raw reach read reader reading ready real really reason receive recent
|
|
81
|
+
record records recover red redirect reduce refer reference refresh regex region register registry
|
|
82
|
+
reject related relay release releases reload rely remain remote remove rename render repeat replace
|
|
83
|
+
reply report reports request requests require required requires rescue research reset resolve
|
|
84
|
+
resource resources respond response responses rest restart restore restrict result results resume
|
|
85
|
+
retry return returns reveal reverse review rewrite rich right ring rise risk road role roles roll root
|
|
86
|
+
round route router routes row rows rule rules run runner running runs safe safer said sale same sample
|
|
87
|
+
sandbox save say says scale scan scanner schedule schema scheme scope score screen script scripts
|
|
88
|
+
scroll seal search second seconds secret secrets section secure security see seed seek seem seen
|
|
89
|
+
select self sell send sender sends sense sent separate sequence serial series serve server servers
|
|
90
|
+
service services session sessions set sets setting settings setup seven several shadow shall shape
|
|
91
|
+
share shared sharp sheet shell shield shift ship short should show shows shut side sign signal
|
|
92
|
+
signature signed simple since single site sites six size skip sleep slice slide slot slow small smart
|
|
93
|
+
snapshot socket sockets soft software solid solution some someone something soon sort sound source
|
|
94
|
+
sources space span spawn speak special specific speed spell spend spin split spot spread spring stack
|
|
95
|
+
staff stage stand standard star start started state statement states static station status statuses
|
|
96
|
+
stay steal step steps stick still stop storage store stores story stream streams strict string strings
|
|
97
|
+
strip strong structure studio study stuff style subject submit success such sudden suite sum summary
|
|
98
|
+
super supply support sure surface swap switch symbol sync syntax system systems tab table tables tag
|
|
99
|
+
tags take taken takes talk tap target targets task tasks team tell temp template templates ten term
|
|
100
|
+
terminal terms test tests text than that the their them theme then there these they thing things think
|
|
101
|
+
third this those though thought thread threads threat three through throw thus ticket tie time timeout
|
|
102
|
+
timer times tiny tip title today together token tokens too tool tools top topic total touch toward
|
|
103
|
+
trace track trade traffic trail train transfer transform transport trap trash travel tree trial trick
|
|
104
|
+
trigger trim trouble true trust try tunnel turn twice two type types under union unique unit units
|
|
105
|
+
unknown unless unlock until update updated updates upgrade upload upon upper url usage use used user
|
|
106
|
+
users uses using usual util utility utils valid validate validation value values variable variables
|
|
107
|
+
variant vary vault vector vendor verify version versions very via victim video view viewer views
|
|
108
|
+
virtual virus visit visual voice void volume wait walk wall want warn warning was watch water wave way
|
|
109
|
+
ways weak web week weeks weight well were what when where whether which while white who whole why wide
|
|
110
|
+
widget width wild will win window windows wire wise wish with within without word words work worker
|
|
111
|
+
workers workflow works world worm worse would wrap wrapper write writer writes wrong year years yes
|
|
112
|
+
yet you young your zero zone
|
|
113
|
+
are async balanced brunch clap commander delegates descriptors err figures finished flatten forwarded
|
|
114
|
+
gauge grunt gulp helmet hosted ink lie math mem meow mute nan negotiator opener pend rand slash tar
|
|
115
|
+
timers ware
|
|
116
|
+
`;
|
|
117
|
+
/**
|
|
118
|
+
* Terms of security and software writing that no 1934 dictionary has, and that are package names
|
|
119
|
+
* too ("xss", "cors", "rollup", "punycode"). They are everyday words of this kind of text.
|
|
120
|
+
*/
|
|
121
|
+
const JARGON = `
|
|
122
|
+
acl aes ajax ansi api apt argon ascii auth backdoor base64 bcrypt bluetooth botnet cdn cgi cli cms
|
|
123
|
+
config cookie cors cpu crc csrf css csv cve cvss cwe ddos dll dns dom dos ecdsa edr email eof exe
|
|
124
|
+
exif ftp gif gpu grpc gui gzip hmac html http https iam icmp ide idor imap ini internet iot ipc ipv4
|
|
125
|
+
ipv6 jar jpeg jpg json jwt kev ldap lfi llm login mac malware mfa mime mitm mqtt nfc ntlm ntp oauth
|
|
126
|
+
oidc online openid otp pbkdf pdf pem phishing php pid pki plugin png pop3 posix punycode ram ransomware
|
|
127
|
+
rbac rce regex rest rfc rollup rootkit rpc rsa rss saml sbom sdk sha shellcode siem smb smtp snmp soc
|
|
128
|
+
socks spyware sql ssh ssl ssrf sso stderr stdin stdout svg tcp telnet tls toml totp tty udp uid unicode
|
|
129
|
+
unix uri url usb utf utf8 uuid vpn waf webhook websocket wifi xdr xml xss xxe yaml zip
|
|
130
|
+
changelog cron daemon distro dotfile firmware hostname hyperlink kernel localhost middleware namespace
|
|
131
|
+
passphrase plaintext runtime screenshot sudo sysadmin timestamp username whitelist blacklist wildcard
|
|
132
|
+
akira clop cobalt conti ghost hive lazarus lockbit medusa royal salt sandworm tesla tornado typhoon
|
|
133
|
+
adware analytics authentication authenticator authorization backend baseline benchmark biometric
|
|
134
|
+
biometrics bitcoin blockchain blog bootloader broadband captcha chatbot checkbox chipset codebase
|
|
135
|
+
compliance cryptocurrency cryptojacking cryptominer cyberattack cybercrime cybercriminal cybersecurity
|
|
136
|
+
darknet darkweb dashboard datacenter dataset deepfake devops downtime dropdown dropper ecommerce
|
|
137
|
+
ethereum ethernet failover fingerprinting fintech freeware frontend geolocation hacker hackers hacking
|
|
138
|
+
hacktivist healthcare homepage hypervisor infosec infostealer keylogger laptop lifecycle livestream
|
|
139
|
+
logon logout mainframe metadata microchip microservice microservices modem navbar offline onboarding
|
|
140
|
+
opensource outage passcode passkey pentest podcast popup roadmap robotics rollback rollout scareware
|
|
141
|
+
screencast semiconductor serverless shareware sidebar signin signup skimmer smartphone smartwatch
|
|
142
|
+
smishing spoofing stakeholder startup stealer takedown telco telecom telehealth timeline toolchain
|
|
143
|
+
toolkit tooltip touchscreen tracker trojan typosquatting uptime vishing webpage website wearable wiper
|
|
144
|
+
`;
|
|
145
|
+
/**
|
|
146
|
+
* Names of well-known libraries that are also dictionary words. Prose about the software writes
|
|
147
|
+
* the name with a capital and may open a sentence with it ("Rails releases patches", "Electron
|
|
148
|
+
* fixes a sandbox escape"); see `packageMentioned` in matching.ts.
|
|
149
|
+
*/
|
|
150
|
+
const PROPER = new Set(`angular backbone bootstrap bottle celery cobra composer cypress electron ember express fiber
|
|
151
|
+
flask gin guava hibernate husky hyper jasmine jest karma meteor mocha mongoose mustache nest nose
|
|
152
|
+
pandas pillow puma puppeteer pyramid rack rails react rocket sass spring struts stylus tide typescript
|
|
153
|
+
viper warp yarn alembic anthropic apollo babel bundler cheerio drizzle faraday jackson playwright poetry
|
|
154
|
+
rake storybook svelte thor tox transformers winston`.split(/\s+/));
|
|
155
|
+
const EVERYDAY = new Set([...WORDS.split(/\s+/), ...JARGON.split(/\s+/)].filter(Boolean));
|
|
156
|
+
const JARGON_WORDS = new Set(JARGON.split(/\s+/).filter(Boolean));
|
|
157
|
+
/** Whether a name is one of the commonest words of security prose ("send", "buffer", "next"). */
|
|
158
|
+
export function everydayWord(name) {
|
|
159
|
+
const word = name.trim().toLowerCase();
|
|
160
|
+
if (PROPER.has(word))
|
|
161
|
+
return false;
|
|
162
|
+
if (EVERYDAY.has(word))
|
|
163
|
+
return true;
|
|
164
|
+
// The plural of a term of security writing is one too ("websockets", "cves").
|
|
165
|
+
const singular = word.endsWith('s') ? word.slice(0, -1) : undefined;
|
|
166
|
+
return singular !== undefined && JARGON_WORDS.has(singular);
|
|
167
|
+
}
|
|
168
|
+
/** Whether a dictionary word is also the name of a well-known library, written with a capital. */
|
|
169
|
+
export function properName(name) {
|
|
170
|
+
return PROPER.has(name.trim().toLowerCase());
|
|
171
|
+
}
|
|
172
|
+
let filter;
|
|
173
|
+
function inDictionary(word) {
|
|
174
|
+
if (word.length < 3 || word.length > 12 || !/^[a-z]+$/.test(word))
|
|
175
|
+
return false;
|
|
176
|
+
filter ??= Uint8Array.from(Buffer.from(WORD_FILTER_DATA.replace(/\s+/g, ''), 'base64'));
|
|
177
|
+
let first = 0x811c9dc5;
|
|
178
|
+
let second = 0x01000193;
|
|
179
|
+
for (let index = 0; index < word.length; index++) {
|
|
180
|
+
const code = word.charCodeAt(index);
|
|
181
|
+
first = Math.imul(first ^ code, 0x01000193) >>> 0;
|
|
182
|
+
second = Math.imul(second ^ code, 0x5bd1e995) >>> 0;
|
|
183
|
+
}
|
|
184
|
+
second |= 1;
|
|
185
|
+
for (let round = 0; round < WORD_FILTER_HASHES; round++) {
|
|
186
|
+
const position = ((first + Math.imul(round, second)) >>> 0) % WORD_FILTER_BITS;
|
|
187
|
+
if (!(filter[position >> 3] & (1 << (position & 7))))
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
return true;
|
|
191
|
+
}
|
|
192
|
+
/** The word and the base forms it may be an inflection of ("entities", "requests", "executing"). */
|
|
193
|
+
function baseForms(word) {
|
|
194
|
+
const forms = [word];
|
|
195
|
+
if (word.endsWith('ies'))
|
|
196
|
+
forms.push(`${word.slice(0, -3)}y`);
|
|
197
|
+
// "denied", "verified", "prettier", "happiest": the -y word they come from.
|
|
198
|
+
if (/(?:ied|ier|iest)$/.test(word))
|
|
199
|
+
forms.push(`${word.replace(/(?:ied|ier|iest)$/, '')}y`);
|
|
200
|
+
if (word.endsWith('es'))
|
|
201
|
+
forms.push(word.slice(0, -2));
|
|
202
|
+
if (word.endsWith('s'))
|
|
203
|
+
forms.push(word.slice(0, -1));
|
|
204
|
+
if (word.endsWith('ed'))
|
|
205
|
+
forms.push(word.slice(0, -2), word.slice(0, -1));
|
|
206
|
+
if (word.endsWith('ing'))
|
|
207
|
+
forms.push(word.slice(0, -3), `${word.slice(0, -3)}e`);
|
|
208
|
+
if (word.endsWith('er') || word.endsWith('or'))
|
|
209
|
+
forms.push(word.slice(0, -2), `${word.slice(0, -2)}e`);
|
|
210
|
+
return forms;
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Whether a single word is an English word, a term of security writing, or an inflection of one.
|
|
214
|
+
* Names known to be library names that the dictionary filter would wrongly claim go in DISTINCTIVE.
|
|
215
|
+
*/
|
|
216
|
+
const DISTINCTIVE = new Set(['chokidar', 'hapi', 'multer', 'nanoid', 'redux', 'spacy']);
|
|
217
|
+
function englishWord(word) {
|
|
218
|
+
if (DISTINCTIVE.has(word))
|
|
219
|
+
return false;
|
|
220
|
+
return (EVERYDAY.has(word) ||
|
|
221
|
+
PROPER.has(word) ||
|
|
222
|
+
// "websockets", "apis": a plural of a term of security writing is one too.
|
|
223
|
+
baseForms(word).some((form) => EVERYDAY.has(form) || inDictionary(form)));
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Compounds that security prose writes with hyphens in their ordinary sense. Any other hyphenated
|
|
227
|
+
* name ("left-pad", "is-odd") is specific enough to be the package wherever it is written out.
|
|
228
|
+
*/
|
|
229
|
+
const COMPOUNDS = new Set(`add-on back-end brute-force built-in buffer-overflow client-side command-line content-type
|
|
230
|
+
cross-origin cross-site denial-of-service diffie-hellman end-to-end front-end high-severity log-in
|
|
231
|
+
long-term man-in-the-middle multi-factor open-source opt-in opt-out out-of-bounds plug-in pre-auth
|
|
232
|
+
proof-of-concept read-only real-time same-origin server-side set-cookie set-up side-channel sign-in
|
|
233
|
+
single-sign-on third-party time-based two-factor use-after-free user-agent zero-click zero-day
|
|
234
|
+
zero-trust one-time one-click one-day n-day two-step multi-step stack-trace stack-based heap-based
|
|
235
|
+
double-free race-condition path-traversal privilege-escalation code-execution remote-code
|
|
236
|
+
content-disposition content-length content-security-policy x-forwarded-for keep-alive cache-control
|
|
237
|
+
rate-limit rate-limiting password-spraying credential-stuffing end-of-life up-to-date out-of-date
|
|
238
|
+
well-known high-risk low-risk high-level low-level first-party closed-source read-write write-only
|
|
239
|
+
drive-by follow-up sign-up check-in pop-up take-over point-of-sale peer-to-peer command-and-control
|
|
240
|
+
living-off-the-land ransomware-as-a-service supply-chain open-redirect file-upload self-signed
|
|
241
|
+
self-hosted cloud-native long-lived short-lived hard-coded`.split(/\s+/));
|
|
242
|
+
/**
|
|
243
|
+
* Whether a package name reads as ordinary English: one word ("entities", "scheduler", "immediate")
|
|
244
|
+
* or a compound that prose writes with a hyphen ("side-channel", "one-time", "stack-trace"). Prose uses such a name in its
|
|
245
|
+
* ordinary sense far more often than it names the package, so a mention of it needs more than the
|
|
246
|
+
* word itself. A name that is not English ("axios", "lodash", "webpack") does not.
|
|
247
|
+
*/
|
|
248
|
+
export function dictionaryName(name) {
|
|
249
|
+
const word = name.trim().toLowerCase();
|
|
250
|
+
if (EVERYDAY.has(word) || PROPER.has(word) || COMPOUNDS.has(word))
|
|
251
|
+
return true;
|
|
252
|
+
// A hyphenated name counts as English only when it is a compound that prose writes with the
|
|
253
|
+
// hyphen ("one-time", "stack-trace", "content-disposition"): those are in COMPOUNDS. A library's
|
|
254
|
+
// compound ("body-parser", "node-fetch", "left-pad") is hardly ever ordinary prose.
|
|
255
|
+
return /^[a-z]+$/.test(word) && englishWord(word);
|
|
256
|
+
}
|