dashboard/server/public/index.php
bashynx fb3c01cdd7 dashPi: a self-hosted home dashboard, its sync server and phone app
The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end
encrypted sync mailbox (PHP + SQLite) and the Android companion app
(Flutter), with docs, clean-install checks and screenshots made from
demo data.

Built mostly with an AI coding assistant; not yet reviewed line by line
by a human (see README and SECURITY.md).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 09:56:19 +02:00

286 lines
13 KiB
PHP

<?php
// dash-sync-server: a mailbox for the dashboard's encrypted sync batches (see ../PROTOCOL.md).
// It never sees a key: it stores what devices send and hands it to the account's other devices.
//
// GET /v1/hello who you are + the newest batch number
// GET /v1/key the account's wrapped data key (404 until the first device sets it)
// PUT /v1/key[?replace=1] store it (replace=1: a new passphrase — only from the device that set it)
// POST /v1/batches an encrypted batch (application/octet-stream) → {seq}
// GET /v1/batches?after=N&limit=50 batches after N, oldest first (blob base64)
// GET /v1/devices the account's devices (+ you, and whether you may manage them)
// POST /v1/devices {name} a new device → {name, token} (shown once) — the managing device only
// POST /v1/devices/revoke {name} its token stops working — the managing device only
// GET /v1/app the newest phone app build: {version, build, size, sha256, published, notes} (404: none)
// GET /v1/app/apk that APK (the app updates itself from it — app/tool/publish.sh puts it here)
// GET /v1/food/search?q=… the Open Food Facts archive (src/food.php): q, brand, country, category, nutriscore, barcode, limit
// GET /v1/food/info the archive: {products, built, source} (404: none uploaded)
//
// Auth: "Authorization: Bearer <device token>" (bin/admin.php makes tokens; only their SHA-256 is kept).
declare(strict_types=1);
$config = require __DIR__ . '/../config.php';
require __DIR__ . '/../src/db.php';
require __DIR__ . '/../src/food.php';
header('Content-Type: application/json');
header('Cache-Control: no-store');
header('X-Content-Type-Options: nosniff');
function out(int $code, array $body): never {
global $pdo, $writing;
if (!empty($writing)) { // a POST's / PUT's writes (see "who is asking"): in before the answer
$pdo->exec('COMMIT'); // (a raw BEGIN: PDO's inTransaction() doesn't know about it)
$writing = false;
}
http_response_code($code);
echo json_encode($body, JSON_UNESCAPED_SLASHES);
exit;
}
// the route: /v1/… from PATH_INFO / the rewritten URI (Apache, nginx), or ?r=/v1/… without rewriting
$path = $_GET['r'] ?? (parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
$base = rtrim($config['base_path'] ?? '', '/');
if ($base !== '' && str_starts_with($path, $base)) {
$path = substr($path, strlen($base));
}
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
try {
$pdo = open_db($config['db']);
} catch (Throwable $e) {
error_log('dash-sync: ' . $e->getMessage());
out(500, ['error' => 'storage unavailable']);
}
// ---- who is asking
$auth = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
if (!preg_match('/^Bearer\s+([A-Za-z0-9_-]{20,})$/', $auth, $m)) {
out(401, ['error' => 'missing token']);
}
$st = $pdo->prepare('SELECT d.id, d.name, d.account_id, a.name AS account FROM device d JOIN account a ON a.id = d.account_id
WHERE d.token_hash = ? AND d.revoked = 0');
$st->execute([hash('sha256', $m[1])]);
$dev = $st->fetch();
$st->closeCursor(); // else the read stays open and a write after it is an upgrade (below)
if (!$dev) {
out(401, ['error' => 'unknown or revoked token']);
}
// A POST / PUT is one write transaction, its lock taken first (BEGIN IMMEDIATE waits up to busy_timeout). A write
// that starts as a read can't wait in WAL mode: it fails at once ("database is locked") when another device's
// batch got in between. out() commits. A GET only notes last_seen, and that may be skipped when busy.
$writing = false;
if ($method !== 'GET') {
$pdo->exec('BEGIN IMMEDIATE');
$writing = true;
}
try {
$pdo->prepare('UPDATE device SET last_seen = ? WHERE id = ?')->execute([gmdate('c'), $dev['id']]);
} catch (PDOException $e) {
if ($method !== 'GET') {
throw $e;
}
}
$acc = (int)$dev['account_id'];
function latest(PDO $pdo, int $acc): int {
$st = $pdo->prepare('SELECT COALESCE(MAX(seq), 0) FROM batch WHERE account_id = ?');
$st->execute([$acc]);
return (int)$st->fetchColumn();
}
// ---- routes
if ($path === '/v1/hello' && $method === 'GET') {
out(200, ['account' => $dev['account'], 'device' => $dev['name'], 'latest' => latest($pdo, $acc), 'server' => 'dash-sync/1']);
}
if ($path === '/v1/key' && $method === 'GET') {
$st = $pdo->prepare('SELECT data FROM keyblob WHERE account_id = ?');
$st->execute([$acc]);
$k = $st->fetchColumn();
if ($k === false) {
out(404, ['error' => 'no key yet']);
}
echo $k;
exit;
}
if ($path === '/v1/key' && $method === 'PUT') {
$raw = file_get_contents('php://input') ?: '';
$k = json_decode($raw, true);
if (!is_array($k) || strlen($raw) > 4096 || !isset($k['v'], $k['salt'], $k['nonce'], $k['box'])) {
out(400, ['error' => 'not a wrapped key']);
}
$st = $pdo->prepare('SELECT data, updated, device_id FROM keyblob WHERE account_id = ?');
$st->execute([$acc]);
$old = $st->fetch();
if ($old && ($_GET['replace'] ?? '') !== '1') {
out(409, ['error' => 'the account has a key already (replace=1 to change the passphrase)']);
}
// a lost phone's token mustn't be able to swap the key for every new device: only the device that set it
// (or any, with 'key_replace_any' => true in config.php); the old one is kept (keyblob_old)
if ($old && (int)$old['device_id'] !== (int)$dev['id'] && empty($config['key_replace_any'])) {
out(403, ['error' => 'only the device that set the key can change the passphrase']);
}
if ($old) {
$pdo->prepare('INSERT INTO keyblob_old (account_id, data, updated, device_id, replaced) VALUES (?, ?, ?, ?, ?)')
->execute([$acc, $old['data'], $old['updated'], $old['device_id'], gmdate('c')]);
}
$pdo->prepare('INSERT INTO keyblob (account_id, data, updated, device_id) VALUES (?, ?, ?, ?)
ON CONFLICT(account_id) DO UPDATE SET data = excluded.data, updated = excluded.updated, device_id = excluded.device_id')
->execute([$acc, json_encode($k, JSON_UNESCAPED_SLASHES), gmdate('c'), $dev['id']]);
out(200, ['ok' => true]);
}
if ($path === '/v1/batches' && $method === 'POST') {
$max = (int)($config['max_batch_bytes'] ?? 8 * 1024 * 1024);
$len = (int)($_SERVER['CONTENT_LENGTH'] ?? 0);
if ($len > $max) {
out(413, ['error' => 'batch too big']);
}
$blob = file_get_contents('php://input') ?: '';
if (strlen($blob) < 45 || strlen($blob) > $max || substr($blob, 0, 4) !== "DS1\0") {
out(400, ['error' => 'not a sync batch']);
}
$quota = (int)($config['max_account_bytes'] ?? 1024 * 1024 * 1024);
$st = $pdo->prepare('SELECT COALESCE(SUM(size), 0) FROM batch WHERE account_id = ?');
$st->execute([$acc]);
if ($quota > 0 && (int)$st->fetchColumn() + strlen($blob) > $quota) {
out(507, ['error' => 'the account is full (max_account_bytes in config.php)']);
}
$st = $pdo->prepare('INSERT INTO batch (account_id, device_id, at, size, blob) VALUES (?, ?, ?, ?, ?)');
$st->bindValue(1, $acc, PDO::PARAM_INT);
$st->bindValue(2, (int)$dev['id'], PDO::PARAM_INT);
$st->bindValue(3, gmdate('c'));
$st->bindValue(4, strlen($blob), PDO::PARAM_INT);
$st->bindValue(5, $blob, PDO::PARAM_LOB);
$st->execute();
out(200, ['seq' => (int)$pdo->lastInsertId()]);
}
if ($path === '/v1/batches' && $method === 'GET') {
$after = max(0, (int)($_GET['after'] ?? 0));
$limit = min(200, max(1, (int)($_GET['limit'] ?? 50)));
$st = $pdo->prepare('SELECT b.seq, d.name AS device, b.at, b.size, b.blob FROM batch b JOIN device d ON d.id = b.device_id
WHERE b.account_id = ? AND b.seq > ? ORDER BY b.seq LIMIT ' . $limit);
$st->execute([$acc, $after]);
$rows = [];
$bytes = 0;
$cap = (int)($config['max_answer_bytes'] ?? 32 * 1024 * 1024); // fewer batches then; clients ask again
while ($r = $st->fetch()) {
if ($rows && $bytes + (int)$r['size'] > $cap) {
break;
}
$bytes += (int)$r['size'];
$blob = is_resource($r['blob']) ? stream_get_contents($r['blob']) : $r['blob'];
$rows[] = ['seq' => (int)$r['seq'], 'device' => $r['device'], 'at' => $r['at'], 'size' => (int)$r['size'],
'blob' => base64_encode($blob)];
}
out(200, ['batches' => $rows, 'latest' => latest($pdo, $acc)]);
}
// ---- the phone app's updates: files in app/ next to the code (not served directly), uploaded over SSH by
// app/tool/publish.sh — app.json + dash-app.apk. Any device of any account may fetch them (it's the app,
// not anyone's data); Android itself refuses an update not signed with the installed app's key.
$appDir = rtrim($config['app_dir'] ?? __DIR__ . '/../app', '/');
if ($path === '/v1/app' && $method === 'GET') {
$j = @file_get_contents($appDir . '/app.json');
$info = $j === false ? null : json_decode($j, true);
if (!is_array($info) || !is_file($appDir . '/dash-app.apk')) {
out(404, ['error' => 'no app published']);
}
out(200, $info);
}
if ($path === '/v1/app/apk' && $method === 'GET') {
$f = $appDir . '/dash-app.apk';
if (!is_file($f)) {
out(404, ['error' => 'no app published']);
}
header_remove('Content-Type');
header('Content-Type: application/vnd.android.package-archive');
header('Content-Length: ' . filesize($f));
header('Content-Disposition: attachment; filename="dash-app.apk"');
while (ob_get_level()) {
ob_end_clean();
}
readfile($f);
exit;
}
// ---- the food archive: a read-only file next to the code (food/off-archive.db, uploaded over SSH — the dashboard's
// plugins/food/off.py --archive). Not anyone's data: any device may search it.
if (str_starts_with($path, '/v1/food/') && $method === 'GET') {
try {
$fdb = food_db($config['food_db'] ?? __DIR__ . '/../food/off-archive.db');
if (!$fdb) {
out(404, ['error' => 'no food archive uploaded']);
}
if ($path === '/v1/food/info') {
out(200, food_info($fdb));
}
if ($path === '/v1/food/search') {
out(200, ['items' => food_search($fdb, $_GET, $config['food_home'] ?? [])]);
}
} catch (PDOException $e) {
error_log('dash-sync food: ' . $e->getMessage());
out(500, ['error' => 'food search failed']);
}
}
// ---- the account's devices. The managing device is the one that set the data key (the first dashboard): it may
// add devices (the phone's token comes from its Settings ▸ General ▸ Sync as a QR code) and revoke them.
function manager(PDO $pdo, int $acc): ?int {
$st = $pdo->prepare('SELECT device_id FROM keyblob WHERE account_id = ?');
$st->execute([$acc]);
$id = $st->fetchColumn();
return $id === false || $id === null ? null : (int)$id;
}
function body_json(): array {
$raw = file_get_contents('php://input') ?: '';
$j = strlen($raw) <= 4096 ? json_decode($raw, true) : null;
return is_array($j) ? $j : [];
}
if ($path === '/v1/devices' && $method === 'GET') {
$st = $pdo->prepare('SELECT id, name, created, last_seen, revoked FROM device WHERE account_id = ? ORDER BY id');
$st->execute([$acc]);
$boss = manager($pdo, $acc);
$rows = array_map(fn($r) => ['name' => $r['name'], 'created' => $r['created'], 'last_seen' => $r['last_seen'],
'revoked' => (int)$r['revoked'], 'you' => (int)$r['id'] === (int)$dev['id'],
'manager' => (int)$r['id'] === $boss], $st->fetchAll());
out(200, ['devices' => $rows, 'manager' => $boss === (int)$dev['id']]);
}
if (($path === '/v1/devices' || $path === '/v1/devices/revoke') && $method === 'POST') {
if (manager($pdo, $acc) !== (int)$dev['id']) {
out(403, ['error' => 'only the device that set up the key can manage devices']);
}
$name = trim((string)(body_json()['name'] ?? ''));
if (!preg_match('/^[A-Za-z0-9 ._-]{1,40}$/', $name)) {
out(400, ['error' => 'a device name: letters, digits, space . _ - (up to 40)']);
}
if ($path === '/v1/devices/revoke') {
if ($name === $dev['name']) {
out(400, ['error' => "a device can't revoke itself"]);
}
$st = $pdo->prepare('UPDATE device SET revoked = 1 WHERE account_id = ? AND name = ?');
$st->execute([$acc, $name]);
out($st->rowCount() ? 200 : 404, $st->rowCount() ? ['ok' => true] : ['error' => 'no such device']);
}
$token = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
try {
$pdo->prepare('INSERT INTO device (account_id, name, token_hash, created) VALUES (?, ?, ?, ?)')
->execute([$acc, $name, hash('sha256', $token), gmdate('c')]);
} catch (PDOException $e) { // the name is taken: a revoked one gets the new token
$st = $pdo->prepare('UPDATE device SET token_hash = ?, created = ?, last_seen = NULL, revoked = 0
WHERE account_id = ? AND name = ? AND revoked = 1');
$st->execute([hash('sha256', $token), gmdate('c'), $acc, $name]);
if (!$st->rowCount()) {
out(409, ['error' => 'there is a device with that name already (revoke it first to replace it)']);
}
}
out(200, ['name' => $name, 'token' => $token]);
}
out(404, ['error' => 'no such endpoint']);