feat(session): WIP - Implement persistent cookies

This commit is contained in:
eapl.mx 2024-12-23 19:50:24 -06:00
parent d3079b0be4
commit 5e4402c230
No known key found for this signature in database
13 changed files with 307 additions and 262 deletions

View file

@ -1 +1 @@
2024.12.06
2024.12.23

View file

@ -10,9 +10,9 @@ if ($config['debug_mode']) {
require_once('session.php');
if (!isset($_SESSION['valid_session'])) {
if (!isset($_SESSION['valid_session'])) {
$secretKey = $config['totp_secret'];
$cookieVal = decodeCookie($secretKey);
$cookieVal = isSavedCookieValid($secretKey);
if ($cookieVal === false) { # Valid cookie ?
header('Location: login.php');
@ -56,27 +56,30 @@ if (isset($_POST['submit'])) {
exit;
}
} else { ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>twtxt</title>
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1><a href=".">twtxt</a></h1>
<form method="POST" class="column">
<div id="login">
<?php if ($invalidURL) { ?>
<div class="alert">URL is invalid, check it!</div><br>
<?php } ?>
<label for="fname">URL to twtxt.txt file</label>
<br>
<input type="text" id="url" name="url" class="input" autocomplete="off"><br>
<input type="submit" value="Add URL" class="btn">
</div>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>twtxt</title>
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1><a href=".">twtxt</a></h1>
<form method="POST" class="column">
<div id="login">
<?php if ($invalidURL) { ?>
<div class="alert">URL is invalid, check it!</div><br>
<?php } ?>
<label for="fname">URL to twtxt.txt file</label>
<br>
<input type="text" id="url" name="url" class="input" autocomplete="off"><br>
<input type="submit" value="Add URL" class="btn">
</div>
</form>
</body>
</html>
<?php } ?>

View file

@ -1,101 +0,0 @@
<?php
$config = parse_ini_file('private/config.ini');
const COOKIE_NAME = 'remember_user';
const ENCRYPTION_METHOD = 'aes-256-cbc';
session_start([
'name' => 'twtxt_session',
'use_strict_mode' => true,
'cookie_httponly' => true,
'cookie_secure' => $config['secure_cookies'],
'sid_length' => 64,
'sid_bits_per_character' => 6,
'cookie_samesite' => 'Strict', // Not compatible with PHP lower than 7.3
]);
function has_valid_session() {
$config = parse_ini_file('private/config.ini');
$secretKey = $config['password'];
if (isset($_SESSION['valid_session'])) {
return true;
}
$cookieVal = decodeCookie($secretKey);
if ($cookieVal === false) {
#echo "Invalid cookie";
return false;
}
return true;
}
function encrypt(string $data, string $key, string $method): string {
$ivSize = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($ivSize);
$encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
# PHP 8.2 - Deprecated: implode():
# Passing null to parameter #1 ($separator) of type array|string is deprecated
//$encrypted = strtoupper(implode(null, unpack('H*', $encrypted)));
$encrypted = strtoupper(implode(unpack('H*', $encrypted)));
return $encrypted;
}
function decrypt(string $data, string $key, string $method): string {
$data = pack('H*', $data);
$ivSize = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($ivSize);
$decrypted = openssl_decrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
return trim($decrypted);
}
function saveLoginSuccess($secretKey) {
// Set a cookie to remember the user
$_SESSION['valid_session'] = true;
// Set a cookie value to remember the user
$encoded_cookie_value = generateCookieValue('admin', $secretKey);
$cookie_expiry = time() + (30 * 24 * 60 * 60); // 30 days
$config = parse_ini_file('private/config.ini');
setcookie(COOKIE_NAME, $encoded_cookie_value, [
'expires' => $cookie_expiry,
'secure' => $config['secure_cookies'],
'httponly' => true,
'samesite' => 'Strict',
]);
}
function generateCookieValue($username, $secretKey) {
$key = bin2hex($secretKey);
$encrypted = encrypt($username, $key, ENCRYPTION_METHOD);
return $encrypted;
}
function decodeCookie($secretKey) {
// Retrieve the encoded cookie name
if (!isset($_COOKIE[COOKIE_NAME])) {
return false;
}
$encoded_cookie_value = $_COOKIE[COOKIE_NAME];
$key = bin2hex($secretKey);
$config = parse_ini_file('private/config.ini');
// Extend expiry by 30 days
$cookie_expiry = time() + (30 * 24 * 60 * 60);
setcookie(COOKIE_NAME, $encoded_cookie_value, [
'expires' => $cookie_expiry,
'secure' => $config['secure_cookies'],
'httponly' => true,
'samesite' => 'Strict',
]);
$decrypted = decrypt($encoded_cookie_value, $key, ENCRYPTION_METHOD);
return $decrypted;
}

View file

@ -1,4 +1,4 @@
<?php
<?php
function getBaseURI() // https://github.com/taniarascia/comments/issues/26#issuecomment-1458121921
{
@ -30,26 +30,28 @@ $routes = [
'/new' => 'new_twt.php',
'/add' => 'add_feed.php',
'/following' => 'following.php',
//'/refresh' => 'load_twt_files.php',
'/refresh' => 'refresh.php',
'/login' => 'login.php',
'/logout' => 'logout.php',
'/profile' => 'profile.php',
'/replies' => 'replies.php',
'/gallery' => 'gallery.php',
//'/profile/([a-zA-Z0-9_-]+)' => 'profile.php',
'/conv/([a-zA-Z0-9]{7})' => 'conv.php', // matches only twtHash of exactly 7 alphanumeric characters
'/post/([a-zA-Z0-9]{7})' => 'post.php', // matches only twtHash of exactly 7 alphanumeric characters
//'/thumb' => 'thumb.php',
'/conv/([a-zA-Z0-9]{7})' => 'conv.php', // matches only twtHash of exactly 7 alphanumeric characters
'/post/([a-zA-Z0-9]{7})' => 'post.php', // matches only twtHash of exactly 7 alphanumeric characters
'/upload' => 'upload_img.php',
'/webmention' => 'webmention_endpoint.php',
//'/thumb' => 'thumb.php',
//'/profile/([a-zA-Z0-9_-]+)' => 'profile.php',
# Debug endpoints
'/test_login' => 'test_login.php',
];
// Loop through the defined routes and try to match the request URI
foreach ($routes as $pattern => $action) {
if (preg_match('#^' . $pattern . '$#', $path, $matches)) {
// Extract any matched parameters (e.g., username)
// Extract any matched parameters (e.g., username)
if(!empty($matches[1])) {
//array_shift($matches);
$id = $matches[1];

115
libs/persistent_session.php Normal file
View file

@ -0,0 +1,115 @@
<?php
$config = parse_ini_file('private/config.ini');
# TODO: Move this verification to another file
$required_keys = ['secret_key', 'password', 'totp_secret', 'totp_digits', 'secure_cookies'];
$missing_keys = array_filter($required_keys, fn($key) => !isset($config[$key]));
if (!empty($missing_keys)) {
die('Missing required keys in config.ini: ' . implode(', ', $missing_keys));
}
# To make it more secure, something like JWT could be used instead
const COOKIE_NAME = 'timeline_login';
const ENCRYPTION_METHOD = 'aes-256-cbc';
const EXPIRATION_DAYS = 30;
session_start([
'name' => 'timeline_session',
'use_strict_mode' => true,
'cookie_httponly' => true,
'cookie_secure' => $config['secure_cookies'],
'sid_length' => 64,
'sid_bits_per_character' => 6,
'cookie_samesite' => 'Strict', # Not compatible with PHP < 7.3
]);
function hasValidSession(): bool|string {
# If short lived session is valid
if (isset($_SESSION['valid_session'])) {
return true;
}
# Otherwise, check the persistent cookie
return isSavedCookieValid();
}
function encrypt(string $data, string $key, string $method): string {
$ivSize = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($ivSize);
$encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
$encrypted = strtoupper(implode(unpack('H*', $encrypted)));
return $encrypted;
}
function decrypt(string $data, string $key, string $method): string | bool {
$data = pack('H*', $data);
$ivSize = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($ivSize);
$decrypted = openssl_decrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
var_dump($decrypted);
if ($decrypted === false) {
return false;
}
return trim($decrypted);
}
function saveLoginSuccess() {
$_SESSION['valid_session'] = true;
$config = parse_ini_file('private/config.ini');
# Set a cookie to remember the user
$cookieExpiry = EXPIRATION_DAYS * 24 * 60 * 60 + time();
$encodedCookieValue = generateCookieValue(strval($cookieExpiry), $config['secret_key']);
setcookie(COOKIE_NAME, $encodedCookieValue, [
'expires' => $cookieExpiry,
'secure' => $config['secure_cookies'],
'httponly' => true,
'samesite' => 'Strict',
]);
}
function generateCookieValue($value, $secretKey) {
$key = bin2hex($secretKey);
$encrypted = encrypt($value, $key, ENCRYPTION_METHOD);
return $encrypted;
}
function isSavedCookieValid() {
if (!isset($_COOKIE[COOKIE_NAME])) {
return false;
}
$config = parse_ini_file('private/config.ini');
$encoded_cookie_value = $_COOKIE[COOKIE_NAME];
$key = bin2hex($config['secret_key']);
$cookieVal = decrypt($encoded_cookie_value, $key, ENCRYPTION_METHOD);
if ($cookieVal === false) {
deletePersistentCookie();
return false;
}
# TODO: Check that the cookie is not expired
saveLoginSuccess(); # Extend expiracy for previous cookie
return true; # If it was decoded correctly, it's a valid session
}
function deletePersistentCookie() {
if (isset($_COOKIE[COOKIE_NAME])) {
unset($_COOKIE[COOKIE_NAME]);
setcookie(COOKIE_NAME, '', time() - 3600);
}
}

View file

@ -1,30 +1,33 @@
<?php
require_once('libs/TOTP.php');
require_once 'libs/TOTP.php';
require_once 'libs/persistent_session.php';
$config = parse_ini_file('private/config.ini');
$password = $config['password'];
$passwordInConfig = $config['password'];
session_start();
# TODO: Replace using $_SESSION['password'] in other files
# to check for a valid session, as in 'new_twt.php'
# Use hasValidSession() instead
if (isset($_POST['submit_pass']) && $_POST['pass'])
{
$pass = $_POST['pass'];
if (isset($_POST['submit_pass']) && $_POST['pass']) {
$passwordInForm = $_POST['pass'];
// @eapl.me 2023-11-23 - I'm trying to add support to passwords
// and TOTP (passwordless). So, in the Pwd field you can enter
// the password, or the current TOTP
if ($pass == $password)
{
$_SESSION['password'] = $pass;
}
elseif ($isCodeValid = verifyTOTP(
$config['totp_secret'], $pass, intval($config['totp_digits']))
)
{
// If TOTP is valid, assume that we entered the Password
$_SESSION['password'] = $password;
}
else
{
$error = "Incorrect Password";
if ($passwordInForm == $passwordInConfig) {
$_SESSION['password'] = $passwordInForm;
saveLoginSuccess();
} elseif ($isCodeValid = verifyTOTP(
$config['totp_secret'],
$passwordInForm,
intval($config['totp_digits'])
)) {
$_SESSION['password'] = 'valid_totp';
saveLoginSuccess();
} else {
$error = 'Incorrect Password';
}
}
# Check for an empty password
if (isset($_POST['submit_pass']) && !$_POST['pass']) {
$error = 'Type a password';
}

View file

@ -1,43 +1,43 @@
<!-- List UI -->
<form action="" method="get">
<!-- Select a list: -->
<select name="list" onchange="this.form.submit()">
<select name="list" onchange="this.form.submit()">
<option value="twtxt.txt" selected>twtxt.txt (Main)</option>
<?php
// TODO: fix it so if List -> Selected for both public and private lists
if( isset($_SESSION['password'])) {
if($_SESSION['password']=="$password") { // Hacky login
// TODO: fix it so if List -> Selected for both public and private lists
if (isset($_SESSION['password'])) {
if ($_SESSION['password'] == "$passwordInConfig") { // Hacky login
// Private lists
echo "<option disabled>Private Lists:</option>";
foreach (glob("private/twtxt-*.txt") as $filename) {
if($filename == $_GET['lists']) $attr="selected";
else $attr = "";
$listName = $filename;
$listName = str_replace("private/twtxt-", "", $listName);
$listName = str_replace("_", " ", $listName);
$listName = str_replace(".txt", "", $listName);
echo "<option value='{$filename}' {$attr}>$listName</option>";
if ($filename == $_GET['lists']) $attr = "selected";
else $attr = "";
$listName = $filename;
$listName = str_replace("private/twtxt-", "", $listName);
$listName = str_replace("_", " ", $listName);
$listName = str_replace(".txt", "", $listName);
echo "<option value='{$filename}' {$attr}>$listName</option>";
}
// Public Lists
echo "<option disabled>Public Lists:</option>";
}
}
}
foreach (glob("twtxt-*.txt") as $filename) {
if($filename == $_GET['lists']) $attr="selected";
else $attr = "";
$listName = $filename;
$listName = str_replace("twtxt-", "", $listName);
$listName = str_replace("_", " ", $listName);
$listName = str_replace(".txt", "", $listName);
echo "<option value='{$filename}' {$attr}>$listName</option>";
}
foreach (glob("twtxt-*.txt") as $filename) {
if ($filename == $_GET['lists']) $attr = "selected";
else $attr = "";
$listName = $filename;
$listName = str_replace("twtxt-", "", $listName);
$listName = str_replace("_", " ", $listName);
$listName = str_replace(".txt", "", $listName);
echo "<option value='{$filename}' {$attr}>$listName</option>";
}
?>
</select>
<noscript><button type="submit">View list</button></noscript>
</select>
<noscript><button type="submit">View list</button></noscript>
</form>

View file

@ -1,43 +1,43 @@
<!-- List UI -->
<form action="" method="get">
<!-- Select a list: -->
<select name="list" onchange="this.form.submit()">
<select name="list" onchange="this.form.submit()">
<option value="twtxt.txt" selected>twtxt.txt (Main)</option>
<?php
// TODO: fix it so if List -> Selected for both public and private lists
if( isset($_SESSION['password'])) {
if($_SESSION['password']=="$password") { // Hacky login
// TODO: fix it so if List -> Selected for both public and private lists
if (isset($_SESSION['password'])) {
if ($_SESSION['password'] == "$passwordInConfig") { // Hacky login
// Private lists
echo "<option disabled>Private Lists:</option>";
foreach (glob("private/twtxt-*.txt") as $filename) {
if($filename == $_GET['list']) $attr="selected";
else $attr = "";
$listName = $filename;
$listName = str_replace("private/twtxt-", "", $listName);
$listName = str_replace("_", " ", $listName);
$listName = str_replace(".txt", "", $listName);
echo "<option value='{$filename}' {$attr}>$listName</option>";
if ($filename == $_GET['list']) $attr = "selected";
else $attr = "";
$listName = $filename;
$listName = str_replace("private/twtxt-", "", $listName);
$listName = str_replace("_", " ", $listName);
$listName = str_replace(".txt", "", $listName);
echo "<option value='{$filename}' {$attr}>$listName</option>";
}
// Public Lists
echo "<option disabled>Public Lists:</option>";
}
}
}
foreach (glob("twtxt-*.txt") as $filename) {
if($filename == $_GET['list']) $attr="selected";
else $attr = "";
$listName = $filename;
$listName = str_replace("twtxt-", "", $listName);
$listName = str_replace("_", " ", $listName);
$listName = str_replace(".txt", "", $listName);
//$filename = "TODO".$baseURL."/".$filename;
echo "<option value='{$filename}' {$attr}>$listName</option>";
}
foreach (glob("twtxt-*.txt") as $filename) {
if ($filename == $_GET['list']) $attr = "selected";
else $attr = "";
$listName = $filename;
$listName = str_replace("twtxt-", "", $listName);
$listName = str_replace("_", " ", $listName);
$listName = str_replace(".txt", "", $listName);
//$filename = "TODO".$baseURL."/".$filename;
echo "<option value='{$filename}' {$attr}>$listName</option>";
}
?>
</select>
<noscript><button type="submit">View list</button></noscript>
</select>
<noscript><button type="submit">View list</button></noscript>
</form>

View file

@ -42,13 +42,18 @@ webmentions_txt_path = "./mentions.txt"
public_webmentions = "https://example.com/timeline/mentions.txt"
[security]
; Generate it with the TOTP module
; Secret key to encrypt cookies
; Create a new one here: https://randomkeygen.com
secret_key = "553GkZzIYZKx5z0lftt4yKDG4aKb4sAG"
; Simple password
password = "change_me"
; A dynamic password (TOTP) changing every 30 seconds
; Use a TOTP client with support for 10 digits like Aegis (Android)
totp_digits = 10
totp_secret = "1234567890"
; It's recommended that your site is hosted on HTTPS
; In case it's in HTTP (not secure), set this to false
secure_cookies = true
; Simple password for unnamed user
password = ""

View file

@ -1,7 +1,7 @@
<?php
require_once("partials/base.php");
$title = "Following - ".$title;
$title = "Following - " . $title;
include 'partials/header.php';
@ -18,46 +18,48 @@ include 'partials/header.php';
<!-- <th></th> -->
<th>Nick</th>
<th>URL</th>
<?php if(isset($_SESSION['password']) && $_SESSION['password']=="$password") { ?>
<?php if (isset($_SESSION['password']) && $_SESSION['password'] == "$passwordInConfig") { ?>
<th>Time ago</th>
<?php } ?>
</tr>
<?php foreach ($twtFollowingList as $currentFollower) { ?>
<tr>
<!-- <td></td> -->
<td><a href="<?= $baseURL ?>/profile?url=<?= $currentFollower[1] ?>"><?= $currentFollower[0] ?></a></td>
<!-- <td><a href="/?twt=<?= $currentFollower[1] ?>"><?= $currentFollower[0] ?></a></td> -->
<td><?= $currentFollower[1] ?>
<!-- <?php //if ($validSession) { ?> -->
<!-- <a href="?remove_url=<?= $currentFollower[1] ?>">Remove</a> -->
<!-- <?php // } ?> -->
</td>
<?php if(isset($_SESSION['password']) && $_SESSION['password']=="$password") { ?>
<td>
<?php
// Test first if URL is a valid feed:
if (is_array(getTwtsFromTwtxtString($currentFollower[1])->twts)) {
<tr>
<!-- <td></td> -->
<td><a href="<?= $baseURL ?>/profile?url=<?= $currentFollower[1] ?>"><?= $currentFollower[0] ?></a></td>
<!-- <td><a href="/?twt=<?= $currentFollower[1] ?>"><?= $currentFollower[0] ?></a></td> -->
<td><?= $currentFollower[1] ?>
<!-- <?php //if ($validSession) {
?> -->
<!-- <a href="?remove_url=<?= $currentFollower[1] ?>">Remove</a> -->
<!-- <?php // }
?> -->
</td>
<?php if (isset($_SESSION['password']) && $_SESSION['password'] == "$passwordInConfig") { ?>
<td>
<?php
// Test first if URL is a valid feed:
if (is_array(getTwtsFromTwtxtString($currentFollower[1])->twts)) {
// Then test if latest twt is at start or end of file:
$resetVar = reset(getTwtsFromTwtxtString($currentFollower[1])->twts);
$endVar = end(getTwtsFromTwtxtString($currentFollower[1])->twts);
if ($resetVar->timestamp < $endVar->timestamp) { // TODO: this can be swapped to get time of first twt
echo $endVar->displayDate;
} else {
echo $resetVar->displayDate;
// Then test if latest twt is at start or end of file:
$resetVar = reset(getTwtsFromTwtxtString($currentFollower[1])->twts);
$endVar = end(getTwtsFromTwtxtString($currentFollower[1])->twts);
if ($resetVar->timestamp < $endVar->timestamp) { // TODO: this can be swapped to get time of first twt
echo $endVar->displayDate;
} else {
echo $resetVar->displayDate;
}
}
}
?>
?>
</td>
<?php } ?>
</td>
<?php } ?>
</tr>
</tr>
<?php } ?>
</table>
</center>
<!-- FOOTER --><?php include 'partials/footer.php';?>
<!-- FOOTER --><?php include 'partials/footer.php'; ?>

View file

@ -1,28 +1,30 @@
<?php
require_once("partials/base.php");
require_once "partials/base.php";
$title = "Login - ".$title;
$title = "Login - $title";
// Password comes from libs/session.php
if (isset($_SESSION['password'])) {
if ($_SESSION['password'] == $password) {
header("Location: .");
include 'partials/header.php';
die();
}
// $password comes from libs/session.php
if (isset($_SESSION['password'])) {
if ($_SESSION['password'] == $passwordInConfig) {
header("Location: .");
die();
}
else {
include 'partials/header.php';
} else {
include 'partials/header.php';
?>
<center>
<h2>Enter password or TOTP</h2>
<form method="post" action="" id="login_form">
<input type="password" name="pass" placeholder="Password" autofocus><br>
<input type="submit" name="submit_pass" value="Login">
<p><font style="color:red;"><?php if(isset($error)) {echo $error;}?></font></p>
</form>
</center>
<!-- TODO: Replace center and font tags with CSS -->
<center>
<h2>Enter password or TOTP</h2>
<form method="post" action="" id="login_form">
<input type="password" name="pass" placeholder="Password" autofocus><br>
<input type="submit" name="submit_pass" value="Login">
<p><font style="color:red;">
<?php if (isset($error)) {
echo $error;
} ?>
</font></p>
</form>
</center>
<?php } ?>
<!-- PHP: GET FOOTER --><?php include 'partials/footer.php';?>
<!-- PHP: GET FOOTER --><?php include 'partials/footer.php'; ?>

View file

@ -1,6 +1,7 @@
<?php
require_once "libs/persistent_session.php";
session_start();
deletePersistentCookie();
session_unset();
session_destroy();

13
views/test_login.php Normal file
View file

@ -0,0 +1,13 @@
<?php
# A simple text to check if sessions are working OK
# Remove it from index.php to hide it from the public
require_once "libs/persistent_session.php";
if (!hasValidSession()) {
#header("Location: /login");
exit;
}
var_dump($_SESSION);
echo "Valid session";