c8-online: cont8nuum's website
Accounts, sign-in for the desktop (OpenID Connect) and settings sync, in plain PHP on MariaDB.
f2288219 +4966
1234# The site's secrets: the database password (config.php), and data/ with# the OpenID signing key and the mail log. Never commit them./config.php/data/1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253# c8-online
The website (PHP + MariaDB): the front page with screenshots, accounts, an OpenID Connect issuer for c8-accounts, the settings sync API. Not built by `build.sh`.Depends on: php, MariaDB/MySQL.
cont8nuum's website: the front page (`views/home.php`, about thedesktop, led by XR: the hero is the glasses' view, then itsown section before the flat screenshots; Start's night blue, Metrotiles, real screenshots in `public/img` that `tools/screenshots.sh`retakes from `.prefix`: a headless c8 in bwrap with an empty home, auser named "cont8nuum", a short app list and a system bus of its own(the real one's NetworkManager put the Wi-Fi name on the charms bar;`tools/ppd-mock.py` serves power modes there), and Start's weather tilemoved to Seattle after a first run writes start.ini (wttr.in otherwiseguesses this PC's place), so nothing personal is in them; C8_XR_DUMPwrites `FILE.part` and renames, so a reader never gets half a picture;then again in XR (a second headless output as theglasses, `tools/imu-still.py` as a still head, placements writtenfirst, frames from `C8_XR_DUMP`; needs a GPU); no inline styles orscripts, the CSP forbids them), and the account website and syncserver; its README has the API and how to host it. Plain PHP (no framework, no Composer, no JavaScript), PDOMySQL only (the user's choice; MariaDB here). `public/index.php` routeseverything; `src/app.php` (config from `config.php` or`C8_ONLINE_CONFIG`, `db()`, `q`/`row`/`transaction`), `http.php`(params, cookies, double-submit CSRF, `page`/`json_out`), `users.php`(Argon2id, sessions as hashed cookies, mailed verify/reset links,`too_many`/`note_attempt` limits), `oauth.php` (the issuer c8-accountssigns in to: discovery, consent, code + PKCE S256, rotating refreshtokens with a 30 s grace then reuse = device signed out, RS256 idtokens with `data/oidc.key`, userinfo, revoke, and `/cont8nuum.provider`for PC settings), `api.php` (`/api/v1/settings`: named blobs, onerevision counter per account, `If-Match` conflicts, `?since=`; an`image/*` item may be `picture_max_bytes`, 1000 KiB, under nginx's 1m,the rest `item_max_bytes`; both in the listing's `limits`),`pages.php` + `views/` (sign-in pages on the accent, the account as PCsettings' two panes; one column under 700 px). Answers that end arequest (`page`, `json_out`, `redirect`) exit, so inside `transaction`return the result and answer after it, or the rollback undoes it.`tests/run.sh` runs its checks against a throwaway MariaDB it startsitself (never the system's). Not done: syncing more than config.ini's sections (seec8-sync), encryptingitems on the PC, real mail (only `mail()`), an admin page. When `.prefix` is built the samerun drives the real c8-accounts through the shipped provider against it(`tests/desktop.py`, `tests/secrets-mock.py` as the wallet: sign-in,token, refresh, restart, remove), then a nested headless c8 with itsc8-sync, the script playing the other PC through the API: first upload,a remote change applied to config.ini and not echoed, both sideschanging while the PC is off, the service turned off and on, and thepictures (shrunk to fit, taken and encoded again, bad ones refused,removed both ways). Deploying needs nothing new: the default limit fitsthe README's nginx block. Thenested c8's socket needs a short TMPDIR (108 characters). Untested: the provider's tile andsign-in band in PC settings by hand, nginx/php-fpm, MySQL proper.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219# c8-online
cont8nuum's website: the front page about the desktop, with pictures ofit, and the cont8nuum account: where people make an account, and theserver a cont8nuum PC will keep its settings on. Plain PHP (8.2 ornewer) and MariaDB or MySQL through PDO. No framework, no Composerpackages, 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 PCsettings with the provider c8-settings ships (below), a PC keeps thesections 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 bykey when two PCs changed the same one. Start and the apps' own settingsaren't synced yet.
## Trying it
```shsudo zypper in php8 php8-cli php8-pdo php8-mysql php8-openssl \ php8-mbstring php8-curl mariadb
# a database and a user for itsudo 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 itbin/c8-online init # makes the tablesbin/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 touchthe 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, headlesscont8nuum at 1920x1080, driven by keys, in a sandbox with an empty homeand a user called "cont8nuum", so nothing of whoever runs it is inthem. Run it after the desktop's look changes. It needs bwrap, grim,wtype, wlrctl, dbus-run-session, python3 and ImageMagick. A new picturegoes in the script (keys, then `shot NAME`) and in `views/home.php`.
The XR pictures (`xr-*`, the page's lead) come from a secondrun: a second headless screen stands in for XREAL glasses(`C8_GLASSES`), `tools/imu-still.py` is a head held still, the apps openwhere `holograms.ini` in the script puts them, and the glasses' framesare read back (`C8_XR_DUMP`, then `glasses NAME`). That part draws withGLES2, so it needs a GPU's render node.
The page has no inline styles or scripts: the Content-Security-Policyallows 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 itpoints is c8-settings' `account_url` build option, empty by default(no provider). `build.sh` gives the nested `.prefix` build the localtest site, `http://127.0.0.1:8088`, and any build the address in`C8_ACCOUNT_URL`; an installed desktop wants the real https one, sinceanyone on the machine can listen on a local port. Plain http is only taken tothe 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 givesthe 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: theactual 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 anested, headless c8 whose c8-sync syncs with the test site while thescript 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, mailedlinks, authorization codes and tokens are random 256 bits and onlytheir SHA-256 is stored, so a copy of the database signs nobody in.Forms carry a CSRF token (double-submit cookie). Wrong passwords arecounted per address and per visitor: 10 per account and 30 per visitorin 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 looksinside, so a PC can encrypt them before sending when the desktop's sideis written; it doesn't yet, so today whoever runs the server can readthem.
## The API
All of it takes `Authorization: Bearer ACCESS-TOKEN`. Errors are JSON:`{"error": "code", "error_description": "words"}`; 401 means refreshthe token (with c8-accounts: call GetAccessToken again with the onethat 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 . _ -`, upto 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_size1m` above, and an account holds 64 (507); all three are in config.phpand in the listing's `limits`.
Revisions: the account has one counter, and every change to any itemtakes the next number, which becomes that item's `rev`. So a PC keepsthe `rev` of its last listing and asks `?since=` for what is new.
To not overwrite another PC's change, say which revision yours isbased 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 returnsthe revision it has.
Deleting everything on the website ("Synced settings") removes theitems outright, not as deletions for the PCs to follow: they keep whatthey 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 clientswith PKCE. To let another app sign in, add one with the redirectaddresses it may use.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465<?php// Copy to config.php (or point C8_ONLINE_CONFIG at a copy) and change// what differs. Everything left out keeps the default in src/app.php,// which is what is shown here.return [ // What the site calls itself 'name' => 'cont8nuum account',
// Who the front page's last line says made cont8nuum; '' leaves the // line out 'author' => 'lowtide',
// Where the site is reached, without a trailing slash. This is also // the OpenID issuer, so it must be exactly what clients are given. // Anything but http://127.0.0.1 or localhost has to be https. 'url' => 'http://127.0.0.1:8088',
// The database (PDO MySQL: MariaDB or MySQL). Make the tables with // `bin/c8-online init`. 'db' => [ 'dsn' => 'mysql:host=127.0.0.1;dbname=c8_online;charset=utf8mb4', // or a socket: 'mysql:unix_socket=/run/mysql/mysql.sock;dbname=…' 'user' => 'c8_online', 'password' => '', ],
// The signing key and the mail log. Keep it outside the web root // and writable by PHP only. 'data' => __DIR__ . '/data',
// May anyone make an account? 'registration' => true,
// 'log' writes mail to data/mail.log (for trying things out), 'mail' // sends it with PHP's mail(). 'mail' => 'log', 'mail_from' => 'cont8nuum account <noreply@localhost>',
// Behind a reverse proxy: take the visitor's address from the last // X-Forwarded-For entry. Only when the proxy sets it. 'trust_proxy' => false,
// OAuth clients. All are public (no secret, PKCE required). // `redirect` are regular expressions the redirect_uri must match // whole; the desktop listens on a loopback port that changes. 'clients' => [ 'cont8nuum' => [ 'name' => 'cont8nuum desktop', 'redirect' => ['http://127\.0\.0\.1:\d+/callback'], 'scopes' => ['openid', 'email', 'profile', 'offline_access', 'sync'], ], ],
// Seconds 'session_ttl' => 30 * 86400, // signed in on the website 'access_ttl' => 3600, 'refresh_ttl' => 90 * 86400, // counted from the last refresh
// Synced items, per account 'item_max_bytes' => 256 * 1024, // Items sent as image/* (the Start and lock screen pictures); keep it // under the web server's body limit (nginx's client_max_body_size) 'picture_max_bytes' => 1000 * 1024, 'item_max_count' => 64,];123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109-- cont8nuum account: the whole database (MariaDB or MySQL, InnoDB).-- `bin/c8-online init` runs this; every statement can be run again.-- Times are Unix seconds. Secrets (cookies, links, codes, tokens) are-- kept only as their SHA-256 in hex.
CREATE TABLE IF NOT EXISTS users ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, -- what apps know the account by (OpenID "sub"): never changes sub CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL UNIQUE, email VARCHAR(254) NOT NULL UNIQUE, email_verified TINYINT NOT NULL DEFAULT 0, name VARCHAR(64) NOT NULL, password VARCHAR(255) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, created BIGINT NOT NULL, -- counts every change to the account's synced items rev BIGINT NOT NULL DEFAULT 0) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Signed in on the website. id is the digest of the cookie.CREATE TABLE IF NOT EXISTS sessions ( id CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL PRIMARY KEY, user_id BIGINT UNSIGNED NOT NULL, created BIGINT NOT NULL, seen BIGINT NOT NULL, expires BIGINT NOT NULL, ip VARCHAR(64) NOT NULL DEFAULT '', agent VARCHAR(200) NOT NULL DEFAULT '', KEY sessions_user (user_id), FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Links sent by email: kind is 'verify' or 'reset'CREATE TABLE IF NOT EXISTS email_tokens ( hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL PRIMARY KEY, user_id BIGINT UNSIGNED NOT NULL, kind VARCHAR(16) CHARACTER SET ascii NOT NULL, email VARCHAR(254) NOT NULL, expires BIGINT NOT NULL, KEY email_tokens_user (user_id), FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- For slowing down guessing: one row per try that countsCREATE TABLE IF NOT EXISTS attempts ( what VARCHAR(300) NOT NULL, tried BIGINT NOT NULL, KEY attempts_what (what, tried)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- A device (an app on it) signed in to the accountCREATE TABLE IF NOT EXISTS grants ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, user_id BIGINT UNSIGNED NOT NULL, client_id VARCHAR(64) NOT NULL, scope VARCHAR(255) NOT NULL, device VARCHAR(64) NOT NULL DEFAULT '', ip VARCHAR(64) NOT NULL DEFAULT '', created BIGINT NOT NULL, used BIGINT NOT NULL, KEY grants_user (user_id), FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Authorization codes. A used one stays until it expires with the grant-- it became, so using it twice ends that grant.CREATE TABLE IF NOT EXISTS codes ( hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL PRIMARY KEY, user_id BIGINT UNSIGNED NOT NULL, client_id VARCHAR(64) NOT NULL, redirect_uri VARCHAR(512) NOT NULL, scope VARCHAR(255) NOT NULL, challenge VARCHAR(128) NOT NULL, nonce VARCHAR(255) NOT NULL DEFAULT '', auth_time BIGINT NOT NULL, expires BIGINT NOT NULL, used TINYINT NOT NULL DEFAULT 0, grant_id BIGINT UNSIGNED NULL, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Access and refresh tokens. A refresh token is replaced every time it-- is used; `replaced` is when.CREATE TABLE IF NOT EXISTS tokens ( hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL PRIMARY KEY, grant_id BIGINT UNSIGNED NOT NULL, kind VARCHAR(16) CHARACTER SET ascii NOT NULL, expires BIGINT NOT NULL, replaced BIGINT NULL, KEY tokens_grant (grant_id), FOREIGN KEY (grant_id) REFERENCES grants(id) ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- What is synced: named blobs the server never looks into. A deleted-- one stays as a row without data, so other devices hear of it.CREATE TABLE IF NOT EXISTS items ( user_id BIGINT UNSIGNED NOT NULL, name VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, type VARCHAR(100) CHARACTER SET ascii NOT NULL DEFAULT 'application/octet-stream', data MEDIUMBLOB NULL, size INT NOT NULL DEFAULT 0, rev BIGINT NOT NULL, updated BIGINT NOT NULL, device VARCHAR(64) NOT NULL DEFAULT '', deleted TINYINT NOT NULL DEFAULT 0, PRIMARY KEY (user_id, name), KEY items_rev (user_id, rev), FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859#!/usr/bin/env php<?php// Looking after the site from a shell.declare(strict_types=1);
require __DIR__ . '/../src/app.php';require __DIR__ . '/../src/http.php';require __DIR__ . '/../src/users.php';
$usage = <<<TXTUsage: c8-online COMMAND
init make the tables that aren't there yet cleanup delete what ran out (run it daily, from cron or a timer) users list the accounts delete EMAIL delete an account and everything in it serve [ADDR] run PHP's own web server, for trying things out (default 127.0.0.1:8088; not for the internet)
TXT;
$cmd = $argv[1] ?? '';switch ($cmd) {case 'init': db_init(); data_dir(); echo "The tables are there.\n"; break;case 'cleanup': cleanup(); break;case 'users': foreach (q('SELECT u.*, (SELECT COUNT(*) FROM grants g WHERE g.user_id = u.id) AS devices FROM users u ORDER BY id') as $u) { printf("%s\t%s\t%s\t%s\t%d devices\n", $u['email'], $u['name'], $u['email_verified'] ? 'confirmed' : 'unconfirmed', date('Y-m-d', $u['created']), $u['devices']); } break;case 'delete': $u = user_by_email($argv[2] ?? ''); if ($u === null) { fwrite(STDERR, "There is no account with that address.\n"); exit(1); } q('DELETE FROM users WHERE id = ?', [$u['id']]); echo "Deleted {$u['email']}.\n"; break;case 'serve': $addr = $argv[2] ?? '127.0.0.1:8088'; $public = realpath(__DIR__ . '/../public'); passthru(escapeshellarg(PHP_BINARY) . ' -S ' . escapeshellarg($addr) . ' -t ' . escapeshellarg($public) . ' ' . escapeshellarg($public . '/index.php'), $status); exit($status);default: fwrite($cmd === '' || $cmd === 'help' ? STDOUT : STDERR, $usage); exit($cmd === '' || $cmd === 'help' ? 0 : 1);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104<?php// Every request comes here (see README.md for the web server's side).declare(strict_types=1);
/* php -S: files that exist in public/ are served as they are */if (PHP_SAPI === 'cli-server') { $p = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); if (is_string($p) && $p !== '/' && !str_ends_with($p, '.php') && is_file(__DIR__ . $p)) { return false; }}
require __DIR__ . '/../src/app.php';require __DIR__ . '/../src/http.php';require __DIR__ . '/../src/users.php';require __DIR__ . '/../src/oauth.php';require __DIR__ . '/../src/api.php';require __DIR__ . '/../src/pages.php';
const ROUTES = [ ['GET', '/', 'page_home'], ['GET', '/login', 'page_login'], ['POST', '/login', 'page_login_post'], ['POST', '/logout', 'page_logout_post'], ['GET', '/register', 'page_register'], ['POST', '/register', 'page_register_post'], ['GET', '/verify', 'page_verify'], ['GET', '/forgot', 'page_forgot'], ['POST', '/forgot', 'page_forgot_post'], ['GET', '/reset', 'page_reset'], ['POST', '/reset', 'page_reset_post'],
['GET', '/account', 'page_account'], ['POST', '/account/profile', 'page_profile_post'], ['POST', '/account/email', 'page_email_post'], ['POST', '/account/verify', 'page_verify_send_post'], ['GET', '/account/password', 'page_password'], ['POST', '/account/password', 'page_password_post'], ['GET', '/account/devices', 'page_devices'], ['POST', '/account/devices/signout', 'page_device_signout_post'], ['POST', '/account/sessions/signout', 'page_session_signout_post'], ['GET', '/account/sync', 'page_sync'], ['POST', '/account/sync/clear', 'page_sync_clear_post'], ['GET', '/account/close', 'page_close'], ['POST', '/account/close', 'page_close_post'],
['GET', '/.well-known/openid-configuration', 'oauth_discovery'], ['GET', '/oauth/jwks', 'oauth_jwks'], ['GET', '/oauth/authorize', 'oauth_authorize'], ['POST', '/oauth/authorize', 'oauth_authorize_post'], ['POST', '/oauth/token', 'oauth_token'], ['GET', '/oauth/userinfo', 'oauth_userinfo'], ['POST', '/oauth/userinfo', 'oauth_userinfo'], ['POST', '/oauth/revoke', 'oauth_revoke'], ['GET', '/cont8nuum.provider', 'provider_file'],
['GET', '/api/v1/account', 'api_account'], ['PUT', '/api/v1/device', 'api_device'], ['GET', '/api/v1/settings', 'api_items'],];
$path = path();/* Programs get JSON, people get pages */$machine = str_starts_with($path, '/api/') || in_array($path, ['/oauth/token', '/oauth/userinfo', '/oauth/revoke'], true);
try { common_headers(); $method = method() === 'HEAD' ? 'GET' : method(); if (preg_match('#^/api/v1/settings/([^/]+)$#', $path, $m)) { api_item(rawurldecode($m[1])); } $known = false; foreach (ROUTES as [$verb, $route, $fn]) { if ($route !== $path) { continue; } if ($verb === $method) { $fn(); } $known = true; } if ($machine) { $known ? json_fail(405, 'method_not_allowed', 'Not that method here') : json_fail(404, 'not_found', 'There is nothing at that address'); } $known ? fail(405, 'That didn\'t work', 'This page can\'t be used that way.') : fail(404, 'We can\'t find that page', 'Check the address and try again.');} catch (Throwable $e) { error_log('c8-online: ' . $e); while (ob_get_level() > 0) { ob_end_clean(); } if ($machine) { json_fail(500, 'server_error', 'Something went wrong on our side'); } http_response_code(500); header('Content-Type: text/html; charset=utf-8'); echo '<!doctype html><meta charset="utf-8"><title>Something went wrong', '</title><link rel="stylesheet" href="/style.css">', '<main class="card"><h1>Something went wrong</h1>', '<p>It\'s us, not you. Try again in a little while.</p></main>';}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220<?php// The API devices use with their access token: the account, the// device's name, and the synced items. Documented in README.md.declare(strict_types=1);
const ITEM_NAME = '/^[a-z0-9][a-z0-9._-]{0,63}$/';
function api_account(): never { $g = bearer_auth(); json_out(claims($g, $g['scopes']) + ['device' => $g['device']]);}
/* PUT /api/v1/device {"name": "…"}: what the account pages call it */function api_device(): never { $g = bearer_auth(); $in = json_decode(file_get_contents('php://input', false, null, 0, 4096), true); $name = is_array($in) && is_string($in['name'] ?? null) ? trim($in['name']) : ''; if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1f\x7f]/', $name)) { json_fail(400, 'invalid_request', 'name must be 1 to 64 characters'); } q('UPDATE grants SET device = ? WHERE id = ?', [$name, $g['id']]); json_out(['device' => $name]);}
function item_out(array $i): array { $o = ['name' => $i['name'], 'rev' => $i['rev'], 'updated' => $i['updated'], 'device' => $i['device']]; if ($i['deleted']) { return $o + ['deleted' => true]; } return $o + ['size' => $i['size'], 'type' => $i['type']];}
/* GET /api/v1/settings[?since=REV]: every item, or what changed after * REV (deletions too). `rev` is what to pass as since next time. */function api_items(): never { $g = bearer_auth('sync'); $since = query('since'); if ($since !== '' && !ctype_digit($since)) { json_fail(400, 'invalid_request', 'since must be a number'); } /* One snapshot, so rev and the items belong together */ [$rev, $items] = transaction(function () use ($g, $since) { $rev = row('SELECT rev FROM users WHERE id = ?', [$g['user_id']]); $cols = 'name, type, size, rev, updated, device, deleted'; $items = $since === '' ? q("SELECT $cols FROM items WHERE user_id = ? AND deleted = 0 ORDER BY name", [$g['user_id']])->fetchAll() : q("SELECT $cols FROM items WHERE user_id = ? AND rev > ? ORDER BY rev", [$g['user_id'], (int)$since])->fetchAll(); return [$rev['rev'], $items]; }); json_out(['rev' => $rev, 'items' => array_map('item_out', $items), 'limits' => ['item_max_bytes' => config('item_max_bytes'), 'picture_max_bytes' => config('picture_max_bytes'), 'item_max_count' => config('item_max_count')]]);}
/* If-Match / If-None-Match: '*', a number, or null when not sent */function precondition(string $header): string|int|null { $v = trim($_SERVER[$header] ?? ''); if ($v === '') { return null; } if ($v === '*') { return '*'; } if (preg_match('/^(?:W\/)?"(\d+)"$/', $v, $m)) { return (int)$m[1]; } json_fail(400, 'invalid_request', 'Give the revision as "REV" or *');}
function item_headers(array $i): void { header('ETag: "' . $i['rev'] . '"'); header('X-C8-Rev: ' . $i['rev']);}
function api_item(string $name): never { $g = bearer_auth('sync'); if (!preg_match(ITEM_NAME, $name)) { json_fail(400, 'invalid_name', 'Names are a-z, 0-9, dot, dash and underscore, up to 64'); } switch (method()) { case 'GET': item_get($g, $name); case 'PUT': item_put($g, $name); case 'DELETE': item_delete($g, $name); } header('Allow: GET, PUT, DELETE'); json_fail(405, 'method_not_allowed', 'GET, PUT or DELETE');}
function item_get(array $g, string $name): never { $i = row('SELECT * FROM items WHERE user_id = ? AND name = ? AND deleted = 0', [$g['user_id'], $name]); if ($i === null) { json_fail(404, 'not_found', 'Nothing is kept under that name'); } item_headers($i); header('Cache-Control: no-store'); if (precondition('HTTP_IF_NONE_MATCH') === $i['rev']) { http_response_code(304); exit; } header('Content-Type: ' . $i['type']); header('Content-Length: ' . strlen($i['data'])); header('X-C8-Updated: ' . $i['updated']); echo $i['data']; exit;}
/* The item as it is now, with the account's row locked: one device's * write at a time, so revisions never run backwards. */function item_locked(array $g, string $name): array { $u = row('SELECT rev FROM users WHERE id = ? FOR UPDATE', [$g['user_id']]); $i = row('SELECT * FROM items WHERE user_id = ? AND name = ?', [$g['user_id'], $name]); return [$u['rev'], $i, $i !== null && !$i['deleted']];}
/* Why the If-Match the device sent doesn't hold, or null */function mismatch(string|int|null $match, ?array $i, bool $exists): ?array { if ($match === null || ($match === '*' && $exists) || ($exists && $match === $i['rev'])) { return null; } return [412, 'conflict', 'Another device changed it first', ['rev' => $exists ? $i['rev'] : null]];}
function item_put(array $g, string $name): never { $type = strtolower(trim($_SERVER['CONTENT_TYPE'] ?? '')); if (!preg_match('~^[a-z0-9.+-]+/[a-z0-9.+-]+(; ?charset=[a-z0-9-]+)?$~', $type) || strlen($type) > 100) { $type = 'application/octet-stream'; } /* Pictures are bigger than settings */ $max = config(str_starts_with($type, 'image/') ? 'picture_max_bytes' : 'item_max_bytes'); if ((int)($_SERVER['CONTENT_LENGTH'] ?? 0) > $max) { json_fail(413, 'too_large', "An item can be $max bytes at most"); } $data = file_get_contents('php://input', false, null, 0, $max + 1); if (strlen($data) > $max) { json_fail(413, 'too_large', "An item can be $max bytes at most"); } $match = precondition('HTTP_IF_MATCH'); $only_new = precondition('HTTP_IF_NONE_MATCH') === '*'; $device = $g['device'] !== '' ? $g['device'] : (client($g['client_id'])['name'] ?? '');
$r = transaction(function () use ($g, $name, $data, $type, $match, $only_new, $device) { [$rev, $i, $exists] = item_locked($g, $name); if ($only_new && $exists) { return [412, 'conflict', 'It is there already', ['rev' => $i['rev']]]; } if ($bad = mismatch($match, $i, $exists)) { return $bad; } if ($exists && $i['data'] === $data && $i['type'] === $type) { return $i + ['created' => false]; // nothing new to tell anyone } if (!$exists) { $n = q('SELECT COUNT(*) FROM items WHERE user_id = ? AND deleted = 0', [$g['user_id']])->fetchColumn(); if ($n >= config('item_max_count')) { return [507, 'too_many', 'The account holds as many ' . 'items as it can', []]; } } $rev++; q('UPDATE users SET rev = ? WHERE id = ?', [$rev, $g['user_id']]); q('REPLACE INTO items (user_id, name, type, data, size, rev, updated, device, deleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)', [$g['user_id'], $name, $type, $data, strlen($data), $rev, now(), $device]); return ['name' => $name, 'type' => $type, 'size' => strlen($data), 'rev' => $rev, 'updated' => now(), 'device' => $device, 'deleted' => 0, 'created' => !$exists]; }); if (array_is_list($r)) { json_fail($r[0], $r[1], $r[2], $r[3]); } item_headers($r); json_out(item_out($r), $r['created'] ? 201 : 200);}
function item_delete(array $g, string $name): never { $match = precondition('HTTP_IF_MATCH'); $r = transaction(function () use ($g, $name, $match) { [$rev, $i, $exists] = item_locked($g, $name); if (!$exists) { return [404, 'not_found', 'Nothing is kept under that name', []]; } if ($bad = mismatch($match, $i, $exists)) { return $bad; } $rev++; q('UPDATE users SET rev = ? WHERE id = ?', [$rev, $g['user_id']]); q('UPDATE items SET data = NULL, size = 0, deleted = 1, rev = ?, updated = ?, device = ? WHERE user_id = ? AND name = ?', [$rev, now(), $g['device'], $g['user_id'], $name]); return ['name' => $name, 'rev' => $rev, 'updated' => now(), 'device' => $g['device'], 'deleted' => 1]; }); if (array_is_list($r)) { json_fail($r[0], $r[1], $r[2], $r[3]); } json_out(item_out($r));}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155<?php// Configuration, the database and the small helpers everything uses.declare(strict_types=1);
const C8_ROOT = __DIR__ . '/..';
function config(?string $key = null): mixed { static $c = null; if ($c === null) { $c = [ 'name' => 'cont8nuum account', 'author' => 'lowtide', 'url' => 'http://127.0.0.1:8088', 'db' => [ 'dsn' => 'mysql:host=127.0.0.1;dbname=c8_online;charset=utf8mb4', 'user' => 'c8_online', 'password' => '', ], 'data' => C8_ROOT . '/data', 'registration' => true, 'mail' => 'log', 'mail_from' => 'cont8nuum account <noreply@localhost>', 'trust_proxy' => false, 'clients' => [ 'cont8nuum' => [ 'name' => 'cont8nuum desktop', 'redirect' => ['http://127\.0\.0\.1:\d+/callback'], 'scopes' => ['openid', 'email', 'profile', 'offline_access', 'sync'], ], ], 'session_ttl' => 30 * 86400, 'access_ttl' => 3600, 'refresh_ttl' => 90 * 86400, 'item_max_bytes' => 256 * 1024, // Start and lock screen pictures (image/*): under nginx's 1m 'picture_max_bytes' => 1000 * 1024, 'item_max_count' => 64, ]; $file = getenv('C8_ONLINE_CONFIG') ?: C8_ROOT . '/config.php'; if (is_file($file)) { $c = array_merge($c, require $file); } $c['url'] = rtrim($c['url'], '/'); } return $key === null ? $c : $c[$key];}
function now(): int { return time();}
/* Is the site served over https? Decides the cookies' Secure flag. */function is_https(): bool { return str_starts_with(config('url'), 'https://');}
function db(): PDO { static $db = null; if ($db !== null) { return $db; } $c = config('db'); $db = new PDO($c['dsn'], $c['user'], $c['password'], [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, /* Real prepared statements: numbers come back as numbers */ PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_STRINGIFY_FETCHES => false, ]); /* Too long or wrong is an error, never quietly cut short */ $db->exec("SET SESSION sql_mode = 'STRICT_ALL_TABLES'"); return $db;}
/* Where the signing key and the mail log are kept */function data_dir(): string { $dir = config('data'); if (!is_dir($dir) && !@mkdir($dir, 0700, true)) { throw new RuntimeException("Can't make the data folder $dir"); } return $dir;}
/* Makes the tables that aren't there yet (bin/c8-online init). */function db_init(): void { $sql = preg_replace('/^\s*--.*$/m', '', file_get_contents(C8_ROOT . '/schema.sql')); foreach (explode(';', $sql) as $statement) { if (trim($statement) !== '') { db()->exec($statement); } }}
/* Run a statement with its values; returns it for fetching. */function q(string $sql, array $args = []): PDOStatement { $st = db()->prepare($sql); foreach (array_values($args) as $i => $v) { $st->bindValue($i + 1, $v, is_int($v) ? PDO::PARAM_INT : ($v === null ? PDO::PARAM_NULL : PDO::PARAM_STR)); } $st->execute(); return $st;}
function row(string $sql, array $args = []): ?array { $r = q($sql, $args)->fetch(); return $r === false ? null : $r;}
/* Writes that belong together. Rows read inside with FOR UPDATE stay * locked until it ends, so a second request waits for the first. */function transaction(callable $fn): mixed { db()->beginTransaction(); try { $r = $fn(); db()->commit(); return $r; } catch (Throwable $e) { if (db()->inTransaction()) { db()->rollBack(); } throw $e; }}
/* A secret for a cookie, a link or a token: 256 bits, URL-safe. */function secret(): string { return b64url(random_bytes(32));}
/* Secrets are kept only as this, so the database alone opens nothing. */function digest(string $secret): string { return hash('sha256', $secret);}
function b64url(string $bytes): string { return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');}
/* Old rows nobody needs: run now and then (bin/c8-online cleanup). */function cleanup(): void { $t = now(); q('DELETE FROM sessions WHERE expires < ?', [$t]); q('DELETE FROM email_tokens WHERE expires < ?', [$t]); q('DELETE FROM attempts WHERE tried < ?', [$t - 86400]); q('DELETE FROM codes WHERE expires < ?', [$t - 3600]); q('DELETE FROM tokens WHERE expires < ?', [$t]); /* A device whose last token ran out is signed out */ q('DELETE FROM grants WHERE id NOT IN (SELECT grant_id FROM tokens)'); /* Every device that syncs has heard of a deletion by now */ q('DELETE FROM items WHERE deleted = 1 AND updated < ?', [$t - 180 * 86400]);}