Commit Graph
3707 Commits
Author SHA1 Message Date
Jason Huebert cbdc445488 docs: describe the v7 named-step migration chain and per-record CRC in AGENTS.md
The support-window note now names the excision procedure (delete the step
function, raise the floor in rule_bytes_for(), delete its fixtures); the
config-integrity bullet reflects that v7 rule records carry a CRC-16 while
channel records and the battery config stay length-only until their own
layout change. Suite counts updated (294 filter cases).
2026-10-06 16:05:37 -05:00
Jason Huebert 96bf7917cc feat(filter): config v7 — all payload types, capacity expansion, per-record CRC with stepwise v3..v7 migration
One version bump covers: the five high payload types become nameable
(path, trace, multipart, control, raw; type_mask_hi joins the record at
byte 186), the capacity knobs double (32 rules, 32 channels, sender 24->32,
text 48->64, advert cache 256->512, chan_mask u16->u32), and each rule
record gains a CRC-16/CCITT-FALSE over its 188 payload bytes (record on
disk: 190 B). The pad byte at 187 is format-guaranteed zero: the writer
forces it, the reader refuses a record that has it set.

parseConfigFile() replaces its inline per-version fixups with a named
migration chain — one step function per version pair (v3->v4 ... v6->v7),
applied in order, so retiring a version later is one excision. A pre-v7
record whose sender/text/regions did not terminate inside the OLD field
widths is still refused up front: migrating would terminate the copy and
mask a record the old firmware could never have written.

Also fixed a latent bug the wider store exposes: cliChanList's pass-2
hold-back could be eaten by the last entry, truncating the '; next=N'
marker (first reachable now that page indexes go two-digit).

FILTER.md: type table rows, trace/control visibility caveats, updated
limits (32/32/31/63), status-line examples, and a new 'Config file
format' section documenting v7, the per-record CRC and the downgrade
caveat.
2026-10-06 16:05:32 -05:00
Jason Huebert 27b75819a7 feat(filter): type= predicate for REQ, RESPONSE, TXT_MSG, ACK, ANON_REQ
The filter already sees every payload type the repeater would relay; type=
could only name advert/txt/data. Add the five low-byte encrypted/auxiliary
types as names (req, response, msg, ack, anonreq), driven by one shared
name/type table that both the parser and the renderer use. Render order keeps
advert,txt,data first so replies for pre-existing rules stay byte-identical.

Same commit, the content-predicate guard: sender=/text=/chan= can only ever
be decided on decrypted group traffic, so a rule narrowed to envelope-only
types (e.g. type=advert sender=...) would sit deferred forever and never
match. add now rejects that with 'Err - sender=/text=/chan= only match group
traffic'; rules with type= unset or including a group type keep working.

The 0x80 bit of type_mask is now a defined value (ANON_REQ), so the
malformed-record fixture case that used it as garbage is removed; the
fully-loaded-rule truncation test switches type=advert -> type=txt because
its chan= predicate would now be rejected alongside an advert-only type.

FILTER.md: type table rows, encrypted-payload subsection, ACK visibility
caveat.
2026-10-06 15:45:00 -05:00
Jason Huebert d669190a10 ci: stop the shell comment spelling an empty template expression
GitHub evaluates template expressions in run: blocks even inside
shell comments, so the literal empty expression in the env-hardening
comment was parsed as a syntax error and filter-build.yml failed
validation before any job could start. Describe the idiom in words.
2026-10-05 15:52:01 -05:00
Jason Huebert fc41b2150f Merge remote-tracking branch 'fork/repeater-filter' into repeater-filter 2026-10-05 15:43:04 -05:00
Jason Huebert 4150320ff7 Merge branch 'repeater-filter-quality' into repeater-filter 2026-10-05 15:41:38 -05:00
github-actions[bot] ccd50b4725 Merge remote-tracking branch 'origin/dev' into repeater-filter filter-v1.17.1-dev.13 2026-10-05 10:46:02 +00:00
Liam Cottle 3e3150c83f Merge pull request #3538 from meshcore-dev/hidden-repeater
Hidden repeater
2026-10-04 20:10:43 +13:00
Scott Powell f19733e478 * don't respond to DISCOVER requests if node has adverts turned off. (isHiddenNode()) 2026-10-04 15:02:00 +11:00
Jason Huebert 99b3085aa9 ci: promote from the revision that was actually verified
A stable_source branch that exists only as origin/<name> passed the
rev-parse check, then git cherry was handed the nonexistent local name and
failed — with `|| true` around the pipeline that became an empty pick list, so
the promotion published stable without a single commit from the branch it was
dispatched for. The README was taken from repeater-filter in that case too.

The verified revision is now resolved once and used for the cherry and for the
fork README, which also covers a source branch that is the one checked out in
this worktree (git branch --force would refuse that). git cherry runs on its own
so a real failure aborts the step instead of looking like "nothing to pick".

Verified against throwaway repositories: the default source, a source that
exists only on the remote, and an unknown source that is refused with stable
untouched.
2026-10-03 17:03:00 -05:00
Jason Huebert 8f59daee90 ci: give the stable promotion gate a toolchain
The gate runs `pio test` but this job never installed PlatformIO, so every
deliberate promotion failed on ubuntu-latest before a single rule was tested.
It now uses the same composite setup action as the build workflow.
2026-10-03 16:59:41 -05:00
Jason Huebert 6b6d293516 ci: build and tag the revision the release names
The version job recorded a source SHA and the release body, tag and per-target
manifests all name it, but the build jobs checked out the branch. A push between
those jobs would have shipped firmware from a newer revision than every one of
them claimed — which is exactly the release-coverage claim the manifests exist
to make honest.

Both downstream checkouts now pin the recorded SHA, so the target list and the
firmware come from the same tree the release describes.
2026-10-03 16:59:11 -05:00
Jason Huebert e5d872a179 ci: actually summarise the boards a release published
Three defects in one step, found by running its shell against a real manifest:

- it globbed out/manifest-*.txt AFTER moving those files to .manifests/, so
  every release reported that no build manifests were produced
- printf "$SUMMARY" treats a leading "-" as an option and exits 2, so the step
  would have failed outright once the manifests were found
- the heading carried literal \n\n text, which glued the first board name onto
  the heading line in the rendered release body

Manifests are read from .manifests/, printed with %b, and the header joins the
same expansion. Verified against one build, a partial build and no builds.
2026-10-03 16:58:26 -05:00
Jason Huebert 75bb867fd9 fix(filter): refuse a trailing word on chan add and chan del
Both channel commands consumed only the tokens they needed and ignored the rest
of the line, so `filter chan del Public typo` reported OK and deleted the
channel — the one failure mode this branch refuses everywhere else, where a
mistake that still changes the config can lock an admin out.

Each now rejects an unexpected extra word with its own usage line before
touching the store.
2026-10-03 16:55:57 -05:00
Jason Huebert a4f00e8687 fix(filter): keep a rejected rule record from shifting the channel records
parseConfigFile() stopped reading rules at the first record it could not adopt
and then read channels from that position, so the next rule record's bytes were
adopted as a channel: with a two-rule config whose first rule was rejected, a
channel written by this firmware came back as a bogus entry instead of Public.

Record sizes are fixed, so a rejected record now ends the rule LIST while the
records after it are still consumed. Channels are read only when every rule
record the header promised arrived — a truncated rule region leaves their offset
unknown, which is the case that already loaded nothing.
2026-10-03 16:54:49 -05:00
Jason Huebert 370c6794e9 fix(filter): time the content rules on the same monotonic clock
checkContent() read a raw millis() value while checkPacket() folds millis()
into a 64-bit accumulator. Both phases write the same rule's throttle state, so
a millis() wrap made a 32-bit comparison read as 49.7 days: a throttled rule
handed out a fresh pass milliseconds after the last one, and a rule that
alternated between the packet and content phases never throttled at all.

The content scan now takes its clock from uptimeMillis(), once per scan, so
both phases agree on elapsed time across a wrap.
2026-10-03 16:53:21 -05:00
Jason Huebert 8279dbdbee test: make four assertions reach the code path they name
Each of these passed for the wrong reason, so the defect it was written to
catch would have slipped through:

- prob=100 was never evaluated: the earlier unconditional drop rule ended the
  scan first, so clear the rule before exercising it.
- the shared packet hash was counted across two rules the region predicate had
  already excluded; make every rule eligible and use a failed roll, so all
  three are reached and a per-rule hash would show up.
- the 50-day throttle test jumped a single truncated clock step, which is
  ~7 hours and already past its 60 s window, so a lost millis cycle passed.
  Tick the accumulator through the whole period, as loop() does.
- the rejected-key test compared one byte of the Public channel, so corrupting
  any other byte passed. Compare the whole record.
2026-10-03 16:52:16 -05:00
Jason Huebert c7d68aa541 refactor: drop the redundant verdict reset and the duplicate list-copy helper
resetToDefaults() already clears the content verdict through
clearContentVerdict(), so the later assignment could not do anything. And the
local copyCsvList() duplicated the bounded copy that CliUtil.h already owns;
all four comma-list callers now use cliCopyCommand(), which refuses an
oversized value exactly as before.
2026-10-03 16:51:59 -05:00
Jason Huebert 83515481c8 test: drop two assertions that could not fail and write no clearer
EXPECT_FALSE(x == false) is EXPECT_TRUE, and the strlen comparison asserted
against a literal the same test already matched, as did the unused snprintf
into a scratch buffer.
2026-10-03 16:18:40 -05:00
Jason Huebert ab905d5ba1 ci: let the sanitizer envs link from build_flags alone
build_flags already carries -fsanitize=address,undefined, which PlatformIO
passes at link time too; the link_flags stanza repeated it for no effect.
Verified both san envs still link the asan/ubsan runtimes and pass.
2026-10-03 16:18:40 -05:00
Jason Huebert e898e2d0df docs: point the comments and guides at what is actually there
Two PacketFilter comments cited sections of a plan document nobody reading the
source has, the limiter's key-offset comment and the test helper's mirror note
named the wrong file, and two FILTER.md troubleshooting rows sat above the
table header they belong under.
2026-10-03 16:18:40 -05:00
Jason Huebert 1896b68c79 refactor: drop the filter's dead quote re-check and the limiter's unused steps
cliAdd() counted quotes to refuse an unbalanced command, but filterCLI() already
rejects one and the tokenizer leaves nothing here that could be misparsed.
AdvertRateLimiter::refreshExpired() and enabled() have no callers; the window
stamp is refreshed by recordForward() on admission, and reset() now reuses
clearCache() instead of repeating its three lines behind a private impl.
2026-10-03 16:18:34 -05:00
Jason Huebert 07448979d0 fix(filter): derive the chan list index range from the channel capacity
The refusal said 0..15 while the parse bound is FILTER_MAX_CHANNELS - 1, so an
overridden build rejected an index it had just called valid. At the default
capacity of 16 the reply is byte-identical.
2026-10-03 16:18:30 -05:00
Jason Huebert fb53dab2a4 ci: drop the sync-upstream changed output nothing consumes
dev_changed and stable_changed gate the downstream jobs; the combined changed
output was replaced by those two and no longer had a reader.
2026-10-03 16:18:30 -05:00
Jason Huebert f468070d0d ci: build the release manifest outside out/ so it cannot list itself
The manifest globbed out/*.txt, and the shell created out/manifest-$TARGET.txt
before the glob ran, so each manifest listed its own half-written file with a
sha256 of nothing. Write it beside out/ and move it in afterwards.
2026-10-03 16:18:28 -05:00
Jason Huebert 6ca90eb874 docs: correct the fork guide's build and test instructions
`xiao_s3_wio` is not an environment — `pio run -e xiao_s3_wio` fails with
UnknownEnvNamesError. The real one is `Xiao_S3_WIO_repeater`, confirmed against
`bash build.sh list`. The guide also said `sh build.sh`, which only worked here
because this machine's sh is bash; the script uses bash arrays.

Also records three things this work made load-bearing, each of which cost time
or a wrong conclusion before it was written down:

- Compile-check every filesystem family, not just the main target. Host-native
  tests cannot catch a platform-specific API difference, and RAK_4631 caught one:
  its file type has no default constructor, so the persistence code passed every
  host test and would not compile for nRF52.
- PlatformIO does not track the force-included NativeShim.h as a dependency, so
  a struct change there leaves stale objects that silently disagree with the new
  layout. Clean the native envs after changing it.
- The full four-env test run belongs in the verification list, since the generic
  envs are where a broken test selection shows up.

Test counts updated to the current 278 filter / 44 battery.
2026-10-03 15:30:21 -05:00
Jason Huebert 6d5ae80c4e ci: promote stable deliberately, and make releases say what they contain
Stable was promoted by the weekly schedule: every missing filter commit was
cherry-picked unattended, and on a conflict the pick was aborted, the loop
`break` out, and the branch was pushed anyway. That publishes a half-applied
feature series as the stable release users install.

Stable is now promoted only by dispatching with promote_stable. The promotion
runs entirely on a scratch branch and touches the real branch exactly once, at
the end: upstream main is merged, the fork-owned README is restored BEFORE the
merge commit exists, the filter commits are picked, the native test gate runs,
and only then is stable pushed — never with --force, so a non-fast-forward
rejection is the correct outcome if something else moved meanwhile. A conflict
at any step fails the job with stable untouched, and the merge's bare
`|| true` is gone: a git error that leaves no merge in progress is now an error
rather than being mistaken for "already up to date". Only the channel that
actually moved gets built.

Release integrity:

- Dev publishes what built, with a per-target manifest naming the target, the
  source SHA and the SHA-256 of every file produced; the release notes list the
  boards included. Stable blocks on any requested board failing, because it is
  what users install. Neither is silently a complete release.
- `sh build.sh list` -> `bash build.sh list`; the script uses bash arrays and
  /bin/sh is not a contract (it worked locally only because this machine's sh is
  bash).
- Branch, targets and the repo variable are passed through env, never spliced
  into shell text: an input containing a quote was becoming shell syntax.
- Every build clears `out/` first and uploads with if-no-files-found: error, so
  a stale artifact or an empty one cannot pass for a successful build.
- Dev tag numbers come from the highest existing suffix, not count+1, which
  collided once a tag was deleted.
- The changes block uses a generated delimiter; a commit subject containing the
  fixed CHANGES_EOF line truncated the release notes.
- build.sh appends its own -<short sha>, so the workflow no longer doubles it.
- The build gate no longer uses --no-merges, which hid merge-only conflict
  resolutions from it.
- Job permissions are contents: read, with contents: write only on the release
  job; the release names the exact source SHA it was built from.

Validated against fixture repos, never a production release: a clean
multi-commit promotion, a series whose second pick conflicts, and a series
whose first pick succeeds and second conflicts. The last is the regression —
the old logic publishes that partial series (confirmed by running it), the new
one leaves stable byte-identical.
2026-10-03 15:27:37 -05:00
Jason Huebert 3c47aa7126 docs: make the guides describe the code that actually runs
FILTER.md, BATTERY.md and AGENTS.md all carried claims the implementation does
not support. Several are ones an operator would act on wrongly.

Corrected:

- The filter governs *forwarding*, not every packet that arrives. Traffic
  addressed to the repeater itself is answered directly and never gated, and
  direct-route group traffic is not decrypted here, so chan=/sender=/text= cannot
  match it at a relay.
- "Never lock out your own admin" recommended a chan=/sender= exception as if it
  authorised remote admin. It does not: the exception is about the relay path,
  and the previous wording implied a security property the filter does not have.
  Replaced with what is actually true, plus a reachability qualification — this
  node answers for itself, but reaching it still needs working relays.
- Added the honest framing the guides were missing: a rule is content policy, not
  authentication. A sender name is freely chosen, a channel key is shared, and
  the protocol tag is two bytes. Treating these as identity is the mistake the
  section should have warned about.
- Probability: the guide said a retransmitted copy "is a new packet and rolls
  again". A relay copy rolls identically — the roll comes from payload and type,
  so it is the same message. Only a genuinely new message rerolls.
- Airtime is now described as an estimate of what dropped packets would have
  cost, usable as a with/without comparison, not as channel utilisation or a
  count of confirmed transmissions.
- The logonly → forward compatibility claim said old firmware "behaves
  identically" while the next paragraph said ordering changed. Now separated:
  the stored byte means the same thing, the evaluation does not.
- Battery: a reboot does not make the gate correct immediately — suspension needs
  a second reading ~30 s later, and the debounce restarts after a reboot.
  Suspension does not guarantee end-to-end reachability through other repeaters.
- Quick start no longer implies `filter on` is required on a fresh node; it is
  belt-and-braces, and the guide now says so.
- Interval limits stated: snr is signed quarter-dB rounded to the nearest
  quarter, plain numeric endpoints are unsigned and cap at 32767, a len= larger
  than the packet buffer is valid syntax that can never match, and hsize=4 is
  protocol-reserved rather than an on-air size.
- An aborted pattern disables only its own rule, not the filter — a later drop
  can still decide. Previously read as a whole-filter bypass.
- Deleting the last channel a rule named leaves it matching nothing rather than
  turning it into a catch-all.

Also fixed the stale comments the review flagged: PacketFilter.cpp still said
"Binary format (version 2)" while saving v6, the rule size was recorded as ~151 B
against a real 180 B, and AGENTS.md's ownership map omitted AdvertRateLimiter and
PersistUtil. AGENTS.md's round-trip claim is corrected to what `filter get`
actually is, plus the chan list continuation.

376 cases green.
2026-10-03 15:20:43 -05:00
Jason Huebert 4fe828ccaf perf(filter): time the rate gates on a 64-bit monotonic clock
Unsigned subtraction of a 32-bit millis() handles exactly one wrap: it cannot
tell 49.7 days + 1 s from 1 s. A repeater left up long enough therefore
spuriously rate-limited a rule or an advert origin on its return — the window
reads as barely started when it lapsed days ago. The longest window the CLI
accepts (720 h) never exceeds a wrap, which is what made this look safe; the
wrap is about uptime, not window length.

FilterRules now folds the 32-bit millis() into a uint64_t accumulator, and the
advert window and per-rule throttle both stamp on it. filter.loop() advances it
unconditionally, so an idle repeater still notices the wrap; the fold is safe to
call from the receive path too, since equal readings add zero. Nothing here is
persisted, so no record bytes and no config version change. BatteryGate is left
alone — its interval is 30 s and it already uses the wrap-safe idiom.

Measured on the tightest target, RAK_4631 (nRF52): RAM 43,448 -> 45,568 bytes,
18.4% -> 19.3%. Xiao_S3_WIO_repeater 67,464 -> 69,584 bytes, 20.6% -> 21.2%.
PicoW and wio-e5 still compile.

ThrottleWrapAround was pinning the bug, not a behaviour: it called 16 real
seconds "past the 30 s window" because the wrap read them as 49.7 days. It now
asserts real elapsed time, and a new test covers a rule and an advert dormant
for 50 days. That test has to tick the clock the way a loop would: the fold sees
one wrap per call, so an idle period longer than that only counts correctly if
the loop kept running through it — which is the design's precondition, now
written down rather than assumed.

376 cases green across all four native envs, 322 clean under sanitizers.
2026-10-03 15:14:43 -05:00
Jason Huebert aa95460abb fix(filter,battery): refuse malformed commands instead of half-applying them
A typo'd tail was silently ignored while the command still replied OK:
`filter off junk`, `del 0 junk`, `move 0 1 junk`, `ratelimit advert 48 junk`
and `battery off junk` all reported success. That is the worst failure mode a
management command has — the operator cannot tell whether the command did what
they meant, or something else, or nothing.

Every command form now refuses a trailing token with its own usage line, checked
BEFORE any side effect, via one shared cliNoExtra() helper rather than a copy per
command. An unbalanced quote is an error on every form, not just `filter add`,
because the tokenizer would otherwise swallow the rest of the line into one
value. An over-long command is refused whole: truncating it and acting on the
prefix is safe memory but not safe policy — a cut `chan add` would store a
mangled name. parseIntRange() now also checks ERANGE and leaves its output
untouched on failure, so a rejected number cannot leave a stale one behind.

`filter chan list <start-idx>` lets a full 16-channel store be walked: the reply
cannot fit them all, and `chan del` takes a NAME, so a channel cut off by the
reply buffer could neither be seen nor reliably removed. A truncated listing now
ends with `next=N`; entries are only ever appended whole, and the bare listing
keeps its old format whenever everything fits.

`filter stats reset` exposes the resetStats() that already existed and had no
CLI route. Counters go: per-rule hits, airtime, limiter drops, regex aborts.
Rate state does NOT: throttle_seen/throttle_last_ms survive, so a stats reset
cannot hand a throttled rule a free pass. Advert history is history, not a
counter, and is kept.

375 cases green across all four native envs, 321 clean under sanitizers, firmware
compiles.
2026-10-03 15:03:25 -05:00
Jason Huebert 209a060a46 fix(filter): bracket the content verdict, gate content on the battery, and
start advert windows on admission

Three receive-path defects, all about state that outlived the operation that
produced it.

The content verdict stash was cleared only inside `if (content_verdict.pkt ==
pkt)`, so a verdict for a packet that never reached the forwarding hook — dropped
earlier, or on a path that skips forwarding — lingered until some later packet
reused that buffer. It is now consumed unconditionally in checkPacket(), and
MyMesh::onRecvPacket() brackets one whole receive with clearContentVerdict() on
both sides, which is what actually bounds its life. The pointer+hash guard stays
as defence in depth against pool reuse. Any rule or channel mutation clears it
too (markDirty() is the one place they all pass through), as do enable toggles
and reload, so a verdict can never be honoured under a rule list it was not
decided under.

The battery gate outranked the filter only for packets that could not be
decrypted. Decryptable group traffic ran the content rules and banked hits and
airtime while a suspended repeater was refusing to relay it, and could spend a
content throttle's free-pass budget — two different stories for one suspension.
onGroupDataRecv() now returns early while suspended, so the packet is accounted
as a battery drop at forwarding admission, once. Battery sampling also moved
before Mesh::loop(), so a receive that crosses a sampling boundary sees that
loop's reading rather than the previous one. No per-packet ADC read was added.

The advert rate limiter recorded a node's window inside the check, which runs
before every stock forwarding check — so a repeater left in `set off`, or
refusing adverts for hop-limit, unknown-region or loop reasons, silently stopped
relaying those nodes for the rest of the 48 h window. drop() is split into
wouldDrop(), which only answers, and recordForward(), called from
onForwardAllowed() at the successful end of allowPacketForward(). The window now
means "relayed", not "received". FILTER.md says so, including the honest limit
that a queued advert that never reaches the air still counts as admitted.

Existing limiter tests assumed check implied commit, which was true before and
would have silently tested nothing after. They now drive a forwardPacket()
helper that mirrors the real hook: check, then commit only on survival.

369 cases green across all four native envs, 315 clean under sanitizers, all four
firmware targets compile, RAM unchanged at 20.6%.
2026-10-03 14:51:07 -05:00
Jason Huebert 80468bc8fd fix(persistence): stage every save so a failed write cannot destroy the config
fsOpenWrite() truncated the live config in place — or removed it first on
nRF52/STM32 — so a failed open, a short write or a power cut destroyed the only
good copy. Keeping a RAM dirty flag is not crash recovery, and a battery-powered
repeater is exactly where brownouts happen.

Saves are now a staged transaction in PersistUtil.h, shared by both configs so
there is one implementation: write a scratch file, read it BACK and validate it,
keep the current good file as a backup, then promote. Dirty state clears only
once the new canonical file is committed and validated, so either the complete
old config or the complete new one survives — never a mixture. Loading prefers a
valid canonical file, falls back to the last-good backup, and marks a repair save
pending when it recovered; a boot ignores the scratch file entirely, because an
uncommitted scratch file is not a config.

Config record bytes are unchanged: this is machinery around the file, not a new
format. `.tmp` and `.bak` are filesystem state. Integrity stays length-checked
with no checksum, as chosen.

Three separate questions get three separate callbacks, because conflating them
was a bug during this work: writing records, checking the scratch file holds
exactly what was written, and checking whether an existing file is usable at all.
Using the writeback check for the last one made a valid-but-stale config look
unusable, so it was silently dropped instead of being backed up.

Both features' parsers were extracted so load() and the readback validator share
one definition of "a file this firmware can use" — no second whole filter on the
stack, and validation never touches live counters, rate history or suspension.

The native shim's remove() now returns bool like the real FS API (transaction
code has to be able to insist on it) and can cut a file short on close to model a
power loss mid-write.

RAK_4631_repeater caught a portability bug: its file type has no default
constructor, so handing an open File back through an out-parameter does not
compile. chooseConfigToLoad() returns the chosen PATH and the caller opens it.

356 cases green across all four native envs, 302 clean under sanitizers, and
Xiao_S3_WIO, RAK_4631, PicoW and wio-e5 all compile with RAM unchanged.
2026-10-03 14:28:57 -05:00
Jason Huebert e152803eea fix(persistence): back off a failed save and time both configs in 32 bits
After a failed save due() stayed true on every loop iteration, so a full or
failing filesystem was opened, truncated and removed at firmware-loop speed.
LazySave now has three named operations: clear() for a confirmed write,
retryLater() to stay dirty but wait out another full delay, and reset() to drop
pending work when a reload or a reset-to-defaults supersedes it. load() calls
reset() in both configs, so an edit cannot outlive the file it was meant for.

Timestamps are uint32_t with elapsed time computed in uint32_t. The host's
unsigned long is 64-bit, so writing these fields as unsigned long meant host
tests could not model the wrap the MCU actually has — the wrap tests below were
meaningless before this change.

Battery sampling no longer stores an absolute deadline with 0 as an
"unarmed" sentinel, which conflated a wrapped deadline with an unarmed timer.
It keeps last_sample_ms plus an explicit sample_pending, samples at most once per
loop (never twice to catch up missed intervals), arms on the first loop, re-arms
when thresholds are set or the gate is enabled, and disarms when it is turned
off. The two-consecutive-reading debounce and the immediate first sample are
unchanged; only resume still takes a single reading, as before.

The native shim gained the fault injection R16 anticipated: fail_open, fail_write
and a write-open attempt counter, so the retry cadence is asserted rather than
inferred from whether a file appeared.

Note: PlatformIO does not track the force-included NativeShim.h as a
dependency, so a change to a struct it defines can leave stale test objects.
Cleaning the two native envs before running is the reliable path.

341 cases green across all four envs, 287 clean under sanitizers, Xiao_S3_WIO and
RAK_4631 compile with RAM unchanged at 20.6%.
2026-10-03 13:29:42 -05:00
Jason Huebert faee91272c fix(filter): treat the saved config as untrusted input, not live objects
load() copied bytes straight into live FilterRule/FilterChannel and only
checked a couple of relations afterwards, so a corrupt or hand-made file could
adopt records holding field values this firmware never writes: an undefined
type_mask or route_mask bit, a path chain longer than its slots, an unterminated
sender/text/region string, a prob above 100, a channel key of the wrong length,
or an "enabled" byte of 2, which a bool field converts to plain true before
anything can range-check it.

Records are now read as bytes and validated before they become objects.
Malformed values REJECT the record rather than being masked or clamped:
sanitising would quietly turn a rule into a different rule, and since matching
is first-match-wins that changes which rule decides a packet. Two cases are
deliberate exceptions, both narrowing rather than widening:

- a chan_mask naming a channel the file does not store is confined to the
  channels that exist after the load, not rejected;
- a chan= whose last channel was deleted keeps MASK_SET with an empty mask and
  stays inert, never a catch-all.

A bad header rejects the whole file, because the header describes the file's
shape and a wrong count means we no longer know where records are. A bad record
only ends the load at that point: sizes are fixed, so the valid prefix is
locatable and surviving rules keep their indices, which the CLI's index
semantics depend on.

Also rejects a ratelimit window outside 0..720 h, and states the version map as
3..6 rather than counting back from the current version.

Two existing tests pinned the old all-or-nothing behaviour for a truncated
file; they now assert the prefix property instead — at every truncation length,
only whole records appear, in order, and an adopted record is a whole record
rather than a plausible-looking prefix.

330 cases green across all four native envs, 276 clean under sanitizers, firmware
compiles with RAM unchanged.
2026-10-03 13:12:35 -05:00
Jason Huebert bbc8231445 fix(filter): freeze the on-disk record sizes and test them as literal bytes
load() derived every historical record size from offsetof(FilterRule, ...), so
moving a field silently changed what a v3, v4 or v5 config meant, and an old
config would load as something it never was with no compile error to explain it.
The sizes are now literals — 124 B (v3), 156 B (v4/v5), 160 B (v6), 50 B per
channel — because a format is a promise to bytes already in the field. The
version map also stops subtracting from FILTER_CFG_VERSION, which had the same
drift problem in a different place.

static_asserts tie the frozen numbers to the live struct, so the current
version still fails to compile when a persisted field moves. Verified the
tripwire fires: changing the v6 size to 161 breaks the build with "v6 record
size is frozen at 160 B; the live struct no longer matches". The assert message
says what to do — bump the version and write migration — and never to edit the
numbers to match.

The old-config tests built v3/v4/v5 files by trimming a freshly saved v6 record,
so the fixtures moved with the struct and could not catch the struct breaking
old configs. They are now literal byte values written out per version, with the
fixture section delimited so the migration path and its fixtures come out in one
excision later.

No record bytes change: v3..v6 configs load exactly as before. 325 cases green
across all four native envs, both sanitizer envs clean.
2026-10-03 13:00:26 -05:00
Jason Huebert 9888e59b9d fix(battery): never report a rejected configuration as applied
Without an explicit resume the CLI computed suspend + 200 and printed success
without checking: suspend values 9801..10000 silently set a resume outside the
accepted range while the reply said OK. Derive the default in a wide integer,
refuse it above 10000 rather than clamping, and check setThresholds()'s return
before reporting success — no accepted path may rely on "this cannot fail".

One validThresholds() helper now backs the API, the CLI and the loader, so a
pair the CLI refuses cannot be applied by another route. load() validates a
whole record on locals before assigning anything live: a disabled gate may keep
the shipped 0/0 default or retain real thresholds, and anything else restores
gate-off with no thresholds.

323 native cases green across all four envs, sanitizer envs clean.
2026-10-03 12:36:46 -05:00
Jason Huebert 1966c77b64 fix(filter): bound key decoding, repeat-key semantics and flood-only path=
Five demonstrated defects, each with tests in this change and its FILTER.md
section updated alongside.

- addChannel() decoded a PSK straight into the next live slot and only then
  checked the length, so a 66-character key already wrote a 33rd byte. The hex
  decoder now takes an output capacity and refuses odd or over-long input
  before writing anything, an explicit key must be exactly 32 or 64 hex
  characters, and the entry is built in a local candidate and copied in only
  once it is fully valid. A rejected key leaves the store byte-identical.
- A repeated list predicate accumulated instead of replacing, though every
  scalar key replaced and the guide promised replacement. type, hsize and chan
  now parse into a local and assign; path= clears the whole substructure so a
  shorter chain leaves no stale bytes behind. Alternatives inside one value
  still OR, and type=any is an explicit wildcard that wins beside named types.
- path= matched any nonempty packet path. A recorded path is flood relay
  history; a routed-direct path is an itinerary between two endpoints and a
  TRACE path holds collected SNRs, so neither satisfies path=.
- Group-text parsing scanned the whole decrypted block, which core zero-pads,
  so padding could supply a colon and manufacture an empty sender for ^$; the
  sender buffer was also 64 bytes, silently hiding longer names from patterns.
  Parsing now stops at the first NUL, the sender scratch matches the text
  buffer, and the parser reports which fields actually existed so a message
  with no colon has no sender field to match.
- The probability roll called pkt_hash.get() — a SHA-256 over the packet — even
  for the unset/100 rule that returns true immediately. Gate it at the caller:
  only a rule that can fail the roll pays for the hash. Probability still runs
  before throttle.

Two related channel fixes:

- A name containing ',', '=' or a quote cannot be represented in a rule's
  comma-separated chan= list, so such a channel could never be referenced by
  any rule. One validation helper, shared by the CLI, chan=#x auto-provisioning
  and the direct API, refuses those and control characters; ordinary spaces are
  supported and the value is quoted on output. Names already in the store are
  never re-validated, so an older config stays loadable and visible.
- core offers at most four distinct keys per one-byte on-air hash. Aliases of a
  single key were each consuming a candidate slot and could starve a different
  channel that would have decrypted. searchChannelsByHash() now skips secrets
  already offered, and chan add says when a hash starts carrying keys the
  repeater may never try.

No persistence version change. 236 filter cases green, both sanitizer envs
clean, Xiao_S3_WIO_repeater and RAK_4631_repeater compile with RAM unchanged.
2026-10-03 12:36:46 -05:00
Jason Huebert 286ba37f8a test: give the native feature suites their own selection and sanitizer envs
The generic `pio test -e native` selected test_packet_filter and
test_battery_gate, which need their own include paths, source selection and
filesystem shim; both errored out and failed the whole command. List them in
test_ignore so each runs in the environment that can actually build it.

Also correct the safety net the review found unsound:

- makePacket() left payload, path and transport codes uninitialized while
  mesh::Packet's constructor only sets header/path_len/payload_len, so tests
  hashed whatever the stack held. Initialize them, and clamp payload_len, hsz
  and hops to the real buffer bounds. LenInterval's 200-byte packet became the
  184-byte boundary that actually exists; the hsize=4 case is now labelled
  artificial, since Packet::setPath rejects hash size 4 as reserved.
- filterCLI() was called through a null RegionMap*, and the CLI does call
  members on it. Provide the real constructor in the stub and pass an instance.
- NativeFile::read() formed a data pointer for zero-length and past-EOF reads,
  so reading an empty file passed nullptr to memcpy. Return 0 first. write()
  validates its backing store and tracks position; the two-argument open now
  honours "r"/"w", and flush/rename exist for the persistence work to come.
- The CLI helper now replies into the real 160-byte CLI_REPLY_MAX with a canary
  after it, asserting both no overrun and NUL termination in the window.

Add ASan+UBSan environments for both feature suites so "assertions passed" is
not mistaken for "no undefined behaviour". The three problems the review found
this way — the oversized fixture, the null member call and the empty read —
had all been passing their assertions.

54 native + native_kiss_modem cases green; the sanitizer envs report zero
diagnostics.
2026-10-03 12:35:51 -05:00
Jason Huebert a0ccb35009 fix(filter): drop the text= branch the merged sender/text param left behind
Folding sender= and text= into one branch kept the original text= arm as
unreachable code, and put the IvUnit enum between parseIvNum()'s comment and
parseIvNum(). Both are caught by reading the diff rather than by a test.
2026-10-02 23:24:01 -05:00
Jason Huebert ca07adaa88 refactor: tuck BatteryGate::resetToDefaults into a trailing private section
The private/public sandwich around the one-line declaration was noise;
resetToDefaults() belongs at the bottom with the rest of the class's
internals. Also aligns the save_flag comment with its neighbours.
2026-10-02 23:21:23 -05:00
Jason Huebert 64f133111d docs(filter): drop a leftover rule index from the admin-lockout example
"filter add 0 chan=<admin channel> action=forward" is left over from a CLI that
took an index; `filter add` takes key=value pairs only, so the command as
written answers "Err - expected key=value, got '0'" — advice that cannot work
in the one situation it is meant for.
2026-10-02 23:19:49 -05:00
Jason Huebert 4ef2889de2 docs(filter): state that a prob= roll is scoped to the rule as stored
ruleDigest() does two jobs with the same bytes: the digest `filter list` shows,
and the salt of the prob roll. Its range is the whole persisted record, tail
padding included, so editing a prob= rule — or loading a config under firmware
whose record differs — silently re-rolls which packets that rule decides, and
churns the digest column at the same time.

Nothing changes here: the roll is what it has always been, and changing it
would change which packets existing rules drop. What was missing is that this
is a choice, and it is now written down in both places: the function says the
two jobs are shared on purpose and that a stable rule identity wants a
different function, and FILTER.md tells users the roll is deterministic per
packet per stored rule, not forever.
2026-10-02 23:19:43 -05:00
Jason Huebert d179dcbfa0 refactor(filter): name a channel's index instead of pointer arithmetic
Two small things in the channel store:

- `filter get`-style status recounted the channels with a non-empty name, but
  every slot below num_channels always has one (addChannel only ever writes the
  slot it is about to count, and delChannel zeroes the tail), so the count was
  always num_channels. The dead loop is gone; the rest of the file already
  treated the store as dense, except searchChannelsByHash()'s null-key guard,
  which stays as the corruption check it is.

- `chan - filter.getChannel(0)` appeared twice as a way to ask "which index is
  this channel?". indexOfChannel() now answers that directly and findChannel()
  is a thin wrapper over it, so `filter add chan=` does one lookup instead of
  find-then-subtract.

No reply changes (StatusLineFormat pins the exact line).
2026-10-02 23:19:27 -05:00
Jason Huebert 5a9ae37618 refactor(pattern): report a budget abort through the call, not a global
patternAborted() answered "did the last patternMatches() give up?" from a
file-static flag, which put an invisible ordering requirement between two
files: read it too late and you count some other pattern's abort. The only
caller is FilterRules::regexMatches(), counting budget aborts for `filter
stats`.

patternMatches() now takes an optional `bool* aborted`, written on every call
(false first), and the global is gone. The parameter defaults to NULL, so the
~40 test call sites that only want a yes/no keep reading as before.

The vendored engine keeps its own budget-exhausted flag — that is TinyRegex's
documented API and stays untouched.
2026-10-02 23:18:45 -05:00
Jason Huebert ef75c60a03 refactor(filter): name the two airtime counters at their call sites
The "bill airtime exactly once per packet" rule was spread over five
`air_evaluated_ms += …` / `air_saved_ms += …` statements in two functions,
with the reason each one is conditional living in a comment somewhere else —
including the one case that is easy to get wrong, a content drop that never
reaches the forwarding hook and so is billed by the phase that dropped it.

billEvaluated() and billSaved() are one-liners, but they put the rule in one
comment next to the only two counters it governs, and every call site now says
which of the two it means. No arithmetic changes; the existing airtime tests
(including the counted-once ones) cover the result.
2026-10-02 23:18:10 -05:00
Jason Huebert b3d7ca5e94 refactor(filter): read the clock once per content scan
checkContent() called millis() inside the rule loop, so the throttle gate
stamped throttle_last_ms from a fresh reading per rule, while checkPacket()
takes its clock as a parameter. Both read the same millis(), but one rule's
window could then be stamped from a later millisecond than its neighbour's.

The scan now takes one reading and passes it to every rule, which is what
checkPacket() effectively already did. No behavior change on this platform.
2026-10-02 23:17:49 -05:00
Jason Huebert 41900e2806 perf(filter): hash each packet once per scan, not once per prob rule
Packet::calculatePacketHash() is a SHA-256 over the payload, and probDecides()
called it for every matching rule that carries prob= — up to FILTER_MAX_RULES
hashes per packet, plus one to tag the content-verdict stash and one to verify
it in checkPacket().

PacketHashCache computes it once per entry point and hands out the same
bytes, so the prob rolls, the stash tag and the stash guard all share one
hash, and a list with no prob rules still pays exactly what it did before
(nothing, or one for the guard).

The roll is bit-for-bit what it was: same hash bytes, same salt, same order.
2026-10-02 23:17:36 -05:00
Jason Huebert 0ee69c1cfd refactor(filter): decide content-predicate deferral in one place
"Which predicates can only be judged on decrypted data" lived in two places:
ruleIsDeferred() named the three fields for the packet-level phase, and
checkContent() re-tested the same three fields inline. A new content predicate
added to only one of them would be evaluated in the wrong phase — and since
content predicates never match a packet-level scan, the failure mode is a rule
that silently never fires.

contentPredicates() is now the single answer, as a flag set: the packet phase
asks "is any bit set", the content phase switches on the same value. No
behavior change, and the existing
ContentRulesAreDeferredNotDroppedAtPacketLevel already pins all three
predicates' deferral, so it stands as the regression net.
2026-10-02 23:15:05 -05:00
Jason Huebert 61eb7fd725 fix(battery): bound every CLI reply write and name the usage line
BatteryGate.cpp still used sprintf() into the reply buffer in three places,
which the fork's hard invariant forbids — commit 0a784736 bounded the filter
CLI and left this file behind. All three write constants today, so nothing
overflowed, but the invariant is about the call, not the payload.

While here, the same edits the filter CLI had already made:

- the usage line was spelled out three times; it is one BATT_USAGE constant now
- the "digits but out of range" vs "not a number at all" distinction moves out
  of parseMilliVolts' `bool* numeric` out-parameter into badMilliVolts(), which
  also drops the hand-rolled strtol in favor of the shared parseIntRange()
- every reply write goes through snprintf(reply, CLI_REPLY_MAX, ...)
- setThresholds()'s return was ignored; it is noted as unreachable, since the
  range and the hysteresis were both checked above

CliUtil.h gains cliCopyCommand(), so both handlers copy the command tail into
their scratch buffer the same way (the battery CLI had its own strncpy + NUL).
It is written without StrHelper::strzcpy on purpose: the battery gate's host
test build links neither StrHelper nor ltoa(), and a shared header that drags
in a link dependency for six lines of truncation is worse than the duplication
it removes.

Reply strings are unchanged.
2026-10-02 23:14:40 -05:00
Jason Huebert f925395ed8 refactor(filter): one list tokenizer and one ranged-integer parser for the CLI
`filter add` spelled out the same four things several times over:

- copy a comma list into a scratch buffer for strsep(), refusing a value that
  does not fit — written out for chan=, type=, region= and hsize=
- "parse a whole decimal token in [lo, hi]" — hand-rolled for prob, throttle,
  hsize, the interval endpoints and `ratelimit advert <hours>`, each with a
  slightly different notion of what "a number" means
- the hops/len/snr branches differed only in which Interval they filled and
  which word the error used
- sender and text differed only in destination and length

copyCsvList() and parseIvNum()'s new IvUnit enum (instead of a bool snr_mode
threaded through parse/format) collapse those, and the rules are named by `key`
in the reply. The interval error wording is unchanged, as is every accepted
value — with one deliberate tightening, called out because it changes
behavior:

  filter ratelimit advert abc   used to answer "OK - advert ratelimit 0h"
  filter add hsize=2x           used to answer "OK - rule 0 added" (atoi -> 2)

Both are now errors, matching what every other numeric parameter already did
and what `filter get`'s own round-trip needs. Covered by tests.

Also rewrites parseInterval's high-endpoint length as `hend - (comma + 1)`
instead of `len - 1 - (comma - tok) - 1`.
2026-10-02 23:12:35 -05:00