MEGAINFRA-WEBAPP/scripts/migrations/2026-10-19-user-session-lifetime.py

50 lines
1.9 KiB
Python

#!/usr/bin/env python3
"""Set named-user tokens to 60 days. Dry-run unless --apply is supplied."""
import argparse
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from pb_env import PB, http, superuser_token # noqa: E402
SESSION_SECONDS = 60 * 24 * 60 * 60
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--apply", action="store_true")
parser.add_argument("--confirm-host", help="Exact configured PocketBase URL")
args = parser.parse_args()
if args.apply and args.confirm_host != PB:
parser.error("--apply requires --confirm-host matching the configured PocketBase URL")
token = superuser_token()
path = "/api/collections/users"
status, users = http("GET", path, token=token)
if status != 200 or users.get("type") != "auth":
raise RuntimeError("Could not read the users auth collection")
previous = users.get("authToken", {}).get("duration")
print(f"users.authToken.duration: {previous} -> {SESSION_SECONDS} seconds (60 days)")
if previous == SESSION_SECONDS:
print("Already configured. No changes needed.")
return
if not args.apply:
print("Dry run: no changes. Deploy matching app cookie lifetime with this setting.")
return
status, _ = http("PATCH", path, {"authToken": {"duration": SESSION_SECONDS}}, token)
if status != 200:
raise RuntimeError(f"Session lifetime update failed (HTTP {status})")
status, verified = http("GET", path, token=token)
if status != 200 or verified.get("authToken", {}).get("duration") != SESSION_SECONDS:
raise RuntimeError("Session lifetime verification failed")
print("Verified: new user tokens last 60 days. Existing tokens retain their original expiry.")
if __name__ == "__main__":
try:
main()
except Exception as error:
print(f"ERROR: {error}", file=sys.stderr)
sys.exit(1)