# Loami security and deployment posture

Provider-specific Clerk controls below describe the Vercel deployment. Independent
Node/Docker uses native credentials and the separate boundary described here;
it does not inherit Clerk's hosted CAPTCHA, lockout or enterprise integrations.

## Independent native deployment

Native accounts, sessions, organizations and agent grants live under the restricted
`loami_auth_app` role, separate from the `loami_app` content role and private
migration ledgers. Both use verified TLS. Closed signup, operator-only bounded
stdin bootstrap, verified invitations and current account/membership checks remain
mandatory. Cookie API writes require the exact configured Origin. Forwarded IP
trust is disabled unless exclusive proxy addresses are explicitly configured.

Native agent connections use SDK discovery, DCR, signed consent, S256 PKCE and
resource-bound hashed opaque tokens. Public registration is bounded by persisted
IP limits and a serialized 1,000-client backstop; it grants no account access.
Administrative OAuth and internal principal routes are not public. The resource
checks current stored session, user, client and consent before enforcing current
team role and actual content RLS. Access is create-only through private publishing
tools; cookies and bearer grants cannot replace each other. User-visible
disconnect revokes their own grants; sign-out, session expiry and recovery
revocation also block subsequent use. A different cookie hostname is required for
callbacks, since ports do not isolate browser cookies. No token or browser state
belongs in document HTML or a test artifact. See `intent/NATIVE-AUTH.md` and
`intent/NATIVE-OAUTH.md` for exact scopes, limits, secret lifecycle and tests.

Native local HTTP/browser and actual-image tests do not certify public SMTP,
hosted HTTPS/ingress, vendor-specific agents, Entra/SCIM or deployed cloud
infrastructure. Vercel retains its selected Clerk provider; there is no fallback
between independent identity stores or automatic ownership matching by email.

## Clerk deployment

Private publishing MCP at `/mcp/publish` accepts verified Clerk user OAuth tokens, never session tokens or anonymous writes. OAuth onboarding uses Clerk consent, PKCE S256, and an allowlist of `profile` and `user:org:read` scopes; CIMD and DCR support are enabled for compatible agents. DCR permits client registration, not account access without consent; review client identity before approval. The public `/mcp` stays source-only. Publishing derives Personal from the verified subject, checks live team membership and edit role on every write, and uses restricted-role/RLS storage and existing quotas. Safe previews retain their sandbox. An identical publication UUID/source/creator retry returns the same document; other reuse is rejected. Returned URLs require account/workspace access. Tokens are verified by Clerk and never stored in source or logs. Revoke OAuth grants through the account provider or disconnect the agent; expired/revoked credentials must reconnect.

Status: team-workspace public preview, 2026-10-18. This is an engineering control inventory, not an independent assessment or a claim of SOC 2, ISO 27001, HIPAA, GDPR, or ASVS certification. Use a limited pilot with non-sensitive documents until the enterprise gates below are closed.

## Trust boundaries and data flow

Browser → same-origin API on Vercel or Node → Clerk JWT and current user/session/membership verification → restricted PostgreSQL role → team-scoped transaction. Clerk manages identity and organization invitations. PostgreSQL stores HTML CRDT state, document metadata, comments, checkpoints, transient presence and audit events. The public MCP generates document source only; it cannot access team content. The separate private publishing MCP requires verified user OAuth and an explicitly chosen destination; there is no shared team API key.

The server derives the organization and user from a verified Clerk bearer session, never from request parameters. Supplying a different organization is rejected. Every query includes organization scope; PostgreSQL row-level policies independently require a transaction-local organization context. Composite foreign keys prevent cross-team folder/thread references. The application role is `loami_app`, with no superuser, role-creation or RLS-bypass privilege. Each transaction resets scope on completion and has an eight-second SQL statement timeout.

Database RLS protects against missing organization predicates, not compromise of the trusted application server: the server can set its organization context. Hosting administrators and migration credentials can access customer data. This is not end-to-end encryption. Native integration owner credentials remain in the hosting secret environment; keep deployment/admin access tightly restricted and move migration credentials to a separate administrative boundary before a sensitive enterprise rollout.

## Identity and permissions

- Production requires live Clerk keys and rejects development credentials. Only verified bearer sessions are accepted; cookies alone cannot mutate APIs. Browser origins are allowlisted, JSON is required for writes, and GET cannot mutate documents/comments.
- Production email one-time-code sign-in and verified email signup are enabled. Google, GitHub and Microsoft are disabled until their production OAuth credentials are configured. CAPTCHA, strict enumeration protection, PII protection and failed-attempt lockout are enabled in Clerk production.
- The SDK verifies session JWTs on every request. Current user/session state and team membership are rechecked for explicit actions and writes; banned, locked, directory-deprovisioned, deleted or inactive identities cannot access Personal or team content. Only background sync may reuse a scoped authorized result for at most five seconds from lookup start. Fresh denials and provider-state failures invalidate that user's process-local cache; older concurrent successes there cannot resurrect it. Other replicas retain only the same bounded sync window. Lookup outages fail closed with 503. See `intent/ENTERPRISE-IDENTITY.md` for exact bounds and pending live Entra acceptance. Organization changes/sign-out clear the private editor, iframe, library, comments and form values.
- Organization admins and members can edit; `org:editor` is also supported. `org:viewer` can read/comment but cannot edit, organize or checkpoint. Unknown organization roles are denied workspace access. Admins alone export the team audit log. Custom role provisioning is not bundled into this preview's role UI.
- Team links require authentication and membership. No anonymous/public cloud shares, email-domain auto-join, cross-team invitations, or public private-document endpoints exist. Clerk handles invitations in its organization profile. Deleting an organization through the member UI is disabled to avoid orphaning saved records.
- Current Clerk configuration permits five memberships per organization. Custom session duration/inactivity controls were attempted in dry-run and rejected by the current subscription; no paid upgrade was made. Current provider default maximum session lifetime is seven days, with inactivity timeout disabled. SSO, SCIM and mandatory MFA policies have not been rolled out.

## Untrusted HTML and browser controls

- The workspace never inserts document HTML into its own DOM. CodeMirror shows source as text. Titles, tags, comments and names use `textContent`.
- Preview runs in an iframe with `sandbox="allow-scripts"` and **without** same-origin, top-navigation, forms, popups or downloads privileges. It cannot access the parent session, cookies or DOM.
- Preview removes authored executable scripts, event handlers, nested frames/objects, refresh metadata, base tags, external stylesheets and non-fragment links. Its CSP denies external connections, images, frames and form submission; only data/blob images and embedded fonts are allowed. Hashes allow the pinned Loami/Anatomy code and a fixed first-party inline-text bridge. Declarative JSON data remains usable. Arbitrary authored JavaScript is deliberately unavailable in the hosted safe preview; export retains authored code.
- The workspace's own CSP allows only first-party assets, the production Clerk host and documented Clerk abuse-protection hosts. Inline application scripts and evaluation are disallowed; pinned runtime hashes support the nested preview. The nested preview also hash-allows the fixed inline-text bridge. Inline CSS remains necessary for Clerk/CodeMirror/Loami. The app denies framing and disables camera, microphone, geolocation, payment and USB access.
- Inline text mode wraps only prose text ranges, excluding authored code, controls, links, SVG/canvas and custom graphics. Plain text is escaped before a bounded source replacement through Yjs; the original HTML structure is retained. The opaque frame messages the parent using a fresh per-render token; the parent checks the exact iframe window, token, target range, edit permission and current source before applying a change. Concurrent changes to the same range are refused and the user's draft is exposed for recovery. No arbitrary HTML or script is accepted through this bridge. The bridge does not expose credentials or general parent capabilities.
- Authentication/data responses use `private, no-store`. No document cache, service worker or private HTML localStorage is used. Unsaved changes live in tab memory; network errors retain pending CRDT updates for idempotent retry. Reloading/closing can lose unsaved work, so the editor warns and offers export. Signing out or changing teams clears that memory to protect privacy.
- Export creates a user-owned HTML file. It includes authored code and may retain third-party resources. Downloaded HTML runs with the recipient's browser permissions; share/open only trusted documents. Workspace permissions, presence and comments are not embedded into exported files. Offline files cannot be remotely revoked.

## Storage, concurrency and abuse controls

TLS certificates are validated for database connections (`sslmode=verify-full`); HTTPS is used for Clerk and the production site. At-rest infrastructure encryption and backup behavior are provider responsibilities, not custom application cryptography or a customer-managed-key feature.

Yjs CRDT updates merge while the database document row is locked, preventing lost concurrent updates. Update UUIDs provide retry idempotency within the retained journal. Clients sync about every 1.5 seconds, with five-second presence heartbeats and a twenty-second online window. Delivery uses HTTP polling, not WebSockets or live cursors. Checkpoints are explicit, with the initial creation checkpoint saved automatically. History can compare checkpoint source as inert text and restore it as a new revision of the same document. Restore requires current edit permission, an unarchived authorized document and the exact reviewed base revision. It preserves the previous source as a checkpoint and records operation identity/provenance in the existing append-only audit. A matching retry replays the saved outcome without replacing later edits while that audit entry is retained. Capacity and stale-base failures leave source/history unchanged.

Limits: 500,000 source characters, 2 MiB encoded CRDT state, approximately 64 KB per edit batch, 750 KB JSON request, 100 documents/team, 50 folders/team, 8 tags/document, 500 comments/document, 4,000 characters/comment, 50 checkpoints/document. The transient journal retains about thirty recent updates and older clients receive a full snapshot. A transaction-serialized 50 MB logical-content budget covers current CRDT state, retained update data, checkpoint source and comment bodies. This is **not** a total database-storage quota: indexes, audit events, presence and metadata also consume storage. Authenticated requests are limited in PostgreSQL to 180 reads and 120 writes per user/team/minute. These are application backstops, not a distributed edge abuse-control program. Vercel's platform DDoS protection remains in place; a dedicated WAF rate-limit policy and tenant quotas need load testing.

The audit table records actor ID, action, resource ID, revision where relevant and timestamp, without raw HTML, comment bodies or credentials. App-role UPDATE/DELETE privileges on audit rows are denied. Admin export returns the latest 500 events. This is not tamper-proof against a database administrator, not a full SIEM integration, and does not capture all identity administration (Clerk has separate admin logs).

## Verification evidence

- `npm test`: generation escaping, MCP protocol, missing/invalid session cases, membership scope, cross-origin denial, JSON/write-method controls, role permissions and cross-team request rejection.
- `node tests/workspace-database.mjs`: actual restricted database role, RLS without an explicit predicate, cross-team document/folder/thread denials, viewer edit denial, simultaneous CRDT writes and idempotent retry, persistence, comments/replies/resolution, verified-name presence, checkpoints, archive behavior and audit deletion denial. Synthetic test teams are removed after the run.
- `tests/workspace-browser.mjs`: two isolated browsers against the actual database and production CSP, simultaneous edits converging, comments/replies, presence, checkpoint download/export, responsive layouts, malicious HTML parent-access/external-request denial and sign-out clearing. Clerk identities are isolated test fixtures, not production user sign-ins. No production users were created or impersonated, and no human invitations were sent.
- Public signed-out production Clerk UI and protected API denial are verified at deployment. A real email OTP, team-creation, invitation acceptance and two real authenticated production users remain a human acceptance step.
- `npm audit` at build time has no known reported dependency vulnerabilities; this is not a penetration test.

## Enterprise release gates and operating responsibilities

Before storing sensitive enterprise content:

1. Complete real-user OTP/team/invitation acceptance and verify two real members editing. Test removed-member access and organization switching with pending edits.
2. Establish an owner-monitored private vulnerability-reporting channel, incident response/on-call, uptime/error alerts, SIEM/audit retention and security change review. Do not publish an unmonitored security email address.
3. Commission an independent application penetration test and assess against applicable OWASP ASVS 5 requirements. Address findings; do not infer certification from this checklist.
4. Agree a DPA/subprocessor list, privacy policy, retention/deletion process, residency requirements and tenant-offboarding procedure. Archive is reversible and is not deletion. No automated retention/deletion or customer legal-hold policy is shipped yet.
5. Set and test provider backups, retention, restore, RPO/RTO, region and disaster recovery. Run a restore drill on an isolated branch. This release has not established a recovery SLA or verified point-in-time restore entitlement.
6. Select Clerk plans and policies for desired team size, shorter session limits, mandatory MFA, SAML/OIDC SSO and SCIM. No automatic subscription upgrades are authorized.
7. Separate development/staging infrastructure, move migration credentials out of the app deployment, scope provider/operator access and document rotation cadence. The setup secret was rotated before team launch with a one-hour old-key overlap; production uses the replacement. Never paste replacements into chat.
8. Load/abuse test polling, large CRDT histories and free-plan database capacity; add edge rate limits, infrastructure storage budgets, pagination and monitoring before a broad public campaign. Journal pruning bounds sync history but audit/checkpoint storage still needs retention operations.
9. Review per-document permissions, restricted sharing, DLP and public export requirements with target customers. Current authorization is team-wide; members can export every team document. There is no rich-text WYSIWYG collaboration, live cursor display, automatic version recovery or encrypted customer vault.

Operational references: [OWASP ASVS](https://owasp.org/www-project-application-security-verification-standard/), [Clerk CSP](https://clerk.com/docs/guides/secure/best-practices/csp-headers), [Clerk rotation](https://clerk.com/docs/guides/secure/rotate-api-keys), [PostgreSQL RLS](https://www.postgresql.org/docs/current/ddl-rowsecurity.html).

### Rendered block comments and customer feedback

Hosted block comments use bounded Yjs relative positions, resolved only against semantic blocks in the current document. The opaque preview sends messages through a fixed first-party bridge hashed in both frame and parent CSP. The parent checks the exact current iframe window, a fresh render token, document scope and role before accepting a comment. Deleted blocks preserve conversations without guessing a new attachment. Drafts prevent navigation until sent or cancelled. Retries carry an idempotency key. Comments and presence are excluded from portable document exports.

The feedback action creates a customer-reviewed draft in the public Darthwares/loami-feedback GitHub repository. No production GitHub token is provisioned, and no document contents, workspace URL, tenant ID or account information is attached automatically. Customers submit using their own GitHub account and receive the issue's permanent tracking URL. Public issues are inappropriate for vulnerabilities or sensitive data.

### Downloadable source templates

The source archive reconstructs `.claude/skills/loam-html/` from the published canonical skill and writes a public authoring-only `.mcp.json`. It does not copy the developer’s local `.claude` settings, unrelated agent skills, or workspace MCP headers/commands. Environment files, Vercel state and working directories remain excluded. This narrows agent-configuration packaging; it is not a general secret scanner for authored source or intentionally public assets. A synthetic regression checks these exclusions.

The authenticated linked-section resolver checks parent access and each source realm independently for the SDK-verified user. Current target membership and source RLS are required; a parent link does not confer source permission. It returns no restricted-source metadata and never materializes source text into parent storage. Live/checkpoint observations are bounded by reference, depth, byte, rate and deadline checks. Returned HTML remains untrusted and requires isolated safe rendering; the workspace uses opaque nested srcdoc with an explicit trusted-hash union and frame/token-scoped fixed bridge. Offline linked snapshots require a fresh, reviewed materialization action; parent HTML retains its native fallback. See intent/LINKED-CONTENT.md for exact contracts and remaining work.
