Skip to content

refactor(channels): unify inbound replay protection - #109117

Merged
steipete merged 6 commits into
mainfrom
claude/chanref-r6-replay-guard
Jul 16, 2026
Merged

steipete merged 6 commits into
mainfrom
claude/chanref-r6-replay-guard

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Resolves a channel reliability risk where concurrent, debounced, or queued inbound work could settle replay state that belonged to a different claim. That could make duplicate suppression and retry behavior diverge between channel plugins.

Why This Change Was Made

Adds one shared plugin SDK replay guard with ownership-bound claim handles, then migrates the bundled channel plugins to carry those handles through deferred processing. Existing per-channel commit-versus-release policy and fail-open handling for unusable replay keys remain intact; no configuration surface changes.

User Impact

Inbound duplicate suppression and retry recovery now follow the same ownership-safe lifecycle across supported channel plugins. Operators need no configuration changes, and plugin developers get a reusable SDK primitive instead of channel-specific orchestration.

Evidence

  • Blacksmith Testbox pnpm test:changed: 15 Vitest shards passed, covering the changed plugin SDK and Discord, Feishu, iMessage, Line, Matrix, Mattermost, Nextcloud Talk, Raft, Telegram, WhatsApp, and Zalo paths.
  • Blacksmith Testbox: core, core-test, extension, and extension-test typechecks passed; full core lint passed; extension and script lint passed; architecture guards passed; pnpm build passed.
  • Focused local proof: plugin SDK replay guard 8/8, Discord queue 12/12, Discord inbound job 5/5, Feishu bot menu 5/5, Telegram dispatch dedupe 9/9.
  • Hard-zero gates: check-deadcode-exports.mjs and check-deadcode-unused-files.mjs both passed with zero entries.
  • Plugin SDK baseline regenerated on the final rebased tree; surface check passed at 7,986 public exports and 4,465 callable exports.
  • Autoreview: clean, with no accepted/actionable findings on the final branch diff.

@steipete steipete self-assigned this Jul 16, 2026
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: discord Channel integration: discord channel: imessage Channel integration: imessage channel: line Channel integration: line channel: matrix Channel integration: matrix channel: mattermost Channel integration: mattermost channel: nextcloud-talk Channel integration: nextcloud-talk channel: telegram Channel integration: telegram channel: whatsapp-web Channel integration: whatsapp-web channel: zalo Channel integration: zalo scripts Repository scripts channel: feishu Channel integration: feishu channel: raft Channel integration: Raft size: XL maintainer Maintainer-authored PR labels Jul 16, 2026
@steipete
steipete force-pushed the claude/chanref-r6-replay-guard branch from bbec824 to dfbc4e6 Compare July 16, 2026 15:35
@steipete
steipete force-pushed the claude/chanref-r6-replay-guard branch from dfbc4e6 to 5f8728a Compare July 16, 2026 15:37
@steipete
steipete merged commit c46cc1e into main Jul 16, 2026
119 checks passed
@steipete
steipete deleted the claude/chanref-r6-replay-guard branch July 16, 2026 15:46
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 17, 2026
* refactor(channels): unify inbound replay-guard orchestration on shared factory

* fix(plugin-sdk): bind replay-guard settlement to claim handles

* fix(plugin-sdk): claim-handle settlement (rest)

* fix(discord): align skipped queue cleanup

* style(feishu): simplify bot menu claim settlement

* refactor(plugin-sdk): extract replay dedupe contracts
zooqueen pushed a commit to zooqueen/openclaw that referenced this pull request Sep 11, 2026
* refactor(channels): unify inbound replay-guard orchestration on shared factory

* fix(plugin-sdk): bind replay-guard settlement to claim handles

* fix(plugin-sdk): claim-handle settlement (rest)

* fix(discord): align skipped queue cleanup

* style(feishu): simplify bot menu claim settlement

* refactor(plugin-sdk): extract replay dedupe contracts
steipete added a commit that referenced this pull request Oct 13, 2026
…el and native code (#170815)

* fix(signal): reserve canonical default transport during legacy cleanup

Keep the canonical root transport in managed-port reservations when a nested
default account still carries retired transport fields. Otherwise Doctor can
allocate the default port to an implicit sibling and produce a collision.

Cover synchronous and asynchronous Doctor migration, nested-field cleanup,
and resolving both accounts to distinct ports. No new configuration surface
or persisted format; existing update/Doctor ownership stays authoritative.

* fix(channels): keep message content out of transport diagnostics

Remove raw content from IRC line/NOTICE, WhatsApp mention/skip, LINE inbound
and postback, Twitch callback, iMessage echo, and Tlon settings diagnostics.
Retain metadata and the complete payload in its delivery/history owner.
LINE peer routing also consumes already prepared source facts instead of
reinspecting the same source through a one-use helper.

Extend existing owning-boundary tests, including real IRC sockets, rather
than adding a separate logging implementation. IRC, WhatsApp, and Tlon
privacy probes failed on the old path and pass with content preserved.

* refactor(channels): simplify old transport helpers and lifecycle state

Consolidate Matrix send preparation, Zalo account/error traversal onto
existing SDK seams, and Google Meet CLI dispatch. Remove pass-through
Promise wrappers, duplicate lifecycle facts, and internal clock defenses.
Keep transport validation, effect authority, FIFO and durable shutdown.

Best-effort tradeoffs accepted:
- Internal cache/follow-up clocks are ordinary Date.now plus constant TTLs;
  synthetic invalid-clock cases are not actual-use incidents. A corrupt clock
  may distort metadata expiry until repair/restart.
- FaceTime does not fence unsupported start-before-stop reentry; its runtime
  creates a new supervisor after joined shutdown. Initial feature #119291
  introduced the generation, without a human reentry incident.
- LINE uses timer cancellation and its stop Promise, not a second stopped
  flag. Synchronous stop reentry is not performed by production callers.
- Mattermost uses one stopped fact, recursive polling and native Promise
  settlement; synchronous callbacks cannot interleave with cancellation.
- Teams uses a fresh UUID without reparsing text to reject a theoretical
  authored-placeholder collision; no human collision report was identified.
- FaceTime expects the documented system_profiler JSON output; malformed
  output reports missing devices instead of parsing old plaintext fixtures.
- Feishu serialization rejects cycles before element counting; exotic
  getter/toJSON objects remain best effort rather than a second graph walk.
- Zalo shares SDK error traversal; provider errors with throwing cause
  getters remain best effort rather than a private short-circuit walker.
- ClickClack uses the timeout race winner directly; exact-deadline late
  microtasks can discard stale ephemeral details, never the durable reply.
- Raft's private FIFO settles replay commits before another claim. If that
  invariant were violated, an unexpected inflight wake is a duplicate hint
  rather than a second settlement path. #109117 gives synthetic/generic
  ownership reasoning, not a human actual-use incident.

Old-code lane o07: production files checked against the last-seven-day
origin/main inventory. No SDK exports, dependencies, schemas or protocols
changed. Standalone session memory remains untouched.

* refactor(mobile): simplify old native lifecycle bookkeeping

Remove duplicate visibility/cache/startup state and unreachable platform/encoder fallbacks in old iOS and Android files. Share outside-tap recognition and let the node invoke boundary own mirrored-notification normalization.

Keep physical-route authorization, permission checks, durable Watch admission and ACKs, FIFO sends, protocol/data shapes, and ordinary concurrency. Net production reduction: 289 LOC, excluding tests, fixtures, and generated files.

Proof: iPhone app/Share/embedded Watch builds, final 273 invoke/Watch ingress/delegate/location tests and 74 sidebar/dashboard tests; Watch scheme build and 11 media tests; Android APK and 89 distinct focused unit cases; 18 shared source-resource tests. Changed-file guards, native lint, runtime/Madge cycles (zero), lint-suppressions (3 tests), and final independent P0-P2 review pass. No hosted CI or hardware/provider-audio/battery proof is claimed.

Best-effort tradeoffs accepted:
- Observer declarations (#113634): synthetic stale-ACK fencing is replaced by FIFO sends and subscription/reconnect replay; failed or obsolete metadata heals on the next declaration.
- Dashboard refresh (#111339): the sole SwiftUI refresh task is sequential and cancellation-owned, so a second generation counter is redundant; a future concurrent direct caller must cancel prior work or accept last-completing cosmetic data until refresh. Roster event/mutation overlap still retains its own generation.
- Delayed cosmetic actions (#113062): the synthetic post-delay interleaving no longer needs generations; replacing an action does not revoke work that already started.
- Delayed gate lifetime (#113062): both real view owners cancel on disappearance, so a second weak-gate lifetime condition is redundant; a future caller omitting cancellation may still perform a harmless cosmetic completion after releasing its gate.
- Watch one-shot transport (#135808): cancelled instances cannot restart, so generations add no supported lifetime; cancellation and physical-resource checks remain.
- Command advertisements (#136192): the synthetic synchronous preference flip may briefly split a command family until reconnect; live invocation admission remains.
- Turn recaps (#112221/#113084): synthetic metadata-only mode and a duplicated pending terminal value are removed; the sole production caller always provides transcript facts, and same-timestamp metadata corrections now use the latest authoritative session row. History/terminal attribution, settlement bounds and all 21 retained tests remain.
- Realtime coordinator (#111033): direct concurrent reset/reuse is unsupported by serialized phone/Wear callers; current-session, duplicate-run, and live-submit guards remain.
- Network availability (#138732): an unexpected duplicate SDK AVAILABLE may wake offline retry early; the human battery fix (#127872), retry ladder, and current-session admission remain.
- iOS resource adapter (#148906): a captured invalidated loader may redundantly reload current metadata; the shared cache owner still cancels stale in-flight results and live authority remains checked.
- Watch startup buffer (5e9bc09): synchronous MainActor registration cannot interleave with queued inbound delivery; a future caller yielding before registration may drop ephemeral requests, never ACK uncommitted chat.
- Mirror validation (#23636): the sole caller supplies normalized bounded fields; future internal callers must preserve that precondition.
- Beacon payload UTF-8 (#73330): Foundation JSONEncoder guarantees the bytes; a framework contract violation is an internal failure, not a recoverable conversion branch.
- Beacon envelope UTF-8 (#73330): the same guarantee removes the second conversion fallback; actual encoding errors still throw.
- Watch request UTF-8 (#135808): default encoder output cannot fail UTF-8 conversion; actual encoding errors still throw.
- Location event UTF-8 (#18260): default encoder output cannot fail UTF-8 conversion; nonfinite-value encoding failures keep their existing handling.
- HealthKit identifiers (#105616): fixed supported identifiers use nonfailable SDK constructors; authorization, privacy scope, and queries remain unchanged.
- Pre-iOS26 button fallback (#168595): the existing native deployment floor is26.2, so supported rendering is unchanged.
- Pre-Android26 priority fallback (#29398): the app minimum is31; notification-channel importance remains the active owner.
- WebView task document fences (#139514): existing MainActor cancellation-at-effect already rejects retired callbacks; navigation and document authority remain.

(cherry picked from commit 3dd5a00)

* refactor(ios): keep delayed cosmetic actions synchronous

Both production callers update toast or flash state synchronously on MainActor. Remove the unused async action contract and invoke it directly after the existing sleep/cancellation boundary. Keep asynchronous sleeping, cancellation, replacement and the returned task unchanged.

Best-effort tradeoffs accepted:
- None added by this type narrowing. The helper is internal, both callers and all retained tests already supply synchronous actions. The hypothetical suspending action discussed with #113062 is not a supported caller and is no longer expressible through this API.

Earlier guard-removal provenance and campaign proof are recorded in the preceding mobile cleanup commit. This follow-up changes no production LOC total, public protocol, permission, signing, dependency, persistence or visible rendering.

Validation: iPhone app/Share/embedded Watch build and61 focused tests in2 suites pass (DelayedActionGateTests and RootTabsPresentationTests),196.654s xcodebuild/0.628s tests. Configured SwiftFormat and strict SwiftLint pass; independent P0-P2 review is scoped-clean. Earlier unchanged-input changed-file, cycle and lint-suppression gates remain valid.
(cherry picked from commit c7c9fb6)

* fix(mattermost): keep inbound message content out of diagnostics

Log conversation, post ID and length instead of a body preview. Keep the
complete agent body and attachment order unchanged, and update the existing
monitor boundary test to reject content in diagnostics.

The regression fails before the repair on the leaked synthetic body prefix
after complete-body/ordered-media assertions pass, then passes after repair.
Final owner24, sibling25 and lint-suppressions3 tests pass; runtime and Madge
cycles are zero. Fresh production/test types, syntax lint, format and line-cap
checks pass, with no baseline, suppression or timeout increase.

This minimal privacy fix is explicitly authorized outside the old-code
eligibility restriction. The combined channel/native patch received a fresh
independent review with no actionable P0-P2 findings.

* fix(ios): remove retired Watch error from i18n inventory

* fix(mattermost): normalize nullable shutdown cleanup before await
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
…el and native code (openclaw#170815)

* fix(signal): reserve canonical default transport during legacy cleanup

Keep the canonical root transport in managed-port reservations when a nested
default account still carries retired transport fields. Otherwise Doctor can
allocate the default port to an implicit sibling and produce a collision.

Cover synchronous and asynchronous Doctor migration, nested-field cleanup,
and resolving both accounts to distinct ports. No new configuration surface
or persisted format; existing update/Doctor ownership stays authoritative.

* fix(channels): keep message content out of transport diagnostics

Remove raw content from IRC line/NOTICE, WhatsApp mention/skip, LINE inbound
and postback, Twitch callback, iMessage echo, and Tlon settings diagnostics.
Retain metadata and the complete payload in its delivery/history owner.
LINE peer routing also consumes already prepared source facts instead of
reinspecting the same source through a one-use helper.

Extend existing owning-boundary tests, including real IRC sockets, rather
than adding a separate logging implementation. IRC, WhatsApp, and Tlon
privacy probes failed on the old path and pass with content preserved.

* refactor(channels): simplify old transport helpers and lifecycle state

Consolidate Matrix send preparation, Zalo account/error traversal onto
existing SDK seams, and Google Meet CLI dispatch. Remove pass-through
Promise wrappers, duplicate lifecycle facts, and internal clock defenses.
Keep transport validation, effect authority, FIFO and durable shutdown.

Best-effort tradeoffs accepted:
- Internal cache/follow-up clocks are ordinary Date.now plus constant TTLs;
  synthetic invalid-clock cases are not actual-use incidents. A corrupt clock
  may distort metadata expiry until repair/restart.
- FaceTime does not fence unsupported start-before-stop reentry; its runtime
  creates a new supervisor after joined shutdown. Initial feature openclaw#119291
  introduced the generation, without a human reentry incident.
- LINE uses timer cancellation and its stop Promise, not a second stopped
  flag. Synchronous stop reentry is not performed by production callers.
- Mattermost uses one stopped fact, recursive polling and native Promise
  settlement; synchronous callbacks cannot interleave with cancellation.
- Teams uses a fresh UUID without reparsing text to reject a theoretical
  authored-placeholder collision; no human collision report was identified.
- FaceTime expects the documented system_profiler JSON output; malformed
  output reports missing devices instead of parsing old plaintext fixtures.
- Feishu serialization rejects cycles before element counting; exotic
  getter/toJSON objects remain best effort rather than a second graph walk.
- Zalo shares SDK error traversal; provider errors with throwing cause
  getters remain best effort rather than a private short-circuit walker.
- ClickClack uses the timeout race winner directly; exact-deadline late
  microtasks can discard stale ephemeral details, never the durable reply.
- Raft's private FIFO settles replay commits before another claim. If that
  invariant were violated, an unexpected inflight wake is a duplicate hint
  rather than a second settlement path. openclaw#109117 gives synthetic/generic
  ownership reasoning, not a human actual-use incident.

Old-code lane o07: production files checked against the last-seven-day
origin/main inventory. No SDK exports, dependencies, schemas or protocols
changed. Standalone session memory remains untouched.

* refactor(mobile): simplify old native lifecycle bookkeeping

Remove duplicate visibility/cache/startup state and unreachable platform/encoder fallbacks in old iOS and Android files. Share outside-tap recognition and let the node invoke boundary own mirrored-notification normalization.

Keep physical-route authorization, permission checks, durable Watch admission and ACKs, FIFO sends, protocol/data shapes, and ordinary concurrency. Net production reduction: 289 LOC, excluding tests, fixtures, and generated files.

Proof: iPhone app/Share/embedded Watch builds, final 273 invoke/Watch ingress/delegate/location tests and 74 sidebar/dashboard tests; Watch scheme build and 11 media tests; Android APK and 89 distinct focused unit cases; 18 shared source-resource tests. Changed-file guards, native lint, runtime/Madge cycles (zero), lint-suppressions (3 tests), and final independent P0-P2 review pass. No hosted CI or hardware/provider-audio/battery proof is claimed.

Best-effort tradeoffs accepted:
- Observer declarations (openclaw#113634): synthetic stale-ACK fencing is replaced by FIFO sends and subscription/reconnect replay; failed or obsolete metadata heals on the next declaration.
- Dashboard refresh (openclaw#111339): the sole SwiftUI refresh task is sequential and cancellation-owned, so a second generation counter is redundant; a future concurrent direct caller must cancel prior work or accept last-completing cosmetic data until refresh. Roster event/mutation overlap still retains its own generation.
- Delayed cosmetic actions (openclaw#113062): the synthetic post-delay interleaving no longer needs generations; replacing an action does not revoke work that already started.
- Delayed gate lifetime (openclaw#113062): both real view owners cancel on disappearance, so a second weak-gate lifetime condition is redundant; a future caller omitting cancellation may still perform a harmless cosmetic completion after releasing its gate.
- Watch one-shot transport (openclaw#135808): cancelled instances cannot restart, so generations add no supported lifetime; cancellation and physical-resource checks remain.
- Command advertisements (openclaw#136192): the synthetic synchronous preference flip may briefly split a command family until reconnect; live invocation admission remains.
- Turn recaps (openclaw#112221/openclaw#113084): synthetic metadata-only mode and a duplicated pending terminal value are removed; the sole production caller always provides transcript facts, and same-timestamp metadata corrections now use the latest authoritative session row. History/terminal attribution, settlement bounds and all 21 retained tests remain.
- Realtime coordinator (openclaw#111033): direct concurrent reset/reuse is unsupported by serialized phone/Wear callers; current-session, duplicate-run, and live-submit guards remain.
- Network availability (openclaw#138732): an unexpected duplicate SDK AVAILABLE may wake offline retry early; the human battery fix (openclaw#127872), retry ladder, and current-session admission remain.
- iOS resource adapter (openclaw#148906): a captured invalidated loader may redundantly reload current metadata; the shared cache owner still cancels stale in-flight results and live authority remains checked.
- Watch startup buffer (5a652b8): synchronous MainActor registration cannot interleave with queued inbound delivery; a future caller yielding before registration may drop ephemeral requests, never ACK uncommitted chat.
- Mirror validation (openclaw#23636): the sole caller supplies normalized bounded fields; future internal callers must preserve that precondition.
- Beacon payload UTF-8 (openclaw#73330): Foundation JSONEncoder guarantees the bytes; a framework contract violation is an internal failure, not a recoverable conversion branch.
- Beacon envelope UTF-8 (openclaw#73330): the same guarantee removes the second conversion fallback; actual encoding errors still throw.
- Watch request UTF-8 (openclaw#135808): default encoder output cannot fail UTF-8 conversion; actual encoding errors still throw.
- Location event UTF-8 (openclaw#18260): default encoder output cannot fail UTF-8 conversion; nonfinite-value encoding failures keep their existing handling.
- HealthKit identifiers (openclaw#105616): fixed supported identifiers use nonfailable SDK constructors; authorization, privacy scope, and queries remain unchanged.
- Pre-iOS26 button fallback (openclaw#168595): the existing native deployment floor is26.2, so supported rendering is unchanged.
- Pre-Android26 priority fallback (openclaw#29398): the app minimum is31; notification-channel importance remains the active owner.
- WebView task document fences (openclaw#139514): existing MainActor cancellation-at-effect already rejects retired callbacks; navigation and document authority remain.

(cherry picked from commit 3dd5a00)

* refactor(ios): keep delayed cosmetic actions synchronous

Both production callers update toast or flash state synchronously on MainActor. Remove the unused async action contract and invoke it directly after the existing sleep/cancellation boundary. Keep asynchronous sleeping, cancellation, replacement and the returned task unchanged.

Best-effort tradeoffs accepted:
- None added by this type narrowing. The helper is internal, both callers and all retained tests already supply synchronous actions. The hypothetical suspending action discussed with openclaw#113062 is not a supported caller and is no longer expressible through this API.

Earlier guard-removal provenance and campaign proof are recorded in the preceding mobile cleanup commit. This follow-up changes no production LOC total, public protocol, permission, signing, dependency, persistence or visible rendering.

Validation: iPhone app/Share/embedded Watch build and61 focused tests in2 suites pass (DelayedActionGateTests and RootTabsPresentationTests),196.654s xcodebuild/0.628s tests. Configured SwiftFormat and strict SwiftLint pass; independent P0-P2 review is scoped-clean. Earlier unchanged-input changed-file, cycle and lint-suppression gates remain valid.
(cherry picked from commit c7c9fb6)

* fix(mattermost): keep inbound message content out of diagnostics

Log conversation, post ID and length instead of a body preview. Keep the
complete agent body and attachment order unchanged, and update the existing
monitor boundary test to reject content in diagnostics.

The regression fails before the repair on the leaked synthetic body prefix
after complete-body/ordered-media assertions pass, then passes after repair.
Final owner24, sibling25 and lint-suppressions3 tests pass; runtime and Madge
cycles are zero. Fresh production/test types, syntax lint, format and line-cap
checks pass, with no baseline, suppression or timeout increase.

This minimal privacy fix is explicitly authorized outside the old-code
eligibility restriction. The combined channel/native patch received a fresh
independent review with no actionable P0-P2 findings.

* fix(ios): remove retired Watch error from i18n inventory

* fix(mattermost): normalize nullable shutdown cleanup before await
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: discord Channel integration: discord channel: feishu Channel integration: feishu channel: imessage Channel integration: imessage channel: line Channel integration: line channel: matrix Channel integration: matrix channel: mattermost Channel integration: mattermost channel: nextcloud-talk Channel integration: nextcloud-talk channel: raft Channel integration: Raft channel: telegram Channel integration: telegram channel: whatsapp-web Channel integration: whatsapp-web channel: zalo Channel integration: zalo docs Improvements or additions to documentation maintainer Maintainer-authored PR scripts Repository scripts size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant