Security & BYOK
This page documents the security model end-to-end: the BYOK promise, the local vault, handoff envelopes, authentication, request hardening and the bridge trust model.
New to the AI side? Read AI concepts from scratch first — agents act through tools on your machine/services, which is exactly why all of this consent, encryption and auditing exists.
The BYOK promise
Section titled “The BYOK promise”“Your API keys are encrypted locally with AES-GCM and never travel to our servers.”
This is a contracted claim (visible in the product’s trust copy: “Tus API keys se cifran localmente con AES-GCM y jamás viajan a nuestros servidores”). The implementation is designed so the claim holds by construction:
- Keys live in an encrypted vault in your browser (
synthhires-credentials+ mirror), AES-256-GCM. - For each request, the key is wrapped in a single-use, expiring E2EE handoff envelope and sent only for that request.
- The server unwraps, uses, and discards — the plaintext key is never stored or logged server-side.
The concepts behind security
Section titled “The concepts behind security”Because agents have tools that act (see Runtimes) and because the platform is BYOK (the model calls run against your keys), the security model guards two distinct things:
- Your keys never leave your device. The model interacts through a proxy that only ever receives a short-lived, single-use E2EE handoff envelope — your key is unwrapped for one request and dropped. This is not a bolt-on; it’s the contract the whole platform depends on.
- Agents act under consent. An autonomous loop calling
desktop.shell.execute,mobile.sms.sendor an external API is genuinely powerful, so every capability is scoped, consent-gated, audited and revocable. The trust boundary is drawn before the model gets the tool, not after.
Both ideas — we never hold your keys plaintext and tools only run with explicit consent — are what make giving a model hands acceptable. See AI concepts → Function/tool calling for why tools exist at all.
The local vault (src/lib/credentials.ts + kdf.ts)
Section titled “The local vault (src/lib/credentials.ts + kdf.ts)”Key derivation
Section titled “Key derivation”- v1 (legacy):
deriveLegacyV1Key()— device-local derivation. Still readable for backward compatibility. - v2 (hardened):
deriveVaultKey(salt, VAULT_KDF_SECRET)— combines a device salt (getOrCreateVaultSalt()) with a server-provided secret fetched from the vault-secret endpoint. v2 blobs carry thev2:prefix.
Resilience
Section titled “Resilience”- Read-before-write: v2 writes only happen when the server secret is reachable this session; reads fall back to v1 so a transient secret-outage never “disconnects” BYOK.
- Self-healing: if a blob fails with the active key, the client tries known historical/dev secrets; on success it flags migration and re-encrypts with the current key on the next save.
- No silent wipes: unreadable blobs are preserved as raw entries rather than deleted, so a corrupt read can’t destroy data.
Cloud sync (explicit opt-in only)
Section titled “Cloud sync (explicit opt-in only)”Per-provider opt-in (synthhires:vault:cloud-sync-opt-in + serverInference: true) can store a server-readable key in /api/vault (vault_entries) — voice/telegram exception only (server-side inference with no browser attached). Without that explicit consent, no key is ever uploaded. migrateToServer only touches opted-in providers. Device-to-device sync is peer-to-peer (both online), never a stored copy.
Handoff envelopes
Section titled “Handoff envelopes”buildVaultHandoff(provider) (credentials.ts):
- Fetches the server’s E2EE public JWK (
/api/handoff-pubkey). - Wraps the plaintext key with the public key, stamps
issuedAt. - Returns
{ provider, ephemeralPublicJwk, encryptedBlob, issuedAt }— the envelope travels with the chat request. - The server decrypts with its private key, uses the key for the provider call, and drops it. The envelope is single-use by design (ephemeral key per envelope).
Authentication
Section titled “Authentication”- Magic link + OTP codes (
src/lib/auth.ts): email-based sign-in with verification codes (verification_codestable: expiry + attempt counter). - Sessions (
sessionstable): server-side session tokens with expiry;authStorerestores fromsessionStoragesynchronously and reconciles with/api/auth/mein the background. - The auth gate: every API route begins with
await requireResolvedAuth(cookies, request)(src/lib/auth-server.ts) — the single gate; one wrong line there breaks every route (it is on the do-not-edit list). - Guest/local mode: unauthenticated users can still use the platform locally; sessions are saved in the browser only.
Per-account isolation on shared devices
Section titled “Per-account isolation on shared devices”Local-first means your data lives in the browser — and browsers are shared. Conversations, vault entries, drafts, pins, model preferences and library metadata are partitioned per account, so switching accounts never leaks data across them:
- IndexedDB: one database per identity —
SynthHiresDB:anonfor guests,SynthHiresDB:u-<hash>per account. The pre-partitioningSynthHiresDBis migrated once (to the account that logs in first) and deleted. NoownerIdcolumn anywhere: a partition that is never opened cannot leak. - localStorage: account keys resolve to
synthhires:u:<tag>:…under the active session (src/lib/account-scope.ts+storage-keys.ts). The unscoped legacy layout is theanonpartition, and it is claimed by whichever account logs in first. Pure UI chrome (theme, language, sidebar width) stays device-global. - On identity switch (login/logout): the previous database is closed, all in-memory material is dropped — decrypted vault entries, the session-derived v2 vault key, the Drive OAuth token — tab session caches are cleared, and the sidebar is rebuilt from the new partition. Nothing is deleted: logging back in restores everything.
- Logout does not wipe. Erasing is always explicit: Settings → Erase this account’s local data (current account only), guest reset (anon partition only), or account deletion (drops only that account’s local partition after the server-side erase).
Honest boundary: the vault KDF salt is device-global, so account isolation is logical partitioning + the browser-profile boundary — it stops cross-account exposure on shared machines, it is not a second encryption layer. Full-device erasure (all partitions) remains available via the global reset.
Data residency & sync (what lives where)
Section titled “Data residency & sync (what lives where)”- Server-side, per account: identity row, sessions, paired devices, PAT hashes, workflow runs, usage records, memory/vault-sync rows. Purged per account via Settings → Server-side legacy cleanup (chats are never part of it).
- Local-only, never uploaded: chats, titles, messages, attachments, provider keys (encrypted vault), drafts and preferences. They live in the account’s IndexedDB partition + namespaced localStorage on this browser only.
- Settings → This device lists every local partition (accounts + guest) with chat counts and the active one, plus a scope map of what each erase button wipes. Read-only: it never opens another partition’s content.
- Google Drive (opt-in backup, push-only): each save uploads that chat as encrypted JSON (
messagesencrypted with your key) to your Drive app folder. There is no pull/restore path: the other browser does not need to be open, and it will not auto-receive anything. Audit note: the Drive payload key derives from your user id with a public hardcoded salt — obfuscation-grade, NOT zero-knowledge. Recommendation: use E2E sync instead; Drive remains a transport copy, not a vault. - Bridge (opt-in archive, push-only): capped transcript archives are pushed to paired devices’ local SQLite for on-PC access. The server DB stays authoritative for dispatch; the device keeps running its daemon to receive.
- Honest boundary: there is no live multi-browser sync. No tab-to-tab realtime, no conflict resolution, no “both browsers open” requirement — because there is no channel that needs it. If you need a chat on another machine, the supported paths are E2E sync (encrypted relay) and the bridge archive (paired device).
- E2E sync between browsers (opt-in, zero-knowledge): Settings → This device → Sync. You invent a passphrase (min. 12 chars); the key is derived locally (PBKDF2 600k) and NEVER leaves the device. The server stores a public salt plus opaque AES-GCM envelopes (
sync_docsrelay,sync_statesalt) — it cannot read titles, messages, or anything else. Newest-wins byupdated_atin both directions; deletes travel as tombstones from the 24h local trash. Push is explicit (Sync now); sign-in converges automatically while unlocked in that tab. Lose the passphrase and the relay copies are unreadable, even for you. No live realtime channel, no CRDTs — convergence on demand, never requiring both browsers open at once. PATs with scopesync:writecan drive the same relay from terminals.
Personal Access Tokens (terminal & external agents)
Section titled “Personal Access Tokens (terminal & external agents)”Machine identity for terminals and external agents: shp_… tokens issued per account in Settings → API tokens, acting as your account on /api/chat (streaming), GET /api/v1/models, GET /api/workflows/runs, POST /api/mcp-server, POST /api/v1/vault (PAT-only provider setup) and GET|POST /api/v1/space?domain= (whole space: automations, memory, knowledge, sessions, usage, runtimes, studio) with the granted scopes (19 total: chat:write, models:read, workflows:read, sync:write, providers:read/write, automations:read/write, memory:read/write, knowledge:read/write, sessions:read/write, usage:read, runtimes:read/write, studio:read/write). Rules that never bend:
- Hash-only storage: Postgres holds HMAC-SHA256 (server pepper) — the plaintext secret is shown once at creation and never again. No
ownerId-less row: every check istokenHash + expiry. - Opt-in routes only: cookie-gated routes never see PATs. Only routes with an explicit PAT gate accept them (
/api/chat,/api/v1/models,GET /api/workflows/runs,/api/mcp-server) — no existing endpoint changed surface. - Fail-closed: unknown, deleted, expired, or under-scoped token → 401/403, never a guest downgrade. Guests cannot mint tokens.
- Scoped + deletable: closed scope allowlist, per-token expiry, root delete on revoke (no dead rows — a revoked token disappears from the list entirely), last-used tracking, mint rate-limited. Account deletion wipes the account’s tokens (verified like every other user table).
Terminal MVP (BYOK key travels per-request as before — the PAT authenticates the platform, it never replaces your provider key):
# 1. Create a token in Settings → API tokens (secret shown once)# 2. Stream as yourself — usage limits and space tools resolve to your accountcurl -N https://synthhires.com/api/chat \ -H "Authorization: Bearer shp_…" \ -H "x-api-key: $ANTHROPIC_API_KEY" \ -H 'Content-Type: application/json' \ -d '{"messages":[{"role":"user","content":"summarise my usage this week"}],"provider":"anthropic"}'
# OpenAI-shaped model list (scope models:read) — same `provider/model` ids /api/chat acceptscurl https://synthhires.com/api/v1/models -H "Authorization: Bearer shp_…"
# Read-only run history (scope workflows:read), scoped to the token ownercurl https://synthhires.com/api/workflows/runs -H "Authorization: Bearer shp_…"MCP (Streamable HTTP, one JSON-RPC message per POST) for external agents — any valid PAT handshakes; tools are filtered by its scopes (server_ping always, models_list needs models:read):
curl https://synthhires.com/api/mcp-server \ -H "Authorization: Bearer shp_…" -H 'Content-Type: application/json' \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'// opencode / claude-code style MCP config (streamable HTTP + Bearer header){ "mcpServers": { "synthhires": { "type": "streamableHttp", "url": "https://synthhires.com/api/mcp-server", "headers": { "Authorization": "Bearer shp_…" } } } }What a PAT deliberately cannot do: touch browser-local state (chats live in your partitioned IndexedDB, never server-side), manage pairing/devices, or delete the account. Those stay behind the session + explicit consent.
Request hardening
Section titled “Request hardening”- CORS / rate limits / redaction live in
src/lib/security.ts. - Log redaction: all sensitive logging goes through the single
src/lib/log-redaction.tssink — keys, tokens, and PII never reach logs in plaintext. - Error sanitization: stream errors are passed through
safeErrorLogbefore surfacing. - Bounded retries: the retry handler applies max 3 attempts with explicit 429/5xx backoff — no infinite loops.
Bridge trust model
Section titled “Bridge trust model”The desktop/mobile bridge (external Rust repo) connects outbound-only:
- No inbound ports: 100% outbound WebSocket, TLS 1.3.
- Scoped capabilities:
desktop.shell.execute,desktop.fs.read,mobile.sms.send, … — each requires consent (consent_prompt/consent_response frames) and is audit-logged (device_action_log). - Destructive-command guard: the daemon filters destructive commands before execution.
- Revocation: revoking a device kills its token (
device_tokens) and closes the connection. - Pairing: pairing codes (
pairing_codes) are single-use; the device proves possession of the code before receiving a token.
Do-not-regress checklist
Section titled “Do-not-regress checklist”- Never weaken the BYOK trust copy or the encryption flow.
- Never store provider keys server-side outside
vault_entries(encrypted at rest, opt-in only). - Never bypass
requireResolvedAuthin a new API route. - Never log raw keys/tokens — route through
log-redaction.ts.