# catID — Integration guide for AI coding assistants

> catID (https://sso.cat) is a single sign-on provider. Users own one catID account and several "cat personas" (name, email, avatar, bio). When they sign in to your app with catID, they choose which persona to share. Your app receives that persona — never the real account.

Use this document as the single source of truth. Do not invent endpoints, scopes, SDKs or secrets that are not listed here.

## 0. Prerequisites (the human must do this)

1. Create a catID account on https://sso.cat and activate the developer account in https://sso.cat/developer.
2. Register the app: give it a name and the exact redirect URL(s), e.g. `https://myapp.com/auth/catid/callback` and `http://localhost:5173/auth/catid/callback`.
3. Copy the `client_id` (a UUID). It is public — it is fine in frontend code.

If the client_id is unknown, ask the user for it. Never hardcode a fake one silently; use a clearly named constant `CATID_CLIENT_ID`.

## 1. Flow overview (OAuth-style authorization code, no client secret)

```
Your app ──(1) redirect──▶ https://sso.cat/authorize?client_id&redirect_uri&state
                              │ user signs in + picks a persona
Your app ◀─(2) redirect── redirect_uri?code=XXX&state=YYY
Your app ──(3) POST code──▶ https://sso.cat/api/public/token  ──▶ { user }
```

## 2. Step 1 — Send the user to catID

Generate a random `state`, store it (sessionStorage or a short-lived cookie), then do a full-page redirect:

```js
const CATID_CLIENT_ID = "YOUR_CLIENT_ID";
const CATID_REDIRECT_URI = window.location.origin + "/auth/catid/callback"; // must be registered EXACTLY

export function loginWithCatId() {
  const state = crypto.randomUUID();
  sessionStorage.setItem("catid_state", state);
  window.location.href = "https://sso.cat/authorize?" + new URLSearchParams({
    client_id: CATID_CLIENT_ID,
    redirect_uri: CATID_REDIRECT_URI,
    state,
  });
}
```

Rules:
- Full-page redirect only. Do not use iframes. Popups are not supported.
- `redirect_uri` must match a registered URL character-for-character (scheme, host, port, path, no trailing slash differences, no query string).

## 3. Step 2 — Handle the callback route

Create a route at the redirect path (e.g. `/auth/catid/callback`). It receives one of:
- Success: `?code=<one-time code>&state=<your state>`
- Cancelled: `?error=access_denied&state=<your state>`

```js
const p = new URLSearchParams(window.location.search);
if (p.get("state") !== sessionStorage.getItem("catid_state")) throw new Error("catID: state mismatch");
sessionStorage.removeItem("catid_state");
if (p.get("error")) { /* user cancelled: show a message, go back to login */ }
const code = p.get("code");
```

Remove `code` from the URL afterwards (`history.replaceState`). Never exchange the same code twice (React StrictMode runs effects twice — guard with a ref).

## 4. Step 3 — Exchange the code

`POST https://sso.cat/api/public/token` — JSON body, CORS enabled, no auth header, no secret.

```js
const res = await fetch("https://sso.cat/api/public/token", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ code, client_id: CATID_CLIENT_ID, redirect_uri: CATID_REDIRECT_URI }),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error);
const user = data.user;
```

Success (200):
```json
{ "user": { "sub": "persona-uuid", "name": "Mochi", "email": "mochi@example.com", "bio": "Professional napper", "avatar": "😺" } }
```
- `sub`: stable unique id of the persona. Use it as the user key in your database (not the email).
- `avatar`: an emoji string, render it as text.
- `bio` may be null.

Errors (400): `{ "error": "invalid_request" | "invalid_grant" | "unknown_client" }`
- `invalid_request`: malformed body.
- `invalid_grant`: code unknown, already used, expired (5 min) or issued for another client/redirect_uri.
- `unknown_client`: client_id not registered or redirect_uri not allowed.

You can call the token endpoint from the browser or, preferably, from your backend (server function / API route) so you can create your own session cookie.

## 5. Sessions in your app

catID does not issue access tokens or refresh tokens. After the exchange, create YOUR OWN session:
- With a backend: upsert a user row keyed by `sub`, set an httpOnly session cookie.
- With Supabase/Firebase/etc.: store `sub` as an external identity on your user record.
- Frontend-only prototypes: store `user` in localStorage (acceptable for demos only).
Sign-out is local to your app — clear your session.

## 6. The catID button (widget)

Default label is just **catID**. Ready-to-paste HTML (works in Webflow, Framer, WordPress, plain HTML):

```html
<a href="#" id="catid-login" class="catid-btn">
  <span class="catid-icon">
    <svg width="22" height="22" viewBox="0 0 32 32" fill="none" stroke="#fff" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">
      <path d="M6 27V9l6 5h8l6-5v18"/>
      <circle cx="12.5" cy="19" r="1.4" fill="#fff" stroke="none"/>
      <circle cx="19.5" cy="19" r="1.4" fill="#fff" stroke="none"/>
    </svg>
  </span>
  <span class="catid-label">catID</span>
</a>

<style>
  .catid-btn { display:inline-flex; align-items:center; height:48px; overflow:hidden; border-radius:999px;
    background:linear-gradient(90deg,#1f2a5c,#7fc4a8); color:#fff; font:500 16px system-ui,sans-serif; text-decoration:none; }
  .catid-icon { display:flex; align-items:center; justify-content:center; width:56px; height:100%; background:#1f2a5c; }
  .catid-label { padding:0 22px; }
</style>

<script>
  document.getElementById("catid-login").addEventListener("click", function (e) {
    e.preventDefault();
    var state = crypto.randomUUID();
    sessionStorage.setItem("catid_state", state);
    location.href = "https://sso.cat/authorize?" + new URLSearchParams({
      client_id: "YOUR_CLIENT_ID",
      redirect_uri: "https://myapp.com/auth/catid/callback",
      state: state
    });
  });
</script>
```

React version:

```tsx
export function CatIdButton() {
  return (
    <button onClick={loginWithCatId} style={{ display: "inline-flex", alignItems: "center", height: 48, padding: 0,
      overflow: "hidden", border: "none", borderRadius: 999, cursor: "pointer",
      background: "linear-gradient(90deg,#1f2a5c,#7fc4a8)", color: "#fff", font: "500 16px system-ui, sans-serif" }}>
      <span style={{ width: 56, height: "100%", display: "grid", placeItems: "center", background: "#1f2a5c" }}>🐱</span>
      <span style={{ padding: "0 22px" }}>catID</span>
    </button>
  );
}
```

Styles available in the developer console: signature (gradient), dark, light; shapes pill, rounded, square. Keep the cat icon and the word "catID" visible.

## 7. Security checklist (mandatory)

- Always generate and verify `state`.
- Use the exact registered `redirect_uri` in both the authorize URL and the token request.
- Codes are single-use and expire after 5 minutes — exchange immediately.
- Key users by `sub`, not by email (a persona's email can change).
- Never put a code or persona data in logs or analytics.
- Only use `https://sso.cat`. There is no other catID domain.

## 8. Framework notes

- Next.js / Remix / TanStack Start / SvelteKit: create a callback page that reads `code`, then call a server action/route that POSTs to the token endpoint and sets your cookie.
- Vite SPA / Lovable / Bolt: add a client route for the callback; exchange from the browser.
- Local dev: register `http://localhost:<port>/<callback>` as an extra redirect URL.

## 9. Done criteria

1. Clicking the catID button lands on https://sso.cat/authorize showing your app name.
2. After picking a persona the user is back on your callback route.
3. The token request returns 200 with `user.sub`.
4. Your app shows the persona name/avatar and survives a page reload.
5. Cancelling on catID shows a friendly message.
