tinyauth-web/src/lib.php

291 lines
8.3 KiB
PHP

<?php
declare(strict_types=1);
const SECRET_PATTERN = '/SECRET|PASSWORD|TOKEN|AUTH_USERS$/i';
const KEY_PATTERN = '/^[A-Za-z_][A-Za-z0-9_]*$/';
const SERVICE_ACTIONS = ['status', 'start', 'stop', 'restart'];
require_once __DIR__ . '/keys.php';
/** Turns a key template such as TINYAUTH_APPS_<NAME>_CONFIG_DOMAIN into a regex. */
function template_regex(string $template): string
{
$parts = array_map(fn (string $p): string => preg_quote($p, '/'), explode('<NAME>', $template));
return '/^' . implode('[A-Z0-9]+', $parts) . '$/';
}
/** Install-level settings that rarely change. Shown in a closed "Core settings" section. Patterns use * wildcards. */
const DEFAULT_CORE_KEYS = [
'TINYAUTH_APPURL',
'TINYAUTH_SERVER_*',
'TINYAUTH_AUTH_SECURECOOKIE',
'TINYAUTH_AUTH_SUBDOMAINSENABLED',
'TINYAUTH_AUTH_TRUSTEDPROXIES',
'TINYAUTH_ANALYTICS_*',
'TINYAUTH_LDAP_*',
'TINYAUTH_OIDC_PRIVATEKEYPATH',
'TINYAUTH_OIDC_PUBLICKEYPATH',
'TINYAUTH_DATABASE_*',
'TINYAUTH_LOG_*',
'TINYAUTH_UI_*',
];
function is_core_key(string $key): bool
{
foreach ((config()['core_keys'] ?? DEFAULT_CORE_KEYS) as $pattern) {
if (fnmatch($pattern, $key)) {
return true;
}
}
return false;
}
function key_info(string $key): ?array
{
static $entries = null;
if ($entries === null) {
$entries = [];
foreach (known_keys() as $entry) {
$entries[] = ['regex' => template_regex($entry['key'])] + $entry;
}
}
foreach ($entries as $entry) {
if (preg_match($entry['regex'], $key)) {
return $entry;
}
}
return null;
}
function blank_keys(array $vars): array
{
return array_keys(array_filter($vars, fn (string $v): bool => trim($v) === ''));
}
function current_env(): string
{
$file = config()['env_file'];
return is_file($file) && is_readable($file) ? (string) file_get_contents($file) : '';
}
function config(): array
{
static $config = null;
if ($config === null) {
$file = dirname(__DIR__) . '/config.php';
if (!is_file($file)) {
http_response_code(500);
exit('Missing config.php. Copy config.example.php to config.php and edit it.');
}
$config = require $file;
}
return $config;
}
function h(?string $value): string
{
return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}
function redirect(string $to): never
{
header('Location: ' . $to);
exit;
}
function start_session(): void
{
session_name('tinyauthweb');
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'secure' => !empty($_SERVER['HTTPS']),
'httponly' => true,
'samesite' => 'Lax',
]);
session_start();
}
function csrf_token(): string
{
return $_SESSION['csrf'] ??= bin2hex(random_bytes(32));
}
function require_csrf(): void
{
if (!hash_equals($_SESSION['csrf'] ?? '', (string) ($_POST['csrf'] ?? ''))) {
http_response_code(400);
exit('Invalid form token. Reload the page and try again.');
}
}
function flash(string $type, string $message): void
{
$_SESSION['flash'][] = ['type' => $type, 'message' => $message];
}
function take_flashes(): array
{
$flashes = $_SESSION['flash'] ?? [];
unset($_SESSION['flash']);
return $flashes;
}
function data_dir(): string
{
$dir = config()['data_dir'];
if (!is_dir($dir) && !mkdir($dir, 0750, true) && !is_dir($dir)) {
throw new RuntimeException("Cannot create data directory $dir");
}
return $dir;
}
function load_settings(): array
{
$file = data_dir() . '/settings.json';
if (!is_file($file)) {
return [];
}
$data = json_decode((string) file_get_contents($file), true);
return is_array($data) ? $data : [];
}
function save_settings(array $settings): void
{
$file = data_dir() . '/settings.json';
if (file_put_contents($file, json_encode($settings, JSON_PRETTY_PRINT), LOCK_EX) === false) {
throw new RuntimeException("Cannot write $file");
}
}
function is_authorized(array $groups): bool
{
$allowed = load_settings()['allowed_group'] ?? '';
return $allowed !== '' && in_array($allowed, $groups, true);
}
function http_request(string $method, string $url, array $fields = [], array $headers = []): array
{
if ($method === 'POST') {
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
}
$options = [
'http' => [
'method' => $method,
'header' => implode("\r\n", $headers),
'timeout' => 15,
'ignore_errors' => true,
],
];
if ($method === 'POST') {
$options['http']['content'] = http_build_query($fields);
}
$body = @file_get_contents($url, false, stream_context_create($options));
if ($body === false) {
throw new RuntimeException("Request to $url failed.");
}
preg_match('#^HTTP/\S+\s+(\d{3})#', $http_response_header[0] ?? '', $m);
$code = (int) ($m[1] ?? 0);
if ($code >= 400 || $code === 0) {
throw new RuntimeException("Request to $url returned HTTP $code");
}
$json = json_decode($body, true);
return is_array($json) ? $json : [];
}
function oidc_discovery(): array
{
static $discovery = null;
if ($discovery === null) {
$base = rtrim(config()['tinyauth_url'], '/');
$discovery = http_request('GET', $base . '/.well-known/openid-configuration');
}
return $discovery;
}
function run_command(array $command): array
{
$proc = proc_open($command, [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
if (!is_resource($proc)) {
return ['code' => -1, 'output' => 'Could not start ' . $command[0]];
}
fclose($pipes[0]);
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$code = proc_close($proc);
return ['code' => $code, 'output' => trim($stdout . "\n" . $stderr)];
}
function service_allowed(string $action): bool
{
$cfg = config();
return run_command(['sudo', '-n', '-l', $cfg['systemctl'], $action, $cfg['service']])['code'] === 0;
}
function service_run(string $action): array
{
$cfg = config();
return run_command(['sudo', '-n', $cfg['systemctl'], $action, $cfg['service']]);
}
function env_parse(string $content): array
{
$vars = [];
foreach (preg_split('/\r?\n/', $content) as $line) {
if (preg_match('/^\s*([A-Za-z_][A-Za-z0-9_]*)=(.*)$/', $line, $m)) {
$vars[$m[1]] = $m[2];
}
}
return $vars;
}
function env_apply(string $content, array $changes, array $deletes): string
{
$out = [];
$written = [];
foreach (preg_split('/\r?\n/', $content) as $line) {
if (preg_match('/^\s*([A-Za-z_][A-Za-z0-9_]*)=/', $line, $m)) {
$key = $m[1];
if (in_array($key, $deletes, true) || isset($written[$key])) {
continue;
}
if (array_key_exists($key, $changes)) {
$out[] = $key . '=' . $changes[$key];
$written[$key] = true;
continue;
}
}
$out[] = $line;
}
while ($out !== [] && end($out) === '') {
array_pop($out);
}
foreach ($changes as $key => $value) {
if (!isset($written[$key])) {
$out[] = $key . '=' . $value;
}
}
return rtrim(implode("\n", $out), "\n") . "\n";
}
function page_start(string $title, string $userHtml = ''): void
{
echo '<!doctype html><html lang="en"><head><meta charset="utf-8">'
. '<meta name="viewport" content="width=device-width,initial-scale=1">'
. '<title>' . h($title) . ' · tinyauth-web</title>'
. '<script>try{var t=localStorage.getItem("tinyauth-web-theme");if(t){document.documentElement.setAttribute("data-theme",t)}}catch(e){}</script>'
. '<link rel="stylesheet" href="assets/style.css">'
. '</head><body>'
. '<header class="topbar"><div class="brand"><span class="logo">◆</span>tinyauth-web</div>'
. '<div class="topbar-right">' . $userHtml
. '<button type="button" class="btn btn-ghost btn-sm" id="theme-toggle" title="Toggle light/dark">◐ Theme</button>'
. '</div></header><main>';
}
function page_end(): void
{
echo '</main><footer class="footer">tinyauth-web</footer><script src="assets/app.js"></script></body></html>';
}