Repository navigation
feat(sessions): add createdAt tracking and date-range filtering - #1
Conversation
7a0ffc3 to
45d9e2a
Compare
Comprehensive PR Review - 7-Agent AnalysisReview Agents: code-reviewer, pr-test-analyzer, silent-failure-hunter, type-design-analyzer, comment-analyzer, code-simplifier, docs-impact-agentCritical Issues (Must Fix)1. SQL Parameter Numbering Bug in
|
| 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:
- Fix SQL parameter numbering bug (Issue feat(sessions): add createdAt tracking and date-range filtering #1) — correctness
- Fix race condition in ensureReady (Issue fix(persist-postgres): address Greptile review feedback and CI failures #2) — reliability
- Add connection validation on startup (Issue feat(memory): add memory-graphiti extension with dual-backend support #4) — debuggability
- Address silent error swallowing (Issue feat: add memory-milvus plugin for Milvus/Zilliz Cloud vector memory #3) — observability
- Fix mergeSessionEntry fallback (Issue feat(memory): add memory-graphiti extension with dual-backend support #5) — correctness
- 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
a7dbe6b to
3ef2f48
Compare
…openclaw#15448) Co-authored-by: Josh Lehman <[email protected]>
…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)
9558d21 to
3ffecf3
Compare
- 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]>
…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]>
…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]>
Summary
Commit 1: Core session timestamp support
createdAttimestamp field toSessionEntrywith merge-safe preservationupdatedAfter,updatedBefore,createdAfter,createdBeforecreatedAtinGatewaySessionRowoutput.claude/to.gitignoreCommit 2: persist-postgres extension plugin
lp_conversationsandlp_messagesonly — no user tablesession_key,last_message_at,conversation_id + created_at)before_agent_start(persist user prompt),agent_end(persist assistant response), plus channel hooks (message_received,message_sent)Test plan