| 1 | <?php |
| 2 | declare(strict_types=1); |
| 3 | require_once __DIR__.'/Chess.php'; |
| 4 | require_once __DIR__.'/MoveFeedback.php'; |
| 5 | ini_set('display_errors','0'); |
| 6 | ini_set('log_errors','1'); |
| 7 | ini_set('error_log',dirname(__DIR__).'/data/php-errors.log'); |
| 8 | header('X-Content-Type-Options: nosniff'); |
| 9 | header('Referrer-Policy: same-origin'); |
| 10 | header("Content-Security-Policy: default-src 'self'; img-src 'self'; style-src 'self'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"); |
| 11 | header('Cache-Control: no-store'); |
| 12 | |
| 13 | function db(): PDO { |
| 14 | static $db; |
| 15 | if ($db) return $db; |
| 16 | $db=new PDO('sqlite:'.dirname(__DIR__).'/data/microchess.sqlite',null,null,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]); |
| 17 | $db->exec('PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;'); |
| 18 | $db->exec('CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, name TEXT NOT NULL); |
| 19 | CREATE TABLE IF NOT EXISTS user_avatars (user_id TEXT PRIMARY KEY REFERENCES users(id), avatar TEXT NOT NULL); |
| 20 | CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, payload TEXT NOT NULL, expires INTEGER NOT NULL); |
| 21 | CREATE TABLE IF NOT EXISTS friends (a TEXT NOT NULL REFERENCES users(id), b TEXT NOT NULL REFERENCES users(id), PRIMARY KEY(a,b), CHECK(a<b)); |
| 22 | CREATE TABLE IF NOT EXISTS links (token TEXT PRIMARY KEY, owner TEXT NOT NULL REFERENCES users(id), kind TEXT NOT NULL, expires INTEGER NOT NULL, used INTEGER NOT NULL DEFAULT 0); |
| 23 | CREATE TABLE IF NOT EXISTS games (id INTEGER PRIMARY KEY AUTOINCREMENT, a TEXT NOT NULL REFERENCES users(id), b TEXT NOT NULL REFERENCES users(id), status TEXT NOT NULL, white TEXT, state TEXT, winner TEXT, reason TEXT, exit_a INTEGER DEFAULT 0, exit_b INTEGER DEFAULT 0, rematch_a INTEGER DEFAULT 0, rematch_b INTEGER DEFAULT 0, draw_offer TEXT, version INTEGER DEFAULT 0, created INTEGER NOT NULL); |
| 24 | CREATE TABLE IF NOT EXISTS results (id INTEGER PRIMARY KEY AUTOINCREMENT, game_id INTEGER NOT NULL REFERENCES games(id), a TEXT NOT NULL, b TEXT NOT NULL, winner TEXT, reason TEXT NOT NULL, state TEXT NOT NULL, ended INTEGER NOT NULL); |
| 25 | CREATE INDEX IF NOT EXISTS games_a ON games(a); CREATE INDEX IF NOT EXISTS games_b ON games(b);'); |
| 26 | $columns=$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1); |
| 27 | if (!in_array('activity_at',$columns,true)) { |
| 28 | $db->exec('BEGIN IMMEDIATE'); |
| 29 | try { |
| 30 | if (!in_array('activity_at',$db->query('PRAGMA table_info(games)')->fetchAll(PDO::FETCH_COLUMN,1),true)) { |
| 31 | $db->exec('ALTER TABLE games ADD COLUMN activity_at INTEGER'); |
| 32 | $db->exec("UPDATE games SET activity_at=CAST(strftime('%s','now') AS INTEGER) WHERE activity_at IS NULL"); |
| 33 | } |
| 34 | $db->exec('COMMIT'); |
| 35 | } catch (Throwable $e) { $db->exec('ROLLBACK');throw $e; } |
| 36 | } |
| 37 | // Replace legacy triggers once, including databases already migrated on newer SQLite. |
| 38 | $legacy=$db->query("SELECT sql FROM sqlite_master WHERE type='trigger' AND name IN ('games_activity_insert','games_activity_update')")->fetchAll(PDO::FETCH_COLUMN); |
| 39 | if (array_filter($legacy,static fn(string $sql): bool => stripos($sql,'unixepoch(')!==false)) { |
| 40 | $db->exec('BEGIN IMMEDIATE'); |
| 41 | try { |
| 42 | $db->exec('DROP TRIGGER IF EXISTS games_activity_insert; DROP TRIGGER IF EXISTS games_activity_update;'); |
| 43 | activityTriggers($db); |
| 44 | $db->exec('COMMIT'); |
| 45 | } catch (Throwable $e) { $db->exec('ROLLBACK');throw $e; } |
| 46 | } else { |
| 47 | activityTriggers($db); |
| 48 | } |
| 49 | // Assign existing accounts once as well as newly created accounts. |
| 50 | foreach ($db->query('SELECT id FROM users WHERE id NOT IN (SELECT user_id FROM user_avatars)')->fetchAll(PDO::FETCH_COLUMN) as $id) { |
| 51 | $avatars=avatarCatalog(); |
| 52 | $q=$db->prepare('INSERT OR IGNORE INTO user_avatars(user_id,avatar) VALUES(?,?)'); |
| 53 | $q->execute([$id,$avatars[random_int(0,count($avatars)-1)]['id']]); |
| 54 | } |
| 55 | return $db; |
| 56 | } |
| 57 | function activityTriggers(PDO $db): void { |
| 58 | $db->exec("CREATE TRIGGER IF NOT EXISTS games_activity_insert AFTER INSERT ON games BEGIN UPDATE games SET activity_at=CAST(strftime('%s','now') AS INTEGER) WHERE id=NEW.id; END; |
| 59 | CREATE TRIGGER IF NOT EXISTS games_activity_update AFTER UPDATE OF version ON games BEGIN UPDATE games SET activity_at=CAST(strftime('%s','now') AS INTEGER) WHERE id=NEW.id; END;"); |
| 60 | } |
| 61 | function query(string $sql,array $args=[]): PDOStatement { $s=db()->prepare($sql);$s->execute($args);return $s; } |
| 62 | function profile(string $id): array { |
| 63 | return query('SELECT u.*,a.avatar FROM users u LEFT JOIN user_avatars a ON a.user_id=u.id WHERE u.id=?',[$id])->fetch(); |
| 64 | } |
| 65 | function avatarCatalog(): array { |
| 66 | static $avatars; |
| 67 | return $avatars ??= json_decode(file_get_contents(dirname(__DIR__).'/assets/avatars/catalog.json'),true,512,JSON_THROW_ON_ERROR); |
| 68 | } |
| 69 | final class DatabaseSessions implements SessionHandlerInterface { |
| 70 | public function open(string $path,string $name): bool {return true;} |
| 71 | public function close(): bool {return true;} |
| 72 | public function read(string $id): string|false {return query('SELECT payload FROM sessions WHERE id=? AND expires>?',[$id,time()])->fetchColumn()?:'';} |
| 73 | public function write(string $id,string $data): bool {query('INSERT OR REPLACE INTO sessions VALUES(?,?,?)',[$id,$data,time()+3600]);return true;} |
| 74 | public function destroy(string $id): bool {query('DELETE FROM sessions WHERE id=?',[$id]);return true;} |
| 75 | public function gc(int $max_lifetime): int|false {return query('DELETE FROM sessions WHERE expires<?',[time()])->rowCount();} |
| 76 | } |
| 77 | function localDev(): bool { |
| 78 | $host=parse_url('http://'.($_SERVER['HTTP_HOST']??''),PHP_URL_HOST); |
| 79 | return is_string($host) && in_array(strtolower($host),['localhost','127.0.0.1','[::1]'],true) && in_array($_SERVER['REMOTE_ADDR']??'', ['127.0.0.1','::1'],true); |
| 80 | } |
| 81 | function config(): array { |
| 82 | static $c; |
| 83 | if ($c !== null) return $c; |
| 84 | $path=dirname(__DIR__).'/data/config.php'; |
| 85 | $lock=fopen(dirname(__DIR__).'/data/config.lock','c'); |
| 86 | if ($lock===false) throw new RuntimeException('The data directory must be writable to initialize configuration.'); |
| 87 | try { |
| 88 | if (!flock($lock,LOCK_EX)) throw new RuntimeException('Unable to lock configuration.'); |
| 89 | if (!file_exists($path)) { |
| 90 | $template="<?php\n// Fill in these values on this server. Empty fields use environment variables.\nreturn [\n 'base_url' => '',\n 'client_id' => '',\n 'client_secret' => '',\n];\n"; |
| 91 | if (file_put_contents($path,$template)!==strlen($template)) throw new RuntimeException('Unable to create data/config.php.'); |
| 92 | } |
| 93 | $values=require $path; |
| 94 | if (!is_array($values)) throw new RuntimeException('data/config.php must return an array.'); |
| 95 | } finally { |
| 96 | flock($lock,LOCK_UN); |
| 97 | fclose($lock); |
| 98 | } |
| 99 | foreach (['base_url'=>'MICROCHESS_BASE_URL','client_id'=>'MICROCHESS_CLIENT_ID','client_secret'=>'MICROCHESS_CLIENT_SECRET'] as $key=>$env) { |
| 100 | if (($values[$key]??'')==='') $values[$key]=getenv($env)?:''; |
| 101 | } |
| 102 | return $c=$values; |
| 103 | } |
| 104 | function baseUrl(): string { |
| 105 | if (localDev()) return 'http://'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['SCRIPT_NAME']),'/'); |
| 106 | $base=rtrim(config()['base_url'],'/'); |
| 107 | if (!str_starts_with($base,'https://')) throw new RuntimeException("Set 'base_url' in data/config.php to this application's production HTTPS URL, or set MICROCHESS_BASE_URL. The data directory is excluded from deployment; update this file on the production server separately."); |
| 108 | return $base; |
| 109 | } |
| 110 | function authRequest(string $path,?array $form=null,?string $token=null): array { |
| 111 | $ch=curl_init('https://auth.timfalken.com'.$path); |
| 112 | $headers=['Accept: application/json','User-Agent: Microchess/1.0']; |
| 113 | if ($token) $headers[]='Authorization: Bearer '.$token; |
| 114 | curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>15,CURLOPT_HTTPHEADER=>$headers]); |
| 115 | if ($form!==null) curl_setopt_array($ch,[CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>http_build_query($form)]); |
| 116 | $body=curl_exec($ch); $status=curl_getinfo($ch,CURLINFO_RESPONSE_CODE); |
| 117 | $data=is_string($body)?json_decode($body,true):null; |
| 118 | if ($status!==200 || !is_array($data)) throw new RuntimeException('Authentication service unavailable or session expired. Please sign in again.'); |
| 119 | return $data; |
| 120 | } |
| 121 | function loginUser(string $id,string $name): void { |
| 122 | query('INSERT INTO users VALUES(?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name',[$id,$name]); |
| 123 | $avatars=avatarCatalog(); |
| 124 | query('INSERT OR IGNORE INTO user_avatars(user_id,avatar) VALUES(?,?)',[$id,$avatars[random_int(0,count($avatars)-1)]['id']]); |
| 125 | session_regenerate_id(true); $_SESSION['user']=$id; $_SESSION['csrf']=bin2hex(random_bytes(24)); |
| 126 | } |
| 127 | // Generate the editable configuration on the first page request, including localhost. |
| 128 | config(); |
| 129 | session_name('microchess_session'); |
| 130 | ini_set('session.use_strict_mode','1'); |
| 131 | session_set_cookie_params(['lifetime'=>0,'path'=>rtrim(dirname($_SERVER['SCRIPT_NAME']),'/').'/', 'secure'=>!localDev(),'httponly'=>true,'samesite'=>'Lax']); |
| 132 | session_set_save_handler(new DatabaseSessions(),true); |
| 133 | session_start(); |
| 134 | if (localDev() && !in_array($_SESSION['user']??'', ['local:test_user_1','local:test_user_2'],true)) { |
| 135 | unset($_SESSION['token'],$_SESSION['expires'],$_SESSION['validated']); |
| 136 | loginUser('local:test_user_1','test_user_1'); |
| 137 | } |
| 138 | function user(): string { |
| 139 | if (!isset($_SESSION['user'])) fail('Please sign in.',401); |
| 140 | if (!localDev() && (($_SESSION['expires']??0)<time())) {unset($_SESSION['user']);fail('Your session expired. Please sign in again.',401);} |
| 141 | return $_SESSION['user']; |
| 142 | } |
| 143 | function fail(string $message,int $status=400): never {http_response_code($status);header('Content-Type: application/json');echo json_encode(['error'=>$message]);exit;} |
| 144 | function jsonOut(mixed $data): never {header('Content-Type: application/json');echo json_encode($data,JSON_THROW_ON_ERROR);exit;} |
| 145 | function pair(string $a,string $b): array { $p=[$a,$b];sort($p,SORT_STRING);return $p; } |
| 146 | function finishGame(array $g,?string $winner,string $reason,array $s): void { |
| 147 | query("UPDATE games SET status='ended',winner=?,reason=?,state=?,draw_offer=NULL,version=version+1 WHERE id=?",[$winner,$reason,json_encode($s),$g['id']]); |
| 148 | query('INSERT INTO results(game_id,a,b,winner,reason,state,ended) VALUES(?,?,?,?,?,?,?)',[$g['id'],$g['a'],$g['b'],$winner,$reason,json_encode($s),time()]); |
| 149 | } |
| 150 | function startGame(string $a,string $b): int { |
| 151 | query("INSERT INTO games(a,b,status,white,state,created) VALUES(?,?,'active',?,?,?)",[$a,$b,random_int(0,1)?$a:$b,json_encode(Chess::initial()),time()]); |
| 152 | return (int)db()->lastInsertId(); |
| 153 | } |
| 154 | function gameView(array $g,string $u): array { |
| 155 | $other=$g['a']===$u?$g['b']:$g['a'];$side=$g['a']===$u?'a':'b';$opSide=$side==='a'?'b':'a'; |
| 156 | $opponent=profile($other); |
| 157 | $s=$g['state']?json_decode($g['state'],true):null; |
| 158 | $color=$g['white']===$u?'w':'b'; |
| 159 | return ['id'=>(int)$g['id'],'opponent'=>$opponent['name'],'opponentAvatar'=>$opponent['avatar'], 'status'=>$g['status'],'incoming'=>$g['b']===$u,'color'=>$color, |
| 160 | 'inactiveDays'=>max(0,(int)floor((time()-($g['activity_at']??time()))/86400)), |
| 161 | 'outcome'=>$g['winner']===null?'draw':($g['winner']===$u?'win':'loss'), |
| 162 | 'state'=>$s,'yourTurn'=>$g['status']==='active' && $s['turn']===$color,'legal'=>$g['status']==='active' && $s['turn']===$color?Chess::legal($s):[], |
| 163 | 'check'=>$s?Chess::check($s):false,'winner'=>$g['winner']?query('SELECT name FROM users WHERE id=?',[$g['winner']])->fetchColumn():null,'reason'=>$g['reason'], |
| 164 | 'canRematch'=>!$g['exit_'.$opSide],'rematch'=>!!$g['rematch_'.$side],'opponentRematch'=>!!$g['rematch_'.$opSide], 'drawOffer'=>$g['draw_offer']?($g['draw_offer']===$u?'you':'opponent'):null, |
| 165 | 'claimable'=>$s?Chess::claimable($s):false,'version'=>(int)$g['version']]; |
| 166 | } |
projects-timfalken-com microchess