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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/CHANGELOG.md +178 -0
  2. package/CONTRIBUTING.md +4 -2
  3. package/README.md +173 -48
  4. package/SECURITY.md +24 -9
  5. package/dist/assessment.d.ts +12 -1
  6. package/dist/assessment.js +223 -52
  7. package/dist/cli.js +340 -27
  8. package/dist/config.d.ts +62 -2
  9. package/dist/config.js +88 -5
  10. package/dist/coverage.d.ts +4 -0
  11. package/dist/coverage.js +11 -0
  12. package/dist/cve-now.d.ts +32 -2
  13. package/dist/cve-now.js +715 -126
  14. package/dist/cvss4.d.ts +3 -0
  15. package/dist/cvss4.js +39 -0
  16. package/dist/delivery.d.ts +34 -2
  17. package/dist/delivery.js +391 -98
  18. package/dist/ecosystems.d.ts +23 -0
  19. package/dist/ecosystems.js +88 -10
  20. package/dist/engine.d.ts +55 -1
  21. package/dist/engine.js +101 -20
  22. package/dist/everyday-words.d.ts +11 -0
  23. package/dist/everyday-words.js +256 -0
  24. package/dist/health.d.ts +7 -0
  25. package/dist/health.js +55 -3
  26. package/dist/http.d.ts +7 -0
  27. package/dist/http.js +31 -2
  28. package/dist/index.d.ts +22 -4
  29. package/dist/index.js +12 -4
  30. package/dist/inventory-evidence.d.ts +10 -0
  31. package/dist/inventory-evidence.js +206 -0
  32. package/dist/inventory.d.ts +273 -0
  33. package/dist/inventory.js +210 -17
  34. package/dist/maintenance.d.ts +5 -0
  35. package/dist/maintenance.js +73 -5
  36. package/dist/matching.d.ts +29 -0
  37. package/dist/matching.js +537 -0
  38. package/dist/models.d.ts +17 -4
  39. package/dist/models.js +359 -29
  40. package/dist/pilot-cases.d.ts +171 -0
  41. package/dist/pilot-cases.js +330 -0
  42. package/dist/pilot-input.d.ts +16 -0
  43. package/dist/pilot-input.js +125 -0
  44. package/dist/pilot-recall.d.ts +166 -0
  45. package/dist/pilot-recall.js +231 -0
  46. package/dist/pilot-report.d.ts +113 -0
  47. package/dist/pilot-report.js +279 -0
  48. package/dist/pilot-responses.d.ts +111 -0
  49. package/dist/pilot-responses.js +159 -0
  50. package/dist/python-version.d.ts +3 -0
  51. package/dist/python-version.js +30 -0
  52. package/dist/rehearsal.d.ts +440 -0
  53. package/dist/rehearsal.js +372 -0
  54. package/dist/sbom.d.ts +13 -0
  55. package/dist/sbom.js +193 -0
  56. package/dist/source-error.d.ts +17 -1
  57. package/dist/source-error.js +18 -3
  58. package/dist/sources.d.ts +2 -2
  59. package/dist/sources.js +699 -45
  60. package/dist/store.d.ts +38 -13
  61. package/dist/store.js +325 -23
  62. package/dist/types.d.ts +159 -2
  63. package/dist/util.d.ts +23 -0
  64. package/dist/util.js +81 -1
  65. package/dist/vendor/cvss4-reference.d.ts +2 -0
  66. package/dist/vendor/cvss4-reference.js +789 -0
  67. package/dist/word-filter.d.ts +3 -0
  68. package/dist/word-filter.js +3291 -0
  69. package/docs/alert-outcome-evaluation.md +150 -0
  70. package/docs/compatibility.md +35 -0
  71. package/docs/configuration.md +289 -29
  72. package/docs/cvss-v4-support.md +41 -0
  73. package/docs/offline-advisory-preview.md +114 -0
  74. package/docs/offline-rehearsal.md +44 -0
  75. package/docs/pilot-cases.md +58 -0
  76. package/docs/pilot-recall.md +124 -0
  77. package/docs/pilot-report.md +52 -0
  78. package/docs/validation/alert-outcome-evaluation-2026-11-05.json +2935 -0
  79. package/docs/validation/cvss-v4-reference-parity-2026-11-05.json +93 -0
  80. package/docs/validation/rehearsal-accepted-2026-11-05.json +175 -0
  81. package/docs/validation/rehearsal-unknown-2026-11-05.json +175 -0
  82. package/docs/vendor/cvss-v4-LICENSE.txt +22 -0
  83. package/docs/vendor/cvss-v4-provenance.json +38 -0
  84. package/examples/agent-advisories-2026.json +145 -0
  85. package/examples/agent-advisory-cases-2026.json +397 -0
  86. package/examples/libraries.example.txt +4 -2
  87. package/examples/libraries.example.yaml +2 -0
  88. package/examples/offline-advisory-preview.mjs +42 -0
  89. package/examples/rehearsal.json +75 -0
  90. package/examples/systems.example.yaml +4 -0
  91. package/package.json +24 -7
  92. package/docs/quality-review.md +0 -104
package/dist/delivery.js CHANGED
@@ -1,14 +1,55 @@
1
1
  import nodemailer from 'nodemailer';
2
2
  import { createConnection } from 'node:net';
3
- import { cleanText } from './util.js';
3
+ import { FILLERS, INVISIBLE, cleanText, cut, singleLine } from './util.js';
4
4
  import { decide } from './assessment.js';
5
5
  import { Store } from './store.js';
6
6
  import { NetworkError } from './http.js';
7
- class EmailConnectionError extends Error {
8
- constructor() {
9
- super('SMTP connection failed before sending');
7
+ /**
8
+ * The message provably never reached the mail server: the failure happened before the client wrote
9
+ * `MAIL FROM`. Only this error (or an explicit SMTP status) lets a job be retried automatically.
10
+ */
11
+ class EmailNotSentError extends Error {
12
+ stage;
13
+ constructor(stage) {
14
+ super(stage === 'connection'
15
+ ? 'SMTP connection failed before sending'
16
+ : 'SMTP TLS or sign-in failed before sending');
17
+ this.stage = stage;
10
18
  }
11
19
  }
20
+ /**
21
+ * What the mail transport's transaction log shows about one SMTP session. "No MAIL FROM was logged"
22
+ * proves that none was written only if the log reports what the client writes. That is shown by a
23
+ * logged client command (its EHLO comes before anything else), or by a session that ended before
24
+ * the server said anything (a refused connection, a failed TLS handshake), where there was nothing
25
+ * to write. Server replies without any client command mean the log cannot be relied on.
26
+ */
27
+ export function smtpTranscript() {
28
+ let logged = false;
29
+ let clientSeen = false;
30
+ let serverSeen = false;
31
+ let notSmtp = false;
32
+ let envelopeStarted = false;
33
+ return {
34
+ observe(entry, line) {
35
+ logged = true;
36
+ const side = typeof entry === 'object' && entry !== null && 'tnx' in entry ? entry.tnx : undefined;
37
+ // A first line from the server that is not an SMTP reply ("* OK IMAP ready", "SSH-2.0") is
38
+ // another service on that port: an SMTP client writes nothing to it.
39
+ if (side === 'server' && !serverSeen && !/^\d{3}(?:[ -]|$)/.test(String(line).trim()))
40
+ notSmtp = true;
41
+ if (side === 'server')
42
+ serverSeen = true;
43
+ if (side !== 'client')
44
+ return;
45
+ clientSeen = true;
46
+ if (/^\s*(?:MAIL|RCPT|DATA|BDAT)\b/i.test(String(line)))
47
+ envelopeStarted = true;
48
+ },
49
+ envelopeStarted: () => envelopeStarted,
50
+ nothingHandedOver: () => logged && !envelopeStarted && (clientSeen || !serverSeen || notSmtp),
51
+ };
52
+ }
12
53
  export const sendEmail = async (message) => {
13
54
  message.signal?.throwIfAborted();
14
55
  const url = new URL(message.url);
@@ -18,7 +59,23 @@ export const sendEmail = async (message) => {
18
59
  (url.pathname && url.pathname !== '/'))
19
60
  throw new Error('Invalid SMTP configuration');
20
61
  let socket;
62
+ // The transport labels every socket error, timeout and unexpected close the same way at any stage,
63
+ // including after the message body was transferred. The only proof that nothing was handed over is
64
+ // that the client never wrote MAIL FROM, so the conversation is observed through the transport's
65
+ // own transaction log.
66
+ const transcript = smtpTranscript();
67
+ const observe = transcript.observe;
21
68
  const transport = nodemailer.createTransport({
69
+ logger: {
70
+ level: () => undefined,
71
+ trace: observe,
72
+ debug: observe,
73
+ info: observe,
74
+ warn: observe,
75
+ error: observe,
76
+ fatal: observe,
77
+ },
78
+ debug: true,
22
79
  host: url.hostname.replace(/^\[|\]$/g, ''),
23
80
  port: Number(url.port || (url.protocol === 'smtps:' ? 465 : 587)),
24
81
  secure: url.protocol === 'smtps:',
@@ -49,7 +106,7 @@ export const sendEmail = async (message) => {
49
106
  socket.once('close', () => clearTimeout(deadline));
50
107
  socket.once('error', () => {
51
108
  if (!connected)
52
- callback(new EmailConnectionError(), {});
109
+ callback(new EmailNotSentError('connection'), {});
53
110
  });
54
111
  socket.once('connect', () => {
55
112
  connected = true;
@@ -79,6 +136,15 @@ export const sendEmail = async (message) => {
79
136
  const result = await Promise.race([sending, cancelled]);
80
137
  return { accepted: result.accepted.map(String), rejected: result.rejected.map(String) };
81
138
  }
139
+ catch (error) {
140
+ // A reply code from the server is passed on as it is: the caller decides from the code.
141
+ if (message.signal?.aborted ||
142
+ error instanceof EmailNotSentError ||
143
+ statusCode(error) !== undefined ||
144
+ !transcript.nothingHandedOver())
145
+ throw error;
146
+ throw new EmailNotSentError('session');
147
+ }
82
148
  finally {
83
149
  if (abort)
84
150
  message.signal?.removeEventListener('abort', abort);
@@ -86,68 +152,228 @@ export const sendEmail = async (message) => {
86
152
  socket?.destroy();
87
153
  }
88
154
  };
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);
155
+ function safeText(input, length, mentions = true) {
156
+ // The length is applied last: what is removed or reduced below must not count against it.
157
+ // Fillers become spaces and characters that show as nothing are removed before any limit is
158
+ // applied, so that they cannot push the visible end of a value past it. Some fillers count as
159
+ // default-ignorable, so they are turned into spaces first; the removal comes before spaces are
160
+ // counted, so that spaces they separated are one run.
161
+ const cleaned = cleanText(input.replace(FILLERS, ' ').replace(/[\r]/g, '').replace(INVISIBLE, ''), Math.max(length, 4000))
162
+ // A lone half of a surrogate pair is not text; services may refuse a message that has one.
163
+ .replace(/\p{Cs}/gu, '\ufffd')
164
+ // A run of blanks moves what follows as far as a line break would.
165
+ .replace(/[^\S\n]{2,}/g, ' ')
166
+ .trim();
167
+ // A value that does not fit ends with "…", so a reader never takes a cut value for a whole one
168
+ // ("8.0.3" for "8.0.39"). An emoji is never cut in half.
169
+ const fitted = cleaned.length <= length ? cleaned : `${cut(cleaned, length - 1).trimEnd()}…`;
170
+ // Only a word Slack treats as a group mention ("@channel", "@here", "@everyone", "@group") gets
171
+ // an invisible break; "express@4.21.2" and "@angular/core" stay exactly as written, so they can
172
+ // be copied and searched for. It is added after the cut: cutting "@channels" to "@channel…"
173
+ // makes a mention of what was none.
174
+ return mentions ? fitted.replace(GROUP_MENTION, '@\u200b') : fitted;
175
+ }
176
+ /** "@" before a word Slack treats as a group mention, in any letter case. */
177
+ const GROUP_MENTION = /@(?=(?:channel|here|everyone|group)(?![\p{L}\p{N}_]))/giu;
178
+ /**
179
+ * One value for one line of a message. Advisory text, model output and inventory names are placed
180
+ * after fixed labels such as `Rule:` and `Where to look:`; a line break inside a value would let it
181
+ * forge the next label, so every break becomes a space, and a run of blank characters, which can
182
+ * push the rest of a value onto what looks like a line of its own, becomes one space.
183
+ */
184
+ function single(value, length) {
185
+ return safeText(singleLine(value), length);
186
+ }
187
+ /**
188
+ * A source link, kept exactly: a shortened link is a different address, so one that is too long is
189
+ * left out, and nothing is inserted into it.
190
+ */
191
+ function link(value) {
192
+ const written = value.trim();
193
+ const cleaned = safeText(singleLine(written), 2000, false);
194
+ // Shown only exactly as written: a link from which a character had to be removed (an invisible
195
+ // mark, a line break) is another address, and so is a shortened one.
196
+ // A link is never altered, so one with a group mention in it ("…/@channel") is left out too.
197
+ return cleaned === written &&
198
+ cleaned.length <= 320 &&
199
+ !/\s/.test(cleaned) &&
200
+ !new RegExp(GROUP_MENTION.source, 'iu').test(cleaned)
201
+ ? cleaned
202
+ : undefined;
203
+ }
204
+ /** A list from a model, each entry whole: as many as fit, then how many more there are. */
205
+ function listLine(label, items, length) {
206
+ const values = items.map((item) => single(item, 4000)).filter(Boolean);
207
+ if (!values.length)
208
+ return `${label}: Not established`;
209
+ const shown = [];
210
+ let used = 0;
211
+ for (const value of values) {
212
+ if (value.length > length || (shown.length && used + value.length + 2 > length))
213
+ break;
214
+ shown.push(value);
215
+ used += value.length + 2;
216
+ }
217
+ const more = values.length - shown.length;
218
+ return `${label}: ${shown.join('; ')}${more ? `${shown.length ? '; ' : ''}and ${more} more` : ''}`;
219
+ }
220
+ /** The operator's own inventory names and notes, so the reader knows where to check. */
221
+ function locationLines(a, length) {
222
+ const where = a.location;
223
+ if (!where)
224
+ return [];
225
+ // With no room for notes (length 0) the names alone are shown.
226
+ const note = (value) => (value && length ? ` - ${single(value, length)}` : '');
227
+ return [
228
+ `Where to look: ${single(where.system, 120)}${where.owner ? ` (owner: ${single(where.owner, 80)})` : ''}${note(where.system_note)}`,
229
+ ...(where.component
230
+ ? [`Affected item: ${single(where.component, 160)}${note(where.component_note)}`]
231
+ : []),
232
+ ];
233
+ }
234
+ const webUrl = (value) => {
235
+ try {
236
+ return ['https:', 'http:'].includes(new URL(value).protocol);
237
+ }
238
+ catch {
239
+ return false;
240
+ }
241
+ };
242
+ /**
243
+ * The fixed versions, each whole. Many fixed branches (or Go pseudo-versions) can be long: as many
244
+ * whole versions as fit are shown, and the line says how many more there are.
245
+ */
246
+ function fixLine(fix) {
247
+ // Versions of one claim are joined with commas, versions of different claims with semicolons.
248
+ const versions = singleLine(fix, fix.length)
249
+ .split(/[;,]\s*/)
250
+ .map((version) => single(version, 4000))
251
+ .filter(Boolean);
252
+ const shown = [];
253
+ let length = 0;
254
+ for (const version of versions) {
255
+ // A version is never shown cut: one that is too long on its own is counted with the rest, and
256
+ // the shorter ones after it are still shown.
257
+ if (version.length > 120)
258
+ continue;
259
+ if (length + version.length + 2 > 300)
260
+ break;
261
+ shown.push(version);
262
+ length += version.length + 2;
263
+ }
264
+ const more = versions.length - shown.length;
265
+ if (!shown.length)
266
+ return `Fix: ${versions.length} version(s) too long to show (run explain for all)`;
267
+ return `Fix: ${shown.join('; ')}${more ? `; and ${more} more (run explain for all)` : ''}`;
94
268
  }
269
+ /** One Slack section holds 3,000 characters. */
270
+ const MESSAGE_LIMIT = 2900;
95
271
  export function notificationText(job) {
96
272
  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 = [
273
+ const subject = single(`[${a.priority.toUpperCase()}] ${a.title}`, 180);
274
+ const urls = a.urls.filter(webUrl);
275
+ /** The lines every message keeps: what, where, how it applies and the summary. */
276
+ const head = (notes) => [
107
277
  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}`,
278
+ `Finding: ${single(a.id, 200)}`,
279
+ `Delivery: ${single(job.id, 200)}`,
280
+ `System: ${single(a.system_id, 200)}${a.component_id ? ` / ${single(a.component_id, 200)}` : ''}`,
281
+ ...locationLines(a, notes ? 300 : 0),
282
+ `Applicability: ${single(a.applicability, 40)}; source severity: ${single(a.source_severity, 40)}; priority: ${single(a.priority, 40)}`,
283
+ ...(a.exploited ? ['Known exploitation reported.'] : []),
284
+ `Summary: ${single(a.summary, 750)}`,
285
+ ];
286
+ // In the order they give way when the text is too long for one Slack section: the last of these
287
+ // lines are dropped first, and a line is never cut in the middle.
288
+ const extra = [
112
289
  ...(a.news_analysis
113
290
  ? [
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)}`,
291
+ `AI news classification: ${single(a.news_analysis.classification, 60)}; reported system impact: ${single(a.news_analysis.impact, 60)}`,
292
+ listLine('Affected products', a.news_analysis.affected_products, 180),
293
+ listLine('Reported versions', a.news_analysis.affected_versions, 180),
294
+ listLine('Prerequisites', a.news_analysis.prerequisites, 240),
295
+ `Impact reasoning: ${single(a.news_analysis.rationale, 400)}`,
119
296
  ]
120
297
  : []),
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)),
298
+ // Every reason: when there are more than fit, the last ones are left out with the note below.
299
+ ...a.reasons.map((r) => `• ${single(r, 180)}`),
300
+ ];
301
+ // The fix, the rule that sent the message and the time close every message, whole, followed by
302
+ // up to three source links.
303
+ const tail = [
304
+ ...(a.fix ? [fixLine(a.fix)] : []),
305
+ `Rule: ${single(reason, 180)}`,
306
+ `Assessment time: ${single(a.updated_at, 40)}`,
128
307
  ];
129
- return { subject, text: safeText(lines.join('\n'), 2900) };
308
+ const links = urls
309
+ .map(link)
310
+ .filter((value) => value !== undefined)
311
+ .slice(0, 3);
312
+ const SHORTENED = '(Message shortened; run explain for the full finding.)';
313
+ const size = (lines) => lines.reduce((total, line) => total + line.length + 1, 0) - 1;
314
+ const full = [...head(true), ...extra, ...tail, ...links];
315
+ // Everything fits: no note.
316
+ if (size(full) <= MESSAGE_LIMIT)
317
+ return { subject, text: full.join('\n') };
318
+ // Otherwise the analysis and reasons give way first, whole lines from the end. Only when the
319
+ // lines every message keeps still do not fit do the source links go, the last first, and then the
320
+ // inventory notes.
321
+ const rounds = [
322
+ ...Array.from({ length: links.length + 1 }, (_, index) => [
323
+ true,
324
+ links.length - index,
325
+ ]),
326
+ [false, 0],
327
+ ];
328
+ for (const [notes, count] of rounds) {
329
+ const fixed = [...head(notes), SHORTENED, ...tail, ...links.slice(0, count)];
330
+ let left = MESSAGE_LIMIT - size(fixed);
331
+ if (left < 0)
332
+ continue;
333
+ const kept = [];
334
+ for (const line of extra) {
335
+ if (line.length + 1 > left)
336
+ break;
337
+ kept.push(line);
338
+ left -= line.length + 1;
339
+ }
340
+ return {
341
+ subject,
342
+ text: [...head(notes), ...kept, SHORTENED, ...tail, ...links.slice(0, count)].join('\n'),
343
+ };
344
+ }
345
+ // Only identifiers at their longest get here: the summary is cut until the message fits.
346
+ const lines = head(false).slice(0, -1);
347
+ const message = (cap) => [...lines, `Summary: ${single(a.summary, cap)}`, SHORTENED, ...tail].join('\n');
348
+ let cap = 750;
349
+ let text = message(cap);
350
+ while (text.length > MESSAGE_LIMIT && cap > 1) {
351
+ cap = Math.max(1, cap - (text.length - MESSAGE_LIMIT));
352
+ text = message(cap);
353
+ }
354
+ return { subject, text };
130
355
  }
131
356
  function digestText(jobs) {
132
357
  const subject = `Security Watch digest: ${jobs.length} findings`;
133
358
  const entries = jobs.map((job) => {
134
359
  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)}`);
360
+ return [
361
+ `[${single(a.priority, 40).toUpperCase()}] ${single(a.title, 90)}`,
362
+ `Finding: ${single(a.id, 200)}`,
363
+ `Delivery: ${single(job.id, 200)}`,
364
+ `System: ${single(a.system_id, 60)}${a.component_id ? ` / ${single(a.component_id, 60)}` : ''}`,
365
+ ...locationLines(a, 120),
366
+ `Applicability: ${single(a.applicability, 40)}; source: ${single(a.source_severity, 40)}`,
367
+ ...(a.news_analysis
368
+ ? [
369
+ `AI news: ${single(a.news_analysis.classification, 60)}; impact: ${single(a.news_analysis.impact, 60)}`,
370
+ ]
371
+ : []),
372
+ a.urls
373
+ .filter(webUrl)
374
+ .map(link)
375
+ .find((value) => value !== undefined) ?? 'No source URL supplied',
376
+ ].join('\n');
151
377
  });
152
378
  return { subject, text: `${subject}\n\n${entries.join('\n\n')}` };
153
379
  }
@@ -159,14 +385,73 @@ function retryAt(headers, now, attempts) {
159
385
  ? Math.min(now + 86_400_000, Math.max(now + 1000, retry))
160
386
  : now + Math.min(3_600_000, 30_000 * 2 ** Math.min(attempts - 1, 7));
161
387
  }
388
+ /**
389
+ * A reason the SMTP address cannot be used, found without connecting. A user name or password
390
+ * containing %, @, : or / must be percent-encoded (a literal % is written %25).
391
+ */
392
+ /** Why a Slack webhook address cannot be used, or nothing. The text never repeats the address. */
393
+ export function slackProblem(address) {
394
+ try {
395
+ const url = new URL(address);
396
+ return url.protocol !== 'https:' ||
397
+ url.hostname !== 'hooks.slack.com' ||
398
+ !url.pathname.startsWith('/services/') ||
399
+ url.username ||
400
+ url.password ||
401
+ url.search ||
402
+ url.hash ||
403
+ (url.port && url.port !== '443')
404
+ ? 'Slack webhook must be an HTTPS hooks.slack.com/services URL'
405
+ : undefined;
406
+ }
407
+ catch {
408
+ return 'Slack webhook URL is invalid';
409
+ }
410
+ }
411
+ export function smtpProblem(address) {
412
+ try {
413
+ const url = new URL(address);
414
+ if (!['smtp:', 'smtps:'].includes(url.protocol) ||
415
+ !url.hostname ||
416
+ url.search ||
417
+ url.hash ||
418
+ (url.pathname && url.pathname !== '/'))
419
+ return 'Invalid SMTP configuration';
420
+ decodeURIComponent(url.username);
421
+ decodeURIComponent(url.password);
422
+ }
423
+ catch {
424
+ return 'Invalid SMTP configuration: the address is not a valid smtp:// or smtps:// URL, or its user name or password is not percent-encoded';
425
+ }
426
+ return undefined;
427
+ }
428
+ function mailbox(address) {
429
+ const at = address.lastIndexOf('@');
430
+ return at < 0 ? address : `${address.slice(0, at)}@${address.slice(at + 1).toLowerCase()}`;
431
+ }
162
432
  function statusCode(error) {
163
433
  if (typeof error !== 'object' || error === null || !('responseCode' in error))
164
434
  return undefined;
165
435
  const code = Number(error.responseCode);
166
436
  return Number.isFinite(code) ? code : undefined;
167
437
  }
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) {
438
+ /**
439
+ * Sends due jobs; "accepted" means the destination accepted the request, not that a human read it.
440
+ * Pass the optional settings as one object. The positional form is kept for existing callers.
441
+ */
442
+ export async function deliverPending(store, config, http, options, positionalSender, positionalSignal, positionalCredentials) {
443
+ const settings = typeof options === 'object'
444
+ ? options
445
+ : {
446
+ ...(options === undefined ? {} : { now: options }),
447
+ ...(positionalSender ? { emailSender: positionalSender } : {}),
448
+ ...(positionalSignal ? { signal: positionalSignal } : {}),
449
+ ...(positionalCredentials ? { credentials: positionalCredentials } : {}),
450
+ };
451
+ const now = settings.now ?? Date.now();
452
+ const emailSender = settings.emailSender ?? sendEmail;
453
+ const signal = settings.signal;
454
+ const credentials = settings.credentials ?? process.env;
170
455
  const result = { accepted: 0, failed: 0, unknown: 0 };
171
456
  let job;
172
457
  const started = Date.now();
@@ -240,20 +525,46 @@ export async function deliverPending(store, config, http, now = Date.now(), emai
240
525
  continue;
241
526
  }
242
527
  const item = batch[0];
528
+ const ids = batch.map((entry) => entry.id);
529
+ // Another handle on the same database can take a job back while it is being sent. The outcome
530
+ // can then no longer be recorded as usual; keep the worker running and never resend silently.
531
+ const displaced = (error, sent) => {
532
+ if (!(error instanceof Error) || error.message !== 'Notification is not in flight')
533
+ throw error;
534
+ if (sent)
535
+ store.markUncertain(ids, 'The delivery result could not be recorded because the job was changed while it was being sent. Verify receipt before retrying.');
536
+ result.unknown += batch.length;
537
+ };
243
538
  const finish = (status, message) => {
244
- for (const entry of batch) {
245
- store.completeJob(entry.id, status, now, message);
246
- result[status]++;
539
+ // Sample once per acknowledgement so every item in an accepted digest shares its receipt time.
540
+ const received = status === 'accepted' ? Date.now() : undefined;
541
+ const acceptedAt = received !== undefined && received >= now ? received : undefined;
542
+ try {
543
+ store.completeBatch(ids, status, now, message, acceptedAt);
544
+ }
545
+ catch (error) {
546
+ displaced(error, status !== 'failed');
547
+ return;
247
548
  }
549
+ result[status] += batch.length;
248
550
  };
249
551
  const retry = (message, at) => {
250
552
  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++;
553
+ try {
554
+ if (entry.attempts >= config.notifications.max_attempts) {
555
+ store.completeJob(entry.id, 'failed', now, `${message}; retry limit reached`);
556
+ result.failed++;
557
+ }
558
+ else if ((store.revisionOf(entry.finding_id) ?? 0) > (entry.revision ?? Infinity))
559
+ // A newer revision was saved while this one was being sent; it carries its own job.
560
+ store.completeJob(entry.id, 'failed', now, 'Superseded by a newer assessment');
561
+ else
562
+ store.completeJob(entry.id, 'pending', at, message);
563
+ }
564
+ catch (error) {
565
+ displaced(error, false);
566
+ return;
254
567
  }
255
- else
256
- store.completeJob(entry.id, 'pending', at, message);
257
568
  }
258
569
  };
259
570
  let text;
@@ -266,27 +577,14 @@ export async function deliverPending(store, config, http, now = Date.now(), emai
266
577
  }
267
578
  if (item.channel === 'slack') {
268
579
  const settings = config.notifications.slack;
269
- const secret = settings ? process.env[settings.webhook_url_env] : undefined;
580
+ const secret = settings ? credentials[settings.webhook_url_env] : undefined;
270
581
  if (!secret) {
271
582
  finish('failed', 'Slack destination is not configured');
272
583
  continue;
273
584
  }
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');
585
+ const problem = slackProblem(secret);
586
+ if (problem) {
587
+ finish('failed', problem);
290
588
  continue;
291
589
  }
292
590
  const nextSlackAt = Number(store.getMeta('delivery:slack:next_at') ?? 0);
@@ -330,7 +628,8 @@ export async function deliverPending(store, config, http, now = Date.now(), emai
330
628
  catch (error) {
331
629
  if (!signal?.aborted &&
332
630
  error instanceof NetworkError &&
333
- ['DNS_FAILED', 'CONNECTION_FAILED'].includes(error.code))
631
+ // Refused before any connection was made: nothing left this machine.
632
+ ['DNS_FAILED', 'CONNECTION_FAILED', 'DESTINATION_DENIED'].includes(error.code))
334
633
  retry('Slack connection failed before sending', retryAt({}, now, item.attempts));
335
634
  else
336
635
  finish('unknown', 'Slack delivery interrupted; receipt is unknown. Verify the destination before retrying.');
@@ -338,23 +637,14 @@ export async function deliverPending(store, config, http, now = Date.now(), emai
338
637
  }
339
638
  else {
340
639
  const settings = config.notifications.email;
341
- const secret = settings ? process.env[settings.smtp_url_env] : undefined;
640
+ const secret = settings ? credentials[settings.smtp_url_env] : undefined;
342
641
  if (!settings || !secret) {
343
642
  finish('failed', 'Email destination is not configured');
344
643
  continue;
345
644
  }
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');
645
+ const problem = smtpProblem(secret);
646
+ if (problem) {
647
+ finish('failed', problem);
358
648
  continue;
359
649
  }
360
650
  try {
@@ -366,8 +656,9 @@ export async function deliverPending(store, config, http, now = Date.now(), emai
366
656
  text: text.text,
367
657
  signal,
368
658
  });
369
- const expected = new Set(settings.to);
370
- const accepted = new Set(receipt.accepted);
659
+ // Mail servers and clients lower-case the domain; the mailbox part is left as written.
660
+ const expected = new Set(settings.to.map(mailbox));
661
+ const accepted = new Set(receipt.accepted.map(mailbox));
371
662
  if (!receipt.rejected.length &&
372
663
  accepted.size === expected.size &&
373
664
  [...expected].every((address) => accepted.has(address)))
@@ -379,8 +670,10 @@ export async function deliverPending(store, config, http, now = Date.now(), emai
379
670
  }
380
671
  catch (error) {
381
672
  const code = statusCode(error);
382
- if (!signal?.aborted && error instanceof EmailConnectionError)
383
- retry('SMTP connection failed before sending', retryAt({}, now, item.attempts));
673
+ // Only a failure the sender proved to precede the envelope is retried. Error labels alone
674
+ // do not prove it: a dropped connection after the message body carries the same label.
675
+ if (!signal?.aborted && error instanceof EmailNotSentError)
676
+ retry(error.message, retryAt({}, now, item.attempts));
384
677
  else if (code && code >= 400 && code < 500)
385
678
  retry(`SMTP rejected request with status ${code}`, retryAt({}, now, item.attempts));
386
679
  else if (code && code >= 500 && code < 600)
@@ -6,6 +6,11 @@ export declare function normalizeEcosystem(value: string): Ecosystem;
6
6
  export declare function normalizePackageName(ecosystem: Ecosystem, value: string): string;
7
7
  /** Keep the published spelling: OSV does not consistently normalize registry aliases. */
8
8
  export declare function osvPackageNames(ecosystem: Ecosystem, value: string): string[];
9
+ /** One comparable key per package identity, or undefined when the ecosystem or name is not recognised. */
10
+ export declare function packageKey(value: {
11
+ ecosystem: string;
12
+ name: string;
13
+ }): string | undefined;
9
14
  export declare function samePackage(left: {
10
15
  ecosystem: string;
11
16
  name: string;
@@ -15,11 +20,29 @@ export declare function samePackage(left: {
15
20
  }): boolean;
16
21
  /** A declared version, never a dependency constraint or an inferred latest release. */
17
22
  export declare function exactLibraryVersion(value: string, ecosystem?: Ecosystem): string;
23
+ /**
24
+ * What to tell the operator about a name typed by hand with capital letters, in a registry that
25
+ * compares names by exact spelling and publishes them in lower case. npm: every name registered
26
+ * since 2017 is lower case, so `Lodash` is not `lodash` and matches no advisory; a few packages
27
+ * from before that rule keep their capitals, so the name is accepted, and anything but a known
28
+ * legacy name is pointed out. RubyGems, Hex and Pub: `Rails`, `Phoenix` and `Flutter_Bloc` are not
29
+ * the published `rails`, `phoenix` and `flutter_bloc`.
30
+ */
31
+ export declare function capitalisedName(component: {
32
+ ecosystem: Ecosystem;
33
+ name: string;
34
+ }): string | undefined;
18
35
  export interface Library {
19
36
  ecosystem: Ecosystem;
20
37
  name: string;
21
38
  version?: string;
39
+ /** Where this library is used, in the operator's words. */
40
+ note?: string;
22
41
  }
42
+ /** A short, single-line pointer written by the operator, such as a service, repository path or owner. */
43
+ export declare function libraryNote(value: string): string;
44
+ /** Keep each distinct note once, in the order given, within the note length limit. */
45
+ export declare function mergeNotes(first: string | undefined, second: string | undefined): string | undefined;
23
46
  export declare function parseLibrary(value: unknown, defaultEcosystem?: string): Library;
24
47
  /** Parse one entry per line; the ecosystem is explicit or supplied for the whole list. */
25
48
  export declare function parseLibraryList(text: string, ecosystem?: string): Component[];