myst/web/app/auth/crypto.py
ZTatman 5fec547983 feat(web): Forgejo OAuth, Myst sessions, and auth schema
Implement Myst-owned sessions after Forgejo OAuth per auth design: User and
LinkedIdentity with encrypted OAuth tokens, Session in its own module,
Grant token_hash plus user_id and expires_at. Add auth/identity and
auth/session helpers, Forgejo login/callback/logout routes, and a minimal
/dashboard that requires get_current_session.

Move get_db to app/deps.py so routers and auth avoid importing app.main.
Add httpx and cryptography; extend Settings with OAuth client fields,
optional MYST_PUBLIC_BASE_URL for redirect_uri, and OAUTH_TOKEN_ENCRYPTION_KEY
(Fernet) required when persisting OAuth tokens.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 15:12:17 -04:00

29 lines
869 B
Python

"""Fernet (AES) encryption for OAuth tokens at rest."""
from __future__ import annotations
from cryptography.fernet import Fernet
from pydantic import SecretStr
def fernet_from_encryption_key(key: SecretStr) -> Fernet | None:
raw = key.get_secret_value().strip()
if not raw:
return None
return Fernet(raw.encode())
def encrypt_oauth_token(fernet: Fernet, plain: str) -> str:
return fernet.encrypt(plain.encode()).decode()
def encrypt_optional(fernet: Fernet | None, plain: str | None) -> str | None:
if plain is None:
return None
if fernet is None:
msg = (
"OAuth token encryption is not configured: set OAUTH_TOKEN_ENCRYPTION_KEY "
"to the output of cryptography.fernet.Fernet.generate_key().decode()"
)
raise ValueError(msg)
return encrypt_oauth_token(fernet, plain)