# API keys

You manage your keys yourself: in the partner portal under **Settings → API**, or over the API with a key that has `keys:manage`. Our team can still issue and revoke keys for you.

## Two modes

| Prefix | Mode | Reaches |
|---|---|---|
| `cg_live_` | live | Your real leads. |
| `cg_test_` | test | The sandbox — see [Test mode](https://docs.creator-guard.com/test-mode/). |

Each mode has its own keys, at most **10 active keys per mode** (one more → [`409 limit_reached`](https://docs.creator-guard.com/errors/#limit_reached)). A key only ever sees the data of its own mode.

## Scopes

| Scope | Allows |
|---|---|
| `account:read` | `GET /v1/me`, agreements, option lists, settings, request logs; agencies: your agency profile |
| `account:write` | `PATCH /v1/me`, your logo; agencies: `PATCH /v1/agency-profile` |
| `agreements:write` | Accepting agreements |
| `leads:read` | Leads, listings, photos, confirmations, timelines |
| `leads:write` | Creating and changing leads and listings, consent links, review, withdrawing, the test helpers for leads and commissions |
| `photos:write` | Uploading, changing and deleting photos |
| `earnings:read` | Earnings, commissions, payout details (masked) |
| `offers:read` | Agencies: offers and their photos, your search profile |
| `offers:write` | Agencies: accepting, declining and progressing offers, your offer notes, the test helpers for offers and the test clock |
| `reservations:read` | Agencies: reservations and, once paid, the creator's contact |
| `reservations:write` | Agencies: warranty claims, the test helpers for reservations |
| `search_profile:write` | Agencies: changing your search profile |
| `extract` | `POST /v1/extract` |
| `usage:read` | `GET /v1/usage` |
| `audit:read` | `GET /v1/audit-events` |
| `keys:manage` | `/v1/api-keys`, `POST /v1/test-helpers/reset` |
| `webhooks:manage` | `/v1/webhook-endpoints` |
| `oauth_apps:manage` | `/v1/oauth-apps`, `POST /v1/test-helpers/oauth-codes` |
| `members:manage` | `/v1/members` (live keys only) — see [Members & roles](https://docs.creator-guard.com/members/) |

Creating, rolling and revoking keys works before your account has accepted its terms, so you can set up an integration first; most other writes need them — the full list of exceptions is under [Authentication → Terms](https://docs.creator-guard.com/authentication/#terms). A **live** key is different: creating or rolling one needs the [API Terms of Use](https://docs.creator-guard.com/authentication/#api-terms), accepted once by an owner or admin of your account. Test keys never need them, and revoking a key always works.

Events (`GET /v1/events`) need no scope of their own: a key sees the events whose object it may read — see [Events](https://docs.creator-guard.com/events/). These nineteen are all scopes there are today; any other value answers [`400 invalid_field`](https://docs.creator-guard.com/errors/#invalid_field) on `scopes`.

## In the portal

**Settings → API** lists the keys of both modes. Pick the mode and the permissions when you create one; the five scopes `account:read`, `agreements:write`, `leads:read`, `leads:write` and `earnings:read` are preselected. Creating, rolling and revoking a key and changing the key policy need your **second factor** (an authenticator app): the portal asks for the six-digit code first. Keys made in the portal have no IP allowlist; create a key over the API to set one.

## With the API

curl:

```bash
curl -X POST https://api.creator-guard.com/v1/api-keys \
  -H "Authorization: Bearer $CG_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
    "label": "CRM production",
    "scopes": ["leads:read", "leads:write", "earnings:read"],
    "ip_allowlist": ["203.0.113.0/24"]
  }'
```

JavaScript:

```js
// Node.js 20+ as an ES module (.mjs, or "type": "module"): built-in fetch + top-level await.
// Server-side only: the key must never reach a browser.
const body = {
  "label": "CRM production",
  "scopes": ["leads:read", "leads:write", "earnings:read"],
  "ip_allowlist": ["203.0.113.0/24"]
};

const res = await fetch('https://api.creator-guard.com/v1/api-keys', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.CG_API_KEY}`,
    'Content-Type': 'application/json',
    'Idempotency-Key': crypto.randomUUID(), // keep it and send it again when you retry
  },
  body: JSON.stringify(body),
});
const data = await res.json();
if (!res.ok) throw new Error(`${res.status} ${data.error.code}: ${data.error.message}`);
console.log(res.status, data);
```

Python:

```python
# pip install requests
import os
import uuid
import requests

body = {
    "label": "CRM production",
    "scopes": ["leads:read", "leads:write", "earnings:read"],
    "ip_allowlist": ["203.0.113.0/24"],
}

res = requests.request(
    "POST",
    "https://api.creator-guard.com/v1/api-keys",
    headers={"Authorization": f"Bearer {os.environ['CG_API_KEY']}", "Idempotency-Key": str(uuid.uuid4())},
    json=body,
    timeout=30,
)
data = res.json()
if not res.ok:
    raise RuntimeError(f"{res.status_code} {data['error']['code']}: {data['error']['message']}")
print(res.status_code, data)
```

The answer carries the full key once, in `secret` — store it straight away, it is never shown again. Sending the same request again with the same `Idempotency-Key` answers the same key with `secret: null`. The new key gets the mode of the key that created it and the `scopes` you list — **at most the calling key's own**; asking for more answers [`403 insufficient_scope`](https://docs.creator-guard.com/errors/#insufficient_scope). So `keys:manage` and `webhooks:manage` reach a key made over the API only through a key that already has them, and those come from the portal with your second factor or from our team. `ip_allowlist` takes up to 20 CIDR blocks; `expires_at` is optional.

A new key is never less restricted than the key that makes it:

- **IP allowlist.** If the calling key has an allowlist, the new key's `ip_allowlist` must lie inside it (each block within one of the caller's blocks) — otherwise [`400 invalid_field`](https://docs.creator-guard.com/errors/#invalid_field) on `ip_allowlist`. Leave it out and the new key gets the caller's allowlist.
- **Expiry.** The new key expires no later than the calling key: a later `expires_at`, or none, becomes the caller's expiry.

Keys made in the portal are not limited this way.

`GET /v1/api-keys` lists the active keys of your mode and those revoked in the last 90 days (prefix, label, scopes, last use, expiry) — never a secret.

## Rolling without downtime

`POST /v1/api-keys/{id}/roll` creates a new key with the same label, scopes, IP allowlist and expiry, and keeps the old one working for `grace_hours` (0–72, default 24). It works only for keys whose scopes the calling key holds, and the new key also takes on the calling key's restrictions: its IP allowlist is the overlap of the old key's and the caller's (if both have one and they do not overlap at all → [`409 invalid_state`](https://docs.creator-guard.com/errors/#invalid_state) with `current_state: ip_allowlist_outside_caller`), and it expires no later than the caller. Rolling in the portal keeps the old key's settings as they are.

curl:

```bash
curl -X POST https://api.creator-guard.com/v1/api-keys/key_hz5ikyc3pnhkrhlb6p7elkx2qy/roll \
  -H "Authorization: Bearer $CG_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
    "grace_hours": 24
  }'
```

JavaScript:

```js
// Node.js 20+ as an ES module (.mjs, or "type": "module"): built-in fetch + top-level await.
// Server-side only: the key must never reach a browser.
const body = {
  "grace_hours": 24
};

const res = await fetch('https://api.creator-guard.com/v1/api-keys/key_hz5ikyc3pnhkrhlb6p7elkx2qy/roll', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.CG_API_KEY}`,
    'Content-Type': 'application/json',
    'Idempotency-Key': crypto.randomUUID(), // keep it and send it again when you retry
  },
  body: JSON.stringify(body),
});
const data = await res.json();
if (!res.ok) throw new Error(`${res.status} ${data.error.code}: ${data.error.message}`);
console.log(res.status, data);
```

Python:

```python
# pip install requests
import os
import uuid
import requests

body = {
    "grace_hours": 24,
}

res = requests.request(
    "POST",
    "https://api.creator-guard.com/v1/api-keys/key_hz5ikyc3pnhkrhlb6p7elkx2qy/roll",
    headers={"Authorization": f"Bearer {os.environ['CG_API_KEY']}", "Idempotency-Key": str(uuid.uuid4())},
    json=body,
    timeout=30,
)
data = res.json()
if not res.ok:
    raise RuntimeError(f"{res.status_code} {data['error']['code']}: {data['error']['message']}")
print(res.status_code, data)
```

Deploy the new secret, then let the grace period run out. The old key shows `grace_until`, the new one `rolled_from`. `grace_hours: 0` revokes the old key at once. As on create, a replay answers `secret: null`.

During its grace period the old key keeps working for your data, but it **manages nothing any more**: every request that needs `keys:manage` or `webhooks:manage` answers [`403 insufficient_scope`](https://docs.creator-guard.com/errors/#insufficient_scope) naming that scope. Manage keys and webhooks with the new key.

## Revoking

`DELETE /v1/api-keys/{id}` revokes a key; it fails on the very next request, and repeating the call is harmless. Like rolling, it works only for keys whose scopes the calling key holds — otherwise [`403 insufficient_scope`](https://docs.creator-guard.com/errors/#insufficient_scope) naming the first one missing — so a narrow key cannot switch off a wider one. In the portal you can revoke any key. A key revokes itself only with `?force=true` (otherwise [`409 invalid_state`](https://docs.creator-guard.com/errors/#invalid_state) with `current_state: in_use`) — so a script cannot lock itself out by mistake.

## Key policy

In **Settings → API → Key policy** (second factor needed) you can set, for the whole account:

- **Maximum key age** (1–3,650 days): every key expires that many days after it was created, whatever its own expiry.
- **Revoke unused keys** after 30–3,650 days without a request. Off by default.

Seven days before a live key expires you get the event [`api_key.expiring`](https://docs.creator-guard.com/events/#event-api_key.expiring), once per key. Every key change — created, rolled, revoked, revoked by the policy — is in the [audit trail](https://docs.creator-guard.com/usage/#audit-trail).
