@blockcast/fec-worker 0.3.0-main.7d476d482371 → 0.3.0-main.bb90ce9247fa

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/src/fec-worker.ts CHANGED
@@ -97,9 +97,6 @@ interface WasmBindings {
97
97
 
98
98
  let wasmDecoder: WasmFecDecoder | null = null;
99
99
  let config: FecTrackConfig | null = null;
100
- let altaEnabled = false;
101
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
102
- let altaVerifier: any = null; // JsAltaVerifier instance (loaded from ALTA WASM)
103
100
  let snapshotTimer: ReturnType<typeof setInterval> | null = null;
104
101
  // blockUpdate events are posted only after a client subscribes (BLO-36599).
105
102
  let blockUpdatesSubscribed = false;
@@ -130,20 +127,6 @@ let repairSymbols = 0;
130
127
  let blocksComplete = 0;
131
128
  let blocksRecovered = 0;
132
129
  let blocksFailed = 0;
133
- let altaVerified = 0;
134
- let altaFailed = 0; // Crypto-confirmed tamper (MAC / sig / hash chain mismatch)
135
- const altaFailedDetails: Array<{
136
- seq: number;
137
- error: string;
138
- authLen: number;
139
- payloadLen: number;
140
- path: string; // "direct" | "recovered" | "pending-retry"
141
- }> = [];
142
- let altaPending = 0; // Unverifiable but not tamper (no trailer, verifier not ready, anchor missing)
143
- let altaPendingEvictedCap = 0; // Incoming "pending" packets rejected because the queue was at cap after stale-sweep (flood indicator)
144
- let altaPendingEvictedTtl = 0; // Deferred-queue entries dropped by TTL (retry window expired)
145
- let altaError = 0; // verifyDetached threw — infrastructure flake, not tamper
146
- let altaInitFailed = false; // ALTA configured but WASM init failed; altaEnabled was forced off
147
130
  let relayBlocksVerified = 0;
148
131
  let relayBlocksFailed = 0;
149
132
  let liveSbn = 0;
@@ -181,35 +164,6 @@ let sourceUnplacedRetired = 0;
181
164
  // Recovery timing
182
165
  const recoveryTimes: number[] = [];
183
166
 
184
- // ── Deferred ALTA verification queue (08-07 Path 3) ───────────────────────
185
- //
186
- // When an ALTA packet arrives whose MAC references point at sequences not yet
187
- // in the verifier's ring buffer, we can't anchor trust — verify returns "No
188
- // trust anchor". Typical cause: a predecessor packet was lost and hasn't been
189
- // FEC-recovered yet. Rather than drop these, hold them in a bounded FIFO and
190
- // retry verification after every successful verify (direct or FEC-recovered)
191
- // that seeds the ring buffer with new raw bytes.
192
- //
193
- // Zero-copy (1B-B): the queue entry stores a Uint8Array view into the
194
- // original `data` ArrayBuffer. JS GC keeps the buffer alive via the view
195
- // reference; no bytes are copied on queue.
196
- //
197
- // Timeout entries (TTL exceeded) and cap-rejections count as `altaPending`
198
- // (2C-B): they're not tamper indicators, they're just packets that couldn't
199
- // be authenticated within the receive window — either loss or, in the cap
200
- // case, a flood of unanchorable arrivals (real or attacker-driven) that
201
- // exceeded the queue budget. See enqueuePendingVerify for the rate-limit
202
- // protocol.
203
- interface PendingVerify {
204
- seq: number;
205
- auth: Uint8Array;
206
- payload: Uint8Array;
207
- arrivalTs: number;
208
- }
209
- const pendingVerify = new Map<number, PendingVerify>();
210
- let pendingVerifyCap = 0;
211
- let pendingVerifyTtlMs = 0;
212
-
213
167
  // --- Helpers ---
214
168
 
215
169
  function emit(event: FecWorkerEvent, transfer?: Transferable[]): void {
@@ -234,7 +188,6 @@ function clearBlockTracking(): void {
234
188
  acceptedSourceEsis.clear();
235
189
  acceptedRepairEsis.clear();
236
190
  unplacedSources.clear();
237
- pendingVerify.clear();
238
191
  recoveryTimes.length = 0;
239
192
  liveSbn = 0;
240
193
  liveSbnKnown = false;
@@ -350,163 +303,6 @@ function retireUnplacedSources(): void {
350
303
  }
351
304
  }
352
305
 
353
- /**
354
- * Run detached ALTA verify against the current verifier. Four-state result:
355
- * - "valid": crypto passed, packet authentic. Caller increments altaVerified.
356
- * - "failed": crypto confirmed tamper (MAC/sig mismatch, hash chain mismatch).
357
- * Caller increments altaFailed. Not retryable.
358
- * - "pending": anchor missing (MAC refs not in buffer, no signature, not
359
- * early-warmup). Caller may enqueue for retry after the next
360
- * successful verify seeds the ring buffer.
361
- * - "error": verifier threw — WASM trap, unmarshal panic, OOM. Caller
362
- * increments altaError (infrastructure flake, not tamper).
363
- * The distinction matters for ops alerting: a spike in
364
- * altaError indicates a runtime problem, not an attack.
365
- */
366
- let _lastVerifyError = "";
367
- function runDetachedVerify(
368
- auth: Uint8Array,
369
- payload: Uint8Array,
370
- ): "valid" | "failed" | "pending" | "error" {
371
- if (!altaVerifier) return "pending";
372
- try {
373
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
374
- const r: any = altaVerifier.verifyDetached(auth, payload);
375
- if (r.valid) {
376
- _lastVerifyError = "";
377
- return "valid";
378
- }
379
- const err = (r.error as string | undefined) ?? "";
380
- _lastVerifyError = err;
381
- // The bootstrap-friendly verifier returns this specific error string when
382
- // the only obstacle to verification is a missing anchor (see alta-rs
383
- // verifier.rs verify()). Distinguishing this from tamper cases keeps us
384
- // from queuing packets that are definitively invalid.
385
- if (err.startsWith("No trust anchor")) return "pending";
386
- return "failed";
387
- } catch (e) {
388
- // Ratelimit: first ~N occurrences get logged. A sustained exception
389
- // stream indicates a real problem — the altaError counter is the
390
- // durable signal.
391
- if (altaError < 5) {
392
- console.warn("[FecWorker] verifyDetached threw:", e);
393
- }
394
- return "error";
395
- }
396
- }
397
-
398
- /** Extract u32 BE sequence number from the ALTA authenticator header (offset 0..3). */
399
- function seqFromAuth(auth: Uint8Array): number {
400
- return (
401
- ((auth[0]! << 24) | (auth[1]! << 16) | (auth[2]! << 8) | auth[3]!) >>> 0
402
- );
403
- }
404
-
405
- /**
406
- * Enqueue a packet whose ALTA verification returned "pending" (anchor
407
- * missing). Dedupes by sequence number.
408
- *
409
- * Flood resistance (08-08 review): when the queue is at cap we do NOT
410
- * evict the oldest entry. The oldest entry is typically the most
411
- * load-bearing one — it's the packet whose anchor everything else in the
412
- * queue is waiting on. Evict-oldest-on-insert let an attacker emitting a
413
- * stream of "No trust anchor" packets flood out legitimate entries and
414
- * prevent them from ever anchoring. Instead:
415
- * 1. First try to free stale TTL'd entries (they'd be evicted on next
416
- * drain anyway — pulling that forward is free).
417
- * 2. If still full, reject the NEW entry. altaPendingEvictedCap counts
418
- * these rejections (rate-limit trigger).
419
- *
420
- * Stores Uint8Array views into the original data + auth buffers — no copy.
421
- * The views keep their underlying ArrayBuffers alive via GC references.
422
- */
423
- function enqueuePendingVerify(
424
- auth: Uint8Array,
425
- payload: Uint8Array,
426
- ): void {
427
- const seq = seqFromAuth(auth);
428
- if (pendingVerify.has(seq)) return;
429
-
430
- if (pendingVerify.size >= pendingVerifyCap) {
431
- // Step 1: sweep stale entries so legitimate traffic isn't penalized
432
- // by TTL'd junk that happens to still occupy slots.
433
- const now = performance.now();
434
- for (const [staleSeq, entry] of pendingVerify) {
435
- if (now - entry.arrivalTs > pendingVerifyTtlMs) {
436
- pendingVerify.delete(staleSeq);
437
- altaPendingEvictedTtl++;
438
- }
439
- }
440
- // Step 2: if the queue is still at cap it's a genuine flood —
441
- // reject the new entry rather than evict an existing one. The
442
- // rejected packet counts as altaPendingEvictedCap (which is
443
- // surfaced up through stats for rate-limit alerting).
444
- if (pendingVerify.size >= pendingVerifyCap) {
445
- altaPendingEvictedCap++;
446
- return;
447
- }
448
- }
449
-
450
- pendingVerify.set(seq, {
451
- seq,
452
- auth,
453
- payload,
454
- arrivalTs: performance.now(),
455
- });
456
- }
457
-
458
- /**
459
- * Retry every queued entry. Called after every successful verify (direct
460
- * source or FEC-recovered) — new raw bytes in the verifier's ring buffer may
461
- * unblock previously-pending MAC references.
462
- *
463
- * Three outcomes per entry:
464
- * - "valid" → remove from queue, altaVerified++
465
- * - "failed" → remove from queue, altaFailed++ (tamper on retry)
466
- * - "pending" → keep in queue, unless TTL expired (then evict as altaPending)
467
- *
468
- * Iteration order: Map preserves insertion order, so we drain oldest-first.
469
- * No-op when the queue is empty or the verifier isn't ready.
470
- */
471
- function drainPendingVerify(): void {
472
- if (pendingVerify.size === 0 || !altaVerifier) return;
473
- const now = performance.now();
474
- // Collect keys to avoid mutating Map during iteration
475
- const keys = Array.from(pendingVerify.keys());
476
- for (const seq of keys) {
477
- const entry = pendingVerify.get(seq);
478
- if (!entry) continue;
479
- if (now - entry.arrivalTs > pendingVerifyTtlMs) {
480
- pendingVerify.delete(seq);
481
- altaPendingEvictedTtl++;
482
- continue;
483
- }
484
- const result = runDetachedVerify(entry.auth, entry.payload);
485
- if (result === "valid") {
486
- pendingVerify.delete(seq);
487
- altaVerified++;
488
- } else if (result === "failed") {
489
- pendingVerify.delete(seq);
490
- altaFailed++;
491
- if (altaFailedDetails.length < 16) {
492
- altaFailedDetails.push({
493
- seq: entry.seq,
494
- error: _lastVerifyError,
495
- authLen: entry.auth.length,
496
- payloadLen: entry.payload.length,
497
- path: "pending-retry",
498
- });
499
- }
500
- } else if (result === "error") {
501
- // Infrastructure failure — remove from queue, count as altaError.
502
- // Keeping it around would just re-throw on every subsequent drain.
503
- pendingVerify.delete(seq);
504
- altaError++;
505
- }
506
- // "pending" → leave in queue for next drain
507
- }
508
- }
509
-
510
306
  /**
511
307
  * Look up or create a block. `isoSsbLength` creates an iso-ssbg1-v1 block,
512
308
  * whose K' is its SSB_length (C.5.3); without it the block has the catalog K.
@@ -528,7 +324,6 @@ function getOrCreateBlock(sbn: number, isoSsbLength?: number): FecBlockSnapshot
528
324
  // A positive interleaveMs makes this the catalog completion deadline;
529
325
  // zero makes deliveryWindowMs a receiver-local cleanup bound.
530
326
  deadlineTs: now + config.deliveryWindowMs,
531
- altaVerified: 0,
532
327
  relayBlockSigValid: null,
533
328
  };
534
329
  if (isoSsbLength !== undefined) block.ssbLength = isoSsbLength;
@@ -581,15 +376,6 @@ function buildStatsSnapshot(): FecTrackStats {
581
376
  (blocksRecovered / (blocksRecovered + blocksFailed)) * 100,
582
377
  ) || 0
583
378
  : 0,
584
- altaVerified,
585
- altaFailed,
586
- altaPending,
587
- altaPendingEvictedCap,
588
- altaPendingEvictedTtl,
589
- altaError,
590
- altaInitFailed,
591
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
592
- altaFailedDetails: altaFailedDetails.slice() as any,
593
379
  relayBlocksVerified,
594
380
  relayBlocksFailed,
595
381
  liveSbn,
@@ -658,15 +444,8 @@ function emitRecoveredSymbols(
658
444
  continue;
659
445
  }
660
446
 
661
- // Source authentication now runs once at router admission in
662
- // @blockcast/mmt-manifest-verify. The worker only records that this
663
- // legacy ALTA-enabled symbol bypassed hot-path verification.
664
- const recoveredAltaVerified: boolean | null = null;
665
- if (altaEnabled) altaPending++;
666
-
667
447
  const buf = toOwnedArrayBuffer(symbol);
668
448
  const meta: FrameMeta = {
669
- altaVerified: recoveredAltaVerified,
670
449
  recovered: true,
671
450
  sbn,
672
451
  esi: i,
@@ -835,7 +614,6 @@ function feedIsoSource(
835
614
  advanceMediaHorizon(cmd.ssId);
836
615
  unplacedSources.set(cmd.ssId, performance.now());
837
616
  sourceSymbols++;
838
- if (altaEnabled) altaPending++;
839
617
  // No repair has named this source's block, so the decoder cannot have
840
618
  // one to recover; data here is a Worker/decoder disagreement that
841
619
  // cannot be attributed to a block, and is refused rather than guessed.
@@ -871,7 +649,6 @@ function feedIsoSource(
871
649
  block.sourceReceived++;
872
650
  block.lastSymbolTs = performance.now();
873
651
  sourceSymbols++;
874
- if (altaEnabled) altaPending++;
875
652
  settleSourceArrival(key, block, result);
876
653
  }
877
654
 
@@ -1040,54 +817,6 @@ async function handleConfigure(
1040
817
  verifyDecoderProfile(decoder, blockProfile);
1041
818
  wasmDecoder = decoder;
1042
819
  config = cmd.config;
1043
- altaEnabled = !!cmd.altaPublicKey;
1044
-
1045
- // Size the deferred-verify queue strictly from catalog-derived FEC
1046
- // parameters. CLAUDE.md bans Math.max(x, floor) magic — if catalog
1047
- // values are zero/missing, throw at init rather than silently applying
1048
- // a hardcoded floor. Consumers of an undersized queue cap would see
1049
- // altaPendingEvictedCap spike with no actionable signal.
1050
- // Cap: 1.5× interleave depth — wide enough to hold one full FEC recovery
1051
- // window plus jitter, narrow enough to bound memory.
1052
- pendingVerifyCap = Math.ceil(config.interleaveDepth * 1.5);
1053
- // TTL: preserve the existing 1.5× K-tick lifetime when a positive span is
1054
- // signaled. A zero span has no media cadence, so use the supplied local
1055
- // cleanup budget rather than manufacturing one from an inferred frame rate.
1056
- const verifyWindowMs = config.interleaveMs > 0
1057
- ? config.interleaveMs * config.k
1058
- : config.deliveryWindowMs;
1059
- pendingVerifyTtlMs = Math.ceil(verifyWindowMs * 1.5);
1060
-
1061
- // Initialize ALTA WASM verifier if public key and WASM module provided (D-05, D-09)
1062
- altaVerifier = null;
1063
- altaInitFailed = false;
1064
- if (cmd.altaPublicKey && cmd.altaWasmModule) {
1065
- try {
1066
- // Load ALTA JS glue (wasm-bindgen output from wasm-pack build).
1067
- // Mirrors the RaptorQ WASM pattern: initSync({ module }) then construct.
1068
- // Dynamic import path matches the IWA static asset layout.
1069
- // Cast via string to prevent TypeScript from attempting static resolution
1070
- // of a runtime-only URL (same pattern as fec-worker-entry.js loading).
1071
- const altaGlueUrl = '/wasm/alta/alta_rs.js' as string;
1072
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1073
- const altaGlue: any = await import(/* webpackIgnore: true */ altaGlueUrl);
1074
- altaGlue.initSync({ module: cmd.altaWasmModule });
1075
- const keyBytes = new Uint8Array(cmd.altaPublicKey);
1076
- altaVerifier = new altaGlue.JsAltaVerifier(keyBytes);
1077
- } catch (e) {
1078
- // T-08-15: WASM init failure must NOT silently look like "not-ready-yet".
1079
- // Force altaEnabled = false so handleFeedSource takes the disabled
1080
- // branch instead of continuously bumping altaPending under the
1081
- // misleading "verifier not yet ready" comment. altaInitFailed
1082
- // flag in the snapshot tells consumers this is an error state, not
1083
- // an opt-out.
1084
- console.warn('[FecWorker] ALTA WASM init failed, verification disabled:', e);
1085
- altaVerifier = null;
1086
- altaEnabled = false;
1087
- altaInitFailed = true;
1088
- }
1089
- }
1090
-
1091
820
  wasmDecoder.configure_params(config.k, config.symbolSize);
1092
821
 
1093
822
  // Tell the client which optional commands this Worker accepts, so it can
@@ -1163,8 +892,8 @@ function handleRelayBlockSig(
1163
892
  // No-op AUTH stub: store sig on block, mark as not-yet-verified
1164
893
  const block = blocks.get(cmd.sbn);
1165
894
  if (block) {
1166
- // Real verification deferred to ALTA milestone
1167
- // For now, mark as null (not verified) — will be wired when ALTA is implemented
895
+ // Relay block signatures are not verified here; source provenance is the
896
+ // signed per-group manifest checked at router admission.
1168
897
  block.relayBlockSigValid = null;
1169
898
  emitBlockUpdate(block);
1170
899
  }
@@ -1234,29 +963,12 @@ function handleDispose(): void {
1234
963
  snapshotTimer = null;
1235
964
  }
1236
965
 
1237
- // Free ALTA verifier WASM object (MUST call to release WASM memory —
1238
- // Worker.terminate() fires immediately after dispose, so the FinalizationRegistry
1239
- // callback has no chance to run and this memory would leak without explicit free)
1240
- if (altaVerifier) {
1241
- try {
1242
- altaVerifier.free();
1243
- } catch (_e) {
1244
- // Best-effort — verifier may already be freed
1245
- }
1246
- altaVerifier = null;
1247
- }
1248
-
1249
966
  // Free WASM decoder (MUST call to release WASM memory)
1250
967
  if (wasmDecoder) {
1251
968
  wasmDecoder.free();
1252
969
  wasmDecoder = null;
1253
970
  }
1254
971
 
1255
- // Clear deferred-verify queue so pinned ArrayBuffers drop.
1256
- pendingVerify.clear();
1257
- pendingVerifyCap = 0;
1258
- pendingVerifyTtlMs = 0;
1259
-
1260
972
  config = null;
1261
973
  clearBlockTracking();
1262
974
  }
@@ -1283,13 +995,6 @@ function handleReset(): void {
1283
995
  blocksComplete = 0;
1284
996
  blocksRecovered = 0;
1285
997
  blocksFailed = 0;
1286
- altaVerified = 0;
1287
- altaFailed = 0;
1288
- altaFailedDetails.length = 0;
1289
- altaPending = 0;
1290
- altaPendingEvictedCap = 0;
1291
- altaPendingEvictedTtl = 0;
1292
- altaError = 0;
1293
998
  relayBlocksVerified = 0;
1294
999
  relayBlocksFailed = 0;
1295
1000
  repairSymbolSizeMismatch = 0;
@@ -1339,8 +1044,7 @@ async function dispatchCommand(cmd: FecWorkerCommand): Promise<void> {
1339
1044
  try {
1340
1045
  switch (cmd.type) {
1341
1046
  case "configure":
1342
- // handleConfigure is async (ALTA WASM init uses dynamic import).
1343
- // Await it so feed/cleanup messages cannot run against a partially
1047
+ // Await handleConfigure so feed/cleanup messages cannot run against a partially
1344
1048
  // configured decoder.
1345
1049
  await handleConfigure(cmd);
1346
1050
  break;