# Data

Keeping and fetching: `persist` and `store`, `db`, `sql`, `fs`, `net`, the
system's clipboard and share sheet, and the calls that work on bytes (`crypto`, `zip`). Also
notifications a page shows by itself. CSV and Excel workbooks are
[tables.md](tables.md). Back to the [map](README.md).

```mote
// docs: whole
shape Post
  id: number
  title: string

state saved: number[] = []
state note = ""

resource posts: Post[] = net.get("posts.json") else []

action restore
  saved = db.get("saved")? ?? []
  note = fs.text("notes/last.txt") else ""

action keep(id: number)
  if saved.includes(id) return
  saved.push(id)
  db.set("saved", saved)?

task
  restore()

column gap=8 padding=16
  for p in posts key=p.id
    row gap=8
      text p.title flex=1
      button (saved.includes(p.id) ? "Kept" : "Keep") press=keep(p.id) disabled=saved.includes(p.id)
  text note color=dim
```

## Mental model

Everything here leaves the page, so **every call can fail** and must be
settled with `else` or `?` ([language.md](language.md#a-call-that-can-fail)).
None says `async` or `await`: the compiler waits for it. So these calls go
in an action, a fn, a handler, a task or a resource, never in a binding or a
derive (`H082`).

Where each keeps its data, in the page:

| | Kept in | Good for |
|---|---|---|
| `persist`, `store` | `localStorage` | a few small settings; read at once, no waiting |
| `db` | IndexedDB, one store of keys to values | records, lists, bytes |
| `sql` | SQLite, a file per name in the site's private files | anything you would query |
| `fs` | the site's private files (the origin's private file system) | files: text or bytes |
| `local model` | SQLite, the database `app` | rows with a declared schema, read and written with no SQL, that lists follow ([models.md](models.md)) |

All four belong to the browser and the site's address: another browser or
device has its own. Data every device should see belongs on a back end
([back-end.md](back-end.md)), where `sql` and `fs` exist too and keep their
data in the back end's data folder.

`data` below means text or bytes, wherever it appears.

## A file read as the program is built

Data that ships with the program (a catalogue, a price list, the countries
of the world) is a JSON file beside it, and one line:

```text
shape Style
  id: string
  name: string
  price: number
  sizes: string[]

data styles: Style[] from "./styles.json"

for s in styles key=s.id
  text `${s.name}: ${s.price}`
```

- **Read once, when the program is built.** `styles` is what the file
  holds, written out in the page: there is no request for it and nothing to
  wait for or to fail. It is a `derive` of a value written out whole, so a
  `server fn` may name it too ([back-end.md](back-end.md#server-fn)).
- **With a type, it is checked against it**: a row with no `price`, or with
  a text where a number is wanted, is a diagnostic at the `data` line.
  Without one (`data prices from "./prices.json"`), its type is what the
  file holds.
- **It is in every page that names it**, whole. A megabyte of JSON is a
  megabyte of page: for that, keep it on the back end (`fs.read` there, or a
  [model](models.md)) and send what a page asks for.
- A file that is not there is `H333`; one that is not JSON, `H334`, at the
  place in the file. The path is from the file that says it.

## persist and store

`state theme = "light" persist` keeps the state in `localStorage` under its
name ([language.md](language.md#state)).

**A `persist` state is kept as soon as it changes**: at the end of the turn
that changed it, before the page does anything else. Nothing waits for the
page to be left, hidden or closed, so a page that a phone closes while its
camera is open comes back with its states as they were (recorded with the
page's process killed right after a press: `tests/room`). Where
`localStorage` is full, or not allowed, the page goes on and says on the
console what it could not keep. It holds some 5 MB in all: pictures go in
`db` or `fs`.

`store.get(k)` · `store.set(k, v)` · `store.remove(k)`: the same storage by
your own keys, values as JSON. `store.get` gives `none` when there is
nothing. These do not wait and cannot fail.

## net

```text
net.get(url)   net.post(url, body)   net.put(url, body)   net.del(url)
net.text(url)  net.bytes(url)
net.send(method, url, options?)      any status is an answer
net.stream(method, url, options?)    the answer's head, then its body as it arrives
net.lookup(host)   net.public(address)      back end only: a name's addresses; whether one is public
net.lookup(host, "MX")                       back end only: its records of one kind, typed (back-end.md#dns-records)
net.pace(host, {per, max})   net.breaker(host, {after, rest})   net.health()   back end only (back-end.md#a-host-paced-and-a-breaker)
```

- JSON in, `json` out. `body` is sent as JSON.
- Any status outside 200 to 299 is a failure; its message is the status and
  what the answer's body said, up to 500 characters
  (`404 Not Found: no such post`).
- An answer with no content (204) gives `none`.
- `net.text(url)` gives the answer as text; `net.bytes(url)` as bytes.
- A last argument `{headers: {…}}` is passed to `fetch` (with any other
  option `fetch` takes).
- `json` takes the type its `let` gives it: `let xs: Post[] = net.get(url)?`.
- Files in `public/` beside the entry ship as they are:
  `net.get("posts.json")`.

`net` works the same in a `server fn` (`runtime/shared/net.mote`), which
has `public: true`, `net.lookup` and `net.public` besides
(`runtime/server/net.mote`).

### net.send

For an API that says things with its status and its headers (a limit, a
refusal with a reason), `net.send` gives the whole answer and fails only
when no answer arrives (nobody there, the line dropped, out of time):

```mote
server fn ask(prompt: string): string
  let a = net.send("POST", "https://api.example.com/v1/answers", {headers: {authorization: `Bearer ${env("API_KEY")}`}, body: {prompt}, timeout: 30000})?
  if a.status == 429 fail(`busy: try again in ${a.headers["retry-after"]} s`)?
  if !a.ok fail(`${a.status}: ${a.text}`)?
  return a.json.answer
```

| | |
|---|---|
| `a.status` `a.ok` | The status, and whether it is 200 to 299. |
| `a.url` | Where the answer came from: the address asked, or the last one a redirect led to. |
| `a.location` | For a 3xx, the whole address it points at (its `location` header, made whole against `a.url`); else `""`. |
| `a.headers` | The answer's headers, a record (`json`) with each name in small letters: `a.headers["retry-after"]`. One that was not sent is `none`. |
| `a.text` | The body as text. |
| `a.json` | The body as `json`, when it says it is JSON or begins like JSON; else `none`. |
| `a.bytes` | The body as bytes, with the option `bytes: true` (then `text` is empty). |
| `a.tries` | How many times it was asked: 1, unless `retries` asked again. |
| `a.written` `a.size` | With `to` (below): the bytes written to the file now, and the file's size after. Else 0. |

Options, all optional: `headers` (a record), `body`, `form`, `multipart`,
`auth`, `idempotency`, `retries`, `retryOn`, `retryWait`, `timeout` (milliseconds, for
the whole answer, each try), `bytes`, `max`, `redirect`, and on the back end
`public` and `allow`. A `body` that is text is sent as it is; bytes as they
are; anything else as JSON, and said to be (`content-type:
application/json`, unless `headers` names one).

| Option | |
|---|---|
| `form: {email, items: [{price: "p_1"}]}` | The body as a form (`application/x-www-form-urlencoded`), the way Stripe, Twilio and OAuth token endpoints take one: a record inside is `items[0][price]=p_1`, a list counts from 0, `none` is left out, `true` is the word. `net.form(record)` gives the same text (for a signature over it). |
| `multipart: {file: {data, name, type}, purpose: "x"}` | The body as parts (`multipart/form-data`): each field a text, bytes (a file named for the field), a file `{data, name, type}`, or a list of those. The boundary is made for you, and said in `content-type`. |
| `auth: {bearer: key}` · `auth: {user, password}` | The `authorization` header: `Bearer …`, or `Basic` and the two in base64. |
| `idempotency: key` | The `Idempotency-Key` header, the same on every try: a service that keeps it does the thing once, however often it is asked. |
| `retries: 3` | Asked again, up to 3 more times, when no answer came or the answer was 408, 425, 429, 500, 502, 503 or 504: after what its `retry-after` says (seconds, or a date; or `retry-after-ms`, in milliseconds), else after half a second, one, two, four, eight at most, each give or take a half. `a.tries` says how many were made. A `POST` or `PATCH` is tried again only with an `idempotency` key (or an `idempotency-key` header): written out without one it is refused when compiled (`H290`), else it fails. Each try has its own `timeout`. In a test nothing is waited for. |
| `retryOn: [429, 529]` | The statuses tried again, in place of the ones above. Said with only 429 ("too many requests") and 529 ("overloaded"), answers that say nothing was done, a `POST` needs no `idempotency` key (`H290` is not said), and one that got no answer at all is not sent again: what a model's API wants, which keeps no keys and charges for what it did. |
| `retryWait: 60000` | The longest `retry-after` that is waited for (a minute unsaid). Asked to wait longer, the answer that asked is the answer: `a.status` 429, `a.headers["retry-after"]`. How these go with a host's pace and breaker: [back-end.md](back-end.md#a-host-paced-and-a-breaker). |
| `http2: true` | Back end only. Over HTTP/2, for a service that speaks nothing else (Apple's push service): Bun's `fetch` speaks HTTP/1.1 only (Bun 1.2.20 and 1.4.5), so the request goes over `node:http2`, one connection kept for each origin and used again. `https` addresses only. In a test it is `fetch`'s, so `given net` answers it. |

Only one of `body`, `form` and `multipart`. With `net.stream`, `retries` is
about the answer beginning: once its body is coming, it is not asked again.

| Option | |
|---|---|
| `redirect: "follow"` | Unsaid. A 3xx is followed (ten steps at most with `public`, else as `fetch` does), and `a.url` says where it ended. |
| `redirect: "manual"` | The 3xx is the answer: `a.status` 302, `a.location` where it points. (In a page the browser hides a redirect it did not follow: `a.status` is 0. Use it on the back end.) |
| `redirect: "error"` | A 3xx is a failure. |
| `max: 1000000` | The most bytes of body taken; a longer answer is let go of and is a failure. |
| `public: true` | Back end only. Refuses any address that is not of the open internet, at every step. Below. |
| `to: {path, folder, resume}` | Back end only. The answer (200 to 299) is written to a file as it arrives, never held whole: [below](#to-and-from-files). |
| `body: {file, folder, from, length, type}` | A file, or `length` bytes of it from `from`, is the body, read from the disk as it is sent: [below](#to-and-from-files). In a page, a private file or one picked unread (`folder` is the back end's). |
| `progress: (sent, total) => moved(sent)` | The page's. Told how much of the body has gone, as it goes: [below](#to-and-from-files). |
| `allow: ["wiki.corp", "*.corp", "10.1.0.0/16"]` | With `public`: hosts (a name, `*.` and a name's ending), addresses and IPv4 networks let through all the same. |

#### To and from files

On the back end a request can send a file and write its answer to one,
neither held in memory whole: a download of gigabytes, an export sent to a
store, an upload in pieces.

```mote
// The night's export, sent in pieces of 8 MB (a service that takes parts by their offset).
server fn sendExport(url: string): number
  let info = fs.info("exports/night.csv")?
  let from = 0
  while from < info.size
    let a = net.send("PUT", url, {body: {file: "exports/night.csv", from, length: 8000000}, headers: {"content-range": `bytes ${from}-${Math.min(info.size, from + 8000000) - 1}/${info.size}`}, timeout: 120000})?
    if !a.ok fail(`the store said ${a.status}: ${a.text}`)?
    from += 8000000
  return info.size

// A large file fetched, and picked up where it broke off when asked again.
server fn fetchVideo(url: string): number
  let a = net.send("GET", url, {to: {path: "videos/raw.mp4", resume: true}})?
  if !a.ok fail(`${a.status}: ${a.text}`)?
  return a.size
```

- **`to: {path, folder, resume}`**: an answer of 200 to 299 is written to
  `path` in the data folder (or in `folder`, a [`fs.folder`](back-end.md#folders)
  handle) a piece at a time as it arrives; `a.text` is `""`, `a.written`
  the bytes written, `a.size` the file's size after. Any other answer is
  read as text, as always, and no file is written.
- A transfer that breaks off leaves **nothing** at `path` (it is written
  beside and moved into place when whole), and fails. With **`resume:
  true`** what came is kept, and the next send asks for the rest
  (`Range: bytes=<size>-`): a 206 that goes on from where the file ends is
  added to it, a 200 is written over it, a 416 (nothing more) leaves it as
  it is. An answer longer or shorter than its `content-length` said is a
  failure, and a resumed file is cut back to where it was. (Under Bun 1.2
  a `GET` whose connection breaks, on a host asked before, is sent once
  more by Bun itself before it fails; Bun 1.4 sends it once.)
- With `to`, `timeout` is how long the answer takes to begin; unsaid, the
  file arrives as long as it takes. `max` is the most bytes written.
- **`body: {file, folder, from, length, type}`**: the file, or `length`
  bytes of it from `from`, sent as the body with its `content-length`, read
  from the disk as it goes, and opened again for each of `retries`. `type`
  is its `content-type` (`application/octet-stream` unsaid). A file that is
  not there fails as `"missing"`, a `from` past its end as `"invalid"`. Only
  a body written out with `file` and nothing a file does not take is a file:
  `{file: "a", name: "b"}` is JSON, and so is `{file: {display_name}}`,
  whose `file` is a record and no path.
- **In a page**, `body: {file, from, length, type}` sends a private file
  (its path) or a file [picked unread](#files-not-read-yet), or a part of
  one, read from the disk as the browser sends it; `folder` and `to` are
  the back end's (`H320`).
- **`progress: (sent, total) => …`**, in a page's `net.send`, is told how
  many bytes of the body have gone, as they go, and once more at the end
  (`sent == total`). Its fn is one expression: call an action, which may
  set state (`progress: (s, t) => moved(s)`). With `progress` the request is
  made with an `XMLHttpRequest`, whose upload says how far it has got (a
  `fetch` says nothing of a body as it goes out; one that streams its body
  needs HTTP/2 and Chrome alone); the answer is the same. On the back end,
  and on `net.stream`, it is `H412`.

```mote
// docs: whole
// A large file sent in parts of 8 MB, each with its progress (to a service that takes parts).
state f: picked? = none
state sent = 0
state said = ""

action choose
  f = fs.pick("*", {read: false})?

action moved(n: number)
  sent = n

action upload
  if f == none return
  let from = 0
  while from < f.size
    sent = 0
    let a = net.send("PUT", `/parts/${from}`, {body: {file: f, from, length: 8000000}, progress: (s, t) => moved(s), timeout: 120000})?
    if !a.ok fail(`${a.status}: ${a.text}`)?
    from += 8000000
    said = `${Math.min(from, f.size)} of ${f.size} bytes sent`

column gap=8 padding=16
  button "Choose" press=choose
  button "Send" press=upload disabled=(f == none || pending(upload))
  text `${said} (this part: ${sent})`
```
- What Mote's own code holds is one piece of the answer at a time (64 KB
  from a file). Bun's `fetch` may read ahead of that when the network is
  faster than the disk, and gives memory back when it collects: a download
  of 256 MB was measured, in Bun 1.2.20, at between 60 and 400 MB more of
  the process at its peak. For files much larger than the machine's memory,
  test on the machine first.

Tested in `tests/files/app.mote` (`mote test`) and against a stand-in file
service: 256 MB written as it arrives, a slow answer seen on the disk before
it ends, one broken off and resumed, one broken off and not resumed, a file
and a part of one sent (`tests/all.sh real_netfiles`,
`tests/files_standin.mjs`). Source: `runtime/server/net.mote` (part `NFL`).

#### An address a person gave

A `server fn` that fetches what a person typed (a link's preview, a
webhook, a picture by its address) can be pointed at the back end's own
network: `http://localhost:8080/admin`, `http://169.254.169.254/` (a
cloud's keys), a public page that redirects there, or a name that answers
a public address when it is checked and a private one when it is fetched.
`public: true` closes all four:

```mote
server fn preview(url: string): string
  let a = net.send("GET", url, {public: true, timeout: 5000, max: 500000}) else err => fail("that link cannot be read")?
  if !a.ok fail(`the link answered ${a.status}`)?
  return a.text.slice(0, 2000)
```

With it the back end leads the request itself, one step at a time. For
each step (the address given, then every redirect) it looks the host's
name up **once**, refuses if any address it got is not public, and
connects **to that very address**: the `Host` header, the name the server
is asked for (SNI) and the name its certificate is checked against are
still the host's. Nothing is looked up a second time, so nothing can
answer the second time differently. Only `http:` and `https:` addresses
are taken, and none with a name and password in it.

Refused as not public: this machine (`127.0.0.0/8`, `::1`, `0.0.0.0/8`,
`::`), private networks (`10/8`, `172.16/12`, `192.168/16`, `fc00::/7`),
link-local (`169.254/16`, `fe80::/10`), carriers' inside (`100.64/10`),
multicast and what is kept back (`224.0.0.0` and above, `ff00::/8`,
`192.0.0.0/24`, `198.18/15`), and an IPv4 address written as an IPv6 one
(`::ffff:10.0.0.1`, NAT64, 6to4, Teredo). An address written oddly
(`http://2130706433/`, `http://0x7f.1/`) is read as the address it is.
The failure says which: `net: wiki.corp is at 10.1.2.3, which is not a
public address: refused`.

After a 303 (and a 301 or 302 to a `POST`) the next step is a `GET` with
no body, as in a browser; `authorization` and `cookie` headers do not
follow to another origin.

`net.lookup(host)` gives a name's addresses (`string[]`; a name with none
is a failure) and `net.public(address)` says whether one is of the open
internet, for a program that wants to decide for itself; both are the
back end's. Checking with them and then fetching by name is the mistake
`public: true` exists to prevent: the name is then looked up twice.

What it leans on: Bun's `fetch` connecting to the address in the URL it
is given and honouring `tls.serverName` and `tls.checkServerIdentity`
(checked against Bun 1.2.20 and 1.4.5). If the back end is run behind an outbound
proxy (`HTTPS_PROXY`), it is the proxy that connects, to the address it
is handed.

### net.stream

`net.stream` comes back when the answer has begun, with its status and
headers, and gives the body piece by piece as it arrives: a model's reply
token by token, a long job's log.

```mote
// docs: whole
state prompt = ""
state reply = ""

server fn ask(prompt: string): string requires signedIn
  let me = auth.me()?
  let s = net.stream("POST", "https://api.example.com/v1/answers", {headers: {authorization: `Bearer ${env("API_KEY")}`}, body: {prompt, stream: true}, timeout: 30000})?
  if !s.ok fail(`${s.status}: ${s.rest()?}`)?
  let all = ""
  while true
    let e = s.event()?
    if e == none
      break
    if e.event == "delta"
      all += e.data
      emitTo(me?.id ?? "", "token", e.data)
  return all

on token(piece: string)
  reply += piece

action send
  reply = ""
  ask(prompt)?

column gap=8 padding=16
  input value=prompt submit=send
  text reply
  text (failure(send) ?? "") color=danger
```

| | |
|---|---|
| `s.status` `s.ok` `s.url` `s.headers` | As for `net.send`, there before any of the body. |
| `s.chunk()` | The next piece of the body's text, as it arrived; `none` at the end. |
| `s.chunkBytes()` | The next piece of the body as bytes, as it arrived; `none` at the end. For a stream that is not text: AWS's event stream, audio. Read a stream one way or the other. |
| `s.event()` | The next event of a `text/event-stream`: `{event, data, id}`; `none` at the end. |
| `s.rest()` | All that is left of the body, as text. |
| `s.stop()` | Lets go of the answer: nothing more is read, and the next `chunk()` or `event()` is `none`. |

- `chunk()`, `event()` and `rest()` wait and can fail (the line dropped).
- **An event** is the lines up to a blank one. `event:` names it
  (`"message"` if nothing does), each `data:` line is a line of `data`
  (several are joined with line ends), `id:` is its id (`""` if none). A
  line that begins with `:` is a comment and is skipped; so is a block with
  no `data` and no `event`. `data` is text: `JSON.parse(e.data)` where it is
  JSON.
- `timeout` is for the answer to begin. A stream may go on as long as it
  likes; stop one that has gone quiet with a `server every`, or do not.
- Options: `headers`, `body`, `form`, `multipart`, `auth`, `idempotency`, `retries`, `retryOn`, `retryWait`, `timeout`, `redirect`, and on the back end `public` and `allow`, as for `net.send`.
- A fn takes one as `s: stream`.

Both work in a page as well, under the browser's rules ([pitfalls](#pitfalls)).

## check

What comes from outside (a service's answer, a webhook's body, a file
read, `JSON.parse`) is `json`: it is whatever was sent. `check(value,
Shape)` holds it to a declared shape as the program runs, and is the value
typed, or a failure (kind `"invalid"`) that says where it differs and what
is there:

```mote
// docs: whole
shape Amount
  value: number
  currency: string

shape Charge
  id: string
  amount: Amount
  refunded: bool
  note: string?

server fn charges(): Charge[]
  let a = net.send("GET", "https://api.pay.example/v1/charges", {timeout: 10000})?
  return check(a.json?.data, [Charge])?

action load
  let cs = charges() else []
  log(cs.length)

button "Load" press=load
```

```text
[3].amount.value: a number was wanted, and there is "12"
refunded: yes or no was wanted, and there is none
```

- **What it takes**: a shape's name, a model's (its row), `string`,
  `number`, `bool`, `json`; `[T]` for a list of them; `{field: T, …}` for a
  record written there. A field that is `T?` may be `none` or missing; any
  other must be there. A shape that holds itself is followed as deep as the
  value goes.
- **Fields the shape has not**: `{extra: "keep"}` (unsaid) gives the value
  back as it came; `{extra: "drop"}` a copy without them; `{extra: "refuse"}`
  fails (`colour: the shape has no such field (it has value, currency)`).
- The failure's `data.path` is where (`err.data.path`), for a program that
  says it otherwise. Nothing is changed or turned into something else: `"12"`
  is not a number here.
- On either side, and it does not wait (it can fail: `?` or `else`).

**`schema(Shape)`** is its [JSON Schema](https://json-schema.org) (2020-12)
as a value, for a model service's structured output, a tool's parameters,
or an OpenAPI file: written out when compiled, nothing run. A shape inside
is written out where it stands (one that holds itself, once under `$defs`);
an object allows no field it has not (`additionalProperties: false`); an
optional field is not `required` and may be `null`; comments above a shape
and its fields are `description`s; `schema(fn)` is a fn's parameters.
`schema(Shape, {strict: true})` lists every field as `required`, as
OpenAI's and Anthropic's strict modes ask. The whole of it is
[language.md](language.md#a-shape-as-a-json-schema).

```mote
let tool = {name: "refund", description: "Refund a charge", input_schema: schema(Refund)}
```

Source: `runtime/shared/check.mote` (part `CHK`), `compiler/src/types/outside.rs`
(the shape described, `H318`), `compiler/src/types/schema.rs` (the schema).

## db

```text
db.get(k)   db.set(k, v)   db.del(k)   db.keys()   db.all()
db.persist()   db.persisted()   db.room()        of all the site keeps here
```

IndexedDB, keys to values. Values may be anything the browser can clone:
records, lists, bytes.

- `db.get(k)` gives `json`, or `none` when there is nothing: give it a type
  and a default, `saved = db.get("saved")? ?? []`.
- `db.keys()` is every key (`string[]`); `db.all()` is every `{key, value}`
  at once.
- `db.set` is done when the browser has it: one that there was no room for
  fails.

One store per page, named for the page's path
(`runtime/page/storage.mote`, part `DB`).

### Storage that stays

What a site keeps in a browser (`persist`, `db`, `fs`, `sql`, local models)
the browser may clear by itself when the device runs short of room, and
Safari after some weeks without a visit. It can be asked not to:

```mote
// docs: whole
state kept = false
state room = ""

task
  kept = db.persisted() else false
  let r = db.room() else none
  room = r == none ? "" : `${Math.round(r.left / 1048576)} MB left`

action keep
  kept = db.persist() else false

action save(photo: bytes)
  fs.write("roof.jpg", photo) else err => (err.kind == "full" ? toast("No room left on this phone.") : toast(`${err}`))

column gap=8 padding=16
  if !kept
    button "Keep my photos on this phone" press=keep
  text room color=dim
  button "Save" press=save(bytes.new(1000))
```

| | |
|---|---|
| `db.persist()` | Asks. `true` if the browser agreed (false if it has not said within three seconds). Firefox asks the person; Chrome and Safari decide by themselves, by whether the site is installed, bookmarked or much used, so it is worth asking again later. |
| `db.persisted()` | Whether it has agreed, and nobody is asked. |
| `db.room()` | `{used, left}` in bytes, as the browser says. A figure to go by, no more: every browser rounds it, and Chrome says 10 GB are left whatever the disk holds. |

**A full disk** (or the site's share of it) fails the write with a kind of
its own, `err.kind == "full"`: `fs.write`, `db.set`, `sql`, and a local
model's `add` and `set`. What was there before is still there: a file is
what it was (and a new one is not there), and a statement that did not fit
was not done.

## sql

SQLite itself: version 3.50.4, the SQLite project's own wasm, pinned
(`batteries/sqlite/README.md`), in a worker of its own.

```mote
// docs: whole
shape Row
  id: number
  name: string

state rows: Row[] = []
state said = ""

action seed
  let d = sql.open("shop")?
  sql.run(d, "create table if not exists wood(id integer primary key, name text)")?
  sql.run(d, "insert into wood(name) values (?)", ["oak"])?
  sql.batch(d, [["insert into wood(name) values (?)", ["ash"]], ["update wood set name = upper(name)"]])?
  rows = sql.run(d, "select id, name from wood where id > ?", [0])?
  let file = sql.bytes(d)?
  said = `SQLite ${sql.version()?}, ${file.length} bytes`

column gap=8 padding=16
  button "Seed" press=seed
  for r in rows key=r.id
    text `${r.id}: ${r.name}`
  text said color=dim
  text (failure(seed) ?? "") color=danger
```

| Call | Gives |
|---|---|
| `sql.open("shop")` | The database of that name, a `database`. Kept in the site's private files. |
| `sql.run(d, "select * from t where n > ?", [5])` | Its rows, as records by column name (`json`). Several statements separated by `;` run in turn, each taking as many of the values as it has `?`s, in order; the last rows are given. |
| `sql.batch(d, [["insert into t(a) values (?)", [1]], ["update …"]])` | All of them or none (one transaction). |
| `sql.bytes(d)` | It as a `.sqlite` file's bytes. |
| `sql.load(bytes)` | A database from such a file, in memory. |
| `sql.close(d)` · `sql.version()` | |

- A named database is written to its file after every statement that
  changes it, before the answer comes back (only the pages that changed).
- **The windows of one origin share a named database.** Two tabs that open
  the same name read and write the same rows: the file is one window's at
  a time, and they take it by turns. A window that wants it asks; the one
  that has it writes back what it changed and lets go between two calls (a
  `sql.batch`, and a model's `atomic` block, are one call for this); the
  one that takes it reads the file again if the other wrote to it. A window
  with no other beside it keeps the file and pays nothing. Two windows that
  both write at once each pay a re-read of the database per turn: fine for
  drafts and settings, not for a table two tabs fill at speed. (It rests
  on the browser's Web Locks, `BroadcastChannel` and private files' sync
  handles: Chrome, Edge, and Safari 15.4 and later, Firefox 111 and later.
  Recorded in Chrome by `tests/tabs`, and not yet run in the others; where a browser has no Web Locks, a
  second window's `sql.open` fails as it used to: `` `app` is open in
  another window``.)
- Values go in and come out as numbers, text, `none` and bytes. A record or
  a list is stored as its JSON; a bool as 1 or 0.
- Give the rows a type: `let rows: Row[] = sql.run(…)?`.
- A statement that there is no room for fails with the kind `"full"`
  ([storage that stays](#storage-that-stays)) and leaves the database, in
  memory and on the disk, as it was before it.
- An integer too large for a number (beyond 2^53) comes out as text.
- Several statements in one `sql.run` are cut at each `;` that is not
  inside a string or a comment, and the values are dealt out in order: each
  statement takes as many as it has `?`s. It is the same in the page and on
  the back end. They are not one transaction: for all or none, use
  `sql.batch`.

In a `server fn` the same calls run on Bun's SQLite; a named database is
`<name>.sqlite` in the data folder (`runtime/server/data.mote`, part `SQ`),
kept with a write-ahead log like every database there, and in its
[snapshots](back-end.md#snapshots).

**Before writing tables by hand, see [models.md](models.md).** A `model`
declares the table, gives typed `find`/`add`/`set`/`del` with no SQL, keeps
lists current, and follows a schema as it changes. Models are kept in the
database `app` on each side, so `sql.open("app")` reads their tables for
what a model does not say (a count across tables, `like`).

## fs

```text
fs.text(path)   fs.bytes(path)   fs.write(path, data)   fs.del(path)   fs.list(dir)
fs.append(path, text)   fs.exists(path)   fs.info(path)   fs.entries(dir)
fs.move(from, to)   fs.mkdir(path)
fs.open(file)                       a reader: a file of any size, a piece at a time (below)
fs.writer(path, {append})           a file written as it is made (below)
fs.folder(path)                     in a server fn only
fs.save(data, name)                 downloads it
fs.pick("image/png,image/jpeg")     a file the user chooses
fs.pickMany("image/*")              several
fs.pickFolder(".txt,.md")           every such file in a folder they choose
fs.pick("image/*", {camera: "back"})          a phone's camera
fs.pickMany("image/*", {read: false})         several, not read yet: fs.bytes(f) reads one
```

- Private files: the page's are in the origin's private file system, which
  the user never sees. Folders on the way are made by `fs.write`,
  `fs.append`, `fs.move` and `fs.mkdir`.
- `fs.list(dir)` is the names in a folder (`string[]`); `fs.entries(dir)`
  each with what `fs.info` says of it, `{name, size, changed, folder}`, in
  the order of their names (`[]` for a folder that is not there).
- `fs.info(path)` is `{size, changed, folder}`: bytes, when it last changed
  (milliseconds), and whether it is a folder (whose time the private file
  system does not keep: `0`). Nothing there fails, kind `"missing"`.
  `fs.exists(path)` says whether anything is.
- `fs.append(path, text)` adds to the end, making the file if it is not
  there; `fs.move(from, to)` moves a file or a folder over what was there.
  In a page (not a worker) the browser writes an appended file through a
  copy of it, swapped in when done: for a file that grows large, append in
  an `off fn`, or keep an [`fs.writer`](#large-files) open.
- `fs.save(data, name)` hands the user a file to keep (a download).
- `fs.pick(accept)` opens the file chooser: `{name, path, data: bytes}`, or
  `none` if they choose nothing. `accept` is what an `<input type=file>`
  takes: kinds (`"image/png"`, `"image/*"`) or endings (`".txt"`),
  separated by commas. It may be left out.
- `fs.pickMany(accept)` lets them choose several: a list of the same
  records, empty if they choose none.
- `fs.pickFolder(accept?)` lets them choose a folder: every file in it and
  in the folders inside it that `accept` allows, in the order of their
  paths.
- **`path`** is where a file is from the folder that was chosen
  (`"trip/day1/a.jpg"`); for a lone file it is its name.
- A pick that is begun while another is still open ends the first, with
  nothing chosen.
- Files dropped on the page arrive through the `drop` event, a folder's
  files with their paths; pasted ones through `paste`
  ([events.md](events.md#the-events)).

A file a person sends for others to see (an attachment, a photo) is not
`fs`: it is a model's [`file` field](models.md#files), sent with
`files.upload`, kept by the back end and served by it under the model's
rules.

In a `server fn`, `fs` is files in the data folder; `fs.pick`,
`fs.pickMany`, `fs.pickFolder` and `fs.save` are the page's alone (a picker
there is `H185`). An `off fn` has the private files too, all but the
pickers and `fs.save`, which need a window (`H410`): see [Large
files](#large-files).

### The camera

`fs.pick("image/*", {camera: "back"})` opens a phone's camera instead of the
file chooser, `{camera: "front"}` the one that looks at the person. What
comes back is the file the phone made, byte for byte (`img.info(f.data)`
reads its Exif).

- **It is a wish.** A desktop browser ignores it and opens its file chooser;
  so may a phone with no such camera, or one that was told no.
- `"back"` or `"front"` is written there; another word, a value worked out,
  or `camera` on `fs.pickMany` or `fs.pickFolder`, is `H185`.
- Say it in the press itself: after a call that waits, a browser may no
  longer open anything.
- A camera that is left gives `none`. Where the browser says nothing of it,
  that is ten seconds after the page is back in front (a photo may arrive
  well after the page does), or at the next pick, whichever is first.
- A phone may close the page while its camera is open. What is in `persist`
  states is kept ([above](#persist-and-store)); keep there what the page
  needs to go on with.

### Files not read yet

A picker reads every file it was given into memory before it answers: ten
photos of a phone's are 100 MB. With `{read: false}` the files come back
unread, at once, as **picked** files (the type `picked`):

```mote
// docs: whole
state photos: picked[] = []
state notes: string[] = []

action choose
  photos = fs.pickMany("image/*", {read: false})?

action small
  notes = []
  for f in photos
    let im = img.decode(f, {fit: 1600}) else err => none
    notes.push(im == none ? `${f.name} could not be read` : `${f.name}: ${im.width} by ${im.height}`)

column gap=8 padding=16
  button "Choose photos" press=choose
  for f in photos
    text `${f.name}, ${Math.round(f.size / 1024)} KB`
  button "Shrink them" press=small disabled=pending(small)
  for n in notes
    text n color=dim
```

| | |
|---|---|
| `f.name` `f.path` | As for any picked file. |
| `f.size` | In bytes. |
| `f.type` | What the browser takes it to be (`"image/jpeg"`), `""` if it cannot say. |
| `f.modified` | When it was last changed, in milliseconds. |
| `fs.bytes(f)?` `fs.text(f)?` | Its bytes, or its text, read now. Each call reads it again; the page holds only what you keep. |
| `img.decode(f)?` `img.info(f)?` `img.frames(f)?` | Read in the worker: its bytes never come to the page. |
| `files.upload(f)?` | Sent from the disk as it is read, never whole in memory. |

- **Each call fails for its own file**: one that was moved, deleted or
  changed since, or is in a cloud that cannot be reached, says so
  (``fs: `roof.jpg` could not be read``), and the others are unharmed.
- It is a value like another: it can stand in state, in a record or a
  shape (`{photo: f, note: ""}`), in a `for`, and be handed to an `off fn`
  and back. `db.set(k, f)` keeps it, and the file with it.
- It is a hold on a file, not data: a `persist` state, a model's field, or
  a `server fn`'s parameter that has one in it is `H186`. Nor can it be
  written by hand.
- All three pickers take `{read: false}`, and `fs.pick` both it and
  `camera`. `read` is written there (`H185`).
- A drop and a paste hand over files read.

### Large files

A file of gigabytes is read a piece at a time and never held whole:
`fs.open` gives a **reader**, and a reader is what a .zip's entry, a .gz
and a .tar give too. A file is written the same way, as it is made, with
`fs.writer`.

```mote
// docs: whole
// A mail archive of many gigabytes, a message at a time; where it got to is kept, so a reload
// (or a closed tab) goes on from there once the file is picked again.
state archive: picked? = none
state offset = 0 persist
state count = 0 persist
state said = ""

shape Read
  offset: number
  count: number

// Messages from where `r` is, each from its "From " line to the next one's, a thousand at most.
fn messages(r: reader, count: number): Read
  let n = count
  while n < count + 1000
    let start = r.at
    let next = r.find("\nFrom ")?
    let m = r.read(next == none ? 100000000 : next + 1 - start)?
    if m == none break
    n += 1
  return {offset: r.at, count: n}

action choose
  archive = fs.pick(".zip", {read: false})?

action more
  if archive == none return
  let r = zip.open(archive, "Takeout/Mail/All mail.mbox")?
  r.seek(offset)?
  let got = messages(r, count)?
  r.close()
  offset = got.offset
  count = got.count
  said = `${count} messages, ${Math.round(offset / 1000000)} MB in`

column gap=8 padding=16
  button "Choose the archive" press=choose
  button "A thousand more" press=more disabled=(archive == none || pending(more))
  text said
```

**`fs.open(file)?`** takes a private file's path (the back end: a path in
the data folder), a file [picked unread](#files-not-read-yet), or bytes.
`zip.open`, `zip.gunzipStream` and `tar.entries` give the same kind of
reader (below). The type is `reader`, for a fn's parameter.

| | |
|---|---|
| `r.size` | How many bytes it has (`number?`: `none` where that is not known until the end, as for what gunzip gives). |
| `r.at` | Where it is: the offset of the next byte it gives. |
| `r.read(n)?` | The next `n` bytes, fewer at the end; `none` when nothing is left. |
| `r.readUntil(end)?` | The bytes before `end` (a text or bytes), which is passed over; at the end, what is left; `none` when nothing is. As a socket's `readUntil`, but a file's end is no failure. |
| `r.line()?` | The text before the next line end (`\n` or `\r\n`); `none` at the end. |
| `r.find(end)?` | The offset of the next `end` from where it is, or `none`; nothing is passed over. With `r.at` and `r.read(n)`, what cuts a file at a delimiter that belongs to the next part. |
| `r.seek(offset)?` | Goes there. |
| `r.readAt(offset, n)?` | `n` bytes from anywhere (fewer at the end), where it is left as it was: a file's, and an entry of a .zip stored as it is. Another (one inflated as it is read) fails, kind `"invalid"`: `seek` and `read` it instead. |
| `r.close()` | Lets the file go (a private file held in a worker is held until then). |

- What a reader holds is the piece it read last, a megabyte, and what of it
  is not given yet. `readUntil`, `line` and `find` read on, twice as far
  each time, until they find what they look for: past 64 MB they fail,
  kind `"toobig"`.
- An `r.seek` back, in what is inflated as it is read, inflates it again
  from its start; forward, it inflates and lets go up to the place. A file
  and a stored entry go there at once.
- Failures have kinds: `"missing"` (no such file, no such entry),
  `"invalid"` (a `seek` past the end, a `readAt` it cannot do),
  `"damaged"` (a .zip, .gz or .tar that breaks its own rules, a checksum
  that does not match, data that ends early), `"unsupported"` (an
  encrypted entry, a method other than stored and deflate, an archive in
  several parts), `"unreadable"` (a picked file changed or moved since it
  was picked), `"closed"`, `"toobig"`.

**A mailbox (`.mbox`)** is messages one after another, each beginning at a
line that begins `From `. Message by message: `let start = r.at`, `let next
= r.find("\nFrom ")?`, then `r.read(next + 1 - start)?` (all that is left
when `next` is `none`). The offset to keep, to go on from later, is `r.at`
after a message, which is where the next one's `From ` is.

#### Archives

```text
zip.entries(file)               what a .zip holds: {name, size, packed, modified, folder}[]
zip.open(file, name or entry)   a reader of one entry, inflated as it is read
zip.gunzipStream(reader)        a reader of what a .gz holds, inflated as it is read
tar.entries(reader)             a .tar an entry at a time: t.next()?, t.close()
```

- `zip.entries` reads a .zip from its end: its list, and nothing of what is
  in it. Zip64 is read (an archive over 4 GB, or of more than 65,535
  entries). `modified` is in milliseconds (the entry's own UTC time where it
  has one, else the archive's local time); a name that does not say it is
  UTF-8 is read as UTF-8, else in the DOS code page.
- `zip.open(file, entry)` takes the entry by its name or as `zip.entries`
  gave it (which saves reading the list again). A deflated entry is inflated
  as it is read, and its CRC-32 and size checked when its end is reached. A
  stored one is read where it lies, and can be read anywhere (`readAt`); its
  checksum is not checked.
- `file` is anything `fs.open` takes, or a reader that can read anywhere (a
  stored entry, for a .zip inside a .zip).
- `zip.gunzipStream(r)` reads every member of a .gz, one after another, and
  checks each one's CRC-32 and size.
- `tar.entries(r)` gives an entry at a time: `t.next()?` passes over what is
  left of the one before and gives the next, a reader of its bytes with
  `name`, `kind` (`"file"`, `"folder"`, `"link"`, `"other"`) and `modified`;
  `none` at the end. Ustar, with pax's and GNU's long names and sizes.

```mote
// docs: whole
state said = ""

// Each entry of a .tgz: its name, and the first line of each text file.
action look
  let f = fs.pick(".tgz,.tar.gz", {read: false})?
  if f == none return
  let t = tar.entries(zip.gunzipStream(fs.open(f)?)?)?
  let lines: string[] = []
  let e = t.next()?
  while e != none
    if e.kind == "file" && e.name.endsWith(".txt")
      lines.push(`${e.name}: ${e.line()? ?? ""}`)
    else
      lines.push(`${e.name} (${e.kind}, ${e.size ?? 0} bytes)`)
    e = t.next()?
  t.close()
  said = lines.join("\n")

button "Look inside a .tgz" press=look
text said white-space=pre-line
```

#### Writing as it is made

**`fs.writer(path, {append})?`** opens a private file to be written a piece at
a time (`append: true` goes on at its end; unsaid, it starts empty). The type
is `writer`.

| | |
|---|---|
| `w.write(data)?` | Text (UTF-8) or bytes, added. A full disk fails, kind `"full"`. |
| `w.close()?` | Done: in a page, this is when what was written takes the file's place. |
| `w.size` `w.path` | The file's size so far, and its path. |

#### Sealed files

A file can be written encrypted as it is made, and read back decrypted a
piece at a time, so that none of it is ever on the disk in the clear:

```mote
// docs: whole
state said = ""

// A file of the device sealed under a key that cannot be read back, and read a line at a time.
action keep
  let key = crypto.aes.key(crypto.randomBytes(32))?
  let w = fs.writer("notes/today.sealed", {seal: key})?
  w.write("first line\n")?
  w.write("second line\n")?
  w.close()?
  let r = fs.open("notes/today.sealed", {seal: key})?
  said = `${r.size ?? 0} bytes: ${r.line()? ?? ""}`
  r.close()

button "Keep and read" press=keep
text said
```

**`fs.writer(path, {seal: key})?`** writes the file sealed;
**`fs.open(file, {seal: key})?`** reads one (a path, a file picked
unread, or bytes). `key` is 32 bytes or what
[`crypto.aes.key`](#a-key-that-cannot-be-read-back) gave. The writer and
the reader are the ones above: `w.write`, `w.size` (the bytes written, not
the file's), `r.read`, `r.line`, `r.find`, `r.seek` and `r.readAt` (both
anywhere, at once), `r.size` (the bytes sealed in it).

- **What is held in the clear** is one chunk of 64 KiB: the writer seals a
  chunk once it is full and more comes (until then it may be the last),
  the reader opens the chunk it is in. Each is zeroed when the writer or the
  reader is closed. A reader's piece (what `read(n)` gives, what `line`
  looks through) is the program's, as with any reader.
- **A writer that never closes** (the process ended, the disk filled)
  leaves its full chunks, sealed, and nothing else: no reader takes that
  file (`"damaged"`: its last chunk is not there).
- **Refused, kind `"damaged"`**, in the same words whichever it is: a bit
  changed anywhere (header, chunk or tag), a chunk moved, put twice or
  dropped, the file cut short (at a chunk's edge too), something added at
  its end, another key, a file that was never sealed. Checked when it is
  opened (the header, and the last chunk, which says the file's size) and
  as each chunk is read. A form a later version writes is `"unsupported"`;
  a key that is not one, `"invalid"`.
- `seal` is written out where the call is (`H475` for choices given as a
  value): a file meant to be sealed is never written plain by a choice
  that went missing. A sealed file is written whole, from its start:
  `{seal, append: true}` is `H476`.
- Give sealed files a key of their own, not one the program also seals
  other things with by `crypto.aes.seal` with nonces of its own choosing.
- Works in a page, in an `off fn` (in place, as any private file) and in a
  `server fn` (the data folder). AES-GCM is the host's (WebCrypto), as for
  `crypto.aes`.

**The format**, for another program that reads or writes one:

```text
header    24 bytes: "moteseal" (ASCII, 8 bytes) · version 1 (1 byte) · 16, the chunk size's
          log2 (1 byte) · two zero bytes · N, 12 random bytes (new for each file)
file key  K' = the first 32 bytes of AES-256-GCM-encrypt(K, nonce N, 32 zero bytes)
          (that is AES_K(N‖00000002) ‖ AES_K(N‖00000003)); its tag is not used
chunk i   AES-256-GCM-encrypt(K', nonce = i as 11 bytes big-endian ‖ L, plaintext, AAD = the
          24-byte header): the ciphertext, then its 16-byte tag. L is 01 for the last chunk,
          00 for every other. Every chunk but the last holds 65,536 bytes; the last holds
          1 to 65,536 (0 only when the whole file is empty, which is one empty last chunk).
file      header ‖ chunk 0 ‖ chunk 1 ‖ … ‖ last chunk
size      with B = file size − 24 and n = ⌈B / 65,552⌉: B − 16·n bytes sealed; a B under 16,
          or whose remainder by 65,552 is 1 to 15, is no sealed file
```

This is the STREAM construction (Hoang, Reyhanitabar, Rogaway and Vizár,
2015) over AES-256-GCM, as `age` uses it: the chunk's number in its nonce
and the last chunk marked make the order and the end part of what is
authenticated, and the header, as every chunk's AAD, binds them to this
file. A file key of its own (made from the random N) means the counter
nonces never repeat under one key, however many files a key seals; N is
drawn at random, so one key seals some 2^32 files before the chance of two
alike is worth a thought (NIST SP 800-38D's bound for random nonces).
`tests/mail_spool.drive.mjs` opens a sealed file with Node's own AES-GCM by
this description alone.

**Why the file key is made with AES-GCM, not HKDF.** `seal` takes 32
bytes or a key `crypto.aes.key` made, whose bytes the program never holds.
An AES key the host keeps does one thing, encrypt and decrypt: it cannot be
HKDF's key material (WebCrypto derives only from an HKDF key, and
`crypto.hkdf` refuses an AES key, `H462`), and its bytes cannot be had to
make one. Running the cipher itself over the file's nonce is the one
derivation that works for both, and gives the same file key for both: a
file sealed with the bytes `K` opens with `crypto.aes.key(K)`, and the
other way round. It is AES used as a pseudorandom function on inputs no
other file uses (N is new for each file), as AES-GCM-SIV makes its
per-nonce keys (RFC 8452). An HKDF key (`crypto.hkdf(…, {as: "hkdf"})`)
could be taken as a third kind of seal, but its file key would differ from
that of the same 32 bytes given plainly, so it is not: derive an AES key
with `crypto.hkdf(material, {…, as: "aes"})` and seal with that (it
opens with the bytes the same derivation gives). `tests/sealed/app.mote`
checks each of these. The format stays version 1 as written above.

Tested in `tests/sealed/app.mote` (`mote test`, in `tests/all.sh
real_mail_spool`): in a page and in an `off fn`, each sealing a file and
reading it and the other's back, with a key of bytes and one the page
holds; on the back end, every size about a chunk's edge (0, 1, 65,535, 65,536,
65,537, 131,072, 200,000 bytes), written in uneven pieces and read back,
their files' sizes as above; no piece of the text in the file, and a new N
each time; lines, finds, seeks back and forth, `readAt` across chunks; a
key `crypto.aes.key` made, each opening what the other sealed; a key
`crypto.hkdf(…, {as: "aes"})` derived; another key; a bit changed, the header changed,
the last chunk cut off, a file cut in a chunk, two chunks swapped, one
dropped, one added, a file never sealed, a later version; a writer left
open. Source: `runtime/shared/files.mote`, part `SLD`.

#### What runs where

Every call above works in a page, in an `off fn` and in a `server fn`.

- **In a page**, a private file is read from the file as the browser hands
  it over, and written through a writable, which the browser writes beside
  the file and swaps in when it is closed (so a file opened with `append`
  is copied first, and a page that closes before `close()` leaves the file
  as it was).
- **In an `off fn`** (a worker), a private file is read and written where it
  lies, through a handle that reads and writes it in place: the fast way.
  A writer holds its file until it is closed, and nothing else may write it
  meanwhile (`"busy"`); readers share it where the browser can (Chrome 121
  on), else each reads it as the page does. A file picked unread goes to an
  `off fn` as it is; a reader or a writer does not (it stays where it was
  opened: `H410`). Open the file in the `off fn`.
- **In a `server fn`**, `path` is in the data folder.
- What inflates is the zip battery, in Rust: in a page each piece is
  inflated by the worker pool (the stream's state, its last 32 KiB, goes
  with the piece and comes back), in a worker and on the back end in place.

#### Going on after a reload

A reader's place is a number: keep `r.at` (a `persist` state, or `db`)
and `seek` there when the file is opened again.

- A **private file** is still there after a reload: open it by its path,
  `seek`, read on.
- A **file picked** must be picked again after a reload: the page is given
  a hold on it only for as long as it is open. A picked file can be kept in
  `db` (`db.set("archive", f)`), but the browser then keeps a copy of its
  bytes in the site's storage: not for a file of gigabytes. Mote has no
  way to keep a hold on a file of the person's own across a reload without
  a copy (the File System Access API's handles, which Chrome alone has).
- To have a large file across reloads without picking it again, copy it in
  once, a piece at a time: `fs.open(picked)`, `fs.writer(path)` in an
  `off fn`, then read the private copy.

Tested in `tests/bigfiles/app.mote` (`tests/all.sh real_bigfiles`): a
.zip of about 3 GB made for the run (a filler stored, then an .mbox of about
550 MB deflated, past 2^31 bytes, with zip64's records), picked, its list
read, its mail read message by message to half way, the page reloaded, the
file picked again and the rest read from the kept offset, every message
counted and checked in order. Meanwhile the page's JavaScript heap stayed
at about 2 MB and the tab's process rose by about 200 MB at most (what the
browser collects later), the same at the end of the read as at its start;
the numbers of each run are in `tests/out/bigfiles-memory.txt`. Also a
private file written in a worker and read there across a reload, the same
read on the page, a .tgz of two gzip members with a pax header, and the back
end's readers and writers (`tests/bigfiles_server/app.mote`, `mote test`).
Source: `runtime/shared/files.mote` (parts `RDR`, `FSO`, `ZPS`, `TAR`),
`runtime/page/storage.mote` (`FSOP`, `FWR`, `FS`), `runtime/server/data.mote`,
`batteries/flate/core.rs` (`inflate_more`).

## clipboard

```mote
// docs: whole
state names: string[] = []
state said = ""

action many
  let files = fs.pickMany("image/*")?
  names = files.map(f => f.name)

action folder
  let files = fs.pickFolder(".txt,.md")?
  names = files.map(f => `${f.path} (${f.data.length})`)

action share
  clipboard.put(names.join("\n"))?
  said = "copied"

action read
  said = clipboard.text() else err => `refused: ${err}`

column gap=8 padding=16
  row gap=8
    button "Pictures" press=many
    button "A folder" press=folder
    button "Copy the names" press=share
    button "What is on the clipboard?" press=read
  for n in names
    text n
  text said color=dim
```

| Call | Gives |
|---|---|
| `clipboard.text()` | The words on the system's clipboard; `""` if it holds none. |
| `clipboard.image()` | The picture on it, an `image`, or `none` if it holds none. |
| `clipboard.put(text or picture)` | Puts words, or an `image` (as a PNG), on it. |

- **Each can fail.** The browser decides whether the page may: it wants a
  press or a key just before, may ask the reader, and needs a secure page
  (https or localhost). Settle each call with `else` or `?`.
- `clipboard.put` takes text or an `image`; anything else is refused
  (`H064`). A sheet's picture is `paint.image(sheet)`; a file's is
  `img.decode(bytes)?`.
- `copy(text)` is the one that never waits or fails
  ([language.md](language.md#built-in)).
- A `paste=` handler is told what is pasted and needs nobody's leave
  ([events.md](events.md#the-events)).

Source: `runtime/page/popover.mote`, part `CB`.

## share

The share sheet of the person's phone (or of a desktop that has one), with
the page in it:

```mote
// docs: whole
app "Shop" "Cabinets drawn by you."

state said = ""

action table
  said = share({title: "Oak table", text: "Drawn by Ada", url: route.link("/t/7")})

action photo
  let f = fs.pick("image/*")?
  if f == none return
  said = share({files: [f], title: f.name})

column gap=8 padding=16
  button "Share" press=share()
  button "Share the table" press=table
  button "Share a photo" press=photo
  text said color=dim
```

| Call | Gives |
|---|---|
| `share()` | Opens the share sheet with this page: its title (a route's own, if it says one), its description and its address. |
| `share({title, text, url, files})` | The same, saying any of them itself. `files` are `{name, data}`, as `fs.pick` gives them, where the sheet takes files (else they are left out). |

- **It gives how it went, and never fails**: `"shared"`, `"cancelled"`
  (the person closed the sheet: not a failure, nothing is logged),
  `"copied"` or `"shown"`.
- **With no share sheet** (most desktops), or one that will not take
  this, the address is copied and a toast says so ("Link copied", and the
  address): `"copied"`. With no clipboard either (a page not served over
  https), the toast holds the address to copy by hand: `"shown"`.
- A phone opens the sheet only for a press: call it from a `press=`, or
  an action a press starts, before anything else waits.
- The address of a route that says its own title, description or picture
  is its path (`https://shop.example/pricing`) where the back end serves
  the page, so the preview a chat shows is the route's
  ([markup.md](markup.md#a-shared-link)); otherwise the address as it
  stands (`…/#/pricing`).
- It is the page's: in a `server fn` it is `H173`, as is anything but one
  record of those four fields. A program with a `share` of its own (a
  fn, a state) has its own.

Source: `runtime/page/share.mote`, part `SHR`. Recorded in
`tests/expect/real_share.txt`.

## crypto

| Call | Gives |
|---|---|
| `crypto.hash(data, kind?)` | SHA-256, as hex. `kind` asks for another: `"sha1"`, `"sha256"`, `"sha384"`, `"sha512"`; and `"md5"`, **not for security** (MD5 is broken: anyone can make two inputs of one MD5), only for a protocol that still asks for it (Postgres's `md5` password exchange, an old checksum). Written out where it is asked for: `"md5"` in a value fails. |
| `crypto.hash(data, "sha3-256")` | SHA-3 (FIPS 202): `"sha3-256"`, `"sha3-512"`; the two SHAKEs, `crypto.hash(data, "shake256", {length: 64})` (`length` bytes of it: 32 unsaid for `"shake128"`, 64 for `"shake256"`); and BLAKE2b (RFC 7693), `crypto.hash(data, "blake2b", {length: 32, key})` (1 to 64 bytes, 64 unsaid; a key of 64 bytes at most). All as hex. Written out where it is asked for, as `"md5"` is: each is a battery's (the one ML-KEM is made of, the one argon2id is made of), and only a page that says the word fetches it. |
| `crypto.hmac(key, data, kind?)` | The HMAC (RFC 2104) of `data` under `key`, as `bytes`: `.hex()` writes it out, `.base64()` too. Key and data are each a text (taken as UTF-8) or bytes; SHA-256 unless `kind` says otherwise. |
| `crypto.equal(a, b)` | Whether two texts, or two byte arrays, are the same: a `bool`. It looks at every byte whatever it finds, so how long it takes tells nobody where they differ (only how long they are). This one cannot fail and does not wait. |
| `crypto.crc32(data)` | The CRC-32 of bytes or of a text (the one zip, gzip and PNG use): a number from 0 to 4294967295. `crypto.crc32("123456789")` is `0xcbf43926`. Cannot fail, does not wait. |
| `crypto.random(n)` | n random bytes, as hex. This one cannot fail and does not wait. |
| `crypto.randomBytes(n)` | n random bytes, as `bytes`: a key, a nonce, a salt. Cannot fail, does not wait. |
| `crypto.pbkdf2(password, salt, {iterations, length, kind})` | PBKDF2 (RFC 8018) with an HMAC of SHA-256 (or `kind`), `length` bytes (32 unsaid), as `bytes`. `iterations` must be said: what the other side asks (SCRAM says it), or 600000 for a password kept today. |
| `crypto.hkdf(key, {salt, info, length, kind})` | HKDF (RFC 5869) with an HMAC of SHA-256 (or `kind`): `length` bytes (32 unsaid) from key material, a salt and a label (text or bytes, each optional), as `bytes`. A key for each use from one secret: `crypto.hkdf(secret("MASTER"), {info: "sessions"})`. With `as: "aes"` it gives an AES key the host keeps instead of bytes, and the key material may be such a handle too: [a derived key that is never bytes](#a-derived-key-that-is-never-bytes). |
| `crypto.reveal(value)` | The value as it is, said to be meant to be seen or kept: the one way past [`H460`](#key-bytes-kept-or-shown). Nothing is added at run time. Does not wait, cannot fail. |
| `crypto.argon2id(password, salt, {memory: 19456, time: 2, parallelism: 1, length: 32})` | The argon2id hash (RFC 9106), as hex. The options are optional and those are their defaults (memory in KiB). `bytes: true`, written out, gives `bytes` instead of hex (a key to derive others from: `H340` where the word is not written out, since what the call gives depends on it). `secret` and `data` are Argon2's own secret value and associated data, each a text or bytes. Mote's own wasm, run in a worker. |

All of them work in a `server fn` too, the same (there `crypto.argon2id` runs
where it is called, and the back end answers nobody else until it is done:
64 MiB and three passes are a tenth of a second on a fast machine and several
on a slow one; an ML-KEM call is a millisecond or two). A page's own
encryption, key exchange and signatures are [next](#keys-of-the-pages-own).
Sealing a value at rest with a key the back end keeps (`crypto.seal`,
`crypto.open`) is the back end's: it is [below](#signatures-with-a-key-pair), beside its keys.

A secret is compared with `crypto.equal`, never with `==`, which stops at
the first letter that differs and so tells an attacker, by how long it
took, how much of a guess was right. A webhook whose sender signs the body
is checked so:

```mote
server route POST "/hooks/orders"(req)
  let body = req.text()?
  let signed = "sha256=" + crypto.hmac(env("HOOK_SECRET"), body)?.hex()
  if !crypto.equal(req.header("x-signature") ?? "", signed)
    return {status: 401, text: "that signature is not ours"}
  return {status: 200, text: "ok"}
```

`crypto.hash` and `crypto.hmac` with a `kind` that is not one of the four are
refused where it is written out (`H064`), and fail when it is a value.

### Keys of the page's own

For a page that encrypts before anything leaves it (the back end stores what
it cannot read), and for the back end the same calls. Keys, nonces, seeds
and signatures are raw `bytes`, as the standards write them.

```mote
// docs: whole
state sealed = ""
state opened = ""

// A key from a passphrase, a nonce that is new each time, and the note bound to its id.
fn seal(passphrase: string, id: string, note: string): string
  let key = crypto.argon2id(passphrase, "a salt of this user's", {bytes: true})?
  let nonce = crypto.randomBytes(12)
  let made = crypto.aes.seal(key, nonce, note, {aad: id})?
  return bytes.join([nonce, made]).base64()

fn open(passphrase: string, id: string, kept: string): string
  let key = crypto.argon2id(passphrase, "a salt of this user's", {bytes: true})?
  let all = bytes.base64(kept)?
  return crypto.aes.open(key, all.slice(0, 12), all.slice(12), {aad: id})?.text()

action go
  sealed = seal("correct horse", "note-1", "the plan")?
  opened = open("correct horse", "note-1", sealed)?

button "Seal and open" press=go
text sealed
text `${opened}${failure(go) ?? ""}`
```

| Call | Gives |
|---|---|
| `crypto.aes.seal(key, nonce, data, {aad})` | AES-256-GCM (NIST SP 800-38D): the ciphertext and then its 16-byte tag, as `bytes`, 16 longer than `data` (a text, taken as UTF-8, or bytes). `key` is 32 bytes; `nonce` is 12, and is **never used twice with one key** (`crypto.randomBytes(12)` each time, or a count); `aad` (a text or bytes, optional) is what the sealing is bound to and must be given again to open. Nothing is added or derived: the bytes are AES-GCM's own, so another implementation opens them. |
| `crypto.aes.open(key, nonce, sealed, {aad})` | What was sealed, as `bytes`. Fails, kind `"invalid"`, for one changed bit of the ciphertext, the tag, the `aad`, the nonce or the key, in the same words whichever it was. |
| `crypto.aes.key(raw)` | The key as the browser keeps it (WebCrypto's non-extractable key): `crypto.aes.seal` and `crypto.aes.open` take it wherever they take the 32 bytes, and nothing reads its bytes back out. For a key that lives long: see [below](#a-key-that-cannot-be-read-back). |
| `crypto.hkdf(material, {salt, info, as: "aes"})` | An AES key derived by the host and kept by it, never bytes: what `crypto.aes.key` gives, made of the 32 bytes HKDF would have given. `crypto.hkdf(material, {as: "hkdf"})` is key material to derive from again, kept the same way. [Below](#a-derived-key-that-is-never-bytes). |
| `crypto.hkdf.key(raw)` | Key material (a passkey's PRF output, a shared secret) as the host keeps it: `crypto.hkdf` takes it in the place of bytes, and nothing reads them back out. |
| `crypto.x25519.keyPair(seed?)` | `{private, public}`, 32 bytes each (RFC 7748). With a 32-byte `seed` the private key is the seed, the same pair each time; with none, 32 random bytes. |
| `crypto.x25519.shared(private, public)` | The 32 bytes both sides come to. Fails (`"invalid"`) where they would be all zeros: a public key of small order, which gives every private key the same secret. Make a key of them with `crypto.hkdf`; never use them as they are. |
| `crypto.ed25519.keyPair(seed?)` | `{private, public}`, 32 bytes each (RFC 8032): the private key is the 32-byte seed (given, or random), so the pair of a seed is the same each time. |
| `crypto.ed25519.sign(private, data)` | The signature, 64 bytes, of a text (as UTF-8) or bytes. The same each time (Ed25519 is deterministic). |
| `crypto.ed25519.verify(public, data, signature)` | Whether that key signed it: a `bool`. A signature that is not 64 bytes, or a key that is no point of the curve, is `false`, not a failure. |
| `crypto.mlkem768.keyPair(seed?)` | ML-KEM-768 (FIPS 203): `{decaps, encaps, seed}`, of 2400, 1184 and 64 bytes. `seed` is FIPS 203's `d` then `z`, given or random: keep the seed, from which `keyPair(seed)` makes the pair again, and publish `encaps`. |
| `crypto.mlkem768.encaps(encapsKey)` | `{ciphertext, shared}`, of 1088 and 32 bytes: send the ciphertext, keep the shared bytes. Fails (`"invalid"`) for a key that fails FIPS 203's check of one (a wrong length, a coefficient out of range). |
| `crypto.mlkem768.decaps(decapsKey, ciphertext)` | The 32 shared bytes. A ciphertext that was changed, or made for another key, gives 32 bytes all the same (FIPS 203's implicit rejection): bytes nobody else has, so whatever was sealed under them fails to open. Fails (`"invalid"`) for a key whose own hash check fails. |
| `crypto.pow(prefix, {bits, length})` | A proof of work: `length` bytes (16 unsaid, 4 to 64) that, written after `prefix` (a text or bytes), give the two a SHA-256 beginning with `bits` zero bits (0 to 40: `H341` for more, written out). What it gives is random bytes and then a count of four, the big end first. 18 bits are a quarter of a million hashes on average, some tens of milliseconds; each bit more doubles it. Checked with `crypto.hash`. |

All of them wait and can fail (`crypto.randomBytes` does neither).

**Where they run.** In a page, in a worker and on the back end, with the same
answers:

- on the page, where they are written: AES-GCM, X25519 and Ed25519 are the
  browser's own and run off the main thread by themselves; ML-KEM, argon2id
  and the proof of work are batteries, which the page sends to its workers;
- in an [`off fn`](reactivity.md#workers), which may call anything of
  `crypto` that a page may: a fn that derives keys and opens a thousand
  blocks does it all in a worker, and the page waits once. (Nothing else
  that waits is an `off fn`'s: `net`, `db` and the models stay the page's.)
- in a `server fn`, a route, a job, a test.

**Whose code each is.**

| | Code | In constant time |
|---|---|---|
| AES-256-GCM, X25519, Ed25519; SHA-2, HMAC, HKDF, PBKDF2 | The host's: WebCrypto in a browser and in Bun (X25519 on the back end is `node:crypto`'s, since Bun's WebCrypto has none). | The host's own care. |
| ML-KEM-768, with SHA-3 and SHAKE | Mote's, in Rust, as wasm (`batteries/mlkem`, 17 KB, 6 KB gzipped). | Written to be: no branch, no index into memory and no division depends on a secret; every reduction modulo q, and the division in Compress, is a multiplication and a shift (held to the true division over every value by a test); decapsulation compares the two ciphertexts whole and picks the key with a mask. The one loop whose length depends on data reads the public seed (FIPS 203's rejection sampling). What a wasm engine makes of that code is the engine's: it is given nothing secret to branch on, and no more than that can be promised of code that runs in a browser. |
| Argon2id, with BLAKE2b | Mote's (`batteries/argon2`). | Argon2id's first half-pass reads memory by position alone, by design; its later passes read it by what it holds, as the `d` in its name says. |
| The proof-of-work search | Mote's (`batteries/pow`, 2.4 KB). | Not, and need not be: nothing in it is secret. |

A battery that held a key or a password has its whole memory set to zero
after each call, and is started afresh for the next. What a program itself
holds (the bytes these calls gave it) is the program's, for as long as it
keeps them, and JavaScript gives no way to wipe that.

**A browser without them.** X25519 and Ed25519 came to WebCrypto in Safari 17
(2023), Firefox 130 (2024) and Chrome 133 and 137 (2025). In an older
browser `crypto.x25519.…` and `crypto.ed25519.…` fail, kind `"unsupported"`
(`crypto.x25519.shared: this browser has no X25519`): Mote carries no curve
code of its own to stand in. AES-GCM, ML-KEM, argon2id and the rest are in
every browser Mote runs in. Ask once as the page starts, and say so:

```text
resource curves = crypto.x25519.keyPair() else none
if curves == none
  text "This browser is too old to keep your data private here. Please update it."
```

**What a failure says.** The call, and one sentence written out in the
runtime: never a key, a nonce, what was sealed or what was to be opened.
`crypto.aes.open` says the same of every way a sealing can be wrong.

#### A key that cannot be read back

`crypto.aes.key(raw)` hands the 32 bytes to the browser and gives a handle
in their place (and `crypto.hkdf(…, {as: "aes"})` derives one with no bytes
at all, [below](#a-derived-key-that-is-never-bytes)):

```text
let vaultKey = crypto.hkdf(material, {salt: "app/v1", info: "enc", as: "aes"})?
let sealed = crypto.aes.seal(vaultKey, nonce, note, {aad: id})?
db.set("vault-key", vaultKey)?        // kept as a key, in IndexedDB
```

- Nothing in the page reads its bytes: not the program, not a script that
  got into the page. Written as JSON (a `persist` state, a `log`, an
  argument of a `server fn`) it is `{}`.
- `db.set` keeps it as it is, and `db.get` gives it back, still unreadable
  (IndexedDB stores WebCrypto keys whole). A `persist` state cannot: it would
  keep `{}`. An `off fn` may be handed one.
- The bytes it was made from (by `crypto.aes.key`) are still wherever the
  program left them: drop them (let the name go) once the handle is made.
  One derived `as: "aes"` was never bytes.
- Only AES, and HKDF's key material, have one. X25519, Ed25519 and ML-KEM keys are bytes: a page that
  must show a public key, or keep an identity in a vault it encrypts, needs
  them as bytes, and ML-KEM's are Mote's own code's, which a browser's key
  store cannot hold.

#### A derived key that is never bytes

`as: "aes"` asks HKDF for the key itself rather than its bytes: the host
derives it (WebCrypto's `deriveKey`, in the page, in a worker and on the
back end) and gives the handle that `crypto.aes.key` gives, so the derived
key is never in the program's hands, nor in a script that got into the page.
The key material may itself be a handle, so a chain of derivations stays
handles from its first step:

```mote
// docs: whole
state said = ""

// A passkey's PRF output (here, 32 bytes for the example) held by the host at once; a key for
// each use derived from it; none of them ever bytes.
action go
  let material = crypto.hkdf.key(crypto.randomBytes(32))?
  let notes = crypto.hkdf(material, {salt: "app/v1", info: "notes", as: "aes"})?
  let nonce = crypto.randomBytes(12)
  let sealed = crypto.aes.seal(notes, nonce, "the plan", {aad: "note-1"})?
  db.set("material", material)?
  said = crypto.aes.open(notes, nonce, sealed, {aad: "note-1"})?.text()

button "Derive and seal" press=go
text `${said}${failure(go) ?? ""}`
```

- **`as: "aes"`**: an AES-256-GCM key, for `crypto.aes.seal` and
  `crypto.aes.open`. It is the 32 bytes HKDF gives (so `length` is 32 or
  unsaid: `H461` for another, written out): sealed under one nonce, it gives
  the same bytes as `crypto.aes.seal(crypto.hkdf(…same…)?, …)`.
- **`as: "hkdf"`**: key material to derive from again (the first `length`
  bytes, 32 unsaid). WebCrypto derives no HKDF key from another, so the
  runtime takes the bytes from the host, hands them straight back as a
  handle and sets them to zero: the program never holds them, but for that
  moment they are in the page's memory, where a script already in the page
  could reach them as it could reach anything the page does.
- **`crypto.hkdf.key(raw)`**: bytes the program has (a PRF output, a shared
  secret) made key material the host keeps; drop the bytes afterwards.
- `crypto.hkdf` with a handle and no `as` gives bytes, as it does of bytes.
- `as` is written out where the call is (`H461`): what it gives depends on
  it. An AES key is not key material, and HKDF material seals nothing
  (`H462`, and at run time `"invalid"`).
- Bun's WebCrypto has HKDF's `deriveKey`, so the back end does the same.

**Tested** against RFC 5869's cases A.1, A.2 and A.3: the bytes are the
RFC's, and a handle (by `as: "aes"`, and by `crypto.hkdf.key` then
`as: "aes"`) seals what the RFC's first 32 bytes seal, byte for byte; a
chain through `as: "hkdf"` seals as the chain of bytes does; each on the
page, in a worker and on the back end (`tests/all.sh real_derived`).

#### Key bytes kept or shown

The compiler follows key bytes from where they are made to where they would
be kept or seen in the clear, and refuses the program there (`H460`):

```text
error[H460]: the `persist` state `kept` would keep, in the clear, key bytes: what `crypto.hkdf` gave
```

- **Key bytes** are what these give: `crypto.hkdf` (with no `as`),
  `crypto.pbkdf2`, `crypto.argon2id(…, {bytes: true})`,
  `crypto.x25519.shared`, `crypto.mlkem768.decaps`, the `shared` of
  `crypto.mlkem768.encaps`, the `private` of an X25519 or Ed25519 key pair,
  the `decaps` and `seed` of an ML-KEM one, and a passkey's `prf.first` and
  `prf.second`. Random bytes (`crypto.randomBytes`, `crypto.random`) are a
  nonce or a salt as often as a key, so they count only where the program
  uses them as a key somewhere (a key of `crypto.aes`, the material of
  `crypto.hkdf` or `crypto.hkdf.key`, a seed of a key pair, a key of
  `crypto.hmac`): no name is guessed from.
- **Made of key bytes** is key bytes too: text made of them, `.hex()`,
  `.slice(…)`, `bytes.join`, a record or a list holding them. What the host
  makes of them is not: a ciphertext, a signature, a MAC, a hash, a handle,
  `.length`, a comparison. A key pair's `public` (and an ML-KEM pair's
  `encaps`, an encapsulation's `ciphertext`) are free.
- **Where they may not go**: a `persist` state (localStorage), `store.set`,
  `db.set` (IndexedDB: both are the browser's storage on disk, not
  encrypted, readable by any script of the site), `log` and `log.*`,
  `toast`, `fail`'s words and data, the page's text and attributes, the
  props of a component of the kit, and the arguments of a `server fn` a page
  calls. A handle may go to `db.set`, which keeps it whole.
- **Across fns**: what a fn gives back is followed through each call, by
  what that call hands it (a public key in, a public key out); a parameter
  that some call hands key bytes is key bytes in all of that fn (one answer
  for every call); random bytes handed to a parameter that is used as a key
  are a key. A component's props are its parameters. The same in a page, a
  worker and the back end.
- **Not followed**: a value read back from where it was kept (a model's
  row, `db`, a file, the back end's answer); what the kit's fns and
  components do inside; a value put into a list or record and changed
  through another name for it; `net`, `fs` and a model's rows on the back
  end, which are not refused (a back end that keeps a key in a row seals it
  with `crypto.seal`). Branches are not told apart: a name that holds key
  bytes on one path holds them on all. `test` blocks are not read (they are
  not shipped).
- **When it is meant** (a recovery key shown once, a key written out for
  another program, a test that compares derived bytes with a standard's):
  `crypto.reveal(x)` is `x`, said to be meant. It is a call, not a comment,
  so that it says which value and stays with it through every edit; nothing
  of it is left at run time.

This is the compiler's, not the run time's: nothing marks the bytes as the
program runs, since a mark would be lost on the first `.slice`, on the way
to a worker and on the way to the back end, and a log line that hid every
32 bytes would hide hashes too.

[`secret("KEY")`](back-end.md#secrets) is the back end's own: its value is
cut out of every log line there, and the compiler refuses a `server fn`
that returns it (`H136`). It is not extended to the page, whose keys are
made as it runs, not named in its settings: the check above is the page's
(and the back end's for the keys it derives).

**Tested** against the standards' own vectors, each on the page, in a
worker and on the back end: RFC 7748 (5.2, 6.1), RFC 8032 (7.1, TEST 1024
among them), RFC 9106 (5.3), GCM's own test cases 13, 14 and 16; and the
published sets: NIST's ACVP vectors for ML-KEM-768 and C2SP's CCTV
(`strcmp`, `unluckysample`, and every encapsulation key with a coefficient
out of range), the Keccak team's ShortMsgKAT for SHA3-256, SHA3-512,
SHAKE128 and SHAKE256, BLAKE2's own known answers for BLAKE2b (with and
without a key), and the Argon2 reference implementation's known answer and
Argon2id tests (up to 256 MiB). `tests/crypto/` (`tests/all.sh real_crypto
real_crypto_vectors`; recorded in `tests/expect/real_crypto.txt`), and
natively in `compiler/src/tests_crypto.rs`. The published sets are fetched,
not kept in the repository: `tests/crypto/fetch.sh` takes each from its
source at a pinned commit and checks its SHA-256 (tests/crypto/README.md).

### Signatures with a key pair

On the back end. `crypto.hmac` is for two parties that share one secret;
these are for a signature anyone holding the public key can check, and for
tokens another service signed.

```mote
// docs: whole
state said = ""

// What a service that signs people in says of someone, as a token (a JWT): taken only
// when one of that service's own keys signed it, and it is for this app, and not over.
server fn whoIs(token: string): string requires anyone limit 20 per minute by ip
  let keys = net.get(env("ISSUER_KEYS_URL"))?
  let claims = crypto.jwt.verify(token, keys, {iss: env("ISSUER"), aud: env("CLIENT_ID")})?
  return `${claims.email ?? claims.sub}`

// A receipt this back end signs, which anyone with its public key can check.
server fn receipt(order: string): string requires signedIn
  let signature = crypto.sign(secret("RECEIPT_KEY"), order, {alg: "ES256"})?
  return `${order}.${signature.hex()}`

server fn receiptHolds(order: string, signature: string): bool requires anyone
  return crypto.verify(env("RECEIPT_PUBLIC_KEY"), order, bytes.hex(signature)?, {alg: "ES256"})?

action ask
  said = receipt("order-17")?
button "Receipt" press=ask
text `${said}${failure(ask) ?? ""}`
```

| Call | Gives |
|---|---|
| `crypto.sign(privateKey, data, {alg})` | The signature of `data` (a text, taken as UTF-8, or bytes), as `bytes`. |
| `crypto.verify(publicKey, data, signature, {alg})` | Whether `signature` (bytes; or text in base64url, as a token carries it) is that key's signature of `data`: a `bool`. |
| `crypto.encrypt(publicKey, data, {alg})` | RSA-OAEP: `data` that only the private key's holder can read, as `bytes`. `alg` is `"RSA-OAEP-256"` (SHA-256), or `"RSA-OAEP"` (SHA-1) where an older service asks for it. It takes a few bytes (a 2048-bit key: 190 with SHA-256): for more, `crypto.seal` the data and encrypt its key. |
| `crypto.decrypt(privateKey, data, {alg})` | The bytes, back; it fails (kind `"invalid"`) with another key or alg, or a changed byte. |
| `crypto.jwt.read(token)` | A token taken apart: `{header, payload, signed, signature}` (`header` and `payload` are `json`; `signed` is the text the signature is of). **Nothing is checked**: whoever made the token wrote every word of it. For looking at one, never for believing it. |
| `crypto.jwt.verify(token, keys, {aud, iss, leeway, algs, maxAge})` | The token's payload (`json`), once its signature is one of `keys`' and its claims hold. Fails otherwise, with why. |
| `crypto.jwt.sign(privateKey, claims, {alg, kid, typ})` | A token this back end signs: the claims as given (say `exp`, `iat`, `iss`, `aud` yourself, or use the [jwt extension](jwt.md)). HS256 takes `{secret: …}` as its key. |
| `crypto.keyPair(alg)` | A new key pair for that alg: `{private, public, kid}`, two JWKs, each with `kid` (the public key's [RFC 7638](https://www.rfc-editor.org/rfc/rfc7638) thumbprint), `alg` and `use: "sig"`. |
| `crypto.thumbprint(jwk)` | A public key's RFC 7638 thumbprint, in base64url. |
| `crypto.cert(pem)` | A certificate (X.509, `-----BEGIN CERTIFICATE-----`, or its DER as `bytes`) read whole: `{publicKey, subject, issuer, notBefore, notAfter, serial, sha1, sha256, …}` and what a chain is checked by ([below](#certificates-read-whole-and-their-chains)). `publicKey` is PEM; `subject` and `issuer` are written as OpenSSL writes them (`C=GB, O=Shop, CN=shop.example`); the two times are ms; `sha1` and `sha256` are the certificate's fingerprints in hex (Microsoft's `x5t` is the SHA-1 one in base64url). **Nothing is checked**: not who issued it, not whether it holds now. A certificate in PEM is also taken wherever a public key is. |
| `crypto.cert.chain(leaf, intermediates, roots, {at})` | The certificate's chain, checked up to one of `roots`: `{root, rootSubject, path}`. Fails (kind `"invalid"`) saying why where none holds ([below](#certificates-read-whole-and-their-chains)). |
| `crypto.seal(key, data, {aad})` | `data` (a text or bytes) sealed with AES-256-GCM, as bytes: for what is kept and must not be read by whoever reads the database (a refresh token, a second factor's secret). `key` is a [secret](back-end.md#secrets) of 16 bytes or more (`crypto.random(32)` makes one); `aad` is what it is bound to, a row's id say. What it gives is one byte that says the form (1), the 12-byte nonce (random, new each time), then the ciphertext and its 16-byte tag; the AES key is HKDF-SHA256 of the key given, so any long secret will do. |
| `crypto.open(key, sealed, {aad})` | The bytes that were sealed (`.text()` for a text). Fails for anything this key and this `aad` did not seal, or that was changed by one bit. |

All of them wait and can fail; all are the back end's (`H092` in a page: what a
page checked proves nothing to the back end, and a private key the back end
keeps is never the page's). A page that signs with a key of its own, or
seals with one, has [`crypto.ed25519` and `crypto.aes`](#keys-of-the-pages-own),
whose keys are raw bytes and whose sealing is AES-GCM's own bytes;
`crypto.seal` keeps its own form (a form byte, a nonce it draws, a key made
with HKDF), for what the back end alone seals and opens.

- **`alg`** is `"RS256"`, `"RS384"`, `"RS512"` (RSA, PKCS #1 v1.5, with
  SHA-256, -384, -512), `"PS256"` (RSA-PSS, SHA-256, a salt of 32 bytes),
  `"ES256"`, `"ES384"` (ECDSA on P-256 with SHA-256, on P-384 with SHA-384;
  the signature is `r` and `s` end to end, 64 or 96 bytes, as a token
  carries it), `"EdDSA"` (Ed25519), or `"RS1"` (RSA, PKCS #1 v1.5, SHA-1),
  which `crypto.verify` takes and nothing signs with: it is there for the
  services that still sign so (Amazon SNS's signature version 1). Written
  out, any other is refused (`H064`). There is no HMAC among them on purpose.
- **`der: true`** (ECDSA only): the signature is the DER sequence of two
  integers that X.509, WebAuthn, OpenSSL and SendGrid's webhooks write,
  both for what `crypto.sign` gives and for what `crypto.verify` reads. A token may also be HS256, and only where
  its key is given as a shared secret, `{secret: secret("KEY")}` (32 bytes
  or more): `crypto.jwt.verify` with `{secret}` checks HS256 tokens and
  nothing else, and with public keys never checks an HS256 token. So a
  token that says HS256 and was signed with a public key as its "secret"
  (the old key-confusion attack) is refused whatever key it names.
- **A key** is PEM text or a JWK (a record, or its JSON as text). In PEM, a
  public key is `PUBLIC KEY` (SPKI), `RSA PUBLIC KEY` (PKCS #1) or a
  `CERTIFICATE` (its key); a private key is `PRIVATE KEY` (PKCS #8), `RSA
  PRIVATE KEY` (PKCS #1: what GitHub Apps and DocuSign hand out) or `EC
  PRIVATE KEY` (SEC 1). An encrypted private key is refused with how to
  write it out without its password. It must be of the kind `alg` signs with: an RSA key is not taken
  for `ES256`, whatever else is said. A private key is not taken to check
  with. Keep a private key in a [`secret`](back-end.md#secrets).
- **`crypto.jwt.verify`**: `keys` is a JWKS (`{keys: […]}`, as a service
  publishes it), a list of JWKs, one JWK, or one key in PEM; or `{secret}`
  for HS256. It refuses: a token whose `alg` is not one of the four (so
  `none`, and every `HS…`: a public key is never taken for a shared
  secret), or not HS256 against a secret; an `alg` that `algs` does not
  list, when it is given; a key of another kind than the token's `alg`, or
  one that says another `alg` or a `use` that is not `sig` (a key's `alg`
  of `"Ed25519"`, the fully specified name of RFC 9864, is EdDSA's: Bun
  1.4's WebCrypto writes it on an Ed25519 key it exports); a `kid` none of
  the keys has; a signature that is none of theirs; a token with no `exp`,
  or past it, or before its `nbf`, or whose `iat` is later than now (give
  or take `leeway` seconds, 60 unsaid); older by its `iat` than `maxAge`
  seconds, when that is given; an `iss` that is not the one given (or one
  of a list); an `aud` (a text or a list) that does not include the one
  given (or one of those given). `iss` and `aud` are asked only when
  given: give them.
- **A certificate's chain**: [below](#certificates-read-whole-and-their-chains).
- Fetching a service's keys, keeping them for a while, and what a sign-in
  with another service does with the claims are the
  [oauth extension](oauth.md)'s; a back end that issues tokens of its own
  and takes them back as a bearer is in [jwt.md](jwt.md).
- The published examples these are checked against (RFC 7515 A.1 and A.3,
  RFC 8037 A.3 and A.4) and every token made to be refused are in
  `tests/identity/vectors.mote` (`tests/all.sh real_identity_vectors`).

### Certificates read whole, and their chains

On the back end (`runtime/server/sign.mote`, the part `X509`, carried only by
a program that reads a certificate). `crypto.cert(given)` takes PEM text or
the DER as `bytes` (as a WebAuthn statement's `x5c` and a token's header
carry them), and gives, beside the fields above:

| | |
|---|---|
| `der`, `pem` | The certificate, both ways. |
| `tbs`, `signature`, `sigAlg` | What its issuer signed (the DER of its `tbsCertificate`), the signature (for ECDSA, the DER sequence: `crypto.verify(issuer.publicKey, c.tbs, c.signature, {alg: c.sigAlg, der: true})`), and how: `"ES256"`, `"ES384"`, `"ES512"`, `"RS256"`, `"RS384"`, `"RS512"`, `"RS1"`, `"PS256"` (and PSS's other hashes), `"EdDSA"`, or the OID of one not known here. |
| `subjectDer`, `issuerDer` | The two names as DER, for matching a certificate to its issuer exactly. |
| `version`, `jwk` | 1 or 3; the public key as a JWK (`{kty, crv, x, y}` or `{kty, n, e}`). |
| `ca`, `pathLen` | The basic constraints: whether it is a CA, and how many CAs may stand below it (`-1`: unsaid). |
| `keyUsage`, `extKeyUsage` | `["digitalSignature", "keyCertSign", …]`; the extended key usages as OIDs. |
| `altNames` | The names it is also for: `"dns:shop.example"`, `"email:…"`, `"uri:…"`, `"ip:…"`, `"dir:C=US, 2.23.133.2.1=id:…"`. |
| `aaguid`, `transports` | The FIDO extensions: the AAGUID it is of (`1.3.6.1.4.1.45724.1.1.4`, `""` for none) and the transports (`1.3.6.1.4.1.45724.2.1.1`: `"usb"`, `"nfc"`, `"ble"`, `"bt"`, `"internal"`). |
| `android`, `appleNonce` | Android's key description (`1.3.6.1.4.1.11129.2.1.17`): `{version, securityLevel, challenge, software, tee}`, each list `{purposes, origin, allApplications}`; Apple's anonymous attestation nonce (`1.2.840.113635.100.8.2`). `none` where absent. |
| `extensions` | Every extension as it came: `[{oid, critical, value}]`. |

`crypto.cert.chain(leaf, intermediates, roots, {at})` finds the path from
`leaf` up through `intermediates` (in any order; some may go unused) to one
of `roots`, and checks along it:

- each certificate's signature, by its issuer's key: ECDSA on P-256, P-384
  and P-521 (SHA-256, -384, -512), RSA PKCS #1 v1.5 and RSA-PSS (its hash
  and salt read from its parameters), Ed25519. **A signature with SHA-1 is
  refused**, as is an algorithm not named here;
- each certificate's validity at `at` (ms; unsaid, now: the back end's
  clock, which a test's `clock` sets);
- each certificate **between** the leaf and the root: a CA (basic
  constraints, for a version 3 certificate), whose key usage, when it has
  one, lets it sign certificates, and whose path length allows the CAs
  below it;
- no certificate on the path has a critical extension that is not
  understood here (RFC 5280 4.2; the ones understood are basic
  constraints, key usage, extended key usage, alternative names, policies,
  the key identifiers, CRL distribution points and authority information
  access).

**A root is a name and a key** the program trusts, as RFC 5280 6.1 takes a
trust anchor: its own constraints are not asked of it (a maker's
self-signed batch certificate, which says it is no CA, may be named as a
root), and the leaf itself may be one of them. A certificate is PEM (a text
may hold several), DER `bytes`, or a list of either. What it gives:
`root`, the root's SHA-256 fingerprint (hex); `rootSubject`, its name;
`path`, each certificate's fingerprint from the leaf to the root. Where no
path holds it fails with the first reason found: `that certificate's chain
does not hold: "CN=…" ended at 2021-01-01T00:00:00Z`, `… is not "…"'s`
(a signature), `… and it is not a CA`, `nothing given issued "…"`.

Not checked: **revocation** (CRLs, OCSP: a revoked certificate is not
known here), name constraints and policies (a certificate that makes
either critical is refused, as not understood). Tested by
`tests/attest/certs.mote` against chains OpenSSL makes for each run
(`tests/attest/make.sh`: a chain that holds with each signature kind,
another root, a root of the same name and another key, one that has
ended, a leaf used as a CA, a path too long, one bit of a signature or of
what was signed changed, a critical extension not understood), and by
real authenticators' chains up to Apple's and Google's roots
([second-factor.md](second-factor.md#attestation-checked)); `tests/all.sh real_attest`.

## cbor

CBOR ([RFC 8949](https://www.rfc-editor.org/rfc/rfc8949)), the binary JSON
that WebAuthn, COSE keys and CTAP write. Page and back end alike.

| Call | Gives |
|---|---|
| `cbor.decode(b)` | The value (`json`): numbers, texts, bools, none, lists, records; a byte string is `bytes`; a tag's value is the value itself. A map's keys, which COSE writes as numbers, are read as text: `key["-2"]`. |
| `cbor.read(b)` | `{value, length}`: one value at the front of more bytes, and how many it took (a passkey's public key sits in the middle of its authenticator data). |
| `cbor.encode(value)` | Bytes, in the canonical form CTAP2 asks for: the shortest heads, a map's keys shorter first and then byte by byte. A record's key that is an integer written as text (`"-1"`) is written as that integer. |

Each can fail. Refused, with why: a length not given ahead (indefinite), a
map that says a key twice, a value that ends too soon, an integer past
2^53, and (for `decode`) bytes left after the value. Tested against RFC
8949 appendix A in `tests/identity/formats.mote`.

## xml

```text
xml.parse(text, {depth, size}?)   the root element, or a failure that says where
xml.find(node, "a/b")   xml.all(node, "a/b")   xml.text(node, "a/b")   xml.attr(node, name)
xml.write(node, declaration?)   xml.of(name, value, attrs?)   xml.escape(text)
```

XML, for the services that answer in it (S3, SQS's and SNS's query API,
STS, Azure Blob Storage), a feed, a sitemap. In a page and in a `server fn`
alike (`runtime/shared/xml.mote`).

```mote
// docs: whole
state said = ""

action read
  let doc = xml.parse("<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Contents><Key>a &amp; b.png</Key><Size>12</Size></Contents><IsTruncated>false</IsTruncated></ListBucketResult>")?
  let keys = xml.all(doc, "Contents").map(c => `${xml.text(c, "Key")} (${xml.text(c, "Size")} bytes)`)
  let made = xml.write(xml.of("Delete", {Object: [{Key: "a"}, {Key: "b"}], Quiet: true}, {xmlns: "http://s3.amazonaws.com/doc/2006-03-01/"})?)
  said = `${keys.join(", ")} in ${doc.ns}; ${made}`

button "Read" press=read
text said
```

- **A node** is `{name, local, ns, attrs, children, text}`: its name as
  written (`s3:Key`), its local name (`Key`), its namespace's URI (`""` for
  none), its attributes (a record, by the names as written), the elements
  inside it (`json`, nodes alike), and the text inside it (entities read,
  CDATA as it is, the pieces between its elements joined).
- **A path** is local names with `/` between, below the node given:
  `xml.find` is the first element there or none, `xml.all` every one,
  `xml.text` the first one's text or `""`. Namespaces are not in a path:
  `Contents` finds `<s3:Contents>` too; check `.ns` where it matters.
- **Read**: elements, attributes, the five named entities and numeric ones
  (`&#233;`, `&#x1F600;`), CDATA, namespaces; the declaration, comments and
  processing instructions are passed over.
- **Refused**: a `DOCTYPE` (so no entity of a document's own, nor one from
  outside: one that expands to a thousand more is how a small document
  fills a machine); more than `size` characters (10,000,000 unsaid); elements
  deeper than `depth` (100). Every failure says the line and column, kind
  `"invalid"`.
- **Written**: `xml.write` writes a node (text escaped, attributes in their
  order; `<a/>` when empty); `true` puts the declaration first. `xml.of`
  makes one from JSON: a record's fields are elements in their order, a list
  is its element said once for each, `none` is left out, the rest is text.
- Not streamed: a document is read whole.

## zip

```text
zip.gzip(data)   zip.gunzip(b)   zip.deflate(data)   zip.inflate(b)      bytes out
zip.zlib(data)   zip.unzlib(b)           deflate in the zlib wrapper
zip.pack([{name: "a.txt", data}])        a .zip, as bytes
zip.unpack(b)                            its files, as {name, data: bytes}[]
zip.entries(file)   zip.open(file, entry)   zip.gunzipStream(reader)     a large one, a piece at a time
```

For an archive too large to hold (a .zip of gigabytes, a .tgz), and for
`tar`, see [Large files](#large-files).

Mote's own wasm, in a worker. `deflate` and `inflate` are raw DEFLATE;
`zlib` and `unzlib` are the same in the zlib wrapper (what a PDF's
FlateDecode and a PNG's chunks hold); `gzip` and `gunzip` in gzip's.

**On the back end too**: the same calls in a `server fn` or a route, where
the same wasm runs in place. So an export is built where the data is, and
either handed to the page as `bytes` or served as a file:

```mote
// docs: whole
model Note
  title: string
  body: string
  read, add anyone

server fn exportNotes(): bytes
  let notes = Note.find({}, {order: "title"})?
  let files = notes.map(n => ({name: `${n.title}.txt`, data: bytes(n.body)}))
  return zip.pack(files)?

// Served as a file: a link to it downloads it.
server route GET "/export.zip"(req)
  return {bytes: exportNotes()?, headers: {"content-type": "application/zip", "content-disposition": "attachment; filename=\"notes.zip\""}}

// Or asked for by the page, as bytes, and saved from there.
action save
  fs.save("notes.zip", exportNotes()?)?

link "Download" href="/export.zip" download="notes.zip"
button "Save a copy" press=save
```

An archive is built in memory: for one too large for that, write the
parts with `fs` and run `zip` or `tar` with [`proc`](back-end.md#other-programs).

```mote
// docs: whole
state said = ""

action pack
  let z = zip.gzip("hello hello hello")?
  let back = zip.gunzip(z)?
  let archive = zip.pack([{name: "a.txt", data: "hello"}, {name: "b.bin", data: back}])?
  let files = zip.unpack(archive)?
  fs.save(archive, "both.zip")?
  said = `${z.length} bytes gzipped; ${files.map(f => f.name).join(", ")}`

button "Pack" press=pack
text said
```

## Notifications without a back end

| Call | Does |
|---|---|
| `notify.ask()` | Asks to show notifications: `true` if allowed. |
| `notify.allowed()` | `"granted"`, `"denied"` or `"default"` (not asked yet): what the browser holds, as a value the page follows. Does not wait. |
| `notify.show("Title", "A line")` | Shows one (through the service worker where the app has one, so it outlives the page). The second line is optional. |
| `notify.show("Ada", "calling", {actions: [{id: "answer", title: "Answer"}], data: {room: "r1"}, tag: "call"})` | With buttons, and what a press hands `on notify.opened` (`action`: the button's `id`); also `url`, `id`, `silent`, `renotify`, `sticky`. ([back-end.md](back-end.md#a-push-the-apps-own-code-opens)) |
| `push.subscribe(serverPublicKey)` | This device's subscription, as `json`, for a server of your own to send to. The key is the server's VAPID public key, base64url. |
| `push.unsubscribe()` | Gives it up. |

A built app's service worker shows what a push carries (`{title, body, url}`
as JSON; and `data`, `tag`, `silent`, `renotify`). On a press it brings the
app's window forward and tells it (`on notify.opened(n: {title: string, body:
string, url: string, data: json})`), or opens the app at `url` if it has no
window. With these calls, sending is
your server's work. A push the program opens itself (sealed to a key the
device keeps) is `on push.received`:
[back-end.md](back-end.md#a-push-the-apps-own-code-opens). With a Mote back end, `notify.send` and
`notify.enable()` do all of it ([back-end.md](back-end.md#notifications)).

## Pitfalls

- **Settle every call.** `db.get("k")` alone is refused (`H081`).
- **`json` is not checked.** `let xs: Post[] = net.get(url)?` trusts the
  server. Check what matters before using it.
- **`db.get` gives `none` for a missing key**, not a failure: `?` then `??`.
- **A named `sql` database is one tab's at a time.**
- **Private files and databases are per browser.** Clearing site data
  removes them; [`db.persist()`](#storage-that-stays) asks the browser not
  to do so on its own.
- **`net` from a page is subject to the browser's rules** (same origin,
  CORS). To call a service that does not allow the page's origin, call it
  from a `server fn`.
- **Large bytes are moved, not copied, to workers** when the page is done
  with them ([reactivity.md](reactivity.md#what-is-copied-and-what-is-moved)).

## Where a new call goes

One heading per namespace, in the order above (`clipboard` sits after `fs`:
both ask the machine the page is on). A new storage or network
call goes under its namespace's heading; a new namespace that keeps or
fetches data gets a `##` heading of its own here, and a line in the
[map](README.md#namespaces).

## In the source

| What | Where |
|---|---|
| Signatures and messages | `compiler/src/types.rs`: `Checker::call` |
| Recorded behaviour of storage | `tests/room` (a full disk, a page killed), `tests/photos` (the pickers) |
| What each call compiles to | `compiler/src/emit.rs`: `Gen::call` |
| `db`, `fs`, `sql` in the page | `runtime/page/storage.mote`: parts `DB`, `FS` `FSK` (the chooser), `SQ`; `compiler/src/types/picks.rs` |
| `clipboard` | `runtime/page/popover.mote`: part `CB` |
| `sql`, `fs` on the back end | `runtime/server/data.mote` (`SQS` cuts SQL into statements) |
| `net` | `runtime/shared/net.mote`; the back end's `public: true`, `net.lookup`, `net.public`: `runtime/server/net.mote` (part `NETS`); tested by `tests/server_net.real.mjs` |
| `crypto.hash`, `crypto.random`, bytes | `runtime/shared/bytes.mote` |
| `crypto.aes`, `crypto.x25519`, `crypto.ed25519`, `crypto.mlkem768`, `crypto.pow`, `crypto.randomBytes`, `crypto.argon2id`, SHA-3 and BLAKE2b | `runtime/shared/keys.mote`: parts `AES` `X25` `EDS` `KEM` `POW` `RNB` `A2`; `batteries/mlkem`, `batteries/pow`, `batteries/argon2`; `compiler/src/types/keys.rs`; `crypto` in an `off fn`: `find_off` in `compiler/src/emit.rs`, and the worker's helpers in `build.rs`; tested by `tests/crypto/` and `compiler/src/tests_crypto.rs` |
| `xml` | `runtime/shared/xml.mote`: part `XM`; tested by `tests/xml/unit.mote` (`tests/all.sh real_xml`) |
| `crypto.sign`, `crypto.verify`, `crypto.jwt` | `runtime/server/sign.mote`: part `SIG`; tested by `tests/signatures.real.mjs` (keys made there, RFC 8037 A.4, RFC 7515 A.3, and every token refused) |
| `crypto.argon2id`, `zip` | `runtime/page/batteries.mote`: parts `A2`, `ZP`; `batteries/argon2`, `batteries/zip` |
| SQLite | `batteries/sqlite/` (`README.md`, `glue.js`) |
| `notify`, `push` | `runtime/page/notify.mote`; `compiler/src/pwa.rs`, `service_worker` |
| Recorded behaviour | `tests/pages/feed`, `tests/sql`, `tests/pages/pack`, `tests/pages/vault`, `tests/desk`, `tests/bytes` (`zip.zlib`) |
