Repository navigation
fix: message gate stability, security, 429 retry & load performance (v0.13) - #134
Merged
Merged
Conversation
…v0.13) What was wrong: - Delegated subagents under tenantIsolation had no state.sessions mapping, falling back to the shared home read scope; case-insensitive paths on macOS/Windows could bypass tenantRoot checks; evaluateReadScope and evaluateEnvFileWrite failed open while resolvedCwd was pending, and startToolPolicy deferred on unexpected errors. - evaluateEnvFileWrite missed tenant <sessionCwd>/.env; evaluateFetch did not block IPv6-mapped metadata addresses; netPolicy CONNECT proxy could throw on out-of-range ports; injection.ts had polynomial ReDoS shapes and only scanned the head of large inputs; recallContext blocks bypassed guardFetchedText; core/memory.ts did not verify resolvesInside before readFileSync. - Slack, Discord, and Telegram lacked bounded HTTP 429 retry / Retry-After handling and safe text-before-JSON error parsing; attachment downloads could buffer unbounded streams or collide on duplicate/case-variant filenames; Discord/Telegram typing spawned one interval per queued turn instead of refcounting per channel/chat. - handleAction did not verify action target channel binding or allowlist and could spam alreadyHandled notices; queues had no per-conversation/global cap or wait TTL; withdrawWaiting, health.json, and alreadySeen called fsyncSync on hot paths; sessionId->key lookups and listConversations did O(N) scans; long-lived Maps/Sets and plugin unload listeners were unbounded/undisposed. What changed: - core/policy.ts, netPolicy.ts, injection.ts, core/memory.ts: confined subagents via session.header.cwd with case-folded path checks and blocked shared sessions from reading inside tenantRoot; failed closed on pending resolvedCwd, .env writes, and toolPolicy exceptions; blocked IPv6-mapped metadata SSRF; validated proxy ports (1..65535) with safe teardown; removed ReDoS patterns and scanned head+tail; verified resolvesInside before reading. - transports/attachments.ts, transports/slack.ts, transports/discord.ts, transports/telegram.ts, transports/local.ts, transports/composite.ts, transports/history.ts: added readBoundedBytes streaming cap, collision-safe deduplication, and maxFiles/maxTotalInlineChars limits; added bounded HTTP 429 retry + X-RateLimit-Global + non-JSON error handling; refcounted typing indicators with immediate onUnavailable propagation; added Discord 20s handshake timeout; bounded all transport LRU caches; fast-pathed CJK/Hangul. - core/state.ts, recallContext.ts, index.ts, messages.ts: added optional fsync:false atomic writes for health.json and alreadySeen, timestamp-ordered 10k seen cap, orphaned platformOf pruning, O(1) sessionToKey reverse index, handleAction channel binding + stale-notice dedupe, queue backpressure and expiration cleanup, batched withdrawWaiting, cached tail-bounded watch-alerts.jsonl reader, memoized recallContext with live invalidation, recall injection guarding, and full listener/timer disposal on unload. How it was checked: - pnpm run build && pnpm run typecheck: passed. - node test/v13-gate-perf.test.ts: 46/46 checks passed. - pnpm test: all 49 unit suites + secrets scan passed (EXIT=0). - Independent adversarial review completed; all 13 findings fixed and re-verified. Still unverified: - Live-model end-to-end scenarios (test/run-scenario.ts) and live gateway daemon redeploy/health-check were not executed in this environment. Signed-off-by: rlaope <rlaope@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Hardens the message gate, policy boundaries, transport rate-limit resilience, memory/queue bounds, and hot-path performance across Slack, Discord, Telegram, and the local terminal.
Security & Policy Boundaries
core/policy.ts): Derives delegated subagents' tenant scope fromsession.header.cwdwith case-foldedrealpathSync.nativechecks (macOS/Windows), blocks unmapped shared sessions from reading insidetenantRoot, and fails closed whenresolvedCwdis pending..env& tool policy (core/policy.ts,index.ts): Protects<tenantCwd>/.env, fails closed on.envwrites while workspace confinement is initializing, and returns{ kind: 'deny' }ifstartToolPolicythrows unexpectedly.core/policy.ts,netPolicy.ts,injection.ts,core/memory.ts,index.ts): Blocks IPv6-mapped metadata SSRF, validates proxy ports (1..65535) with safe socket teardown, eliminates polynomial ReDoS ininjection.tswhile scanning head+tail on large inputs, guards recalled past passages throughguardFetchedText, and verifiesresolvesInsidebeforereadFileSyncincore/memory.ts.index.ts): Enforces action target channel binding and allowlist verification inhandleAction, and deduplicates stalealreadyHandlednotices per action ID.Transport Resilience & Bounded I/O
transports/slack.ts,transports/discord.ts,transports/telegram.ts): Bounded retry honoringRetry-After/retry_afterand DiscordX-RateLimit-Global, plus text-before-JSON parsing so 502/HTML responses never throwSyntaxError.transports/attachments.ts,transports/slack.ts,transports/telegram.ts):readBoundedBytesaborts oversized streams mid-flight;writeAttachmentsenforcesmaxFiles, post-fetchmaxBytes, collision-safe case-insensitive deduplication, andmaxTotalInlineChars; Telegram rejectsfile_pathtraversal; Slack enforces HTTPS and non-HTML responses.transports/discord.ts,transports/telegram.ts,transports/slack.ts): Refcounts typing indicators per channel/chat with immediateonUnavailablepropagation on failed entries; adds a 20s Discord gateway handshake timeout (cleared onREADY/RESUMED/close); deduplicates concurrent SlackloadNames()and removescfgmutation races.Load, Queue & Memory Performance
core/state.ts,index.ts,recallContext.ts,transports/history.ts): Eliminates per-eventfsyncSyncstalls onhealth.jsonandalreadySeen()(atomic rename{ fsync: false }+ coalesced counter writes), adds O(1)sessionToKeyreverse lookups, batcheswithdrawWaitingstate writes, caches tail-boundedwatch-alerts.jsonlreads, memoizesrecallContextcandidates with live file-change invalidation, and fast-paths CJK/Hangul inquoted().index.ts,core/state.ts,transports/composite.ts,transports/local.ts): ValidatesmaxConcurrency(1..64), enforcesmaxQueuePerConversation/maxTotalQueued/maxQueueWaitMs(with clean progress/TUI cleanup on expiration), bounds long-lived Maps/Sets (state.seentimestamp-evicted at 10k,composite.owners2k,requesterOf5k, transport caches), prunes orphanedstate.platformOf, and disposes all listeners/timers on unload.Verification
pnpm run build && pnpm run typecheck: passed.node test/v13-gate-perf.test.ts: 46/46 checks passed.pnpm test: all 49 local unit test suites + secrets scan (416 files) passed (EXIT=0).Still Unverified
test/run-scenario.ts) and live gateway daemon redeploy/health-check were not executed in this environment.