Sync 2: device-token bearer auth + linked-devices UI (M8)
Native clients (Tauri/Android) authenticate sync with a long-lived device bearer token, alongside the existing web session cookie. Backend: - security.py: generate_token() (secrets.token_urlsafe) + hash_token() (SHA-256 — device tokens are already high-entropy, so no slow KDF; keeps per-request bearer auth cheap). Only the hash is stored. - device_tokens table (migration 0016): id, user_id, token_hash (unique), name, created_at, last_used_at. - login_required now accepts `Authorization: Bearer <token>` OR the session cookie. Session path stays DB-free (fast); bearer path looks up the token hash, sets g.user_id, and stamps last_used_at. - Endpoints: POST /api/auth/device-login (public; email+password → token, the native first-link flow), POST /api/auth/devices (session/bearer → token, web "link a device"), GET /api/auth/devices (list), DELETE /api/auth/devices/<id> (revoke). All owner-scoped; token shown once. Frontend: - Per-user (not admin) /account view "Linked devices": create a token (one-time reveal + copy), list devices (name, linked/last-synced), revoke with confirm. Top-bar device icon for all users; devices Pinia store. Tests (DB-free): token hash determinism + uniqueness; device endpoints auth-guard (401 without auth, before DB); device-login input validation. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FRgehjoz7Yv8LkUfADxACm
This commit is contained in:
+117
-2
@@ -2,19 +2,22 @@ from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from quart import Blueprint, g, jsonify, request, session
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from .db import session_scope
|
||||
from .models.device_token import DeviceToken
|
||||
from .models.user import User
|
||||
from .security import hash_password, verify_password
|
||||
from .security import generate_token, hash_password, hash_token, verify_password
|
||||
from .settings import get_setting
|
||||
|
||||
bp = Blueprint("auth", __name__, url_prefix="/api/auth")
|
||||
|
||||
SESSION_KEY = "user_id"
|
||||
MIN_PASSWORD_LEN = 8
|
||||
DEVICE_NAME_CAP = 100
|
||||
|
||||
|
||||
def _serialize_user(user: User) -> dict:
|
||||
@@ -38,12 +41,40 @@ def _session_user_id() -> uuid.UUID | None:
|
||||
return None
|
||||
|
||||
|
||||
def _bearer_token() -> str | None:
|
||||
"""Extract a `Authorization: Bearer <token>` device token, if present."""
|
||||
header = request.headers.get("Authorization", "")
|
||||
if header.startswith("Bearer "):
|
||||
return header[7:].strip() or None
|
||||
return None
|
||||
|
||||
|
||||
async def _user_id_from_bearer() -> uuid.UUID | None:
|
||||
"""Resolve a device bearer token to its owner, refreshing last_used_at. Native
|
||||
clients (Tauri/Android) authenticate sync this way instead of a session cookie."""
|
||||
token = _bearer_token()
|
||||
if not token:
|
||||
return None
|
||||
async with session_scope() as db:
|
||||
row = await db.scalar(select(DeviceToken).where(DeviceToken.token_hash == hash_token(token)))
|
||||
if row is None:
|
||||
return None
|
||||
# Cheap liveness stamp; sync calls are user-initiated/periodic, not per-keystroke.
|
||||
row.last_used_at = datetime.now(timezone.utc)
|
||||
await db.commit()
|
||||
return row.user_id
|
||||
|
||||
|
||||
def login_required(fn):
|
||||
"""Guard: 401 unless a valid session is present. Sets g.user_id for the view."""
|
||||
"""Guard: 401 unless authenticated. Accepts a web session cookie OR a device
|
||||
bearer token (native clients). Sets g.user_id for the view. The session path
|
||||
stays DB-free (fast); only bearer auth does a token lookup."""
|
||||
|
||||
@functools.wraps(fn)
|
||||
async def wrapper(*args, **kwargs):
|
||||
uid = _session_user_id()
|
||||
if uid is None:
|
||||
uid = await _user_id_from_bearer()
|
||||
if uid is None:
|
||||
return jsonify({"error": "authentication required"}), 401
|
||||
g.user_id = uid
|
||||
@@ -142,3 +173,87 @@ async def me():
|
||||
session.pop(SESSION_KEY, None)
|
||||
return jsonify({"error": "authentication required"}), 401
|
||||
return jsonify(_serialize_user(user))
|
||||
|
||||
|
||||
# --- Device (bearer) tokens for native clients — M8 sync hub ---
|
||||
|
||||
|
||||
def _serialize_device(d: DeviceToken) -> dict:
|
||||
return {
|
||||
"id": str(d.id),
|
||||
"name": d.name,
|
||||
"created_at": d.created_at.isoformat() if d.created_at else None,
|
||||
"last_used_at": d.last_used_at.isoformat() if d.last_used_at else None,
|
||||
}
|
||||
|
||||
|
||||
async def _issue_device_token(db, user_id: uuid.UUID, name: str) -> tuple[DeviceToken, str]:
|
||||
"""Create a device token; return the row plus the ONE-TIME plaintext token."""
|
||||
token = generate_token()
|
||||
row = DeviceToken(
|
||||
user_id=user_id,
|
||||
token_hash=hash_token(token),
|
||||
name=(name or "").strip()[:DEVICE_NAME_CAP] or "Device",
|
||||
)
|
||||
db.add(row)
|
||||
await db.flush()
|
||||
return row, token
|
||||
|
||||
|
||||
@bp.post("/device-login")
|
||||
async def device_login():
|
||||
"""Native first-link: exchange email+password for a device bearer token. Public
|
||||
(no existing session) — this is how a fresh native install authenticates."""
|
||||
data = await request.get_json(silent=True) or {}
|
||||
email = (data.get("email") or "").strip().lower()
|
||||
password = data.get("password") or ""
|
||||
if not email or not password:
|
||||
return jsonify({"error": "email and password are required"}), 400
|
||||
async with session_scope() as db:
|
||||
user = await db.scalar(select(User).where(User.email == email))
|
||||
if user is None or not user.password_hash or not verify_password(password, user.password_hash):
|
||||
return jsonify({"error": "invalid email or password"}), 401
|
||||
row, token = await _issue_device_token(db, user.id, data.get("name") or "")
|
||||
await db.commit()
|
||||
return jsonify({"token": token, "device": _serialize_device(row), "user": _serialize_user(user)}), 201
|
||||
|
||||
|
||||
@bp.post("/devices")
|
||||
@login_required
|
||||
async def create_device():
|
||||
"""Issue a device token for the already-authenticated user (web 'Link a device')."""
|
||||
data = await request.get_json(silent=True) or {}
|
||||
async with session_scope() as db:
|
||||
row, token = await _issue_device_token(db, g.user_id, data.get("name") or "")
|
||||
await db.commit()
|
||||
return jsonify({"token": token, "device": _serialize_device(row)}), 201
|
||||
|
||||
|
||||
@bp.get("/devices")
|
||||
@login_required
|
||||
async def list_devices():
|
||||
async with session_scope() as db:
|
||||
rows = (
|
||||
await db.scalars(
|
||||
select(DeviceToken).where(DeviceToken.user_id == g.user_id).order_by(DeviceToken.created_at.desc())
|
||||
)
|
||||
).all()
|
||||
return jsonify({"devices": [_serialize_device(d) for d in rows]})
|
||||
|
||||
|
||||
@bp.delete("/devices/<device_id>")
|
||||
@login_required
|
||||
async def revoke_device(device_id: str):
|
||||
try:
|
||||
did = uuid.UUID(device_id)
|
||||
except (ValueError, TypeError):
|
||||
return jsonify({"error": "not found"}), 404
|
||||
async with session_scope() as db:
|
||||
row = await db.scalar(
|
||||
select(DeviceToken).where(DeviceToken.id == did, DeviceToken.user_id == g.user_id)
|
||||
)
|
||||
if row is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
await db.delete(row)
|
||||
await db.commit()
|
||||
return jsonify({"ok": True})
|
||||
|
||||
@@ -4,6 +4,7 @@ Imported for side effects only (model registration on Base.metadata).
|
||||
"""
|
||||
|
||||
from . import ( # noqa: F401
|
||||
device_token,
|
||||
group,
|
||||
label,
|
||||
note,
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Text, func
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from . import Base
|
||||
|
||||
|
||||
class DeviceToken(Base):
|
||||
"""A long-lived bearer token a native client (Tauri/Android) uses to authenticate
|
||||
sync. Only the token's SHA-256 hash is stored; the plaintext is shown once at
|
||||
creation. Owner-scoped and individually revocable."""
|
||||
|
||||
__tablename__ = "device_tokens"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
token_hash: Mapped[str] = mapped_column(Text(), nullable=False, unique=True)
|
||||
name: Mapped[str] = mapped_column(Text(), nullable=False, server_default="")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
last_used_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
@@ -1,5 +1,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
|
||||
import bcrypt
|
||||
|
||||
# bcrypt hashes at most 72 bytes and bcrypt>=4 raises on longer input, so we
|
||||
@@ -16,3 +19,15 @@ def verify_password(password: str, password_hash: str) -> bool:
|
||||
return bcrypt.checkpw(password.encode("utf-8")[:_MAX_BCRYPT_BYTES], password_hash.encode("utf-8"))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def generate_token() -> str:
|
||||
"""A high-entropy opaque device (bearer) token, URL-safe so it pastes cleanly."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def hash_token(token: str) -> str:
|
||||
"""One-way hash for device-token LOOKUP. A device token is already high-entropy
|
||||
random, so a plain SHA-256 is enough (no slow KDF like passwords need) — which
|
||||
keeps per-request bearer auth cheap. Only this hash is stored server-side."""
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
Reference in New Issue
Block a user