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

## Quick start

1. Host your app at its own origin, for example `https://planner.example.com`. It must not be the same origin as AANCER.
2. Send this header on the embedded page, with your AANCER address:

   ```text
   Content-Security-Policy: frame-ancestors https://aancer.example.com
   ```

3. Write the pack manifest:

   ```json
   {
     "v": 2,
     "kind": "bundle",
     "id": "acme.shift-board",
     "version": "1.0.0",
     "title": "Shift board",
     "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-board",
         "scope": "workspace",
         "workspace": "{{param.target_workspace}}",
         "spec": {
           "id": "shift-board",
           "title": "Shift board",
           "icon": "Table",
           "group": "Operations",
           "order": 31,
           "url": "https://planner.example.com/board.html",
           "origin": "https://planner.example.com",
           "sso": { "mode": "none" },
           "capabilities": ["read:dataset:shift_plan"],
           "egress": { "hosts": [] },
           "embed": { "sandbox": ["allow-scripts", "allow-same-origin"] }
         }
       }
     ]
   }
   ```

4. In the page, say hello to the shell and read the dataset:

   ```js
   const PLATFORM = 'https://aancer.example.com';
   const bridge = await AancerBridge.connect({ platformOrigin: PLATFORM });
   const result = await bridge.call('read:dataset', { datasetId: 'shift_plan', limit: 100 });
   render(result.rows);
   ```

   `AancerBridge` is the small helper `bridge.js` from the examples repository (MIT licence). You can also write the messages yourself; see Bridge protocol below.

5. Sign the pack, import and activate it, then approve the app under **Manage app**. The app appears in the Dashboards navigation of that workspace.

## File layout

The pack carries only the manifest. Your app is a normal web application on your own server.

```text
acme-shift-planner/                # the pack
  manifest.json                    # one item of kind "app" (spec inline, or $ref to content/app.json)

shift-planner-app/                 # your app, deployed at https://planner.example.com
  server.mjs                       # serves the pages, redeems the sign-in code, checks tokens
  public/
    index.html                     # the embedded page
    app.js                         # your app logic
    bridge.js                      # bridge helper (frame side)
```

## Field reference

JSON Schema: [app.schema.json](https://aancer.ai/dev/schemas/app.schema.json). `$defs/link` and `$defs/card` cover navigation links and Home cards.

### App item

| Field | Type | Required | Rules |
|---|---|---|---|
| `kind` | string | yes | `"app"` |
| `schemaVersion` | integer | yes | `2` |
| `id` | string | yes | `^[a-z0-9][a-z0-9._-]{0,63}$`. Keep it equal to `spec.id` |
| `scope` | string | no | `workspace` (the app shows in one workspace) or `install` (every workspace). Default `install` |
| `workspace` | string | if scope is `workspace` | a workspace id or `{{param.<id>}}` |
| `spec` | object | yes | the app spec, inline or `{"$ref": "content/app.json"}` |

### App spec

| Field | Type | Required | Rules |
|---|---|---|---|
| `id` | string | yes | `^[a-z0-9][a-z0-9._-]{0,63}$`. Approvals, the app secret and network rules are keyed by it. One active pack per app id |
| `title` | string | yes | 1 to 80 characters. The navigation label and frame title |
| `icon` | string | no | at most 40 characters, an icon name such as `Clock`, `Table` or `Calendar` |
| `group` | string | no | at most 40 characters. The heading the app is listed under in the navigation |
| `order` | integer | no | 0 or more, default 100. Sorting is by group, order, then title |
| `url` | string | yes | https only, 9 to 2048 characters. No user or password, no `#fragment`. The only placeholder is `{{workspace}}` |
| `origin` | string | yes | exactly the origin of `url`: scheme, host and port, no trailing slash |
| `sso` | object | yes | `{ "mode": "code" or "none", "scopes"?: ["profile", "workspace"] }` |
| `capabilities` | string[] | yes | up to 20, unique. See Capabilities. `[]` is valid |
| `egress` | object | no | `{ "hosts": [...] }`: up to 20 extra hosts, `api.example.com` or `*.example.com`. Never `*` |
| `embed` | object | no | `{ "sandbox": [...], "height"?: "full" or "auto" }`: `sandbox` takes up to 5 of `allow-scripts`, `allow-forms`, `allow-same-origin`, `allow-popups`, `allow-downloads` |
| `csp` | object | no | `{ "connectSrc": [...] }`: up to 10 https origins the frame may connect to |
| `workspace` | string | no | a workspace id or `{{param.<id>}}` |

No other fields are allowed.

`url` rules in detail:

- `{{workspace}}` is replaced by the URL-encoded workspace id, but only if the `workspace` identity scope is approved. Otherwise it becomes an empty string.
- The host must not be a loopback, link-local or cloud metadata address. An IP address as host needs the operator to allow private origins; use a DNS name.
- The app origin must differ from the AANCER origin. Use a separate host name such as `planner.example.com`.

### Sign-in modes and scopes

| `sso.mode` | What happens | Default scopes |
|---|---|---|
| `code` | the frame receives a one-time code; your server redeems it and gets the user's identity | `profile`, `workspace` |
| `none` | no sign-in; the app uses the bridge only | none |

| Scope | Gives your app |
|---|---|
| `profile` | user id (`sub`), e-mail, display name |
| `workspace` | workspace id and the user's role label |

The role is a label for display. Do not use it to decide what a user may do. The bridge already applies the user's real permissions.

### Capabilities

| Capability | Lets the app | User permission needed in the workspace |
|---|---|---|
| `read:me` | read the user's identity (within the approved scopes) | none |
| `read:dataset:<id>` | read rows of dataset `<id>` | `datasets.view_own` |
| `write:dataset:<id>` | append or upsert rows in dataset `<id>` | `datasets.write_own` |
| `query:model:<id>` | run a query on BI model `<id>` | `dashboards.view_own` |
| `navigate` | move the user to another AANCER page | none |
| `notify` | show a short notice in AANCER | none |

Dataset ids in capabilities match `[a-z][a-z0-9_]{0,63}` (no dashes). Model ids match `[a-z][a-z0-9_.-]{0,63}`.

A capability works in a session only if it is declared in the manifest, approved by an administrator, and granted when the session starts.

### Sandbox

The frame is `<iframe src="<url>" sandbox="..." referrerpolicy="no-referrer" allow="">`. The default sandbox is `["allow-scripts", "allow-forms", "allow-same-origin"]`. Keep `allow-scripts` and `allow-same-origin`, or the bridge cannot work. Top-level navigation and modal dialogs are never allowed. Add `allow-popups` if your app opens links in a new tab, and `allow-downloads` if it offers file downloads.

## Your server's headers

The embedded page must allow AANCER to frame it:

```text
Content-Security-Policy: frame-ancestors https://aancer.example.com
```

- Accepted sources: the exact AANCER origin, its host, or `*.example.com` / `https://*.example.com` matching the AANCER host. `'none'` refuses.
- Do not send `X-Frame-Options: DENY` or `SAMEORIGIN`.
- The AANCER server checks this header when the app is activated and when it opens, with a HEAD request; it sends a GET only when HEAD answers 404 or 405. Redirects are judged as they are, not followed. The result is cached for 5 minutes per origin.

If the check fails because the header is missing or does not allow AANCER, an approved app opens in a new browser tab at its own URL instead of the frame. The bridge does not exist there. If the app cannot be reached, the user sees a retry card.

We also recommend `default-src 'self'`, `Cache-Control: no-store`, `X-Content-Type-Options: nosniff` and `Referrer-Policy: no-referrer`.

## 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:<id>` |
| `write:dataset` | `{ datasetId, mode, rows }`. `mode` is `append` or `upsert`; `rows` is a non-empty array | `{ written, datasetId }` | `write:dataset:<id>` |
| `query:model` | `{ modelId, query? }`. `query` is a model query (see [Dashboards](/developers/dashboards)) | the query result | `query:model:<id>` |
| `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; }
```

Next part: https://aancer.ai/dev/parts/reference/13-sign-in-by-one-time-code.md
