// php bin/admin.php add-device prints the token once (only its hash is kept) // php bin/admin.php list // php bin/admin.php revoke // php bin/admin.php stats declare(strict_types=1); if (PHP_SAPI !== 'cli') { exit(1); } $config = require __DIR__ . '/../config.php'; require __DIR__ . '/../src/db.php'; $pdo = open_db($config['db']); $a = $argv; $now = gmdate('c'); function account_id(PDO $pdo, string $name): int { $st = $pdo->prepare('SELECT id FROM account WHERE name = ?'); $st->execute([$name]); $id = $st->fetchColumn(); if ($id === false) { fwrite(STDERR, "No account “{$name}”.\n"); exit(1); } return (int)$id; } switch ($a[1] ?? '') { case 'add-account': if (!isset($a[2]) || !preg_match('/^[a-z0-9_-]{2,40}$/', $a[2])) { exit("Usage: add-account (a-z, 0-9, _ -)\n"); } $pdo->prepare('INSERT INTO account (name, created) VALUES (?, ?)')->execute([$a[2], $now]); echo "Account “{$a[2]}” made.\n"; break; case 'add-device': if (!isset($a[2], $a[3])) { exit("Usage: add-device \n"); } $acc = account_id($pdo, $a[2]); $token = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '='); $pdo->prepare('INSERT INTO device (account_id, name, token_hash, created) VALUES (?, ?, ?, ?)') ->execute([$acc, $a[3], hash('sha256', $token), $now]); echo "Device “{$a[3]}” added to “{$a[2]}”. Its token (shown only now):\n\n {$token}\n\n"; break; case 'list': foreach ($pdo->query('SELECT a.name AS account, d.name, d.created, d.last_seen, d.revoked FROM device d JOIN account a ON a.id = d.account_id ORDER BY a.name, d.id') as $r) { printf("%-12s %-20s made %s seen %s%s\n", $r['account'], $r['name'], substr($r['created'], 0, 10), $r['last_seen'] ? substr($r['last_seen'], 0, 16) : 'never', $r['revoked'] ? ' REVOKED' : ''); } break; case 'revoke': if (!isset($a[2], $a[3])) { exit("Usage: revoke \n"); } $st = $pdo->prepare('UPDATE device SET revoked = 1 WHERE account_id = ? AND name = ?'); $st->execute([account_id($pdo, $a[2]), $a[3]]); echo $st->rowCount() ? "Revoked.\n" : "No such device.\n"; break; case 'stats': foreach ($pdo->query('SELECT a.name, COUNT(b.seq) AS n, COALESCE(SUM(b.size), 0) AS bytes, MAX(b.at) AS last FROM account a LEFT JOIN batch b ON b.account_id = a.id GROUP BY a.id') as $r) { printf("%-12s %6d batches %8.1f KB last %s\n", $r['name'], $r['n'], $r['bytes'] / 1024, $r['last'] ?? '—'); } break; default: echo "php bin/admin.php add-account | add-device | list | revoke | stats\n"; }