M0: backend skeleton — Quart factory, async DB, auth, ACL spine, migrations

Foundation & Identity backend for ThoughtSync:
- Quart app factory (create_app) with /api/health + SPA history-fallback
- async SQLAlchemy 2.0 + asyncpg engine/session (lazy; boots without a DB)
- native email+password auth via signed-cookie session (register/login/logout/me
  + login_required guard); bcrypt password hashing (72-byte safe)
- multi-user sharing-ACL spine (rule 47): users, groups, group_members, and a
  polymorphic shares table + visible_to_user() SQL predicate (owner OR direct
  share OR group share) that M1's notes will scope through
- Alembic async env (adapted from family pattern) + 0001 foundation migration
- DB-free unit tests (app/health/auth-guard, password roundtrip, ACL compile)

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:
2026-07-19 13:09:37 -04:00
co-authored by Claude Opus 4.8
parent cefffa2bd6
commit 04e3ab20cf
21 changed files with 734 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
"""ThoughtSync — self-hosted personal thought-capture web app (FabledSword family)."""
__version__ = "0.1.0"
+46
View File
@@ -0,0 +1,46 @@
from __future__ import annotations
import uuid
from sqlalchemy import ColumnElement, exists, or_, select
from .models.group import GroupMember
from .models.share import Share
def visible_to_user(
resource_type: str,
owner_column,
resource_id_column,
user_id: uuid.UUID,
) -> ColumnElement[bool]:
"""Boolean SQL predicate: is this resource visible to ``user_id``?
A resource is visible if the user OWNS it, OR it is shared DIRECTLY with the
user, OR it is shared with a GROUP the user belongs to. Scope every read (and
mutation) of shareable user data through this — never assume a single operator
(family rule 47).
Usage (M1+), e.g. for notes::
stmt = select(Note).where(visible_to_user("note", Note.owner_id, Note.id, uid))
Args:
resource_type: the ``Share.resource_type`` tag for this entity (e.g. "note").
owner_column: the resource's owner column (e.g. ``Note.owner_id``).
resource_id_column: the resource's primary-key column (e.g. ``Note.id``).
user_id: the viewer.
"""
user_group_ids = select(GroupMember.group_id).where(GroupMember.user_id == user_id)
direct_share = exists().where(
Share.resource_type == resource_type,
Share.resource_id == resource_id_column,
Share.shared_with_user_id == user_id,
)
group_share = exists().where(
Share.resource_type == resource_type,
Share.resource_id == resource_id_column,
Share.shared_with_group_id.in_(user_group_ids),
)
return or_(owner_column == user_id, direct_share, group_share)
+43
View File
@@ -0,0 +1,43 @@
from __future__ import annotations
import os
from quart import Quart, jsonify, send_from_directory
from . import __version__
from .auth import bp as auth_bp
from .config import Config
STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
def create_app() -> Quart:
# static_folder=None: the SPA catch-all below owns static serving instead of
# Quart's default /static handler.
app = Quart(__name__, static_folder=None)
app.secret_key = Config.secret_key()
app.config["APP_VERSION"] = os.environ.get("APP_VERSION", __version__)
app.register_blueprint(auth_bp)
@app.get("/api/health")
async def health():
return jsonify({"status": "ok", "version": app.config["APP_VERSION"]})
# Serve the built Vue SPA (baked into static/ by the Docker build) with a
# history-fallback to index.html. In dev the Vite server proxies /api here, so
# a missing static/ dir is expected and simply 404s the frontend.
@app.get("/", defaults={"path": ""})
@app.get("/<path:path>")
async def spa(path: str):
if path.startswith("api/"):
return jsonify({"error": "not found"}), 404
candidate = os.path.join(STATIC_DIR, path)
if path and os.path.isfile(candidate):
return await send_from_directory(STATIC_DIR, path)
index = os.path.join(STATIC_DIR, "index.html")
if os.path.isfile(index):
return await send_from_directory(STATIC_DIR, "index.html")
return jsonify({"error": "frontend not built"}), 404
return app
+100
View File
@@ -0,0 +1,100 @@
from __future__ import annotations
import functools
import uuid
from quart import Blueprint, g, jsonify, request, session
from sqlalchemy import select
from .db import session_scope
from .models.user import User
from .security import hash_password, verify_password
bp = Blueprint("auth", __name__, url_prefix="/api/auth")
SESSION_KEY = "user_id"
MIN_PASSWORD_LEN = 8
def _serialize_user(user: User) -> dict:
return {
"id": str(user.id),
"email": user.email,
"display_name": user.display_name,
"email_verified": user.email_verified,
}
def login_required(fn):
"""Guard: 401 unless a valid session is present. Sets g.user_id for the view."""
@functools.wraps(fn)
async def wrapper(*args, **kwargs):
raw = session.get(SESSION_KEY)
if not raw:
return jsonify({"error": "authentication required"}), 401
try:
g.user_id = uuid.UUID(raw)
except (ValueError, TypeError):
session.pop(SESSION_KEY, None)
return jsonify({"error": "authentication required"}), 401
return await fn(*args, **kwargs)
return wrapper
@bp.post("/register")
async def register():
data = await request.get_json(silent=True) or {}
email = (data.get("email") or "").strip().lower()
password = data.get("password") or ""
display_name = (data.get("display_name") or "").strip()
if not email or "@" not in email:
return jsonify({"error": "a valid email is required"}), 400
if len(password) < MIN_PASSWORD_LEN:
return jsonify({"error": f"password must be at least {MIN_PASSWORD_LEN} characters"}), 400
if not display_name:
display_name = email.split("@", 1)[0]
async with session_scope() as db:
existing = await db.scalar(select(User).where(User.email == email))
if existing is not None:
return jsonify({"error": "an account with that email already exists"}), 409
user = User(email=email, password_hash=hash_password(password), display_name=display_name)
db.add(user)
await db.commit()
await db.refresh(user)
session[SESSION_KEY] = str(user.id)
return jsonify(_serialize_user(user)), 201
@bp.post("/login")
async def login():
data = await request.get_json(silent=True) or {}
email = (data.get("email") or "").strip().lower()
password = data.get("password") or ""
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
session[SESSION_KEY] = str(user.id)
return jsonify(_serialize_user(user))
@bp.post("/logout")
async def logout():
session.pop(SESSION_KEY, None)
return jsonify({"ok": True})
@bp.get("/me")
@login_required
async def me():
async with session_scope() as db:
user = await db.get(User, g.user_id)
if user is None:
session.pop(SESSION_KEY, None)
return jsonify({"error": "authentication required"}), 401
return jsonify(_serialize_user(user))
+52
View File
@@ -0,0 +1,52 @@
from __future__ import annotations
import os
import secrets
from pathlib import Path
class Config:
"""Runtime configuration.
Values come from environment variables with working local-dev defaults, so the
app boots with zero configuration (family rule 26 — integrations default to
working, never coerce setup). As the product grows, anything an operator wants
to tune moves into a DB-backed Settings UI (rule 25); env is bootstrap only.
"""
# Where runtime-generated secrets + uploaded media live.
DATA_DIR = os.environ.get("THOUGHTSYNC_DATA_DIR", "/var/thoughtsync")
# Empty -> defaults to <DATA_DIR>/media (see media_root()).
MEDIA_ROOT = os.environ.get("THOUGHTSYNC_MEDIA_ROOT", "")
# postgresql+asyncpg URL. Mirrors alembic.ini's local-dev default.
DATABASE_URL = os.environ.get(
"THOUGHTSYNC_DATABASE_URL",
"postgresql+asyncpg://thoughtsync:thoughtsync@localhost:5432/thoughtsync",
)
# Auth session cookie: a capture app should rarely log you out, so keep it long.
AUTH_TTL_SECONDS = 60 * 60 * 24 * 30 # 30 days
@classmethod
def media_root(cls) -> Path:
return Path(cls.MEDIA_ROOT or os.path.join(cls.DATA_DIR, "media"))
@classmethod
def secret_key(cls) -> bytes:
"""Secret used to sign the auth session cookie.
Read from env if set; otherwise read/generate a persistent key file under
DATA_DIR so signed sessions survive restarts (no forced re-login on deploy).
"""
env = os.environ.get("THOUGHTSYNC_SECRET_KEY")
if env:
return env.encode()
data_dir = Path(cls.DATA_DIR)
data_dir.mkdir(parents=True, exist_ok=True)
key_file = data_dir / "secret_key"
if key_file.exists():
return key_file.read_bytes()
key = secrets.token_bytes(32)
key_file.write_bytes(key)
return key
+41
View File
@@ -0,0 +1,41 @@
from __future__ import annotations
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker, create_async_engine
from .config import Config
_engine: AsyncEngine | None = None
_sessionmaker: async_sessionmaker[AsyncSession] | None = None
def get_engine() -> AsyncEngine:
"""Lazily create the process-wide async engine.
Lazy so the app (and unit tests) can import/boot without a live database —
only routes that actually touch data open a connection.
"""
global _engine, _sessionmaker
if _engine is None:
_engine = create_async_engine(Config.DATABASE_URL, pool_pre_ping=True)
_sessionmaker = async_sessionmaker(_engine, expire_on_commit=False)
return _engine
def get_sessionmaker() -> async_sessionmaker[AsyncSession]:
if _sessionmaker is None:
get_engine()
assert _sessionmaker is not None
return _sessionmaker
def session_scope() -> AsyncSession:
"""Open a new AsyncSession. Use as `async with session_scope() as db: ...`."""
return get_sessionmaker()()
async def dispose_engine() -> None:
global _engine, _sessionmaker
if _engine is not None:
await _engine.dispose()
_engine = None
_sessionmaker = None
+7
View File
@@ -0,0 +1,7 @@
from __future__ import annotations
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
"""Declarative base for all ORM models. Alembic reads Base.metadata."""
+6
View File
@@ -0,0 +1,6 @@
"""Import every model module so Base.metadata is fully populated for Alembic.
Imported for side effects only (model registration on Base.metadata).
"""
from . import group, share, user # noqa: F401
+39
View File
@@ -0,0 +1,39 @@
from __future__ import annotations
import uuid
from datetime import datetime
from sqlalchemy import DateTime, ForeignKey, Text, UniqueConstraint, func
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column
from . import Base
class Group(Base):
"""A named set of users. Sharing a resource with a group grants it to every
member (see thoughtsync.acl.visible_to_user)."""
__tablename__ = "groups"
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
name: Mapped[str] = mapped_column(Text(), nullable=False)
owner_id: Mapped[uuid.UUID | None] = mapped_column(
UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True
)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now())
class GroupMember(Base):
__tablename__ = "group_members"
__table_args__ = (UniqueConstraint("group_id", "user_id", name="uq_group_members_group_user"),)
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
group_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True), ForeignKey("groups.id", ondelete="CASCADE"), nullable=False
)
user_id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False
)
role: Mapped[str] = mapped_column(Text(), nullable=False, server_default="member")
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now())
+41
View File
@@ -0,0 +1,41 @@
from __future__ import annotations
import uuid
from datetime import datetime
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Text, func
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column
from . import Base
class Share(Base):
"""An additional access grant on one resource (identified by type + id).
A resource's OWNER is tracked on the resource row itself (its owner_id column);
this table records grants BEYOND the owner — to a single user or to a whole
group. It is polymorphic (resource_type + resource_id) so every future
shareable entity (notes first, in M1) reuses one table and one ACL predicate.
Exactly one of shared_with_user_id / shared_with_group_id is set.
"""
__tablename__ = "shares"
__table_args__ = (
CheckConstraint(
"(shared_with_user_id IS NOT NULL) <> (shared_with_group_id IS NOT NULL)",
name="ck_shares_one_target",
),
)
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
resource_type: Mapped[str] = mapped_column(Text(), nullable=False)
resource_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
shared_with_user_id: Mapped[uuid.UUID | None] = mapped_column(
UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=True
)
shared_with_group_id: Mapped[uuid.UUID | None] = mapped_column(
UUID(as_uuid=True), ForeignKey("groups.id", ondelete="CASCADE"), nullable=True
)
permission: Mapped[str] = mapped_column(Text(), nullable=False, server_default="view")
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now())
+25
View File
@@ -0,0 +1,25 @@
from __future__ import annotations
import uuid
from datetime import datetime
from sqlalchemy import Boolean, DateTime, Text, func
from sqlalchemy.dialects.postgresql import CITEXT, UUID
from sqlalchemy.orm import Mapped, mapped_column
from . import Base
class User(Base):
__tablename__ = "users"
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
# CITEXT so lookups/uniqueness are case-insensitive without lower() everywhere.
email: Mapped[str] = mapped_column(CITEXT(), nullable=False, unique=True)
email_verified: Mapped[bool] = mapped_column(Boolean(), nullable=False, server_default=func.false())
# Nullable: leaves room for external-identity-only accounts later (rule 26).
password_hash: Mapped[str | None] = mapped_column(Text(), nullable=True)
display_name: Mapped[str] = mapped_column(Text(), nullable=False)
avatar_path: Mapped[str | None] = mapped_column(Text(), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now())
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now())
+18
View File
@@ -0,0 +1,18 @@
from __future__ import annotations
import bcrypt
# bcrypt hashes at most 72 bytes and bcrypt>=4 raises on longer input, so we
# truncate defensively — long passphrases stay valid instead of erroring.
_MAX_BCRYPT_BYTES = 72
def hash_password(password: str) -> str:
return bcrypt.hashpw(password.encode("utf-8")[:_MAX_BCRYPT_BYTES], bcrypt.gensalt()).decode("utf-8")
def verify_password(password: str, password_hash: str) -> bool:
try:
return bcrypt.checkpw(password.encode("utf-8")[:_MAX_BCRYPT_BYTES], password_hash.encode("utf-8"))
except (ValueError, TypeError):
return False