Major cleanup and refactoring of the backend (frontend not fully updated).
This commit is contained in:
@@ -8,67 +8,67 @@ This module contains all the HTTP API endpoints for:
|
||||
- Login/logout functionality
|
||||
"""
|
||||
|
||||
from fastapi import FastAPI, Request, Response
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Cookie, Depends, FastAPI, Request, Response
|
||||
from fastapi.security import HTTPBearer
|
||||
|
||||
from .. import aaguid
|
||||
from ..db import sql
|
||||
from ..util.session import refresh_session_token, validate_session_token
|
||||
from .session import (
|
||||
clear_session_cookie,
|
||||
get_current_user,
|
||||
get_session_token_from_bearer,
|
||||
get_session_token_from_cookie,
|
||||
set_session_cookie,
|
||||
)
|
||||
from ..util.tokens import session_key
|
||||
from . import session
|
||||
|
||||
bearer_auth = HTTPBearer(auto_error=True)
|
||||
|
||||
|
||||
def register_api_routes(app: FastAPI):
|
||||
"""Register all API routes on the FastAPI app."""
|
||||
|
||||
@app.post("/auth/user-info")
|
||||
async def api_user_info(request: Request, response: Response):
|
||||
"""Get user information and credentials from session cookie."""
|
||||
@app.post("/auth/validate")
|
||||
async def validate_token(request: Request, response: Response, auth=Cookie(None)):
|
||||
"""Lightweight token validation endpoint."""
|
||||
try:
|
||||
user = await get_current_user(request)
|
||||
if not user:
|
||||
return {"error": "Not authenticated"}
|
||||
|
||||
# Get current session credential ID
|
||||
current_credential_id = None
|
||||
session_token = get_session_token_from_cookie(request)
|
||||
if session_token:
|
||||
token_data = await validate_session_token(session_token)
|
||||
if token_data:
|
||||
current_credential_id = token_data.get("credential_id")
|
||||
s = await session.get_session(auth)
|
||||
return {
|
||||
"status": "success",
|
||||
"valid": True,
|
||||
"user_uuid": str(s.user_uuid),
|
||||
}
|
||||
except ValueError:
|
||||
return {"status": "error", "valid": False}
|
||||
|
||||
@app.post("/auth/user-info")
|
||||
async def api_user_info(request: Request, response: Response, auth=Cookie(None)):
|
||||
"""Get full user information for the authenticated user."""
|
||||
try:
|
||||
s = await session.get_session(auth, reset_allowed=True)
|
||||
u = await sql.get_user_by_uuid(s.user_uuid)
|
||||
# Get all credentials for the user
|
||||
credential_ids = await sql.get_user_credentials(user.user_id)
|
||||
credential_ids = await sql.get_user_credentials(s.user_uuid)
|
||||
|
||||
credentials = []
|
||||
user_aaguids = set()
|
||||
|
||||
for cred_id in credential_ids:
|
||||
stored_cred = await sql.get_credential_by_id(cred_id)
|
||||
c = await sql.get_credential_by_id(cred_id)
|
||||
|
||||
# Convert AAGUID to string format
|
||||
aaguid_str = str(stored_cred.aaguid)
|
||||
aaguid_str = str(c.aaguid)
|
||||
user_aaguids.add(aaguid_str)
|
||||
|
||||
# Check if this is the current session credential
|
||||
is_current_session = current_credential_id == stored_cred.credential_id
|
||||
is_current_session = s.credential_uuid == c.uuid
|
||||
|
||||
credentials.append(
|
||||
{
|
||||
"credential_id": stored_cred.credential_id.hex(),
|
||||
"credential_uuid": str(c.uuid),
|
||||
"aaguid": aaguid_str,
|
||||
"created_at": stored_cred.created_at.isoformat(),
|
||||
"last_used": stored_cred.last_used.isoformat()
|
||||
if stored_cred.last_used
|
||||
"created_at": c.created_at.isoformat(),
|
||||
"last_used": c.last_used.isoformat() if c.last_used else None,
|
||||
"last_verified": c.last_verified.isoformat()
|
||||
if c.last_verified
|
||||
else None,
|
||||
"last_verified": stored_cred.last_verified.isoformat()
|
||||
if stored_cred.last_verified
|
||||
else None,
|
||||
"sign_count": stored_cred.sign_count,
|
||||
"sign_count": c.sign_count,
|
||||
"is_current_session": is_current_session,
|
||||
}
|
||||
)
|
||||
@@ -82,13 +82,11 @@ def register_api_routes(app: FastAPI):
|
||||
return {
|
||||
"status": "success",
|
||||
"user": {
|
||||
"user_id": str(user.user_id),
|
||||
"user_name": user.user_name,
|
||||
"created_at": user.created_at.isoformat()
|
||||
if user.created_at
|
||||
else None,
|
||||
"last_seen": user.last_seen.isoformat() if user.last_seen else None,
|
||||
"visits": user.visits,
|
||||
"user_uuid": str(u.user_uuid),
|
||||
"user_name": u.user_name,
|
||||
"created_at": u.created_at.isoformat() if u.created_at else None,
|
||||
"last_seen": u.last_seen.isoformat() if u.last_seen else None,
|
||||
"visits": u.visits,
|
||||
},
|
||||
"credentials": credentials,
|
||||
"aaguid_info": aaguid_info,
|
||||
@@ -97,196 +95,44 @@ def register_api_routes(app: FastAPI):
|
||||
return {"error": f"Failed to get user info: {str(e)}"}
|
||||
|
||||
@app.post("/auth/logout")
|
||||
async def api_logout(request: Request, response: Response):
|
||||
async def api_logout(response: Response, auth=Cookie(None)):
|
||||
"""Log out the current user by clearing the session cookie and deleting from database."""
|
||||
# Get the session token before clearing the cookie
|
||||
session_token = get_session_token_from_cookie(request)
|
||||
|
||||
# Clear the cookie
|
||||
clear_session_cookie(response)
|
||||
|
||||
# Delete the session from the database if it exists
|
||||
if session_token:
|
||||
from ..util.session import logout_session
|
||||
|
||||
try:
|
||||
await logout_session(session_token)
|
||||
except Exception:
|
||||
# Continue even if session deletion fails
|
||||
pass
|
||||
|
||||
if not auth:
|
||||
return {"status": "success", "message": "Already logged out"}
|
||||
await sql.delete_session(session_key(auth))
|
||||
response.delete_cookie("auth")
|
||||
return {"status": "success", "message": "Logged out successfully"}
|
||||
|
||||
@app.post("/auth/set-session")
|
||||
async def api_set_session(request: Request, response: Response):
|
||||
"""Set session cookie using JWT token from request body or Authorization header."""
|
||||
async def api_set_session(
|
||||
request: Request, response: Response, auth=Depends(bearer_auth)
|
||||
):
|
||||
"""Set session cookie from Authorization header. Fetched after login by WebSocket."""
|
||||
try:
|
||||
session_token = await get_session_token_from_bearer(request)
|
||||
|
||||
if not session_token:
|
||||
return {"error": "No session token provided"}
|
||||
|
||||
# Validate the session token
|
||||
token_data = await validate_session_token(session_token)
|
||||
if not token_data:
|
||||
return {"error": "Invalid or expired session token"}
|
||||
|
||||
# Set the HTTP-only cookie
|
||||
set_session_cookie(response, session_token)
|
||||
user = await session.get_session(auth.credentials)
|
||||
if not user:
|
||||
raise ValueError("Invalid Authorization header.")
|
||||
session.set_session_cookie(response, auth.credentials)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"message": "Session cookie set successfully",
|
||||
"user_id": str(token_data["user_id"]),
|
||||
"user_uuid": str(user.user_uuid),
|
||||
}
|
||||
|
||||
except ValueError as e:
|
||||
return {"error": str(e)}
|
||||
except Exception as e:
|
||||
return {"error": f"Failed to set session: {str(e)}"}
|
||||
|
||||
@app.post("/auth/delete-credential")
|
||||
async def api_delete_credential(request: Request):
|
||||
@app.delete("/auth/credential/{uuid}")
|
||||
async def api_delete_credential(uuid: UUID, auth: str = Cookie(None)):
|
||||
"""Delete a specific credential for the current user."""
|
||||
try:
|
||||
user = await get_current_user(request)
|
||||
if not user:
|
||||
return {"error": "Not authenticated"}
|
||||
|
||||
# Get the credential ID from the request body
|
||||
try:
|
||||
body = await request.json()
|
||||
credential_id = body.get("credential_id")
|
||||
if not credential_id:
|
||||
return {"error": "credential_id is required"}
|
||||
except Exception:
|
||||
return {"error": "Invalid request body"}
|
||||
|
||||
# Convert credential_id from hex string to bytes
|
||||
try:
|
||||
credential_id_bytes = bytes.fromhex(credential_id)
|
||||
except ValueError:
|
||||
return {"error": "Invalid credential_id format"}
|
||||
|
||||
# First, verify the credential belongs to the current user
|
||||
try:
|
||||
stored_cred = await sql.get_credential_by_id(credential_id_bytes)
|
||||
if stored_cred.user_id != user.user_id:
|
||||
return {"error": "Credential not found or access denied"}
|
||||
except ValueError:
|
||||
return {"error": "Credential not found"}
|
||||
|
||||
# Check if this is the current session credential
|
||||
session_token = get_session_token_from_cookie(request)
|
||||
if session_token:
|
||||
token_data = await validate_session_token(session_token)
|
||||
if (
|
||||
token_data
|
||||
and token_data.get("credential_id") == credential_id_bytes
|
||||
):
|
||||
return {"error": "Cannot delete current session credential"}
|
||||
|
||||
# Get user's remaining credentials count
|
||||
remaining_credentials = await sql.get_user_credentials(user.user_id)
|
||||
if len(remaining_credentials) <= 1:
|
||||
return {"error": "Cannot delete last remaining credential"}
|
||||
|
||||
# Delete the credential
|
||||
await sql.delete_user_credential(credential_id_bytes)
|
||||
|
||||
await session.delete_credential(uuid, auth)
|
||||
return {"status": "success", "message": "Credential deleted successfully"}
|
||||
|
||||
except Exception as e:
|
||||
return {"error": f"Failed to delete credential: {str(e)}"}
|
||||
|
||||
@app.get("/auth/sessions")
|
||||
async def api_get_sessions(request: Request):
|
||||
"""Get all active sessions for the current user."""
|
||||
try:
|
||||
user = await get_current_user(request)
|
||||
if not user:
|
||||
return {"error": "Authentication required"}
|
||||
|
||||
# Get all sessions for this user
|
||||
from sqlalchemy import select
|
||||
|
||||
from ..db.sql import SessionModel, connect
|
||||
|
||||
async with connect() as db:
|
||||
stmt = select(SessionModel).where(
|
||||
SessionModel.user_id == user.user_id.bytes
|
||||
)
|
||||
result = await db.session.execute(stmt)
|
||||
session_models = result.scalars().all()
|
||||
|
||||
sessions = []
|
||||
current_token = get_session_token_from_cookie(request)
|
||||
|
||||
for session in session_models:
|
||||
# Check if session is expired
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
expiry_time = session.created_at + timedelta(hours=24)
|
||||
is_expired = datetime.now() > expiry_time
|
||||
|
||||
sessions.append(
|
||||
{
|
||||
"token": session.token[:8]
|
||||
+ "...", # Only show first 8 chars for security
|
||||
"created_at": session.created_at.isoformat(),
|
||||
"client_ip": session.info.get("client_ip")
|
||||
if session.info
|
||||
else None,
|
||||
"user_agent": session.info.get("user_agent")
|
||||
if session.info
|
||||
else None,
|
||||
"connection_type": session.info.get(
|
||||
"connection_type", "http"
|
||||
)
|
||||
if session.info
|
||||
else "http",
|
||||
"is_current": session.token == current_token,
|
||||
"is_reset_token": session.credential_id is None,
|
||||
"is_expired": is_expired,
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"sessions": sessions,
|
||||
"total_sessions": len(sessions),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {"error": f"Failed to get sessions: {str(e)}"}
|
||||
|
||||
|
||||
async def validate_token(request: Request, response: Response) -> dict:
|
||||
"""Validate a session token and return user info. Also refreshes the token if valid."""
|
||||
try:
|
||||
session_token = get_session_token_from_cookie(request)
|
||||
if not session_token:
|
||||
return {"error": "No session token found"}
|
||||
|
||||
# Validate the session token
|
||||
token_data = await validate_session_token(session_token)
|
||||
if not token_data:
|
||||
clear_session_cookie(response)
|
||||
return {"error": "Invalid or expired session token"}
|
||||
|
||||
# Refresh the token if valid
|
||||
new_token = await refresh_session_token(session_token)
|
||||
if new_token:
|
||||
set_session_cookie(response, new_token)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"valid": True,
|
||||
"refreshed": bool(new_token),
|
||||
"user_id": str(token_data["user_id"]),
|
||||
"credential_id": token_data["credential_id"].hex()
|
||||
if token_data["credential_id"]
|
||||
else None,
|
||||
"created_at": token_data["created_at"].isoformat(),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {"error": f"Failed to validate token: {str(e)}"}
|
||||
except ValueError as e:
|
||||
return {"error": str(e)}
|
||||
except Exception:
|
||||
return {"error": "Failed to delete credential"}
|
||||
|
||||
@@ -9,15 +9,12 @@ This module provides a simple WebAuthn implementation that:
|
||||
- Enables true passwordless authentication where users don't need to enter a user_name
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import (
|
||||
FastAPI,
|
||||
Request,
|
||||
Response,
|
||||
)
|
||||
from fastapi import Cookie, FastAPI, Request, Response
|
||||
from fastapi.responses import (
|
||||
FileResponse,
|
||||
JSONResponse,
|
||||
@@ -25,12 +22,9 @@ from fastapi.responses import (
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from ..db import sql
|
||||
from .api import (
|
||||
register_api_routes,
|
||||
validate_token,
|
||||
)
|
||||
from . import session, ws
|
||||
from .api import register_api_routes
|
||||
from .reset import register_reset_routes
|
||||
from .ws import ws_app
|
||||
|
||||
STATIC_DIR = Path(__file__).parent.parent / "frontend-build"
|
||||
|
||||
@@ -44,7 +38,7 @@ async def lifespan(app: FastAPI):
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
|
||||
# Mount the WebSocket subapp
|
||||
app.mount("/auth/ws", ws_app)
|
||||
app.mount("/auth/ws", ws.app)
|
||||
|
||||
# Register API routes
|
||||
register_api_routes(app)
|
||||
@@ -52,24 +46,19 @@ register_reset_routes(app)
|
||||
|
||||
|
||||
@app.get("/auth/forward-auth")
|
||||
async def forward_authentication(request: Request):
|
||||
"""A verification endpoint to use with Caddy forward_auth or Nginx auth_request."""
|
||||
# Create a dummy response object for internal validation (we won't use it for cookies)
|
||||
response = Response()
|
||||
async def forward_authentication(request: Request, auth=Cookie(None)):
|
||||
"""A validation endpoint to use with Caddy forward_auth or Nginx auth_request."""
|
||||
with contextlib.suppress(ValueError):
|
||||
s = await session.get_session(auth)
|
||||
# If authenticated, return a success response
|
||||
if s.info and s.info["type"] == "authenticated":
|
||||
return Response(status_code=204, headers={"x-auth-user": str(s.user_uuid)})
|
||||
|
||||
result = await validate_token(request, response)
|
||||
if result.get("status") != "success":
|
||||
# Serve the index.html of the authentication app if not authenticated
|
||||
return FileResponse(
|
||||
STATIC_DIR / "index.html",
|
||||
status_code=401,
|
||||
headers={"www-authenticate": "PrivateToken"},
|
||||
)
|
||||
|
||||
# If authenticated, return a success response
|
||||
return Response(
|
||||
status_code=204,
|
||||
headers={"x-auth-user-id": result["user_id"]},
|
||||
# Serve the index.html of the authentication app if not authenticated
|
||||
return FileResponse(
|
||||
STATIC_DIR / "index.html",
|
||||
status_code=401,
|
||||
headers={"www-authenticate": "PrivateToken"},
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,114 +1,74 @@
|
||||
"""
|
||||
Device addition API handlers for WebAuthn authentication.
|
||||
import logging
|
||||
|
||||
This module provides endpoints for authenticated users to:
|
||||
- Generate device addition links with human-readable tokens
|
||||
- Validate device addition tokens
|
||||
- Add new passkeys to existing accounts via tokens
|
||||
"""
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import FastAPI, Path, Request
|
||||
from fastapi import Cookie, HTTPException, Request
|
||||
from fastapi.responses import RedirectResponse
|
||||
|
||||
from ..db import sql
|
||||
from ..util.passphrase import generate
|
||||
from ..util.session import get_client_info
|
||||
from .session import get_current_user, is_device_addition_session, set_session_cookie
|
||||
from ..util import passphrase, tokens
|
||||
from . import session
|
||||
|
||||
|
||||
def register_reset_routes(app: FastAPI):
|
||||
def register_reset_routes(app):
|
||||
"""Register all device addition/reset routes on the FastAPI app."""
|
||||
|
||||
@app.post("/auth/create-device-link")
|
||||
async def api_create_device_link(request: Request):
|
||||
@app.post("/auth/create-link")
|
||||
async def api_create_link(request: Request, auth=Cookie(None)):
|
||||
"""Create a device addition link for the authenticated user."""
|
||||
try:
|
||||
# Require authentication
|
||||
user = await get_current_user(request)
|
||||
if not user:
|
||||
return {"error": "Authentication required"}
|
||||
s = await session.get_session(auth)
|
||||
|
||||
# Generate a human-readable token
|
||||
token = generate(n=4, sep=".") # e.g., "able-ocean-forest-dawn"
|
||||
|
||||
# Create session token in database with credential_id=None for device addition
|
||||
client_info = get_client_info(request)
|
||||
await sql.create_session(user.user_id, None, token, client_info)
|
||||
token = passphrase.generate() # e.g., "cross.rotate.yin.note.evoke"
|
||||
await sql.create_session(
|
||||
user_uuid=s.user_uuid,
|
||||
key=tokens.reset_key(token),
|
||||
expires=session.expires(),
|
||||
info=session.infodict(request, "device addition"),
|
||||
)
|
||||
|
||||
# Generate the device addition link with pretty URL
|
||||
addition_link = f"{request.headers.get('origin', '')}/auth/{token}"
|
||||
path = request.url.path.removesuffix("create-link") + token
|
||||
url = f"{request.headers['origin']}{path}"
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"message": "Device addition link generated successfully",
|
||||
"addition_link": addition_link,
|
||||
"expires_in_hours": 24,
|
||||
"message": "Registration link generated successfully",
|
||||
"url": url,
|
||||
"expires": session.expires().isoformat(),
|
||||
}
|
||||
|
||||
except ValueError:
|
||||
return {"error": "Authentication required"}
|
||||
except Exception as e:
|
||||
return {"error": f"Failed to create device addition link: {str(e)}"}
|
||||
return {"error": f"Failed to create registration link: {str(e)}"}
|
||||
|
||||
@app.get("/auth/device-session-check")
|
||||
async def check_device_session(request: Request):
|
||||
"""Check if the current session is for device addition."""
|
||||
is_device_session = await is_device_addition_session(request)
|
||||
return {"device_addition_session": is_device_session}
|
||||
|
||||
@app.get("/auth/{passphrase}")
|
||||
@app.get("/auth/{reset_token}")
|
||||
async def reset_authentication(
|
||||
request: Request,
|
||||
passphrase: str = Path(pattern=r"^\w+(\.\w+){2,}$"),
|
||||
reset_token: str,
|
||||
):
|
||||
"""Verifies the token and redirects to auth app for credential registration."""
|
||||
# This route should only match to exact passphrases
|
||||
print(f"Reset handler called with url: {request.url.path}")
|
||||
if not passphrase.is_well_formed(reset_token):
|
||||
raise HTTPException(status_code=404)
|
||||
try:
|
||||
# Get session token to validate it exists and get user_id
|
||||
session = await sql.get_session(passphrase)
|
||||
if not session:
|
||||
# Token doesn't exist, redirect to home
|
||||
return RedirectResponse(url="/", status_code=303)
|
||||
key = tokens.reset_key(reset_token)
|
||||
sess = await sql.get_session(key)
|
||||
if not sess:
|
||||
raise ValueError("Invalid or expired registration token")
|
||||
|
||||
# Check if this is a device addition session (credential_id is None)
|
||||
if session.credential_id is not None:
|
||||
# Not a device addition session, redirect to home
|
||||
return RedirectResponse(url="/", status_code=303)
|
||||
|
||||
# Create a device addition session token for the user
|
||||
client_info = get_client_info(request)
|
||||
session_token = await sql.create_session(
|
||||
UUID(bytes=session.user_id), None, None, client_info
|
||||
)
|
||||
|
||||
# Create response and set session cookie
|
||||
response = RedirectResponse(url="/auth/", status_code=303)
|
||||
set_session_cookie(response, session_token)
|
||||
|
||||
session.set_session_cookie(response, reset_token)
|
||||
return response
|
||||
|
||||
except Exception:
|
||||
# On any error, redirect to home
|
||||
return RedirectResponse(url="/", status_code=303)
|
||||
|
||||
|
||||
async def use_reset_token(token: str) -> dict:
|
||||
"""Delete a device addition token after successful use."""
|
||||
try:
|
||||
# Get session token first to validate it exists and is not expired
|
||||
session = await sql.get_session(token)
|
||||
if not session:
|
||||
return {"error": "Invalid or expired device addition token"}
|
||||
|
||||
# Check if this is a device addition session (credential_id is None)
|
||||
if session.credential_id is not None:
|
||||
return {"error": "Invalid device addition token"}
|
||||
|
||||
# Delete the token (it's now used)
|
||||
await sql.delete_session(token)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"message": "Device addition token used successfully",
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {"error": f"Failed to use device addition token: {str(e)}"}
|
||||
except Exception as e:
|
||||
# On any error, redirect to auth app
|
||||
if isinstance(e, ValueError):
|
||||
msg = str(e)
|
||||
else:
|
||||
logging.exception("Internal Server Error in reset_authentication")
|
||||
msg = "Internal Server Error"
|
||||
return RedirectResponse(url=f"/auth/#{msg}", status_code=303)
|
||||
|
||||
@@ -5,144 +5,85 @@ This module provides session management functionality including:
|
||||
- Getting current user from session cookies
|
||||
- Setting and clearing HTTP-only cookies
|
||||
- Session validation and token handling
|
||||
- Device addition token management
|
||||
- Device addition route handlers
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Request, Response
|
||||
|
||||
from ..db.sql import User, get_user_by_id
|
||||
from ..util.session import validate_session_token
|
||||
from ..db import Session, sql
|
||||
from ..util import passphrase
|
||||
from ..util.tokens import create_token, reset_key, session_key
|
||||
|
||||
COOKIE_NAME = "auth"
|
||||
COOKIE_MAX_AGE = 86400 # 24 hours
|
||||
EXPIRES = timedelta(hours=24)
|
||||
|
||||
|
||||
async def get_current_user(request: Request) -> User | None:
|
||||
"""Get the current user from the session cookie."""
|
||||
session_token = request.cookies.get(COOKIE_NAME)
|
||||
if not session_token:
|
||||
return None
|
||||
|
||||
token_data = await validate_session_token(session_token)
|
||||
if not token_data:
|
||||
return None
|
||||
|
||||
try:
|
||||
user = await get_user_by_id(token_data["user_id"])
|
||||
return user
|
||||
except Exception:
|
||||
return None
|
||||
def expires() -> datetime:
|
||||
return datetime.now() + EXPIRES
|
||||
|
||||
|
||||
def set_session_cookie(response: Response, session_token: str) -> None:
|
||||
def infodict(request: Request, type: str) -> dict:
|
||||
"""Extract client information from request."""
|
||||
return {
|
||||
"ip": request.client.host if request.client else "",
|
||||
"user_agent": request.headers.get("user-agent", "")[:500],
|
||||
"type": type,
|
||||
}
|
||||
|
||||
|
||||
async def create_session(user_uuid: UUID, info: dict, credential_uuid: UUID) -> str:
|
||||
"""Create a new session and return a session token."""
|
||||
token = create_token()
|
||||
await sql.create_session(
|
||||
user_uuid=user_uuid,
|
||||
key=session_key(token),
|
||||
expires=datetime.now() + EXPIRES,
|
||||
info=info,
|
||||
credential_uuid=credential_uuid,
|
||||
)
|
||||
return token
|
||||
|
||||
|
||||
async def get_session(token: str, reset_allowed=False) -> Session:
|
||||
"""Validate a session token and return session data if valid."""
|
||||
if passphrase.is_well_formed(token):
|
||||
if not reset_allowed:
|
||||
raise ValueError("Reset link is not allowed for this endpoint")
|
||||
key = reset_key(token)
|
||||
else:
|
||||
key = session_key(token)
|
||||
|
||||
session = await sql.get_session(key)
|
||||
if not session:
|
||||
raise ValueError("Invalid or expired session token")
|
||||
return session
|
||||
|
||||
|
||||
async def refresh_session_token(token: str):
|
||||
"""Refresh a session extending its expiry."""
|
||||
# Get the current session
|
||||
s = await sql.update_session(session_key(token), datetime.now() + EXPIRES, {})
|
||||
|
||||
if not s:
|
||||
raise ValueError("Session not found or expired")
|
||||
|
||||
|
||||
def set_session_cookie(response: Response, token: str) -> None:
|
||||
"""Set the session token as an HTTP-only cookie."""
|
||||
response.set_cookie(
|
||||
key=COOKIE_NAME,
|
||||
value=session_token,
|
||||
max_age=COOKIE_MAX_AGE,
|
||||
key="auth",
|
||||
value=token,
|
||||
max_age=int(EXPIRES.total_seconds()),
|
||||
httponly=True,
|
||||
secure=True,
|
||||
samesite="lax",
|
||||
path="/auth/",
|
||||
)
|
||||
|
||||
|
||||
def clear_session_cookie(response: Response) -> None:
|
||||
"""Clear the session cookie."""
|
||||
response.delete_cookie(key=COOKIE_NAME)
|
||||
|
||||
|
||||
def get_session_token_from_cookie(request: Request) -> str | None:
|
||||
"""Extract session token from request cookies."""
|
||||
return request.cookies.get(COOKIE_NAME)
|
||||
|
||||
|
||||
async def validate_session_from_request(request: Request) -> dict | None:
|
||||
"""Validate session token from request and return token data."""
|
||||
session_token = get_session_token_from_cookie(request)
|
||||
if not session_token:
|
||||
return None
|
||||
|
||||
return await validate_session_token(session_token)
|
||||
|
||||
|
||||
async def get_session_token_from_bearer(request: Request) -> str | None:
|
||||
"""Extract session token from Authorization header or request body."""
|
||||
# Try to get token from Authorization header first
|
||||
auth_header = request.headers.get("Authorization")
|
||||
if auth_header and auth_header.startswith("Bearer "):
|
||||
return auth_header.removeprefix("Bearer ")
|
||||
|
||||
|
||||
async def get_user_from_cookie_string(cookie_header: str) -> UUID | None:
|
||||
"""Parse cookie header and return user ID if valid session exists."""
|
||||
if not cookie_header:
|
||||
return None
|
||||
|
||||
# Parse cookies from header (simple implementation)
|
||||
cookies = {}
|
||||
for cookie in cookie_header.split(";"):
|
||||
cookie = cookie.strip()
|
||||
if "=" in cookie:
|
||||
name, value = cookie.split("=", 1)
|
||||
cookies[name] = value
|
||||
|
||||
session_token = cookies.get(COOKIE_NAME)
|
||||
if not session_token:
|
||||
return None
|
||||
|
||||
token_data = await validate_session_token(session_token)
|
||||
if not token_data:
|
||||
return None
|
||||
|
||||
return token_data["user_id"]
|
||||
|
||||
|
||||
async def is_device_addition_session(request: Request) -> bool:
|
||||
"""Check if the current session is for device addition."""
|
||||
session_token = request.cookies.get(COOKIE_NAME)
|
||||
if not session_token:
|
||||
return False
|
||||
|
||||
token_data = await validate_session_token(session_token)
|
||||
if not token_data:
|
||||
return False
|
||||
|
||||
return token_data.get("device_addition", False)
|
||||
|
||||
|
||||
async def get_device_addition_user_id(request: Request) -> UUID | None:
|
||||
"""Get user ID from device addition session."""
|
||||
session_token = request.cookies.get(COOKIE_NAME)
|
||||
if not session_token:
|
||||
return None
|
||||
|
||||
token_data = await validate_session_token(session_token)
|
||||
if not token_data or not token_data.get("device_addition"):
|
||||
return None
|
||||
|
||||
return token_data.get("user_id")
|
||||
|
||||
|
||||
async def get_device_addition_user_id_from_cookie(cookie_header: str) -> UUID | None:
|
||||
"""Parse cookie header and return user ID if valid device addition session exists."""
|
||||
if not cookie_header:
|
||||
return None
|
||||
|
||||
# Parse cookies from header (simple implementation)
|
||||
cookies = {}
|
||||
for cookie in cookie_header.split(";"):
|
||||
cookie = cookie.strip()
|
||||
if "=" in cookie:
|
||||
name, value = cookie.split("=", 1)
|
||||
cookies[name] = value
|
||||
|
||||
session_token = cookies.get(COOKIE_NAME)
|
||||
if not session_token:
|
||||
return None
|
||||
|
||||
token_data = await validate_session_token(session_token)
|
||||
if not token_data or not token_data.get("device_addition"):
|
||||
return None
|
||||
|
||||
return token_data["user_id"]
|
||||
async def delete_credential(credential_uuid: UUID, auth: str):
|
||||
"""Delete a specific credential for the current user."""
|
||||
s = await get_session(auth)
|
||||
await sql.delete_credential(credential_uuid, s.user_uuid)
|
||||
|
||||
@@ -13,17 +13,18 @@ from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
import uuid7
|
||||
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
||||
from fastapi import Cookie, FastAPI, Query, Request, WebSocket, WebSocketDisconnect
|
||||
from webauthn.helpers.exceptions import InvalidAuthenticationResponse
|
||||
|
||||
from ..db import sql
|
||||
from ..db.sql import User
|
||||
from passkey.fastapi import session
|
||||
|
||||
from ..db import User, sql
|
||||
from ..sansio import Passkey
|
||||
from ..util.session import create_session_token, get_client_info_from_websocket
|
||||
from .session import get_user_from_cookie_string
|
||||
from ..util.tokens import create_token, reset_key, session_key
|
||||
from .session import create_session, infodict
|
||||
|
||||
# Create a FastAPI subapp for WebSocket endpoints
|
||||
ws_app = FastAPI()
|
||||
app = FastAPI()
|
||||
|
||||
# Initialize the passkey instance
|
||||
passkey = Passkey(
|
||||
@@ -34,51 +35,55 @@ passkey = Passkey(
|
||||
|
||||
async def register_chat(
|
||||
ws: WebSocket,
|
||||
user_id: UUID,
|
||||
user_uuid: UUID,
|
||||
user_name: str,
|
||||
credential_ids: list[bytes] | None = None,
|
||||
origin: str | None = None,
|
||||
):
|
||||
"""Generate registration options and send them to the client."""
|
||||
options, challenge = passkey.reg_generate_options(
|
||||
user_id=user_id,
|
||||
user_id=user_uuid,
|
||||
user_name=user_name,
|
||||
credential_ids=credential_ids,
|
||||
origin=origin,
|
||||
)
|
||||
await ws.send_json(options)
|
||||
response = await ws.receive_json()
|
||||
return passkey.reg_verify(response, challenge, user_id, origin=origin)
|
||||
return passkey.reg_verify(response, challenge, user_uuid, origin=origin)
|
||||
|
||||
|
||||
@ws_app.websocket("/register_new")
|
||||
async def websocket_register_new(ws: WebSocket, user_name: str):
|
||||
@app.websocket("/register")
|
||||
async def websocket_register_new(
|
||||
request: Request, ws: WebSocket, user_name: str = Query(""), auth=Cookie(None)
|
||||
):
|
||||
"""Register a new user and with a new passkey credential."""
|
||||
await ws.accept()
|
||||
origin = ws.headers.get("origin")
|
||||
try:
|
||||
user_id = uuid7.create()
|
||||
|
||||
user_uuid = uuid7.create()
|
||||
# WebAuthn registration
|
||||
credential = await register_chat(ws, user_id, user_name, origin=origin)
|
||||
credential = await register_chat(ws, user_uuid, user_name, origin=origin)
|
||||
|
||||
# Store the user and credential in the database
|
||||
await sql.create_user_and_credential(
|
||||
User(user_id, user_name, created_at=datetime.now()),
|
||||
User(user_uuid, user_name, created_at=datetime.now()),
|
||||
credential,
|
||||
)
|
||||
|
||||
# Create a session token for the new user
|
||||
client_info = get_client_info_from_websocket(ws)
|
||||
session_token = await create_session_token(
|
||||
user_id, credential.credential_id, client_info
|
||||
token = create_token()
|
||||
await sql.create_session(
|
||||
user_uuid=user_uuid,
|
||||
key=session_key(token),
|
||||
expires=datetime.now() + session.EXPIRES,
|
||||
info=infodict(request, "authenticated"),
|
||||
credential_uuid=credential.uuid,
|
||||
)
|
||||
|
||||
await ws.send_json(
|
||||
{
|
||||
"status": "success",
|
||||
"user_id": str(user_id),
|
||||
"session_token": session_token,
|
||||
"user_uuid": str(user_uuid),
|
||||
"session_token": token,
|
||||
}
|
||||
)
|
||||
except ValueError as e:
|
||||
@@ -90,28 +95,31 @@ async def websocket_register_new(ws: WebSocket, user_name: str):
|
||||
await ws.send_json({"error": "Internal Server Error"})
|
||||
|
||||
|
||||
@ws_app.websocket("/add_credential")
|
||||
async def websocket_register_add(ws: WebSocket):
|
||||
@app.websocket("/add_credential")
|
||||
async def websocket_register_add(ws: WebSocket, token: str | None = None):
|
||||
"""Register a new credential for an existing user."""
|
||||
await ws.accept()
|
||||
origin = ws.headers.get("origin")
|
||||
try:
|
||||
# Authenticate user via cookie
|
||||
cookie_header = ws.headers.get("cookie", "")
|
||||
user_id = await get_user_from_cookie_string(cookie_header)
|
||||
|
||||
if not user_id:
|
||||
await ws.send_json({"error": "Authentication required"})
|
||||
if not token:
|
||||
await ws.send_json({"error": "Token is required"})
|
||||
return
|
||||
# If a token is provided, use it to look up the session
|
||||
key = reset_key(token)
|
||||
s = await sql.get_session(key)
|
||||
if not s:
|
||||
await ws.send_json({"error": "Invalid or expired token"})
|
||||
return
|
||||
user_uuid = s.user_uuid
|
||||
|
||||
# Get user information to get the user_name
|
||||
user = await sql.get_user_by_id(user_id)
|
||||
user = await sql.get_user_by_uuid(user_uuid)
|
||||
user_name = user.user_name
|
||||
challenge_ids = await sql.get_user_credentials(user_id)
|
||||
challenge_ids = await sql.get_user_credentials(user_uuid)
|
||||
|
||||
# WebAuthn registration
|
||||
credential = await register_chat(
|
||||
ws, user_id, user_name, challenge_ids, origin=origin
|
||||
ws, user_uuid, user_name, challenge_ids, origin=origin
|
||||
)
|
||||
# Store the new credential in the database
|
||||
await sql.create_credential_for_user(credential)
|
||||
@@ -119,7 +127,7 @@ async def websocket_register_add(ws: WebSocket):
|
||||
await ws.send_json(
|
||||
{
|
||||
"status": "success",
|
||||
"user_id": str(user_id),
|
||||
"user_uuid": str(user_uuid),
|
||||
"credential_id": credential.credential_id.hex(),
|
||||
"message": "New credential added successfully",
|
||||
}
|
||||
@@ -133,103 +141,8 @@ async def websocket_register_add(ws: WebSocket):
|
||||
await ws.send_json({"error": "Internal Server Error"})
|
||||
|
||||
|
||||
@ws_app.websocket("/add_device_credential")
|
||||
async def websocket_add_device_credential(ws: WebSocket, token: str):
|
||||
"""Add a new credential for an existing user via device addition token."""
|
||||
await ws.accept()
|
||||
origin = ws.headers.get("origin")
|
||||
try:
|
||||
reset_token = await sql.get_session(token)
|
||||
if not reset_token:
|
||||
await ws.send_json({"error": "Invalid or expired device addition token"})
|
||||
return
|
||||
|
||||
# Get user information
|
||||
user = await sql.get_user_by_id(reset_token.user_id)
|
||||
|
||||
# WebAuthn registration
|
||||
# Fetch challenge IDs for the user
|
||||
challenge_ids = await sql.get_user_credentials(reset_token.user_id)
|
||||
|
||||
credential = await register_chat(
|
||||
ws, reset_token.user_id, user.user_name, challenge_ids, origin=origin
|
||||
)
|
||||
|
||||
# Store the new credential in the database
|
||||
await sql.create_credential_for_user(credential)
|
||||
|
||||
# Delete the device addition token (it's now used)
|
||||
await sql.delete_reset_token(token)
|
||||
|
||||
await ws.send_json(
|
||||
{
|
||||
"status": "success",
|
||||
"user_id": str(reset_token.user_id),
|
||||
"credential_id": credential.credential_id.hex(),
|
||||
"message": "New credential added successfully via device addition token",
|
||||
}
|
||||
)
|
||||
except ValueError as e:
|
||||
await ws.send_json({"error": str(e)})
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
except Exception:
|
||||
logging.exception("Internal Server Error")
|
||||
await ws.send_json({"error": "Internal Server Error"})
|
||||
|
||||
|
||||
@ws_app.websocket("/add_device_credential_session")
|
||||
async def websocket_add_device_credential_session(ws: WebSocket):
|
||||
"""Add a new credential for an existing user via device addition session."""
|
||||
await ws.accept()
|
||||
origin = ws.headers.get("origin")
|
||||
try:
|
||||
# Get device addition user ID from session cookie
|
||||
cookie_header = ws.headers.get("cookie", "")
|
||||
from .session import get_device_addition_user_id_from_cookie
|
||||
|
||||
user_id = await get_device_addition_user_id_from_cookie(cookie_header)
|
||||
|
||||
if not user_id:
|
||||
await ws.send_json({"error": "No valid device addition session found"})
|
||||
return
|
||||
|
||||
# Get user information
|
||||
user = await sql.get_user_by_id(user_id)
|
||||
if not user:
|
||||
await ws.send_json({"error": "User not found"})
|
||||
return
|
||||
|
||||
# WebAuthn registration
|
||||
# Fetch challenge IDs for the user
|
||||
challenge_ids = await sql.get_user_credentials(user_id)
|
||||
|
||||
credential = await register_chat(
|
||||
ws, user_id, user.user_name, challenge_ids, origin=origin
|
||||
)
|
||||
|
||||
# Store the new credential in the database
|
||||
await sql.create_credential_for_user(credential)
|
||||
|
||||
await ws.send_json(
|
||||
{
|
||||
"status": "success",
|
||||
"user_id": str(user_id),
|
||||
"credential_id": credential.credential_id.hex(),
|
||||
"message": "New credential added successfully via device addition session",
|
||||
}
|
||||
)
|
||||
except ValueError as e:
|
||||
await ws.send_json({"error": str(e)})
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
except Exception:
|
||||
logging.exception("Internal Server Error")
|
||||
await ws.send_json({"error": "Internal Server Error"})
|
||||
|
||||
|
||||
@ws_app.websocket("/authenticate")
|
||||
async def websocket_authenticate(ws: WebSocket):
|
||||
@app.websocket("/authenticate")
|
||||
async def websocket_authenticate(request: Request, ws: WebSocket):
|
||||
await ws.accept()
|
||||
origin = ws.headers.get("origin")
|
||||
try:
|
||||
@@ -242,19 +155,21 @@ async def websocket_authenticate(ws: WebSocket):
|
||||
# Verify the credential matches the stored data
|
||||
passkey.auth_verify(credential, challenge, stored_cred, origin=origin)
|
||||
# Update both credential and user's last_seen timestamp
|
||||
await sql.login_user(stored_cred.user_id, stored_cred)
|
||||
await sql.login_user(stored_cred.user_uuid, stored_cred)
|
||||
|
||||
# Create a session token for the authenticated user
|
||||
client_info = get_client_info_from_websocket(ws)
|
||||
session_token = await create_session_token(
|
||||
stored_cred.user_id, stored_cred.credential_id, client_info
|
||||
assert stored_cred.uuid is not None
|
||||
token = await create_session(
|
||||
user_uuid=stored_cred.user_uuid,
|
||||
info=infodict(request, "auth"),
|
||||
credential_uuid=stored_cred.uuid,
|
||||
)
|
||||
|
||||
await ws.send_json(
|
||||
{
|
||||
"status": "success",
|
||||
"user_id": str(stored_cred.user_id),
|
||||
"session_token": session_token,
|
||||
"user_uuid": str(stored_cred.user_uuid),
|
||||
"session_token": token,
|
||||
}
|
||||
)
|
||||
except (ValueError, InvalidAuthenticationResponse) as e:
|
||||
|
||||
Reference in New Issue
Block a user