836 Commits

Author SHA1 Message Date
0xmrpeter
8a8a80f3e9 fix: persist topicId to disk atomically on session creation
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>
2026-04-03 16:27:38 +07:00
0xmrpeter
f9e36052ad fix: improve error handling in session prompt execution
- Updated the error handling in the Session class to emit a detailed error message when prompt execution fails, enhancing debugging and user feedback.
2026-04-03 16:13:47 +07:00
0xmrpeter
e193309e08 feat: enhance path validation and plugin configuration
- 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.
2026-04-03 15:50:24 +07:00
0xmrpeter
18cc04d3f3 feat: implement file service path whitelisting for agents
- 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.
2026-04-03 14:38:16 +07:00
0xmrpeter
5329803b86 fix: Claude missing from onboarding list when Claude CLI not installed
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>
2026-04-03 14:29:14 +07:00
0xmrpeter
62cf9bd2bf fix: improve daemon restart logic and config management
- 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.
2026-04-03 14:14:29 +07:00
0xmrpeter
46350a95c5 refactor: enhance API server port retrieval and adjust health check interval
- 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.
2026-04-03 13:58:41 +07:00
0xmrpeter
adbe268209 test: fix pre-existing api-server test failures to match current implementation
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>
2026-04-03 13:37:37 +07:00
0xmrpeter
e90fedcef8 fix: properly clean up SSE connections and eventBus listeners on shutdown
- 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>
2026-04-03 13:36:04 +07:00
0xmrpeter
9720330085 merge: resolve conflict in file-viewer.ts — keep sanitizeHtml version 2026-04-03 13:23:35 +07:00
0xmrpeter
fa071dc5c4 fix: address code review findings — resolve critical, high, and medium issues
- 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
2026-04-03 13:14:02 +07:00
0xmrpeter
fc69a2f122 security: harden API server and tunnel against injection and DoS attacks
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>
2026-04-03 13:12:38 +07:00
0xmrpeter
b1840d538d test: update tests to match new security behavior (reject unsafe paths, no description auto-approve)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:38:28 +07:00
0xmrpeter
f33f89223a fix: tunnel auth default on, XSS sanitization, credential env vars, path redaction
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:36:23 +07:00
0xmrpeter
3919d29c12 feat: add lightweight HTML sanitizer for tunnel viewer XSS prevention
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:34:58 +07:00
0xmrpeter
8a9a724b15 fix: add download size limit and tar validation to install-binary 2026-04-03 12:32:52 +07:00
0xmrpeter
6e0cde1e41 fix: add --ignore-scripts to all npm install calls to prevent lifecycle RCE 2026-04-03 12:31:28 +07:00
0xmrpeter
ae6a904789 feat: add checksum verification, size limits, path validation to agent installer
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:30:02 +07:00
0xmrpeter
7f75153a4c fix: require sessions:dangerous scope for bypass permissions endpoint
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>
2026-04-03 12:27:00 +07:00
0xmrpeter
a8217ea535 fix: remove description-based auto-approve bypass in session-bridge
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>
2026-04-03 12:25:27 +07:00
0xmrpeter
2bb70d0ac9 feat: wire PathGuard and EnvFilter into agent file operations and process spawning
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:23:57 +07:00
0xmrpeter
e8a0242e72 feat: add workspace.security config schema and fix resolveWorkspace path traversal
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:21:22 +07:00
0xmrpeter
ace8d675d8 feat: add EnvFilter module to prevent environment variable leakage
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:19:11 +07:00
0xmrpeter
59c76a080b feat: add PathGuard module for workspace boundary enforcement
Implements PathGuard with symlink resolution, default deny patterns for
sensitive files (.env, *.key, credentials*), allowedPaths support, and
custom ignore pattern overrides via constructor options.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 12:17:14 +07:00
0xmrpeter
f9bcb34979 fix(viewer): skip binary files and downgrade spurious WARN for out-of-workspace paths
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>
2026-04-03 11:15:05 +07:00
0xmrpeter
78495c7856 fix: always show Claude Agent in onboarding list when Claude CLI is missing
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>
2026-04-03 10:56:26 +07:00
0xmrpeter
8b9b7ffc36 fix(channels): read config from plugin settings instead of config.channels
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>
2026-04-03 10:55:38 +07:00
0xmrpeter
1f071db03a Merge branch 'develop' of github.com-peter:Open-ACP/OpenACP into develop 2026-04-03 10:04:45 +07:00
0xmrpeter
eea6e9a4fe fix: update tests for current API and add config value-type validation
- Add TypedEmitter to mock AgentInstance (Session constructor requires .on())
- Update config-migrations test for cloudflare→openacp tunnel provider migration
- Add missing mock fields (api, agentCatalog, settingsManager, setPath)
- Isolate instance-context tests from OPENACP_INSTANCE_ROOT env var
- Fix SSE tests to read past initial `: connected` comment
- Add validateFieldValue() to config-registry for type-safe config writes
- Handle ConfigValidationError in API error handler (→ 400)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 10:03:53 +07:00
0xmrpeter
d9b93b3542 test: update instance-copy tests for migrated section stripping 2026-04-03 09:49:18 +07:00
0xmrpeter
378b97d3d0 fix: config editor routes edits to plugin settings for migrated fields
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 09:47:26 +07:00
0xmrpeter
73b6d58b20 fix: correct inheritableKeys to match actual plugin setting keys
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 09:46:11 +07:00
0xmrpeter
0a91c37f28 fix: speech hot-reload reads from plugin settings, emit synthetic config:changed
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 09:46:05 +07:00
0xmrpeter
36cdf4ce1c fix: env var overrides now flow to plugin settings
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>
2026-04-03 09:43:57 +07:00
0xmrpeter
92ac54a3c3 fix: instance-copy strips migrated plugin sections from config.json
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>
2026-04-03 09:35:15 +07:00
0xmrpeter
377e84c6f3 fix: Telegram /settings reads/writes plugin settings for migrated fields
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>
2026-04-03 09:33:15 +07:00
0xmrpeter
5179d3334d fix: API config route reads/writes plugin settings for migrated fields
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 09:31:33 +07:00
0xmrpeter
aebd7fa8d8 fix: SecurityGuard reads live from SettingsManager, checkAccess now async
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>
2026-04-03 09:29:55 +07:00
0xmrpeter
3c74ec0feb feat: add plugin mapping to config registry with async read/write helpers
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 09:25:41 +07:00
0xmrpeter
32132a801e fix(api-server): use singleton RegistryClient to enable 1-min TTL cache 2026-04-03 01:20:34 +07:00
0xmrpeter
a031d21f6e fix(api-server): move GET /marketplace before parameterized routes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-03 01:04:43 +07:00
0xmrpeter
b92e542a30 feat(api-server): register /api/v1/plugins route group
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>
2026-04-03 00:35:41 +07:00
0xmrpeter
d676faadc7 fix(api-server): fix decodeURIComponent, static node imports, assert enable test spies 2026-04-03 00:33:33 +07:00
0xmrpeter
3d39d1d811 fix(test): mock RegistryClient to make marketplace tests reliable
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.
2026-04-03 00:29:32 +07:00
0xmrpeter
4648ae50a1 feat(api-server): add DELETE /plugins/:name endpoint 2026-04-03 00:27:45 +07:00
0xmrpeter
c3e4e32a9b feat(api-server): add POST /plugins/:name/disable endpoint 2026-04-03 00:27:09 +07:00
0xmrpeter
f731f30b9a feat(api-server): add POST /plugins/:name/enable endpoint 2026-04-03 00:26:30 +07:00
0xmrpeter
2a72a1ee38 feat(api-server): add GET /plugins/marketplace endpoint 2026-04-03 00:24:07 +07:00
0xmrpeter
3526752bb3 chore: remove unused beforeEach import in routes-plugins test 2026-04-03 00:22:47 +07:00
0xmrpeter
cea1009e6c feat(api-server): add GET /plugins endpoint
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>
2026-04-03 00:20:24 +07:00