## Bridge protocol The bridge is `postMessage` between your page (the frame) and the AANCER shell (the parent window). Rules for your page: - Post to `window.parent` with the exact AANCER origin as `targetOrigin`. Never `*`. - Accept a message only when `event.origin` is the AANCER origin and `event.source === window.parent`. - Every message is an object with `v: 1` and a string `id` that you choose. Answers carry the same `id`. - Send `hello` within 10 seconds of loading, or the shell shows a "no hello" note. ### Messages | Direction | Message | Answer | |---|---|---| | app to shell | `{ v: 1, id, type: "hello", protocol: "aancer-bridge/2", codeChallenge? }` | `{ v: 1, id, type: "hello-ack", protocol, nonce, capabilities, user, sso }` | | | | `{ type: "hello-nack", code: "BRIDGE_PROTOCOL_MISMATCH", expected }` when the protocol does not match | | app to shell | `{ v: 1, id, type: "call", nonce, op, args }` | `{ v: 1, id, type: "result", ok: true, data }` or `{ v: 1, id, type: "result", ok: false, code }` | | shell to app | `{ v: 1, id, type: "session", state: "revoked", reason }` | none | The `nonce` from `hello-ack` goes into every `call`. In `hello-ack`: - `capabilities`: the capabilities granted to this session. - `user`: `{ displayName, locale }` with the `profile` scope, otherwise `{ locale }`. For display only. - `sso`: `{ mode: "code", code, expiresIn }` when you sent a `codeChallenge`; `{ mode: "code" }` when you did not; `{ mode: "code", error }` on a problem; `{ mode: "none" }` for apps without sign-in. ### Operations | `op` | `args` | `data` | Capability | |---|---|---|---| | `read:me` | none | with `profile`: `sub`, `email`, `name`; with `workspace`: `workspaceId`, `role` | `read:me` | | `read:dataset` | `{ datasetId, limit?, cursor? }`. `limit` default 200, max 500 | `{ rows, nextCursor, total }` | `read:dataset:` | | `write:dataset` | `{ datasetId, mode, rows }`. `mode` is `append` or `upsert`; `rows` is a non-empty array | `{ written, datasetId }` | `write:dataset:` | | `query:model` | `{ modelId, query? }`. `query` is a model query (see [Dashboards](/developers/dashboards)) | the query result | `query:model:` | | `navigate` | `{ path }`, matching `^/[a-z0-9\-/]*$`, for example `/dashboards/sales-overview` | `null` | `navigate` | | `notify` | `{ text }`, cut to 200 characters and prefixed with the app title | `null` | `notify` | | `authorize` | `{ codeChallenge }` | `{ code, expiresIn }` | `sso.mode: "code"` | Writes go through the same path as a workflow Publish step: column checks, quotas, and the `dataset.rows.published` event. So a hook can react to rows your app writes. ### A minimal bridge client ```js // bridge-min.js: hello plus one call, no dependencies function connect(platformOrigin, codeChallenge) { const pending = new Map(); let nonce = null; const TIMEOUT_MS = 10000; // the shell does not answer a malformed message window.addEventListener('message', (event) => { if (event.origin !== platformOrigin || event.source !== window.parent) return; const msg = event.data; if (!msg || msg.v !== 1) return; if (msg.type === 'session' && msg.state === 'revoked') { onEnd(msg.reason); return; } const p = pending.get(msg.id); if (p) { pending.delete(msg.id); p(msg); } }); function send(msg) { return new Promise((resolve, reject) => { const timer = setTimeout(() => { pending.delete(msg.id); reject(new Error('BRIDGE_TIMEOUT')); }, TIMEOUT_MS); pending.set(msg.id, (answer) => { clearTimeout(timer); resolve(answer); }); window.parent.postMessage(msg, platformOrigin); }); } const newId = () => crypto.randomUUID(); return send({ v: 1, id: newId(), type: 'hello', protocol: 'aancer-bridge/2', codeChallenge }) .then((ack) => { if (ack.type !== 'hello-ack') throw new Error(ack.code || 'HELLO_REFUSED'); nonce = ack.nonce; return { capabilities: ack.capabilities, user: ack.user, sso: ack.sso, call: (op, args) => send({ v: 1, id: newId(), type: 'call', nonce, op, args }) .then((r) => { if (!r.ok) throw new Error(r.code); return r.data; }), }; }); } function onEnd(reason) { document.body.textContent = 'Session ended: ' + reason; } ``` ## 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(:) Content-Type: application/x-www-form-urlencoded grant_type=authorization_code&code=&code_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(:) Content-Type: application/json { "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:`, `dashboard:` 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/`. - **Home**: through a `card` item with `"href": "app:"`. - 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`). Next part: https://aancer.ai/dev/parts/pages/17-install-and-approve.md