<!-- AANCER Developer Reference (English): every field, limit and error code, part 13 of 16. All parts: https://aancer.ai/dev/llms.txt -->

## Sign-in by one-time code

Use `sso.mode: "code"` when your app has its own server and needs to know who the user is. The flow is OAuth 2.0 authorization code with PKCE (S256).

```text
your server            your page (frame)            AANCER shell            AANCER API
    | 1 PKCE pair            |                            |                        |
    |-- challenge ---------->|                            |                        |
    |                        |-- hello + codeChallenge -->|                        |
    |                        |<-- hello-ack (sso.code) ---|                        |
    |<-- code ---------------|                            |                        |
    |-- 3 POST /api/apps/oauth/token (Basic appId:secret, code, verifier) -------->|
    |<-- access_token (5 minutes) -------------------------------------------------|
    |-- 4 POST /api/apps/introspect (Basic appId:secret, token) ------------------>|
    |<-- active, sub, email, name, workspaceId, role ------------------------------|
```

### 1. Make a PKCE pair on your server

The verifier is 43 to 128 characters of `[A-Za-z0-9._~-]`. The challenge is base64url(sha256(verifier)), exactly 43 characters. Keep the verifier on the server. Send only the challenge to the page.

```js
import { randomBytes, createHash } from 'node:crypto';
const verifier = randomBytes(32).toString('base64url');                       // 43 characters
const challenge = createHash('sha256').update(verifier).digest('base64url');  // 43 characters
```

### 2. Get the code in the page

Send `hello` with `codeChallenge`. The `hello-ack` carries `sso.code`. The code is valid for 60 seconds and works once. Post it to your own server.

### 3. Redeem the code on your server

```http
POST https://aancer.example.com/api/apps/oauth/token
Authorization: Basic base64(<app id>:<app secret>)
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&code=<code>&code_verifier=<verifier>
```

JSON bodies are also accepted. The body must be under 4 kB. Answer:

```json
{ "access_token": "...", "token_type": "Bearer", "expires_in": 300, "scope": "profile workspace", "session_id": "..." }
```

### 4. Check the token on every request

```http
POST https://aancer.example.com/api/apps/introspect
Authorization: Basic base64(<app id>:<app secret>)
Content-Type: application/json

{ "token": "<access_token>" }
```

Answer when valid:

```json
{ "active": true, "token_type": "Bearer", "client_id": "shift-planner", "aud": "shift-planner",
  "sub": "u_123", "email": "jane@example.com", "name": "Jane Doe", "workspaceId": "ws-ops", "role": "Member",
  "scope": "profile workspace", "scopes": ["profile", "workspace"], "sid": "...", "appId": "shift-planner",
  "exp": 1763640000, "iat": 1763639700 }
```

Otherwise `{ "active": false, "reason"? }` with `reason` `revoked`, `ended`, `expired` or `legacy_disabled`. A wrong or missing app secret gets `401 APP_INTROSPECT_UNAUTHORIZED`; after 20 failed attempts within 60 seconds from one address, `429`. You may cache a positive answer for up to 30 seconds. A token becomes inactive after logout, a password change, a change of the user's access, a withdrawn approval, a retired or updated pack, or about 150 seconds after the AANCER frame stops sending its heartbeat (for example after the tab is closed).

### 5. Renew

When introspection says inactive and the user is still in the frame, make a new PKCE pair and call `authorize` through the bridge with the new challenge. Redeem the new code. A new code replaces the previous one; a session can request up to 10 codes in 5 minutes. A token obtained with a code lives at most 600 seconds.

If your server repeats the identical token request within 60 seconds (for example because it lost the answer), it gets a new token, the previous one is revoked and the session stays. Any other reuse of a code ends the user's app session with `code_replayed`.

### Server example (Node.js, no dependencies)

```js
// server.mjs (excerpt): redeem the code and read the user
const PLATFORM = process.env.PLATFORM_ORIGIN;          // https://aancer.example.com
const APP_ID = process.env.APP_ID;                     // shift-planner
const APP_SECRET = process.env.APP_SECRET;             // from "Create app secret"
const basic = 'Basic ' + Buffer.from(`${APP_ID}:${APP_SECRET}`).toString('base64');

async function redeem(code, verifier) {
  const res = await fetch(`${PLATFORM}/api/apps/oauth/token`, {
    method: 'POST',
    headers: { Authorization: basic, 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({ grant_type: 'authorization_code', code, code_verifier: verifier }),
  });
  if (!res.ok) throw new Error(`token ${res.status}`);
  return res.json();                                   // { access_token, expires_in, ... }
}

async function introspect(token) {
  const res = await fetch(`${PLATFORM}/api/apps/introspect`, {
    method: 'POST',
    headers: { Authorization: basic, 'Content-Type': 'application/json' },
    body: JSON.stringify({ token }),
  });
  return res.json();                                   // { active, sub, email, name, ... }
}
```

The full server, with sessions and the required headers, is in the examples repository under `examples/apps/shift-planner`.

### Session end

The shell sends `{ type: "session", state: "revoked", reason }` when the app session ends. Reasons: `logout`, `membership_changed`, `access_changed`, `retired`, `withdrawn`, `approval_withdrawn`, `app_updated`, `code_replayed`, `password_changed`, `password_reset`, `not_licensed`. Clear your own session and show a short message.

## Full examples

### App with sign-in, for one workspace

```json
{
  "v": 2,
  "kind": "bundle",
  "id": "acme.shift-planner",
  "version": "2.0.0",
  "title": "Shift planner",
  "publisher": { "name": "Acme Example Ltd", "keyId": "pub-0123456789ab" },
  "requires": { "platform": ">=1.0.0" },
  "parameters": [ { "id": "target_workspace", "type": "workspace", "label": "Workspace", "required": true } ],
  "items": [
    {
      "kind": "app",
      "schemaVersion": 2,
      "id": "shift-planner",
      "scope": "workspace",
      "workspace": "{{param.target_workspace}}",
      "spec": {
        "id": "shift-planner",
        "title": "Shift planner",
        "icon": "Clock",
        "group": "Operations",
        "order": 30,
        "url": "https://planner.example.com/?ws={{workspace}}",
        "origin": "https://planner.example.com",
        "sso": { "mode": "code", "scopes": ["profile", "workspace"] },
        "capabilities": ["read:me", "read:dataset:shift_plan", "write:dataset:shift_requests", "navigate", "notify"],
        "egress": { "hosts": [] },
        "embed": { "sandbox": ["allow-scripts", "allow-forms", "allow-same-origin"] }
      }
    }
  ]
}
```

### App for every workspace, with a Home card and a navigation link

```json
{
  "v": 2, "kind": "bundle", "id": "acme.ops-apps", "version": "1.0.0", "title": "Operations apps",
  "publisher": { "name": "Acme Example Ltd", "keyId": "pub-0123456789ab" },
  "requires": { "platform": ">=1.0.0" },
  "items": [
    { "kind": "app", "schemaVersion": 2, "id": "shift-planner", "scope": "install",
      "spec": { "id": "shift-planner", "title": "Shift planner", "icon": "Clock", "group": "Operations", "order": 30,
        "url": "https://planner.example.com/embed?ws={{workspace}}", "origin": "https://planner.example.com",
        "sso": { "mode": "code", "scopes": ["profile", "workspace"] },
        "capabilities": ["read:me", "read:dataset:shift_plan", "navigate", "notify"],
        "egress": { "hosts": [] },
        "embed": { "sandbox": ["allow-scripts", "allow-forms", "allow-same-origin"] } } },
    { "kind": "card", "schemaVersion": 1, "id": "shift-card", "scope": "install",
      "spec": { "id": "shift-card", "title": "Shift planner", "body": "Plan next week's shifts.", "href": "app:shift-planner", "icon": "Clock", "order": 10 } },
    { "kind": "link", "schemaVersion": 1, "id": "hr-intranet", "scope": "install",
      "spec": { "id": "hr-intranet", "label": "HR intranet", "url": "https://intranet.example.com/hr", "group": "Operations", "order": 90, "openIn": "new-tab" } }
  ]
}
```

`link` fields: `id`, `label` (1 to 80), `url` (https), `icon`, `group` (40), `order`, `openIn` (`new-tab` only). `card` fields: `id`, `title` (1 to 80), `body` (1 to 280, plain text, no `<` or `>`), `href` (`app:<id>`, `dashboard:<id>` or an https URL, at most 2048 characters), `icon`, `group`, `order`. Home shows up to 6 cards.

### Writing rows from the app

```js
const bridge = await AancerBridge.connect({ platformOrigin: PLATFORM });
await bridge.call('write:dataset', {
  datasetId: 'shift_requests',
  mode: 'append',
  rows: [{ employee: 'u_123', date: '2026-12-01', shift: 'early', note: 'Swap with late shift' }],
});
await bridge.call('notify', { text: 'Your request was sent.' });
await bridge.call('navigate', { path: '/dashboards/shift-overview' });
```

The dataset `shift_requests` must exist in the workspace with matching columns. Ship it in the same pack as a `dataset` item (see [Dashboards](/developers/dashboards)).

## Where the app shows

- **Navigation**: under **Dashboards**, in the group named by `group`, sorted by `order` and then title. The page address is `/dashboards/app/<id>`.
- **Home**: through a `card` item with `"href": "app:<id>"`.
- A workspace-scoped app shows only in its workspace. An install-scoped app shows in every workspace.
- Users need the permission "Open embedded apps" (`apps.view_own`).

## Install and approve

### In the UI

1. **Platform Settings > Extensions > Trust keys > Add trust key**, once per publisher.
2. **Import pack**, then **Activate**, and pick the workspace.
3. Open the pack and choose **Manage app**, then **Approve**. The administrator sees and approves the origin, every capability and the identity scopes.
4. **Create app secret**. It is shown once. Give it to the person who runs your app server, for example as the `APP_SECRET` environment variable.
5. Users open the app from the Dashboards navigation.

The activation also runs the frame check. A warning `APP_EMBED_REFUSED` names the reason: `no_csp` (no `frame-ancestors`), `not_allowed` (AANCER is not among the sources), `xfo` (an `X-Frame-Options` header blocks framing), `unreachable` (the app did not answer) or `egress` (the installation's network rules do not allow the origin).

### With the REST API

Every app manage call (approve, secret, withdraw, frame check, extra hosts) carries the app's `workspaceId`.

| Step | Call | Permission |
|---|---|---|
| Add trust key | `POST /api/extensions/trust-keys {keyId, label, publicKeyPem}` | `extensions.manage` |
| Import | `POST /api/extensions/packs/import` (raw bytes) | `extensions.manage` |
| Activate | `POST /api/extensions/packs/{packId}/activate {version, parameters: {target_workspace: "ws-ops"}}` | `extensions.manage` or `extensions.manage_own` |
| List apps | `GET /api/apps?workspaceId=ws-ops` | `apps.view_own` |
| Approve | `POST /api/apps/{id}/approve {workspaceId?, origins: [origin], capabilities: [...], scopes: [...]}` | `apps.manage_own` in the workspace, or `extensions.manage` for install-scoped apps |
| Create or rotate the secret | `POST /api/apps/{id}/introspect-secret/rotate` returns `201 {secret, previousValidUntil}` | same as approve |
| End the previous secret now | `POST /api/apps/{id}/introspect-secret/previous/end` | same |
| Withdraw approval | `POST /api/apps/{id}/approval/withdraw` | same |
| Run the frame check again | `POST /api/apps/{id}/embed-check/run` | same |
| Allow or remove an extra host | `POST /api/apps/{id}/egress/approve {host}`, `DELETE /api/apps/{id}/egress/{host}` | same |

After a rotation the previous secret stays valid for one hour by default, so you can update your server without downtime.

### Updates

Bump the pack `version`. A new origin, a new capability or a new identity scope must be approved again. Fewer or equal requests need no new approval. Open sessions of the old version end with `app_updated`. Retiring the pack removes approvals, the secret and network rules; a later pack with the same app id starts unapproved.

### Testing

Import and activate the pack in an EVAL or test installation. Open the app, then check: the frame loads (header correct), `hello-ack` arrives (origin correct), each `call` returns `ok: true` (capability approved and user permission present). For sign-in apps, check that your server gets `active: true` from introspection.

Next part: https://aancer.ai/dev/parts/reference/14-common-errors.md
