multi-tenant relay und card-push to user
This commit is contained in:
1 parent
7219bae655
commit
5b18c46ac2
22 files changed
+7453
-519
No files matched your search
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
// Auth helpers: rate limiting, sessions (UI), client API auth (header).
|
||||
|
||||
if (!defined('RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
function isRateLimited(PDO $db, string $endpoint, int $max = 10): bool {
|
||||
$ip = $_SERVER['REMOTE_ADDR'] ?? '';
|
||||
$count = $db->prepare("SELECT COUNT(*) FROM rate_limits WHERE ip = :ip AND endpoint = :ep AND attempted_at > datetime('now', '-1 minutes')");
|
||||
$count->execute(['ip' => $ip, 'ep' => $endpoint]);
|
||||
if ((int)$count->fetchColumn() >= $max) return true;
|
||||
$db->prepare("INSERT INTO rate_limits (ip, endpoint) VALUES (:ip, :ep)")->execute(['ip' => $ip, 'ep' => $endpoint]);
|
||||
return false;
|
||||
}
|
||||
|
||||
function makeSession(PDO $db, int $tenantId, int $hours = 24): string {
|
||||
$token = bin2hex(random_bytes(32));
|
||||
$db->prepare("INSERT INTO sessions (id, tenant_id, expires_at) VALUES (:t, :u, datetime('now', '+{$hours} hours'))")
|
||||
->execute(['t' => $token, 'u' => $tenantId]);
|
||||
return $token;
|
||||
}
|
||||
|
||||
function getSessionTenant(PDO $db): ?array {
|
||||
$token = $_COOKIE['relay_session'] ?? '';
|
||||
if (!$token) return null;
|
||||
$stmt = $db->prepare("SELECT t.* FROM sessions s JOIN tenants t ON t.id = s.tenant_id WHERE s.id = :tok AND s.expires_at > datetime('now')");
|
||||
$stmt->execute(['tok' => $token]);
|
||||
return $stmt->fetch() ?: null;
|
||||
}
|
||||
|
||||
function destroySession(PDO $db): void {
|
||||
$token = $_COOKIE['relay_session'] ?? '';
|
||||
if ($token) {
|
||||
$db->prepare('DELETE FROM sessions WHERE id = :t')->execute(['t' => $token]);
|
||||
}
|
||||
setcookie('relay_session', '', [
|
||||
'expires' => time() - 3600,
|
||||
'path' => '/',
|
||||
'httponly' => true,
|
||||
'samesite' => 'Strict',
|
||||
'secure' => !empty($_SERVER['HTTPS']) || ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https',
|
||||
]);
|
||||
}
|
||||
|
||||
function setSessionCookie(string $token): void {
|
||||
setcookie('relay_session', $token, [
|
||||
'expires' => time() + 86400,
|
||||
'path' => '/',
|
||||
'httponly' => true,
|
||||
'samesite' => 'Strict',
|
||||
'secure' => !empty($_SERVER['HTTPS']) || ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate a tenant via the client API headers (X-Relay-User + X-Relay-Key).
|
||||
* Returns the tenant row on success, null on failure.
|
||||
*/
|
||||
function authClient(PDO $db): ?array {
|
||||
$username = $_SERVER['HTTP_X_RELAY_USER'] ?? '';
|
||||
$key = $_SERVER['HTTP_X_RELAY_KEY'] ?? '';
|
||||
if (!$username || !$key) return null;
|
||||
$tenant = getTenantByUsername($db, $username);
|
||||
if (!$tenant) return null;
|
||||
if (!password_verify($key, $tenant['secret_hash'])) return null;
|
||||
return $tenant;
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
<?php
|
||||
// Bootstrap: DB connection, master key, schema + migration, common helpers.
|
||||
// All include files require RELAY_BOOTSTRAPPED to be defined by index.php.
|
||||
|
||||
if (!defined('RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
error_reporting(0);
|
||||
ini_set('display_errors', '0');
|
||||
|
||||
// ── Paths ─────────────────────────────────────────────────────────
|
||||
|
||||
$RELAY_ROOT = dirname(__DIR__);
|
||||
$dbPath = $RELAY_ROOT . '/data/relay.db';
|
||||
$dbDir = dirname($dbPath);
|
||||
if (!is_dir($dbDir)) mkdir($dbDir, 0755, true);
|
||||
|
||||
// ── Master key ────────────────────────────────────────────────────
|
||||
//
|
||||
// Generated on first install, stored in data/master.key (chmod 600,
|
||||
// blocked from web access via .htaccess). Encrypts everything that
|
||||
// needs to be recoverable: tenant secrets, the inter-tenant key.
|
||||
|
||||
$masterKeyPath = $RELAY_ROOT . '/data/master.key';
|
||||
if (!file_exists($masterKeyPath)) {
|
||||
file_put_contents($masterKeyPath, bin2hex(random_bytes(32)));
|
||||
@chmod($masterKeyPath, 0600);
|
||||
}
|
||||
$MASTER_KEY = trim(file_get_contents($masterKeyPath));
|
||||
|
||||
// ── Database ──────────────────────────────────────────────────────
|
||||
|
||||
$db = new PDO('sqlite:' . $dbPath, null, null, [
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
||||
]);
|
||||
$db->exec('PRAGMA journal_mode = WAL');
|
||||
$db->exec('PRAGMA foreign_keys = ON');
|
||||
|
||||
// ── Schema migration from single-tenant relay ──────────────────────
|
||||
//
|
||||
// Old schema (pre-multitenant) had `messages` and `attachments` tables
|
||||
// without recipient_id/sender_id. CREATE TABLE IF NOT EXISTS would skip
|
||||
// recreating them, leaving the old shape in place — and inserts with
|
||||
// the new column list would silently fail. Detect and drop the old
|
||||
// tables here. Old data is 24h ephemeral so it's a safe drop.
|
||||
|
||||
function tableHasColumn(PDO $db, string $table, string $col): bool {
|
||||
try {
|
||||
$cols = array_column($db->query("PRAGMA table_info($table)")->fetchAll(), 'name');
|
||||
return in_array($col, $cols, true);
|
||||
} catch (\Throwable $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function tableExists(PDO $db, string $table): bool {
|
||||
try {
|
||||
$r = $db->prepare("SELECT name FROM sqlite_master WHERE type='table' AND name = :n");
|
||||
$r->execute(['n' => $table]);
|
||||
return (bool)$r->fetchColumn();
|
||||
} catch (\Throwable $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (tableExists($db, 'messages') && !tableHasColumn($db, 'messages', 'recipient_id')) {
|
||||
$db->exec('DROP TABLE IF EXISTS messages');
|
||||
@error_log('[hyprcrd-relay] migrated: dropped legacy single-tenant messages table');
|
||||
}
|
||||
if (tableExists($db, 'attachments') && !tableHasColumn($db, 'attachments', 'recipient_id')) {
|
||||
$db->exec('DROP TABLE IF EXISTS attachments');
|
||||
@error_log('[hyprcrd-relay] migrated: dropped legacy single-tenant attachments table');
|
||||
}
|
||||
// Old single-tenant settings keys (relay_password, relay_key) are unused
|
||||
// but left in place to allow downgrade.
|
||||
|
||||
// v2 → v3 migration: tenants.secret_hash and .secret_encrypted are now
|
||||
// nullable because users set their own client secret rather than having
|
||||
// the admin assign one. SQLite can't ALTER COLUMN constraints, so we
|
||||
// recreate the table while preserving rows.
|
||||
function tableColumnIsNotNull(PDO $db, string $table, string $col): bool {
|
||||
try {
|
||||
$cols = $db->query("PRAGMA table_info($table)")->fetchAll();
|
||||
foreach ($cols as $c) {
|
||||
if ($c['name'] === $col) return (bool)$c['notnull'];
|
||||
}
|
||||
} catch (\Throwable $e) {}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (tableExists($db, 'tenants') && tableColumnIsNotNull($db, 'tenants', 'secret_hash')) {
|
||||
$db->exec('PRAGMA foreign_keys = OFF');
|
||||
$db->exec('CREATE TABLE tenants_v3_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
secret_hash TEXT,
|
||||
secret_encrypted TEXT,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
password_changed INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)');
|
||||
// Copy existing rows but blank the secret columns — old admin-assigned
|
||||
// secrets are deprecated; users must re-set their own via the account UI.
|
||||
// Non-admin tenants in v2 had admin-set passwords, so force them to change.
|
||||
$db->exec('INSERT INTO tenants_v3_new (id, username, password_hash, secret_hash, secret_encrypted, is_admin, password_changed, created_at)
|
||||
SELECT id, username, password_hash, NULL, NULL, is_admin,
|
||||
CASE WHEN is_admin = 1 THEN 1 ELSE 0 END,
|
||||
created_at FROM tenants');
|
||||
$db->exec('DROP TABLE tenants');
|
||||
$db->exec('ALTER TABLE tenants_v3_new RENAME TO tenants');
|
||||
$db->exec('PRAGMA foreign_keys = ON');
|
||||
@error_log('[hyprcrd-relay] migrated v2->v3: tenant secrets now self-set, non-admin passwords flagged for forced change');
|
||||
}
|
||||
|
||||
// v3.0 → v3.1 migration: add password_changed column if missing
|
||||
if (tableExists($db, 'tenants') && !tableHasColumn($db, 'tenants', 'password_changed')) {
|
||||
$db->exec('ALTER TABLE tenants ADD COLUMN password_changed INTEGER NOT NULL DEFAULT 1');
|
||||
// Force non-admin users to change their password (they were admin-set)
|
||||
$db->exec('UPDATE tenants SET password_changed = 0 WHERE is_admin = 0');
|
||||
@error_log('[hyprcrd-relay] migrated v3.0->v3.1: added password_changed flag, non-admins forced to change');
|
||||
}
|
||||
|
||||
// ── Schema ─────────────────────────────────────────────────────────
|
||||
|
||||
$db->exec('CREATE TABLE IF NOT EXISTS tenants (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
secret_hash TEXT,
|
||||
secret_encrypted TEXT,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
password_changed INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)');
|
||||
|
||||
$db->exec('CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT
|
||||
)');
|
||||
|
||||
$db->exec('CREATE TABLE IF NOT EXISTS messages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
recipient_id INTEGER NOT NULL,
|
||||
sender_id INTEGER,
|
||||
sender_username TEXT,
|
||||
title TEXT DEFAULT "",
|
||||
body TEXT NOT NULL,
|
||||
color TEXT DEFAULT "#38bdf8",
|
||||
tags TEXT DEFAULT "",
|
||||
relay_uid TEXT DEFAULT NULL,
|
||||
fetched INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (recipient_id) REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (sender_id) REFERENCES tenants(id) ON DELETE SET NULL
|
||||
)');
|
||||
|
||||
$db->exec('CREATE TABLE IF NOT EXISTS attachments (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
recipient_id INTEGER NOT NULL,
|
||||
relay_uid TEXT NOT NULL,
|
||||
filename TEXT NOT NULL,
|
||||
data TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (recipient_id) REFERENCES tenants(id) ON DELETE CASCADE
|
||||
)');
|
||||
|
||||
$db->exec('CREATE TABLE IF NOT EXISTS sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at TEXT NOT NULL,
|
||||
FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
|
||||
)');
|
||||
|
||||
$db->exec('CREATE TABLE IF NOT EXISTS rate_limits (
|
||||
ip TEXT NOT NULL,
|
||||
endpoint TEXT NOT NULL,
|
||||
attempted_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)');
|
||||
|
||||
// Cleanup: 24h ephemeral storage, expired sessions, old rate limits
|
||||
$db->exec("DELETE FROM messages WHERE created_at < datetime('now', '-24 hours')");
|
||||
$db->exec("DELETE FROM attachments WHERE created_at < datetime('now', '-24 hours')");
|
||||
$db->exec("DELETE FROM sessions WHERE expires_at < datetime('now')");
|
||||
$db->exec("DELETE FROM rate_limits WHERE attempted_at < datetime('now', '-5 minutes')");
|
||||
|
||||
// ── Common response helper ────────────────────────────────────────
|
||||
|
||||
function jsonResponse($data, int $code = 200): void {
|
||||
http_response_code($code);
|
||||
header('Content-Type: application/json');
|
||||
echo json_encode($data);
|
||||
exit;
|
||||
}
|
||||
|
||||
// ── Security headers ──────────────────────────────────────────────
|
||||
|
||||
header('X-Frame-Options: DENY');
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
header('Referrer-Policy: no-referrer');
|
||||
if (!empty($_SERVER['HTTPS']) || ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https') {
|
||||
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
// Crypto helpers: at-rest encryption with master key, plus the
|
||||
// HYPRCRD-RELAY-V1 envelope format used by both the JS client and
|
||||
// the relay's internal re-encryption hops.
|
||||
|
||||
if (!defined('RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
/**
|
||||
* Encrypt a value at-rest with the master key. Used for tenant secrets
|
||||
* and the inter-tenant key in the DB.
|
||||
*/
|
||||
function masterEncrypt(string $plain, string $masterKeyHex): string {
|
||||
$key = hex2bin($masterKeyHex);
|
||||
$iv = random_bytes(16);
|
||||
$cipher = openssl_encrypt($plain, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
|
||||
return base64_encode($iv . $cipher);
|
||||
}
|
||||
|
||||
function masterDecrypt(string $encoded, string $masterKeyHex): string {
|
||||
$key = hex2bin($masterKeyHex);
|
||||
$raw = base64_decode($encoded);
|
||||
if (!$raw || strlen($raw) < 17) return '';
|
||||
$iv = substr($raw, 0, 16);
|
||||
$cipher = substr($raw, 16);
|
||||
return openssl_decrypt($cipher, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv) ?: '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Match the JS client's encryption format exactly:
|
||||
* key = first 32 chars of hex(SHA-256(secret)) used as 32-byte ASCII key
|
||||
* envelope = "HYPRCRD-RELAY-V1\n" + base64(iv || ciphertext)
|
||||
*/
|
||||
function clientEncrypt(string $plain, string $secret): string {
|
||||
$key = substr(hash('sha256', $secret), 0, 32);
|
||||
$iv = random_bytes(16);
|
||||
$cipher = openssl_encrypt($plain, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
|
||||
return "HYPRCRD-RELAY-V1\n" . base64_encode($iv . $cipher);
|
||||
}
|
||||
|
||||
function clientDecrypt(string $envelope, string $secret): string {
|
||||
if (!str_starts_with($envelope, 'HYPRCRD-RELAY-V1')) return $envelope;
|
||||
$b64 = trim(substr($envelope, strlen('HYPRCRD-RELAY-V1') + 1));
|
||||
$raw = base64_decode($b64);
|
||||
if (!$raw || strlen($raw) < 17) return '';
|
||||
$key = substr(hash('sha256', $secret), 0, 32);
|
||||
$iv = substr($raw, 0, 16);
|
||||
$cipher = substr($raw, 16);
|
||||
$result = openssl_decrypt($cipher, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
|
||||
return $result !== false ? $result : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Inter-tenant key: relay-wide shared "super secret" key. Set by the admin
|
||||
* during initial setup (it's the third field in the setup form). Used to
|
||||
* re-encrypt messages at rest so they can be routed between tenants.
|
||||
*
|
||||
* Returns null if not set yet (e.g. legacy v2 installs that haven't been
|
||||
* upgraded through the new setup wizard).
|
||||
*/
|
||||
function getInterTenantKey(PDO $db, string $masterKey): ?string {
|
||||
$stored = $db->query("SELECT value FROM settings WHERE key = 'inter_tenant_key'")->fetchColumn();
|
||||
if (!$stored) return null;
|
||||
$decrypted = masterDecrypt($stored, $masterKey);
|
||||
return $decrypted !== '' ? $decrypted : null;
|
||||
}
|
||||
|
||||
/** Set/replace the inter-tenant key. Stored encrypted with the master key. */
|
||||
function setInterTenantKey(PDO $db, string $masterKey, string $newKey): void {
|
||||
$encrypted = masterEncrypt($newKey, $masterKey);
|
||||
$db->prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('inter_tenant_key', :v)")
|
||||
->execute(['v' => $encrypted]);
|
||||
}
|
||||
|
||||
/** True if the relay-wide super secret has been configured. */
|
||||
function hasInterTenantKey(PDO $db): bool {
|
||||
$stored = $db->query("SELECT value FROM settings WHERE key = 'inter_tenant_key'")->fetchColumn();
|
||||
return !empty($stored);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
// Account routes — every logged-in user manages their own client secret
|
||||
// here. The admin never sees or sets it.
|
||||
//
|
||||
// GET /api/account/secret show plaintext (decrypted via master key)
|
||||
// POST /api/account/secret set/replace (body: {secret} or {generate:true})
|
||||
// DELETE /api/account/secret clear (disconnects all clients)
|
||||
|
||||
if (!defined('RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
// $sessionTenant comes from routes/public.php earlier in the chain
|
||||
|
||||
if ($route === '/api/account/secret' && $method === 'GET') {
|
||||
if (!$sessionTenant) jsonResponse(['error' => 'not logged in'], 401);
|
||||
if (empty($sessionTenant['secret_encrypted'])) {
|
||||
jsonResponse(['has_secret' => false]);
|
||||
}
|
||||
$plain = masterDecrypt($sessionTenant['secret_encrypted'], $MASTER_KEY);
|
||||
jsonResponse(['has_secret' => true, 'secret' => $plain]);
|
||||
}
|
||||
|
||||
if ($route === '/api/account/secret' && $method === 'POST') {
|
||||
if (!$sessionTenant) jsonResponse(['error' => 'not logged in'], 401);
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
|
||||
// Either accept a user-supplied secret OR generate a random one
|
||||
if (!empty($input['generate'])) {
|
||||
$secret = bin2hex(random_bytes(24)); // 48-char hex
|
||||
} else {
|
||||
$secret = (string)($input['secret'] ?? '');
|
||||
if (strlen($secret) < 8) {
|
||||
jsonResponse(['error' => 'secret must be at least 8 chars'], 400);
|
||||
}
|
||||
}
|
||||
|
||||
$db->prepare('UPDATE tenants SET secret_hash = :sh, secret_encrypted = :se WHERE id = :id')
|
||||
->execute([
|
||||
'sh' => password_hash($secret, PASSWORD_BCRYPT),
|
||||
'se' => masterEncrypt($secret, $MASTER_KEY),
|
||||
'id' => $sessionTenant['id'],
|
||||
]);
|
||||
|
||||
jsonResponse(['ok' => true, 'secret' => $secret]);
|
||||
}
|
||||
|
||||
if ($route === '/api/account/secret' && $method === 'DELETE') {
|
||||
if (!$sessionTenant) jsonResponse(['error' => 'not logged in'], 401);
|
||||
$db->prepare('UPDATE tenants SET secret_hash = NULL, secret_encrypted = NULL WHERE id = :id')
|
||||
->execute(['id' => $sessionTenant['id']]);
|
||||
jsonResponse(['ok' => true]);
|
||||
}
|
||||
|
||||
if ($route === '/api/account/password' && $method === 'POST') {
|
||||
if (!$sessionTenant) jsonResponse(['error' => 'not logged in'], 401);
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$current = (string)($input['current'] ?? '');
|
||||
$new = (string)($input['new'] ?? '');
|
||||
|
||||
if (strlen($new) < 4) jsonResponse(['error' => 'new password must be at least 4 chars'], 400);
|
||||
if (!password_verify($current, $sessionTenant['password_hash'])) {
|
||||
jsonResponse(['error' => 'current password is wrong'], 401);
|
||||
}
|
||||
if ($current === $new) {
|
||||
jsonResponse(['error' => 'new password must differ from current'], 400);
|
||||
}
|
||||
|
||||
$db->prepare('UPDATE tenants SET password_hash = :p, password_changed = 1 WHERE id = :id')
|
||||
->execute([
|
||||
'p' => password_hash($new, PASSWORD_BCRYPT),
|
||||
'id' => $sessionTenant['id'],
|
||||
]);
|
||||
jsonResponse(['ok' => true]);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
// Admin-only routes (session + is_admin):
|
||||
// GET /api/users
|
||||
// POST /api/users
|
||||
// PATCH /api/users/{id}
|
||||
// DELETE /api/users/{id}
|
||||
//
|
||||
// Plus the tenant directory available to any logged-in user:
|
||||
// GET /api/tenants
|
||||
|
||||
if (!defined('RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
// $sessionTenant is set by routes/public.php earlier in the chain
|
||||
|
||||
if ($route === '/api/users' && $method === 'GET') {
|
||||
if (!$sessionTenant || !$sessionTenant['is_admin']) jsonResponse(['error' => 'admin only'], 403);
|
||||
$rows = $db->query('SELECT id, username, is_admin, created_at FROM tenants ORDER BY id ASC')->fetchAll();
|
||||
jsonResponse(['users' => $rows]);
|
||||
}
|
||||
|
||||
if ($route === '/api/users' && $method === 'POST') {
|
||||
if (!$sessionTenant || !$sessionTenant['is_admin']) jsonResponse(['error' => 'admin only'], 403);
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$username = trim((string)($input['username'] ?? ''));
|
||||
$password = (string)($input['password'] ?? '');
|
||||
$isAdmin = !empty($input['is_admin']) ? 1 : 0;
|
||||
|
||||
if (!preg_match('/^[a-zA-Z0-9_-]{2,32}$/', $username)) {
|
||||
jsonResponse(['error' => 'username must be 2-32 chars: letters, digits, _ or -'], 400);
|
||||
}
|
||||
if (strlen($password) < 4) jsonResponse(['error' => 'password must be at least 4 chars'], 400);
|
||||
if (getTenantByUsername($db, $username)) jsonResponse(['error' => 'username already exists'], 409);
|
||||
|
||||
// No client secret — the new user sets that themselves after first login
|
||||
// via the account view. password_hash is bcrypted; secret columns stay NULL.
|
||||
// password_changed = 0 forces a password change on first login (the
|
||||
// admin-supplied password is meant as a temporary credential).
|
||||
// Admin-flagged users still need to change because the admin set it.
|
||||
$db->prepare('INSERT INTO tenants (username, password_hash, is_admin, password_changed) VALUES (:u, :p, :a, 0)')
|
||||
->execute([
|
||||
'u' => $username,
|
||||
'p' => password_hash($password, PASSWORD_BCRYPT),
|
||||
'a' => $isAdmin,
|
||||
]);
|
||||
jsonResponse(['ok' => true, 'id' => (int)$db->lastInsertId()]);
|
||||
}
|
||||
|
||||
if (preg_match('#^/api/users/(\d+)$#', $route, $m) && $method === 'PATCH') {
|
||||
if (!$sessionTenant || !$sessionTenant['is_admin']) jsonResponse(['error' => 'admin only'], 403);
|
||||
$id = (int)$m[1];
|
||||
$target = getTenantById($db, $id);
|
||||
if (!$target) jsonResponse(['error' => 'user not found'], 404);
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$fields = []; $params = ['id' => $id];
|
||||
if (!empty($input['password'])) {
|
||||
if (strlen($input['password']) < 4) jsonResponse(['error' => 'password too short'], 400);
|
||||
$fields[] = 'password_hash = :pw';
|
||||
$params['pw'] = password_hash($input['password'], PASSWORD_BCRYPT);
|
||||
}
|
||||
if (array_key_exists('is_admin', $input)) {
|
||||
if (!$input['is_admin'] && $target['is_admin'] && adminCount($db) <= 1) {
|
||||
jsonResponse(['error' => 'cannot demote the last admin'], 400);
|
||||
}
|
||||
$fields[] = 'is_admin = :ad';
|
||||
$params['ad'] = $input['is_admin'] ? 1 : 0;
|
||||
}
|
||||
// Note: client secret is set by the user themselves via /api/account/secret,
|
||||
// not by the admin. Admins can only reset password and toggle admin flag.
|
||||
if (!$fields) jsonResponse(['ok' => true]);
|
||||
$db->prepare('UPDATE tenants SET ' . implode(', ', $fields) . ' WHERE id = :id')->execute($params);
|
||||
jsonResponse(['ok' => true]);
|
||||
}
|
||||
|
||||
if (preg_match('#^/api/users/(\d+)$#', $route, $m) && $method === 'DELETE') {
|
||||
if (!$sessionTenant || !$sessionTenant['is_admin']) jsonResponse(['error' => 'admin only'], 403);
|
||||
$id = (int)$m[1];
|
||||
$target = getTenantById($db, $id);
|
||||
if (!$target) jsonResponse(['error' => 'user not found'], 404);
|
||||
if ($target['is_admin'] && adminCount($db) <= 1) {
|
||||
jsonResponse(['error' => 'cannot delete the last admin'], 400);
|
||||
}
|
||||
if ($id === (int)$sessionTenant['id']) {
|
||||
jsonResponse(['error' => 'cannot delete yourself'], 400);
|
||||
}
|
||||
$db->prepare('DELETE FROM tenants WHERE id = :id')->execute(['id' => $id]);
|
||||
jsonResponse(['ok' => true]);
|
||||
}
|
||||
|
||||
// ── Tenant directory (visible to all authenticated tenants) ──────
|
||||
// Accepts both UI session auth and client API headers, so hyprcrd
|
||||
// instances can fetch the list to populate their recipient picker.
|
||||
|
||||
if ($route === '/api/tenants' && $method === 'GET') {
|
||||
$authedTenant = $sessionTenant ?: authClient($db);
|
||||
if (!$authedTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
$rows = $db->query('SELECT id, username FROM tenants ORDER BY username ASC')->fetchAll();
|
||||
jsonResponse(['tenants' => $rows, 'self' => $authedTenant['username']]);
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
<?php
|
||||
// Message + attachment routes:
|
||||
// POST /api/messages (UI session: server encrypts)
|
||||
// POST /api/messages (client API: decrypt-reencrypt hop)
|
||||
// GET /api/messages (client API: re-encrypt for recipient)
|
||||
// DELETE /api/messages/{id} (own only)
|
||||
// POST /api/attachments (client API)
|
||||
// GET /api/attachments (client API)
|
||||
|
||||
if (!defined('RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
// $sessionTenant comes from routes/public.php earlier in the chain
|
||||
|
||||
// ── UI compose path: server encrypts plaintext with inter-tenant key ──
|
||||
|
||||
if ($route === '/api/messages' && $method === 'POST' && $sessionTenant && empty($_SERVER['HTTP_X_RELAY_KEY'])) {
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$title = (string)($input['title'] ?? '');
|
||||
$body = (string)($input['body'] ?? '');
|
||||
$recipientName = trim((string)($input['recipient'] ?? $sessionTenant['username']));
|
||||
if ($body === '') jsonResponse(['error' => 'body required'], 400);
|
||||
|
||||
$recipient = getTenantByUsername($db, $recipientName);
|
||||
if (!$recipient) jsonResponse(['error' => "no such user: $recipientName"], 404);
|
||||
|
||||
$interKey = getInterTenantKey($db, $MASTER_KEY);
|
||||
if (!$interKey) jsonResponse(['error' => 'relay super-shared key not set'], 500);
|
||||
$storedTitle = clientEncrypt($title, $interKey);
|
||||
$storedBody = clientEncrypt($body, $interKey);
|
||||
|
||||
$db->prepare('INSERT INTO messages (recipient_id, sender_id, sender_username, title, body, color, tags, relay_uid) VALUES (:r, :s, :sn, :t, :b, :c, :tg, :uid)')
|
||||
->execute([
|
||||
'r' => $recipient['id'],
|
||||
's' => $sessionTenant['id'],
|
||||
'sn' => $sessionTenant['username'],
|
||||
't' => $storedTitle,
|
||||
'b' => $storedBody,
|
||||
'c' => $input['color'] ?? '#38bdf8',
|
||||
'tg' => $input['tags'] ?? '',
|
||||
'uid' => $input['relay_uid'] ?? null,
|
||||
]);
|
||||
jsonResponse(['ok' => true, 'id' => (int)$db->lastInsertId(), 'recipient' => $recipientName]);
|
||||
}
|
||||
|
||||
// ── Client API auth (X-Relay-User + X-Relay-Key) ──
|
||||
|
||||
$clientTenant = authClient($db);
|
||||
|
||||
if ($route === '/api/messages' && $method === 'POST') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$encryptedTitle = (string)($input['title'] ?? '');
|
||||
$encryptedBody = (string)($input['body'] ?? '');
|
||||
$recipientName = trim((string)($input['recipient'] ?? $clientTenant['username']));
|
||||
if ($encryptedBody === '') jsonResponse(['error' => 'body required'], 400);
|
||||
|
||||
$recipient = getTenantByUsername($db, $recipientName);
|
||||
if (!$recipient) jsonResponse(['error' => "no such user: $recipientName"], 404);
|
||||
|
||||
// Decrypt with sender's secret
|
||||
if (empty($clientTenant['secret_encrypted'])) {
|
||||
jsonResponse(['error' => 'sender has no client secret set — log into the relay UI and configure one in your account'], 400);
|
||||
}
|
||||
$senderSecret = masterDecrypt($clientTenant['secret_encrypted'], $MASTER_KEY);
|
||||
if (!$senderSecret) jsonResponse(['error' => 'sender secret unavailable'], 500);
|
||||
$plainTitle = clientDecrypt($encryptedTitle, $senderSecret);
|
||||
$plainBody = clientDecrypt($encryptedBody, $senderSecret);
|
||||
|
||||
// Re-encrypt with the inter-tenant (super-shared) key for at-rest storage
|
||||
$interKey = getInterTenantKey($db, $MASTER_KEY);
|
||||
if (!$interKey) jsonResponse(['error' => 'relay super-shared key not set — admin must complete setup'], 500);
|
||||
$storedTitle = clientEncrypt($plainTitle, $interKey);
|
||||
$storedBody = clientEncrypt($plainBody, $interKey);
|
||||
|
||||
$db->prepare('INSERT INTO messages (recipient_id, sender_id, sender_username, title, body, color, tags, relay_uid) VALUES (:r, :s, :sn, :t, :b, :c, :tg, :uid)')
|
||||
->execute([
|
||||
'r' => $recipient['id'],
|
||||
's' => $clientTenant['id'],
|
||||
'sn' => $clientTenant['username'],
|
||||
't' => $storedTitle,
|
||||
'b' => $storedBody,
|
||||
'c' => $input['color'] ?? '#38bdf8',
|
||||
'tg' => $input['tags'] ?? '',
|
||||
'uid' => $input['relay_uid'] ?? null,
|
||||
]);
|
||||
jsonResponse(['ok' => true, 'id' => (int)$db->lastInsertId(), 'recipient' => $recipientName]);
|
||||
}
|
||||
|
||||
if ($route === '/api/messages' && $method === 'GET') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
if (empty($clientTenant['secret_encrypted'])) {
|
||||
jsonResponse(['error' => 'no client secret set — log into the relay UI and configure one in your account'], 400);
|
||||
}
|
||||
|
||||
$since = $_GET['since'] ?? null;
|
||||
if ($since) {
|
||||
$stmt = $db->prepare("SELECT * FROM messages WHERE recipient_id = :r AND created_at > :s ORDER BY created_at ASC");
|
||||
$stmt->execute(['r' => $clientTenant['id'], 's' => $since]);
|
||||
} else {
|
||||
$stmt = $db->prepare("SELECT * FROM messages WHERE recipient_id = :r ORDER BY created_at ASC");
|
||||
$stmt->execute(['r' => $clientTenant['id']]);
|
||||
}
|
||||
$msgs = $stmt->fetchAll();
|
||||
|
||||
// Decrypt with inter-tenant key, re-encrypt with recipient's secret
|
||||
$interKey = getInterTenantKey($db, $MASTER_KEY);
|
||||
if (!$interKey) jsonResponse(['error' => 'relay super-shared key not set'], 500);
|
||||
$recipientSecret = masterDecrypt($clientTenant['secret_encrypted'], $MASTER_KEY);
|
||||
if (!$recipientSecret) jsonResponse(['error' => 'recipient secret unavailable'], 500);
|
||||
|
||||
$out = [];
|
||||
foreach ($msgs as $msg) {
|
||||
$plainTitle = clientDecrypt($msg['title'] ?? '', $interKey);
|
||||
$plainBody = clientDecrypt($msg['body'] ?? '', $interKey);
|
||||
$msg['title'] = clientEncrypt($plainTitle, $recipientSecret);
|
||||
$msg['body'] = clientEncrypt($plainBody, $recipientSecret);
|
||||
$out[] = $msg;
|
||||
}
|
||||
$db->prepare("UPDATE messages SET fetched = 1 WHERE recipient_id = :r AND fetched = 0")
|
||||
->execute(['r' => $clientTenant['id']]);
|
||||
jsonResponse($out);
|
||||
}
|
||||
|
||||
if (preg_match('#^/api/messages/(\d+)$#', $route, $m) && $method === 'DELETE') {
|
||||
$tenant = $clientTenant ?: $sessionTenant;
|
||||
if (!$tenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
$id = (int)$m[1];
|
||||
$db->prepare('DELETE FROM messages WHERE id = :id AND recipient_id = :r')
|
||||
->execute(['id' => $id, 'r' => $tenant['id']]);
|
||||
jsonResponse(['ok' => true]);
|
||||
}
|
||||
|
||||
if ($route === '/api/attachments' && $method === 'POST') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$relayUid = (string)($input['relay_uid'] ?? '');
|
||||
$filename = (string)($input['filename'] ?? '');
|
||||
$data = (string)($input['data'] ?? '');
|
||||
$recipientName = trim((string)($input['recipient'] ?? $clientTenant['username']));
|
||||
if (!$relayUid || !$filename || !$data) jsonResponse(['error' => 'relay_uid, filename, and data required'], 400);
|
||||
|
||||
$recipient = getTenantByUsername($db, $recipientName);
|
||||
if (!$recipient) jsonResponse(['error' => "no such user: $recipientName"], 404);
|
||||
|
||||
$db->prepare('DELETE FROM attachments WHERE recipient_id = :r AND relay_uid = :uid AND filename = :fn')
|
||||
->execute(['r' => $recipient['id'], 'uid' => $relayUid, 'fn' => $filename]);
|
||||
$db->prepare('INSERT INTO attachments (recipient_id, relay_uid, filename, data) VALUES (:r, :uid, :fn, :data)')
|
||||
->execute(['r' => $recipient['id'], 'uid' => $relayUid, 'fn' => $filename, 'data' => $data]);
|
||||
jsonResponse(['ok' => true, 'id' => (int)$db->lastInsertId()]);
|
||||
}
|
||||
|
||||
if ($route === '/api/attachments' && $method === 'GET') {
|
||||
if (!$clientTenant) jsonResponse(['error' => 'unauthorized'], 401);
|
||||
$relayUid = $_GET['relay_uid'] ?? '';
|
||||
if (!$relayUid) jsonResponse(['error' => 'relay_uid required'], 400);
|
||||
$stmt = $db->prepare('SELECT id, relay_uid, filename, data, created_at FROM attachments WHERE recipient_id = :r AND relay_uid = :uid');
|
||||
$stmt->execute(['r' => $clientTenant['id'], 'uid' => $relayUid]);
|
||||
jsonResponse($stmt->fetchAll());
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
// Public + UI session routes:
|
||||
// GET /api/status
|
||||
// POST /api/setup
|
||||
// POST /api/login
|
||||
// POST /api/logout
|
||||
// GET /api/me
|
||||
//
|
||||
// Each handler exits on match. Falls through to other route files if
|
||||
// none of these matched.
|
||||
|
||||
if (!defined('RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
// ── Public: status ─────────────────────────────────────────────────
|
||||
|
||||
if ($route === '/api/status' && $method === 'GET') {
|
||||
$data = [
|
||||
'setup' => $isSetup,
|
||||
'has_admin' => adminCount($db) > 0,
|
||||
'has_super_secret' => hasInterTenantKey($db),
|
||||
];
|
||||
$sessionTenant = getSessionTenant($db);
|
||||
if ($sessionTenant) {
|
||||
$cnt = $db->prepare('SELECT COUNT(*) FROM messages WHERE recipient_id = :r AND fetched = 0');
|
||||
$cnt->execute(['r' => $sessionTenant['id']]);
|
||||
$data['logged_in'] = true;
|
||||
$data['username'] = $sessionTenant['username'];
|
||||
$data['is_admin'] = (bool)$sessionTenant['is_admin'];
|
||||
$data['inbox_count'] = (int)$cnt->fetchColumn();
|
||||
$data['has_secret'] = !empty($sessionTenant['secret_hash']);
|
||||
$data['password_changed'] = (bool)$sessionTenant['password_changed'];
|
||||
} else {
|
||||
$data['logged_in'] = false;
|
||||
}
|
||||
jsonResponse($data);
|
||||
}
|
||||
|
||||
// ── Public: setup (only when no tenants exist) ────────────────────
|
||||
|
||||
if ($route === '/api/setup' && $method === 'POST') {
|
||||
if (isRateLimited($db, 'setup', 5)) jsonResponse(['error' => 'too many attempts'], 429);
|
||||
if (!$isSetup) jsonResponse(['error' => 'already configured'], 403);
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$username = trim((string)($input['username'] ?? ''));
|
||||
$password = (string)($input['password'] ?? '');
|
||||
$superSecret = (string)($input['super_secret'] ?? '');
|
||||
|
||||
if (!preg_match('/^[a-zA-Z0-9_-]{2,32}$/', $username)) {
|
||||
jsonResponse(['error' => 'username must be 2-32 chars: letters, digits, _ or -'], 400);
|
||||
}
|
||||
if (strlen($password) < 4) jsonResponse(['error' => 'password must be at least 4 chars'], 400);
|
||||
if (strlen($superSecret) < 12) jsonResponse(['error' => 'super-shared secret must be at least 12 chars'], 400);
|
||||
|
||||
// Create the admin tenant. NO client secret yet — the admin (and every
|
||||
// user) sets that themselves later via the account view.
|
||||
$passHash = password_hash($password, PASSWORD_BCRYPT);
|
||||
$db->prepare('INSERT INTO tenants (username, password_hash, is_admin) VALUES (:u, :p, 1)')
|
||||
->execute([
|
||||
'u' => $username,
|
||||
'p' => $passHash,
|
||||
]);
|
||||
|
||||
// Set the relay-wide super-shared key. This is the cross-tenant
|
||||
// routing key — used by the relay to re-encrypt messages at rest.
|
||||
setInterTenantKey($db, $MASTER_KEY, $superSecret);
|
||||
|
||||
$tenantId = (int)$db->lastInsertId();
|
||||
$token = makeSession($db, $tenantId);
|
||||
setSessionCookie($token);
|
||||
jsonResponse(['ok' => true, 'username' => $username, 'is_admin' => true]);
|
||||
}
|
||||
|
||||
// ── Public: login (UI session) ────────────────────────────────────
|
||||
|
||||
if ($route === '/api/login' && $method === 'POST') {
|
||||
if (isRateLimited($db, 'login', 5)) jsonResponse(['error' => 'too many attempts'], 429);
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?: [];
|
||||
$username = trim((string)($input['username'] ?? ''));
|
||||
$password = (string)($input['password'] ?? '');
|
||||
$tenant = getTenantByUsername($db, $username);
|
||||
if (!$tenant || !password_verify($password, $tenant['password_hash'])) {
|
||||
jsonResponse(['error' => 'wrong username or password'], 401);
|
||||
}
|
||||
$token = makeSession($db, (int)$tenant['id']);
|
||||
setSessionCookie($token);
|
||||
jsonResponse([
|
||||
'ok' => true,
|
||||
'username' => $tenant['username'],
|
||||
'is_admin' => (bool)$tenant['is_admin'],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($route === '/api/logout' && $method === 'POST') {
|
||||
destroySession($db);
|
||||
jsonResponse(['ok' => true]);
|
||||
}
|
||||
|
||||
// ── Session-authenticated: /api/me ────────────────────────────────
|
||||
|
||||
$sessionTenant = getSessionTenant($db);
|
||||
|
||||
if ($route === '/api/me' && $method === 'GET') {
|
||||
if (!$sessionTenant) jsonResponse(['error' => 'not logged in'], 401);
|
||||
jsonResponse([
|
||||
'username' => $sessionTenant['username'],
|
||||
'is_admin' => (bool)$sessionTenant['is_admin'],
|
||||
'created_at' => $sessionTenant['created_at'],
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
// Tenant DB lookup helpers.
|
||||
|
||||
if (!defined('RELAY_BOOTSTRAPPED')) { http_response_code(404); exit; }
|
||||
|
||||
function getTenantById(PDO $db, int $id): ?array {
|
||||
$stmt = $db->prepare('SELECT * FROM tenants WHERE id = :id');
|
||||
$stmt->execute(['id' => $id]);
|
||||
return $stmt->fetch() ?: null;
|
||||
}
|
||||
|
||||
function getTenantByUsername(PDO $db, string $username): ?array {
|
||||
$stmt = $db->prepare('SELECT * FROM tenants WHERE username = :u');
|
||||
$stmt->execute(['u' => $username]);
|
||||
return $stmt->fetch() ?: null;
|
||||
}
|
||||
|
||||
function tenantCount(PDO $db): int {
|
||||
return (int)$db->query('SELECT COUNT(*) FROM tenants')->fetchColumn();
|
||||
}
|
||||
|
||||
function adminCount(PDO $db): int {
|
||||
return (int)$db->query('SELECT COUNT(*) FROM tenants WHERE is_admin = 1')->fetchColumn();
|
||||
}
|
||||
Reference in new issue
Block a user