# Security Trust-boundary tracking for Grida. Every prevented vulnerability gets a stable id, the id appears in every file the boundary depends on, and this document is the central registry. ## Convention: `GRIDA-SEC-` We use `GRIDA-SEC-001`, `GRIDA-SEC-002`, … as canonical ids for **security boundaries we have prevented**. The format is deliberately unlike CVE: - A **CVE** describes a vulnerability that was discovered, often after exposure. The id implies "this was a problem." - A **GRIDA-SEC** id describes a vulnerability that was structurally prevented from existing — and a contract with the codebase that it must stay prevented. The id is "this is a thing we keep safe." Every GRIDA-SEC id has: - An entry in this file with the threat model and the enforcement mechanism. - A grep tag in every file bound by the contract — comments in source, callouts in READMEs, ingress filters in scripts. - An auto-loaded skill ([.agents/skills/security/SKILL.md](.agents/skills/security/SKILL.md)) that triggers when an agent encounters the tag. > **The grep is the index.** `grep -r GRIDA-SEC-001 .` returns every > file in that contract. `grep -r GRIDA-SEC .` returns every security > boundary in the repo. ## Philosophy: transparent tracking Grida is open source. The threat model is public; the URLs an attacker might find are public; the fact that webhooks exist is public. Security in this repo is therefore **structural**, not secret. We make every boundary loud, named, and grep-able so that future work doesn't drift into opening new attack surface by accident. A developer touching tagged code can't miss the marker; a code review of any tagged file naturally surfaces the others; an agent picks up the [security skill](.agents/skills/security/SKILL.md) the moment it sees "GRIDA-SEC" anywhere in context. > If you're adding a new boundary, allocate the next sequential id, add > an entry below, and tag the relevant files. Don't reuse ids; don't > renumber. --- ## Active boundaries ### `GRIDA-SEC-001` — Retired machine ingress **What it protects.** Grida does not expose financial-provider callback receivers. The retired `/webhooks` namespace returns 404 before browser, tenant or handler processing. Do not reuse that namespace for an unauthenticated mutation. **Vulnerable scenario (prevented).** An old callback path accidentally regains a handler or an authentication bypass during unrelated routing work. **How the code prevents it.** The proxy rejects the entire retired namespace. Regression checks cover its root and child paths with read, write and preflight methods on an arbitrary host. They verify no handler pass-through or browser service loading. **Files bound by this id.** - [editor/proxy.ts](editor/proxy.ts) — rejects retired ingress. - [editor/lib/api/proxy.test.ts](editor/lib/api/proxy.test.ts) — ingress regression checks. --- ### `GRIDA-SEC-002` — Insiders dev harness is local-only **What it protects.** The `(insiders)` route group remains a local developer surface. `/insiders/*` is reachable only when `NODE_ENV === "development"`. Next server actions are HTTP RPC endpoints; hiding a harness link does not prevent access to its actions. Never import insiders actions from production routes, which would publish them under a different URL and bypass this gate. **How the code prevents it.** [editor/proxy.ts](editor/proxy.ts) returns 404 for `/insiders` and `/insiders/*` outside development, including action POSTs. [The insiders layout]() independently calls `notFound()` outside development. Provider tunnels must not expose this group. **Retained history.** The former `/insiders/billing` harness exercised privileged financial lifecycle actions without org-membership checks. It was retired with Grida's duplicate financial engine; Platform owns current financial QA. Its deleted billing actions are not current proof or instructions. This ID retains the threat model and governs every remaining insiders surface. **What does NOT belong under `(insiders)/`.** Anything that needs to ship to production. Move a graduating feature to its authenticated product/API surface; never relax the insiders gate. --- ### `GRIDA-SEC-003` — AI seam org-id trust boundary **What it protects.** Every call into the AI provider SDKs (Vercel AI SDK, Replicate, OpenAI, Anthropic, and funded Tripo) is gated and billed against an `organizationId`. If that id reaches the seam unverified, an attacker who can choose the id drains another org's credit balance. The boundary is the rule that **every `organizationId` reaching `editor/lib/ai/server.ts` has been verified as a member-org for the calling user.** **Vulnerable scenario (prevented).** A developer adds a new AI route handler that reads `organizationId` from the request body and forwards it straight into the seam. An attacker enumerates `organization_id` (sequential bigint) and submits requests with `organizationId = `. Each request spends the victim's credit and can deny their subsequent AI work until the account is funded again. Worse, the attacker's free-tier user enjoys the victim's credit for as long as it lasts. Mass automation makes this an asymmetric DoS-by-billing attack. **Why it's specifically risky here.** AI route handlers and server actions sit on internal/private surfaces, but they are still HTTP endpoints reachable by any authenticated user. Org membership on product data reads does not by itself authorize AI spending. GG obtains fresh shared-credit admission for migrated execution; retained native operations preserve source receipts. Explicit producer membership verification is still required. Without a structural producer-side rule, every new AI endpoint is a fresh chance to forget the membership check. **How the code prevents it.** 1. **Verified organization producers** — [editor/lib/auth/organization.ts](editor/lib/auth/organization.ts) exports `requireOrganizationId({ user_id, request, routeParams, inputOrgId })`. It resolves from: route param slug → request header `X-Grida-Organization-Id` → explicit input. Every resolved id is verified via `assertOrgMember(user_id, org_id)` before return. No "current org" is read from session blob / cookie. GG execution instead consumes the `org` claim from the exclusively verified GRIDA-SEC-006 bearer. That grant was minted after authenticated membership verification; the documented token lifetime bounds this authority. Neither the GG 3D binding nor its execution seam reads an org from input, cookies, account headers or a provider upload reference. 2. **Runtime contract in the seam** — [editor/lib/ai/server.ts](editor/lib/ai/server.ts) `withTransaction` and the trusted GG adapter validate organization identity; native calls throw `MissingOrgIdError` if `organizationId` is missing, non-integer, or non-positive. This is **unconditional** on the billed path: the former `NEXT_PUBLIC_GRIDA_LOCALDEV_SUPERUSER` exception (synthetic `organizationId:0`, gate/ingest/auth skip) has been **removed** — no code path skips this check while billing. The only intentional bypass is the BYOK carve-out below, and it does not bill. 3. **One billing seam, explicit provider-import owners** — [editor/lib/ai/server.ts](editor/lib/ai/server.ts) owns the selected Grida execution entry point; GG owns migrated provider dispatch/metering and Platform owns shared financial billing. Retained native operations use Grida source admission/receipt integration; value imports of `replicate`, `openai`, `@ai-sdk/*`, `@anthropic-ai/sdk` and the portable `@grida/ai` execution SDK are restricted to the reviewed seam allowlist. The exact `@grida/ai/catalogue` and `@grida/ai/discovery` metadata entries are allowed independently: neither executes inference or acquires credentials. Enforced by oxlint `no-restricted-imports` ([editor/.oxlintrc.jsonc](editor/.oxlintrc.jsonc)) and the CI audit script ([editor/scripts/audit-ai-seam.ts](editor/scripts/audit-ai-seam.ts)). A new file that bypasses the seam fails at lint or CI. The [trusted GG adapter](editor/lib/ai/gateway-product.ts) uses a distinct server workload secret, canonical organization and feature. Its receiver checks current credential authority and organization existence; Grida must verify user membership before sending the assertion. Browser cookies and personal API keys cannot substitute for this credential. All generation/metering stays in GG; there is no direct-provider fallback or duplicate native receipt. 4. **3D upload ownership and result custody** — the named [3D adapter](editor/lib/ai/gg-three-d.ts) retains only free Tripo presign preparation with server-only `GG_TRIPO_API_KEY`. Its key must belong to the same provider account as GG. Authenticated caller/org-bound signed upload tickets are verified before forwarding an internal typed file reference; ordinary users cannot claim a provider file token or arbitrary input URL. GG owns paid model generation, checking, rigging, durable observation and settlement. Grida validates/downloads product output using its [pinned public HTTPS transport](editor/lib/ai/gg-three-d-http.ts), without provider credentials, redirects or private DNS destinations. An asset failure does not regenerate, refund known cost or issue a second native receipt. Already accepted pre-transition work keeps its original source recovery obligation; [KI-BILL-005](docs/wg/platform/billing/known-issues.md#ki-bill-005--tripo-jobs-without-an-observed-terminal-receipt-need-reconciliation) preserves that historical distinction. **BYOK carve-out (intentional).** When a contributor sets a `BYOK_*` key ([editor/lib/ai/models.ts](editor/lib/ai/models.ts) — `BYOK_OPENROUTER_API_KEY`, `BYOK_VERCEL_AI_GATEWAY_API_KEY`), `grida`/`model` return a **bare** provider so the **AI-SDK text/chat path** bypasses the billing seam: no Platform admission or charged usage delivery, **and** the `MissingOrgIdError` runtime contract above does not fire (a bare provider has no middleware). The contributor's own provider key is charged directly — there is no Grida balance, hence no victim to drain, so the billing trust boundary is moot for that path. **Scope — AI-SDK path only.** BYOK only swaps the AI-SDK provider; Replicate- backed actions (`runPrediction`/`withTransaction` — audio, image) are **not** bypassed and still gate + ingest under BYOK. Accordingly the `withAiAuth` `balanceCents:0` short-circuit is opt-gated (`byokBypass`, default `false`): only AI-SDK actions set it, so billed actions still read the real balance and cannot silently drain credit while reporting `0`. **BYOK bypasses billing only — never auth.** `requireOrganizationId` and route/action auth always run, so a logged-in user with no resolvable org is still rejected. Gated solely by server-only, non-`NEXT_PUBLIC_` env vars never set in the hosted product (same trust model as other server-only credentials). Fail-closed: `byok` is `null` unless a key env var is a non-empty string, so any ambiguity falls back to the billed path. **Residual risk:** `byok` is resolved once at module load with no per-request guard — an accidental `BYOK_*` on a hosted/preview deploy would make every org bypass billing and the org-id sanity gate (auth still holds). Acceptable only because it is a contributor/self-host switch under the existing server-env trust model. **Funded provider authority.** Migrated generation uses the server-only GG product workload configuration. The retained Library Vercel embedding provider reads only `GG_VERCEL_AI_GATEWAY_API_KEY` for an explicit API key. An absent or blank value retains the SDK's per-request platform OIDC resolution; an explicit empty SDK setting prevents its ambient `AI_GATEWAY_API_KEY` lookup. Replicate predictions require a nonblank `GG_REPLICATE_API_TOKEN` at execution, with no legacy token fallback. Contributor overrides never supply these funded clients. Library query embeddings still use the shared provider without user billing (or the contributor override locally), and OpenAI model listing keeps its separate `OPENAI_API_KEY`. Native CLI/Desktop credential names and stored provider IDs are independent of this server configuration. **Files bound by this id.** Run `grep -rn GRIDA-SEC-003 .` to enumerate. Today: - [editor/lib/auth/organization.ts](editor/lib/auth/organization.ts) — `requireOrganizationId`. - [editor/lib/ai/server.ts](editor/lib/ai/server.ts) — single seam entry; unconditional runtime gate; BYOK layer switch. - [editor/lib/ai/models.ts](editor/lib/ai/models.ts) — contributor BYOK and explicit funded Vercel AI Gateway/OIDC authority. - [Provider credential tests](editor/lib/ai/__tests__/models.test.ts) and [Replicate credential tests](editor/lib/ai/__tests__/replicate-credentials.test.ts) — funding-role separation, per-request OIDC, missing credentials and preserved billing. - [GG Tripo execution](editor/lib/ai/gg-three-d.ts) and [billing contract tests](editor/lib/ai/__tests__/gg-three-d.test.ts) — verified org input, unconditional gate, infrastructure-key-only execution and actual receipts. - [GG Tripo egress](editor/lib/ai/gg-three-d-http.ts) and [transport tests](editor/lib/ai/__tests__/gg-three-d-http.test.ts) — fixed API/asset authority, public DNS pinning, verified TLS and no credential-bearing redirects. - [editor/.oxlintrc.jsonc](editor/.oxlintrc.jsonc) — import lint rule. - [editor/scripts/audit-ai-seam.ts](editor/scripts/audit-ai-seam.ts) — CI audit. **What does NOT belong here.** Reading `organizationId` directly off a request body in any AI-adjacent code. Even if you think you "trust" the body — Next.js server-action hashes ship in the client bundle and become public the moment they're shipped. Always go through `requireOrganizationId` or the exclusively verified, membership-derived GG claims described above. An upload ticket is never organization authority. --- ### `GRIDA-SEC-004` — Desktop daemon trust boundary **What it protects.** Grida Desktop supervises a native Rust chat host and a retained daemon sidecar. The native host owns new chat sessions and agent execution. The Node sidecar retains local file paths, workspaces, media, provider settings and shared credential adapters. Native-provider OAuth has its separate credential boundary (GRIDA-SEC-008). The TypeScript chat composition has been removed. Electron main listens on an ephemeral `127.0.0.1` port and transfers only accepted connected sockets to the socketless sidecar, whose authenticated daemon protocol is the canonical local capability surface for the renderer. If anything other than the legitimate Electron renderer reaches it — another browser tab on grida.co, a local malware process, a same-origin XSS payload — that party can exfiltrate secrets, read/write the user's files, and bill AI calls. The boundary is the rule that **only requests originating from the desktop's privileged renderer at a `/desktop/*` path, signed with the per-spawn Basic Auth token, may reach the daemon, and only the main-owned provider transport may carry the daemon's provider HTTP outside its sandbox. Electron main owns the exact loopback listener; ServicesSidecar receives no listener, and the macOS/Linux sandbox grants it no generic bind/connect authority. Windows does not yet satisfy that containment clause; its current nonconformance is recorded below.** **Package shape.** The perimeter and the host capability routes (files, recents, workspaces, the secrets store) are owned by [`packages/grida-daemon`](packages/grida-daemon) (`@grida/daemon` — `DaemonServer`, `http/auth.ts`, `http/origin.ts`, `http/server.ts`). The media/provider HTTP adapters are mounted behind that perimeter through the typed `DaemonTenant` seam and ship in [`packages/grida-ai-host`](packages/grida-ai-host). Its separate `@grida/ai-host/media-server` entry starts the media routes, BYOK configuration and scoped GG custody; the package contains no chat runtime, chat SQLite state, skills or ACP. On macOS/Linux, provider access lazily opens only the shared credential owner's SQLite exclusion lock (GRIDA-SEC-014). Windows retains the host-local credential backend described in that entry. Chat enforcement belongs to the Rust host and native process contracts. Desktop selects the composition before importing the server. A media-only launch does not construct a command executor or enable native ChatGPT OAuth. It retains the same main-owned listener, authenticated perimeter, provider transport and media root. The choice is explicit host configuration, never an automatic fallback after agent initialization fails. No second daemon or credential store is created: the daemon-owned OAuth `AuthStore` remains separate from the shared provider TOML owner, with one memory-only GG session and one catalogue per composition. The first provider access retires legacy API entries through GRIDA-SEC-014; subsequent reads never use that retired source. The [supervisor](desktop/src/main/services-sidecar-supervisor.ts) loads its native sandbox before spawning the child. On macOS and Linux an unavailable sandbox refuses the launch; Windows keeps its explicitly unconfined non-agent services. Shared image, video, audio and 3D operations and provider HTTP belong to [`@grida/ai`](packages/grida-ai/README.md). The tenant supplies narrow key/token readers and the same host-authorized transport; host adapters retain request admission, workspace reads, media persistence, and optional chat lifecycle. The SDK does not mount a route or create a daemon. Extracting an operation grants no additional network or filesystem authority. **Vulnerable scenario (prevented).** A stored XSS lands on a marketing page or blog post served from `grida.co`. The user has the desktop app open. Without the boundary, the XSS calls `fetch('http://127.0.0.1:/secrets/get?key=byok.openrouter')` and ships the key to an attacker-controlled host; or `fetch('http://127.0.0.1:/files/read?docId=…')` and exfiltrates the user's design files. A parallel local-machine attack: an unprivileged malware process scans `127.0.0.1:49152-65535`, finds the daemon, and hits its endpoints (a non-browser client doesn't honor `Origin` checks). Both attacks defeat the "secrets in keychain" intuition because the local network is a trust shortcut. **Why it's specifically risky here.** The desktop V1 renderer URL-loads `https://grida.co/desktop/...` (a literal path, distinct from the universal-routing `/_/...` system). That puts the privileged preload bridge on the same Chromium origin as every other grida.co page. Without per-path preload scoping and per-request agent-server auth, "XSS on grida.co" becomes "RCE-equivalent in the desktop app" (the same failure class as the Discord 2021 Sketchfab embed → context-isolation-disabled → RCE chain). Industry precedent (Figma's `FigmaAgent` allowlisting only figma.com + Local Network Access permission) confirms the threat is real and the mitigation shape is standard. **How the code prevents it.** Composed of mutually reinforcing controls; any single control is insufficient. 1. **Path-scoped preload** — the bridge in [desktop/src/preload.ts](desktop/src/preload.ts) installs `window.grida` only when `location.pathname` is `/desktop` or starts with `/desktop/` at preload-run time. The preload fails closed when the current document is not a desktop route. Electron preload is the sole bridge installer. Desktop renderer code reads the bridge through its typed client. A fresh document load that doesn't match the prefix gets no bridge, so XSS on `/blog/foo` cannot see it. SPA navigation within an already-loaded document is constrained by preload's history guard and the `will-navigate` / `did-navigate-in-page` allowlist in `desktop/src/window.ts` — `contextBridge.exposeInMainWorld` has no revocation API, so the navigation guards defend the post-mount surface. Path eligibility is not capability admission by itself: `desktop/src/main/desktop-entry-window.ts` resolves an exact sender window to its current native role only while that role is stable, and `desktop/src/main/ipc-admission.ts` applies a closed role + pathname + channel policy inside the common guarded-IPC wrapper. Main rejects auth and onboarding paths even before a navigation observer runs; sign-in receives only browser launch + read-only title-bar state. Onboarding receives only ChatGPT controls, completion, and two purpose-scoped main-owned workspace operations (read the default or choose/register one folder). It never receives the daemon connection tuple or a generic filesystem dialog. A transitioning, stale, foreign, or post-sign-out auxiliary renderer resolves to no role and receives no IPC capability. 2. **CSP-strict `/desktop/*` routes** — [`editor/proxy.ts`](editor/proxy.ts) sets a per-request nonce-based CSP on every `/desktop/*` response, following the canonical Next.js pattern (nonce + `'strict-dynamic'`). Concretely: `default-src 'self'; script-src 'self' 'nonce-' 'strict-dynamic' 'wasm-unsafe-eval'; connect-src 'self' http://127.0.0.1:* http://localhost:*`. The nonce is generated in the proxy, exposed to SSR via the `x-nonce` request header, and Next.js attaches it to its own framework scripts automatically. No third-party analytics, Sentry, or marketing scripts run on these routes — eliminates the "Sentry input masking is fragile" exfil for BYOK keys. We chose nonce + `'strict-dynamic'` over `'unsafe-inline'` because `/desktop/*` was already dynamic-rendered (bridge gate is client-only) — the dynamic-rendering cost most Next.js teams pay for nonce CSP is a cost we already pay, so this control stays load-bearing at zero additional maintenance. **For maintainers:** if you add inline scripts to a `/desktop/*` layout or page, they must carry the nonce. Read it via `(await headers()).get("x-nonce")` and pass it to whatever you're rendering (e.g. `` for `next-themes`, `