# App API - Sign-in Client Code

The client half of [app-auth](app-auth.md): load that skill first to pick the sign-in mode (Gipity accounts or app users), gate functions with `auth_level`, and keep a signed-out user's work at the auth wall. This skill is the code that runs in the page: the SDK (use it), then the low-level REST flow it wraps, for reference.

## Client Code - use the SDK (do this)
Load the Gipity client SDK and let it handle sign-in. **Do not hand-roll the popup, polling, or COOP workarounds** - `Gipity.auth.signIn()` opens the popup synchronously on click and drives login + consent for you. Hand-rolling it is the #1 source of broken auth.

```html
<script crossorigin="anonymous" src="https://media.gipity.ai/client/v1/gipity.js"></script>
<gipity-signin app-guid="<PROJECT_GUID>" permissions="1"></gipity-signin>
```

Or wire your own button:

```js
Gipity.auth.configure({ appGuid: '<PROJECT_GUID>' });   // permissions defaults to 1 (identity only)
signinBtn.addEventListener('click', async () => {
  const user = await Gipity.auth.signIn(); // opens popup, handles login + consent
  if (user) showApp(user); else showSignedOut();
});
// On load, reflect any existing session (null if not signed in / not consented):
const me = await Gipity.auth.user();
if (me) showApp(me);
```

**Consent scopes (`permissions`) - set this to 5 for any app that calls paid AI on the user's credits.** `permissions` is a bitmask of the scopes the sign-in/consent popup asks the user to grant; it defaults to `1` (identity only). If your app calls an AI service under **`user_pays`** billing (`Gipity.service('llm' | 'image' | 'tts' | ...)` charging the signed-in user), the user must also consent to the AI scope - pass `permissions: 5` (or `permissions="5"` on `<gipity-signin>`) so `signIn()` requests it up front. Without it the first AI call 403s with `CONSENT_REQUIRED` and the flow can't self-recover: a service call can't open a consent popup (browsers only allow that inside the sign-in click). The bits, OR'd together: `IDENTITY = 1` (display name / avatar / account slug / user guid - always needed) and `AI = 4` (call paid AI services on the user's credits), so `1 | 4 = 5`. (Bits 32/64 cover this app's workflows; identity-only apps stay at `1`.)

**Account scope (`128`) - only for an app you own, like Monitor.** `ACCOUNT = 128` lets the app act as the signed-in user's whole Gipity account on the platform API (the same routes the CLI calls: `/account/logs/*`, `/projects/*`, `/workflows/*`, `/secrets`, `/users/me`, ...). It is **owner-only**: the consent screen refuses it for anyone who doesn't own the app, and every request is re-checked, so it only ever works when the project owner is the one signed in. Request it with `permissions=129` (identity + account), then send the app token as `X-App-Token` with `credentials: 'include'` on each platform API call. Use it for your own dashboards and admin tools, never for an app other people sign into. Unlike other scopes, the owner isn't granted it automatically: they approve it once on the consent screen, and until then `auth/status?permissions=129` reports `consented: false`.

Once signed in, `Gipity.fn(name, body)` (call a function), `Gipity.service(path, body)` (call an app service like `'llm'` / `'image'` - see [app-llm](app-llm.md)), and `Gipity.upload(file)` all auto-attach the token and session cookie for you - never hand-roll `fetch('/api/token')` + `X-App-Token`. Each throws on non-2xx with the server message and `err.status`/`err.code` (branch `402`/`401`). Call `signIn()` **directly in the click handler** - don't `await` anything before it or the browser blocks the popup.

**Reacting to auth changes from elsewhere in the app - `Gipity.auth.onChange`.** The simplest path is to re-render straight from the return values above (`signIn()` / `signOut()` resolve to the user-or-null; `user()` gives the initial state on load). When code that *didn't* trigger the change also needs to react - a header avatar, a sidebar, gated sections - subscribe once:

```js
const off = Gipity.auth.onChange((user) => {
  if (user) showApp(user); else showSignedOut();
});
// off();  // unsubscribe when you no longer care
```

The callback fires with the new user (or `null`) **only on a real transition** - signed-out → user, user → signed-out, or user → different user - at the three points auth actually moves: on load via `await Gipity.auth.user()`, and on `signIn()` / `signOut()` (including the `<gipity-signin>` button). It does **not** fire on subscribe (call `user()` yourself for the initial paint) and there is **no** background session-expiry signal - the SDK never polls, so nothing fires if the session is lost server-side without a `signIn`/`signOut` call in this tab. Don't write a polling loop waiting for one. There is also no `gipity:auth` DOM event on `document`/`window`; `onChange` is the subscription API. (The `<gipity-signin>` web component additionally emits a bubbling `gipity-signin` `CustomEvent` on the element itself, for that component's own button only.)

### Verifying sign-in behind the login wall (`--auth`)
Pass `--auth` to `gipity page inspect`/`screenshot`/`eval` to load the page **signed in as you** (your Gipity account, which for your own app auto-consents), so UI and data behind a Sign-in-with-Gipity gate are reachable headlessly:

```bash
gipity page inspect "https://dev.gipity.ai/<acct>/<app>/" --auth          # inspect the signed-in page
gipity page screenshot "https://dev.gipity.ai/<acct>/<app>/" --auth        # capture the members-only UI
gipity page eval "https://dev.gipity.ai/<acct>/<app>/" --auth "App.commands().length"   # drive signed-in app code
```

How it works: the server mints a short-lived session for you and injects the `gipity_sid` cookie into the headless browser before it navigates - the same session a normal login produces, so your app needs no changes. You can only ever browse as **yourself**.

**Without `--auth` the page loads as a genuinely anonymous, signed-out visitor** - the browser's cookie jar is wiped before every navigation, so nothing carries over from an earlier `--auth` run. Each command's identity is exactly its flags, which is what makes the two-state check on an app with a signed-in/signed-out split cheap and safe: run once with `--auth` (the signed-in path) and once without (the anonymous path - the gate, the nudge, the public view). Every run prints an `Auth:` line naming which identity the page ran as. No `Gipity.auth.signOut()` workaround inside the eval body, and no risk of an "anonymous" check silently writing rows as the owner.

Scope: `--auth` covers apps hosted on `*.gipity.ai` (dev/app). With **Sign in with Gipity** it signs in as your Gipity account; on your own app in app-user mode (`gipity project auth app|both`) it signs in as your app user, the account your email code creates, so the page shows the real signed-in view with your data. It does **not** cover other people's apps, apps with their own custom login, nor (for a page that reads a same-host cookie) custom domains. For those, verify the wiring instead: the gate renders, the button is wired, `window.Gipity.auth` exists, and `Gipity.auth.status()` is reachable - not the full popup; final confirmation needs a real browser with a signed-in user. Without `--auth`, the sandbox is headless with no logged-in user, so a signed-in round-trip can't complete there.

### Signing out
Wire your sign-out button to `await Gipity.auth.signOut()` - it ends the Gipity session **server-side** (clears the session cookie) and locally, so the user stays signed out across reloads. Then refresh your UI / navigate home.

```js
signoutBtn.addEventListener('click', async () => {
  await Gipity.auth.signOut();
  showSignedOut();          // re-render header + view for the signed-out state
});
```

Don't expect a one-liner local flag flip to log anyone out: the session lives in a cookie, so anything that only clears in-memory state leaves it live and `Gipity.auth.user()` re-detects the session on the next load - the user "comes back" signed in. `signOut()` is the only call you need. For a Gipity account it ends their shared Gipity session; for an app user it ends their session in this app only, and `signOutEverywhere()` ends their sessions on every device.

## How It Works
Users logged into Gipity already have a session cookie on `.gipity.ai`. Your app needs two things:
1. An **app token** (identifies your app to the API). It works only on your app's own `/api/<PROJECT_GUID>/...` routes: a token minted for one app (or one environment) is refused with 403 on any other.
2. `credentials: 'include'` on all fetch calls (sends the user's session cookie cross-origin)

Your app's owner and its project members never see a consent screen for identity: the owner is consented to their own app automatically, and a member's identity grant is recorded the first time they sign in. Anything beyond identity still asks a member.

## Step 1: Get an App Token
`POST https://a.gipity.ai/api/token` with your project GUID.

```js
const res = await fetch('https://a.gipity.ai/api/token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ app: '<PROJECT_GUID>' })
});
const json = await res.json();
const appToken = json.data.token;  // IMPORTANT: .data.token, NOT .token
```

**Response shape:**
```json
{ "data": { "token": "eyJ...", "expiresIn": 900 } }
```

The token is short-lived (15 minutes). Cache it and fetch a new one when it expires.

## Step 2: Check Auth State (Recommended)
`GET /api/<PROJECT_GUID>/auth/status` - returns auth state + URLs in one call.

Add `X-App-Token` header and `credentials: 'include'`.

**Response shapes:**
```jsonc
// Not logged in
{ "authenticated": false, "consented": false, "user": null, "loginUrl": "..." }

// Logged in, no consent
{ "authenticated": true, "consented": false, "user": null, "consentUrl": "..." }

// Fully authed
{ "authenticated": true, "consented": true, "user": { "guid", "displayName", "avatarUrl", "accountSlug" } }
```

Optional query param: `?permissions=N` (default `1` = IDENTITY). Use `5` for IDENTITY + AI.

## Lightweight Check
`GET /api/auth/me` (with `credentials: 'include'`) returns `{ user: { guid, displayName, avatarUrl, accountSlug } }` or `{ user: null }`. No app context - cannot return login/consent URLs.

## Client Code - Popup Flow (low-level - prefer the SDK above)
Shown only to explain what happens under the hood; new apps should not hand-roll it.
```js
async function checkAuth(appGuid, appToken) {
  const res = await fetch(\`https://a.gipity.ai/api/\${appGuid}/auth/status\`, {
    credentials: 'include',
    headers: { 'X-App-Token': appToken }
  });
  const data = await res.json();

  if (data.authenticated && data.consented) {
    return data.user; // Already authed
  }

  // Open login or consent popup
  const authUrl = (data.loginUrl || data.consentUrl) + '&mode=popup';
  const popup = window.open(authUrl, 'gipity_auth', 'width=450,height=600');
  return new Promise(resolve => {
    window.addEventListener('message', function handler(e) {
      if (e.data?.type === 'gipity_auth') {
        window.removeEventListener('message', handler);
        if (e.data.status === 'success') {
          // Re-check to get user profile
          checkAuth(appGuid, appToken).then(resolve);
        } else {
          resolve(null); // User denied
        }
      }
    });
  });
}
```

## Client Code - Redirect Flow
Navigates away from the app. Use `&return=<app_url>` so users come back after auth.
```js
const res = await fetch(\`https://a.gipity.ai/api/\${appGuid}/auth/status\`, {
  credentials: 'include',
  headers: { 'X-App-Token': token }
});
const data = await res.json();
if (!data.authenticated) {
  location.href = data.loginUrl + '&return=' + encodeURIComponent(location.href);
} else if (!data.consented) {
  location.href = data.consentUrl + '&return=' + encodeURIComponent(location.href);
}
```

## Complete Example (low-level REST - the SDK is simpler)
This raw-REST flow is reference only; for real apps prefer the SDK section above. Note it does **not** include the popup gesture/COOP handling the SDK provides.
```js
const API = 'https://a.gipity.ai';
const APP_GUID = '<PROJECT_GUID>';

// Step 1: Get app token
const tokenRes = await fetch(\`\${API}/api/token\`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ app: APP_GUID })
});
const tokenData = await tokenRes.json();
const appToken = tokenData.data.token;  // NOTE: .data.token, not .token

// Step 2: Check auth status
const authRes = await fetch(\`\${API}/api/\${APP_GUID}/auth/status\`, {
  credentials: 'include',
  headers: { 'X-App-Token': appToken }
});
const auth = await authRes.json();

if (!auth.authenticated) {
  // Open login popup
  const popup = window.open(auth.loginUrl + '&mode=popup', 'gipity_auth', 'width=450,height=600');
} else if (!auth.consented) {
  // Open consent popup
  const popup = window.open(auth.consentUrl + '&mode=popup', 'gipity_auth', 'width=450,height=600');
} else {
  // Step 3: Call an authenticated function
  const res = await fetch(\`\${API}/api/\${APP_GUID}/fn/my_function\`, {
    method: 'POST',
    credentials: 'include',
    headers: { 'Content-Type': 'application/json', 'X-App-Token': appToken },
    body: JSON.stringify({ param1: 'value' })
  });
  const result = await res.json();
}
```

## Common Mistakes
- **Reading `response.token` instead of `response.data.token`** - the token endpoint wraps its response in a `data` object
- **Forgetting `credentials: 'include'`** - without this, the session cookie won't be sent on cross-origin requests to `a.gipity.ai`
- **Using the project GUID as the token** - the GUID identifies your app, but you still need to call `POST /api/token` to get an actual bearer token
- **Using relative URLs** - app code runs on `app.gipity.ai` or `dev.gipity.ai`, so API calls must use the full URL `https://a.gipity.ai/...`
