---
title: "Data requests and side effects"
description: "Import a module's shared sources and sends from its interface package."
modificationDate: "2026-11-30"
---

> ## Documentation index
> Fetch the complete documentation index at: https://exact.expo.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Data requests and side effects

<AgentInstructions>

## Submitting feedback

From the app's directory, read `bun exact.mjs feedback status`. Under `never`, keep no note.
Respect `EXACT_FEEDBACK=0` and do not change the policy.

Otherwise record specific, actionable feedback with:
`bun exact.mjs feedback note "Exact docs: https://exact.expo.dev/learn/contract-for-agents/data-requests-and-side-effects: <what was wrong or missing>"`

The note goes to Expo only as that status allows. Include no secrets or personal data.

</AgentInstructions>

Import a module's shared sources and sends from its interface package. A
platform's own names and types come from its implementation in both Contract
and TypeScript. Tracking consent, for example, is `@exact/tracking-consent/apple`:
elsewhere its status reads denied and unavailable, and its requests fail
`NotSupportedError` (LLP 1133.028 D12–D13).

An implementation import must name the implementation bound on the targets it
covers. An implicit replacement fails the bake; an explicit selection in
`app.json` makes the imported name use its declared default or refusal there.
The agent identifies an implementation's own name as
`<extension>.<name>#<import-path>` in `state.extensions` and `prefer extension`;
shared names keep `<extension>.<name>`.

`@exact/language-model` tools name functions in the data module's `tools`
export, as its own properties: a class's methods are its prototype's and are
not found. A handler receives the input object, `Store`, and `Storage`. Baking
checks literal declarations it can resolve in Contract and the data module's
runtime dependencies against that export and each declared input schema
(`language-model-tool-handler`). Type-only dependencies introduce no tools.
For Contract declarations, annotate `export const tools: LanguageModelTools`
with the generated type from `./app.contract.d.ts` to infer each handler's input.
Computed declarations, including objects that are mutated or escape to other
code, and a `tools` value whose type has only an index signature keep their
runtime checks.

Choose the mechanism from its lifetime:

| Requirement | Mechanism |
| --- | --- |
| Value follows query arguments | `resource result = source(args) as shape T` |
| One HTTP request read into a shape (a `GET`, a GraphQL query), with no data module | a `source` declared in `app.contract` ([Declared sources](https://exact.expo.dev/learn/contract-for-agents/data-requests-and-side-effects.md#declared-sources)) |
| Source needs changing context while the same kept answer is suitable at boot | `resource result = source(identity) with context as shape T` |
| Ask nothing until a condition holds (nothing selected, a query too short, a page not open) | `resource result = source(args) when cond as shape T`: idle while `cond` is false, asked again, forced, when it turns true |
| Explicit command with a reply | `mutation reply as shape T`, then `send reply = source(args)` |
| Re-request current resource arguments | `refresh result` |
| Refresh reads around a mutation | `mutation … refreshes resourceA, resourceB` |
| Show a write before its reply (optimistic) | `refreshes` on the mutation, and the source's `overlay` |
| React once to a settled mutation | `mutation … then actionName` |
| Writes that must all land, in order | `mutation … queue`: one in flight, later sends wait their turn |
| Writes a person may repeat before the first answers: a rename, a save | `mutation … parallel`: every send asked at once, each reply lands |
| Run once after a delay, while a condition holds (a toast, a debounce) | `task … when cond` with `after(ms, action)` |
| Repeat while a condition holds (a game tick, a pulse) | `task … when cond` with `every(ms, action)` |
| Act when a sheet or route opens (scroll the chosen item into view, load its draft) | In the screen component: `task reveal when active key=id` with `change(reveal)`; pass its activity and entry id as props |
| Pending indicator | `pending(resourceOrMutationName)` |
| "Loading" for a new question, not for a refresh | `not current(resourceName)`: false while it shows its placeholder, an answer to other call arguments, or a value kept across `when`'s idleness; a refresh of the same arguments leaves it true |
| Resource request failed without an answer | `failed(resourceOrMutationName)` |
| Why it failed, to branch on or show | `failure(resourceOrMutationName)`: `none`, or `some({ code, message, reason })`, `code` a domain refusal code when supplied, otherwise one of `offline`, `timeout`, `refused`, `shape`, `storage`, `error`; `reason` a Snapback refusal's code (`SLOT_FULL`), else `""` |
| Initial resource fallback | `else empty(field=constant)`, or `else source(values)` answered once at build |

A timer's step that reloads a resource runs the data module before the next frame, and
the frame waits for it: a module that rebuilds every row each second drops a frame of a
scrolling list each second, and `verify ios` says when the data module is in a late
frame's time. Rebuild only what the tick changed (keep last tick's rows, remake those
whose values moved), and leave out of the rows what the list does not show: a detail
screen's chart points belong to a resource the detail reads.

Resources read as their declared type. Mutations read as `option<T>` and start at
`none`, so a mutation's `T` is not itself an option. Do not treat a resource as an optional wrapper unless its declared type
itself is optional. A mutation reply is unwrapped with match.

An answer is held to its shape exactly: a field the shape does not declare, at any
depth, fails the resource as a thrown error does (TypeScript lets a spread such as
`{ ...row }` through). The view keeps its placeholder or last value and
`failed(x)` is true, so a banner on `failed` reads "unreachable" for what is a
shape mismatch: `state` names the field under `failed`, a CLI drive says so on
stderr, and a failing `expect` names it. Project a backend row onto the shape
field by field (`({ id: row.id, title: row.title })`).

`failure(x)` says why, for the view to branch on: `none` while `x` has not
failed, else `some` of a `Failure`, whose `code` is the nonempty domain `reason`, or the infrastructure class the same on every host (`docs/contract-grammar.md`), whose `message`
is the text `state.failed` shows (for a developer; it differs by host), and
whose `reason` is the string the source's error carried as `reason` (a
Snapback refusal's code), else `""`:

```contract
shape Item
  id: string

component Items
  resource items = loadItems() as shape Item[] else empty()
  derive banner = match failure(items) {
    case some(f) => f.code == "offline" ? "You're offline" : f.code == "shape" ? "This app needs an update" : "Couldn't load items",
    case none => ""
  }
  view
    column
      if banner != ""
        text banner testId="banner"
```

`offline`, `timeout`, `refused` and `storage` reach the view only when the
TypeScript module lets the `fetch` or storage rejection through (rethrows it, or
does not catch it): an error it makes of its own, one for an HTTP 500 among
them, is `error`. Its own error keeps its `message`, and `failure(x).message`
is that text. An error with a string `reason` property keeps that too, as
`failure(x).reason`: the snapback4 driver's `refused` throws a server's
refusal with its code there, so a query's `require … else NOT_MANAGER` is
`f.code == "NOT_MANAGER"` in the view. Mutations expose their latest admitted request failure too; a new send, assignment or success clears it. `bun scripts/agent.mjs web "fail fetch https://api…"` fails
those fetches as a lost connection, so the banner says "You're offline".

`with` takes one or more expressions, before `as shape`, and appends them to the
source's arguments. All arguments still trigger re-asks and identify live
requests. An eligible persisted answer admitted while the source is unready
at boot matches the call arguments alone; it can then stand while activation is
pending. Without `with`, every argument identifies that kept answer. Keep
account/tenant IDs and representation choices in the call, credentials below
the seam. Use `with` for a live event counter when an in-flight read should
land and the view should keep showing its answer during the follow-up.
Use `refresh` for an explicit reload or `refreshes` when a mutation changes
the resource. For a plain read, both force a new ask that joins nothing in flight. The default web JS target keeps no persisted resource answers
(LLP 1027.005).

Resource inputs are not asynchronous prerequisites, and HTTP request lanes do
not make resources depend on one another. A resource that reads another resource
uses its current displayed value; it does not wait for the upstream request to
succeed. While that request is pending, the value may be a retained answer, and
`not pending(upstream)` does not prove the latest request succeeded.

An authenticated source must await the app's shared current-session helper
before issuing its protected request. It must verify that the session authorizes
the principal named by the resource call. The helper and auth generation are app
code, not Exact APIs. The app must advance its auth generation and clear its
authorized principal whenever the principal changes or signs out. A request
that must belong to that auth attempt should take the generation as a resource
argument and return the principal and generation as fields in its answer. The
view should show private data only when both fields match the currently
authorized principal and generation. Checking only the owner cannot distinguish
signing into A, then B, then A again. A pending session resource, or one that is
merely not pending, does not prove authorization.

Before committing a refreshed session or shared owner-sensitive cache write,
recheck the generation at the commit point, including inside queued work. When
possible, partition persistent caches by owner so one owner's valid result can
still populate its cache after the view changes. If writes share a slot, guard
the commit by owner and auth generation. Do not suppress a valid per-owner cache
write only because another request became current. See the
[fetch/loading/error recipe](https://exact.expo.dev/recipes/fetch-loading-error.md) for retained-answer
and owner-gating patterns. The [REST starter](https://github.com/expo/exact/blob/41ded8c5ede0b2959ef0daa83b1ff78545dd4428/docs/patterns/rest/app.contract) uses
public development identities and does not implement an authenticated session
lifecycle.

The current request owns its answer; older replies cannot overwrite a newer
request. A newer send or an assignment drops a newest-wins mutation's in-flight
reply. It does not undo storage operations the source has already started; those
operations and any serialized storage chain behind them run to completion. Other
source work, such as a fetch, may be aborted when an answer is replaced (see the
[runtime reference](https://exact.expo.dev/reference/developer/generate-typescript-data-source-types.md#what-a-data-module-can-use)).

The action sending a newest-wins mutation (neither `queue` nor `parallel`) must
not also assign its slot to `none`. Assignments commit after sends, so the reset
can discard the new reply even when it appears first. Keep the mutation for its
reply and hide an old error while `pending(added)`, as the [after-a-write
recipe](https://exact.expo.dev/recipes/after-a-write.md) does. `none` means the slot contains no reply,
not that the write failed: use `failure(added)` for a request failure, and match
a shaped reply's `ok` or error for a domain refusal.

An action that sends one mutation twice on one path is refused
(`analyze-send-twice`) because the second send would forget the first reply, counting
the sends of the actions it calls. Every `if` is read as one that can run: two
sends are separate paths only as arms of one `if … else if … else` or `match`,
or in `if`s testing one unchanged name against different literals. A `match`
binder and an outer name it shadows are different values; testing them against
different literals does not make the paths separate. Send one
combined request, use a mutation per request, or declare the mutation `queue`
(LLP 1092) or `parallel` (LLP 1161.000). A
`queue` mutation (`mutation wrote as shape Ack queue then afterWrote`) keeps one
request in flight; every later send waits, in order, with the arguments it was
made with, and is asked after the reply before it and that reply's `then`, so
`then` runs once per reply, in send order. `pending(m)` is true while a send is
in flight or waits: send while it is pending, since `not pending(m)` means the
spinner is off, not that a send may be skipped. Assigning a queue's slot forgets
nothing — every reply still lands over it — so a mutation that must drop a late
reply (a session's sign-in) does not declare `queue`. At most 64 sends wait; the
65th refuses its action.

A `parallel` mutation (`mutation renamed as shape Ack parallel refreshes issues`)
asks every send when it is made, each its own request, and lands every reply in
whatever order they come: two renames, two saves of one form, two comments. A
reply lands in the slot unless a later send has already concluded, so a late
reply never overwrites a newer outcome; `failure(m)` shows a send's failure
unless a later send has already concluded, and an earlier send's success leaves
a later one's failure standing. `pending(m)` is true while any send is out, an
assignment forgets no request, at most 64 sends are in flight (the 65th refuses
its action), and it takes no `then` (`type-parallel-then`), since its replies
land in any order. Its source is called once per send, with several calls
outstanding: one that reads local storage, changes it and writes it back must
order its own work, or the mutation should be `queue`. Keep the default,
newest-wins, for a reply that must be droppable, such as a sign-in.

`refreshes` asks its resources again when the reply lands; a mutation the source
answers synchronously (without a request) has landed, so its resources are asked
in the sending commit. A send still in flight does not ask them; what it writes
shows before its reply only through the data module's `overlay`, if it exports
one (below). `then` is parameterless, runs once at the host's next clock advance
as a new commit (under the driver, an input's own answer's `then` before the
input's reply), reads the latest answer, does not run for a failure that brought
no answer, and cannot send its own mutation; to repeat, use a task (see
"Repeating while a condition holds"). Do not mistake the scheduling boundary for
a general async workflow or a per-reply event log.

A long poll (`/changes?since=…&wait=…`) is a stream too: add
`exactLongPoll: { cursor: 'since', from: 'seq' }` beside `exactStream`, and the
host asks again with each reply's cursor, skipping heartbeats and backing off
on failures (`docs/reference.md`, LLP 1016.000 D8). Re-read on each event with
`resource view = load() with live.seq`. If `load` returns the same single
plain HTTP request while a read is in flight, that reply lands with the newest arguments.
One ordinary read follows, however many events arrived during the first read.
An event during the follow-up earns another read after that reply.
Use revalidation or `no-store` if a cached response could hide the change.
A Rust source returning `Later(GET /state)` supports this rule. A plain
TypeScript `fetch` returns a separate promise on each ask and can still be
replaced mid-read. Keep a counter used only to signal freshness out of the
request. Putting it in the URL or a header makes each event replace the read.
If events arrive every 100 ms and reads take 200 ms, none lands until the
events stop. Uploads keep their once-per-identity record. A stream keeps its
existing rules for opening and replacing its transport.

A native app has 16 network stream slots. Long polls, event feeds, WebSockets, listeners and running uploads each use one. Use one poll carrying changes for all open documents. Desktop apps have 16 additional slots for streaming children.

A bidirectional WebSocket uses a resource's TypeScript
`fetch(url, { exactStream(event, socket) { … } })` (LLP 1016.000 D7).
Keep the handle in module state by resource identity; after its `open` event,
a mutation source can call `socket.send(textOrBytes)` or `socket.close(code,
reason)`. The mapper may also send and close on its own socket while it
answers `open` or a `message` (a subscribe, an Ack per frame), with no
`fetch`. A mapper may be `async` (inflating a frame with `DecompressionStream`,
splitting a large parse with `await scheduler.yield()`): later frames wait for
it, in order; work a synchronous mapper leaves running has no turns of its own,
so return a promise (an `async` mapper) to give its yields host turns; after
its first `await` it sends as an answer's turn does
natively and cannot send on the web. Sends run after the commit that settles
the mutation or the frame stands, in order, and have bounded admission. A mutation's source that
sends answers now or with a promise, and cannot also `fetch` (whichever
comes second refuses it). A resource's answer may send its own
request on its module's socket and await the reply, with no timer, and so
may a mutation whose source answers with a promise: what each turn of it
sends goes out once the commit that ran that turn stands, and stays sent if
it is let go (on the web build a later turn has no commit of its own: what it
sends goes as the turn ends, once the commit that asked the answer stands).
Refreshing or removing the
resource invalidates the old handle. **TypeScript on the web JS target,
macOS, iOS and Linux**; the wasm target and Rust sources remain
receive-only. See
[the reference](https://exact.expo.dev/reference/developer/generate-typescript-data-source-types.md) for bounds and events.

A large response needs a parse that yields. On native hosts each turn of an
answer has 100 ms of its own (CPU) time by default: from its call, or from the `fetch` or
storage step it awaited, until it next awaits one. A turn over that is refused;
a resource keeps its value and is asked again twice before it fails, so a parse
that passes its tests on a 300 KB thread fails on a 1 MB one. For an indivisible
call such as signing, `app.ts` can set one source’s budget with
`export const turnBudgets = { signOrder: 400 }` (100 to 1000 ms).
`await scheduler.yield()` (the web's [Prioritized Task
Scheduling](https://wicg.github.io/scheduling-apis/#dom-scheduler-yield)) ends
the turn, and the answer goes on in a new one with its own 100 ms. Yield every
few thousand items in a parse or tree walk:

```ts
type Node = { id: string; body: string };
type Post = { id: string; text: string };

export async function toPosts(nodes: Node[]): Promise<Post[]> {
  const posts: Post[] = [];
  for (let i = 0; i < nodes.length; i++) {
    if (i % 2000 === 1999) await scheduler.yield();
    posts.push({ id: nodes[i].id, text: nodes[i].body });
  }
  return posts;
}
```

The function that yields is `async`, and so is every caller that awaits it.
On the web the page has no such budget, and a yield lets it paint mid-parse.

## A TypeScript package for the data module

Source capture skips dot directories at every depth in the app and in
`typescript.sources` mounts, including `backend/.elixir_ls/` and `server/.venv/`.
Keep source code outside those directories. Source symlinks remain refused.

A package whose runtime entry is TypeScript source must also provide declaration
files for the type check. This applies to installed packages and linked `file:`
or workspace dependencies, including packages outside the app folder. The checker
stages package manifests and `.d.ts`, `.d.mts` and `.d.cts` files; it does not stage
package source (LLP 1027 D5). The bundler captures runtime code separately.

For example, a package with `index.ts` and `index.d.ts` can export:

```json
{
  "name": "my-data-helper",
  "type": "module",
  "exports": {
    ".": { "types": "./index.d.ts", "default": "./index.ts" }
  }
}
```

Put `types` before `default`. Supply declarations for each imported subpath, and
make their imports resolve to declarations too. Keep declarations in step with
source: generate them with the package's own TypeScript configuration using
`declaration` and `emitDeclarationOnly`, or maintain them by hand for a small API.
A `module outside captured app` refusal naming a package's TypeScript source
means the checker reached source outside its stage; check that entry's declaration
export and its declaration imports. Moving the package into the app does not
supply the missing declarations.

## Declared sources

A source that is one HTTP request read into a shape is declared in the root
file, `app.contract`, and needs no data module (LLP 1162.001). Its lines are
`fetch()`'s ([the recipe](https://exact.expo.dev/recipes/declared-source.md) has whole examples):

```contract
shape Current
  temperature_2m: number

source weather(latitude: number, longitude: number) as shape Current
  url "https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&current=temperature_2m"
  pointer "/current"

component App
  resource now = weather(52.52, 13.41) as shape Current
  view
    text `${now.temperature_2m}°`
```

| Line | Meaning |
| --- | --- |
| `url "…"` | Required. `{param}` is the argument as text (a `string`, `number` or `bool`), percent-encoded as RFC 6570 encodes it. The origin is written out before any `{…}`. |
| `method "…"` | `GET` (the default), `POST`, `PUT`, `PATCH` or `DELETE`. |
| `header "Name" "value"` | One header. The value may name a parameter, `{param}`, and a secret the data module keeps, `{secret:name}`; a header the browser sets itself (`Cookie`, `Origin`, …) is refused. |
| `body json` | The parameters as one JSON object by name, `Content-Type: application/json`. |
| `graphql "…"` | A `POST` of `{"query": document, "variables": {param: value, …}}`; no `method` or `body` beside it. |
| `pointer "…"` | Where the answer is in the reply: an RFC 6901 JSON Pointer, `"/data/items"`; the whole reply when it is left out. |

- **The grant is the origin.** A declared source reaches its URL's origin and nothing
  else, on every host, with no `grants` line; an update that declares a new origin is a
  new binary, as a new grant is. A `{secret:name}` needs `secret.keep name` in the data
  module's grants; while the secret is absent nothing is sent and the resource fails
  with `refused`.
- **The answer is read field by field.** A field the shape doesn't declare is left out
  (unlike a data module's answer, which is held to its shape exactly), an absent or
  `null` `option` field is `none`, and anything else missing fails it with `shape`.
  Rename or compute in a `derive`.
- **A failure** is a TypeScript `fetch`'s that is let through: `offline`, `timeout` or
  `refused`, or `error` for a status outside 200–299, a reply that is not JSON, or a
  GraphQL `errors` (its first error's `extensions.code` is `failure(x).reason`).
- **Reads and writes.** A resource's request is a read: it overlaps others and a `GET`
  keeps the GET cache; `refresh` asks past it. A `send` to a declared source with
  another method, or a GraphQL mutation, is a write. Nothing is asked at build: a
  declared resource shows its `else`, or its shape's zero, until the launch's answer.
- **What stays in a data module:** token refresh, pagination across requests, offline
  queues and retries, an optimistic `overlay`, streams and sockets, uploads, form bodies,
  and an origin from `app.json`'s `env`. An app with both keeps `app.ts`, and with it
  the JavaScript engine on native hosts; an app whose sources are all declared has
  neither.

## Optimistic writes: the overlay

To show a write before its reply, the mutation declares `refreshes` and the data
module exports an `overlay`:

```contract
shape Item
  text: string

component List
  resource items = loadItems() as shape Item[]
  mutation added as shape Item refreshes items
  action add(text: string)
    send added = addItem(text)
  view
    column
      for item in items key=item.text
        text item.text
```

```ts
import type { Overlay } from './app.contract.d.ts';
type Item = { text: string };
export const overlay: Overlay = (source, args, answer, writes) => {
  if (source !== 'loadItems') return undefined;    // other resources show their answers
  const shown = [...(answer as Item[])];
  for (const w of writes) {
    if (w.source !== 'addItem') continue;
    const [text] = w.args as [string];
    if (shown.some(i => i.text === text)) continue; // the answer has it
    if (w.answered) w.keep();                       // the server has not caught up yet
    shown.push({ text });
  }
  return shown as never; // `Result<S>` cannot be narrowed from a generic `S`
};
```

From the send, derives and views read `items` as the overlay's value. Without an
overlay they read the answer, and the write shows only once a refreshed answer
has it. The runner calls `overlay` for each resource a write affects, with:

- `source` and `args`: the resource's source name and arguments. Resources can
  share a source with different arguments; check `args` when a write belongs to
  one of them.
- `answer`: the resource's current answer. Copy it rather than changing it.
- `writes`: the sends that affect it, in send order. Each has `id`, `mutation`
  (the mutation's name), `source` and `args` (the send's), `reply` once its reply
  has landed, and `answered`: its reply has landed and `answer` was asked after
  that, so `answer` should include it.

A write shows until the first answer asked after its reply landed. If that
answer does not include it yet (a server that is not read-after-write
consistent), call `keep()` on it to go on showing it. The runner does not ask
again on its own, so a kept write shows until a later answer (from `refresh`,
another write's reply, or new arguments) that the overlay does not keep it over.
Returning `undefined`, throwing, or returning a value outside the resource's
shape shows the answer and stops showing every answered write; the journal says
why for the last two.

A write that ends without landing stops showing in that commit, with no undo
code, and the resource is asked again: its reply fails, its wake expires, or a
newest-wins mutation's send is replaced by a newer send or an assignment to its
slot. If that ask fails, `failed(items)` is true and `items` keeps its last
answer. A `parallel` mutation's writes each show until their own reply and the
answer asked after it, and one's failure takes nothing else with it; the overlay
receives the writes that have landed, in the order they landed, then those still
out, in send order.

- The overlay runs synchronously inside the commit, so it cannot await, and it
  has no effects: `fetch`, storage, the store (`get` included), `native` and
  `crypto` (`crypto.getRandomValues()`, `crypto.randomUUID()` and every
  `crypto.subtle` call) refuse with an error naming the call, the same on every
  host: a call that returns a promise rejects, any other throws. The
  runner reuses its value while its inputs are unchanged, so compute it from
  them alone.
- Writes are not saved: after a relaunch or a reload only answers show, and a
  resource a write was showing in is asked again.
- A source whose module runs on a worker shows answers only, said once in the
  journal.
- A Rust source implements `DataSource::overlay`, returning
  `Ok(Some(Overlaid { value, keep }))`, or `Ok(None)` to show the answer.
- The agent's `state` shows what the overlay shows; `state.writes` lists the
  writes still showing, as `{ id, mutation, landed }`, when there are any.

A failed resource retains its value or placeholder, with `pending=false` and
`failed=true`. Argument changes, refresh, or successful answers clear the failure.
A domain error returned as a record is an answer and must be handled as data.

Infer the actual source interface from the Contract:

```sh
bun exact.mjs contract types app.contract -o app.contract.d.ts
bun exact.mjs contract rust app.contract -o /tmp/shapes.rs
```

Use those generated declarations with the existing TypeScript/Rust integration.
A mixed app imports `TypeScriptSources` and `TypeScriptAnswer` from
`app.contract.d.ts`; its `build_mixed_with` bake excludes Rust-owned providers.
Run `bun exact.mjs contract build app.contract` to generate and check that narrowed
declaration. Standalone `contract types` has no Rust roster; `Sources` always
describes the complete seam. See [the provider types](https://exact.expo.dev/reference/developer/generate-typescript-data-source-types.md).
A shape has no exported name in the `.d.ts`: name one by its source,
`type Recipe = Result<'recipe'>` (a list's element: `Result<'recipes'>[number]`;
an optional answer is `… | null`, so `NonNullable<Result<'find'>>`).
`app:/data`, `app:/cache` and `app:/tmp` exist on every host before a source
runs, so a file directly in one (`app:/data/notes.json`) needs no `mkdir`; a file
deeper down needs its folder first (`storage.fs.mkdir('app:/data/drafts')`, which
makes the folders above it too), or the write fails with `ENOENT`.
The [human guide's data-module section](https://exact.expo.dev/learn/contract-for-humans/writing-the-data-module.md)
has a complete `app.ts`: synchronous, `fetch` and SQLite sources, the grants
each needs (one per line: `['sqlite.open app:/data/books.db', 'net.fetch https://…'].join('\n')`;
`net.fetch` takes an `http` or `https` origin, `http://127.0.0.1:8080` too,
`net.fetch loopback` for a local helper process on any ephemeral port
(`127.0.0.0/8`, `[::1]`, or exact `localhost`, `http:` and `https:`, with no
`device.local-network` grant; `net.websocket loopback` does the same for `ws:`
and `wss:`, LLP 1016 D6), or a whole scheme, `net.fetch https:` (any host and
port, for a server the person names at run time; `net.websocket` takes `wss:` or
`ws:` the same way); on iOS
cleartext `http` reaches only a local host, and only with `app.json`'s
`host.ios.localNetworking` set, unless ATS is off (below); a device on the local
network the person names or the app finds is `net.fetch local-network` with
`device.local-network purpose.<key>`, whose text is the platform's prompt on macOS
and iOS ([recipe](https://exact.expo.dev/recipes/local-network.md)); the app's own `http` to any other
host, such as a server the person types in, needs each Apple platform's
`appTransportSecurity` (`host.macos`, `host.ios`) set to
`{ "allowsArbitraryLoads": true }`, which turns ATS off for every connection the
app makes, frames included, and which App Store review asks the app to justify;
an `iframe` of `http://` from a named host, or such a sub-resource of the app's
own `assets/` page, needs `host.macos.appTransportSecurity` or
`host.ios.appTransportSecurity` set to `{ "allowsArbitraryLoadsInWebContent": true }`,
which relaxes web views only (ATS lets a local-network IP address or a `.local` name through
without it, LLP 1020.001 §4 Q6, though on an iPhone those also ask for Local
Network access; non-LAN IPs such as Tailscale `100.64.0.0/10` or public IPs are still blocked
over plain `http://` unless served over HTTPS or permitted in development with
`allowsArbitraryLoads`), and how to drive it with storage. The macOS driver launches the assembled app
bundle, so its ATS policy also applies during drives. A path grant covers its path and what is below
it, by whole names: `sqlite.open app:/data` covers `app:/data/inbox-amy.sqlite`,
`sqlite.open app:/data/inbox` does not. A refused open names the file it wanted
and the grant line that would admit it.
A line of `app.ts`'s grants that begins with the word `development` is a development
build's only: a production bake (`EXACT_UPDATE_TRUST=production`, which an Apple
`--archive` or `--release` and a deploy set) leaves it out, and any other keeps it
without the word (`development device.calls purpose.calls`, Harmony's test call,
LLP 1133.033 §13 question 4). Only the build's copy of `app.ts` changes, so the
module's own `grants` constant is the build's, and the app can hide what the line
serves (Harmony's `testCallBuild` source). A Rust data crate's `grants()` can't mark
a line yet: the bake refuses one (`grant-development`). The bake's own trailing word
on a development build's `local-network` line (LLP 1133.036 D5) is another thing.
A token, a password or a key the module keeps is a secret, not a file: grant
`secret.keep <name>` (one line per name, `secret.keep signal.token`) and use
`store.set(name, value)`, `store.get(name)` (a string, or `null`) and
`store.forget(name)` in an answer (LLP 1018). It is the Keychain on Apple; on the
web, the page's `localStorage`, readable by any script on that origin; on Linux,
unencrypted files in the app's data directory, retained across launches (an app
without an ID keeps them in memory). A drive keeps it, by default,
only in a named `--storage` store (`EXACT_STORE=real` gives an Apple drive, on a Mac, a simulator or a phone, the Keychain a normal launch reads).

**Web refresh and session tokens belong in an HttpOnly, Secure cookie set by the
app's server, which the page never reads.** Follow [web sign-in tokens and
sessions](https://exact.expo.dev/recipes/web-sessions.md) for SameSite, credentialed fetch, CSRF, rotation
and logout, sharing the flow with native `secret.keep`. Inside an answer,
`exactHost()` returns `'web'` or `'native'` at run time; no per-build transport
setting is needed. Inside an answer, `exactProcess()` returns a frozen
`{ id: string }` for the current OS process natively (constant across
`deploy.activate: "immediate"` runtime replacements, dev reloads, OOM
retirements, and multiple windows in one process; fresh after a relaunch) or
the current browser document load on the web, letting crash marks distinguish
an in-process replacement from a process restart without clock arithmetic;
extensions and widgets run in separate OS processes and get their own `id`
(answers reading `exactProcess()` are never baked). This string store does not protect a web token from
injected scripts. See the browser's [cookie attributes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie).

A secret that only the person in front of the device may read (an account's token
behind Face ID) carries a policy on its line, `secret.keep token user-presence`
(`biometry-any`, `biometry-current-set`, `device-credential`), then `optional` when
the person chooses whether it is locked; the app grants `device.local-auth <purposeKey>`
and depends on `@exact/local-auth` (LLP 1133.010). Its value is never in the store:
`store.get` throws `InvalidAccessError` while it is locked, `await store.unlock(name,
{ reason })` shows the platform's sheet and answers the value, `store.has` and
`store.locked` say what is kept. `await store.protect(name)` turns an `optional` lock
on without a prompt on iOS, iPadOS, Android, and macOS builds provisioned for the
data-protection Keychain. It rejects without a prompt when locked secrets are unavailable.
For a switch that asks for confirmation, call `authenticate(reason=)` from
`@exact/local-auth` first and wait for it to succeed before calling `store.protect`.
The store's presence policy controls access to the secret.
`await store.unprotect(name, { reason })` shows the platform's sheet before turning
the lock off. `store.set` keeps every write in the name's state, a rotated token's too.
Keep the value out of every answer: an answer is kept and shown. The web keeps no
locked secret yet: a name that must be locked is refused there, and
`localAuthStatus().presenceSecrets` is false. Under the agent the sheet is a
`presence` ticket (`tap @presence allow`, `cancel`, `fail`,
`lockout`, `invalidated`), after Face ID's `permission` ticket while it is `prompt`.
The compiler accepting a source call does not provide its implementation. Check
its arguments, declared result, grants, storage access, and bake-time behavior.
Keep generated output out of version control. Use app-local sources for domain
formatting or algorithms beyond the finite standard roster.

A bake runs initial data work and packages first-frame values. A first-frame
value is not the answer: every host asks the TypeScript module again at launch,
natively once it loads after first pixel, even a source with no arguments
(`logs`: `<resource> shows its build-time answer until its source answers`, then
`<resource> answered: …`). A resource with an argument (one after `with` too) made
from `exactTime()`, through a derive, another resource or a state an action
assigns it (or writes under a condition on the date), gets no first-frame value, since the bake's date is unknown: it shows
its placeholder until the module answers with the launch's date, so a task waiting
on `lib.loaded` never adopts an answer stamped at 1970. Don't pass the clock into a
source whose answer doesn't depend on it, or its first frame waits for the module:
format times in Contract (`formatTime(at, time.utcOffset, "short")`). A `send` an action makes before the module loads (a
document opened at launch) waits for it, `pending` meanwhile (`logs`: `send <name>:
waits until the data source is ready`). Live requests run after that under host scheduling. Do not assume a secret store, disk database,
or authenticated network session is available while baking. See
[the data-module reference](https://exact.expo.dev/reference/developer/generate-typescript-data-source-types.md).

## Sign-in providers (`@exact/oauth`)

The `oauth` recipe is the code; this is each provider's configuration, as its
documentation requires (LLP 1146; the IDs are `packages/oauth/test/PROVIDERS.md`'s).

| Provider | Configuration |
|---|---|
| Google | `issuer: 'https://accounts.google.com'`, `issuerAliases: ['accounts.google.com']` (GOOG-2), `authorizationParams: { access_type: 'offline', prompt: 'consent' }` for a refresh token (GOOG-8). Grant `net.fetch https://oauth2.googleapis.com`, its token endpoint's origin (GOOG-1). An iOS client's callback is its reversed client ID, `com.googleusercontent.apps.<id>:/oauth2redirect` (GOOG-5); a desktop or web client needs its `clientSecret`, which is not secret (GOOG-4) |
| Microsoft Entra ID | `issuer: 'https://login.microsoftonline.com/common/v2.0'`, `issuerTemplate: true` (ENTRA-1), `offline_access` in `scopes`. Register the callback as "Mobile and desktop"; send no `clientSecret` (ENTRA-3). A web build's callback is registered as "Single-page application" (ENTRA-4) |
| Auth0 | `issuer: 'https://<tenant>.auth0.com/'`, the tenant's domain with a trailing slash (AUTH0-1); `offline_access`, with "Allow Offline Access" on the API (AUTH0-3); `authorizationParams: { audience }` for an API's token. With rotation's overlap period on, `retryLostRefresh: true` |
| Okta | `issuer`: the authorization server's issuer, `https://<org>.okta.com/oauth2/default` (OKTA-1); `offline_access` (OKTA-4); `retryLostRefresh: true` while refresh tokens rotate with a grace period (OKTA-6) |
| OneLogin | `issuer: 'https://<subdomain>.onelogin.com/oidc/2'` (ONELOGIN-1); no `offline_access`, which it refuses (ONELOGIN-2); `endedErrors: [{ error: 'invalid_request', status: 401 }]` (ONELOGIN-4) |
| GitHub | `endpoints: { authorization: 'https://github.com/login/oauth/authorize', token: 'https://github.com/login/oauth/access_token' }`, no `openid` (GH-1), `clientSecret` (GH-7), `commaScopes: true` (GH-5), `endedErrors: ['bad_refresh_token']` (GH-4). Its token endpoint does not answer a browser, so a web build needs a server (GH-8) |
| Salesforce | `issuer: 'https://login.salesforce.com'`, the `refresh_token` scope (SF-14); it sends no `expires_in`, so the expiry is learned from a 401 (SF-1) |
| Amazon Cognito | the endpoints are on the user pool's domain, not the issuer's: grant both origins (COGNITO-1) |
| ForgeRock (PingAM) | `issuer`: the realm's, `…/oauth2/realms/root/realms/<realm>`, as its discovery document names it. An app with its own sign-in screens answers the authentication tree (FR-1), then passes `signIn` an `authorize` that POSTs the authorization request with the SSO token (FR-2; below), natively only. A gateway that answers 403 for an expired access token: `expiredStatus: [401, 403]` (FR-4) |
| Sign in with Apple | not supported: its token exchange needs a server-signed client secret |

`signOut` forgets and revokes the session, but the browser keeps the
provider's own sign-in, so the next sign-in returns as the same account
without showing a page. To let the person choose another account,
`signOut(store, { endSession: true })` also opens the provider's end-session
endpoint (OpenID Connect RP-Initiated Logout 1.0): send it from a press,
register the callback as a post-logout redirect URI, and set
`logoutRedirectParam` for a provider that does not call that parameter
`post_logout_redirect_uri`. A browser step that does not finish still signs
out, answered `ok` with code `end_session` and a sentence in `error`. A later
end-session press retries that provider logout. The web reserves a blank
provider window synchronously at the press, then navigates it after sign-out
takes the session under its store lease and constructs the logout URL. Its
ID-token hint and revocation therefore always name the same login without
losing the press's browser activation. Until the provider logout succeeds or
a new sign-in replaces it, the store retains its endpoint and ID token under
the same secret lease; the app remains signed out. Entra and Cognito may
return from logout without `state`. A successful logout return carries no
`code`, `error`, `id_token` or `access_token` in its query or fragment. Its
state, when present, must occur once and match the request.
On Android and in the runner, a matching state addresses the return; a
sign-in takes a sign-in answer before a logout sharing its state. A return
without state and without a sign-in answer goes to the oldest logout at that
callback, whoever else waits; one without state that carries a sign-in answer
goes to nobody. On the web, the
logout's own popup addresses its return through its opener. Before navigating,
the glue also puts a fresh random identity in that popup's `sessionStorage`;
the callback reads and removes it. After severance, that identity addresses
the return to the live logout holding it. An addressed logout return carrying
a sign-in answer fails immediately with 502. An unaddressed broadcast carrying
a sign-in answer completes no logout, even if its state matches. No tab takes
a shared lock or reads another tab's state.
A request still held at the ten-minute bound answers 499 once, whether its
timer or a late return arrives first.

Revocation runs inside the same lease that removes the credential, before the
provider browser opens. Each token request has a 60-second host deadline, so
sign-in, refresh and another sign-out for the same key wait behind it. No reply,
a timeout, 429 or 5xx leaves the token for the next sign-out in the same data
module runtime; any other reply clears it. This is best effort: there is no
background retry and the debt is not stored in the secret, so a reload, restart
or runtime replacement ends those retries. Another browser tab may revoke the
same token again; RFC 7009 treats that as success. Recovery from an interrupted
secret update remains fail-closed and removes the whole secret, which can also
discard a retained provider-logout hint.

Every option, with what it does, is in `@exact/oauth`'s `index.d.ts`.

**Tokens outside HTTP.**

Use `provider.accessToken(store)` in data code when the intended API takes
its access token somewhere `provider.fetch` cannot reach: a third-party SDK,
or a message after a WebSocket opens, on a host whose mapper receives a
socket handle. Prefer `provider.fetch` for HTTP requests. An OpenID Connect
service such as Convex instead takes `provider.idToken(store)`, with that
service configured to trust the issuer and audience. An ID token is not an
API access token.

Like `idToken`, `accessToken` synchronously answers what the store holds now,
or `null` when signed out. It reads no clock and makes no refresh of its own.
When the service reports expiry (a socket's authentication failure or an SDK's
error), await `provider.refresh(store)`, check its `ok`, and ask for the token
again. This uses the same refresh as `provider.fetch` after an API refusal;
concurrent callers refreshing the same held token make one refresh. A failed
refresh that keeps the session leaves the old token; one that ends it leaves
`null`. Handle the failure before attempting authentication again.

Both tokens are credentials. Keep them in data code; never return them in
a Contract answer, put them in state, or log them. Answers are kept and
shown by the agent. The return types warn about this in their documentation;
they are ordinary strings, with no compiler warning or runtime filter that
prevents a credential from entering an answer (LLP 1018 D5, LLP 1157 D7).

With a token in hand, the caller owns where and how it is sent:

- Send it only to the API it was issued for, over an encrypted connection.
  `provider.fetch` checks the destination against `apis`; the getter cannot
  check what the caller or SDK does with the returned string.
- Never put it in a URL. [RFC 9700 §4.3.2](https://www.rfc-editor.org/rfc/rfc9700.html#section-4.3.2)
  prohibits passing access tokens by the URI query method described in
  [RFC 6750 §2.3](https://www.rfc-editor.org/rfc/rfc6750.html#section-2.3).
- Ask for the token again when authenticating or reconnecting. Do not hold
  a copy across a refresh or sign-out. The caller handles the service's
  authentication failure and reconnect protocol. `provider.fetch` still refuses
  `ws:` and `wss:`.

If the API requires a credential on the handshake URL, it refuses an
unauthenticated upgrade before `open`; a first message cannot authenticate it.
Use the ticket exchange:
call `provider.fetch(store, url, { method: "POST" })` over HTTPS for a short-lived,
single-use ticket, then open
`fetch('wss://…?ticket=…', { exactStream })` synchronously in a fresh source call.
Keep the ticket in data code and obtain a new one for each reconnect. See the
[socket-ticket recipe](https://exact.expo.dev/recipes/socket-ticket.md).

The following excerpt is only for an API that accepts the upgrade without a
credential, then accepts an `authenticate` message and reports expiry with
`token_expired`. It needs a mapper with a usable socket handle: worker-placed
TypeScript sources and the web's wasm target do not support this send path
(see `docs/reference.md`, socket sending). The app has checked that
`wss://api.example.com/live` is the intended API and granted `net.websocket`
for it. Add these sources to the app's `Sources` object:

```ts
live: (_args, store) => {
  let expired = false;
  return fetch('wss://api.example.com/live', {
    exactStream(event, socket) {
      if (event.type === 'open') {
        const token = provider.accessToken(store);
        if (token) socket.send(JSON.stringify({ type: 'authenticate', token }));
      }
      if (event.type === 'message' && event.data === 'token_expired') expired = true;
      return { expired };
    },
  });
},
renew: async (_args, store) => await provider.refresh(store),
```

When `live.expired` becomes true, the app sends the `renew` mutation. After
its successful answer, it refreshes the `live` resource to reconnect; the
next `open` asks for the token again and sends it as the first message.
The token never enters the URL, subprotocols or a Contract answer. Adapt the
message and refusal handling to the service; do not retry indefinitely.

**Development identity servers.** `issuer`, every `endpoints` URL and each
`apis` origin require HTTPS, except loopback (`localhost`, `127.0.0.1` or
`[::1]`). A refusal names the option, such as `endpoints.token` or `apis[2]`.
For a phone reaching your Mac over the LAN, serve the identity server and API
through HTTPS with a certificate the phone trusts, or an HTTPS tunnel. A
simulator can use the Mac's loopback server. Development builds keep this
HTTPS rule; they have no insecure-origin switch.

**Parameters chosen at the press.** Keep provider defaults in
`authorizationParams`; pass a login hint, connection or account-choice prompt
with the sign-in itself:

```ts
provider.signIn(store, { params: { login_hint: email, prompt: 'select_account' } });
```

`params` overrides those defaults for this request alone, including when
`authorize` sends it. The package still opens a prepared browser request
before awaiting anything. Both parameter maps refuse `response_type`,
`client_id`, `redirect_uri`, `scope`, `state`, `code_challenge`,
`code_challenge_method`, `nonce` and `max_age` with `TypeError`; the package
sets those fields or cannot validate what they ask for.

With `openid`, `signIn(store, { nonce })` sends an app-chosen, non-empty string
and checks the ID token against that exact value. Use a fresh value for each
sign-in. Omit it to let the package generate one. The option applies only to
that press, for a browser sign-in or `authorize`; raw parameter maps still
refuse `nonce`.

For flows the package does not cover, data code may use `openAuthSession`
and `authCallback` directly; their public declarations and rejection statuses
are in the generated `app.d.ts`. A callback must carry exactly one `state`
across its query and fragment, equal to the nonempty value supplied to
`openAuthSession`; duplicates are refused, including one in each. The full URL
returns to data code unchanged, including fragment parameters such as
`id_token` ([OIDC fragment responses](https://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse)). Keep callback URLs
in data code: they can contain credentials.

On the web, closing the sign-in popup is not reported as cancellation:
a provider's Cross-Origin-Opener-Policy can make an open popup appear closed.
The session waits for its callback, supersession, or a ten-minute bound (499
`cancelled`). Returning focus to the app does not end it. A new sign-in on the
same request target supersedes the previous one. Offer an enabled Cancel while
sign-in is pending: assigning `signed = none` to the mutation holding the
sign-in releases its request and clears `pending(signed)`, so the person can
retry at once. See `apps/auth-fixture/app.contract`.

**An app's own sign-in screens.** A provider that lets an app sign the person
in with its own screens (ForgeRock's authentication trees) still issues an
authorization code. The app sends the authorization request as the provider
documents and answers where it was redirected; the package checks it and does
the rest. The source that answers the tree's last step keeps its SSO token in
the module and answers only that the tree is done: an answer is kept and
shown, and whoever holds the token can sign in as the person.

```ts
let sso = '';  // the tree's SSO token, set by the source that answers its last step
const sources: Sources = {
  signIn: (_a, store) => {
    const token = sso;
    sso = '';
    return provider.signIn(store, {
      authorize: async ({ endpoint, params, fetch }) => {
        const reply = await fetch(endpoint, { method: 'POST', redirect: 'manual',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded', Cookie: `iPlanetDirectoryPro=${token}` },
          body: new URLSearchParams({ ...params, csrf: token, decision: 'allow' }).toString() });
        return reply.headers.get('Location') ?? '';
      },
    });
  },
};
```

This sign-in runs natively. On the web, the browser answers `redirect:
'manual'` with no status or headers (Fetch's opaque redirect) and drops a
`Cookie` an app sets, so a web build needs a server to send the authorization
request, as GitHub's needs one for its token exchange (GH-8). Grant no
`auth.session` or `auth.callback`, and set `callback` to the redirect URI the
provider registered. Send with the `fetch` that `authorize` is given, the
package's transport, and throw an `OAuthError` to say why sign-in failed,
giving it the failing reply's status. `claims(store)` reads the ID token's
claims, for an API that wants one of them in a header; the `log` option hears
what the session did, with no token in it, for a diagnostics screen; the
`fetch` option carries every request the package makes, for a demo whose
server is in the app.

**Testing against a fake provider.** Name `<exact2>/packages/oauth/test/fixture.ts`
as the app's server in `app.json` (`"commands": {"server": ["bun", "<exact2>/packages/oauth/test/fixture.ts", "--port", "4400"]}`,
`"server": {"database": false}`). Its profiles (`spec`, `google`, `entra`, `auth0`,
`okta`, `onelogin`, `github`, `salesforce`, `forgerock`) behave as those providers do. The
issuer is `http://127.0.0.1:4400/p/<profile>`, except Entra's
`…/p/entra/common/v2.0`, Auth0's `…/p/auth0/` and OneLogin's
`…/p/onelogin/oidc/2`. Google's token endpoint is on the next port, `4401`:
grant it too. GitHub has no discovery: its `endpoints` are `…/p/github/authorize`
and `…/p/github/token`. `GET /p/<profile>/api/me` answers the person.
ForgeRock's tree is `POST /p/forgerock/json/authenticate` (the person is
`ada@example.com`, password `lovelace`), and its API answers 403 for an expired
access token.
`authorize` completes the held sign-in against the fixture;
`authorize cancel` cancels it. `request POST "/control"` changes what the
fixture does next: `{"action": "expire-access", "profile": "spec"}`, and
`revoke`, `fail-token`, `hold-token` (then `{"action": "await", "held": 1}`
returns once the app's token request is held, and `release-token` lets it
go), `deny-authorize`; `fixture.ts`'s `control` lists them all.

To open a fresh test already signed in, configure the app's provider with the
local fixture's `/p/spec` issuer. Give `signed-in` the provider's plain
`secret.keep` name, its `clientId`, and the test person's `sub`. The fixture
completes the code exchange before launch. The first data read, a token refresh
and a relaunch all see the same person. Signing out clears the test's session.

```contract-test
test "opens the reader's profile"
  signed-in "oauth.spec" {"clientId":"client-spec","sub":"reader-2","name":"Grace Hopper"}
  answer fetch "http://127.0.0.1:4400/p/spec/api/me" with 200 {"name":"Offline reader"}
  expect text "status" == "Signed in"
  expect text "name" == "Offline reader"
```

`name` defaults to `sub`, and `email` defaults to the empty string. The
fixture generates a bearer token. Give `token` a test value to choose the
first bearer, for example `"token":"reader-2-test"`. The fixture refuses a
value it already issued until reset. To exercise the sign-in button and the
callback itself, start signed out, tap the button and use `authorize`.

### HTTPS callbacks

For a backend that accepts only HTTPS return URLs, declare
`auth.callback https://app.example/auth/return` instead of the custom-scheme
callback. Register that URL with the backend. Apple uses
[`ASWebAuthenticationSession.Callback.https`](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession/callback/https(host:path:));
it requires iOS 17.4 or macOS 14.4. Android uses an
[Auth Tab](https://developer.chrome.com/docs/android/custom-tabs/guide-auth-tab)
when the selected browser supports it, otherwise a browser returning through
a verified App Link on exactly `/auth/return`. HTTP loopback remains unavailable
on Android.

Serve the domain associations over HTTPS at the origin root, without redirects:

- `/.well-known/apple-app-site-association` needs
  `{"webcredentials":{"apps":["TEAM.com.example.app"]}}`. `TEAM` is the signing
  team and `com.example.app` the bundle id. The bake derives the matching
  `webcredentials:app.example` entitlement from the callback grant. On macOS,
  signing it requires a provisioning profile that allows Associated Domains.
  A development build without one reports the missing association; a release
  build refuses to ship without it.
  Debuggable builds append `?mode=developer` to each derived `webcredentials:`
  entry so Apple fetches the file from the domain directly. Enable Associated
  Domains Development on the test device ([Apple's setup](https://developer.apple.com/documentation/xcode/supporting-associated-domains)).
- `/.well-known/assetlinks.json` needs a `delegate_permission/common.handle_all_urls`
  statement naming the Android package and its signing certificates' SHA-256
  fingerprints. Put the fingerprints in `host.android.certificates` in `app.json`;
  include each signing identity used to install the app, including Play App Signing.

With `app.origin` set to this origin and `host.ios.team` set, the web build writes
these files into `.well-known/`, and deploy publishes them with the web root.
For a callback on another origin, the build prints the files that domain must
serve, merging any passkey and navigation entries into the same documents.
Keep `.well-known/` at the origin root when the site has a base path.
`handle_links` controls ordinary navigation and is not needed for auth callbacks.
On Android 11 and earlier, one unverified navigation or callback host prevents
verification of every App Link; the build names the hosts when more than one is registered.
Reserve `/.exact/auth/callback` for the web popup; use a different path for the
native callback so an installed app does not intercept the web sign-in.
Apple returns `502` with its reason when the app is not associated with the
callback domain. A session that starts has not yet proved callback delivery;
check the return in a signed app with the domain's association file published.

## Web sign-in callback

Grant the deployed site's exact `auth.callback https://app.example/.exact/auth/callback`
and register it with the provider. A loopback development page grants its own
callback automatically; deployment has no such exception.

Serve the generated `dist/.exact/auth/callback` at `/.exact/auth/callback`,
without a router fallback or trailing-slash redirect, and its script at
`/.exact/auth/callback.js`. Include the hidden `.exact/` directory in the upload.
With Wrangler or another static-assets uploader, verify that both URLs return
the generated files after deploying; if the uploader omits them, serve them
explicitly from the Worker. Keep the callback's `Cache-Control: no-store` and
`Referrer-Policy: no-referrer` headers.

## Native sign-in (`@exact/sign-in`)

The [sign-in recipe](https://exact.expo.dev/recipes/sign-in.md) gives the call and server flow.

On iOS and macOS, an Apple-only request opens AuthenticationServices in the
calling session's window. The answer has an empty `id`, a `handle`,
`configURL`, `isAutoSelected: false`, Apple's `user` and authorized scopes
under `apple`, and `token.authorization` containing `id_token`, `code` and
`state`. First-authorization name and email, when supplied, are in
`token.user`. A dismissal returns `NetworkError`, as the web does; runtime
cancellation returns `AbortError`.
Backgrounding returns `NotAllowedError` for an open or waiting sheet.

Pass the raw server nonce in `params.nonce`. Both the native request and
the web authorization URL carry it unchanged. Apple's
[nonce property](https://developer.apple.com/documentation/authenticationservices/asauthorizationopenidrequest/nonce)
and [ID-token claims](https://developer.apple.com/documentation/signinwithapplejs/authorizationi/id_token)
describe checking the supplied value in the token. Exact does not hash it
on either host. Construction and fixture tests cover this rule; comparing
real Apple tokens from both hosts remains a device/provider qualification.

The `auth.apple` grant derives `com.apple.developer.applesignin`; there is
no separate app.json switch. Enable Sign in with Apple for the app's
Apple Developer App ID and use a provisioning profile that grants it.
The build signs the entitlement on a simulator or when the signing profile
allows it. On macOS, a build without the signed entitlement reports Apple
unavailable and requests return `NotSupportedError`. iOS leaves entitlement
validation to AuthenticationServices; an authorization failure returns `IdentityCredentialError` with Apple's code. A simulator run
does not establish successful sign-in on a signed device.

Pass both `publicKey` and passive `identity` to `get` for one system sheet
offering a passkey and Sign in with Apple. Passkeys owns the controller and
the call's lifetime; sign-in builds the Apple request and decodes its result
(LLP 1133.014 D10). Apple `withPublicKey` follows its entitlement availability.
A newer credential ceremony ends a pending passive request with `AbortError`.
Other credential sheets wait in session order, across passkeys and sign-in.
Active identity requests and `silent` or `conditional` mediation cannot share
the sheet. Google on Apple and `getCredentialState` remain unimplemented.
On Apple, use `@exact/oauth` through the system browser for Google.
On Android, Credential Manager offers Google both actively and passively
when Play services is enabled. A Google request runs alone.
See the [Android sign-in options](https://github.com/expo/exact/blob/41ded8c5ede0b2959ef0daa83b1ff78545dd4428/packages/sign-in/README.md).

## Convex live queries

The `convex` recipe is the code for `@exact/convex`; this is what it leaves
out (LLP 1157).

- **The deployment's address.** `convex(address, …)` takes its `CONVEX_URL`
  (`https:`) or the same origin as a socket's (`wss:`), so one build-time
  setting can name both it and the `net.websocket` grant.
- **`live.status`.** `connecting`, `open`, `ready` (results have arrived),
  `closed` (the socket ended or never opened: refresh `live`, as the recipe's
  `retry` does) or `failed` (Convex said something this client cannot follow;
  `live.error` says what, and a new connection would meet it again, so nothing
  retries it). A frame over the module's ceiling is one: the first frame of
  a connection carries every query's result, 8 MiB together unless
  `convex(url, functions, { maxMessageBytes })` says another.
- **A quiet socket.** Convex sends a frame every 15 seconds. The module asks
  its socket with `exactIdleTimeout`, so the host ends one that carries nothing
  for a minute (`convex(url, functions, { idleTimeoutMs })` says another), in
  real time, whatever the driver's clock. It ends as `closed`, which the
  recipe's `reconnect` opens again. So does a connection with no results by
  Convex's second ping, about half a minute after it opened, whatever
  `idleTimeoutMs` says: the module cannot tell opening frames that were lost
  from a first answer that late.
- **A query's lifetime.** Its identity is its function and arguments. One a
  screen no longer asks for is dropped at the second change after its last
  ask. One asked while the socket is closed, with nothing delivered for it,
  fails and is asked again when results arrive.
- **Values.** A Contract shape is closed (every field, no others) and holds no
  `bigint` or bytes: map a result with `cx.query`'s fourth argument. A value
  outside its shape fails that resource; the socket goes on.
- **Failures.** A failed query throws `ConvexFailure`: the resource fails and
  keeps what it showed. A mutation or an action rejects with one when Convex
  refuses it (`message` is Convex's, `data` a `ConvexError`'s payload), when
  the socket is not open (nothing was sent), and when the socket closes before
  the answer. That last one may have run, and the module sends nothing again
  on the next connection by itself. When
  Convex refuses a token it closes the socket. A request sent behind the
  refused `setAuth` rejects with Convex's words, as `live.authError` has them:
  it did not run. When a token expires, Convex refuses it at whichever request
  meets it first, and one sent earlier (an action still running) may have run,
  so each rejects with "Convex refused the token before it answered (…); the
  mutation may have run".
- **Sending a mutation again.** The failure of a mutation whose connection
  ended before Convex answered carries `again`, a handle (none if you signed
  out after sending it). Once `live.status`
  is `ready` again, `cx.again(handle)` in a mutation's source sends the same
  request: Convex answers one it has seen with its first answer, so the write
  happens once, and runs one it never saw as the person signed in now. Keep
  the handle in state (`catch (e) { return { ok: false, again: e.again ?? -1 } }`)
  and offer the retry. A handle is good once (a mutation sent again and left
  unanswered again fails with the next), the module keeps the last hundred,
  and `cx.setAuth(undefined)` forgets them all, so a mutation is never sent
  again as the next person. An action has no handle: one that must not repeat
  carries its own key.
- **An action's reply** arrives as soon as Convex has it, and the queries may
  show what it wrote a moment later: a mutation's reply waits for them, an
  action's does not. A view that reads both can show them out of step.
- **A person's token.** `cx.setAuth(jwt)` in a mutation's source, with a JWT
  the deployment accepts (its `auth.config.ts`); `cx.setAuth(undefined)` signs
  out. In an `async` source it may follow an `await`; in a plain `.then`
  callback its send throws on the web. With `@exact/oauth`, signing in is one
  source: `async (_a, store) => { const r = await provider.signIn(store);
  cx.setAuth(provider.idToken(store) ?? undefined); return r; }`. When
  `live.authError` says the token expired, a source that awaits
  `provider.refresh(store)` and calls `setAuth` the same way renews it. The token stays in data code.
- **A source's synchronous part may not both send and `fetch`.** `setAuth`
  sends on the socket, and the runner refuses a mutation whose source does
  both before its first `await` (`a mutation cannot both send on a socket and
  fetch`): nothing is sent and its `then` does not run. Fetch first in an `async` source, await
  it, then call `setAuth`: `async () => { await fetch(signOutUrl, …);
  cx.setAuth(undefined); return … }`. If a call's frame never left anyway,
  the module still gives no answer for the wrong person and sends each
  mutation behind the token again, so Convex runs none as the person before;
  calling `setAuth` again sends it again.
- **An upload to a URL Convex signed** is one `async` source, since a
  mutation whose source sent may fetch after an `await`: `const url = await
  cx.mutation(api.files.uploadUrl, {}); await fetch(url, { method: 'PUT',
  exactBodyFrom: path }); return cx.mutation(api.files.saved, { … })` (a
  component's signed URL, such as R2's; Convex's own file storage takes a
  `POST`).
- **After a token change** no answer computed for another token is given,
  across a reconnect too, until Convex delivers it for the new one. The screen
  keeps what it showed until the new answers land: gate a signed-in screen on
  your own session, as with any backend. A refused token is `live.authError`;
  Convex closes the socket, and the next connection is signed out.
- **Renew a token before it expires.** Convex refuses an expired token only
  when a request or a query's rerun meets it, not on a quiet socket. Renew it
  from a Contract task (every 10 minutes for a token that lives an hour) with
  the same `refresh`-then-`setAuth` source.
- **Tests** run with no Convex. `server.ts` beside `app.ts` gives
  `@exact/convex/test/server.ts` the app's functions as plain JavaScript over
  memory, and `test` and `verify` start it (`apps/mosaic/server.ts`); its
  `app.json` needs `"server": { "database": false }`, since the stand-in keeps
  no database. A function's second argument is who asks, `{ identity }`: the
  `sub` of the JWT the client sent, unchecked, or `null` signed out. The
  stand-in takes the socket on any path that ends in `/sync`, and Convex's
  HTTP API answers too (`POST /api/mutation`, `/api/query`, `/api/action`,
  `Authorization: Bearer <jwt>`), so a test's `request` can write as another
  client; after both, `http: (request) => Response | undefined` answers the
  app's other routes (an auth endpoint), with CORS headers added. Keep the
  rules both run in a file with no Convex import (`convex/tiles.ts`). Each
  test starts an empty stand-in, including with `database: false`. Remote
  servers stay shared. Only `test` and `agent --test` share an ancestor's server,
  saying so; `verify` refuses an answering local server, including an ancestor's.
- **The socket origin of a test build.** `test` and `verify` start the
  stand-in at the socket origin the build reads, when that origin is a loopback
  address with a port (`ws://127.0.0.1:3210`). With a cloud origin, no stand-in
  starts and the tests run against that deployment. A setting
  (`"env": ["CONVEX_SOCKET_URL"]` in app.json, read as
  `import.meta.env.CONVEX_SOCKET_URL`) has the same value in a test or check
  build as in any build: the environment's, else `.env.local`'s, else `.env`'s,
  else the default in app.ts. Give tests, checks and drives the stand-in's
  origin in the environment:
  `CONVEX_SOCKET_URL=ws://127.0.0.1:3210 bun exact.mjs verify`.
- **Driving a native host against a real deployment.** The driver seeds a
  native host's randomness (`EXACT_AGENT_SEED`, 1 by default), so two launches
  draw the same session id and Convex answers the second's writes with the
  first's answers, without running them. Give each launch a new seed: `agent
  macos --seed 7 …`. The tests of one file launch at the file's seed too, on
  every host: give each test that writes its own `seed` line, first in the test.
- **Hosts.** The web, macOS, iOS, Linux and Windows. A worker-placed source
  and any other host have no socket to send on. There, and for a read that
  need not be live, use Convex's HTTP client under `net.fetch`: `new
  ConvexHttpClient(CONVEX, { logger: false })` from `convex/browser` (`{ logger:
  false }` avoids its default logger drawing ambient `Math.random()`, which
  excludes the resource from launch bake and SSR caching), then
  `await http.query(api.messages.list, { channel })`.

### Convex Auth

With Convex Auth (`@convex-dev/auth`) the deployment runs the OAuth flow, and
the client calls three of its mutations: one that starts a sign-in (`{
redirectTo }` to `{ redirect, state }`), one that completes it (`{ code, state
}` to tokens) and `refreshSession` (`{ refreshToken }` to tokens). Its React
hooks and browser session manager do not run in a data module. Call the
mutations with `cx.mutation`, open `redirect` with `openAuthSession` (it and
`authCallback` are declared for every app in `app.contract.d.ts`), keep the
refresh token with `store.set` under a `secret.keep` grant on native hosts, and
give the access token to `cx.setAuth`. This direct token flow exposes web tokens
to page scripts. For [web sessions](https://exact.expo.dev/recipes/web-sessions.md), put the flow behind
your server's HttpOnly cookie; `cx.setAuth` does not turn a bearer token into a
cookie. The mutations' names are the deployment's:

```ts
const SESSION = 'example.session';
export const grants = [`net.websocket ${CONVEX}`, 'auth.session https://accounts.google.com', `secret.keep ${SESSION}`].join('\n');

// a source of `sources`
signIn: async (_a, store) => {
  const callback = authCallback(), mine = crypto.randomUUID();
  const started = await cx.mutation(api.auth.startSignInWithGoogle, { redirectTo: `${callback}?state=${mine}` });
  const back = new URL(await openAuthSession(started.redirect, { callback, state: mine })).searchParams;
  const failed = back.get('convexAuthError');
  if (failed !== null) return { ok: false, error: failed };
  const done = await cx.mutation(api.auth.completeSignInWithGoogle, { code: back.get('convexAuthCode') ?? '', state: started.state });
  if (done.status !== 'complete') return { ok: false, error: done.userError.error };
  store.set(SESSION, done.tokens.refreshToken);
  cx.setAuth(done.tokens.accessToken);
  return { ok: true, error: '' };
},
```

- **The state goes in `redirectTo`.** `openAuthSession` completes only on a
  callback that carries the `state` it was given, and Convex Auth sends back
  only `convexAuthCode` or `convexAuthError`. It keeps `redirectTo`'s query, so
  a state drawn in data code and written there comes back.
- **The code is `convexAuthCode`,** not `code`: an empty code is
  `INVALID_CODE`.
- **Resuming and signing out.** At launch, once `live.status` is `ready`, a
  source sends `refreshSession` with the kept token, keeps the new refresh
  token and calls `cx.setAuth`; a reply with no new tokens means the session
  ended, so it forgets the kept one (`store.forget`). Renew the same way when
  `live.authError` says the token expired. To sign out, forget the kept token,
  call the deployment's sign-out mutation, then `cx.setAuth(undefined)`.
- **A drive needs a fixed origin.** Convex Auth checks `redirectTo`'s origin
  against its allowed redirect origins, and the driver picks a new port each
  run: drive with `agent web --port 3000` (or `EXACT_PORT`) and allow
  `http://127.0.0.1:3000`.
- **Native callbacks.** Convex Auth takes only HTTP or HTTPS `redirectTo` URLs.
  Declare `auth.callback https://app.example/auth/return` and allow its origin
  in Convex. Use only an HTTPS callback for this flow: `authCallback()` prefers
  a declared custom scheme when one is present. Apple requires iOS 17.4 or
  macOS 14.4 and the callback host's `webcredentials` association. Android uses
  Auth Tab when supported, otherwise the callback's verified App Link; HTTP
  loopback still answers 501. The [HTTPS callback setup](https://exact.expo.dev/learn/contract-for-agents/data-requests-and-side-effects.md#https-callbacks) describes
  the signing identities and association files. Native Google approval and
  token rotation still need a check against the app's real Convex deployment.

## Supabase

The `supabase` recipe wires the session and a table; this is the rest. It was
tried against a loopback stand-in for Supabase's APIs, not a live project.

### Supabase session

Copy `supabase.ts` whole, this section's code and the next one's. The origin and the publishable key are settings:
`"env": ["SUPABASE_URL", "SUPABASE_KEY"]` in app.json, their values in
`.env.local`. Each Auth call keeps its reply under the `secret.keep` name; a
change to the session holds that name's lease (`store.exclusive`, LLP 1146 D5),
whose work must not throw after a request, or the secret is forgotten.

```ts
import { PostgrestClient } from '@supabase/postgrest-js';
import { StorageClient } from '@supabase/storage-js';
import { FunctionsClient } from '@supabase/functions-js';
import type { Store } from './app.contract.d.ts';

// The project's URL and publishable key, settings in app.json's `env`: neither is a secret.
export const PROJECT = import.meta.env.SUPABASE_URL ?? 'http://127.0.0.1:54321';
const KEY = import.meta.env.SUPABASE_KEY ?? 'anon-key';
export const SESSION = 'supabase.session';

type Session = { project: string; access_token: string; refresh_token: string; expires_in: number; expires_at: number; user: { id: string; is_anonymous: boolean } };
export class AuthError extends Error {
  readonly reason: string; // what a failed resource or mutation shows as its code
  constructor(readonly status: number, readonly code: string, message: string) { super(message); this.reason = code; }
}
// Auth's answers to a refresh token it will never take again.
const ENDED = ['refresh_token_not_found', 'refresh_token_already_used', 'session_not_found', 'session_expired'];

// The session's changes, one at a time: a refresh, a sign-in and a sign-out each
// read what is kept inside the lease, so none writes over another's result. A
// lease whose work throws after a POST forgets the secret (LLP 1146 D5), so the
// work's error is carried out of the lease and thrown there.
async function exclusive<T>(store: Store, work: () => Promise<T>): Promise<T> {
  type Done = { value: T } | { error: unknown };
  const leased = store as Store & { exclusive(name: string, work: () => Promise<Done>): Promise<Done> };
  const done = await leased.exclusive(SESSION, () => work().then((value) => ({ value }), (error: unknown) => ({ error })));
  if ('error' in done) throw done.error;
  return done.value;
}
// A session kept for another project's URL is not this one's.
const kept = (store: Store): Session | null => {
  const s: Session | null = JSON.parse(store.get(SESSION) ?? 'null');
  return s?.project === PROJECT ? s : null;
};

// One Auth (GoTrue) call that answers a session, kept with its expiry on the app's clock.
async function auth(store: Store, now: number, path: string, body: object, jwt = KEY): Promise<Session> {
  const res = await fetch(`${PROJECT}/auth/v1/${path}`, { method: 'POST', body: JSON.stringify(body),
    headers: { apikey: KEY, Authorization: `Bearer ${jwt}`, 'Content-Type': 'application/json' } });
  const out = await res.json();
  if (!res.ok) throw new AuthError(res.status, typeof out.error_code === 'string' ? out.error_code : '', out.msg ?? out.message ?? `Auth answered ${res.status}`);
  if (typeof out.access_token !== 'string' || typeof out.refresh_token !== 'string' || typeof out.user?.id !== 'string' || !(out.expires_in > 0))
    throw new AuthError(res.status, 'bad_session', 'Auth answered no session');
  const s = { ...out, project: PROJECT, expires_at: Math.floor(now / 1000) + out.expires_in };
  store.set(SESSION, JSON.stringify(s));
  return s;
}

/** A new anonymous user, unless a session is kept. */
export const signInAnonymously = (store: Store, now: number) =>
  exclusive(store, async () => kept(store) ?? auth(store, now, 'signup', { data: {} }));

// Due for a refresh at `now` (`time.epochAtZero + performanceNow()`): a quarter of its life left, at most five
// minutes, so the minute tick reaches a five-minute token in time.
const due = (s: Session | null, now?: number): s is Session => s !== null && now !== undefined
  && s.expires_at * 1000 - now <= Math.min(300_000, s.expires_in * 250);
// The refreshed session, or `null` when Auth has ended it. A reply lost on the way is
// asked for again at once, inside Auth's reuse interval, which answers it as before.
async function refresh(store: Store, s: Session, now: number): Promise<Session | null> {
  const ask = () => auth(store, now, 'token?grant_type=refresh_token', { refresh_token: s.refresh_token });
  try {
    return await ask().catch((e: unknown) => { if (e instanceof AuthError) throw e; return ask(); });
  } catch (e) {
    if (!(e instanceof AuthError && ENDED.includes(e.code))) throw e;
    store.forget(SESSION);
    return null;
  }
}

/** The kept session, or `null` when signed out; given `now`, refreshed first when due. */
export async function session(store: Store, now?: number): Promise<Session | null> {
  if (!due(kept(store), now)) return kept(store);
  return exclusive(store, async () => {
    const s = kept(store);
    return due(s, now) ? refresh(store, s, now!) : s;
  });
}

/** Supabase's own clients, sending the session's access token; given `user`, only that user's. */
export async function supabase(store: Store, now?: number, user?: string) {
  const s = await session(store, now);
  if (s === null || (user !== undefined && s.user.id !== user)) throw new AuthError(401, 'signed_out', 'Signed out');
  const headers = { apikey: KEY, Authorization: `Bearer ${s.access_token}` };
  return {
    user: s.user, headers,
    db: new PostgrestClient(`${PROJECT}/rest/v1`, { headers }),
    storage: new StorageClient(`${PROJECT}/storage/v1`, headers),
    functions: new FunctionsClient(`${PROJECT}/functions/v1`, { headers }),
  };
}
```

### Supabase sign-out and Apple sign-in

The rest of `supabase.ts`:

```ts
/** Signs this device out. Revoking its refresh token is best effort: offline, the token stays valid on the server. */
export const signOut = (store: Store, now: number) => exclusive(store, async () => {
  let s = kept(store);
  if (due(s, now)) s = await refresh(store, s, now).catch(() => s);
  store.forget(SESSION);
  if (s !== null) await fetch(`${PROJECT}/auth/v1/logout?scope=local`, { method: 'POST',
    headers: { apikey: KEY, Authorization: `Bearer ${s.access_token}` } }).catch(() => undefined);
});

/** Sign in with Apple's ID token, linked to `user`, the anonymous user the sheet
 * opened for. An Apple ID that already has an account throws `identity_already_exists`
 * and keeps the anonymous session: switching leaves its data behind, so it is the
 * app's choice (`true`). */
export const signInWithApple = (store: Store, idToken: string, nonce: string, now: number, user: string, switching = false) =>
  exclusive(store, async () => {
    let s = kept(store);
    if (s?.user.id !== user) throw new AuthError(401, 'signed_out', 'Signed out');
    if (due(s, now)) s = await refresh(store, s, now);
    if (s === null) throw new AuthError(401, 'signed_out', 'Signed out');
    const body = { provider: 'apple', id_token: idToken, nonce };
    if (!s.user.is_anonymous || switching) return auth(store, now, 'token?grant_type=id_token', body);
    return auth(store, now, 'token?grant_type=id_token', { ...body, link_identity: true }, s.access_token);
  });

// Auth checks that an ID token's nonce is the hex SHA-256 of the nonce it is given: ask Apple for this.
export async function sha256(text: string) {
  const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)));
  return [...bytes].map(b => b.toString(16).padStart(2, '0')).join('');
}
```

### Supabase accounts

- **The project:** enable anonymous sign-ins; give each table a `user_id uuid
  default auth.uid()` column and row-level security policies on it for the
  `authenticated` role (an anonymous user has it too), and the bucket policies
  on the first folder of an object's name, which is the user's id here. Row
  security that refuses a read answers an empty list, not an error.
- **Sign out** from a mutation that refreshes `session`, passing the press's
  time: `signOut: async ([now], store) => { await signOut(store, now); return {
  ok: true, error: '' }; }`. The recipe's `anonymous` task then signs in a new
  anonymous user. Until a read of the new user lands, and while a `when` is
  false, a resource shows its last answer: put the user in the answer and show
  rows only when it is `session.userId`, as [your own REST
  server](https://exact.expo.dev/recipes/rest-backend.md) does with `owner`.
- **A refused refresh** (`refresh_token_not_found` and the other ended
  sessions) forgets the session, and `session` answers `null`; a 429, a 5xx or
  no network keeps it for the next tick, and a reply lost on the way is asked
  for again at once. Auth takes a refresh token again within its reuse interval (10 s
  by default), or when it is the active token's parent, and revokes the session
  for any other reuse ([Supabase
  sessions](https://supabase.com/docs/guides/auth/sessions)); the lease keeps
  two answers from spending one token. A session kept for another
  `SUPABASE_URL` is ignored, and its token never sent there.
- **Sign in with Apple** links the Apple ID to the anonymous user. The project
  enables manual linking, and its Apple provider lists the app's bundle ID.
  `@exact/sign-in` passes `params.nonce` to Apple unchanged, and Auth compares
  the token's nonce with the hex SHA-256 of the nonce it is given: before the
  press, draw `raw = crypto.randomUUID()` and ask Apple for `await sha256(raw)`,
  then call `signInWithApple(store, credential.token.authorization.id_token,
  raw, now, user)`, `user` being the `session.userId` the sheet opened for. That
  is the native credential. On the web the ID token stays with the app's server
  ([sign-in recipe](https://exact.expo.dev/recipes/sign-in.md)), whose token's audience is the
  Services ID, which the Apple provider then lists too; that server makes the
  exchange, with the anonymous session to link, and hands back the session.
  An Apple ID with an account of its own throws `identity_already_exists`
  (`failure(x).code`, from `AuthError`'s `reason`) and keeps the anonymous
  user; switching (`signInWithApple(…, true)`) leaves that user's rows behind.
- **The tokens:** on the web `secret.keep` is the page's `localStorage`, where
  supabase-js keeps them in a browser, readable by any script on the origin;
  on Linux an unencrypted file. A web refresh token out of scripts' reach needs
  the exchange behind your server and an HttpOnly cookie ([web
  sessions](https://exact.expo.dev/recipes/web-sessions.md)).

### Supabase Storage and Functions

From a test app's sources, after `const { db, storage, functions, user,
headers } = await supabase(store, now, owner)` and `images =
storage.from('images')`, `owner` being the `session.userId` the file was chosen
under, so a write queued across a sign-out is refused:

```ts
ok(await images.upload(`${user.id}/a.png`, new Uint8Array([137, 80, 78, 71]), { contentType: 'image/png', upsert: true }));
(ok(await storage.from('images').list(user.id)) ?? []).map(f => f.name)
ok(await images.remove([`${user.id}/a.png`]));
ok(await functions.invoke<{ greeting: string }>('hello', { body: { name: 'Ada' } }))?.greeting ?? ''
```

A native request holds at most 4 MiB, so a photo goes up from its file
(`fs.read` of its folder) with `fetch`, which streams it from disk:

```ts
const res = await fetch(`${PROJECT}/storage/v1/object/images/${user.id}/photo.jpg`, { method: 'POST', exactBodyFrom: 'app:/tmp/photo.jpg',
  headers: { ...headers, 'Content-Type': 'image/jpeg', 'x-upsert': 'true' } });
if (!res.ok) throw new Error((await res.json()).message);
```

### Supabase limits

- **`@supabase/auth-js`, and so `@supabase/supabase-js`.** The build refuses
  both for their uses of the DOM's and Node's globals: the Auth client reads
  `window`, `location`, `localStorage` and `navigator.locks` on browser-only
  paths, and Realtime's socket factory reads `process`. The umbrella client
  with `accessToken` would serve tables, Storage and Functions, at 403 KB of
  web JavaScript to these three packages' 92 KB.
- **Realtime.** Its socket outlives an answer; `QUEUE.md`, "A stream that can
  send: Supabase Realtime without polling".

## Child processes (`@exact/child-process`)

A desktop app's data code starts a program with Node's names (LLP 1133.007). Each streaming child takes one of the app’s 16 child slots. Network streams have 16 slots of their own. Each streaming child and network stream also reserves its response ceiling against the independent lane’s byte budget. One-shot processes have 16 slots and a separate 64 MiB budget. A single one-shot can exceed that byte budget when it runs alone (LLP 1133.007 D3). A refused spawn starts no child. When room opens, refresh the resource to retry.
A resource answers `spawn(program, args, {exactStream})`: the child lives
while the resource holds it, and its mapper hears `spawn`, `stdout`,
`stderr`, `exit`, `close`, `drain`, `ready` and `ready-timeout`, with the
incarnation's handle (`write`, `end`, `kill`). An answer awaits `execFile`
for a one-shot run. Each program needs a grant line naming it
(`process.spawn path:ssh`, `process.spawn /usr/bin/tar`); a call with none is
`grant-missing`. Only a person's input or the app's own code starts or
drives a child: a tool's call, a wake or a device event is refused
`person-required`, and its commit lets no child go. Under the agent nothing
runs unless the drive names it: `--process <program>=script:<file.json>`
answers from a script on the agent's clock. macOS and Linux run it; every
other target answers `NotSupportedError`, which `processStatus()` says
ahead. The options, events and limits are `docs/reference.md`'s "Child
processes".

## Tools: what a call answers

A `tool` line offers a root action to callers outside the app: the agent
driver, and, through its face in `app.json` `intents.tools`, Siri and
Shortcuts (App Intents) and a browser's agent
([WebMCP](https://webmachinelearning.github.io/webmcp/)). Every door
answers one envelope (LLP 1111 D4), and `state.intents.calls` keeps the
last twenty with their `door`:

- `outcome`: `ok`, `failed`, `superseded`, `timeout`, `interrupted` or
  `refused`. `certainty`: `none` (it did not run), `applied` (it ran and
  its work settled) or `uncertain` (it ran, and its effect may or may not
  have landed: read before calling again).
- `reason`, one word where there is one: `unavailable` (not offered on that
  door, `available when` false, a face that changed), `arguments`, `busy`
  (5 s behind another call or a wake, what it reports still being answered,
  storage still writing), `cancelled`, `refused-commit`, `background`,
  `person-required`.
- `value` is what `returns` reads (null when refused), and `message` a
  sentence for the caller. The record adds `cancelled`.

A refresh does not make a call `busy`: `returns` and `fails when` read a
resource's standing value (its last answer, its placeholder, a family's
gathered list), and `pending`, `failed`, `failure` and `current` answer at
once.

**A cancelled call.** A browser's agent aborting `execute`, or the system
cancelling an intent's task, cancels the call (the door sends
`{"op":"cancel","id":<call>}`). One still waiting never runs: `refused`,
`none`, `cancelled`. One already dispatched runs to its end, since its
commit has landed and what it started is the app's to finish; its record
says `cancelled: true`, and the journal that the caller left.

**On the web**, each faced tool is registered with `document.modelContext`:

- `readOnlyHint` for a `reads` tool whose reach (its action, the actions
  it calls, the `then`s of what it sends) has no `send`; `consequentialHint`
  for `destroys` and for every `writes` except `writes additive closed`,
  which only adds to the app's own data; `untrustedContentHint` when
  `returns` is a string, whose text may not be the author's (a note, a
  review).
- `outputSchema` is the envelope, its `value` typed from `returns`, and
  `execute` resolves with it for every outcome. It never rejects: an agent
  learns nothing of a rejection but "OperationError".
- A face parameter's `title` and `description` are its input schema's
  (`"page": { "title": "Page", "description": "The page you have read up
  to.", "type": "integer" }`); App Intents shows the same two words.
- A route with no `activate=` that would wait for the reader is `idle` in
  an app with a faced tool on the web door, so the agent finds the tools
  once the page has loaded. A declared `activate` is kept.
- `document.modelContext` exists only in a secure context: on `https`, on
  `localhost` and on `127.0.0.1`, not on a LAN address over `http`
  (Chrome 157 with `--enable-features=WebMCP`: none at
  `http://10.0.0.4:<port>`). To try a LAN host, serve it over HTTPS or
  start Chrome with `--unsafely-treat-insecure-origin-as-secure=<origin>`.

An app may also declare its own `AppIntent` in `modules/apple/*.swift` or a module's
`apple/launch/*.swift`. Apple builds extract those modules' constants and combine their
metadata with generated faces in the app's `Metadata.appintents`, even with no faced tools.
An app with native intents links its module library at launch so the system can resolve the
intent before any view opens. Launch-part extraction uses the target's compilation conditions,
including `DEBUG` for its debug configuration. On Linux, authored `openAppWhenRun`, `isDiscoverable`,
introduced iOS/macOS availability and scalar parameter defaults are preserved; defaults that
cannot be represented exactly and unsupported declarations fail the build.
Linux builds also refuse more than one App Shortcuts provider across modules and generated faces.
A launch part can import ExactToolDoor, which a plan with a tool links, and call the public `ExactTools.call` door (LLP 1133.023 D15).
The `--extensions` selection applies to native and generated intents alike.
On Linux, native `IntentFile` content types may use `UTType(importedAs:)` or the constants
`.image`, `.png`, `.jpeg`, `.heic`, `.heif` and `.data`.

## File parameters on an Apple face

On a string parameter, declare `"type": "file", "accept": ["image/png", "image/jpeg", "image/heic"]`
and set the face's `"doors": ["apple"]`. Accepted MIME types come from `scripts/document-utis.json`,
excluding directories. Set `host.ios.minimumOS` to `"18.0"` or later and `host.macos.minimumOS`
to `"15.0"` or later: App Intents' `IntentFile` initializer with `supportedContentTypes` needs them.

The accepted MIME types map to UTI identifiers in `scripts/document-utis.json`. A type the
supported Apple platforms do not declare (Markdown and Ogg audio) is refused at build time.
The generated action copies the file before calling the tool; only the path crosses the door.

The tool receives an `app:/tmp/picked/…` path, as a file input does. Each file is at most 64 MiB;
the copy lasts until the next process launch, including after the caller cancels. Read it under
`fs.read app:/tmp/picked`, or copy it to durable app storage before returning if it must survive.
WebMCP takes JSON arguments with no file handoff, and AppFunctions' door is not built;
a file face naming either is refused at build time. The call's existing time bounds stay the same.

## Global shortcuts

Import `globalShortcut`, `globalshortcut`, and `globalshortcutup` from
`@exact/global-shortcuts` and declare the `device.global-shortcuts` grant.
Keep the registration resource in the view. Bind the root’s press and
release handlers to separate actions. Each receives the shortcut ID and
can take a second argument of type `GlobalShortcutEvent` with `id` and
`keys`. Check `globalShortcutStatus().releaseEvents` for hold actions.
macOS delivers both events. Windows supports presses only. Linux currently
has no global shortcut registration.

On macOS, `keys="MetaRight"` binds Right ⌘ and `keys="AltRight"` binds
Right ⌥. Each fires on press and release. The monitor sees only modifier
changes, so Right ⌘ fires as part of ⌘C and Right ⌥ fires when someone types
a character with it. Windows returns `reason="unsupported"` for both codes.
Hosts without global shortcuts report `NotSupportedError` for the operation.

Like modifier pairs, these triggers require the Accessibility grant. A missing
grant gives `reason="not-allowed"`. For a modifier trigger, `registered: true`
means the permission gate passed and the system accepted the monitor. It is
not proof of delivery. Modifier triggers depend on the system delivering
modifier-flag changes to a global monitor, as measured on macOS 27.2.
