# Admin

The page every product builds for its own people: who has an account and
where they are signed in, every model's rows, the jobs, what the back end
stands on, who may do what, and a log of what admins did. An extension: a
package of ordinary Mote, taken with one `use`. Back to the
[map](README.md).

```mote
app "Shop"
use "pkg:admin/admin.mote"

// Who is an admin: this program's answer, as a rule.
rule admin = exists(Member, {who: me, role: "admin"})

route "/admin"
  AdminPanel
```

```toml
# mote.toml, beside the entry
[packages]
admin = "../mote/extensions/admin"
```

That is all of it. With those lines `/admin` has, in tabs: **People**
(accounts, search by email, when each was made, their sessions, "sign out
everywhere", "see what they see"), **Data** (every model: a page of rows at
a time, search, sort, open a row, follow its references both ways, change
and remove what the model's own rules let this admin), **Jobs** (by state
and name, the failure's words, try again, cancel), **Health** (the build,
how long it has been up, the databases and their sizes, snapshots, the
settings it reads, the last faults), **Access** (what [`mote check
--access`](back-end.md#who-may-do-what) says of this build) and **Log**
(what admins did). To anyone who is not an admin it says so, and every door
behind it is shut.

## Mental model

- **It is a program's own code, not a way round it.** The extension is a
  file of models, `server fn`s and components
  (`extensions/admin/admin.mote`, `panel.mote`): read it, copy it, change
  it. Each `server fn` says `requires admin`: the program's rule.
- **An admin changes what the rules let an admin change.** Data writes
  through the model's own operations, as the admin (`T.as(me)`): the
  model's `change` rule, its `check`s, its hooks, its `live` values all
  stand. What they refuse is refused, in their words. There is no write
  past the rules here; a program that wants one writes its own `server fn`.
- **Reading every row is a setting of the back end's**, off unless said
  (`ADMIN_READ_ALL=1`), and even then never what is `private`, nor what is
  `hidden` without a second setting.
- **What the page asks for decides nothing.** A component's prop
  (`trusted=true`, `write=true`) is the page's word, and an admin's page
  could send anything: what widens what an admin may do is a
  [setting](#settings) the back end reads.
- **What makes it possible** is three small things the back end's code can
  say, none of them a call a page can make: a model named at run time
  ([`models.of(name)`](models.md#models-chosen-at-run-time)), the accounts
  there are ([`auth.list`](back-end.md#passwords-from-the-programs-own-code)),
  and what the back end is ([`app.info()`](back-end.md#what-the-back-end-is)).
  A program's own admin page can be written on the same three.

## Who is an admin

A [rule](back-end.md#rules) called `admin`, with no parameters, declared by
the program. Every `server fn` of the extension says `requires admin`, so:

- until the program declares it, it does not compile, and each door says
  what to write (`H131`: there is no rule `admin`);
- nobody signed in gets `401`, someone the rule refuses `403`, before any
  line of the extension runs;
- `mote check --access` lists every door of the extension with the
  program's test written out beside it.

**Admins as a list of addresses.** A rule may read the signed-in
account's address and a setting ([a rule that reads a
setting](back-end.md#a-rule-that-reads-a-setting)), so the list in the
environment is the rule itself:

```text
rule admin = me.email in setting.list("ADMIN_EMAILS")
```

```text
ADMIN_EMAILS="ada@shop.example, bo@shop.example"
```

The setting is read as the back end starts (a change is a restart), in
lower case as addresses are kept; an account made later for an address in
the list is an admin from its first call. An address is whoever holds its
account: where anyone may sign up, make the admins' accounts first. Admins
kept as rows are a model of the program's own:
`rule admin = exists(Staff, {who: me})`.

## The components

`AdminPanel` is these in tabs. Each stands alone too, asks the back end
itself, follows the app's colours in light and dark, and works at a phone's
width.

| | |
|---|---|
| `AdminPanel` | Everything, in tabs. `trusted=true`: Data opens on every row (where `ADMIN_READ_ALL` allows). `write=true`: People offers acting to write (where `ADMIN_ACT_WRITE` allows). |
| `AdminPeople` | Accounts by email, fifty at a time, with how many sessions each has (one with [no address](back-end.md#a-sign-in-of-the-programs-own) is shown by its id, before the others). A person: their sessions (when made, until when), who is acting as whom, "Sign out everywhere", "See what they see". `write=true` as above. |
| `AdminData` | Every model. `AdminData model="Order"`: one. `trusted=true` as above. |
| `AdminJobs` | The program's [jobs](back-end.md#later-job-fn) (the newest thousand, which is what `jobs.list` gives), newest first, by state and name; "Try again" for one that failed or was cancelled, "Cancel" for one waiting. |
| `AdminHealth` | Build, time up, pages on the open line, databases and sizes, snapshots, settings, the hosts the program paces or guards with a breaker ([`net.pace`, `net.breaker`](back-end.md#a-host-paced-and-a-breaker)), the last faults. |
| `AdminAccess` | The access report of the build: what is worth a look, each call with its `requires`, each model with its rules and who they admit. |
| `AdminTrail` | The log. |

### A page of one's own

The pieces are components, so an admin page is laid out like any page,
beside the program's own panels and the [usage](usage.md) extension's:

```mote
use "pkg:admin/admin.mote"
use "pkg:usage/usage.mote"

rule admin = exists(Member, {who: me, role: "admin"})
fn usageMay(): bool
  return Member.has({who: (auth.me()?)?.id ?? "", role: "admin"})?

route "/desk"
  column gap=16 max-width=1100 margin="0 auto" padding=16
    text "Orders desk" font-size=20 font-weight=600
    UsageChart event="checkout" by="plan" last="30 days"
    AdminData model="Order"
    AdminJobs
    RefundsWaiting
    AdminHealth
```

### A tab of one's own, and the usage tab

`AdminPanel` has two [named slots](markup.md#components): `admin.tabs`, in
the row of tabs, and `admin.body`, under it. Both are given `tab`, the name
of the tab that is open.

```text
fill "admin.tabs"(tab: string)
  AdminTab name="Refunds" tab=tab

fill "admin.body"(tab: string)
  if tab == "Refunds"
    RefundsWaiting
```

A program that takes the usage extension too gets its panel as a tab with
one more line, `use "pkg:admin/usage.mote"`, and `usage` beside `admin` in
its `mote.toml`: that file takes the usage extension for the program (a
package's `use "pkg:…"` is looked up through the program's `[packages]`
first). It is the two fills above for `UsagePanel`, and `usageMay` (which
the usage extension wants) said as "whoever the rule `admin` admits".
Without it, and without the usage package, the admin panel is as it is:
nothing in it needs usage.

## Data: under the rules, and every row

**Under the rules** (as it comes). The rows are those the admin's own page
would be given: the model's `read` rule is asked as them, `hidden` fields
are not there, a `private` field is theirs or none. A model with no `read`
rule cannot be read (the panel says `you may not read this Vault`). A row
is changed with `T.as(me).set`, added with `.add`, removed with `.del`:

| What the admin does | What decides |
|---|---|
| Change a field | The model's `change` rule, asked as the admin. Where every `change` line names its fields, only those are offered. Then the `before` hooks, the `check`s, references and `unique`, as for any write. |
| Add a row | The `add` rule. A `= me` field is the admin. |
| Remove a row | The `remove` rule; `cascade` and what points at the row, as for any removal. |
| What follows | `after` hooks run, and every page that keeps a `live` value the row is in is sent it: the customer sees the change at once. |

A refusal is shown as the model says it: `you may not change this
Receipt`, a hook's `an order's total is never below zero`, a check's own
words.

**Every row** (`ADMIN_READ_ALL=1`). A switch appears, "Every row"; with it
the engine is asked without the rules, so support can see what a customer
sees and what they cannot. Still:

- nothing `private` is ever sent, and nothing `hidden` unless
  `ADMIN_SHOW_HIDDEN=1`; and nothing may be asked *of* such a field (a
  filter, a search, an order), since whether a search finds something says
  what the field holds;
- **nothing is written**: Change, Remove and Add are not offered, and the
  back end's `adminSet`, `adminAdd` and `adminDel` have no such mode. A
  write is always under the rules.

**The extension's own models** (`AdminLog`, `AdminFault`, `AdminProbe`) and the usage extension's are listed after the program's,
read like any other where reading is allowed, and never changed through
Data, whatever their rules.

**In a list**: fifty rows a page, by the key (or the order pressed for in a
column's head), each next page asked for with the last row's key, so a
model of any size opens at once and no table is read whole. Search is by
what a text field starts with, by a number or a yes/no being a value, or,
where the model has a [full-text index](models.md#full-text-search), by
its words. A long text and a large `json` value are cut in the list and
whole in the row. A reference is a chip that opens the row it points at; a
row lists what points at it, each a link to those rows. A `file` is a link
through the row's own address, so under its `read` rule. Bytes are never
sent: only how many there are. A time is shown in the reader's zone.

## Acting as someone

"See what they see" calls [`auth.as`](back-end.md#acting-as-someone): the
admin is taken for that person in this app, their own session kept, and is
brought to `/`. The runtime's banner says so on every page until they
press End.

- **To look**, unless said: every write is refused by the engine.
- **To write** only where the back end says `ADMIN_ACT_WRITE=1` *and* the
  page says `write=true`; the panel then asks a second time before it
  begins.
- **Never as oneself, and never as another admin** (the program's rule is
  asked about the other person) unless `ADMIN_ACT_ADMINS=1`.
- While acting as someone who is no admin, the extension's doors are shut
  to that browser, as they are to that person. Acting as another admin
  (where that is allowed), they are open as that admin's are, and what is
  not a model's write (a job tried again, a person signed out, an acting
  begun) is refused: it is done as oneself.
- It is written in the log before it begins, with who and as whom; one that
  was refused because the other is an admin is written too.

## The log

`AdminLog`: who (and, while acting, who was really there), what, the model
and key, a note, and when. A row is written **in the same turn** as the
thing it tells of (a change and its line are kept together, or neither),
by the extension's own fns, and by nothing else: the model has no rule, so
no page reads or writes it, and Data never changes it. For a change the
note is the **names** of the fields, never what they hold. The back end's
own [log](back-end.md#logs) has the same at `info` (`admin: changed`, with
`model`, `key`, `note`, and the call's `user`).

| What is written | |
|---|---|
| `changed`, `added`, `removed` | A row, through Data. |
| `signed out everywhere` | With the person's email. |
| `acted as, to look` / `acted as, to write` | Before it begins. |
| `acting refused: an admin` | The other person is one. |
| `retried a job`, `cancelled a job` | With the job's id. |

It is a record of what was done through this extension, not of everything
(a program's own `server fn` writes its own line: `adminNote(…)` is there
to call).

## Settings

Read by the back end (a build's `.env.example` lists them, and Health shows
which are set). Each is off unless set to `1`, `on`, `true` or `yes`.

| | |
|---|---|
| `ADMIN_EMAILS` | Addresses, with commas between: who is an admin, where the program's rule says `me.email in setting.list("ADMIN_EMAILS")`. |
| `ADMIN_READ_ALL` | Data may read every row, past the rules. |
| `ADMIN_SHOW_HIDDEN` | With the one above: `hidden` fields too. (`private` ones never.) |
| `ADMIN_ACT_WRITE` | Acting as someone may be to write. |
| `ADMIN_ACT_ADMINS` | An admin may act as another admin. |
| `ADMIN_KEEP_FAULTS` | How many faults Health remembers (200). |

## What it shows of the back end

- **People** are the accounts in the accounts' store. Where [several apps
  share one](back-end.md#accounts-several-apps-share), they are everyone's,
  the panel says so, and "sign out everywhere" ends that person's sessions
  in each of the apps. A session is shown by when it was made and until
  when it holds; its id is never sent anywhere (it is the cookie). When
  someone was last seen is not kept by the runtime, and is not shown.
- **Health**'s faults are those `server on failure` heard since the
  extension was taken, the newest `ADMIN_KEEP_FAULTS`, kept in the model
  `AdminFault`; each has the id the back end's log has it under. A
  setting's value is shown; a [`secret`](back-end.md#secrets)'s, and a
  `MOTE_` setting's, only whether it is set. With a [shared
  database](back-end.md#several-apps-one-database) the apps at it are
  named, with when each last started.
- **Access** is the report as the build made it, kept in the back end
  because the extension asks for it (`app.access()`).

## The questions

The components are thin: each asks one of these, and a program's own page
may ask them too. All say `requires admin`.

```text
adminAbout()                           {me, models, shared, allows: {readAll, hidden, actWrite, actAdmins}}
adminRows(model, {field, text, filter, order, after, all, limit})    {rows, next}
adminCount(model, {field, text, filter, all})                        how many
adminRow(model, key, all)              {row, back: [{model, field, count}]}
adminSet(model, key, changes) · adminAdd(model, row) · adminDel(model, key)
adminPeople(search, after)             {rows: [{id, email, made, sessions}], total, next}
adminPerson(id)                        {who, sessions, actedAs, actingAs}
adminSignOut(id) · adminActAs(id, write)
adminJobs(state, name)                 {jobs, counts, names, total} · adminJobRetry(id) · adminJobCancel(id)
adminHealth()                          {info, now, faults, faultsKept, hosts}
adminAccess() · adminLogs(after)
adminHello()                           requires signedIn: whether the caller is an admin
```

## Pitfalls

- **No rule `admin`**: the program does not compile, with a line for each
  door. Declare the rule; it may name other rules.
- **A prop is not a permission.** `AdminData trusted=true` on a back end
  without `ADMIN_READ_ALL` reads under the rules, and says nothing more.
- **An admin who cannot read a model** sees `you may not read this …`.
  That is the model's `read` rule speaking: add `|| admin` to it, or turn on
  `ADMIN_READ_ALL` for reading.
- **Names.** The extension's names begin `Admin…` / `admin…`; a program
  with a model, a fn or a component of one of those names meets `H022`,
  which names both places. (`adminMay`, `adminDo` and `adminEmails` are not
  taken: a program may have its own.)
- **`use "pkg:admin/usage.mote"` with a `usageMay` of the program's own**
  is the name declared twice: leave the file out and write the two fills.
- **A fault is heard only by a back end that listens**: in `mote test` a
  call that breaks fails the test's line and no `server on failure` block
  runs, so `AdminFault` stays empty there.

## In the source

| | |
|---|---|
| `extensions/admin/admin.mote` | The models, the settings, every `server fn`. |
| `extensions/admin/panel.mote` | The components. |
| `extensions/admin/usage.mote` | The usage panel as a tab. |
| `extensions/admin/tests.mote` | Its tests, run by `mote test` from `tests/admin_logic/`. |
| `runtime/server/zz_admin.mote` | `models.list`, `models.of`, `auth.list`, `auth.sessions`, `app.info`, `app.access`. |
| `compiler/src/types/e3.rs`, `emit/e3.rs` | Those words, checked and written. |
| `tests/admin/`, `tests/admin.real.mjs` | The panel in a browser: `tests/all.sh real_admin`. |
