@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
@@ -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
+ }
package/dist/health.d.ts CHANGED
@@ -13,5 +13,12 @@ export interface HealthReport {
13
13
  overdue_pending: number;
14
14
  };
15
15
  }
16
+ /**
17
+ * Since when a worker starting at `startedAt` has been catching up without recording a scan. It is
18
+ * kept across restarts until a scan is recorded, so a worker killed during every scan cannot renew
19
+ * its startup grace by restarting; a restart after a recorded scan starts afresh. The time between
20
+ * the previous worker's last sign of life and this start does not count.
21
+ */
22
+ export declare function catchingUpFrom(store: Store, startedAt: string): string;
16
23
  /** Read-only monitoring health check; does not assess system security or make network requests. */
17
24
  export declare function checkHealth(store: Store, config: Config, now?: number, requireWorker?: boolean): HealthReport;
package/dist/health.js CHANGED
@@ -1,4 +1,8 @@
1
1
  import { Store } from './store.js';
2
+ /** How long a running worker may take over its first scan before health reports none. */
3
+ const FIRST_SCAN_GRACE = 3_600_000;
4
+ /** How long a worker that died may have run after its last heartbeat (written every 15 seconds). */
5
+ const CRASH_MARGIN = 60_000;
2
6
  function object(value) {
3
7
  if (!value)
4
8
  return undefined;
@@ -15,6 +19,34 @@ function object(value) {
15
19
  function time(value) {
16
20
  return typeof value === 'string' ? Date.parse(value) : NaN;
17
21
  }
22
+ /**
23
+ * Since when a worker starting at `startedAt` has been catching up without recording a scan. It is
24
+ * kept across restarts until a scan is recorded, so a worker killed during every scan cannot renew
25
+ * its startup grace by restarting; a restart after a recorded scan starts afresh. The time between
26
+ * the previous worker's last sign of life and this start does not count.
27
+ */
28
+ export function catchingUpFrom(store, startedAt) {
29
+ try {
30
+ const previous = JSON.parse(store.getMeta('worker') ?? 'null');
31
+ const scan = JSON.parse(store.getMeta('last_scan') ?? 'null');
32
+ const since = time(previous?.catching_up_since);
33
+ const scanned = time(scan?.at);
34
+ const seen = Math.max(...[time(previous?.heartbeat_at), time(previous?.started_at)].filter(Number.isFinite));
35
+ const start = Date.parse(startedAt);
36
+ if (!Number.isFinite(since) || since > start || scanned >= since)
37
+ return startedAt;
38
+ // Only running time counts: the time the worker was stopped moves the start forward. A clean stop
39
+ // records its last moment. A worker that died may have run up to a heartbeat interval past its
40
+ // last heartbeat, so that much more of the gap counts as running: a crash loop, down for seconds,
41
+ // cannot renew the grace however soon it dies.
42
+ const gap = Number.isFinite(seen) && seen >= since && seen <= start ? start - seen : 0;
43
+ const down = previous?.status === 'stopped' ? gap : Math.max(0, gap - CRASH_MARGIN);
44
+ return new Date(since + down).toISOString();
45
+ }
46
+ catch {
47
+ return startedAt;
48
+ }
49
+ }
18
50
  /** Read-only monitoring health check; does not assess system security or make network requests. */
19
51
  export function checkHealth(store, config, now = Date.now(), requireWorker = true) {
20
52
  const scan = object(store.getMeta('last_scan'));
@@ -23,7 +55,22 @@ export function checkHealth(store, config, now = Date.now(), requireWorker = tru
23
55
  const started = time(worker?.started_at);
24
56
  const scanned = time(scan?.at);
25
57
  const issues = [];
26
- const startupGrace = worker?.status === 'running' && Number.isFinite(started) && now >= started && now - started <= 120_000;
58
+ const staleAfter = Math.max(120_000, config.poll_interval_minutes * 120_000);
59
+ // The first scan reads a day of advisories and every package lookup at about a request a second:
60
+ // it can take well over the two minutes later scans need, so a running worker that has not
61
+ // finished one yet is healthy for up to an hour.
62
+ // Measured from when the worker began catching up, which survives restarts until a scan is
63
+ // recorded: a worker killed during every scan does not renew its grace by restarting.
64
+ const catchingUpSince = time(worker?.catching_up_since);
65
+ const graceFrom = Number.isFinite(catchingUpSince) && catchingUpSince <= started ? catchingUpSince : started;
66
+ const startupGrace = worker?.status === 'running' &&
67
+ Number.isFinite(started) &&
68
+ now >= started &&
69
+ (Number.isFinite(scanned) && scanned >= started
70
+ ? now - started <= 120_000
71
+ : now - graceFrom <= FIRST_SCAN_GRACE);
72
+ /** Whether this check passes only because a worker is still catching up. */
73
+ let catchingUp = false;
27
74
  if (requireWorker &&
28
75
  (worker?.status !== 'running' ||
29
76
  !Number.isFinite(heartbeat) ||
@@ -35,7 +82,10 @@ export function checkHealth(store, config, now = Date.now(), requireWorker = tru
35
82
  issues.push('No completed scan is recorded.');
36
83
  }
37
84
  else {
38
- if (scanned > now + 5000 || now - scanned > Math.max(120_000, config.poll_interval_minutes * 120_000))
85
+ const stale = now - scanned > staleAfter;
86
+ if (stale && startupGrace && requireWorker && scanned < started)
87
+ catchingUp = true;
88
+ else if (scanned > now + 5000 || stale)
39
89
  issues.push('The last completed scan is stale or has an invalid future timestamp.');
40
90
  if (scan?.degraded !== false)
41
91
  issues.push('The last scan reported degraded monitoring; inspect status and findings.');
@@ -60,7 +110,9 @@ export function checkHealth(store, config, now = Date.now(), requireWorker = tru
60
110
  issues.push('Current notifications are overdue by more than five minutes.');
61
111
  return {
62
112
  ok: issues.length === 0,
63
- status: issues.length ? 'degraded' : Number.isFinite(scanned) ? 'healthy' : 'starting',
113
+ // While a worker catches up the check passes, but it is "starting": no success is reported to
114
+ // an external heartbeat until a scan completes.
115
+ status: issues.length ? 'degraded' : Number.isFinite(scanned) && !catchingUp ? 'healthy' : 'starting',
64
116
  checked_at: new Date(now).toISOString(),
65
117
  issues,
66
118
  last_scan_at: Number.isFinite(scanned) ? new Date(scanned).toISOString() : null,
package/dist/http.d.ts CHANGED
@@ -4,5 +4,12 @@ export declare class NetworkError extends Error {
4
4
  constructor(code: string);
5
5
  }
6
6
  export declare function isPublicAddress(address: string): boolean;
7
+ /**
8
+ * Whether an unencrypted connection to this address stays on this machine or a private network:
9
+ * loopback, RFC 1918, carrier-grade NAT (also used by overlay networks), link-local and IPv6
10
+ * unique-local addresses. Addresses that wrap a public IPv4 address (NAT64, 6to4, Teredo),
11
+ * multicast and reserved ranges are not private.
12
+ */
13
+ export declare function privateAddress(address: string): boolean;
7
14
  export declare function validateDestination(value: string, allowPrivate?: boolean): URL;
8
15
  export declare const safeHttp: HttpClient;
package/dist/http.js CHANGED
@@ -99,12 +99,31 @@ function recordCooldown(origin, status, retryAfter) {
99
99
  export function isPublicAddress(address) {
100
100
  try {
101
101
  const parsed = ipaddr.process(address);
102
+ // ::a.b.c.d, the deprecated IPv4-compatible form: a stack that still routes it reaches the
103
+ // embedded IPv4 address, which may be this machine. Written with a dotted quad the address is
104
+ // judged as that IPv4 address; written in hexadecimal it is no public destination.
105
+ if (parsed.kind() === 'ipv6' && parsed.parts.slice(0, 6).every((part) => part === 0))
106
+ return false;
102
107
  return parsed.range() === 'unicast';
103
108
  }
104
109
  catch {
105
110
  return false;
106
111
  }
107
112
  }
113
+ /**
114
+ * Whether an unencrypted connection to this address stays on this machine or a private network:
115
+ * loopback, RFC 1918, carrier-grade NAT (also used by overlay networks), link-local and IPv6
116
+ * unique-local addresses. Addresses that wrap a public IPv4 address (NAT64, 6to4, Teredo),
117
+ * multicast and reserved ranges are not private.
118
+ */
119
+ export function privateAddress(address) {
120
+ try {
121
+ return ['private', 'loopback', 'linkLocal', 'carrierGradeNat', 'uniqueLocal', 'unspecified'].includes(ipaddr.process(address).range());
122
+ }
123
+ catch {
124
+ return false;
125
+ }
126
+ }
108
127
  export function validateDestination(value, allowPrivate = false) {
109
128
  let url;
110
129
  try {
@@ -118,10 +137,15 @@ export function validateDestination(value, allowPrivate = false) {
118
137
  url.hash ||
119
138
  !['https:', ...(allowPrivate ? ['http:'] : [])].includes(url.protocol))
120
139
  throw new NetworkError('DESTINATION_DENIED');
121
- const host = url.hostname.replace(/^\[|\]$/g, '');
140
+ // A trailing dot names the same host ("localhost.").
141
+ const host = url.hostname.replace(/^\[|\]$/g, '').replace(/\.+$/, '');
122
142
  if (!allowPrivate &&
123
143
  (host === 'localhost' || host.endsWith('.localhost') || (isIP(host) && !isPublicAddress(host))))
124
144
  throw new NetworkError('DESTINATION_DENIED');
145
+ // Permission to reach a private destination is not permission to send a request in the clear
146
+ // across the internet: plain HTTP is only for private and local addresses.
147
+ if (url.protocol === 'http:' && isIP(host) && !privateAddress(host))
148
+ throw new NetworkError('DESTINATION_DENIED');
125
149
  return url;
126
150
  }
127
151
  export const safeHttp = async (value, options = {}) => {
@@ -143,6 +167,11 @@ export const safeHttp = async (value, options = {}) => {
143
167
  callback(new NetworkError('DESTINATION_DENIED'), '', 4);
144
168
  return;
145
169
  }
170
+ // A name that resolves to a public address must not receive a plain HTTP request.
171
+ if (url.protocol === 'http:' && addresses.some((a) => !privateAddress(a.address))) {
172
+ callback(new NetworkError('DESTINATION_DENIED'), '', 4);
173
+ return;
174
+ }
146
175
  // Resolve and validate the addresses actually used by the socket, including redirects.
147
176
  if (lookupOptions.all)
148
177
  callback(null, addresses);
@@ -166,7 +195,7 @@ export const safeHttp = async (value, options = {}) => {
166
195
  agent: false,
167
196
  signal: options.signal,
168
197
  headers: {
169
- 'user-agent': 'Shielda-Security-Watch/0.1',
198
+ 'user-agent': 'Shielda-Security-Watch/1.0',
170
199
  'accept-encoding': 'identity',
171
200
  ...options.headers,
172
201
  },
package/dist/index.d.ts CHANGED
@@ -1,18 +1,36 @@
1
- export * from './types.js';
1
+ export type { Severity, Category, Applicability, Channel, Provenance, DeploymentObservation, ArtifactKind, DeclaredVerification, DependencyLink, DependencyRelationship, DeclaredRemediation, InventoryEvidence, Component, Product, FindingLocation, System, Inventory, PackageClaim, CvssV4BaseScore, Evidence, ModelSpec, Config, Rule, Assessment, AiReviewReason, AiReview, Decision, Notification, HttpOptions, HttpResult, HttpClient, CoverageReceipt, InventoryDrift, RemediationEvidence, SourceResult, AiAnalysis, NewsAnalysis, } from './types.js';
2
+ export { scorePilotResponses, type PilotResponseRegister, type PilotResponseScore, } from './pilot-responses.js';
2
3
  export { loadConfig, parseConfig, configSchema } from './config.js';
3
4
  export { loadInventory } from './inventory.js';
4
5
  export { assess, decide } from './assessment.js';
5
6
  export { collectSources } from './sources.js';
6
7
  export { ModelAnalyzer, validateAnalysis } from './models.js';
8
+ export type { ModelState } from './models.js';
7
9
  export { PROVIDERS, PROVIDER_IDS, providerDefinition } from './providers.js';
8
10
  export type { ProviderDefinition, ProviderProtocol, ModelProvider, OutputFormat } from './providers.js';
9
- export { Store } from './store.js';
10
- export { deliverPending } from './delivery.js';
11
+ export { Store, readPilotReport, SCHEMA_VERSION } from './store.js';
12
+ export type { PilotReport, PilotWindow } from './pilot-report.js';
13
+ export { createPilotCasePacket, scorePilotCases } from './pilot-cases.js';
14
+ export type { PilotCasePacket, PilotScore, PilotFeedback } from './pilot-cases.js';
15
+ export { createPilotResponseTemplate, scorePilotRecall, type PilotIncidentReference, type PilotRecallScore, } from './pilot-recall.js';
16
+ export { deliverPending, notificationText, sendEmail, smtpProblem } from './delivery.js';
17
+ export type { DeliveryOptions, EmailMessage, EmailReceipt, EmailSender } from './delivery.js';
18
+ export { safeHttp } from './http.js';
19
+ export { acquireLock } from './lock.js';
11
20
  export { runScan, readFixture } from './engine.js';
12
21
  export { checkHealth } from './health.js';
22
+ export type { HealthReport } from './health.js';
13
23
  export { ECOSYSTEMS, normalizeEcosystem, normalizePackageName, parseLibraryList } from './ecosystems.js';
14
24
  export type { Ecosystem, Library } from './ecosystems.js';
15
25
  export { HeartbeatMonitor } from './heartbeat.js';
26
+ export type { ExternalHeartbeat } from './heartbeat.js';
16
27
  export { MaintenanceScheduler } from './operations.js';
17
- export { verifyBackup } from './maintenance.js';
28
+ export type { MaintenanceRun } from './operations.js';
29
+ export { verifyBackup, readPilotBackupReport } from './maintenance.js';
30
+ export { runRehearsal, readRehearsal } from './rehearsal.js';
31
+ export type { RehearsalReport, RehearsalScenario, RehearsalSink } from './rehearsal.js';
18
32
  export type { RetentionPolicy, PruneCounts, PruneReport, BackupVerification } from './maintenance.js';
33
+ export { importCycloneDx } from './sbom.js';
34
+ export type { SbomImport } from './sbom.js';
35
+ export { compareInventories, attachLocation, attachRemediation } from './inventory-evidence.js';
36
+ export { refreshCoverage } from './coverage.js';
package/dist/index.js CHANGED
@@ -1,15 +1,23 @@
1
- export * from './types.js';
1
+ export { scorePilotResponses, } from './pilot-responses.js';
2
2
  export { loadConfig, parseConfig, configSchema } from './config.js';
3
3
  export { loadInventory } from './inventory.js';
4
4
  export { assess, decide } from './assessment.js';
5
5
  export { collectSources } from './sources.js';
6
6
  export { ModelAnalyzer, validateAnalysis } from './models.js';
7
7
  export { PROVIDERS, PROVIDER_IDS, providerDefinition } from './providers.js';
8
- export { Store } from './store.js';
9
- export { deliverPending } from './delivery.js';
8
+ export { Store, readPilotReport, SCHEMA_VERSION } from './store.js';
9
+ export { createPilotCasePacket, scorePilotCases } from './pilot-cases.js';
10
+ export { createPilotResponseTemplate, scorePilotRecall, } from './pilot-recall.js';
11
+ export { deliverPending, notificationText, sendEmail, smtpProblem } from './delivery.js';
12
+ export { safeHttp } from './http.js';
13
+ export { acquireLock } from './lock.js';
10
14
  export { runScan, readFixture } from './engine.js';
11
15
  export { checkHealth } from './health.js';
12
16
  export { ECOSYSTEMS, normalizeEcosystem, normalizePackageName, parseLibraryList } from './ecosystems.js';
13
17
  export { HeartbeatMonitor } from './heartbeat.js';
14
18
  export { MaintenanceScheduler } from './operations.js';
15
- export { verifyBackup } from './maintenance.js';
19
+ export { verifyBackup, readPilotBackupReport } from './maintenance.js';
20
+ export { runRehearsal, readRehearsal } from './rehearsal.js';
21
+ export { importCycloneDx } from './sbom.js';
22
+ export { compareInventories, attachLocation, attachRemediation } from './inventory-evidence.js';
23
+ export { refreshCoverage } from './coverage.js';
@@ -0,0 +1,10 @@
1
+ import type { Assessment, Config, Evidence, Inventory, InventoryDrift } from './types.js';
2
+ /** Compares declarations; a changed or removed declaration never proves deployed remediation. */
3
+ export declare function compareInventories(previous: Inventory | undefined, current: Inventory): InventoryDrift[];
4
+ /**
5
+ * Copy the inventory's own names and notes onto a finding so a notification says where to look.
6
+ * This is the operator's text, not evidence: it never changes applicability, priority or routing.
7
+ */
8
+ export declare function attachLocation(finding: Assessment, inventory: Inventory): Assessment;
9
+ /** Cited guidance and operator observations, never an automatic closure or configuration attestation. */
10
+ export declare function attachRemediation(finding: Assessment, inventory: Inventory, evidence: Evidence[], config: Config, now: number): Assessment;