Harden auth, add subtitles, vendor all assets locally
- Session cookies are HttpOnly + SameSite=Lax (Secure on HTTPS), with strict session-ID mode; the CSRF token from GET api/auth.php must now accompany every state-changing request (X-CSRF-Token header, or a csrf body field for the sendBeacon progress save), rotated at login. - Failed sign-ins are throttled per username and IP via login_attempts (created lazily, so existing installs need no migration): 5 failures a username / 20 an IP inside 15 minutes answer 429 with Retry-After. - A video's sibling .srt now appears as a CC button in the player; captions.php converts it to WebVTT (comma timestamps, legacy encodings, and the already-VTT files with out-of-spec 6-digit fractions). - Plyr and Inter ship in assets/vendor/ instead of coming from CDNs, and anime.js is gone along with all scripted animations and the motion setting — the app now runs with no internet access at all. - .htaccess denies direct access to videos/, includes/, config.php and schema.sql, so video URLs cannot bypass login on Apache. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SePf61iazhCLJBefdRLBDm
This commit is contained in:
@@ -2,6 +2,16 @@
|
||||
require_once __DIR__ . '/db.php';
|
||||
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
// Reject session IDs the server never issued (blocks session fixation),
|
||||
// and keep the cookie away from scripts and cross-site requests.
|
||||
ini_set('session.use_strict_mode', '1');
|
||||
session_set_cookie_params([
|
||||
'lifetime' => 0,
|
||||
'path' => '/',
|
||||
'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
|
||||
'httponly' => true,
|
||||
'samesite' => 'Lax',
|
||||
]);
|
||||
session_start();
|
||||
}
|
||||
|
||||
@@ -10,6 +20,33 @@ function currentUserId(): ?int
|
||||
return isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : null;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* CSRF
|
||||
* The token lives in the session and reaches the SPA via GET api/auth.php
|
||||
* (and again in the login/register response, since login rotates it). Every
|
||||
* state-changing request must echo it back — fetch() sends the X-CSRF-Token
|
||||
* header; sendBeacon() can't set headers, so a `csrf` body field counts too.
|
||||
* ------------------------------------------------------------------------- */
|
||||
function csrfToken(): string
|
||||
{
|
||||
if (empty($_SESSION['csrf_token'])) {
|
||||
$_SESSION['csrf_token'] = bin2hex(random_bytes(16));
|
||||
}
|
||||
return $_SESSION['csrf_token'];
|
||||
}
|
||||
|
||||
/** 403s the request unless it carries the session's CSRF token. */
|
||||
function verifyCsrfApi(?array $body = null): void
|
||||
{
|
||||
$sent = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? $body['csrf'] ?? '';
|
||||
if (!is_string($sent) || $sent === '' || !hash_equals(csrfToken(), $sent)) {
|
||||
http_response_code(403);
|
||||
header('Content-Type: application/json');
|
||||
echo json_encode(['error' => 'Invalid session token — reload the page and try again.']);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
function currentUsername(): ?string
|
||||
{
|
||||
return $_SESSION['username'] ?? null;
|
||||
@@ -44,6 +81,7 @@ function attemptLogin(string $username, string $password): bool
|
||||
$user = $stmt->fetch();
|
||||
if ($user && password_verify($password, $user['password_hash'])) {
|
||||
session_regenerate_id(true);
|
||||
unset($_SESSION['csrf_token']); // a fresh token for the fresh session id
|
||||
$_SESSION['user_id'] = (int)$user['id'];
|
||||
$_SESSION['username'] = $user['username'];
|
||||
return true;
|
||||
@@ -51,6 +89,82 @@ function attemptLogin(string $username, string $password): bool
|
||||
return false;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* Login brute-force throttle
|
||||
* Failed attempts are recorded per username + IP. Once a username collects
|
||||
* LOGIN_MAX_USER_FAILS failures (or an IP LOGIN_MAX_IP_FAILS, across any
|
||||
* usernames) inside LOGIN_FAIL_WINDOW, sign-in answers 429 until the window
|
||||
* has passed since the last failure. Retrying while blocked never verifies a
|
||||
* password, so it doesn't extend the block. A successful login clears the
|
||||
* username's failures.
|
||||
* ------------------------------------------------------------------------- */
|
||||
const LOGIN_FAIL_WINDOW = 900; // seconds
|
||||
const LOGIN_MAX_USER_FAILS = 5;
|
||||
const LOGIN_MAX_IP_FAILS = 20;
|
||||
|
||||
/** Seconds until this username/IP may try again — 0 means go ahead. */
|
||||
function loginRetryAfter(string $username, string $ip): int
|
||||
{
|
||||
// The clock math stays inside MySQL: TIMESTAMP values come back in the
|
||||
// connection's time zone, so comparing them against PHP's clock would be
|
||||
// off by the server's UTC offset.
|
||||
$recent = function (string $col, string $value): array {
|
||||
$stmt = db()->prepare(
|
||||
"SELECT COUNT(*) AS fails,
|
||||
COALESCE(TIMESTAMPDIFF(SECOND, NOW(),
|
||||
MAX(attempted_at) + INTERVAL " . LOGIN_FAIL_WINDOW . " SECOND), 0) AS retry
|
||||
FROM login_attempts
|
||||
WHERE $col = ? AND attempted_at > NOW() - INTERVAL " . LOGIN_FAIL_WINDOW . " SECOND"
|
||||
);
|
||||
$stmt->execute([$value]);
|
||||
return $stmt->fetch();
|
||||
};
|
||||
|
||||
try {
|
||||
$user = $recent('username', $username);
|
||||
$byIp = $recent('ip', $ip);
|
||||
} catch (Throwable $e) {
|
||||
return 0; // table not created yet — no failures recorded so far
|
||||
}
|
||||
|
||||
$retry = 0;
|
||||
if ((int)$user['fails'] >= LOGIN_MAX_USER_FAILS) {
|
||||
$retry = max($retry, (int)$user['retry']);
|
||||
}
|
||||
if ((int)$byIp['fails'] >= LOGIN_MAX_IP_FAILS) {
|
||||
$retry = max($retry, (int)$byIp['retry']);
|
||||
}
|
||||
return max(0, $retry);
|
||||
}
|
||||
|
||||
function recordLoginFailure(string $username, string $ip): void
|
||||
{
|
||||
$db = db();
|
||||
// Lazy creation keeps installs made before this table existed working
|
||||
// (same pattern as app_meta).
|
||||
$db->exec(
|
||||
'CREATE TABLE IF NOT EXISTS login_attempts (
|
||||
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
||||
username VARCHAR(50) NOT NULL,
|
||||
ip VARCHAR(45) NOT NULL,
|
||||
attempted_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
INDEX idx_la_user_time (username, attempted_at),
|
||||
INDEX idx_la_ip_time (ip, attempted_at)
|
||||
) ENGINE=InnoDB'
|
||||
);
|
||||
$db->prepare('DELETE FROM login_attempts WHERE attempted_at < NOW() - INTERVAL 1 HOUR')->execute();
|
||||
$db->prepare('INSERT INTO login_attempts (username, ip) VALUES (?, ?)')->execute([$username, $ip]);
|
||||
}
|
||||
|
||||
function clearLoginFailures(string $username): void
|
||||
{
|
||||
try {
|
||||
db()->prepare('DELETE FROM login_attempts WHERE username = ?')->execute([$username]);
|
||||
} catch (Throwable $e) {
|
||||
// table doesn't exist yet — nothing to clear
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns true on success, or an error-message string. */
|
||||
function registerUser(string $username, string $password): string|bool
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user