The lazy-resume flow failed after server restart because topicId was
written in a separate debounced patchRecord call (2-second window).
If the server restarted before that debounce fired, the on-disk record
had platform:{} with no topicId, so findByPlatform returned null and
the session could not be resumed.
Fix: add threadId? to handleNewSession and createSessionWithContext
options so callers can pass the Telegram topic ID at creation time.
createSession already includes platform.topicId in its initial
patchRecord({ immediate: true }) call, so the topicId is flushed to
disk atomically — no separate patchRecord needed.
Updated callers:
- telegram/commands/new-session.ts: 3 call sites
- telegram/commands/resume.ts: createSessionWithContext path
- core/assistant/assistant-manager.ts: pass threadId to createSession
Added regression tests documenting both the broken pattern (debounced
write loses topicId on crash) and the fixed pattern (included in
initial immediate save).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Added a new test to verify that allowedPaths can override ignore patterns for paths within the current working directory, ensuring proper access control for file uploads.
- Updated the path-guard logic to clarify that allowedPaths take precedence over ignore patterns.
- Simplified the plugin configuration logic for the Telegram channel by removing unnecessary mapping, directly importing the plugin when the channelId matches.
- Added functionality to allow agents to read attachments from the file-service upload directory by whitelisting the base directory.
- Enhanced AgentInstance with addAllowedPath method to manage additional read paths.
- Updated SessionFactory to inject extra filesystem paths for agents, ensuring they can access necessary files without compromising workspace security.
- Refactored AgentSwitchHandler to utilize the file service for managing allowed paths during agent switching.
This change improves the flexibility of agent interactions with external files while maintaining security boundaries.
The previous fallback wrote to a separate AgentStore instance, which saved
Claude to disk but left the in-memory AgentCatalog unaware of it. As a result,
catalog.getAvailable() did not include Claude, so it never appeared in the
onboarding agent multiselect.
Fix: add AgentCatalog.registerFallbackAgent() that writes directly into the
catalog's own store (this.store), making Claude immediately visible to
getAvailable() without requiring a reload.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Added console log for stopping the daemon to enhance user feedback.
- Updated ConfigManager initialization to load from the specified config file.
- Refined the logic for determining the run mode, ensuring correct behavior when restarting a daemon based on its previous state.
- Updated API server port retrieval to use the service's getPort() method, ensuring accurate port assignment.
- Changed health heartbeat interval from 30 seconds to 15 seconds for more frequent health checks.
- Removed unnecessary DOMPurify script from file-viewer template to streamline loading for markdown rendering.
1. Health endpoint split: /health now returns only {status, uptime, version}
(public, no auth). Sensitive details (memory, sessions, tunnel) moved to
/health/details (requires auth + system:health scope). Split the single
test into two — one for each endpoint. Also remove stale mockReturnValueOnce
calls in the "allows health endpoint without auth" auth test that were never
consumed and polluted the "accepts requests with valid auth token" test via
Vitest's clearAllMocks not clearing the once-return queue.
2. Notify validation error: the error message changed from "Missing message" to
"Required" (Zod default). Update the assertion to match.
3. SPA fallback bug fix (static-server.ts): the symlink traversal guard
introduced in the security hardening commit broke SPA fallback for
non-existent paths on macOS where /var is a symlink to /private/var.
When realpathSync fails (file doesn't exist), the unresolved filePath starts
with /var/... but realUiDir resolves to /private/var/..., so the prefix check
fails and the static server returns false instead of serving index.html.
Fix: skip the symlink guard when the file doesn't exist — a non-existent path
cannot be a symlink pointing anywhere dangerous, so the guard is unnecessary.
4. Auth test pollution root cause: fixed by #1 — the old health test queued two
mockReturnValueOnce values that were never consumed (new /health endpoint
doesn't call listSessions/listRecords), so they leaked into the auth test
which then got stale session data when calling the sessions route, causing
s.clientOverrides to be undefined → TypeError → 500.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- api-server: store SSEManager reference in plugin closure so teardown()
can call sseManager.stop() before server.stop(); SSE connections use
reply.hijack() and are not tracked by Fastify, so they must be
explicitly closed to allow the server to release its port
- telegram: store session:threadReady and session:configChanged listener
references as private fields and remove them in stop(); these were
registered directly on core.eventBus (not via ctx.on) so ctx.cleanup()
did not remove them, causing listener leaks on plugin restart
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- C1: resolveWorkspace() now allows absolute/tilde paths under baseDir; rejects paths outside baseDir; update tests to match new semantics and add coverage for allowed cases
- C2: revert bore.ts to use --secret CLI flag instead of BORE_SECRET env var (bore does not support env var)
- H1: revert openacp.ts to use --token CLI flag instead of TUNNEL_TOKEN env var (cloudflared env var support unreliable)
- H2: add sessions:dangerous scope to KNOWN_SCOPES in roles.ts; not granted to any named role (admin-only via wildcard)
- H3: expand DEFAULT_ENV_WHITELIST with GIT_*, SSH_AUTH_SOCK/PID, terminal rendering vars; add comments documenting envWhitelist/allowedPaths config wiring as follow-up
- H4: revert tunnel viewer routes to auth: false — content is already gated by random UUIDs
- M1: readTextFile PathGuard rejection now throws Error instead of returning access-denied string as content
- M2: apply sanitizeHtml() to file-viewer fallback path (non-marked rendering) to prevent XSS
- M3: envWhitelist/allowedPaths documented as follow-up in agent-instance.ts comments
- M4: validateTarContents uses segment-based check for .. traversal to avoid false positives on filenames like setup..sh
Fix 26 vulnerabilities identified in security audit of the API server
plugin and public tunnel surface:
Input validation & injection prevention:
- Add Zod schemas with strict field limits to notify, tunnel, and topic routes
- Block absolute workspace paths in CreateSession to prevent path injection
- Validate scope strings with regex and cap at 20 scopes / 50 chars each
- Validate port range (1-65535) in tunnel POST and DELETE /:port
- Cap token lifetime to max 365 days; enforce max lengths on auth fields
- Cap command strings at 1000 chars; add max lengths to ID/name params
XSS prevention:
- Load DOMPurify CDN alongside marked.js in file-viewer template
- Sanitize marked.parse() output with DOMPurify before innerHTML assignment
- Escape HTML entities as fallback when DOMPurify is unavailable
CORS hardening:
- Remove Access-Control-Allow-Credentials: true from main server CORS
- Remove Access-Control-Allow-Credentials: true from SSE responses
Rate limiting:
- Add keyGenerator to extract real client IP from cf-connecting-ip /
x-forwarded-for headers so rate limits work correctly behind tunnel proxies
- Apply per-route limit (5 req/min) on unauthenticated /auth/exchange
DoS & resource exhaustion:
- Cap SSE connections at 50; return 503 when limit is reached
- Cap prompt body at 100 KB (was unbounded)
- Add overall max lengths throughout all input schemas
Information disclosure:
- Public GET /health returns only {status, uptime, version}
- Move sensitive details (memory, sessions, adapters) to authenticated
GET /health/details requiring system:health scope
Symlink traversal:
- Resolve realpathSync() before path prefix check in static-server.ts
to prevent symlink-based path escapes out of the UI directory
Token leakage:
- Log a warning (with token redacted) when auth token is passed via URL
query param instead of Authorization header to catch accidental logging
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The /dangerous endpoint previously accepted any sessions:write token, allowing
any write-authorized API client to toggle bypass permissions. It now requires
the dedicated sessions:dangerous scope to restrict this capability to explicitly
authorized clients.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Agents could craft tool descriptions containing "openacp" to bypass all
permission gates. Remove the string-match check entirely; the only
legitimate auto-approve path is now the explicit bypass mode (agent
bypassPermissions config or client clientOverrides.bypassPermissions).
Update tests to assert that "openacp" in a description no longer
auto-approves requests when bypass mode is off.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
When an agent reads a voice attachment saved to ~/.openacp/files/ (e.g. after
a Telegram voice message), the viewer-store logged a WARN "Path outside
workspace, rejecting" for every such read. This was misleading — the rejection
only affected viewer link generation, not the actual file access — but it made
the STT feature appear broken.
Two fixes:
1. message-transformer: skip binary/non-text file extensions (.wav, .ogg, .mp3,
.mp4, .jpg, .png, .pdf, .zip, etc.) before attempting to generate viewer
links. Binary files cannot be displayed in the code viewer, so calling
storeFile/storeDiff for them was always pointless.
2. viewer-store: downgrade the path-outside-workspace log from WARN to DEBUG.
Returning null for out-of-workspace paths is expected, not an error.
Fixes#195
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
When the Claude CLI (`claude` command) is not installed, `installAgent()`
fails the dependency check and returns `{ ok: false }` without adding the
agent to the store. The previous code ignored this return value, so the
fallback path (direct store.addAgent) was never reached, leaving Claude
absent from the onboarding agent selection list entirely.
Fix: check the install result and fall through to the bundled fallback when
the registry install fails for any reason.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
After the plugin system migration, channel configuration (botToken, chatId,
etc.) is stored in SettingsManager (~/.openacp/plugins/data/) rather than
in config.channels. Several UI and diagnostic code paths still read from
the old location, causing channels to always appear as "Not configured"
even after a successful setup.
Fixes#194
Changes:
- getChannelStatuses(): make async, check SettingsManager before config.channels
- configureChannels(): accept settingsManager param, use it for status display
and when invoking plugin configure()
- editChannels(): check SettingsManager for configured/enabled display status
- editDiscord(): fix wrong SettingsManager basePath (plugins → plugins/data)
- summarizeConfig(): make async, check SettingsManager for channel status
- telegramCheck (openacp doctor): read botToken/chatId from plugin settings
first, fall back to legacy config.channels
- config.ts cmdConfig: fix SettingsManager basePath (plugins → plugins/data)
- onboard.ts cmdOnboard: pass settingsManager to runReconfigure()
- runReconfigure(): accept and propagate settingsManager to sub-functions
Tests: add setup-channels, helpers, and telegram-check unit tests covering
the plugin-settings-first read behavior.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Add ConfigManager.applyEnvToPluginSettings() that maps env vars like
OPENACP_TUNNEL_ENABLED and OPENACP_TELEGRAM_BOT_TOKEN to the correct
plugin settings keys, and call it from main.ts after config load.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Remove security, tunnel, api, speech, usage sections and plugin-owned
channel fields when copying an instance, preventing lifecycle-manager
fallback from leaking unfiltered settings to the new instance.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Replace getConfigValue/configManager.save() with getFieldValueAsync/
setFieldValueAsync so that fields with a plugin scope (tunnel, security,
speech) are read from and written to plugin settings instead of config.json.
Also make buildSettingsKeyboard async and fix speech.stt.provider API key
check to read groqApiKey from plugin settings when SettingsManager is available.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
SecurityGuard no longer takes ConfigManager directly. Instead it receives
a getSecurityConfig() async accessor that reads from SettingsManager on
each checkAccess call, so runtime settings changes take effect immediately.
- Export SecurityConfig interface for type-safe config access
- Fix inheritableKeys to match actual settings keys
- Update core.ts to await the now-async checkAccess
- Rewrite tests for new async API with full coverage
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Wire lifecycleManager into RouteDeps and register pluginRoutes at
/api/v1/plugins alongside the existing route plugins.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Replace network-dependent 503 assumption with vi.mock of registry-client,
enabling deterministic happy-path (200) and error-path (503) tests regardless
of internet availability in the test environment.
Implements GET /api/v1/plugins route that lists all installed plugins
with runtime state (loaded, failed, essential, hasConfigure) merged
from the plugin registry and LifecycleManager.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>