
# Platform APIs: sign-in and email

An app calls two Agent Cloud APIs with credentials from its environment. The sign-in broker (`AGC_AUTH_URL`, `AGC_AUTH_TOKEN`) signs people in without the app holding a sign-in secret. The email API (`AGC_EMAIL_URL`, `AGC_EMAIL_TOKEN`) sends plain-text mail at most once per key.

## Sign-in broker API

An app with `[auth] provider = "agent.cloud"` (the default) never holds a sign-in secret. It sends the browser to Agent Cloud, gets a one-time code back on its callback, and trades the code server-side for the person. Two environment variables carry everything: `AGC_AUTH_URL` (the broker for this app and environment) and `AGC_AUTH_TOKEN` (`agca_…`, this app's credential for it).

```bash
curl -s -X POST "$AGC_AUTH_URL/token" -H "Authorization: Bearer $AGC_AUTH_TOKEN" -H 'content-type: application/json' -d '{"code":"<code from the callback>"}'
```

```json
{"user":{"id":"3f0c9a52-1d2e-4b7a-9e61-0a8d5c7e2b14","email":"pat@example.test","name":"Pat","method":"google","role":null}}
```

### The flow

```mermaid
sequenceDiagram
  participant B as Browser
  participant A as Your app
  participant X as Agent Cloud broker
  B->>A: GET /auth/sign-in
  A->>B: 302 to AGC_AUTH_URL/authorize?state=S
  B->>X: authorize (Google, email link, or the organization's provider)
  X->>B: 302 to https://<app host>/auth/callback?code=C&state=S
  B->>A: GET /auth/callback?code=C&state=S
  A->>A: check S matches what this browser was given
  A->>X: POST AGC_AUTH_URL/token {code: C} + AGC_AUTH_TOKEN
  X->>A: {user: {id, email, name, method, role}}
```

The app starts the sign-in, the broker proves who the person is, and the app trades the one-time code server-side.

### `GET {AGC_AUTH_URL}/authorize`

A browser navigation, not an API call.

| Query | Required | Rules |
|---|---|---|
| `state` | yes | 8 to 200 of `A-Z a-z 0-9 . _ ~ -`. Without it the broker shows an error page and won't start. |
| `host` | no | The host the browser should come back to: one of the app's own addresses (its Agent Cloud address or a custom domain). Any other host is refused. Omitted: the app's Agent Cloud address. |

The broker offers the app's configured methods (Google, email links, and a password form when an owner turns Password on; see [Password sign-in](/docs/owners/password-sign-in-for-an-app.md)), or goes straight to the organization's identity provider when the app's audience is the organization, a group or named people. It then redirects to `https://<host><callback>?code=…&state=…`; the callback path is the app's setting, `/auth/callback` unless changed.

### `POST {AGC_AUTH_URL}/token`

| | |
|---|---|
| Header | `Authorization: Bearer $AGC_AUTH_TOKEN` |
| Body | `{"code": "<code>"}` as JSON, or a form with `code` |
| 200 | `{"user": {"id", "email", "name", "method", "role"}}`; `method` is `google`, `email`, `password` or `sso`; an `sso` user also has `groups` |

A code works once, for 60 seconds, for this app and this environment only.

`role` is the person's membership of the app's organization, read at each answer: `"owner"` for an owner, `"member"` for any other member, `null` for everyone else. Use it to make the organization's owners the app's owners; treat `null` as someone outside the organization, never an owner. Test identities carry no role.

### `GET {AGC_AUTH_URL}/users/:id`

Same header. Answers `{"user": {…}}`, `role` included, so a promotion or removal shows at your next recheck, for someone who may still sign in, or 404 `auth.no_user` when they've been blocked, left the app's audience, were deactivated by SCIM or removed from the organization since they last signed in. End their session on a 404.

### Sign-in buttons on your own pages

To show your own "Continue with Google" button or email field instead of Agent Cloud's page, have your server call one of these, with the same `Authorization: Bearer $AGC_AUTH_TOKEN`, then send the browser to the `url` it answers. The person comes back to your callback with `?code=…&state=…` exactly as from `/authorize`, and you trade the code at `/token`; user ids stay the same whichever way they signed in.

| Route | Body (JSON) | 200 |
|---|---|---|
| `POST {AGC_AUTH_URL}/stytch/google` | `{"state": "…", "host": "…"}` (`host` optional, as on `/authorize`) | `{"url": "…"}` |
| `POST {AGC_AUTH_URL}/stytch/email` | `{"state": "…", "email": "…", "host": "…"}` | `{"sent": true, "url": "…"}`: the link is emailed, and `url` returns the browser to your callback with `?state=…&sent=email` and no code, so you can say "check your email" |

`url` is a one-off pass through Agent Cloud that lasts ten minutes. Only the methods the app offers start, under the same email-link limits as the page (3 an hour per address and app, 200 per app). An app whose audience signs in through its organization's provider is refused with `auth.sso_required`; send those people to `/authorize`. In test mode, Google answers the test sign-in page and email captures the link in the outbox (`agc outbox`).

| Code | HTTP | Cause |
|---|---|---|
| `auth.bad_request` | 400 | The body isn't `{state}` or `{state, email}`. |
| `auth.app_host_invalid` | 400 | `host` isn't the app's address or one of its active domains. |
| `auth.email_invalid` | 400 | `email` isn't an email address. |
| `auth.sso_required` | 400 | The audience signs in through the organization's provider. |
| `auth.method_not_offered` | 404 | The app doesn't offer that method. |
| `auth.email_rate_limited` | 429 | Too many sign-in emails; offer another way or wait an hour. |
| `auth.email_send_failed` | 502 | The email couldn't be sent; try again in a moment. |

### Test mode: mirrors and rehearsals

On a mirror and in a rehearsal, `AGC_AUTH_URL` is `https://agent.cloud/auth/test/<ticket>`. The routes and shapes are the same, with these differences:

| Route | Test mode behavior |
|---|---|
| `GET …/authorize?state=S` | A page where you choose who to be: any email address, or a user id (a uuid) from the mirror's data. Adding `&as=<email or uuid>` skips the page. The browser returns to the mirror's `127.0.0.1` port. |
| `POST …/token` | `{"user":{"id":"…","email":"pat@example.test","name":null,"method":"test","test":true}}`. An email always maps to the same id for that app; a uuid is used as is, so masked mirror data keeps working. |
| `GET …/users/:id` | Any uuid answers a test user. |
| `GET …/codes/:code` | `{"traded": true}` or `{"traded": false}`: whether the app traded that code. Rehearsals use it to prove your callback checks `state` before trading. |

Test identities are never stored as users. A production token doesn't work on test routes, and a mirror's token doesn't work on production's, so a mirror's ids can't be turned back into real people.

## Email API

The API sends plain-text email without an app-owned provider account. One request sends one message to one address, and Agent Cloud sends each `(app, environment, key)` at most once, so a retried job can't email someone twice. A sent message answers `{"status": "sent"}`.

```bash
curl -s -X POST "$AGC_EMAIL_URL" \
  -H "Authorization: Bearer $AGC_EMAIL_TOKEN" -H 'content-type: application/json' \
  -d '{"to":"pat@example.test","subject":"Your booking is confirmed","text":"See you on Monday.","key":"booking-42/confirmation"}'
```

```json
{"id":"…","status":"captured"}
```

`pat@example.test` is at a reserved test domain, so even production captures it.

### Request

`POST https://agent.cloud/email/v1/messages` (the value of `AGC_EMAIL_URL`).

| Part | Rules |
|---|---|
| `Authorization` | `Bearer agce_…`: `AGC_EMAIL_TOKEN` from the environment. A token names one app and one environment; a mirror's dies with the mirror, a rehearsal's ends when the rehearsal does. |
| `to` | One email address. Trimmed and lowercased. Send one request per recipient. |
| `subject` | Required, one line, 1 to 300 characters, no control characters. |
| `text` | Required, plain text, at most 50,000 characters. |
| `key` | Required, 1 to 200 of `A-Z a-z 0-9 . _ : / -`. Names the message for good. |
| `reply_to` | Optional. One email address. |
| `headers` | Optional. Only `List-Unsubscribe` (one or more `<https://…>` or `<mailto:…>` addresses in angle brackets, comma-separated, at most 2,000 characters, one line) and `List-Unsubscribe-Post` (exactly `List-Unsubscribe=One-Click`, and only with an https address in `List-Unsubscribe`). Agent Cloud sets every other header. |
| `attachments` | Optional. A list of `{filename, content, content_type}`: `filename` one line of at most 255 characters with no slashes, `content` the file in standard base64, `content_type` optional (like `application/pdf`). At most 10 files and 10 MB in all, counted before base64. Executables, scripts and installers (`.exe`, `.bat`, `.cmd`, `.com`, `.js`, `.vbs`, `.ps1`, `.scr`, `.msi`, `.jar` and the like, judged by the last extension) are refused on a mirror as in production. |

The sender is always shown as `agent.cloud`, whatever the app.

### Responses

| `status` | HTTP | Meaning |
|---|---|---|
| `sent` | 200 | Handed to the mail provider. |
| `captured` | 200 | Recorded, not sent: a mirror or rehearsal, an address at a reserved domain, an app nobody has claimed yet, or a deployment with no mail provider. |
| `failed` | 200 | The provider refused it. A retry with the same `key` tries again. |
| `duplicate` | 200 | A message with this `key` was already accepted. Nothing is sent. The body adds `first: {status, at}`, the first attempt's outcome. |

Retrying a key whose first send `failed`, was `held`, or has been stuck sending for over 60 seconds takes it back and sends again; anything else is a `duplicate`. A retry must carry the same `reply_to`, `headers` and `attachments` as the key's first send; a changed one is `email.key_reused` (409) and sends nothing, so a changed message needs a new key. `agc outbox` shows a captured message's Reply-To, unsubscribe headers and each attachment's name and size, never its bytes.

### Where mail goes

| Environment | Outcome |
|---|---|
| Production | Sent only with a configured mail provider; otherwise captured. Undeliverable addresses are captured; holds and daily limits can refuse a real send. |
| Rehearsal | Captured under the rehearsal. During its chaos run, the first send of each message answers 503 `email.unavailable` (the message is kept), to prove your retry reuses the key. |
| Mirror | Captured in the mirror's outbox: `agc outbox`. |

Undeliverable means a domain with no dot, or one ending in `.test`, `.example`, `.invalid`, `.localhost` or `.local`, or `example.com`, `example.net`, `example.org`.

## Errors

### Sign-in errors

<!-- generated: signin-errors -->
| Code | HTTP | Message | Fix | Line |
|---|---|---|---|---|
| `auth.bad_code` | 400 | That code is unknown, already used, expired, or from another environment. | Send the person to sign in again: a code works once, within a minute. | 576 |
| `auth.bad_request` | 400 | Send {state}: a fresh value, kept in this browser’s cookie. / Send {state, email}: a fresh value, kept in this browser’s cookie, and the person’s address. | Send {state}, as on /authorize. | 693, 705, 788, 797 |
| `auth.blocked` | 403 | This person can’t sign in to the app any more. | Don’t start a session for them. | 582 |
| `auth.email_invalid` | 400 | That doesn’t look like an email address. | Ask the person for their address again. | 799 |
| `auth.method_not_offered` | 404 | This app doesn’t offer ‹Google\|email› sign-in. | Offer the methods the app has. | 782 |
| `auth.no_code` | 404 | No such code. | Mint one with a test sign-in. | 821 |
| `auth.no_user` | 404 | No one with that id can sign in to this app. / No one with that identity can sign in to this app. / That isn’t a user id. | End their session. | 600, 617, 812 |
| `auth.token` | 401 | That isn’t this app’s sign-in token. | Call with AGC_AUTH_TOKEN from the app’s environment. | 549 |
<!-- /generated: signin-errors -->

Browser-facing failures on `/authorize` and the callback (expired, cancelled, not in the audience, too many email links) are pages, not JSON.

### Email errors

<!-- generated: email-errors -->
| Code | HTTP | Message | Fix | Line |
|---|---|---|---|---|
| `email.auth` | 401 | Not an Agent Cloud email token. / ‹dead.message› / That token’s app is gone. / That rehearsal is over. | Send with AGC_EMAIL_TOKEN from the environment. | 253, 255, 258, 261, 370, 372, 373 |
| `email.bad_key` | 400 | `key` is required: letters, digits and . _ : / -, at most 200. | Use a key that names the message for good, like booking-42/confirmation. A retry must send the same key. | 267 |
| `email.bad_subject` | 400 | `subject` is required: one line, at most 300 characters. | Send a short subject. | 269 |
| `email.bad_text` | 400 | `text` is required, at most 50,000 characters. | Send the plain-text body. | 270 |
| `email.bad_to` | 400 | `to` must be one email address. | Send one message per recipient. | 265 |
| `email.events_auth` | 401 | Not an event signed by the mail provider. | Check that RESEND_WEBHOOK_SECRET is the signing secret of this webhook in Resend. | 351 |
| `email.held` | 403 | This app’s production email is held: ‹hold.reason›. | Ask an owner of the app’s organization: they see why on the app’s Email page and can resume it. Then retry with the same key. | 322 |
| `email.key_reused` | 409 | The key ‹b.key› was first sent with a different Reply-To, headers or attachments, so this isn’t a retry of it. Nothing was sent. | A retry sends the same message under the same key. A changed message needs a new key, like booking-42/confirmation-2. | 305 |
| `email.rate` | 429 | Too many messages this hour. / Too many messages today. / This app’s email limit for today is reached. / Agent Cloud’s email limit for today is reached. | Send fewer; ask the owner if this is expected. | 301, 302, 332 |
| `email.unavailable` | 503 | The mail service didn’t answer (Agent Cloud chaos run). | Retry with the same key. | 316 |
<!-- /generated: email-errors -->

The checks on `reply_to`, `headers` and `attachments` answer these, before anything is saved or sent:

| Code | HTTP | Cause | Fix |
|---|---|---|---|
| `email.bad_reply_to` | 400 | `reply_to` isn't one email address. | Send one address, or leave it out. |
| `email.bad_headers` | 400 | A header other than the two unsubscribe ones, a value that isn't one line, a malformed `List-Unsubscribe`, or `List-Unsubscribe-Post` without an https unsubscribe address. | Send only those two, as the message says. |
| `email.bad_attachments` | 400 | `attachments` isn't a list of `{filename, content, content_type}` with a valid name and base64 content. | Send each file as `{"filename": "report.pdf", "content": "<base64>"}`. |
| `email.attachment_type` | 400 | A file is an executable, script or installer, named in the message. | Store the file and email a link to it. |
| `email.attachments_too_large` | 413 | More than 10 files, or more than 10 MB of files. | Attach fewer or smaller files, or store the file and email a link. |

Every error body is `{"error": {"code", "message", "fix"}}`:

```json
{"error":{"code":"email.bad_key","message":"`key` is required: letters, digits and . _ : / -, at most 200.","fix":"Use a key that names the message for good, like booking-42/confirmation. A retry must send the same key."}}
```

`email.held` (403) means an owner must resume the app's production mail on its Email page; retry with the same key afterwards. A `429 email.rate` for the daily cap holds the message: the same key sends once the count allows.

## Limits

### Sign-in limits

| Limit | Value |
|---|---|
| Code lifetime | 60 s, single use |
| Pending sign-in in the browser | 30 minutes (a `__Host-` cookie set by the broker) |
| Email links an hour | 3 per address and app, 20 per network address, 200 per app |

### Email limits

| Limit | Value |
|---|---|
| Messages an hour, one app in production | 300 |
| Messages an hour, one mirror or rehearsal | 3,000 |
| Messages a day, one production token | 1,000 |
| Real sends a day, one app | 100 |
| Real sends a day, all apps together | 300 |

The hourly limit and the 1,000-a-day token limit count every accepted message, captured ones included; the per-app and all-apps limits count only real sends.

## Agent notes

- Check `state` before you trade the code. Every rehearsal of an app on Agent Cloud sign-in tests it, and a release whose callback trades a code with the wrong state fails its checks.
- Key your users table on `user.id` (a uuid), not the email: emails change, and a mirror's data is masked.
- Keep your own session short (a day or less) and recheck with `GET /users/:id`, so a person removed from the app loses access.
- `SIGN IN pat@example.test` in a smoke flow drives the sign-in test flow end to end.
- Make `key` a function of the message, not of the attempt: `booking-42/confirmation`, never a timestamp or a random id. The rehearsal's chaos run fails a release whose retries send twice.
- Enqueue the email in the same transaction as the write it belongs to, and send it from the worker; see [Background work and workers](/docs/build/background-work-and-workers.md).
- Use `example.test` addresses in seed data and smoke flows. They're captured everywhere, including production.
- `MAIL <address> -> N` in a smoke flow counts captured messages to an address; see [Smoke step grammar](/docs/checks/smoke-flows.md#step-grammar).

## Related

- [Agent Cloud sign-in](/docs/build/choosing-a-sign-in-shape.md#agent-cloud-sign-in-shape-2)
- [Choosing a sign-in shape](/docs/build/choosing-a-sign-in-shape.md)
- [Sending email](/docs/build/sending-email.md)
- [Email holds and resume](/docs/build/sending-email.md#email-holds-and-resume)
- [App runtime contract](/docs/reference/app-runtime-contract.md)
- [Custom domains](/docs/build/custom-domains.md)

<!-- feedback:start -->
---
Wrong, outdated or unclear? Run `agc feedback docs "reference/sign-in-broker-api: <what is wrong>" --body <file>` with the sentence quoted in the file. No code or app data is sent.
<!-- feedback:end -->
