BlueGit

projects-timfalken-com microchess

Increase Microchess session TTL to 24 hours with sliding cookies.

Database session rows expire at now+86400 on each write. The browser
microchess_session cookie lifetime is 86400 and is refreshed on every
request so activity slides expiry. README and auth-extend comment updated.

timfa Tim Falken · pushed by timfa

Authored 2026-09-10 · 2 months ago

Hash
27f66dbe46425f4de61cbbf99d2b39990bac3a6d
Parent
e35d061f
3 files changed +17 −3
web/README.md +1 −1
@@ -31,7 +31,7 @@ return [
31 31
32 32 Environment equivalents: `MICROCHESS_BASE_URL`, `MICROCHESS_CLIENT_ID`, `MICROCHESS_CLIENT_SECRET`. Empty or missing config fields fall back to these environment variables; populated fields in the file take precedence. The base URL may include a subdirectory and must not have a trailing slash.
33 33
34 Register your client domain and `/callback.php` (or `/subdirectory/callback.php`) in the [auth service admin](https://auth.timfalken.com/admin). Integration follows the service's [integration guide](https://auth.timfalken.com/help): state validation, server-side code exchange, `/api/me` validation, session renewal and logout. Credentials and bearer tokens never enter client JavaScript. Provider validation occurs at most once per minute during active use; sessions expire after an hour of inactivity. OAuth itself requires the real registered client credentials to test.
34 Register your client domain and `/callback.php` (or `/subdirectory/callback.php`) in the [auth service admin](https://auth.timfalken.com/admin). Integration follows the service's [integration guide](https://auth.timfalken.com/help): state validation, server-side code exchange, `/api/me` validation, session renewal and logout. Credentials and bearer tokens never enter client JavaScript. Provider validation occurs at most once per minute during active use; sessions expire after 24 hours of inactivity (sliding on activity). OAuth itself requires the real registered client credentials to test.
35 35
36 36 Apache: enable `AllowOverride All` for this directory so the included `.htaccess` files deny access to `data/`, `lib/` and `tests/`, and disable directory listings. Nginx does not read `.htaccess`; add equivalent deny rules **before** your PHP location and adjust the prefix if mounted in a subdirectory:
37 37
@@ -31,7 +31,7 @@ return [
31
31
32Environment equivalents: `MICROCHESS_BASE_URL`, `MICROCHESS_CLIENT_ID`, `MICROCHESS_CLIENT_SECRET`. Empty or missing config fields fall back to these environment variables; populated fields in the file take precedence. The base URL may include a subdirectory and must not have a trailing slash.
32Environment equivalents: `MICROCHESS_BASE_URL`, `MICROCHESS_CLIENT_ID`, `MICROCHESS_CLIENT_SECRET`. Empty or missing config fields fall back to these environment variables; populated fields in the file take precedence. The base URL may include a subdirectory and must not have a trailing slash.
33
33
34Register your client domain and `/callback.php` (or `/subdirectory/callback.php`) in the [auth service admin](https://auth.timfalken.com/admin). Integration follows the service's [integration guide](https://auth.timfalken.com/help): state validation, server-side code exchange, `/api/me` validation, session renewal and logout. Credentials and bearer tokens never enter client JavaScript. Provider validation occurs at most once per minute during active use; sessions expire after an hour of inactivity. OAuth itself requires the real registered client credentials to test.
34Register your client domain and `/callback.php` (or `/subdirectory/callback.php`) in the [auth service admin](https://auth.timfalken.com/admin). Integration follows the service's [integration guide](https://auth.timfalken.com/help): state validation, server-side code exchange, `/api/me` validation, session renewal and logout. Credentials and bearer tokens never enter client JavaScript. Provider validation occurs at most once per minute during active use; sessions expire after 24 hours of inactivity (sliding on activity). OAuth itself requires the real registered client credentials to test.
35
35
36Apache: enable `AllowOverride All` for this directory so the included `.htaccess` files deny access to `data/`, `lib/` and `tests/`, and disable directory listings. Nginx does not read `.htaccess`; add equivalent deny rules **before** your PHP location and adjust the prefix if mounted in a subdirectory:
36Apache: enable `AllowOverride All` for this directory so the included `.htaccess` files deny access to `data/`, `lib/` and `tests/`, and disable directory listings. Nginx does not read `.htaccess`; add equivalent deny rules **before** your PHP location and adjust the prefix if mounted in a subdirectory:
37
37
web/api.php +1 −0
@@ -14,6 +14,7 @@ try {
14 14 if (!localDev() && time()-($_SESSION['validated']??0)>60) {
15 15 try {
16 16 authRequest('/api/me',null,$_SESSION['token']);
17 // Extend when <15 min remain; with 24h auth TTL this still only renews near the end.
17 18 if ($_SESSION['expires']-time()<900) { $extended=authRequest('/api/session/extend',[],$_SESSION['token']);$_SESSION['expires']=time()+(int)$extended['expires_in']; }
18 19 $_SESSION['validated']=time();
19 20 } catch (Throwable $e) {unset($_SESSION['user']);fail('Please sign in again.',401);}
@@ -14,6 +14,7 @@ try {
14 if (!localDev() && time()-($_SESSION['validated']??0)>60) {
14 if (!localDev() && time()-($_SESSION['validated']??0)>60) {
15 try {
15 try {
16 authRequest('/api/me',null,$_SESSION['token']);
16 authRequest('/api/me',null,$_SESSION['token']);
17 // Extend when <15 min remain; with 24h auth TTL this still only renews near the end.
17 if ($_SESSION['expires']-time()<900) { $extended=authRequest('/api/session/extend',[],$_SESSION['token']);$_SESSION['expires']=time()+(int)$extended['expires_in']; }
18 if ($_SESSION['expires']-time()<900) { $extended=authRequest('/api/session/extend',[],$_SESSION['token']);$_SESSION['expires']=time()+(int)$extended['expires_in']; }
18 $_SESSION['validated']=time();
19 $_SESSION['validated']=time();
19 } catch (Throwable $e) {unset($_SESSION['user']);fail('Please sign in again.',401);}
20 } catch (Throwable $e) {unset($_SESSION['user']);fail('Please sign in again.',401);}
web/lib/bootstrap.php +15 −2
@@ -98,7 +98,7 @@ final class DatabaseSessions implements SessionHandlerInterface {
98 98 public function open(string $path,string $name): bool {return true;}
99 99 public function close(): bool {return true;}
100 100 public function read(string $id): string|false {return query('SELECT payload FROM sessions WHERE id=? AND expires>?',[$id,time()])->fetchColumn()?:'';}
101 public function write(string $id,string $data): bool {query('INSERT OR REPLACE INTO sessions VALUES(?,?,?)',[$id,$data,time()+3600]);return true;}
101 public function write(string $id,string $data): bool {query('INSERT OR REPLACE INTO sessions VALUES(?,?,?)',[$id,$data,time()+86400]);return true;}
102 102 public function destroy(string $id): bool {query('DELETE FROM sessions WHERE id=?',[$id]);return true;}
103 103 public function gc(int $max_lifetime): int|false {return query('DELETE FROM sessions WHERE expires<?',[time()])->rowCount();}
104 104 }
@@ -156,9 +156,22 @@ function loginUser(string $id,string $name): void {
156 156 config();
157 157 session_name('microchess_session');
158 158 ini_set('session.use_strict_mode','1');
159 session_set_cookie_params(['lifetime'=>0,'path'=>rtrim(dirname($_SERVER['SCRIPT_NAME']),'/').'/', 'secure'=>!localDev(),'httponly'=>true,'samesite'=>'Lax']);
159 $sessionLifetime=86400;
160 $sessionPath=rtrim(dirname($_SERVER['SCRIPT_NAME']),'/').'/';
161 $sessionSecure=!localDev();
162 session_set_cookie_params(['lifetime'=>$sessionLifetime,'path'=>$sessionPath,'secure'=>$sessionSecure,'httponly'=>true,'samesite'=>'Lax']);
160 163 session_set_save_handler(new DatabaseSessions(),true);
161 164 session_start();
165 // Refresh browser cookie expiry on each request so activity slides the 24h lifetime.
166 if (session_status()===PHP_SESSION_ACTIVE && session_id()!=='') {
167 setcookie(session_name(),session_id(),[
168 'expires'=>time()+$sessionLifetime,
169 'path'=>$sessionPath,
170 'secure'=>$sessionSecure,
171 'httponly'=>true,
172 'samesite'=>'Lax',
173 ]);
174 }
162 175 if (localDev() && !in_array($_SESSION['user']??'', ['local:test_user_1','local:test_user_2'],true)) {
163 176 unset($_SESSION['token'],$_SESSION['expires'],$_SESSION['validated']);
164 177 loginUser('local:test_user_1','test_user_1');
@@ -98,7 +98,7 @@ final class DatabaseSessions implements SessionHandlerInterface {
98 public function open(string $path,string $name): bool {return true;}
98 public function open(string $path,string $name): bool {return true;}
99 public function close(): bool {return true;}
99 public function close(): bool {return true;}
100 public function read(string $id): string|false {return query('SELECT payload FROM sessions WHERE id=? AND expires>?',[$id,time()])->fetchColumn()?:'';}
100 public function read(string $id): string|false {return query('SELECT payload FROM sessions WHERE id=? AND expires>?',[$id,time()])->fetchColumn()?:'';}
101 public function write(string $id,string $data): bool {query('INSERT OR REPLACE INTO sessions VALUES(?,?,?)',[$id,$data,time()+3600]);return true;}
101 public function write(string $id,string $data): bool {query('INSERT OR REPLACE INTO sessions VALUES(?,?,?)',[$id,$data,time()+86400]);return true;}
102 public function destroy(string $id): bool {query('DELETE FROM sessions WHERE id=?',[$id]);return true;}
102 public function destroy(string $id): bool {query('DELETE FROM sessions WHERE id=?',[$id]);return true;}
103 public function gc(int $max_lifetime): int|false {return query('DELETE FROM sessions WHERE expires<?',[time()])->rowCount();}
103 public function gc(int $max_lifetime): int|false {return query('DELETE FROM sessions WHERE expires<?',[time()])->rowCount();}
104}
104}
@@ -156,9 +156,22 @@ function loginUser(string $id,string $name): void {
156config();
156config();
157session_name('microchess_session');
157session_name('microchess_session');
158ini_set('session.use_strict_mode','1');
158ini_set('session.use_strict_mode','1');
159session_set_cookie_params(['lifetime'=>0,'path'=>rtrim(dirname($_SERVER['SCRIPT_NAME']),'/').'/', 'secure'=>!localDev(),'httponly'=>true,'samesite'=>'Lax']);
159$sessionLifetime=86400;
160$sessionPath=rtrim(dirname($_SERVER['SCRIPT_NAME']),'/').'/';
161$sessionSecure=!localDev();
162session_set_cookie_params(['lifetime'=>$sessionLifetime,'path'=>$sessionPath,'secure'=>$sessionSecure,'httponly'=>true,'samesite'=>'Lax']);
160session_set_save_handler(new DatabaseSessions(),true);
163session_set_save_handler(new DatabaseSessions(),true);
161session_start();
164session_start();
165// Refresh browser cookie expiry on each request so activity slides the 24h lifetime.
166if (session_status()===PHP_SESSION_ACTIVE && session_id()!=='') {
167 setcookie(session_name(),session_id(),[
168 'expires'=>time()+$sessionLifetime,
169 'path'=>$sessionPath,
170 'secure'=>$sessionSecure,
171 'httponly'=>true,
172 'samesite'=>'Lax',
173 ]);
174}
162if (localDev() && !in_array($_SESSION['user']??'', ['local:test_user_1','local:test_user_2'],true)) {
175if (localDev() && !in_array($_SESSION['user']??'', ['local:test_user_1','local:test_user_2'],true)) {
163 unset($_SESSION['token'],$_SESSION['expires'],$_SESSION['validated']);
176 unset($_SESSION['token'],$_SESSION['expires'],$_SESSION['validated']);
164 loginUser('local:test_user_1','test_user_1');
177 loginUser('local:test_user_1','test_user_1');