Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Remember-me cookie Secure, SameSite=Lax and 30 days; password change ends other sign-ins (#437)
Murtaza Nasir143bfb732da0
diff --git a/config/env.asr.example b/config/env.asr.exampleindex 394acd4b..da01bec5 100644--- a/config/env.asr.example+++ b/config/env.asr.example@@ -152,6 +152,10 @@ CHAT_MAX_TOKENS=5000# HTTPS deployment. Default: false so plain-HTTP LAN setups keep working.# SESSION_COOKIE_SECURE=false+# Days a "Remember me" or SSO sign-in lasts without a visit; each visit starts+# the period again. Default: 30.+# REMEMBER_COOKIE_DAYS=30+# --- Security headers ---# The app sets X-Frame-Options, X-Content-Type-Options, Referrer-Policy,# Permissions-Policy, a Content-Security-Policy, and (over HTTPS) HSTS, so adiff --git a/config/env.transcription.example b/config/env.transcription.exampleindex 451a301e..80c37c2a 100644--- a/config/env.transcription.example+++ b/config/env.transcription.example@@ -366,6 +366,10 @@ REGISTRATION_ALLOWED_DOMAINS=# HTTPS deployment. Default: false so plain-HTTP LAN setups keep working.# SESSION_COOKIE_SECURE=false+# Days a "Remember me" or SSO sign-in lasts without a visit; each visit starts+# the period again. Default: 30.+# REMEMBER_COOKIE_DAYS=30+# --- Security headers ---# The app sets X-Frame-Options, X-Content-Type-Options, Referrer-Policy,# Permissions-Policy, a Content-Security-Policy, and (over HTTPS) HSTS, so adiff --git a/config/env.whisper.example b/config/env.whisper.exampleindex 20f4fcab..dde2cbdf 100644--- a/config/env.whisper.example+++ b/config/env.whisper.example@@ -135,6 +135,10 @@ CHAT_MAX_TOKENS=5000# HTTPS deployment. Default: false so plain-HTTP LAN setups keep working.# SESSION_COOKIE_SECURE=false+# Days a "Remember me" or SSO sign-in lasts without a visit; each visit starts+# the period again. Default: 30.+# REMEMBER_COOKIE_DAYS=30+# --- Security headers ---# The app sets X-Frame-Options, X-Content-Type-Options, Referrer-Policy,# Permissions-Policy, a Content-Security-Policy, and (over HTTPS) HSTS, so adiff --git a/docs/admin-guide/system-settings.md b/docs/admin-guide/system-settings.mdindex b27d80ac..6b7b29ca 100644--- a/docs/admin-guide/system-settings.md+++ b/docs/admin-guide/system-settings.md@@ -188,6 +188,10 @@ If the process that owns the background work is recycled or killed, the replacem**SESSION_COOKIE_SECURE**: When `true`, the session cookie is sent only over HTTPS. Set this to `true` for any production deployment behind TLS (Nginx Proxy Manager, Caddy, Traefik with a real certificate). Default: `false`, so http://localhost and bare-LAN deployments keep working out of the box. If you turn this on and reach the instance over plain HTTP, the browser will silently drop the cookie and you'll be unable to log in.+**REMEMBER_COOKIE_DAYS**: How long a sign-in with "Remember me" (and every SSO sign-in) lasts without a visit, in days. Each visit starts the period again, so a person who uses Speakr regularly stays signed in. The cookie follows `SESSION_COOKIE_SECURE` and is `SameSite=Lax`. Default: `30`.++When a password is changed, reset by email, or set by an administrator, the account is signed out of every browser. The browser in which the password was changed stays signed in. Sign-ins made before v0.10.15 remain valid until the account's password is next set.+### Public Share Page Rendering**READABLE_PUBLIC_LINKS**: When `true`, transcripts on public share pages are server-side rendered in HTML, making them accessible to LLMs, scrapers, and accessibility tools. When `false`, transcripts are rendered client-side via JavaScript. Default: `false`.diff --git a/src/api/admin.py b/src/api/admin.pyindex f8b743cd..440843cd 100644--- a/src/api/admin.py+++ b/src/api/admin.py@@ -9,7 +9,7 @@ import jsonimport timefrom datetime import datetime, timedeltafrom flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, Response, current_app-from flask_login import login_required, current_user+from flask_login import login_required, current_user, login_userfrom werkzeug.utils import secure_filenamefrom src.database import db@@ -288,6 +288,8 @@ def admin_update_user(user_id):if 'password' in data and data['password']:user.password = bcrypt.generate_password_hash(data['password']).decode('utf-8')+ # Sign the account out of every browser (#437)+ user.end_all_sessions()if 'is_admin' in data:new_is_admin = bool(data['is_admin'])@@ -325,6 +327,10 @@ def admin_update_user(user_id):return jsonify({'error': 'The storage quota must be a positive number of MB.'}), 400db.session.commit()+ if user.id == current_user.id and data.get('password'):+ # An administrator who sets their own password stays signed in here+ remembered = current_app.config.get('REMEMBER_COOKIE_NAME', 'remember_token') in request.cookies+ login_user(user, remember=remembered)# Get recordings count and storage usedrecordings_count = len(user.recordings)diff --git a/src/api/auth.py b/src/api/auth.pyindex e0f7ac71..c4c3dfd8 100644--- a/src/api/auth.py+++ b/src/api/auth.py@@ -601,6 +601,8 @@ def reset_password(token):user.password = hashed_passworduser.password_reset_token = None # Clear the tokenuser.password_reset_sent_at = None+ # Sign the account out of every browser (#437)+ user.end_all_sessions()# Also verify email if not already verifiedif not user.email_verified:@@ -1066,7 +1068,12 @@ def change_password():# not leave an emailed reset token able to overwrite the new password.current_user.password_reset_token = Nonecurrent_user.password_reset_sent_at = None+ # Sign the account out of every other browser (#437), and sign this one+ # in again with the new login id.+ remembered = current_app.config.get('REMEMBER_COOKIE_NAME', 'remember_token') in request.cookies+ current_user.end_all_sessions()db.session.commit()+ login_user(current_user, remember=remembered)flash('Your password has been updated!', 'success')return redirect(url_for('auth.account'))diff --git a/src/app.py b/src/app.pyindex 5162f4a6..a200338b 100644--- a/src/app.py+++ b/src/app.py@@ -432,6 +432,21 @@ app.config['SESSION_COOKIE_SECURE'] = (app.config['SESSION_COOKIE_HTTPONLY'] = True # Still protect against XSSapp.config['SESSION_COOKIE_SAMESITE'] = 'Lax' # CSRF protection+# Remember-me cookie (#437). Flask-Login's defaults are a 365-day cookie with+# no Secure flag and no SameSite attribute. It now follows the session+# cookie's Secure setting, is SameSite=Lax, and lasts REMEMBER_COOKIE_DAYS+# (default 30) from the last visit, so a person who keeps using Speakr stays+# signed in.+app.config['REMEMBER_COOKIE_SECURE'] = app.config['SESSION_COOKIE_SECURE']+app.config['REMEMBER_COOKIE_HTTPONLY'] = True+app.config['REMEMBER_COOKIE_SAMESITE'] = 'Lax'+try:+ _remember_days = max(1, int(os.environ.get('REMEMBER_COOKIE_DAYS', '30')))+except ValueError:+ _remember_days = 30+app.config['REMEMBER_COOKIE_DURATION'] = timedelta(days=_remember_days)+app.config['REMEMBER_COOKIE_REFRESH_EACH_REQUEST'] = True+# --- Security response headers ---# Set at the app level so a deployment WITHOUT a hardening reverse proxy is# still protected (previously the app set only X-Robots-Tag, leaving direct /@@ -844,7 +859,18 @@ os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)# --- User loader for Flask-Login ---@login_manager.user_loaderdef load_user(user_id):- return db.session.get(User, int(user_id))+ # "<id>" or "<id>:<session_version>" (see User.get_id). A sign-in made+ # before the password was last set carries an older version and is+ # refused (#437).+ uid, _, version = str(user_id).partition(':')+ try:+ user = db.session.get(User, int(uid))+ version = int(version or 0)+ except ValueError:+ return None+ if user is None or (user.session_version or 0) != version:+ return None+ return user@login_manager.request_loaderdiff --git a/src/init_db.py b/src/init_db.pyindex 2b3a5f33..186f24d5 100644--- a/src/init_db.py+++ b/src/init_db.py@@ -404,6 +404,10 @@ def _run_migrations(app, engine):if add_column_if_not_exists(engine, 'user', 'theme_color_scheme', 'VARCHAR(16)'):app.logger.info("Added theme_color_scheme column to user table")+ # Raised when the password is set, to end the account's sign-ins (#437)+ if add_column_if_not_exists(engine, 'user', 'session_version', 'INTEGER'):+ app.logger.info("Added session_version column to user table")+# Storage quota in megabytes (#413)if add_column_if_not_exists(engine, 'user', 'storage_quota_mb', 'INTEGER'):app.logger.info("Added storage_quota_mb column to user table")diff --git a/src/models/user.py b/src/models/user.pyindex 4ca38de1..19772c8b 100644--- a/src/models/user.py+++ b/src/models/user.py@@ -118,6 +118,20 @@ class User(db.Model, UserMixin):# 'top' renders it above the columns so it sits closer to the# title bar. User-configurable from the Display tab in settings.audio_player_position = db.Column(db.String(10), default='bottom')+ # Raised when the password is set (#437), which signs the account out of+ # every browser: the login id that Flask-Login keeps in the session and+ # the remember-me cookie carries it, and an id with an older value is+ # refused. Null and 0 keep the plain id, so sign-ins made before the+ # column existed stay valid until the password is next set.+ session_version = db.Column(db.Integer, nullable=True, default=0)++ def get_id(self):+ version = self.session_version or 0+ return f"{self.id}:{version}" if version else str(self.id)++ def end_all_sessions(self):+ """Sign the account out of every browser (see session_version)."""+ self.session_version = (self.session_version or 0) + 1def __repr__(self):return f"User('{self.username}', '{self.email}')"diff --git a/tests/test_sign_in_revocation.py b/tests/test_sign_in_revocation.pynew file mode 100644index 00000000..cd7602fb--- /dev/null+++ b/tests/test_sign_in_revocation.py@@ -0,0 +1,110 @@+"""Remember-me cookie and sign-ins after a password change (#437).++The remember-me cookie had Flask-Login's defaults (365 days, no Secure flag,+no SameSite), and neither it nor the session was ended when the password+changed. A password change, a reset by email or a password set by an+administrator now signs the account out of every other browser. Sign-ins made+before the change keep working until the password is next set.+"""++import uuid+from datetime import timedelta++import pytest++from src.app import app, bcrypt, db, load_user+from src.models import User++app.config["WTF_CSRF_ENABLED"] = False++OLD = "Old-passw0rd!x"+NEW = "New-passw0rd!y"+++def user_id():+ with app.app_context():+ suffix = uuid.uuid4().hex[:8]+ u = User(username=f"rev_{suffix}", email=f"rev_{suffix}@local.test",+ password=bcrypt.generate_password_hash(OLD).decode("utf-8"))+ db.session.add(u)+ db.session.commit()+ uid = u.id+ yield uid+ with app.app_context():+ u = db.session.get(User, uid)+ if u:+ db.session.delete(u)+ db.session.commit()+++def _client(login_id):+ client = app.test_client()+ with client.session_transaction() as sess:+ sess["_user_id"] = login_id+ sess["_fresh"] = True+ return client+++def _signed_in(client):+ return client.get("/account").status_code == 200+++def test_cookie_settings():+ assert app.config["REMEMBER_COOKIE_SAMESITE"] == "Lax"+ assert app.config["REMEMBER_COOKIE_HTTPONLY"] is True+ assert app.config["REMEMBER_COOKIE_SECURE"] == app.config["SESSION_COOKIE_SECURE"]+ assert app.config["REMEMBER_COOKIE_DURATION"] == timedelta(days=30)+ assert app.config["REMEMBER_COOKIE_REFRESH_EACH_REQUEST"] is True+++def test_existing_plain_id_sign_in_stays_valid(user_id):+ with app.app_context():+ assert db.session.get(User, user_id).get_id() == str(user_id)+ assert load_user(str(user_id)).id == user_id+ assert _signed_in(_client(str(user_id)))+++def test_password_change_signs_out_other_browsers(user_id):+ this, other = _client(str(user_id)), _client(str(user_id))+ resp = this.post("/change_password", data={+ "current_password": OLD, "new_password": NEW, "confirm_password": NEW})+ assert resp.status_code == 302+ with app.app_context():+ assert db.session.get(User, user_id).session_version == 1+ assert _signed_in(this)+ assert not _signed_in(other)+++def test_admin_setting_the_password_signs_the_user_out(user_id):+ with app.app_context():+ suffix = uuid.uuid4().hex[:8]+ admin = User(username=f"reva_{suffix}", email=f"reva_{suffix}@local.test",+ password="x", is_admin=True)+ db.session.add(admin)+ db.session.commit()+ admin_id = admin.id+ victim = _client(str(user_id))+ resp = _client(str(admin_id)).put(f"/admin/users/{user_id}", json={"password": NEW})+ assert resp.status_code == 200, resp.data+ assert not _signed_in(victim)+ with app.app_context():+ db.session.delete(db.session.get(User, admin_id))+ db.session.commit()++[email protected]("login_id", ["abc", "1:x", ""])+def test_malformed_login_ids_are_refused(login_id):+ with app.app_context():+ assert load_user(login_id) is None+++def test_older_version_is_refused(user_id):+ with app.app_context():+ u = db.session.get(User, user_id)+ u.end_all_sessions()+ u.end_all_sessions()+ db.session.commit()+ assert load_user(f"{user_id}:1") is None+ assert load_user(str(user_id)) is None+ assert load_user(f"{user_id}:2").id == user_id