{
  "name": "app-auth-client",
  "title": "App API - Sign-in Client Code",
  "description": "Sign-in client code for web apps: the Gipity.auth SDK (signIn, user, signOut, onChange), popup vs redirect, verifying a signed-in page with page inspect --auth, and the low-level REST flow (app token, auth/status)",
  "guid": "sk_plat_aucl",
  "category": "App services",
  "requiredTools": [],
  "content": "# App API - Sign-in Client Code\n\nThe 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.\n\n## Client Code - use the SDK (do this)\nLoad 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.\n\n```html\n<script crossorigin=\"anonymous\" src=\"https://media.gipity.ai/client/v1/gipity.js\"></script>\n<gipity-signin app-guid=\"<PROJECT_GUID>\" permissions=\"1\"></gipity-signin>\n```\n\nOr wire your own button:\n\n```js\nGipity.auth.configure({ appGuid: '<PROJECT_GUID>' });   // permissions defaults to 1 (identity only)\nsigninBtn.addEventListener('click', async () => {\n  const user = await Gipity.auth.signIn(); // opens popup, handles login + consent\n  if (user) showApp(user); else showSignedOut();\n});\n// On load, reflect any existing session (null if not signed in / not consented):\nconst me = await Gipity.auth.user();\nif (me) showApp(me);\n```\n\n**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`.)\n\n**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`.\n\nOnce 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.\n\n**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:\n\n```js\nconst off = Gipity.auth.onChange((user) => {\n  if (user) showApp(user); else showSignedOut();\n});\n// off();  // unsubscribe when you no longer care\n```\n\nThe 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.)\n\n### Verifying sign-in behind the login wall (`--auth`)\nPass `--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:\n\n```bash\ngipity page inspect \"https://dev.gipity.ai/<acct>/<app>/\" --auth          # inspect the signed-in page\ngipity page screenshot \"https://dev.gipity.ai/<acct>/<app>/\" --auth        # capture the members-only UI\ngipity page eval \"https://dev.gipity.ai/<acct>/<app>/\" --auth \"App.commands().length\"   # drive signed-in app code\n```\n\nHow 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**.\n\n**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.\n\nScope: `--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.\n\n### Signing out\nWire 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.\n\n```js\nsignoutBtn.addEventListener('click', async () => {\n  await Gipity.auth.signOut();\n  showSignedOut();          // re-render header + view for the signed-out state\n});\n```\n\nDon'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.\n\n## How It Works\nUsers logged into Gipity already have a session cookie on `.gipity.ai`. Your app needs two things:\n1. 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.\n2. `credentials: 'include'` on all fetch calls (sends the user's session cookie cross-origin)\n\nYour 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.\n\n## Step 1: Get an App Token\n`POST https://a.gipity.ai/api/token` with your project GUID.\n\n```js\nconst res = await fetch('https://a.gipity.ai/api/token', {\n  method: 'POST',\n  headers: { 'Content-Type': 'application/json' },\n  body: JSON.stringify({ app: '<PROJECT_GUID>' })\n});\nconst json = await res.json();\nconst appToken = json.data.token;  // IMPORTANT: .data.token, NOT .token\n```\n\n**Response shape:**\n```json\n{ \"data\": { \"token\": \"eyJ...\", \"expiresIn\": 900 } }\n```\n\nThe token is short-lived (15 minutes). Cache it and fetch a new one when it expires.\n\n## Step 2: Check Auth State (Recommended)\n`GET /api/<PROJECT_GUID>/auth/status` - returns auth state + URLs in one call.\n\nAdd `X-App-Token` header and `credentials: 'include'`.\n\n**Response shapes:**\n```jsonc\n// Not logged in\n{ \"authenticated\": false, \"consented\": false, \"user\": null, \"loginUrl\": \"...\" }\n\n// Logged in, no consent\n{ \"authenticated\": true, \"consented\": false, \"user\": null, \"consentUrl\": \"...\" }\n\n// Fully authed\n{ \"authenticated\": true, \"consented\": true, \"user\": { \"guid\", \"displayName\", \"avatarUrl\", \"accountSlug\" } }\n```\n\nOptional query param: `?permissions=N` (default `1` = IDENTITY). Use `5` for IDENTITY + AI.\n\n## Lightweight Check\n`GET /api/auth/me` (with `credentials: 'include'`) returns `{ user: { guid, displayName, avatarUrl, accountSlug } }` or `{ user: null }`. No app context - cannot return login/consent URLs.\n\n## Client Code - Popup Flow (low-level - prefer the SDK above)\nShown only to explain what happens under the hood; new apps should not hand-roll it.\n```js\nasync function checkAuth(appGuid, appToken) {\n  const res = await fetch(\\`https://a.gipity.ai/api/\\${appGuid}/auth/status\\`, {\n    credentials: 'include',\n    headers: { 'X-App-Token': appToken }\n  });\n  const data = await res.json();\n\n  if (data.authenticated && data.consented) {\n    return data.user; // Already authed\n  }\n\n  // Open login or consent popup\n  const authUrl = (data.loginUrl || data.consentUrl) + '&mode=popup';\n  const popup = window.open(authUrl, 'gipity_auth', 'width=450,height=600');\n  return new Promise(resolve => {\n    window.addEventListener('message', function handler(e) {\n      if (e.data?.type === 'gipity_auth') {\n        window.removeEventListener('message', handler);\n        if (e.data.status === 'success') {\n          // Re-check to get user profile\n          checkAuth(appGuid, appToken).then(resolve);\n        } else {\n          resolve(null); // User denied\n        }\n      }\n    });\n  });\n}\n```\n\n## Client Code - Redirect Flow\nNavigates away from the app. Use `&return=<app_url>` so users come back after auth.\n```js\nconst res = await fetch(\\`https://a.gipity.ai/api/\\${appGuid}/auth/status\\`, {\n  credentials: 'include',\n  headers: { 'X-App-Token': token }\n});\nconst data = await res.json();\nif (!data.authenticated) {\n  location.href = data.loginUrl + '&return=' + encodeURIComponent(location.href);\n} else if (!data.consented) {\n  location.href = data.consentUrl + '&return=' + encodeURIComponent(location.href);\n}\n```\n\n## Complete Example (low-level REST - the SDK is simpler)\nThis 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.\n```js\nconst API = 'https://a.gipity.ai';\nconst APP_GUID = '<PROJECT_GUID>';\n\n// Step 1: Get app token\nconst tokenRes = await fetch(\\`\\${API}/api/token\\`, {\n  method: 'POST',\n  headers: { 'Content-Type': 'application/json' },\n  body: JSON.stringify({ app: APP_GUID })\n});\nconst tokenData = await tokenRes.json();\nconst appToken = tokenData.data.token;  // NOTE: .data.token, not .token\n\n// Step 2: Check auth status\nconst authRes = await fetch(\\`\\${API}/api/\\${APP_GUID}/auth/status\\`, {\n  credentials: 'include',\n  headers: { 'X-App-Token': appToken }\n});\nconst auth = await authRes.json();\n\nif (!auth.authenticated) {\n  // Open login popup\n  const popup = window.open(auth.loginUrl + '&mode=popup', 'gipity_auth', 'width=450,height=600');\n} else if (!auth.consented) {\n  // Open consent popup\n  const popup = window.open(auth.consentUrl + '&mode=popup', 'gipity_auth', 'width=450,height=600');\n} else {\n  // Step 3: Call an authenticated function\n  const res = await fetch(\\`\\${API}/api/\\${APP_GUID}/fn/my_function\\`, {\n    method: 'POST',\n    credentials: 'include',\n    headers: { 'Content-Type': 'application/json', 'X-App-Token': appToken },\n    body: JSON.stringify({ param1: 'value' })\n  });\n  const result = await res.json();\n}\n```\n\n## Common Mistakes\n- **Reading `response.token` instead of `response.data.token`** - the token endpoint wraps its response in a `data` object\n- **Forgetting `credentials: 'include'`** - without this, the session cookie won't be sent on cross-origin requests to `a.gipity.ai`\n- **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\n- **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/...`"
}
