@blamejs/exceptd-skills 0.12.11 → 0.12.13

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/lib/prefetch.js CHANGED
@@ -188,9 +188,93 @@ function loadIndex(cacheDir) {
188
188
  }
189
189
  }
190
190
 
191
- function saveIndex(cacheDir, idx) {
191
+ // v0.12.12 C4: atomic write helper — tmp + rename. Concurrent readers either
192
+ // see the prior file in full or the new file in full, never a half-written
193
+ // buffer. fs.renameSync is atomic on POSIX and on Windows for same-volume
194
+ // renames; a `.tmp.<pid>.<rand>` sibling to the destination is always
195
+ // same-volume.
196
+ function writeFileAtomic(p, body) {
197
+ const tmpPath = `${p}.tmp.${process.pid}.${Math.random().toString(36).slice(2, 10)}`;
198
+ fs.writeFileSync(tmpPath, body);
199
+ try {
200
+ fs.renameSync(tmpPath, p);
201
+ } catch (err) {
202
+ try { fs.unlinkSync(tmpPath); } catch {}
203
+ throw err;
204
+ }
205
+ }
206
+
207
+ // v0.12.12 C2: lockfile-gated read-modify-write for _index.json. Two
208
+ // concurrent prefetch runs against the same cache dir previously raced —
209
+ // each loaded the index at start, mutated its in-memory copy as entries
210
+ // fetched, then wrote at the end. The second writer overwrote the first,
211
+ // silently dropping any entries the first run wrote.
212
+ //
213
+ // Stale-lock recovery: if a holder crashes without unlinking, the lockfile
214
+ // persists. After backoff, if the lockfile's mtime is older than 30s we
215
+ // treat it as orphaned and unlink it before retrying.
216
+ async function withIndexLock(cacheDir, mutator) {
192
217
  if (!fs.existsSync(cacheDir)) fs.mkdirSync(cacheDir, { recursive: true });
193
- fs.writeFileSync(path.join(cacheDir, "_index.json"), JSON.stringify(idx, null, 2) + "\n", "utf8");
218
+ const lockPath = path.join(cacheDir, "_index.json.lock");
219
+ const indexPath = path.join(cacheDir, "_index.json");
220
+ const MAX_RETRIES = 50;
221
+ const STALE_LOCK_MS = 30_000;
222
+ let acquired = false;
223
+ for (let i = 0; i < MAX_RETRIES; i++) {
224
+ try {
225
+ fs.writeFileSync(lockPath, String(process.pid), { flag: "wx" });
226
+ acquired = true;
227
+ break;
228
+ } catch (e) {
229
+ // EEXIST is the POSIX signal another process holds the lock. On
230
+ // Windows the same race surfaces as EPERM (a sharing-violation
231
+ // raised when the other process is mid-unlink). Treat both as
232
+ // "lock held, back off" rather than a fatal error.
233
+ if (e.code !== "EEXIST" && e.code !== "EPERM") throw e;
234
+ try {
235
+ const stat = fs.statSync(lockPath);
236
+ if (Date.now() - stat.mtimeMs > STALE_LOCK_MS) {
237
+ try { fs.unlinkSync(lockPath); } catch {}
238
+ continue;
239
+ }
240
+ } catch {}
241
+ await new Promise((r) => setTimeout(r, 50 + Math.random() * 150));
242
+ }
243
+ }
244
+ if (!acquired) {
245
+ throw new Error(`withIndexLock: could not acquire ${lockPath} after ${MAX_RETRIES} attempts`);
246
+ }
247
+ try {
248
+ // Always re-read the current on-disk index inside the lock. Stale
249
+ // in-memory copies from before acquisition are the entire bug class.
250
+ let current;
251
+ if (fs.existsSync(indexPath)) {
252
+ try { current = JSON.parse(fs.readFileSync(indexPath, "utf8")); }
253
+ catch { current = { entries: {}, generated_at: null }; }
254
+ } else {
255
+ current = { entries: {}, generated_at: null };
256
+ }
257
+ const mutated = await mutator(current);
258
+ const toWrite = mutated === undefined ? current : mutated;
259
+ writeFileAtomic(indexPath, JSON.stringify(toWrite, null, 2) + "\n");
260
+ return toWrite;
261
+ } finally {
262
+ try { fs.unlinkSync(lockPath); } catch {}
263
+ }
264
+ }
265
+
266
+ // Back-compat: existing callers used saveIndex(cacheDir, idx). The thin
267
+ // wrapper merges entries under the lock so a concurrent run's writes are
268
+ // preserved (rather than blindly overwriting them with the caller's
269
+ // possibly-stale in-memory `idx`).
270
+ async function saveIndex(cacheDir, idx) {
271
+ await withIndexLock(cacheDir, (current) => {
272
+ const mergedEntries = { ...current.entries, ...idx.entries };
273
+ return {
274
+ entries: mergedEntries,
275
+ generated_at: idx.generated_at || current.generated_at,
276
+ };
277
+ });
194
278
  }
195
279
 
196
280
  function entryKey(source, id) {
@@ -292,17 +376,32 @@ async function prefetch(options = {}) {
292
376
  run: () => timedFetch(item.url, reqHeaders),
293
377
  meta: { id: item.id },
294
378
  })
295
- .then((res) => {
296
- const dir = path.dirname(entryPath(opts.cacheDir, item.source, item.id));
379
+ .then(async (res) => {
380
+ const targetPath = entryPath(opts.cacheDir, item.source, item.id);
381
+ const dir = path.dirname(targetPath);
297
382
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
298
- fs.writeFileSync(entryPath(opts.cacheDir, item.source, item.id), JSON.stringify(res.json, null, 2) + "\n", "utf8");
299
- idx.entries[entryKey(item.source, item.id)] = {
383
+ // v0.12.12 C4: atomic write of the payload. A concurrent reader
384
+ // (refresh --from-cache running in parallel) sees the prior
385
+ // payload in full or the new payload in full, never a partial
386
+ // buffer.
387
+ writeFileAtomic(targetPath, JSON.stringify(res.json, null, 2) + "\n");
388
+ const meta = {
300
389
  fetched_at: new Date().toISOString(),
301
390
  etag: res.etag,
302
391
  last_modified: res.lastModified,
303
392
  url: item.url,
304
393
  sha256: crypto.createHash("sha256").update(JSON.stringify(res.json)).digest("hex"),
305
394
  };
395
+ idx.entries[entryKey(item.source, item.id)] = meta;
396
+ // v0.12.12 C2: persist this entry's metadata to _index.json under
397
+ // lock immediately, merging with whatever the on-disk index has
398
+ // (another concurrent prefetch may have written sibling entries).
399
+ // Without this, only the in-memory idx is updated; the final
400
+ // saveIndex() would overwrite a sibling run's writes.
401
+ await withIndexLock(opts.cacheDir, (current) => {
402
+ current.entries[entryKey(item.source, item.id)] = meta;
403
+ return current;
404
+ });
306
405
  result.fetched++;
307
406
  result.by_source[item.source].fetched++;
308
407
  log(` [${item.source}] ${item.id} — ok`);
@@ -317,7 +416,10 @@ async function prefetch(options = {}) {
317
416
  await Promise.all(jobPromises);
318
417
  await queue.drain();
319
418
  idx.generated_at = new Date().toISOString();
320
- saveIndex(opts.cacheDir, idx);
419
+ // v0.12.12 C2: saveIndex now merges under lock with whatever is on disk
420
+ // (another concurrent prefetch's entries). Without the merge, a sibling
421
+ // run's writes would be silently overwritten here at the end of our run.
422
+ await saveIndex(opts.cacheDir, idx);
321
423
 
322
424
  // Final summary is unconditional — --quiet suppresses per-entry chatter
323
425
  // (the noisy part) but the operator still needs one line confirming success.
@@ -398,4 +500,15 @@ async function main() {
398
500
 
399
501
  if (require.main === module) main();
400
502
 
401
- module.exports = { prefetch, readCached, parseArgs, SOURCES, DEFAULT_CACHE };
503
+ module.exports = {
504
+ prefetch,
505
+ readCached,
506
+ parseArgs,
507
+ SOURCES,
508
+ DEFAULT_CACHE,
509
+ // v0.12.12 C2: exported for the concurrent-writer regression test.
510
+ // Not part of the operator-facing API — internal contract for tests
511
+ // that need to exercise the lockfile path without spawning the full
512
+ // prefetch network pipeline.
513
+ _internal: { withIndexLock, writeFileAtomic, loadIndex, saveIndex },
514
+ };
@@ -141,6 +141,17 @@ Modes:
141
141
  exceptd refresh --advisory GHSA-xxxx-xxxx-xxxx --apply
142
142
  exceptd refresh --advisory MAL-2026-3083
143
143
  exceptd refresh --advisory RUSTSEC-2025-0001
144
+ --curate <CVE-ID> emit editorial questions + ranked candidates
145
+ (ATLAS/ATT&CK/CWE/framework gaps) for a draft entry.
146
+ With --answers <path> the operator-supplied answers
147
+ are validated, applied to the catalog entry, and the
148
+ draft is promoted out of _auto_imported / _draft once
149
+ every required schema field is populated. Atomic write;
150
+ concurrent --apply runs against the same catalog are
151
+ safe. --apply is an alias for "--answers implies write".
152
+ Examples:
153
+ exceptd refresh --curate CVE-2026-45321
154
+ exceptd refresh --curate CVE-2026-45321 --answers a.json --apply
144
155
 
145
156
  Sources (default = all):
146
157
  kev CISA Known Exploited Vulnerabilities
@@ -214,26 +225,32 @@ const KEV_SOURCE = {
214
225
  let updated = 0;
215
226
  let added = 0;
216
227
  const errors = [];
217
- for (const d of diffs) {
218
- if (d.op === "add") {
219
- // Auto-discovered new entry. Refuse to overwrite if the entry
220
- // somehow exists (race condition / stale fixture); skip silently.
221
- if (ctx.cveCatalog[d.id]) continue;
222
- ctx.cveCatalog[d.id] = d.entry;
223
- added++;
224
- continue;
225
- }
226
- if (!ctx.cveCatalog[d.id]) {
227
- errors.push(`KEV: no local entry for ${d.id}`);
228
- continue;
228
+ const catalogPath = ctx.cvePath || ABS("data/cve-catalog.json");
229
+ await withCatalogLock(catalogPath, (catalog) => {
230
+ for (const d of diffs) {
231
+ if (d.op === "add") {
232
+ // Auto-discovered new entry. Refuse to overwrite if the entry
233
+ // somehow exists (race condition / stale fixture); skip silently.
234
+ if (catalog[d.id]) continue;
235
+ catalog[d.id] = d.entry;
236
+ added++;
237
+ continue;
238
+ }
239
+ if (!catalog[d.id]) {
240
+ errors.push(`KEV: no local entry for ${d.id}`);
241
+ continue;
242
+ }
243
+ catalog[d.id][d.field] = d.after;
244
+ catalog[d.id].last_verified = TODAY;
245
+ updated++;
229
246
  }
230
- ctx.cveCatalog[d.id][d.field] = d.after;
231
- ctx.cveCatalog[d.id].last_verified = TODAY;
232
- updated++;
233
- }
234
- ctx.cveCatalog._meta = ctx.cveCatalog._meta || {};
235
- ctx.cveCatalog._meta.last_updated = TODAY;
236
- writeJson(ctx.cvePath || ABS("data/cve-catalog.json"), ctx.cveCatalog);
247
+ catalog._meta = catalog._meta || {};
248
+ catalog._meta.last_updated = TODAY;
249
+ // Refresh the in-memory view so later sources in the same process
250
+ // (sequential or --swarm) see the post-write state.
251
+ ctx.cveCatalog = catalog;
252
+ return catalog;
253
+ });
237
254
  return { updated: updated + added, added, drift_updated: updated, errors };
238
255
  },
239
256
  };
@@ -297,18 +314,22 @@ const EPSS_SOURCE = {
297
314
  async applyDiff(ctx, diffs) {
298
315
  let updated = 0;
299
316
  const errors = [];
300
- for (const d of diffs) {
301
- if (!ctx.cveCatalog[d.id]) {
302
- errors.push(`EPSS: no local entry for ${d.id}`);
303
- continue;
317
+ const catalogPath = ctx.cvePath || ABS("data/cve-catalog.json");
318
+ await withCatalogLock(catalogPath, (catalog) => {
319
+ for (const d of diffs) {
320
+ if (!catalog[d.id]) {
321
+ errors.push(`EPSS: no local entry for ${d.id}`);
322
+ continue;
323
+ }
324
+ catalog[d.id][d.field] = d.after;
325
+ catalog[d.id].last_verified = TODAY;
326
+ updated++;
304
327
  }
305
- ctx.cveCatalog[d.id][d.field] = d.after;
306
- ctx.cveCatalog[d.id].last_verified = TODAY;
307
- updated++;
308
- }
309
- ctx.cveCatalog._meta = ctx.cveCatalog._meta || {};
310
- ctx.cveCatalog._meta.last_updated = TODAY;
311
- writeJson(ctx.cvePath || ABS("data/cve-catalog.json"), ctx.cveCatalog);
328
+ catalog._meta = catalog._meta || {};
329
+ catalog._meta.last_updated = TODAY;
330
+ ctx.cveCatalog = catalog;
331
+ return catalog;
332
+ });
312
333
  return { updated, errors };
313
334
  },
314
335
  };
@@ -342,18 +363,22 @@ const NVD_SOURCE = {
342
363
  async applyDiff(ctx, diffs) {
343
364
  let updated = 0;
344
365
  const errors = [];
345
- for (const d of diffs) {
346
- if (!ctx.cveCatalog[d.id]) {
347
- errors.push(`NVD: no local entry for ${d.id}`);
348
- continue;
366
+ const catalogPath = ctx.cvePath || ABS("data/cve-catalog.json");
367
+ await withCatalogLock(catalogPath, (catalog) => {
368
+ for (const d of diffs) {
369
+ if (!catalog[d.id]) {
370
+ errors.push(`NVD: no local entry for ${d.id}`);
371
+ continue;
372
+ }
373
+ catalog[d.id][d.field] = d.after;
374
+ catalog[d.id].last_verified = TODAY;
375
+ updated++;
349
376
  }
350
- ctx.cveCatalog[d.id][d.field] = d.after;
351
- ctx.cveCatalog[d.id].last_verified = TODAY;
352
- updated++;
353
- }
354
- ctx.cveCatalog._meta = ctx.cveCatalog._meta || {};
355
- ctx.cveCatalog._meta.last_updated = TODAY;
356
- writeJson(ctx.cvePath || ABS("data/cve-catalog.json"), ctx.cveCatalog);
377
+ catalog._meta = catalog._meta || {};
378
+ catalog._meta.last_updated = TODAY;
379
+ ctx.cveCatalog = catalog;
380
+ return catalog;
381
+ });
357
382
  return { updated, errors };
358
383
  },
359
384
  };
@@ -398,26 +423,30 @@ const RFC_SOURCE = {
398
423
  let updated = 0;
399
424
  let added = 0;
400
425
  const errors = [];
401
- for (const d of diffs) {
402
- if (d.op === "add") {
403
- if (ctx.rfcCatalog[d.id]) continue;
404
- ctx.rfcCatalog[d.id] = d.entry;
405
- added++;
406
- continue;
407
- }
408
- if (d.field !== "status") continue; // notes are informational
409
- const entry = ctx.rfcCatalog[d.id];
410
- if (!entry) {
411
- errors.push(`RFC: no local entry for ${d.id}`);
412
- continue;
426
+ const rfcPath = ABS("data/rfc-references.json");
427
+ await withCatalogLock(rfcPath, (rfcCatalog) => {
428
+ for (const d of diffs) {
429
+ if (d.op === "add") {
430
+ if (rfcCatalog[d.id]) continue;
431
+ rfcCatalog[d.id] = d.entry;
432
+ added++;
433
+ continue;
434
+ }
435
+ if (d.field !== "status") continue; // notes are informational
436
+ const entry = rfcCatalog[d.id];
437
+ if (!entry) {
438
+ errors.push(`RFC: no local entry for ${d.id}`);
439
+ continue;
440
+ }
441
+ entry.status = d.after;
442
+ entry.last_verified = TODAY;
443
+ updated++;
413
444
  }
414
- entry.status = d.after;
415
- entry.last_verified = TODAY;
416
- updated++;
417
- }
418
- ctx.rfcCatalog._meta = ctx.rfcCatalog._meta || {};
419
- ctx.rfcCatalog._meta.last_updated = TODAY;
420
- writeJson(ABS("data/rfc-references.json"), ctx.rfcCatalog);
445
+ rfcCatalog._meta = rfcCatalog._meta || {};
446
+ rfcCatalog._meta.last_updated = TODAY;
447
+ ctx.rfcCatalog = rfcCatalog;
448
+ return rfcCatalog;
449
+ });
421
450
  return { updated: updated + added, added, drift_updated: updated, errors };
422
451
  },
423
452
  };
@@ -824,8 +853,97 @@ function loadCtx(opts) {
824
853
  return ctx;
825
854
  }
826
855
 
856
+ // v0.12.12 C4: every persisted JSON write goes through writeJsonAtomic — a
857
+ // tmp + rename pattern. fs.renameSync is atomic on POSIX and on Windows for
858
+ // same-volume renames (which a `.tmp.<pid>.<rand>` adjacent to the target
859
+ // always satisfies). A concurrent reader either sees the prior file content
860
+ // in full or the new content in full — never a half-written buffer. The
861
+ // tmp name carries pid + random so two writers in the same process (e.g.
862
+ // worker threads) never collide on the same scratch path.
863
+ function writeJsonAtomic(p, obj) {
864
+ const tmpPath = `${p}.tmp.${process.pid}.${Math.random().toString(36).slice(2, 10)}`;
865
+ fs.writeFileSync(tmpPath, JSON.stringify(obj, null, 2) + "\n", "utf8");
866
+ try {
867
+ fs.renameSync(tmpPath, p);
868
+ } catch (err) {
869
+ try { fs.unlinkSync(tmpPath); } catch {}
870
+ throw err;
871
+ }
872
+ }
873
+
874
+ // Back-compat alias — exported callers and historical sites still reference
875
+ // writeJson. Atomic by default; never the unsafe direct-write form.
827
876
  function writeJson(p, obj) {
828
- fs.writeFileSync(p, JSON.stringify(obj, null, 2) + "\n", "utf8");
877
+ writeJsonAtomic(p, obj);
878
+ }
879
+
880
+ /**
881
+ * v0.12.12 C1: lockfile-gated read-modify-write helper for JSON catalogs.
882
+ *
883
+ * Two concurrent `refresh --advisory CVE-A --apply` and
884
+ * `refresh --advisory CVE-B --apply` processes against the same catalog used
885
+ * to race: each read the catalog, mutated its in-memory copy, then wrote —
886
+ * the second write overwrote the first, silently dropping one CVE. The fix
887
+ * is a sidecar lockfile (created with O_EXCL via `flag: 'wx'`) that
888
+ * serializes the read-mutate-write triple. The mutator receives the
889
+ * current-on-disk catalog (re-read inside the lock, NOT a stale in-memory
890
+ * copy from before lock acquisition) and returns it after mutation; the
891
+ * helper then writes atomically via writeJsonAtomic.
892
+ *
893
+ * Stale-lock recovery: if a holder crashes without unlinking, the lockfile
894
+ * persists. After backoff, if the lockfile's mtime is older than 30s we
895
+ * treat it as orphaned and unlink it before retrying. 30s is well past any
896
+ * legitimate single-CVE apply (sub-second on modern disks).
897
+ *
898
+ * On acquisition failure after N retries, we throw — better than silently
899
+ * proceeding without the lock.
900
+ *
901
+ * @param {string} catalogPath path to the JSON catalog to lock
902
+ * @param {(catalog: object) => object | Promise<object>} mutator
903
+ * receives current-on-disk catalog, returns mutated catalog. May be
904
+ * async. The return value is what gets written; if it returns
905
+ * undefined, the in-place mutation of the passed-in catalog is used.
906
+ * @returns {Promise<{ wrote: boolean, result: any }>}
907
+ */
908
+ async function withCatalogLock(catalogPath, mutator) {
909
+ const lockPath = `${catalogPath}.lock`;
910
+ const MAX_RETRIES = 50;
911
+ const STALE_LOCK_MS = 30_000;
912
+ let acquired = false;
913
+ for (let i = 0; i < MAX_RETRIES; i++) {
914
+ try {
915
+ fs.writeFileSync(lockPath, String(process.pid), { flag: "wx" });
916
+ acquired = true;
917
+ break;
918
+ } catch (e) {
919
+ // EEXIST is the POSIX signal another process holds the lock. On
920
+ // Windows the same race surfaces as EPERM (sharing-violation raised
921
+ // when the holder is mid-unlink). Treat both as "lock held, back off."
922
+ if (e.code !== "EEXIST" && e.code !== "EPERM") throw e;
923
+ // Stale-lock check before sleeping — a long-dead holder shouldn't keep
924
+ // us waiting MAX_RETRIES * backoff before we recover.
925
+ try {
926
+ const stat = fs.statSync(lockPath);
927
+ if (Date.now() - stat.mtimeMs > STALE_LOCK_MS) {
928
+ try { fs.unlinkSync(lockPath); } catch {}
929
+ continue; // retry immediately without sleeping
930
+ }
931
+ } catch {} // lockfile vanished between EEXIST and stat — fine, retry
932
+ await new Promise((r) => setTimeout(r, 50 + Math.random() * 150));
933
+ }
934
+ }
935
+ if (!acquired) {
936
+ throw new Error(`withCatalogLock: could not acquire ${lockPath} after ${MAX_RETRIES} attempts`);
937
+ }
938
+ try {
939
+ const catalog = JSON.parse(fs.readFileSync(catalogPath, "utf8"));
940
+ const mutated = await mutator(catalog);
941
+ const toWrite = mutated === undefined ? catalog : mutated;
942
+ writeJsonAtomic(catalogPath, toWrite);
943
+ return { wrote: true, result: toWrite };
944
+ } finally {
945
+ try { fs.unlinkSync(lockPath); } catch {}
946
+ }
829
947
  }
830
948
 
831
949
  function chosenSources(opts) {
@@ -834,8 +952,13 @@ function chosenSources(opts) {
834
952
  const out = [];
835
953
  for (const n of names) {
836
954
  if (!ALL_SOURCES[n]) {
837
- console.error(`refresh-external: unknown source "${n}". Valid: ${Object.keys(ALL_SOURCES).join(", ")}`);
838
- process.exit(2);
955
+ // v0.12.12 C3: previously `process.exit(2)` after a console.error.
956
+ // Stdout writes elsewhere in this run could truncate; throwing lets
957
+ // main().catch() surface the error through the standard channel and
958
+ // exit code via process.exitCode + natural event-loop drain.
959
+ const err = new Error(`refresh-external: unknown source "${n}". Valid: ${Object.keys(ALL_SOURCES).join(", ")}`);
960
+ err._exceptd_unknown_source = true;
961
+ throw err;
839
962
  }
840
963
  out.push(ALL_SOURCES[n]);
841
964
  }
@@ -939,18 +1062,29 @@ async function seedSingleAdvisory(opts) {
939
1062
 
940
1063
  // Apply: write to cve-catalog.json with the _auto_imported flag.
941
1064
  // v0.12.8: honor --catalog / EXCEPTD_CVE_CATALOG so tests can redirect.
1065
+ // v0.12.12 C1: lock-gated RMW. Without this, two concurrent
1066
+ // `refresh --advisory CVE-A --apply` + `--advisory CVE-B --apply`
1067
+ // processes against the same catalog silently dropped one CVE 1-in-20
1068
+ // trials (read-old → mutate → write-overwrites-sibling-mutation).
942
1069
  const catalogPath = resolveCatalogPath(opts);
943
- const catalog = JSON.parse(fs.readFileSync(catalogPath, "utf8"));
944
- if (catalog[cveId] && !catalog[cveId]._auto_imported && !catalog[cveId]._draft) {
945
- // Refuse to overwrite a human-curated entry.
946
- const err = { ok: false, verb: "refresh", error: `${cveId} already present in catalog and is human-curated (not a draft). Refusing to overwrite. Edit manually if intentional.`, existing_last_updated: catalog[cveId].last_updated };
1070
+ let humanCurated = null;
1071
+ await withCatalogLock(catalogPath, (catalog) => {
1072
+ if (catalog[cveId] && !catalog[cveId]._auto_imported && !catalog[cveId]._draft) {
1073
+ // Refuse to overwrite a human-curated entry signal via closure so
1074
+ // we can emit the structured error after the lock releases.
1075
+ humanCurated = { last_updated: catalog[cveId].last_updated };
1076
+ return catalog; // unchanged write — idempotent, releases lock
1077
+ }
1078
+ catalog[cveId] = normalized[cveId];
1079
+ return catalog;
1080
+ });
1081
+ if (humanCurated) {
1082
+ const err = { ok: false, verb: "refresh", error: `${cveId} already present in catalog and is human-curated (not a draft). Refusing to overwrite. Edit manually if intentional.`, existing_last_updated: humanCurated.last_updated };
947
1083
  if (opts.json) process.stdout.write(JSON.stringify(err) + "\n");
948
1084
  else process.stderr.write(`[refresh --advisory] ${err.error}\n`);
949
1085
  process.exitCode = 4;
950
1086
  return;
951
1087
  }
952
- catalog[cveId] = normalized[cveId];
953
- fs.writeFileSync(catalogPath, JSON.stringify(catalog, null, 2) + "\n", "utf8");
954
1088
  const output = {
955
1089
  ok: true,
956
1090
  verb: "refresh",
@@ -971,7 +1105,9 @@ async function main() {
971
1105
  const opts = parseArgs(process.argv);
972
1106
  if (opts.help) {
973
1107
  printHelp();
974
- process.exit(0);
1108
+ // v0.12.12 C3: exitCode + return so buffered stdout flushes naturally.
1109
+ process.exitCode = 0;
1110
+ return;
975
1111
  }
976
1112
 
977
1113
  // v0.12.0: `--advisory <id>` short-circuits the normal source loop and
@@ -1068,7 +1204,12 @@ async function main() {
1068
1204
  }
1069
1205
  }
1070
1206
 
1071
- process.exit(hadFailure ? 1 : 0);
1207
+ // v0.12.12 C3: same anti-pattern v0.12.9 fixed in prefetch's main(). After
1208
+ // Promise.all(sources.map(runOne)) in --swarm mode, process.exit() could
1209
+ // truncate buffered stdout (refresh-report path log line, summary log
1210
+ // lines piped to a consumer). exitCode + return lets the event loop end
1211
+ // naturally and stdout drains in full.
1212
+ process.exitCode = hadFailure ? 1 : 0;
1072
1213
  }
1073
1214
 
1074
1215
  async function sequential(items, fn) {
@@ -1084,11 +1225,18 @@ if (require.main === module) {
1084
1225
  if (err && err._exceptd_hint) {
1085
1226
  console.error(err.message);
1086
1227
  console.error(JSON.stringify({ ok: false, error: err.message.split("\n")[0], hint: err.message.split("\n").slice(1).join(" ").trim(), verb: "refresh" }));
1228
+ } else if (err && err._exceptd_unknown_source) {
1229
+ // v0.12.12 C3: surface the source-validation error without leaking a
1230
+ // stack trace; chosenSources throws this for unknown --source values.
1231
+ console.error(err.message);
1087
1232
  } else {
1088
1233
  console.error(`refresh-external: fatal: ${err && err.stack ? err.stack : err}`);
1089
1234
  }
1090
- process.exit(2);
1235
+ // v0.12.12 C3: exitCode + return rather than process.exit(2) — the
1236
+ // event loop has no further work after main()'s rejection, so this
1237
+ // ends the process with code 2 but lets stderr drain first.
1238
+ process.exitCode = 2;
1091
1239
  });
1092
1240
  }
1093
1241
 
1094
- module.exports = { ALL_SOURCES, loadCtx, parseArgs, seedSingleAdvisory };
1242
+ module.exports = { ALL_SOURCES, loadCtx, parseArgs, seedSingleAdvisory, withCatalogLock, writeJsonAtomic };
@@ -125,6 +125,18 @@ function parseTar(buf) {
125
125
  const entries = [];
126
126
  let offset = 0;
127
127
  let pendingLongName = null;
128
+ // v0.12.12: tarballs from a compromised registry CDN could ship entries
129
+ // with `..`-bearing names targeting paths outside the install root. The
130
+ // immediate callers (verify-shipped-tarball.js + the network update path)
131
+ // do hash + signature checks before honoring entries, so this is
132
+ // defense-in-depth — drop the entry rather than handing a path-traversal
133
+ // string downstream.
134
+ const isSafeName = (n) => {
135
+ if (typeof n !== "string" || n.length === 0) return false;
136
+ // Reject absolute paths AND any segment that is exactly ".."
137
+ if (/^[\\/]/.test(n) || /^[A-Za-z]:[\\/]/.test(n)) return false;
138
+ return !n.split(/[\\/]/).some((seg) => seg === "..");
139
+ };
128
140
  while (offset + 512 <= buf.length) {
129
141
  const block = buf.subarray(offset, offset + 512);
130
142
  // empty block = end-of-archive marker
@@ -141,7 +153,9 @@ function parseTar(buf) {
141
153
  if (type === "L") {
142
154
  pendingLongName = buf.subarray(dataStart, dataEnd).toString("utf8").replace(/\0.*$/, "");
143
155
  } else if (type === "0" || type === "" || type === "\0") {
144
- entries.push({ name, body: buf.subarray(dataStart, dataEnd) });
156
+ if (isSafeName(name)) {
157
+ entries.push({ name, body: buf.subarray(dataStart, dataEnd) });
158
+ }
145
159
  }
146
160
  // round up to 512
147
161
  offset = dataStart + Math.ceil(size / 512) * 512;
@@ -82,6 +82,22 @@
82
82
  "type": "array",
83
83
  "items": { "type": "string", "minLength": 1 }
84
84
  },
85
+ "rfc_refs": {
86
+ "type": "array",
87
+ "items": { "type": "string", "minLength": 1 }
88
+ },
89
+ "cwe_refs": {
90
+ "type": "array",
91
+ "items": { "type": "string", "minLength": 1 }
92
+ },
93
+ "d3fend_refs": {
94
+ "type": "array",
95
+ "items": { "type": "string", "minLength": 1 }
96
+ },
97
+ "dlp_refs": {
98
+ "type": "array",
99
+ "items": { "type": "string", "minLength": 1 }
100
+ },
85
101
  "last_threat_review": {
86
102
  "type": "string",
87
103
  "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"