# OAuth for creator dashboards

> **Note:**
>
> Beta — the platform and this API are in beta. The rules on this page are binding; we may add features and tighten validation without notice.

Your dashboard can act for a creator — read her status, edit her profile, follow her consent — once she signs in with Creator Guard and approves your app. This is OAuth 2.1: the authorization-code flow with PKCE (`S256`) and refresh tokens that rotate on every use. The authorization server is `https://app.creator-guard.com` (the issuer); the API stays on `https://api.creator-guard.com`. If you do not want to build screens for creators, send her our [hosted pages](https://docs.creator-guard.com/hosted-pages/) instead.

## Who can connect to your app

She can approve your app only while your account is **approved** and either **submitted her** (you are her referring partner) or, as an agency, **holds a paid reservation for her** (paid, contact released or completed). Anyone else is told on our consent screen that your app cannot connect to her account; the redirect back to you carries `error=access_denied`.

We check the relationship again on every token exchange, every refresh and every API call. When it ends (for example a refunded reservation), her grant is revoked: refreshing answers `invalid_grant`, the API `401 invalid_token`. Your account's status is different: while it is pending or disabled, her token answers `403 account_not_active` and refreshing answers `unauthorized_client`, but nothing is revoked — once your account is approved again, the same tokens work.

When you remove a team member (or lower her role below admin), every redirect URI that one of her keys added to a live app is removed with her: open codes issued to it stop working, and an authorization whose current refresh token was issued through it is revoked, because that token went to her address. An app left without redirect URIs is **disabled** (`enabled: false`, `disabled_reason: member_offboarded`): the consent screen does not know it and `/oauth/token` answers `unauthorized_client` without revoking anything. Register its redirect URIs again with `PATCH /v1/oauth-apps/{id}` to enable it. Removing a redirect URI yourself has the same effect on what went through it: its open codes fail and refresh tokens issued through it answer `invalid_grant` until it is registered again — keep the old URI registered while you move clients to a new one. The scopes she approves take effect when you exchange the code, not before.

She needs her own Creator Guard login for this. A creator without one gets it through a [claim link](https://docs.creator-guard.com/hosted-pages/#claim-link).

### Consent, 18+ and creator terms: never through the referrer's app

The account that referred a creator never records her decisions. Her consent, her 18+ confirmation and her acceptance of the creator terms are refused with [`403 referrer_app_not_allowed`](https://docs.creator-guard.com/errors/#referrer_app_not_allowed) when they come through an OAuth app owned by the account that submitted her lead. Apps belong to the account, not to a person, so this covers the app of every member of that account. She gives these only in Creator Guard's own screens: the [consent link](https://docs.creator-guard.com/hosted-pages/#consent-link) or her creator portal. A referrer's app can still read her consent state (`GET /v1/creator/consent`), and **withdrawing** consent works through any connected app, the referrer's included. Claim links are not affected: you can still send her one. Details: [Creator API](https://docs.creator-guard.com/creator-api/#consent-and-18) and [Consent ledger](https://docs.creator-guard.com/consent-ledger/).

## 1. Register your app

```bash
curl -X POST https://api.creator-guard.com/v1/oauth-apps \
  -H "Authorization: Bearer $CG_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name":"Studio Dashboard","privacy_url":"https://example.com/privacy","redirect_uris":["https://dashboard.example.com/oauth/callback"],"scopes":["creator.profile:read","creator.consent:write"],"confidential":true}'
```

The key needs the scope `oauth_apps:manage`. The answer holds `client_id` (`cgcl_live_…`, public) and, for a confidential app, `client_secret` (`cgcs_live_…`) — shown **once**. A browser or mobile app that cannot keep a secret registers with `"confidential": false` and relies on PKCE alone. `POST /v1/oauth-apps/{id}/roll` issues a new secret; the old one keeps working for 24 hours. At most 10 apps per mode.

- Redirect URIs are compared character by character: no wildcards, and `…/callback/` is not `…/callback`.
- Live apps need `https` and a real host name (no `localhost`, no IP address). Test-mode apps may also use `http://localhost:<port>` and `http://127.0.0.1:<port>`.
- `scopes` is the most your app may ask for; each authorize request names the scopes it needs now. The scopes and what she is told about each are listed on [Creator API](https://docs.creator-guard.com/creator-api/#scopes).
- Name, logo, privacy policy and your account's name are shown to her on the consent screen.

## 2. Create the PKCE pair

Create a new verifier for every sign-in and keep it on your side (server session or browser storage); send only the challenge.

```js
// Works in Node 22 and in browsers (Web Crypto).
function base64url(bytes) {
  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}

export async function challengeFor(verifier) {
  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
  return base64url(new Uint8Array(digest));
}

export async function pkcePair() {
  const verifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
  return { verifier, challenge: await challengeFor(verifier) };
}
```

```python
import base64
import hashlib
import secrets

def b64url(raw: bytes) -> str:
    return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")

def challenge_for(verifier: str) -> str:
    return b64url(hashlib.sha256(verifier.encode("ascii")).digest())

def pkce_pair() -> tuple[str, str]:
    verifier = b64url(secrets.token_bytes(32))
    return verifier, challenge_for(verifier)
```

## 3. Send her to the authorize URL

```text
https://app.creator-guard.com/oauth/authorize?response_type=code
  &client_id=cgcl_live_3f9c2a7e5b1d4c8fa06e2b9d7c4a1f53
  &redirect_uri=https%3A%2F%2Fdashboard.example.com%2Foauth%2Fcallback
  &scope=creator.profile%3Aread%20creator.consent%3Awrite
  &state=8c1f0e…  (random, 1 to 500 characters, stored in her session)
  &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
  &code_challenge_method=S256
```

(One line in practice.) `state` and `code_challenge_method=S256` are required; `plain` is refused, and so is any parameter sent twice. She signs in with her own Creator Guard email and password, sees your app's name, logo, owner and each scope in plain words, and allows or denies. The screen serves live apps only. An unknown `client_id` or a `redirect_uri` that is not registered shows an error page and never redirects. The page cannot be framed: open it in the top window or a new tab.

## 4. Handle the redirect

We send her back to your redirect URI with `?code=…&state=…&iss=https%3A%2F%2Fapp.creator-guard.com`. First compare `state` with the one you stored and `iss` with the issuer; if either differs, stop. On a denial or error the query holds `error` (`access_denied`, `invalid_scope`, `invalid_request`, `unsupported_response_type`), `error_description`, the same `state` and `iss`. A code is valid for **60 seconds** and **once**: a second use fails and revokes the grant, with every token issued from it.

## 5. Exchange the code

```bash
curl -X POST https://app.creator-guard.com/oauth/token \
  -u "$CLIENT_ID:$CLIENT_SECRET" \
  -d grant_type=authorization_code -d code="$CODE" -d code_verifier="$VERIFIER" \
  --data-urlencode redirect_uri=https://dashboard.example.com/oauth/callback
```

```js
const res = await fetch('https://app.creator-guard.com/oauth/token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  body: new URLSearchParams({
    grant_type: 'authorization_code',
    code: process.env.CG_CODE,
    code_verifier: process.env.CG_VERIFIER,
    redirect_uri: 'https://dashboard.example.com/oauth/callback',
    client_id: process.env.CG_CLIENT_ID,
    client_secret: process.env.CG_CLIENT_SECRET, // confidential apps only, server side only
  }),
});
const tokens = await res.json(); // { access_token, token_type: 'Bearer', expires_in: 3600, refresh_token, scope }
```

```python
import json
import os
import urllib.parse
import urllib.request

def exchange(code: str, verifier: str) -> dict:
    body = urllib.parse.urlencode({
        "grant_type": "authorization_code",
        "code": code,
        "code_verifier": verifier,
        "redirect_uri": "https://dashboard.example.com/oauth/callback",
        "client_id": os.environ["CG_CLIENT_ID"],
        "client_secret": os.environ["CG_CLIENT_SECRET"],  # confidential apps only
    }).encode()
    req = urllib.request.Request("https://app.creator-guard.com/oauth/token", data=body, method="POST")
    with urllib.request.urlopen(req) as res:
        return json.load(res)
```

Confidential apps authenticate with HTTP Basic (`client_secret_basic`) or with `client_id` + `client_secret` in the body (`client_secret_post`); public apps send only `client_id` (`none`). The access token (`cgo_live_…`) lasts 1 hour, the refresh token (`cgr_live_…`) 30 days from its last use. Store both like passwords — we keep only their hashes and cannot show them again. Every answer is `Cache-Control: no-store`.

If a client secret or a token turns up in public (GitHub secret scanning reports `cgcs_`, `cgo_` and `cgr_` values to us, like API keys), we act at once, without asking first: a leaked client secret is replaced by one nobody knows — the app cannot authenticate until you roll a new one with `POST /v1/oauth-apps/{id}/roll` (a leaked previous secret, still accepted after a roll, simply stops working); a leaked access or refresh token ends the creator's whole authorization, and she has to connect your app again. Your audit events show `oauth_app.secret_leaked` or `oauth_app.token_leaked`, and we email your account's contact address.

### Browser apps (CORS)

**The API itself is server-side only: `/v1` sends no CORS headers**, so a browser page cannot read any `/v1` answer — the creator API included. A browser or mobile front end calls your own backend, and your backend calls `https://api.creator-guard.com` with the access token.

Only the sign-in endpoints have CORS:

- `/oauth/token` and `/oauth/revoke`: a public client running in the browser may call them directly. The answer is readable only from the **origin of one of the app's registered redirect URIs** (`Access-Control-Allow-Origin` names exactly that origin; any other origin gets no CORS header). The preflight allows only `POST` with `Content-Type` — no `Authorization` header, so a client secret can never be sent from a browser. Confidential apps call these endpoints from their server.
- `/.well-known/oauth-authorization-server` (the server metadata) is readable from any origin (`Access-Control-Allow-Origin: *`); it holds nothing secret.
- `/oauth/authorize` is a page the creator's browser navigates to, not something to fetch.

## 6. Call the creator API

```bash
curl https://api.creator-guard.com/v1/creator/me -H "Authorization: Bearer $ACCESS_TOKEN"
```

Every endpoint is listed on [Creator API](https://docs.creator-guard.com/creator-api/). A token without the scope an endpoint needs gets `403 insufficient_scope`; an expired one `401 expired_token`; a revoked one `401 invalid_token`. An account API key on a creator endpoint is `403 wrong_account_type`. Requests count against your account's limits, per grant.

## Refresh tokens rotate

```bash
curl -X POST https://app.creator-guard.com/oauth/token -u "$CLIENT_ID:$CLIENT_SECRET" \
  -d grant_type=refresh_token -d refresh_token="$REFRESH_TOKEN"
```

Every refresh returns a **new** refresh token and invalidates the old one. Save the new one before you use the new access token. A `scope` sent with a refresh is ignored: the answer states the grant's scopes.

> **Important:**
>
> Never send an old refresh token again. If a refresh token that was already rotated arrives a second time, we treat it as stolen: the whole grant is revoked, every access and refresh token of it stops working (`invalid_grant`, then `401 invalid_token`), and she has to approve your app again. Run refreshes in one place (no two workers refreshing the same grant at once), and if a refresh fails with a network error, do not retry it with the same token — send her through authorize again.

## Revoke

```bash
curl -X POST https://app.creator-guard.com/oauth/revoke -u "$CLIENT_ID:$CLIENT_SECRET" -d token="$REFRESH_TOKEN"
```

Revoking a refresh token ends the grant; revoking an access token ends only that token. The answer is `200` whether or not the token existed (RFC 7009). She can also disconnect your app herself in the creator portal, and your app can disconnect itself through `DELETE /v1/creator/connected-apps/{app}` with its own app id (scope `creator.profile:write`; other apps' ids are `404`); deleting your app (`DELETE /v1/oauth-apps/{id}`) revokes every grant it has.

## Consent texts and `409 consent_text_outdated`

Before you record her consent, her 18+ confirmation or her acceptance of the creator terms, fetch the current text with `GET /v1/creator/consent-text?kind=consent` (`age_confirmation`, `creator_terms`), show `body_md` to her unchanged, and send its `version` with her answer (`POST /v1/creator/consent/grant` with `{"text_version": 1}`). We record the version and the text's hash in the [consent ledger](https://docs.creator-guard.com/consent-ledger/). When we publish a new wording, the old version is refused with `409 consent_text_outdated` (`error.current_version` names the new one) and nothing is recorded: fetch the new text, show it to her, and ask again. Never retry with the new version number without showing her the new text.

A **withdrawal** (`POST /v1/creator/consent/revoke`) never fails because of the text version: she can always take her consent back.

## Test mode

Test-mode apps (`cgcl_test_…`, registered with a `cg_test_` key) work against the sandbox. Our consent screen serves live apps only, because the sandbox has no real creator logins. Instead, mint a code with your test key (scope `oauth_apps:manage`) for a sandbox lead you submitted:

```bash
curl -X POST https://api.creator-guard.com/v1/test-helpers/oauth-codes \
  -H "Authorization: Bearer $CG_TEST_KEY" -H "Content-Type: application/json" \
  -d '{"client_id":"cgcl_test_3f9c2a7e5b1d4c8fa06e2b9d7c4a1f53","lead_id":"lead_eaaaaaaaabaabaaaaaaaaaaaae","redirect_uri":"http://localhost:3000/callback","scopes":["creator.profile:read"],"code_challenge":"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"}'
```

The answer is `{"object": "oauth_test_code", "code": "cgac_…", "expires_in": 60}`. Exchange the `code` at `/oauth/token` exactly as in step 5; the tokens start with `cgo_test_` / `cgr_test_` and only ever see test data. Refresh, reuse detection and revoke behave as in live mode. A live key gets `404 not_found` from every test helper.

## Errors of the OAuth endpoints

`/oauth/token` and `/oauth/revoke` answer like RFC 6749: `{"error": "invalid_grant", "error_description": "…"}`.

| `error` | HTTP | Meaning |
|---|---|---|
| `invalid_request` | 400 | A parameter is missing or repeated, or the verifier is not 43 to 128 characters |
| `invalid_client` | 401 | Unknown `client_id`, wrong secret, a secret from a public client, or none from a confidential one |
| `invalid_grant` | 400 | Code or refresh token unknown, used, expired or revoked; `redirect_uri` or verifier does not match; the relationship to her ended |
| `unauthorized_client` | 400 | Your account is not approved right now; nothing was revoked |
| `unsupported_grant_type` | 400 | Only `authorization_code` and `refresh_token` |
| `server_error` | 500 | Something failed on our side; try again |
| `temporarily_unavailable` | 503 | OAuth is not configured on our side; try again later |
| `rate_limited` | 429 | Too many refused requests from your IP address; wait for `Retry-After` |

`/oauth/token`, `/oauth/revoke`, the authorize page and its decision share the per-IP budget of requests without an account (30 per minute per IP). Successful token and revoke calls spend nothing, so refreshing many tokens from your server is never throttled; refused ones (a wrong secret, an unknown code) do.

The API itself answers with the usual error object; see [Errors](https://docs.creator-guard.com/errors/).

## Server metadata

`GET https://app.creator-guard.com/.well-known/oauth-authorization-server` (RFC 8414) lists the issuer `https://app.creator-guard.com`, the authorization, token and revocation endpoints, `code_challenge_methods_supported: ["S256"]`, the client authentication methods and the scopes.
