# Authentication

Separate agent capabilities from owner spending authority.

## Connect an agent without copying keys

An agent can request a connection before it has an account or email address. The human owner still signs in and approves access. This is MarketingRouter JSON pairing, not a general OAuth authorization server.

1. POST `/api/v1/agent-authorizations` with the agent name, `mode` (`sandbox` by default or `live`) and the smallest required scopes. No Authorization header is needed.
2. Keep the returned `device_code` private. Show the owner **both** `verification_uri_complete` and `user_code`. The owner signs in, checks the matching code and permissions, and approves or declines.
3. POST `/api/v1/agent-authorizations/token` with `{ "device_code": "PRIVATE_CODE_FROM_STEP_1" }` at most once every five seconds. HTTP 202 means pending. HTTP 200 with `status:approved` returns the scoped `key` and `key_id`.
4. Save `key` in your secret store, discard `device_code`, and use `Authorization: Bearer` for the API. The owner can revoke it under Dashboard → API keys.

```json
{
  "name": "My growth agent",
  "mode": "live",
  "scopes": ["campaigns:read", "campaigns:write"]
}
```

Connection requests expire after 15 minutes. `device_code` is a secret: never put it in URLs, owner messages, browser storage, telemetry or logs. The approval link contains only the public confirmation code. Neither endpoint asks for the owner's session token. The agent-provided name is not verified identity; owners should approve only requests they initiated.

An approved key can be retrieved again with the same private code until the request expires, so a lost response does not issue another key. Revocation blocks subsequent retrieval and key use. The key remains valid until revoked; the request's 15-minute expiry does not revoke an already issued key. HTTP 429 `slow_down` requires at least five seconds before polling again. Stop on 403 `authorization_denied`, 404 `authorization_not_found`, or 410 `authorization_expired`. Start requests are capped at 20 per source per hour and 1,000 service-wide per hour. If an initial start response is lost, requesting a new connection is safe; the old request expires without granting access.

Connecting grants the reviewed scopes, not payment or campaign-launch approval. Live `campaigns:write` can consume the workspace's generation allowance and control already-approved ads within their limits. Sandbox access cannot call live advertising or image-generation providers.

## Keys and owner sessions

Public: GET /api/v1/capabilities, POST /api/v1/quotes and the two agent connection endpoints. Other resources require authentication and belong to one workspace owner.

```http
Authorization: Bearer YOUR_API_KEY
```

Keys have a 256-bit random secret: mr_test_ plus 64 hex characters for sandbox; mr_live_ plus 64 hex characters for managed Meta operations and paid creative generation. Store keys in a secret store, never URLs, public code, browser local storage, or logs. Manually created keys are shown once. Pairing keys can be retrieved by the initiating agent during the request lifetime; the database stores only credential hashes. Owner accounts use Supabase email links and HttpOnly sessions. Open a sign-in link in the browser that requested it.

## Scopes

| Scope | Operations |
| --- | --- |
| campaigns:read | Read campaigns, results, activity, creative jobs/previews, assigned live assets and balance; reconcile campaigns and balance top-ups |
| campaigns:write | Create/revise campaigns; prepare/pause live resources; generate/revise/publish creatives; upload assets; request balance checkout links |
| events:write | Submit conversion observations |

Each agent should receive its own key. A sandbox key cannot mutate provider resources. A live key grants provider preparation and controls within its scope; it never grants advertising launch approval. Revoke keys in the owner console.

## Owner-only actions

Only the authenticated owner can create/revoke keys, accept advertiser consent, create campaign-specific checkout, or approve a campaign. The API refuses agent keys for those operations. Never request an owner's session token to bypass approval.

Guided setup provisions an isolated brand workspace and binds its approved Facebook Page and destination to the owner. Operators separately validate purchasing capacity and spending ceilings. A customer cannot access another workspace’s Pages or creatives. Advertising credentials stay server-side.

## Failure handling

401 means credentials are missing, invalid, or revoked. 403 means the principal lacks a scope or owner authority. Fix credentials or request the owner's action rather than repeatedly retrying. Cookie-authenticated writes enforce same-origin requests. Machine agents should use bearer authentication.

Live agents can request reusable balance top-ups, but the owner must authorize each hosted payment. There is no saved-card charging scope or automatic refill. Agents can now connect through the approval-link flow above without an agent email or manual key copying. Owners still sign in by email; social sign-in and unclaimed sandbox workspaces are not available.

## Paid creative authorization

A live campaigns:write key can initiate paid creative generation and revisions when creative.enabled is true, even if advertiser setup is incomplete or live_spend_enabled is false. Issue this scope only to agents authorized to use the generation service. It does not debit advertising credit. campaigns:read can inspect existing jobs and refresh previews. Sandbox keys cannot generate, revise, publish, or read live creative jobs. Only owner approval can authorize campaign activation.