# c8-online

cont8nuum's website: the front page about the desktop, with pictures of
it, and the cont8nuum account: where people make an account, and the
server a cont8nuum PC will keep its settings on. Plain PHP (8.2 or
newer) and MariaDB or MySQL through PDO. No framework, no Composer
packages, no JavaScript.

It is four things:

- **The front page** (`views/home.php`): what the desktop is, in its own
  look, with screenshots taken from the real thing (see below).
- **The website**: create an account, sign in, confirm the email
  address, forgotten password, change name / address / password, see
  and sign out the PCs and browsers that are signed in, see and delete
  what is synced, close the account.
- **An OpenID Connect issuer**, made to fit `c8-accounts` (PC settings'
  Online accounts) as it is today: authorization code with PKCE (S256),
  public clients, a loopback redirect on any port, refresh tokens that
  are replaced on every use, userinfo, revocation.
- **The sync API**: named blobs per account with revisions, so two PCs
  changing the same thing notice.

The desktop's side is `c8-sync` (in c8-settings): signed in from PC
settings with the provider c8-settings ships (below), a PC keeps the
sections of its config.ini here as items named `config.SECTION`
(appearance, general, notifications, keyboard, touchpad, mouse,
bindings), each a text of sorted `key=value` lines, and merges key by
key when two PCs changed the same one. Start and the apps' own settings
aren't synced yet.

## Trying it

```sh
sudo zypper in php8 php8-cli php8-pdo php8-mysql php8-openssl \
	php8-mbstring php8-curl mariadb

# a database and a user for it
sudo mariadb -e "CREATE DATABASE c8_online;
	CREATE USER 'c8_online'@'localhost' IDENTIFIED BY 'CHANGE ME';
	GRANT ALL ON c8_online.* TO 'c8_online'@'localhost';"

cp config.sample.php config.php    # put the password in it
bin/c8-online init                 # makes the tables
bin/c8-online serve                # http://127.0.0.1:8088
```

With `'mail' => 'log'` (the default) nothing is mailed: the messages,
with their links, are appended to `data/mail.log`.

`tests/run.sh` runs everything end to end (as a browser and as a PC)
against a MariaDB of its own in a temporary folder; it doesn't touch
the system's.

## The screenshots

`public/img/` holds pictures of the desktop, and `tools/screenshots.sh`
takes them again from the build in `../.prefix`: a nested, headless
cont8nuum at 1920x1080, driven by keys, in a sandbox with an empty home
and a user called "cont8nuum", so nothing of whoever runs it is in
them. Run it after the desktop's look changes. It needs bwrap, grim,
wtype, wlrctl, dbus-run-session, python3 and ImageMagick. A new picture
goes in the script (keys, then `shot NAME`) and in `views/home.php`.

The XR pictures (`xr-*`, the page's lead) come from a second
run: a second headless screen stands in for XREAL glasses
(`C8_GLASSES`), `tools/imu-still.py` is a head held still, the apps open
where `holograms.ini` in the script puts them, and the glasses' frames
are read back (`C8_XR_DUMP`, then `glasses NAME`). That part draws with
GLES2, so it needs a GPU's render node.

The page has no inline styles or scripts: the Content-Security-Policy
allows neither.

## Signing in from a PC

c8-settings ships the provider (`data/accounts/cont8nuum.provider.in`),
so PC settings, Online accounts offers "cont8nuum account". Where it
points is c8-settings' `account_url` build option, by default the live
site, `https://c8.lowtide.sbs` (empty: no provider). `build.sh` gives
any build the address in `C8_ACCOUNT_URL`, else the nested `.prefix`
build the local test site, `http://127.0.0.1:8088`, so tests never
sync into the real account, and any other build the live site. An installed desktop wants
an https one, since anyone on the machine can listen on a local port. Plain http is only taken to
the PC itself (127.0.0.1, localhost), or anywhere with
`C8_ACCOUNTS_ALLOW_HTTP=1` set, which is for tests.

Apps get a token with `GetAccessToken("sync", "")`, which also gives
the API's address.

The site serves the same file for its own address at
`/cont8nuum.provider`, for a PC whose build points elsewhere: put it in
`~/.local/share/cont8nuum/accounts/` and it replaces the shipped one.

`tests/run.sh` checks this for real when `../.prefix` is built: the
actual c8-accounts signs in through the provider, stores a setting,
refreshes, restarts and removes the account (`tests/desktop.py`, with
`tests/secrets-mock.py` standing in for the wallet). It then runs a
nested, headless c8 whose c8-sync syncs with the test site while the
script plays the account's other PC. That part needs a short `TMPDIR`
(the nested c8's socket path can be 108 characters at most).

## Putting it on a server

- Serve `public/` only; everything else stays outside the web root.
  Every request that isn't a file there goes to `public/index.php`:

  ```nginx
  root /srv/c8-online/public;
  location / { try_files $uri /index.php$is_args$args; }
  location = /index.php {
  	include fastcgi_params;
  	fastcgi_param SCRIPT_FILENAME $document_root/index.php;
  	fastcgi_pass unix:/run/php-fpm/c8-online.sock;
  }
  client_max_body_size 1m;
  ```

  Apache with FastCGI needs `CGIPassAuth On` (or the
  `SetEnvIf Authorization` line) so the API sees the bearer token.
- `url` in config.php is the address people use, https, no trailing
  slash. It is the OpenID issuer too, so it can't change later without
  every PC signing in again.
- `data/` (the id token signing key `oidc.key`, the mail log) and
  `config.php` must be readable by PHP only.
- `'mail' => 'mail'` sends through PHP's `mail()`, so the server needs
  a working sendmail.
- Behind a reverse proxy set `trust_proxy`, or every visitor has the
  proxy's address and the limits on guessing count them as one.
- Run `bin/c8-online cleanup` daily (cron or a systemd timer).
- `registration => false` closes sign-ups.

## How it keeps things

Passwords are Argon2id (`password_hash`). Session cookies, mailed
links, authorization codes and tokens are random 256 bits and only
their SHA-256 is stored, so a copy of the database signs nobody in.
Forms carry a CSRF token (double-submit cookie). Wrong passwords are
counted per address and per visitor: 10 per account and 30 per visitor
in 15 minutes.

- A code works once, for two minutes; used twice, what it gave is
  signed out.
- An access token lasts an hour, a refresh token 90 days from its last
  use. Each refresh replaces the refresh token; the old one works 30
  more seconds (the answer may have been lost), and after that using it
  signs the device out, since it means the token got out.
- A password reset signs out every browser and PC. Changing the
  password signs out the other browsers only.
- Closing the account deletes everything of it at once.

The synced items are stored as they are sent. The server never looks
inside, so a PC can encrypt them before sending when the desktop's side
is written; it doesn't yet, so today whoever runs the server can read
them.

## The API

All of it takes `Authorization: Bearer ACCESS-TOKEN`. Errors are JSON:
`{"error": "code", "error_description": "words"}`; 401 means refresh
the token (with c8-accounts: call GetAccessToken again with the one
that was rejected).

| | |
|---|---|
| `GET /api/v1/account` | `sub`, and by scope `name`, `email`, `email_verified`; `device` |
| `PUT /api/v1/device` | `{"name": "Study PC"}`: what the account pages call this sign-in |
| `GET /api/v1/settings` | `{"rev": N, "items": [...], "limits": {...}}`: every item (without its data) |
| `GET /api/v1/settings?since=N` | only what changed after revision N, deletions too (`"deleted": true`) |
| `GET /api/v1/settings/NAME` | the item's bytes, with its `Content-Type`, `ETag: "REV"`, `X-C8-Rev`, `X-C8-Updated` |
| `PUT /api/v1/settings/NAME` | the body becomes the item; 201 when new |
| `DELETE /api/v1/settings/NAME` | deletes it (other devices hear of it through `since`) |

The settings calls need the `sync` scope. Names are `a-z 0-9 . _ -`, up
to 64, starting with a letter or digit. An item is at most 256 KiB
(413), one sent as `image/*` (the desktop's `picture.start` and
`picture.lock`, JPEGs) 1000 KiB, under nginx's `client_max_body_size
1m` above, and an account holds 64 (507); all three are in config.php
and in the listing's `limits`.

Revisions: the account has one counter, and every change to any item
takes the next number, which becomes that item's `rev`. So a PC keeps
the `rev` of its last listing and asks `?since=` for what is new.

To not overwrite another PC's change, say which revision yours is
based on:

- `If-Match: "REV"` on PUT or DELETE: only if the item is still at that
  revision, else 412 with `"error": "conflict"` and the `rev` it is at
  now (`null`: deleted). Fetch it, merge, try again.
- `If-None-Match: *` on PUT: only if there is no such item yet.
- Neither: the last writer wins.

Sending an item exactly as it is stored changes nothing and returns
the revision it has.

Deleting everything on the website ("Synced settings") removes the
items outright, not as deletions for the PCs to follow: they keep what
they have.

## Layout

| | |
|---|---|
| `public/` | the web root: `index.php` (routes), `style.css`, Selawik (OFL, see `fonts/LICENSE.txt`) |
| `src/app.php` | config, the database, small helpers, `cleanup` |
| `src/http.php` | the request, cookies, CSRF, pages and JSON answers |
| `src/users.php` | accounts, passwords, website sessions, mail, limits |
| `src/oauth.php` | discovery, authorize + consent, token, userinfo, revoke, id tokens, the provider file |
| `src/api.php` | the API above |
| `src/pages.php` | the website's pages; their HTML is in `views/` |
| `schema.sql` | the tables |
| `bin/c8-online` | `init`, `cleanup`, `users`, `delete EMAIL`, `serve` |
| `tools/screenshots.sh` | takes the front page's pictures again |
| `tools/imu-still.py` | a still head for the XR pictures |
| `tests/` | `run.sh` starts a database and the site, `run.php` is the checks, `desktop.py` the real c8-accounts against it |

OAuth clients are in config.php (`clients`); all are public clients
with PKCE. To let another app sign in, add one with the redirect
addresses it may use.
