@shieldaai/security-watch 0.0.0-stage → 0.1.0-alpha.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/CONTRIBUTING.md +90 -0
- package/LICENSE +202 -0
- package/README.md +269 -2
- package/SECURITY.md +47 -0
- package/dist/assessment.d.ts +5 -0
- package/dist/assessment.js +398 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +792 -0
- package/dist/config.d.ts +242 -0
- package/dist/config.js +298 -0
- package/dist/cve-now.d.ts +5 -0
- package/dist/cve-now.js +413 -0
- package/dist/delivery.d.ts +26 -0
- package/dist/delivery.js +394 -0
- package/dist/ecosystems.d.ts +25 -0
- package/dist/ecosystems.js +254 -0
- package/dist/engine.d.ts +26 -0
- package/dist/engine.js +307 -0
- package/dist/health.d.ts +17 -0
- package/dist/health.js +70 -0
- package/dist/heartbeat.d.ts +13 -0
- package/dist/heartbeat.js +74 -0
- package/dist/http.d.ts +8 -0
- package/dist/http.js +251 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +15 -0
- package/dist/inventory.d.ts +3 -0
- package/dist/inventory.js +143 -0
- package/dist/lock.d.ts +3 -0
- package/dist/lock.js +112 -0
- package/dist/maintenance.d.ts +43 -0
- package/dist/maintenance.js +227 -0
- package/dist/models.d.ts +20 -0
- package/dist/models.js +602 -0
- package/dist/operations.d.ts +17 -0
- package/dist/operations.js +117 -0
- package/dist/providers.d.ts +209 -0
- package/dist/providers.js +459 -0
- package/dist/setup.d.ts +113 -0
- package/dist/setup.js +100 -0
- package/dist/source-error.d.ts +22 -0
- package/dist/source-error.js +56 -0
- package/dist/sources.d.ts +3 -0
- package/dist/sources.js +1071 -0
- package/dist/store.d.ts +71 -0
- package/dist/store.js +651 -0
- package/dist/types.d.ts +247 -0
- package/dist/types.js +1 -0
- package/dist/util.d.ts +6 -0
- package/dist/util.js +14 -0
- package/dist/vendor-sources.d.ts +24 -0
- package/dist/vendor-sources.js +56 -0
- package/docs/configuration.md +406 -0
- package/docs/quality-review.md +104 -0
- package/examples/advisories.json +17 -0
- package/examples/common-systems.yaml +243 -0
- package/examples/libraries.example.txt +16 -0
- package/examples/libraries.example.yaml +38 -0
- package/examples/library-watch.example.yaml +27 -0
- package/examples/security-watch.example.yaml +86 -0
- package/examples/systems.example.yaml +31 -0
- package/package.json +69 -4
package/dist/delivery.js
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
import nodemailer from 'nodemailer';
|
|
2
|
+
import { createConnection } from 'node:net';
|
|
3
|
+
import { cleanText } from './util.js';
|
|
4
|
+
import { decide } from './assessment.js';
|
|
5
|
+
import { Store } from './store.js';
|
|
6
|
+
import { NetworkError } from './http.js';
|
|
7
|
+
class EmailConnectionError extends Error {
|
|
8
|
+
constructor() {
|
|
9
|
+
super('SMTP connection failed before sending');
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export const sendEmail = async (message) => {
|
|
13
|
+
message.signal?.throwIfAborted();
|
|
14
|
+
const url = new URL(message.url);
|
|
15
|
+
if (!['smtp:', 'smtps:'].includes(url.protocol) ||
|
|
16
|
+
url.search ||
|
|
17
|
+
url.hash ||
|
|
18
|
+
(url.pathname && url.pathname !== '/'))
|
|
19
|
+
throw new Error('Invalid SMTP configuration');
|
|
20
|
+
let socket;
|
|
21
|
+
const transport = nodemailer.createTransport({
|
|
22
|
+
host: url.hostname.replace(/^\[|\]$/g, ''),
|
|
23
|
+
port: Number(url.port || (url.protocol === 'smtps:' ? 465 : 587)),
|
|
24
|
+
secure: url.protocol === 'smtps:',
|
|
25
|
+
requireTLS: true,
|
|
26
|
+
ignoreTLS: false,
|
|
27
|
+
...(url.username
|
|
28
|
+
? { auth: { user: decodeURIComponent(url.username), pass: decodeURIComponent(url.password) } }
|
|
29
|
+
: {}),
|
|
30
|
+
tls: { rejectUnauthorized: true, minVersion: 'TLSv1.2' },
|
|
31
|
+
connectionTimeout: 30_000,
|
|
32
|
+
greetingTimeout: 30_000,
|
|
33
|
+
socketTimeout: 30_000,
|
|
34
|
+
disableFileAccess: true,
|
|
35
|
+
disableUrlAccess: true,
|
|
36
|
+
// Keep the underlying socket so cancellation also stops SMTP/STARTTLS traffic.
|
|
37
|
+
getSocket: (_options, callback) => {
|
|
38
|
+
if (message.signal?.aborted) {
|
|
39
|
+
callback(new Error('Email delivery aborted'), {});
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
let connected = false;
|
|
43
|
+
socket = createConnection({
|
|
44
|
+
host: url.hostname.replace(/^\[|\]$/g, ''),
|
|
45
|
+
port: Number(url.port || (url.protocol === 'smtps:' ? 465 : 587)),
|
|
46
|
+
signal: message.signal,
|
|
47
|
+
});
|
|
48
|
+
const deadline = setTimeout(() => socket?.destroy(new Error('SMTP connection timeout')), 30_000);
|
|
49
|
+
socket.once('close', () => clearTimeout(deadline));
|
|
50
|
+
socket.once('error', () => {
|
|
51
|
+
if (!connected)
|
|
52
|
+
callback(new EmailConnectionError(), {});
|
|
53
|
+
});
|
|
54
|
+
socket.once('connect', () => {
|
|
55
|
+
connected = true;
|
|
56
|
+
clearTimeout(deadline);
|
|
57
|
+
callback(null, { connection: socket });
|
|
58
|
+
});
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
let abort;
|
|
62
|
+
try {
|
|
63
|
+
const cancelled = new Promise((_resolve, reject) => {
|
|
64
|
+
abort = () => {
|
|
65
|
+
reject(new Error('Email delivery aborted'));
|
|
66
|
+
socket?.destroy();
|
|
67
|
+
transport.close();
|
|
68
|
+
};
|
|
69
|
+
message.signal?.addEventListener('abort', abort, { once: true });
|
|
70
|
+
});
|
|
71
|
+
const sending = transport.sendMail({
|
|
72
|
+
from: message.from,
|
|
73
|
+
to: message.to,
|
|
74
|
+
subject: message.subject,
|
|
75
|
+
text: message.text,
|
|
76
|
+
disableFileAccess: true,
|
|
77
|
+
disableUrlAccess: true,
|
|
78
|
+
});
|
|
79
|
+
const result = await Promise.race([sending, cancelled]);
|
|
80
|
+
return { accepted: result.accepted.map(String), rejected: result.rejected.map(String) };
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
if (abort)
|
|
84
|
+
message.signal?.removeEventListener('abort', abort);
|
|
85
|
+
transport.close();
|
|
86
|
+
socket?.destroy();
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
function safeText(input, length) {
|
|
90
|
+
return cleanText(input, length)
|
|
91
|
+
.replace(/[\r\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '')
|
|
92
|
+
.replace(/@/g, '@\u200b')
|
|
93
|
+
.slice(0, length);
|
|
94
|
+
}
|
|
95
|
+
export function notificationText(job) {
|
|
96
|
+
const { assessment: a, reason } = JSON.parse(job.payload);
|
|
97
|
+
const subject = safeText(`[${a.priority.toUpperCase()}] ${a.title}`, 180).replace(/[\n\r]/g, ' ');
|
|
98
|
+
const urls = a.urls.filter((value) => {
|
|
99
|
+
try {
|
|
100
|
+
return ['https:', 'http:'].includes(new URL(value).protocol);
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
const lines = [
|
|
107
|
+
subject,
|
|
108
|
+
`Finding: ${a.id}`,
|
|
109
|
+
`Delivery: ${job.id}`,
|
|
110
|
+
`System: ${safeText(a.system_id, 200)}${a.component_id ? ` / ${safeText(a.component_id, 200)}` : ''}`,
|
|
111
|
+
`Applicability: ${a.applicability}; source severity: ${a.source_severity}; priority: ${a.priority}`,
|
|
112
|
+
...(a.news_analysis
|
|
113
|
+
? [
|
|
114
|
+
`AI news classification: ${a.news_analysis.classification}; reported system impact: ${a.news_analysis.impact}`,
|
|
115
|
+
`Affected products: ${safeText(a.news_analysis.affected_products.join('; ') || 'Not established', 180)}`,
|
|
116
|
+
`Reported versions: ${safeText(a.news_analysis.affected_versions.join('; ') || 'Not established', 180)}`,
|
|
117
|
+
`Prerequisites: ${safeText(a.news_analysis.prerequisites.join('; ') || 'Not established', 240)}`,
|
|
118
|
+
`Impact reasoning: ${safeText(a.news_analysis.rationale, 400)}`,
|
|
119
|
+
]
|
|
120
|
+
: []),
|
|
121
|
+
...(a.exploited ? ['Known exploitation reported.'] : []),
|
|
122
|
+
safeText(a.summary, 750),
|
|
123
|
+
...a.reasons.slice(0, 4).map((r) => `• ${safeText(r, 180)}`),
|
|
124
|
+
...(a.fix ? [`Fix: ${safeText(a.fix, 160)}`] : []),
|
|
125
|
+
`Rule: ${safeText(reason, 180)}`,
|
|
126
|
+
`Assessment time: ${a.updated_at}`,
|
|
127
|
+
...urls.slice(0, 3).map((u) => safeText(u, 320)),
|
|
128
|
+
];
|
|
129
|
+
return { subject, text: safeText(lines.join('\n'), 2900) };
|
|
130
|
+
}
|
|
131
|
+
function digestText(jobs) {
|
|
132
|
+
const subject = `Security Watch digest: ${jobs.length} findings`;
|
|
133
|
+
const entries = jobs.map((job) => {
|
|
134
|
+
const { assessment: a } = JSON.parse(job.payload);
|
|
135
|
+
const sourceUrl = a.urls.find((value) => {
|
|
136
|
+
try {
|
|
137
|
+
return ['https:', 'http:'].includes(new URL(value).protocol);
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
return (`[${a.priority.toUpperCase()}] ${safeText(a.title, 90)}\n` +
|
|
144
|
+
`Finding: ${a.id}\nDelivery: ${job.id}\n` +
|
|
145
|
+
`System: ${safeText(a.system_id, 60)}${a.component_id ? ` / ${safeText(a.component_id, 60)}` : ''}\n` +
|
|
146
|
+
`Applicability: ${a.applicability}; source: ${a.source_severity}\n` +
|
|
147
|
+
(a.news_analysis
|
|
148
|
+
? `AI news: ${a.news_analysis.classification}; impact: ${a.news_analysis.impact}\n`
|
|
149
|
+
: '') +
|
|
150
|
+
`${safeText(sourceUrl ?? 'No source URL supplied', 160)}`);
|
|
151
|
+
});
|
|
152
|
+
return { subject, text: `${subject}\n\n${entries.join('\n\n')}` };
|
|
153
|
+
}
|
|
154
|
+
function retryAt(headers, now, attempts) {
|
|
155
|
+
const raw = Object.entries(headers).find(([name]) => name.toLowerCase() === 'retry-after')?.[1];
|
|
156
|
+
const retry = raw === undefined ? NaN : /^\d+(\.\d+)?$/.test(raw) ? now + Number(raw) * 1000 : Date.parse(raw);
|
|
157
|
+
// Clamp Retry-After values to avoid immediate retries or excessive delays.
|
|
158
|
+
return Number.isFinite(retry)
|
|
159
|
+
? Math.min(now + 86_400_000, Math.max(now + 1000, retry))
|
|
160
|
+
: now + Math.min(3_600_000, 30_000 * 2 ** Math.min(attempts - 1, 7));
|
|
161
|
+
}
|
|
162
|
+
function statusCode(error) {
|
|
163
|
+
if (typeof error !== 'object' || error === null || !('responseCode' in error))
|
|
164
|
+
return undefined;
|
|
165
|
+
const code = Number(error.responseCode);
|
|
166
|
+
return Number.isFinite(code) ? code : undefined;
|
|
167
|
+
}
|
|
168
|
+
/** Sends due jobs; "accepted" means the destination accepted the request, not that a human read it. */
|
|
169
|
+
export async function deliverPending(store, config, http, now = Date.now(), emailSender = sendEmail, signal) {
|
|
170
|
+
const result = { accepted: 0, failed: 0, unknown: 0 };
|
|
171
|
+
let job;
|
|
172
|
+
const started = Date.now();
|
|
173
|
+
let batches = 0;
|
|
174
|
+
// One snapshot of due work avoids waiting in-process for rate limits or retry timers.
|
|
175
|
+
while (!signal?.aborted &&
|
|
176
|
+
batches++ < 50 &&
|
|
177
|
+
Date.now() - started < 2000 &&
|
|
178
|
+
(job = store.claimDue(now, Number(store.getMeta('delivery:slack:next_at') ?? 0) > now ? ['slack'] : []))) {
|
|
179
|
+
let batch = [job];
|
|
180
|
+
let wantsDigest = false;
|
|
181
|
+
try {
|
|
182
|
+
wantsDigest = JSON.parse(job.payload).mode === 'digest';
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
/* Invalid payload is handled below. */
|
|
186
|
+
}
|
|
187
|
+
if (wantsDigest)
|
|
188
|
+
batch.push(...store.claimAdditionalDigest(job.channel, now));
|
|
189
|
+
// A worker restart can load a new policy before its first source scan finishes. Do not
|
|
190
|
+
// deliver previously queued routes or urgency blindly under that changed configuration.
|
|
191
|
+
batch = batch.filter((entry) => {
|
|
192
|
+
const current = store.getFinding(entry.finding_id);
|
|
193
|
+
if (!current || current.active === false) {
|
|
194
|
+
store.completeJob(entry.id, 'failed', now, 'Finding is no longer active');
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
const decision = decide(current, config);
|
|
198
|
+
if (decision.action === 'record' || !decision.channels.includes(entry.channel)) {
|
|
199
|
+
store.completeJob(entry.id, 'failed', now, 'Notification policy no longer selects this destination');
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
let mode;
|
|
203
|
+
try {
|
|
204
|
+
mode = JSON.parse(entry.payload).mode;
|
|
205
|
+
// Validate each saved entry before grouping it with other findings.
|
|
206
|
+
if (mode === 'digest')
|
|
207
|
+
digestText([entry]);
|
|
208
|
+
else
|
|
209
|
+
notificationText(entry);
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
store.completeJob(entry.id, 'failed', now, 'Invalid saved notification payload');
|
|
213
|
+
result.failed++;
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
216
|
+
if (mode !== decision.action) {
|
|
217
|
+
store.completeJob(entry.id, 'failed', now, 'Notification urgency changed under the current policy');
|
|
218
|
+
store.saveAssessment(current, decision, now, config.digest_interval_hours * 3_600_000);
|
|
219
|
+
return false;
|
|
220
|
+
}
|
|
221
|
+
return true;
|
|
222
|
+
});
|
|
223
|
+
if (!batch.length)
|
|
224
|
+
continue;
|
|
225
|
+
const digest = JSON.parse(batch[0].payload).mode === 'digest';
|
|
226
|
+
if (digest && batch[0].channel === 'slack') {
|
|
227
|
+
const fitting = [];
|
|
228
|
+
for (const entry of batch) {
|
|
229
|
+
if (digestText([entry]).text.length > 2900) {
|
|
230
|
+
store.completeJob(entry.id, 'failed', now, 'Saved finding exceeds the Slack message limit');
|
|
231
|
+
result.failed++;
|
|
232
|
+
}
|
|
233
|
+
else if (digestText([...fitting, entry]).text.length > 2900)
|
|
234
|
+
store.deferJob(entry.id, now + 1000, 'Waiting for the next digest batch');
|
|
235
|
+
else
|
|
236
|
+
fitting.push(entry);
|
|
237
|
+
}
|
|
238
|
+
batch = fitting;
|
|
239
|
+
if (!batch.length)
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
const item = batch[0];
|
|
243
|
+
const finish = (status, message) => {
|
|
244
|
+
for (const entry of batch) {
|
|
245
|
+
store.completeJob(entry.id, status, now, message);
|
|
246
|
+
result[status]++;
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
const retry = (message, at) => {
|
|
250
|
+
for (const entry of batch) {
|
|
251
|
+
if (entry.attempts >= config.notifications.max_attempts) {
|
|
252
|
+
store.completeJob(entry.id, 'failed', now, `${message}; retry limit reached`);
|
|
253
|
+
result.failed++;
|
|
254
|
+
}
|
|
255
|
+
else
|
|
256
|
+
store.completeJob(entry.id, 'pending', at, message);
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
let text;
|
|
260
|
+
try {
|
|
261
|
+
text = digest ? digestText(batch) : notificationText(item);
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
finish('failed', 'Invalid saved notification payload');
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
if (item.channel === 'slack') {
|
|
268
|
+
const settings = config.notifications.slack;
|
|
269
|
+
const secret = settings ? process.env[settings.webhook_url_env] : undefined;
|
|
270
|
+
if (!secret) {
|
|
271
|
+
finish('failed', 'Slack destination is not configured');
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
try {
|
|
275
|
+
const url = new URL(secret);
|
|
276
|
+
if (url.protocol !== 'https:' ||
|
|
277
|
+
url.hostname !== 'hooks.slack.com' ||
|
|
278
|
+
!url.pathname.startsWith('/services/') ||
|
|
279
|
+
url.username ||
|
|
280
|
+
url.password ||
|
|
281
|
+
url.search ||
|
|
282
|
+
url.hash ||
|
|
283
|
+
(url.port && url.port !== '443')) {
|
|
284
|
+
finish('failed', 'Slack webhook must be an HTTPS hooks.slack.com/services URL');
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
catch {
|
|
289
|
+
finish('failed', 'Slack webhook URL is invalid');
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
const nextSlackAt = Number(store.getMeta('delivery:slack:next_at') ?? 0);
|
|
293
|
+
if (nextSlackAt > now) {
|
|
294
|
+
for (const entry of batch)
|
|
295
|
+
store.deferJob(entry.id, nextSlackAt);
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
store.setMeta('delivery:slack:next_at', String(now + 1000));
|
|
299
|
+
try {
|
|
300
|
+
const escaped = text.text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
301
|
+
const response = await http(secret, {
|
|
302
|
+
signal,
|
|
303
|
+
method: 'POST',
|
|
304
|
+
redirects: 0,
|
|
305
|
+
timeoutMs: 30_000,
|
|
306
|
+
maxBytes: 16_384,
|
|
307
|
+
headers: { 'content-type': 'application/json' },
|
|
308
|
+
body: JSON.stringify({
|
|
309
|
+
text: escaped,
|
|
310
|
+
mrkdwn: false,
|
|
311
|
+
unfurl_links: false,
|
|
312
|
+
unfurl_media: false,
|
|
313
|
+
blocks: [{ type: 'section', text: { type: 'plain_text', text: text.text, emoji: false } }],
|
|
314
|
+
}),
|
|
315
|
+
});
|
|
316
|
+
if (response.status === 200 && response.body.trim() === 'ok')
|
|
317
|
+
finish('accepted');
|
|
318
|
+
else if (response.status === 429 || response.status >= 500) {
|
|
319
|
+
const at = retryAt(response.headers, now, item.attempts);
|
|
320
|
+
if (response.status === 429) {
|
|
321
|
+
store.setMeta('delivery:slack:next_at', String(at));
|
|
322
|
+
}
|
|
323
|
+
retry(`Slack rejected request with HTTP ${response.status}`, at);
|
|
324
|
+
}
|
|
325
|
+
else if (response.status >= 200 && response.status < 300)
|
|
326
|
+
finish('unknown', 'Unexpected Slack success response; verify receipt before retrying');
|
|
327
|
+
else
|
|
328
|
+
finish('failed', `Slack rejected request with HTTP ${response.status}`);
|
|
329
|
+
}
|
|
330
|
+
catch (error) {
|
|
331
|
+
if (!signal?.aborted &&
|
|
332
|
+
error instanceof NetworkError &&
|
|
333
|
+
['DNS_FAILED', 'CONNECTION_FAILED'].includes(error.code))
|
|
334
|
+
retry('Slack connection failed before sending', retryAt({}, now, item.attempts));
|
|
335
|
+
else
|
|
336
|
+
finish('unknown', 'Slack delivery interrupted; receipt is unknown. Verify the destination before retrying.');
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
else {
|
|
340
|
+
const settings = config.notifications.email;
|
|
341
|
+
const secret = settings ? process.env[settings.smtp_url_env] : undefined;
|
|
342
|
+
if (!settings || !secret) {
|
|
343
|
+
finish('failed', 'Email destination is not configured');
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
try {
|
|
347
|
+
const url = new URL(secret);
|
|
348
|
+
if (!['smtp:', 'smtps:'].includes(url.protocol) ||
|
|
349
|
+
url.search ||
|
|
350
|
+
url.hash ||
|
|
351
|
+
(url.pathname && url.pathname !== '/')) {
|
|
352
|
+
finish('failed', 'Invalid SMTP configuration');
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
catch {
|
|
357
|
+
finish('failed', 'Invalid SMTP configuration');
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
try {
|
|
361
|
+
const receipt = await emailSender({
|
|
362
|
+
url: secret,
|
|
363
|
+
from: settings.from,
|
|
364
|
+
to: [...new Set(settings.to)],
|
|
365
|
+
subject: text.subject,
|
|
366
|
+
text: text.text,
|
|
367
|
+
signal,
|
|
368
|
+
});
|
|
369
|
+
const expected = new Set(settings.to);
|
|
370
|
+
const accepted = new Set(receipt.accepted);
|
|
371
|
+
if (!receipt.rejected.length &&
|
|
372
|
+
accepted.size === expected.size &&
|
|
373
|
+
[...expected].every((address) => accepted.has(address)))
|
|
374
|
+
finish('accepted');
|
|
375
|
+
else if (receipt.accepted.length)
|
|
376
|
+
finish('unknown', 'SMTP accepted only some recipients. Verify receipt before retrying to avoid duplicates.');
|
|
377
|
+
else
|
|
378
|
+
finish('failed', 'SMTP did not accept any recipients');
|
|
379
|
+
}
|
|
380
|
+
catch (error) {
|
|
381
|
+
const code = statusCode(error);
|
|
382
|
+
if (!signal?.aborted && error instanceof EmailConnectionError)
|
|
383
|
+
retry('SMTP connection failed before sending', retryAt({}, now, item.attempts));
|
|
384
|
+
else if (code && code >= 400 && code < 500)
|
|
385
|
+
retry(`SMTP rejected request with status ${code}`, retryAt({}, now, item.attempts));
|
|
386
|
+
else if (code && code >= 500 && code < 600)
|
|
387
|
+
finish('failed', `SMTP rejected request with status ${code}`);
|
|
388
|
+
else
|
|
389
|
+
finish('unknown', 'SMTP delivery interrupted; receipt is unknown. Verify the destination before retrying.');
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return result;
|
|
394
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Component } from './types.js';
|
|
2
|
+
/** Package identities follow the registry named by the OSV ecosystem. */
|
|
3
|
+
export declare const ECOSYSTEMS: readonly ['npm', 'PyPI', 'Packagist', 'Go', 'Maven', 'crates.io', 'RubyGems', 'NuGet', 'Hex', 'Pub', 'Hackage', 'SwiftURL'];
|
|
4
|
+
export type Ecosystem = (typeof ECOSYSTEMS)[number];
|
|
5
|
+
export declare function normalizeEcosystem(value: string): Ecosystem;
|
|
6
|
+
export declare function normalizePackageName(ecosystem: Ecosystem, value: string): string;
|
|
7
|
+
/** Keep the published spelling: OSV does not consistently normalize registry aliases. */
|
|
8
|
+
export declare function osvPackageNames(ecosystem: Ecosystem, value: string): string[];
|
|
9
|
+
export declare function samePackage(left: {
|
|
10
|
+
ecosystem: string;
|
|
11
|
+
name: string;
|
|
12
|
+
}, right: {
|
|
13
|
+
ecosystem: string;
|
|
14
|
+
name: string;
|
|
15
|
+
}): boolean;
|
|
16
|
+
/** A declared version, never a dependency constraint or an inferred latest release. */
|
|
17
|
+
export declare function exactLibraryVersion(value: string, ecosystem?: Ecosystem): string;
|
|
18
|
+
export interface Library {
|
|
19
|
+
ecosystem: Ecosystem;
|
|
20
|
+
name: string;
|
|
21
|
+
version?: string;
|
|
22
|
+
}
|
|
23
|
+
export declare function parseLibrary(value: unknown, defaultEcosystem?: string): Library;
|
|
24
|
+
/** Parse one entry per line; the ecosystem is explicit or supplied for the whole list. */
|
|
25
|
+
export declare function parseLibraryList(text: string, ecosystem?: string): Component[];
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { hash } from './util.js';
|
|
2
|
+
import { valid } from 'semver';
|
|
3
|
+
/** Package identities follow the registry named by the OSV ecosystem. */
|
|
4
|
+
export const ECOSYSTEMS = [
|
|
5
|
+
'npm',
|
|
6
|
+
'PyPI',
|
|
7
|
+
'Packagist',
|
|
8
|
+
'Go',
|
|
9
|
+
'Maven',
|
|
10
|
+
'crates.io',
|
|
11
|
+
'RubyGems',
|
|
12
|
+
'NuGet',
|
|
13
|
+
'Hex',
|
|
14
|
+
'Pub',
|
|
15
|
+
'Hackage',
|
|
16
|
+
'SwiftURL',
|
|
17
|
+
];
|
|
18
|
+
const aliases = {
|
|
19
|
+
npm: 'npm',
|
|
20
|
+
node: 'npm',
|
|
21
|
+
nodejs: 'npm',
|
|
22
|
+
javascript: 'npm',
|
|
23
|
+
js: 'npm',
|
|
24
|
+
pypi: 'PyPI',
|
|
25
|
+
python: 'PyPI',
|
|
26
|
+
pip: 'PyPI',
|
|
27
|
+
packagist: 'Packagist',
|
|
28
|
+
php: 'Packagist',
|
|
29
|
+
composer: 'Packagist',
|
|
30
|
+
go: 'Go',
|
|
31
|
+
golang: 'Go',
|
|
32
|
+
maven: 'Maven',
|
|
33
|
+
java: 'Maven',
|
|
34
|
+
'crates.io': 'crates.io',
|
|
35
|
+
rust: 'crates.io',
|
|
36
|
+
cargo: 'crates.io',
|
|
37
|
+
rubygems: 'RubyGems',
|
|
38
|
+
ruby: 'RubyGems',
|
|
39
|
+
gem: 'RubyGems',
|
|
40
|
+
nuget: 'NuGet',
|
|
41
|
+
dotnet: 'NuGet',
|
|
42
|
+
'.net': 'NuGet',
|
|
43
|
+
hex: 'Hex',
|
|
44
|
+
erlang: 'Hex',
|
|
45
|
+
elixir: 'Hex',
|
|
46
|
+
pub: 'Pub',
|
|
47
|
+
dart: 'Pub',
|
|
48
|
+
flutter: 'Pub',
|
|
49
|
+
hackage: 'Hackage',
|
|
50
|
+
haskell: 'Hackage',
|
|
51
|
+
swifturl: 'SwiftURL',
|
|
52
|
+
swift: 'SwiftURL',
|
|
53
|
+
};
|
|
54
|
+
export function normalizeEcosystem(value) {
|
|
55
|
+
const ecosystem = Object.hasOwn(aliases, value.trim().toLowerCase())
|
|
56
|
+
? aliases[value.trim().toLowerCase()]
|
|
57
|
+
: undefined;
|
|
58
|
+
if (!ecosystem)
|
|
59
|
+
throw new Error(`Unsupported library ecosystem: ${value}`);
|
|
60
|
+
return ecosystem;
|
|
61
|
+
}
|
|
62
|
+
export function normalizePackageName(ecosystem, value) {
|
|
63
|
+
const name = value.trim();
|
|
64
|
+
let normalized = name;
|
|
65
|
+
let valid = name.length > 0 && name.length <= 500 && !/[\s\u0000-\u001f\u007f]/u.test(name);
|
|
66
|
+
switch (ecosystem) {
|
|
67
|
+
case 'npm':
|
|
68
|
+
valid &&= name.length <= 214 && /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(name);
|
|
69
|
+
break;
|
|
70
|
+
case 'PyPI':
|
|
71
|
+
valid &&= /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(name);
|
|
72
|
+
normalized = name.toLowerCase().replace(/[-_.]+/g, '-');
|
|
73
|
+
break;
|
|
74
|
+
case 'Packagist':
|
|
75
|
+
valid &&= /^[a-z0-9](?:[a-z0-9_.-]*[a-z0-9])?\/[a-z0-9](?:[a-z0-9_.-]*[a-z0-9])?$/.test(name);
|
|
76
|
+
break;
|
|
77
|
+
case 'Maven':
|
|
78
|
+
valid &&= /^[A-Za-z0-9_.-]+:[A-Za-z0-9_.-]+$/.test(name);
|
|
79
|
+
break;
|
|
80
|
+
case 'Go':
|
|
81
|
+
valid &&=
|
|
82
|
+
/^[A-Za-z0-9][A-Za-z0-9._~/-]*$/.test(name) &&
|
|
83
|
+
!name.split('/').some((p) => !p || p === '.' || p === '..');
|
|
84
|
+
break;
|
|
85
|
+
case 'NuGet':
|
|
86
|
+
valid &&= /^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(name);
|
|
87
|
+
break;
|
|
88
|
+
case 'crates.io':
|
|
89
|
+
valid &&= /^[A-Za-z][A-Za-z0-9_-]*$/.test(name);
|
|
90
|
+
normalized = name.toLowerCase();
|
|
91
|
+
break;
|
|
92
|
+
case 'SwiftURL':
|
|
93
|
+
try {
|
|
94
|
+
const url = new URL(name.startsWith('https://') ? name : `https://${name}`);
|
|
95
|
+
valid &&=
|
|
96
|
+
url.protocol === 'https:' &&
|
|
97
|
+
!url.username &&
|
|
98
|
+
!url.password &&
|
|
99
|
+
!url.port &&
|
|
100
|
+
!url.search &&
|
|
101
|
+
!url.hash &&
|
|
102
|
+
url.hostname.includes('.') &&
|
|
103
|
+
!/[\\%]/.test(name) &&
|
|
104
|
+
url.pathname !== '/' &&
|
|
105
|
+
!name
|
|
106
|
+
.replace(/^https:\/\//, '')
|
|
107
|
+
.split('/')
|
|
108
|
+
.some((part) => !part || part === '.' || part === '..');
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
valid = false;
|
|
112
|
+
}
|
|
113
|
+
break;
|
|
114
|
+
default:
|
|
115
|
+
valid &&= /^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(name);
|
|
116
|
+
}
|
|
117
|
+
if (!valid)
|
|
118
|
+
throw new Error(`Invalid ${ecosystem} package name: ${value}`);
|
|
119
|
+
return normalized;
|
|
120
|
+
}
|
|
121
|
+
function packageIdentity(ecosystem, name) {
|
|
122
|
+
const normalized = normalizePackageName(ecosystem, name);
|
|
123
|
+
if (ecosystem === 'NuGet')
|
|
124
|
+
return normalized.toLowerCase();
|
|
125
|
+
if (ecosystem === 'crates.io')
|
|
126
|
+
return normalized.replace(/_/g, '-');
|
|
127
|
+
if (ecosystem === 'SwiftURL') {
|
|
128
|
+
const url = new URL(normalized.startsWith('https://') ? normalized : `https://${normalized}`);
|
|
129
|
+
return `${url.hostname}${url.pathname.replace(/\.git$/, '')}`;
|
|
130
|
+
}
|
|
131
|
+
return normalized;
|
|
132
|
+
}
|
|
133
|
+
/** Keep the published spelling: OSV does not consistently normalize registry aliases. */
|
|
134
|
+
export function osvPackageNames(ecosystem, value) {
|
|
135
|
+
const name = normalizePackageName(ecosystem, value);
|
|
136
|
+
if (ecosystem === 'crates.io')
|
|
137
|
+
return [...new Set([name, name.replace(/_/g, '-'), name.replace(/-/g, '_')])];
|
|
138
|
+
if (ecosystem === 'NuGet')
|
|
139
|
+
return [...new Set([name, name.toLowerCase()])];
|
|
140
|
+
if (ecosystem === 'SwiftURL') {
|
|
141
|
+
const identity = packageIdentity(ecosystem, name);
|
|
142
|
+
return [
|
|
143
|
+
...new Set([name, identity, `${identity}.git`, `https://${identity}`, `https://${identity}.git`]),
|
|
144
|
+
];
|
|
145
|
+
}
|
|
146
|
+
return [name];
|
|
147
|
+
}
|
|
148
|
+
export function samePackage(left, right) {
|
|
149
|
+
try {
|
|
150
|
+
const ecosystem = normalizeEcosystem(left.ecosystem);
|
|
151
|
+
return (ecosystem === normalizeEcosystem(right.ecosystem) &&
|
|
152
|
+
packageIdentity(ecosystem, left.name) === packageIdentity(ecosystem, right.name));
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
return false;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/** A declared version, never a dependency constraint or an inferred latest release. */
|
|
159
|
+
export function exactLibraryVersion(value, ecosystem) {
|
|
160
|
+
const version = value.trim();
|
|
161
|
+
if (!version ||
|
|
162
|
+
version.length > 500 ||
|
|
163
|
+
!/^[A-Za-z0-9][A-Za-z0-9.!+_-]*$/.test(version) ||
|
|
164
|
+
/^(?:latest|\*)$/i.test(version))
|
|
165
|
+
throw new Error('Use an exact installed library version, or omit the version');
|
|
166
|
+
if (ecosystem &&
|
|
167
|
+
['npm', 'Go', 'crates.io', 'Hex', 'Pub', 'SwiftURL'].includes(ecosystem) &&
|
|
168
|
+
!valid(version))
|
|
169
|
+
throw new Error(`Use an exact installed ${ecosystem} version, or omit the version`);
|
|
170
|
+
// Validate PEP 440 syntax without ordering versions or rewriting the declared installation.
|
|
171
|
+
if (ecosystem === 'PyPI' &&
|
|
172
|
+
!/^v?(?:\d+!)?\d+(?:\.\d+)*(?:[-_.]?(?:alpha|beta|preview|pre|rc|a|b|c)[-_.]?\d*)?(?:-\d+|[-_.]?(?:post|rev|r)[-_.]?\d*)?(?:[-_.]?dev[-_.]?\d*)?(?:\+[a-z0-9]+(?:[-_.][a-z0-9]+)*)?$/i.test(version))
|
|
173
|
+
throw new Error('Use an exact installed Python version in PEP 440 syntax, or omit the version');
|
|
174
|
+
return version;
|
|
175
|
+
}
|
|
176
|
+
export function parseLibrary(value, defaultEcosystem) {
|
|
177
|
+
let ecosystem;
|
|
178
|
+
let name;
|
|
179
|
+
let version;
|
|
180
|
+
if (typeof value === 'string') {
|
|
181
|
+
let entry = value.trim();
|
|
182
|
+
if (defaultEcosystem)
|
|
183
|
+
ecosystem = normalizeEcosystem(defaultEcosystem);
|
|
184
|
+
else {
|
|
185
|
+
const separator = entry.indexOf(':');
|
|
186
|
+
if (separator < 1)
|
|
187
|
+
throw new Error('Library entries require an ecosystem prefix, such as python:requests');
|
|
188
|
+
ecosystem = normalizeEcosystem(entry.slice(0, separator));
|
|
189
|
+
entry = entry.slice(separator + 1).trim();
|
|
190
|
+
}
|
|
191
|
+
const parts = entry.split(/\s+/);
|
|
192
|
+
if (parts.length > 2)
|
|
193
|
+
throw new Error('Expected a library name and optional exact version');
|
|
194
|
+
if (parts.length === 2)
|
|
195
|
+
[name, version] = parts;
|
|
196
|
+
else if (ecosystem === 'PyPI' && entry.includes('==')) {
|
|
197
|
+
const split = entry.split('==');
|
|
198
|
+
if (split.length !== 2)
|
|
199
|
+
throw new Error('Expected one exact library version');
|
|
200
|
+
[name, version] = split;
|
|
201
|
+
}
|
|
202
|
+
else {
|
|
203
|
+
const separator = entry.lastIndexOf('@');
|
|
204
|
+
if (separator > 0)
|
|
205
|
+
[name, version] = [entry.slice(0, separator), entry.slice(separator + 1)];
|
|
206
|
+
else
|
|
207
|
+
name = entry;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
else if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
211
|
+
const input = value;
|
|
212
|
+
if (Object.keys(input).some((key) => !['name', 'version', 'ecosystem'].includes(key)) ||
|
|
213
|
+
typeof input.name !== 'string' ||
|
|
214
|
+
(input.version !== undefined && typeof input.version !== 'string') ||
|
|
215
|
+
(input.ecosystem !== undefined && typeof input.ecosystem !== 'string'))
|
|
216
|
+
throw new Error('Library objects accept name, optional version and ecosystem only');
|
|
217
|
+
if (!defaultEcosystem && typeof input.ecosystem !== 'string')
|
|
218
|
+
throw new Error('Library ecosystem is required');
|
|
219
|
+
ecosystem = normalizeEcosystem(defaultEcosystem ?? String(input.ecosystem));
|
|
220
|
+
if (input.ecosystem !== undefined && normalizeEcosystem(input.ecosystem) !== ecosystem)
|
|
221
|
+
throw new Error('Library ecosystem does not match its group');
|
|
222
|
+
name = input.name;
|
|
223
|
+
version = input.version;
|
|
224
|
+
}
|
|
225
|
+
else
|
|
226
|
+
throw new Error('Expected a library string or object');
|
|
227
|
+
return {
|
|
228
|
+
ecosystem,
|
|
229
|
+
name: normalizePackageName(ecosystem, name),
|
|
230
|
+
...(version === undefined ? {} : { version: exactLibraryVersion(version, ecosystem) }),
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
/** Parse one entry per line; the ecosystem is explicit or supplied for the whole list. */
|
|
234
|
+
export function parseLibraryList(text, ecosystem) {
|
|
235
|
+
if (ecosystem !== undefined)
|
|
236
|
+
normalizeEcosystem(ecosystem);
|
|
237
|
+
if (Buffer.byteLength(text, 'utf8') > 2 * 1024 * 1024)
|
|
238
|
+
throw new Error('Library list exceeds 2 MiB');
|
|
239
|
+
const entries = text
|
|
240
|
+
.split(/\r?\n/)
|
|
241
|
+
.map((line) => line.trim())
|
|
242
|
+
.filter((line) => line && !line.startsWith('#'));
|
|
243
|
+
if (entries.length > 20_000)
|
|
244
|
+
throw new Error('Library list exceeds 20000 entries');
|
|
245
|
+
const unique = new Map();
|
|
246
|
+
for (const entry of entries) {
|
|
247
|
+
const library = parseLibrary(entry, ecosystem);
|
|
248
|
+
unique.set(JSON.stringify(library), library);
|
|
249
|
+
}
|
|
250
|
+
return [...unique.values()].map((library) => ({
|
|
251
|
+
id: `library:${hash(JSON.stringify([library.ecosystem, library.name, library.version ?? null])).slice(0, 24)}`,
|
|
252
|
+
...library,
|
|
253
|
+
}));
|
|
254
|
+
}
|