Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ Rules for any AI coding agent working in this repository. Human contributors: se

LibreLibrary is a self-hosted personal library server with a web interface, a versioned REST API, and a built-in MCP server. The design is in `docs/design/architecture.md`; read it rather than relying on a copy here.

**Status:** early development. The core exists: the data model, migrations, the REST API, local sign-in, tokens, and the policy layer. There is no web interface yet.
**Status:** early development. The core exists: the data model, migrations, the REST API, local sign-in, tokens, and the policy layer. The web interface has cookie sessions, CSRF protection, sign-in, and pages for works, editions, libraries, and copies. The rest of Phase 3 is still to build.

## Repository layout

- `src/librelibrary/`: the application.
- `api/v1/`: thin REST routes.
- `ui/`: server-rendered pages. Each route uses `@ui_route` to declare the API operation it fulfills.
- `services/`: business logic. Each public function declares a policy action with `@policy_action`.
- `authz/`: the policy layer and query scoping.
- `auth/`: passwords, tokens, and sign-in rate limits.
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,6 @@ The format is based on [Keep a Changelog 1.1.0](https://keepachangelog.com/en/1.
- Four privacy levels (personal, library, group, and server), groups of users and libraries, and admin transfer of library ownership.
- Database migrations that run at startup, on SQLite and PostgreSQL.
- The `librelibrary` command, with `create-admin` and `migrate`.
- A web interface foundation: browser sign-in and sign-out with server-side cookie sessions, CSRF protection, a searchable, paged list of works, and work pages to view, add, edit, and delete.
- Web pages for libraries, copies, and editions: list and open the libraries you belong to, add and change a library and its settings, add copies from an edition, and edit or delete a copy. Each page offers only what your role allows.
- Library member lists in the API now include each member's display name.
2 changes: 1 addition & 1 deletion docs/design/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ Roles are `admin`, `member`, and `guest` (read-only). Library roles (owner, edit

### Web protections

- **Cookie sessions:** arrive in Phase 3 with the pages that use them. Server-side, `Secure`, `HttpOnly`, `SameSite=Lax`, with a synchronizer CSRF token on every state-changing request. Bearer-token requests don't use cookies and skip CSRF.
- **Cookie sessions:** arrive in Phase 3 with the pages that use them. Server-side, `Secure`, `HttpOnly`, `SameSite=Lax`, with a synchronizer CSRF token on every state-changing request. Bearer-token requests don't use cookies and skip CSRF. **Built:** the `web_session` table holds a hash of the cookie value and the session's CSRF token. A page accepts only the cookie, and the API accepts only a bearer token, so one can't be used for the other. The sign-in form has no session yet, so it uses a double-submit token: a short-lived `SameSite=Lax` cookie that the form must repeat. A session lasts 14 days, set by `LIBRELIBRARY_SESSION_LIFETIME_DAYS`, and signing out deletes it on the server.
- **Rate limiting:** the [`limits`](https://pypi.org/pypi/limits/json) library (MIT) in middleware, per IP and per username for sign-in. slowapi is not used because [it does not declare 3.14 support](https://pypi.org/pypi/slowapi/json). **Decided:** counters live in the application's database, so limits hold across workers with no new service. Each counted attempt writes a row, so per-token limits on ordinary API requests are not built yet, and need their own decision before they are.
- **Reverse proxy:** forwarded headers are honored only from `TRUSTED_PROXIES`. `BASE_URL` sets generated links, including a path prefix.
- **Importers:** size limits, no XML entity expansion, and outbound fetches restricted to approved providers, blocking private addresses unless an admin allows them.
Expand Down
8 changes: 6 additions & 2 deletions docs/getting-started.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Getting started

LibreLibrary has no release yet. These steps work from a checkout of the repository, and they cover the REST API only, because the web interface doesn't exist yet.
LibreLibrary has no release yet. These steps work from a checkout of the repository, and they cover the REST API and the first pages of the web interface.

## Run the server

Expand All @@ -23,7 +23,11 @@ docker exec --interactive --tty librelibrary \
librelibrary create-admin --username admin
```

## Sign in
## Sign in on the web

Open `http://localhost:8000/` and sign in with the admin's username and password. The pages so far are the sign-in form and a searchable, paged list of works. The session cookie is marked `Secure`, so browsers send it only over HTTPS. Chrome and Firefox also accept it on `localhost`, but a server on another host needs HTTPS in front of it.

## Sign in to the API

Sign in to get a bearer token, and send that token with each request:

Expand Down
35 changes: 35 additions & 0 deletions migrations/versions/0002_add_web_sessions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""add web sessions

Revision ID: 0002
Revises: 0001
"""

from alembic import op
import sqlalchemy as sa


revision = '0002'
down_revision = '0001'
branch_labels = None
depends_on = None


def upgrade() -> None:
"""Apply this migration."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('web_session',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('session_hash', sa.String(length=64), nullable=False),
sa.Column('csrf_token', sa.String(length=64), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('expires_at', sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['user_account.id'], name=op.f('fk_web_session_user_id_user_account'), ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id', name=op.f('pk_web_session')),
sa.UniqueConstraint('session_hash', name=op.f('uq_web_session_session_hash'))
)
with op.batch_alter_table('web_session', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_web_session_expires_at'), ['expires_at'], unique=False)
batch_op.create_index(batch_op.f('ix_web_session_user_id'), ['user_id'], unique=False)

# ### end Alembic commands ###
9 changes: 7 additions & 2 deletions openapi/openapi.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ dependencies = [
"alembic==1.20.1",
"argon2-cffi==25.1.0",
"fastapi==0.162.0",
"jinja2==3.1.6",
"limits==5.8.0",
"pg8000==1.31.6",
"pydantic-settings==2.16.2",
"python-multipart==0.0.33",
"sqlalchemy==2.1.6",
"structlog==26.1.0",
"uvicorn==0.54.0",
Expand Down Expand Up @@ -57,7 +59,7 @@ select = ["B", "D", "E", "F", "I", "N", "S", "UP", "W"]
convention = "pep257"

[tool.ruff.lint.per-file-ignores]
"tests/**" = ["S101"]
"tests/**" = ["S101", "S105", "S106"]
"tools/**" = ["S603"]
"noxfile.py" = ["S603"]

Expand Down
7 changes: 6 additions & 1 deletion src/librelibrary/api/v1/accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,18 @@ def login(
) -> TokenCreatedOut:
"""Check a username and password, and issue a bearer token."""
limiter = cast(RateLimiter, request.app.state.login_limiter)
issued = accounts.login(
user = accounts.sign_in(
session,
limiter=limiter,
settings=settings,
ip=client_ip(request, settings),
username=payload.username,
password=payload.password,
)
issued = accounts.issue_login_token(
session,
settings=settings,
user=user,
token_name=payload.token_name,
scopes=[str(scope) for scope in payload.scopes],
)
Expand Down
95 changes: 78 additions & 17 deletions src/librelibrary/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
import structlog
from fastapi import APIRouter, FastAPI, Request, Response, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from limits.strategies import FixedWindowRateLimiter
from sqlalchemy import Engine
from sqlalchemy.exc import DBAPIError
Expand All @@ -24,6 +25,11 @@
from librelibrary.proxy import ForwardedProtoMiddleware
from librelibrary.schemas import ErrorOut
from librelibrary.settings import Settings
from librelibrary.ui import copies as copy_pages
from librelibrary.ui import libraries as library_pages
from librelibrary.ui import pages, works
from librelibrary.ui.deps import LoginRequired
from librelibrary.ui.templating import UI_DIRECTORY, templates

_ERROR_RESPONSES: dict[int | str, dict[str, Any]] = {
status.HTTP_401_UNAUTHORIZED: {"model": ErrorOut},
Expand All @@ -33,42 +39,80 @@
}


def _error(code: int, detail: str, **headers: str) -> JSONResponse:
return JSONResponse({"detail": detail}, status_code=code, headers=headers or None)
_PAGE_ERRORS = {
401: ("Sign in required", "Sign in to continue."),
403: ("Not allowed", "You can't do that."),
404: ("Not found", "That page doesn't exist, or you can't see it."),
409: ("Conflict", "That conflicts with the current state."),
422: ("Invalid request", "Something in the request wasn't valid."),
429: ("Too many attempts", "Wait a minute and try again."),
500: ("Something went wrong", "The server hit an error."),
}
_SECURITY_HEADERS = {
"Content-Security-Policy": (
"default-src 'self'; frame-ancestors 'none'; form-action 'self'; "
"base-uri 'none'"
),
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "same-origin",
}


def _error(request: Request, code: int, detail: str, **headers: str) -> Response:
"""Answer the API with JSON, and the web interface with a page."""
if request.url.path.startswith("/api/"):
return JSONResponse(
{"detail": detail}, status_code=code, headers=headers or None
)
heading, message = _PAGE_ERRORS[code]
return templates.TemplateResponse(
request,
"error.html",
{"heading": heading, "message": message},
status_code=code,
)


def _add_error_handlers(app: FastAPI) -> None:
@app.exception_handler(LoginRequired)
async def login_required(_request: Request, _error_: Exception) -> Response:
return RedirectResponse("/login", status_code=303)

@app.exception_handler(Unauthenticated)
async def unauthenticated(_request: Request, _error_: Exception) -> Response:
return _error(401, "Not authenticated", **{"WWW-Authenticate": "Bearer"})
async def unauthenticated(request: Request, _error_: Exception) -> Response:
return _error(
request, 401, "Not authenticated", **{"WWW-Authenticate": "Bearer"}
)

@app.exception_handler(Denied)
async def denied(_request: Request, _error_: Exception) -> Response:
return _error(403, "Not allowed")
async def denied(request: Request, _error_: Exception) -> Response:
return _error(request, 403, "Not allowed")

@app.exception_handler(NotFound)
async def not_found(_request: Request, _error_: Exception) -> Response:
return _error(404, "Not found")
async def not_found(request: Request, _error_: Exception) -> Response:
return _error(request, 404, "Not found")

@app.exception_handler(Conflict)
async def conflict(_request: Request, _error_: Exception) -> Response:
return _error(409, "Conflict with the current state")
async def conflict(request: Request, _error_: Exception) -> Response:
return _error(request, 409, "Conflict with the current state")

@app.exception_handler(RateLimited)
async def rate_limited(_request: Request, _error_: Exception) -> Response:
return _error(429, "Too many attempts. Try again later.")
async def rate_limited(request: Request, _error_: Exception) -> Response:
return _error(request, 429, "Too many attempts. Try again later.")

@app.exception_handler(DBAPIError)
async def database_error(_request: Request, error: Exception) -> Response:
async def database_error(request: Request, error: Exception) -> Response:
if isinstance(error, DBAPIError) and is_constraint_violation(error):
return _error(409, "Conflict with the current state")
return _error(request, 409, "Conflict with the current state")
structlog.get_logger().error("database_error", kind=type(error).__name__)
return _error(500, "Internal server error")
return _error(request, 500, "Internal server error")

@app.exception_handler(RequestValidationError)
async def invalid(_request: Request, error: Exception) -> Response:
async def invalid(request: Request, error: Exception) -> Response:
"""Describe what is wrong without echoing the input, which may be secret."""
assert isinstance(error, RequestValidationError) # noqa: S101
if not request.url.path.startswith("/api/"):
return _error(request, 422, "Invalid request")
details = [
{"type": item["type"], "loc": item["loc"], "msg": item["msg"]}
for item in error.errors()
Expand Down Expand Up @@ -116,5 +160,22 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
protected.include_router(module.router)
api.include_router(protected)
app.include_router(api)
app.include_router(pages.router)
app.include_router(works.router)
app.include_router(library_pages.router)
app.include_router(copy_pages.router)
app.mount("/static", StaticFiles(directory=UI_DIRECTORY / "static"), name="static")

@app.middleware("http")
async def secure_pages(request: Request, call_next: Any) -> Response:
"""Add browser protections to every page; the API is JSON only."""
response: Response = await call_next(request)
if not request.url.path.startswith("/api/"):
for name, value in _SECURITY_HEADERS.items():
response.headers.setdefault(name, value)
if not request.url.path.startswith("/static/"):
response.headers.setdefault("Cache-Control", "no-store")
return response

_add_error_handlers(app)
return app
2 changes: 2 additions & 0 deletions src/librelibrary/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
RateLimitCounter,
Setting,
User,
WebSession,
)

__all__ = [
Expand Down Expand Up @@ -70,6 +71,7 @@
"Subject",
"Tag",
"User",
"WebSession",
"Work",
"WorkSubject",
]
10 changes: 9 additions & 1 deletion src/librelibrary/models/personal.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.orm import Mapped, mapped_column, relationship

from librelibrary.db import Base, Hundredths, UTCDateTime, utcnow
from librelibrary.models.system import User


class Group(Base):
Expand Down Expand Up @@ -79,6 +80,13 @@ class LibraryMember(Base):
)
role: Mapped[str] = mapped_column(String(16))

user: Mapped["User"] = relationship(viewonly=True, lazy="joined")

@property
def display_name(self) -> str:
"""Return the member's name, so that members can tell each other apart."""
return self.user.display_name


class Copy(Base):
"""A physical or digital item someone owns."""
Expand Down
15 changes: 15 additions & 0 deletions src/librelibrary/models/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,21 @@ class ApiToken(Base):
revoked_at: Mapped[datetime | None] = mapped_column(UTCDateTime)


class WebSession(Base):
"""A browser sign-in; only the hash of its cookie value is stored."""

__tablename__ = "web_session"

id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(
ForeignKey("user_account.id", ondelete="CASCADE"), index=True
)
session_hash: Mapped[str] = mapped_column(String(64), unique=True)
csrf_token: Mapped[str] = mapped_column(String(64))
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow)
expires_at: Mapped[datetime] = mapped_column(UTCDateTime, index=True)


class AuditEvent(Base):
"""A security-relevant event. Never holds a secret."""

Expand Down
3 changes: 2 additions & 1 deletion src/librelibrary/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,10 +437,11 @@ class MemberIn(_In):


class MemberOut(_Out):
"""A user's role in a library."""
"""A user's role in a library, with the name other members know them by."""

user_id: int
role: LibraryRole
display_name: str


class CopyIn(_In):
Expand Down
Loading
Loading