Skip to content

feat(sessions): add createdAt tracking and date-range filtering - #1

Merged
supmo668 merged 20 commits into
mainfrom
feature/session-timestamp-filtering
Feb 14, 2026
Merged

supmo668 merged 20 commits into
mainfrom
feature/session-timestamp-filtering

Conversation

@supmo668

@supmo668 supmo668 commented Feb 11, 2026 •

Copy link
Copy Markdown

Summary

Commit 1: Core session timestamp support

  • Add createdAt timestamp field to SessionEntry with merge-safe preservation
  • Expose four new session-list filters: updatedAfter, updatedBefore, createdAfter, createdBefore
  • Surface createdAt in GatewaySessionRow output
  • Add .claude/ to .gitignore

Commit 2: persist-postgres extension plugin

  • PostgreSQL persistence for conversations and messages via agent lifecycle hooks
  • Plugin boundary: owns lp_conversations and lp_messages only — no user table
  • Schema auto-created on first use with indexes (session_key, last_message_at, conversation_id + created_at)
  • Hooks: before_agent_start (persist user prompt), agent_end (persist assistant response), plus channel hooks (message_received, message_sent)
  • Validated end-to-end: gateway → hooks/chat → both messages persisted to PostgreSQL

Test plan

  • 37 unit tests pass (10 new date-range filter tests)
  • 16 PostgreSQL integration tests pass against clean database
  • E2E: gateway startup → chat via /hooks/chat → user + assistant messages verified in lp_conversations + lp_messages

@supmo668
supmo668 force-pushed the feature/session-timestamp-filtering branch 4 times, most recently from 7a0ffc3 to 45d9e2a Compare February 13, 2026 00:49
@supmo668

Copy link
Copy Markdown
Author

Comprehensive PR Review - 7-Agent Analysis

Review Agents: code-reviewer, pr-test-analyzer, silent-failure-hunter, type-design-analyzer, comment-analyzer, code-simplifier, docs-impact-agent


Critical Issues (Must Fix)

1. SQL Parameter Numbering Bug in queryConversations

File: extensions/persist-postgres/src/db.ts:139
Severity: Critical (95/100)

The first condition hardcodes $1 instead of using $${values.length + 1}. When createdAfter is undefined but other filters are present, placeholder numbering becomes misaligned.

// BUG: hardcoded $1 instead of dynamic
if (opts.createdAfter !== undefined) {
  query += ` AND started_at >= $1::timestamptz`;

Fix: Use $${values.length + 1} consistently for all conditions, or better yet, refactor to use postgres tagged templates with sql.join() instead of sql.unsafe().

2. Race Condition in ensureReady() Schema Initialization

File: extensions/persist-postgres/src/index.ts:20-26
Severity: Critical (92/100)

Multiple concurrent hooks can see schemaReady === false simultaneously, causing redundant schema creation calls.

Fix: Replace boolean flag with promise-based initialization:

let schemaReadyPromise: Promise<void> | null = null;
async function ensureReady() {
  if (!schemaReadyPromise) {
    schemaReadyPromise = ensureSchema(sql).then(() => {
      api.logger.info("persist-postgres: schema ready");
    });
  }
  await schemaReadyPromise;
}

3. Silent Error Swallowing in All 4 Hook Handlers

File: extensions/persist-postgres/src/index.ts:28-135
Severity: Critical

All hooks wrap operations in try/catch that only log errors. Users have zero indication when persistence fails — data loss is silent and undetectable.

Fix: At minimum, surface persistence failures via prependContext in before_agent_start, and track failure state for visibility on subsequent interactions.

4. No Connection Validation on Plugin Startup

File: extensions/persist-postgres/src/index.ts:17
Severity: Critical (88/100)

createPgClient() creates a lazy connection pool — no actual connection until first query. Plugin appears healthy even with invalid DATABASE_URL.

Fix: Add a startup health check: await sql\SELECT 1`` with error handling that disables the plugin cleanly.


Important Issues

5. mergeSessionEntry Missing createdAt Fallback

File: src/config/sessions/types.ts:111
Severity: Important (85/100)

When merging existing entries where both existing.createdAt and patch.createdAt are undefined, the result is undefined — unlike new entries which default to Date.now().

Fix: const createdAt = existing.createdAt ?? patch.createdAt ?? Date.now();

6. Plugin Config Schema Mismatch

File: extensions/persist-postgres/openclaw.plugin.json vs src/index.ts
Severity: Important (82/100)

Plugin declares configSchema requiring databaseUrl, but the code reads from process.env.DATABASE_URL directly. The schema declaration is misleading.


Test Coverage Gaps (4 Critical)

  1. No mergeSessionEntry createdAt tests — The core timestamp preservation logic has zero test coverage
  2. No plugin error handling tests — Silent failures, schema creation failures, invalid events untested
  3. No SQL parameter edge case tests — All 4 filters + limit combined never tested (would expose Issue feat(sessions): add createdAt tracking and date-range filtering #1)
  4. No invalid filter input tests — NaN, Infinity, negative timestamps not verified

Type Design Assessment (7/10 Overall)

  • Good: SessionEntry.createdAt is well-designed with backward compatibility
  • Good: pgRowToSessionEntry mapping is clean
  • Needs Work: No temporal invariant validation (createdAt <= updatedAt)
  • Needs Work: GatewaySessionRow.createdAt uses redundant ?: + | null (3 states)
  • Needs Work: PgMessageRow.role typed as string instead of union type

Code Simplification Opportunities

  1. High Impact: Extract shared persistMessage() helper from 4 repetitive hook handlers (~60 lines saved)
  2. Medium Impact: Refactor queryConversations to use sql.join() tagged templates instead of manual string concatenation
  3. Low Impact: Extract normalizeTimestamp() helper for repeated filter validation

Comment Quality (Needs Attention)

  • Test file header: incomplete run instructions (missing default DB info)
  • Hook comments: don't describe conditional behavior or return values
  • queryConversations JSDoc: missing @param documentation

Documentation Impact

Doc File Change Needed Priority
docs/cli/sessions.md Add 4 new filter flags documentation HIGH
docs/concepts/session.md Document createdAt field + timestamp filters in sessions.list API HIGH
No README update needed for fork-specific extension -

Verdict: NEEDS FIXES before merge

Priority order:

  1. Fix SQL parameter numbering bug (Issue feat(sessions): add createdAt tracking and date-range filtering #1) — correctness
  2. Fix race condition in ensureReady (Issue fix(persist-postgres): address Greptile review feedback and CI failures #2) — reliability
  3. Add connection validation on startup (Issue feat(memory): add memory-graphiti extension with dual-backend support #4) — debuggability
  4. Address silent error swallowing (Issue feat: add memory-milvus plugin for Milvus/Zilliz Cloud vector memory #3) — observability
  5. Fix mergeSessionEntry fallback (Issue feat(memory): add memory-graphiti extension with dual-backend support #5) — correctness
  6. Add missing test coverage — confidence

Positive notes:

  • Comprehensive date-range filtering with good test coverage for happy paths
  • Clean plugin architecture following OpenClaw conventions
  • Proper use of parameterized queries (except Issue feat(sessions): add createdAt tracking and date-range filtering #1)
  • Good separation between core session logic and plugin persistence
  • E2E verified: gateway → hooks/chat → messages persisted

@supmo668
supmo668 force-pushed the feature/session-timestamp-filtering branch 2 times, most recently from a7dbe6b to 3ef2f48 Compare February 13, 2026 12:42
sebslight and others added 19 commits February 13, 2026 08:15
…to-approval (OC-02)

Two critical RCE vectors patched:

Vector 1 - Gateway HTTP /tools/invoke:
- Add DEFAULT_GATEWAY_HTTP_TOOL_DENY blocking sessions_spawn,
  sessions_send, gateway, whatsapp_login from HTTP invocation
- Apply deny filter after existing policy cascade, before tool lookup
- Add gateway.tools.{allow,deny} config override in GatewayConfig

Vector 2 - ACP client auto-approval:
- Replace blind allow_once selection with danger-aware permission handler
- Dangerous tools (exec, sessions_spawn, etc.) require interactive confirmation
- Safe tools retain auto-approve behavior (backward compatible)
- Empty options array now denied (was hardcoded "allow")
- 30s timeout auto-denies to prevent hung sessions

CWE-78 | CVSS:3.1 9.8 Critical
…openclaw#11020) thanks @lailoo

Verified:
- pnpm install --frozen-lockfile
- pnpm build
- pnpm check
- pnpm test

Co-authored-by: ${pr_author_login} <${coauthor_email}>
Co-authored-by: ${tak_name} <${tak_email}>
- Add mention parsing and validation logic
- Handle mention entities with proper whitespace
- Validate mention IDs to prevent false positives from code snippets
- Use fake placeholders in tests for privacy
Clarify that User.Read.All permission is only needed for searching
users not in the current conversation. Mentions work out of the box
for conversation participants.
Escape regex metacharacters in display names before constructing RegExp
to prevent runtime errors or unintended matches when names contain special
characters like (, ), ., +, ?, [, etc.

Add test coverage for names with regex metacharacters.
…mpatibility

Older OpenClaw versions stored absolute sessionFile paths in sessions.json.
v2026.2.12 added path traversal security that rejected these absolute paths,
breaking all Telegram group handlers with 'Session file path must be within
sessions directory' errors.

Changes:
- resolvePathWithinSessionsDir() now normalizes absolute paths that resolve
  within the sessions directory, converting them to relative before validation
- Added 3 tests for absolute path handling (within dir, with topic, outside dir)

Fixes openclaw#15283
Closes openclaw#15214, openclaw#15237, openclaw#15216, openclaw#15152, openclaw#15213
…law#15035)

* feat(gateway): add auth rate-limiting & brute-force protection

Add a per-IP sliding-window rate limiter to Gateway authentication
endpoints (HTTP, WebSocket upgrade, and WS message-level auth).

When gateway.auth.rateLimit is configured, failed auth attempts are
tracked per client IP. Once the threshold is exceeded within the
sliding window, further attempts are blocked with HTTP 429 + Retry-After
until the lockout period expires. Loopback addresses are exempt by
default so local CLI sessions are never locked out.

The limiter is only created when explicitly configured (undefined
otherwise), keeping the feature fully opt-in and backward-compatible.

* fix(gateway): isolate auth rate-limit scopes and normalize 429 responses

---------

Co-authored-by: buerbaumer <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
Add `createdAt` timestamp to SessionEntry, preserve it across merges,
and expose four new list-sessions filters (updatedAfter, updatedBefore,
createdAfter, createdBefore) for querying sessions by absolute time
range. This is foundational for external persistence backends (e.g.
PostgreSQL) that need incremental sync by timestamp.

Includes 10 new tests covering all filter combinations and edge cases.
…d messages

Add persist-postgres extension plugin that persists conversations and
messages to PostgreSQL via agent lifecycle hooks (before_agent_start,
agent_end) and channel hooks (message_received, message_sent).

Plugin boundary: owns lp_conversations and lp_messages tables only.
No user table — user identity is outside this plugin's scope.
Schema auto-created on first use with proper indexes.

Files:
- db.ts: connection pooling, schema DDL, upsert/insert/query, row mapping
- index.ts: plugin registration with lifecycle and channel hooks
- integration.test.ts: 16 tests (CRUD, date-range SQL filtering,
  listSessionsFromStore round-trip with PG-sourced data)
@supmo668
supmo668 force-pushed the feature/session-timestamp-filtering branch from 9558d21 to 3ffecf3 Compare February 14, 2026 08:38
- Read databaseUrl from api.pluginConfig with env var fallback
- Remove duplicate message_received/message_sent hooks (before_agent_start
  and agent_end already cover user/assistant messages)
- Fix message_count inflation: increment only on insertMessage, not upsert
- Add PG 13+ requirement note for gen_random_uuid()
- Rename integration test to .e2e.test.ts (excluded from default pnpm test)

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@supmo668
supmo668 merged this pull request into main Feb 14, 2026
8 of 13 checks passed
supmo668 added a commit that referenced this pull request Jun 21, 2026
… — oc-hygiene #1, CTO-landed, QGR 47c8e3e

perf(syntropy): single-flight + negative-cache for get_health_profile (oc-hygiene #1)
supmo668 added a commit that referenced this pull request Jul 15, 2026
…ession (CRITICAL), webhook DoS cap, inbound-policy enforcement + coverage

Addresses all confirmed 4-reviewer QG findings.
CRITICAL (code+test+security): STOP/HELP compliance acks were suppressed by guardedSendSms (which re-checks isOptedOut after optOut persists) → the CTIA/TCPA-mandated confirmation never sent. Fix: extract testable inbound.ts (handleInboundSms) from index.ts's inline closures; compliance acks now go via UNGUARDED sendSms (mandated replies exempt from the opt-out gate); agent-generated replies stay opt-out-guarded (createSmsReplyDeliver).
MEDIUM (security): readBody had no size cap on the unauthenticated webhook (CWE-770 OOM DoS) → MAX_INBOUND_BODY_BYTES=64KB, 413 on Content-Length over cap AND on streamed overflow.
MEDIUM (design): inbound policy (disabled/allowlist/pairing) was declared but never enforced → inboundAllowed() gates passthrough (STOP always honored first regardless).
LOW: send.ts success-path JSON.parse guarded (never-throws contract); outbound.ts uses SMS_CHANNEL_ID not literal.
Coverage (test): +18 tests → inbound.test.ts (STOP-ack-sends-despite-optout ★, HELP-to-opted-out, compliance-first ordering, policy enforcement, pin-#1 at the agent-reply deliver), webhook-handler.test.ts (503 inert / 200→onInbound / forged→no-onInbound / 413), send missing-sid + non-JSON, classify blank-body, strengthened outbound secret-leak assertion. Full twilio suite 80/80; tsgo+lint+fmt clean.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>
supmo668 added a commit that referenced this pull request Jul 15, 2026
…ig, signed webhook, TCPA STOP/HELP rail) (#68)

* mangyinm/cto: feat(twilio): B-Twilio-1 slice 1 — SMS config contract (scoped API keys / per-env subaccount, fail-closed)

First slice of B-Twilio-1 (Twilio SMS ChannelTransport adapter, greenfield). The auth + number config contract per AD-onboarding-channels §4.2/4.3.

- Scoped Standard API Keys (SID+Secret) on per-env SUBACCOUNTS, NEVER the master Auth Token (test/prod isolation by construction); subaccount Auth Token retained ONLY as the X-Twilio-Signature HMAC key (§4.3).
- E.164 sender + allowFrom validation; inbound policy defaults to 'pairing' (deny-by-default, mirrors SYNTROPY_GATE).
- resolveTwilioSmsConfig: FAIL-CLOSED on credential completeness — returns null (channel INERT, registers nothing) unless EVERY credential + the sender number is present; no partial Twilio wiring. authToken REQUIRED (an SMS channel with no way to validate inbound signatures must not run).
- Infisical channels/twilio/{env} → runtime env fallback; config wins per-field.

Red-first: 11 tests (E.164 valid/invalid, strict-schema typo-safety, inbound default, credential-completeness incl. each-single-missing → null, authToken-required, env fallback, config precedence). tsgo clean, oxfmt clean. Standalone module — no plugin wiring yet (slice 5). Slices 2-6 (send / webhook+sig / TCPA STOP-HELP hard rail / plugin wiring / rails tests) per B-TWILIO-1-PLAN.md.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: feat(twilio): B-Twilio-1 slice 2 — outbound SMS send (scoped API-key auth, injectable fetch, fail-closed secret hygiene)

send.ts: sendSms() → Twilio REST POST /2010-04-01/Accounts/{accountSid}/Messages.json. Basic-auth apiKeySid:apiKeySecret (scoped API key §4.2), NOT the authToken (webhook-HMAC only). Form-encoded From/To/Body. Injectable fetch seam (default global fetch). Discriminated {ok:true,sid}|{ok:false,status,error} — never throws, never leaks the api-key secret in error/return. No media v1. Does NOT import voice-call's twilioApiRequest (keeps the vendor-agnostic single-extension rail; that helper is account-auth + non-injectable). 6 red-first tests: URL/path, scoped-key auth (asserts NOT account:authToken), form fields, success sid, HTTP-error no-leak, network-throw no-leak. Full twilio suite 17/17; tsgo+lint+fmt clean.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: feat(twilio): B-Twilio-1 slice 3 — inbound SMS webhook + X-Twilio-Signature gate (validate BEFORE routing)

webhook.ts: decideInboundSms() pure security gate — non-POST 405; X-Twilio-Signature validated (HMAC-SHA1, subaccount authToken §4.3) BEFORE any parse/route, mismatch/absent => 403 and inbound NEVER surfaced; authenticated-but-no-From => 400; authenticated+routable => 200 with {from,body}. Validator REUSED from voice-call (validateTwilioSignature, pure timing-safe) — single source of truth for the crypto (precedent: syntropy-mcp reuses syntropy/src). createSmsWebhookHandler: thin IncomingMessage/ServerResponse adapter (body read, header/url extraction, empty-TwiML 200); resolveUrl seam for proxy URL reconstruction. 9 red-first tests incl. genuine-HMAC accept + tamper-detection (good sig + altered body => 403) proving reject-on-mismatch end-to-end. Full twilio suite 26/26; tsgo+lint+fmt clean.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: feat(twilio): B-Twilio-1 slice 4 — TCPA STOP/HELP hard rail (QG-blocking behavioral pin, CTO openclaw#3559)

compliance.ts: the non-negotiable opt-out rail. classifyCompliance() EXACT-match (trim/upper/strip-punct) STOP/STOPALL/UNSUBSCRIBE/CANCEL/END/QUIT->stop, START/YES/UNSTOP->start, HELP/INFO->help — conversational text containing a keyword as substring does NOT opt-out (no false positives). handleInboundCompliance(): STOP persists durable opt-out + confirmation, START clears, HELP replies (no state change), else passthrough to agent; replies are generic (no PHI/clerk-id/pairing). guardedSendSms(): enforcement half — checks opt-out FAIL-CLOSED (store throws => suppress, never send) before delegating to sendSms. ★ BEHAVIORAL PIN GREEN: a STOP'd number receives ZERO subsequent sends (fetch never called) + fail-closed. OptOutStore is an injectable seam; durable DB impl wired at slice 5. 12 red-first tests. Full twilio suite 38/38; tsgo+lint+fmt clean.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: feat(twilio): B-Twilio-1 slice 5b — SMS outbound adapter (send→OutboundDeliveryResult, opt-out=terminal sentinel)

outbound.ts buildSmsOutboundAdapter(): maps guardedSendSms → ChannelOutboundAdapter.sendText per the delivery-queue semantics (returned result=ack/terminal, throw=fail/retry). Opt-out suppression returns a TERMINAL sentinel {messageId:'suppressed:optout',meta.suppressed} so a STOP'd recipient never re-enters the retry queue; genuine send failure THROWS (retryable); resolveConfig→null throws not-configured. deliveryMode 'direct'. Config/store/fetch injected — pure testable mapping. Secret never in thrown error. 6 red-first tests. Full twilio suite 44/44; tsgo+lint+fmt clean. Remaining slice-5 parts: 5a config-adapter bridge, 5c durable pg OptOutStore, 5d plugin object + register()/registerHttpRoute wiring, 5e manifest.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: feat(twilio): B-Twilio-1 slice 5c — durable pg OptOutStore (ADR 0001: OpenClaw's own DB, user-independent key)

optout-store.ts: ensureOptOutSchema (idempotent CREATE TABLE IF NOT EXISTS lp_sms_optouts) + createPgOptOutStore backing the slice-4 OptOutStore seam. Per ADR 0001: lives in OpenClaw's OWN persist-user-identity Postgres, NEVER the Journal PHI DB; keyed by bare E.164 (user-independent) so a pre-pairing STOP is honored. Injected-sql convention (mirrors persist-user-identity/db.ts) via a minimal structural SqlTag type — zero new deps, decoupled from the postgres driver (real postgres.Sql satisfies it structurally at the wiring site). 4 tests via fake-sql round-trip (optOut->isOptedOut true, optIn clears, unknown=false, DDL issued). Full twilio suite 48/48; tsgo+lint+fmt clean. Remaining: 5d plugin object + register() (create pg client from DATABASE_URL, ensureSchema, wire channel + /twilio/sms route + compliance-before-gateway), 5e manifest.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: feat(twilio): B-Twilio-1 slice 5a — SMS config-adapter bridge (OpenClawConfig.channels.sms → resolveTwilioSmsConfig)

accounts.ts: resolveSmsAccount reads cfg.channels.sms (ChannelsConfig index signature — no core config-type change) → TwilioSmsConfigSchema.safeParse → resolveTwilioSmsConfig (+ TWILIO_* env fallback). Inert until credential-complete (configured=false, config=null); malformed config object is ignored (falls back to env) rather than throwing. v1 single-account (listSmsAccountIds → [DEFAULT_ACCOUNT_ID]). Exports smsConfigAdapter (ChannelConfigAdapter) for the plugin object (5d). 7 red-first tests (full/inert/env-fallback/partial-fail-closed/bad-schema/default-account). Full twilio suite 55/55; tsgo+lint+fmt clean.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: feat(twilio): B-Twilio-1 slice 5d — SMS plugin assembled + registered (channel + inbound webhook → compliance → agent)

Wires the tested blocks into a live channel. package.json (@openclaw/twilio, postgres dep, openclaw.extensions entry — the extension now LOADS). db.ts: own pg pool to DATABASE_URL (ADR 0001, OpenClaw's DB). channel.ts: createSmsPlugin factory (id 'sms', direct-only, no media, config adapter + opt-out-guarded outbound; 5 tests). index.ts register(): build durable pg opt-out store (fail-closed if no DATABASE_URL), api.registerChannel, api.registerHttpRoute('/twilio/sms') → createSmsWebhookHandler; onInbound runs handleInboundCompliance FIRST (STOP/START/HELP reply via guardedSendSms, no agent) else routeInboundToAgent (buildAgentPeerSessionKey agent:main:sms:direct:<e164> + minimal MsgContext → dispatchInboundMessageWithDispatcher, agent reply delivered via opt-out-guarded send); gateway_stop closes the pool. webhook.ts: handler now resolves config lazily (503 when inert) — honors unprovisioned/changed config. Deep core imports (dispatch/session-key/MsgContext) per established twitch/syntropy-mcp precedent. Full twilio suite 60/60; tsgo+lint+fmt clean. Remaining: 5e manifest (uiHints) + slice 6 integration/rails tests.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: feat(twilio): B-Twilio-1 slices 5e+6 — manifest uiHints + rails/integration tests (PHI-deny, register wiring)

5e: openclaw.plugin.json uiHints — apiKeySecret+authToken marked sensitive (masked in config UI), field labels/help/placeholders. 6: rails.test.ts — (a) PHI boundary: isThirdPartyChannel('sms')===true (sms can never be phiApproved via plain config; B5 deny-unknown), (b) register() wiring integration: fake api confirms registerChannel(id 'sms') + registerHttpRoute('/twilio/sms') + gateway_stop cleanup, forcing the no-DB branch for determinism. Signature-negative + opt-out-suppression rails already covered in webhook/compliance suites. Full twilio suite 62/62; tsgo+lint+fmt clean. B-Twilio-1 feature-complete.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

* mangyinm/cto: fix(twilio): B-Twilio-1 QG remediation — STOP-ack suppression (CRITICAL), webhook DoS cap, inbound-policy enforcement + coverage

Addresses all confirmed 4-reviewer QG findings.
CRITICAL (code+test+security): STOP/HELP compliance acks were suppressed by guardedSendSms (which re-checks isOptedOut after optOut persists) → the CTIA/TCPA-mandated confirmation never sent. Fix: extract testable inbound.ts (handleInboundSms) from index.ts's inline closures; compliance acks now go via UNGUARDED sendSms (mandated replies exempt from the opt-out gate); agent-generated replies stay opt-out-guarded (createSmsReplyDeliver).
MEDIUM (security): readBody had no size cap on the unauthenticated webhook (CWE-770 OOM DoS) → MAX_INBOUND_BODY_BYTES=64KB, 413 on Content-Length over cap AND on streamed overflow.
MEDIUM (design): inbound policy (disabled/allowlist/pairing) was declared but never enforced → inboundAllowed() gates passthrough (STOP always honored first regardless).
LOW: send.ts success-path JSON.parse guarded (never-throws contract); outbound.ts uses SMS_CHANNEL_ID not literal.
Coverage (test): +18 tests → inbound.test.ts (STOP-ack-sends-despite-optout ★, HELP-to-opted-out, compliance-first ordering, policy enforcement, pin-#1 at the agent-reply deliver), webhook-handler.test.ts (503 inert / 200→onInbound / forged→no-onInbound / 413), send missing-sid + non-JSON, classify blank-body, strengthened outbound secret-leak assertion. Full twilio suite 80/80; tsgo+lint+fmt clean.

Generated-With: Claude Code
Co-Authored-By: cto <[email protected]>
Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: cto <[email protected]>
Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants