
# Web security for the console and apps

New apps live at `<name>.ac0.app`, a different site from the console at `agent.cloud`, so no console cookie reaches an app. The edge also refuses cross-origin writes with 403 `cross_origin`, and the console uses CSRF tokens, a strict CSP and `__Host-` cookies.

Success: your own pages' forms and fetches work, a webhook to a listed `cross_origin` path reaches your handler, and another origin's post gets the 403.

## Steps

```text
Stripe needs to call our webhook at /api/webhooks/stripe. Let that one path through
Agent Cloud's cross-site protection and verify Stripe's signature on it.
```

The agent lists the path in `cross_origin`, declares the signing secret, and gives you a console link to set its value. List only paths that take cross-origin writes:

```toml
[service.web]
cross_origin = ["/api/webhooks/*", "/api/public/signup"]

[secrets]
required = ["PAYMENTS_WEBHOOK_SECRET"]
```

On each listed path, verify the caller with something only it has. A generic HMAC check (follow your provider's header, encoding and timestamp rules, or use its SDK):

```ts
import { createHmac, timingSafeEqual } from 'node:crypto';

app.post('/api/webhooks/payments', async (c) => {
  const raw = await c.req.text(); // the signed bytes: verify before parsing
  const given = Buffer.from(c.req.header('x-signature') ?? '');  // your provider's header
  const want = Buffer.from(createHmac('sha256', process.env.PAYMENTS_WEBHOOK_SECRET!).update(raw).digest('hex'));
  if (given.length !== want.length || !timingSafeEqual(given, want)) return c.json({ error: 'bad signature' }, 401);
  const event = JSON.parse(raw);
  // Providers retry: make the handler safe to run twice, keyed on the event's id.
  return c.json({ received: true });
});
```

```bash
agc secret set PAYMENTS_WEBHOOK_SECRET
agc check
agc ship
```

## How it works

### Console sessions and cookies

A person signs in through Stytch with PKCE. The `__Host-` prefix makes browsers refuse a `Domain` attribute, so a page on another host can't plant or replace these cookies, and none of them reaches an app:

| Cookie | Holds | Lifetime |
|---|---|---|
| `__Host-agc_signin` | The PKCE verifier and return path, signed | 30 minutes |
| `__Host-agc_stytch_session` | Stytch's opaque session token; `HttpOnly`, `Secure`, `SameSite=Lax`, `Path=/` | 14 days, or the organization's length for company sign-in |
| `__Host-agc_stytch_jwt` | A JWT checked locally; same flags | Five minutes |

Signing out revokes the session at Stytch and records it in `signed_out`, so a still-fresh JWT copy is refused. `safeNext()` only accepts same-site paths for `?next=`.

### CSRF

Every `POST` or `PUT` under `/console/`, `/a/`, `/claim/` and to `/auth/signout` must carry `HMAC-SHA256(secret, "csrf:" + session id)`, as the form field `csrf` or the header `x-csrf-token`, compared in constant time. A stale token gets `console.stale` (JSON) or a "Please try again" page, both 400.

### Approval links

An approval page `/a/apr_…` needs the 128-bit id (valid 24 hours, decided once), a signed-in person and `canManage()`: the app's owner, or an owner of its organization while a member.

### Edge sign-in

For apps with `[auth] provider = "edge"`, the gate strips client-sent `x-agc-user-email` and `x-agc-user-name` and sets them from its own session, `__Host-agc_edge` (HttpOnly, Secure, SameSite=Lax), sealed for one app. The one-time sign-in code lasts 60 seconds, works for one app, and burns on use. On Agent Cloud's own cluster the gate rechecks the person with control at most once a minute, failing closed after 10 minutes without an answer.

**Login CSRF.** Before sign-in, the gate sets a `__Host-agc_edge_state` nonce cookie and passes the nonce as `state`. The code is bound to it, and the callback redeems it only when the browser's cookie matches, in constant time, so a code someone else sends as a link signs nobody in.

### Request size limits

Control checks a declared `Content-Length` against the route's cap ([Limits and quotas](/docs/reference/limits-and-quotas.md)) before reading a byte, reads a chunked body only up to 64 KiB, and closes the connection on a refusal (`request.too_large`). `POST /email/v1/events` takes at most 256 KiB; asset chunks and preview webhooks have their own caps.

### Uploaded app icons

`agc icon use icon.svg` never stores the uploaded bytes. Control parses the SVG strictly (no DOCTYPE), keeps an allowlist of shapes, gradients, clip paths, masks and text, and writes a new SVG from that; scripts, styles, links, event attributes and any URL but `#id` are dropped and listed in `dropped`. An unsafe file gets `icon.unsafe_svg`; one past 2,000 elements, 32 levels of nesting, 64 KB in one attribute or 2 s to render gets `icon.too_complex`. Icon files are served with `X-Content-Type-Options: nosniff`, and SVGs with `Content-Security-Policy: default-src 'none'; sandbox`.

## Same-site neighbours and webhooks

The edge's origin check (below) stops a page on another app, such as `other-app.ac0.app`, from sending writes that carry your app's cookies. Agent Cloud never trusts an Origin, Referer or redirect target just because it ends in `.agent.cloud` or `.ac0.app`.

**The origin check.** On Agent Cloud's own cluster and on platform targets, each app's route sends `POST`, `PUT`, `PATCH` and `DELETE` through forwardAuth to the `agc-edge` gate (two replicas); reads skip it. The gate refuses a request whose `Origin` isn't `https://<the request's host>` (including `Origin: null`), or, with no `Origin`, whose `Sec-Fetch-Site` is `same-site` or `cross-site`. A request with neither header passes, so servers, agents and `curl` still work. On a mirror, `agc up`'s proxy applies the same rule and exceptions. When the console frames a mirror, the proxy keeps the app's own `frame-ancestors` and adds the console's origin.

**Exceptions.** Paths in `cross_origin` skip the check, leaving the handler as their only guard. A trailing `/*` is a prefix including its slash: `/api/webhooks/*` matches `/api/webhooks/` and everything under it, never `/api/webhooksx`; anything else matches exactly. Matching is on Traefik's normalized path, so a request reaching an exception only through encoded characters (`%2e%2e`, `%2f`) gets the check.

**Reviews.** The release and [Well-Architected](/docs/ship/well-architected-review.md) reviews list every exception as `cross-origin-exception` (info). They flag `cross-origin-writes` for an app with cookie sessions and no origin check of its own: high or medium where nothing in front checks, info where the edge does. The starters ship an app-level check.

**Your side.** Your handler guards every listed path: keep the list short, and authenticate each one with a signature or token, never a cookie.

## Reference

| Key | Takes |
|---|---|
| `[service.web] cross_origin` | At most 20 paths, each starting with `/` and at most 200 characters after it; a trailing `/*` is a prefix. No `.` or `..` segments, no `//`, no encoded characters |

| Header | Where | Value |
|---|---|---|
| `Strict-Transport-Security` | Every response from control | `max-age=31536000; includeSubDomains` |
| `Content-Security-Policy` | `/console`, `/a`, `/r`, `/auth`, `/claim`, `/comms` | `default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; media-src 'self'; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'` |
| `X-Content-Type-Options` | Same paths | `nosniff` |
| `Referrer-Policy` | Same paths | `same-origin` unless a route sets its own |

The test sign-in page under `/auth/test/` widens `form-action` to `http://localhost:*` and `http://127.0.0.1:*`, so a mirror's app on localhost can receive the result.

## Errors

Every code, its exit and fix: [Error code catalog](/docs/reference/error-code-catalog.md). The edge's 403 `cross_origin` answers an unsafe request whose `Origin` or `Sec-Fetch-Site` says another origin sent it. Make the write same-origin, or list the path and authenticate it there.

```bash
curl -i -X POST https://camp-bookings.ac0.app/api/bookings \
  -H 'Origin: https://other-app.ac0.app' -H 'content-type: application/json' -d '{}'
```

```text
HTTP/2 403
content-type: application/json

{"error":{"code":"cross_origin","message":"Changes come from this app’s own pages."}}
```

## Agent notes

- Keep an app's own Origin check as a second wall. Custom domains get the edge's check wherever the app's address does; a customer target runs it only where the target has edge sign-in.
- A listed path is open to every unsafe method, and `/*` exceptions are wide; prefer exact paths.
- A 403 `cross_origin` from your own page usually means it calls an API on another host. Use the same host.
- Smoke steps send no `Origin` and already pass; don't list a path to fix one.

## Related

- [The edge gate](/docs/build/the-edge-gate.md)
- [Agent Cloud sign-in](/docs/build/choosing-a-sign-in-shape.md#agent-cloud-sign-in-shape-2)
- [Console sessions](/docs/owners/company-sign-in-and-scim.md#console-sessions)
- [Secrets](/docs/build/secrets.md)
- [Well-Architected review](/docs/ship/well-architected-review.md)
- [Approvals](/docs/concepts/approvals.md)

<!-- feedback:start -->
---
Wrong, outdated or unclear? Run `agc feedback docs "security/web-security-for-the-console-and-apps: <what is wrong>" --body <file>` with the sentence quoted in the file. No code or app data is sent.
<!-- feedback:end -->
