Repository navigation
feat(server): opt-in sign-in before anything can be changed - #534
Conversation
2e86573 to
fb734dd
Compare
Without a users file the server stays open to anyone who can reach it, exactly as before. Once one exists, guests can still browse, but every request that changes something needs a signed-in user: recipes, the pantry, the shopping list, the editor's language server and the cook.md sync controls. Guests get a Sign in link, and the controls that change things are hidden from them. Users are managed on the server only, with `cook server user add|passwd|remove|list` (and `cook server hash-password` for hand edits). They live in users.toml in the configuration directory, or in --users-file / COOK_USERS_FILE, as argon2 hashes. A running server reloads the file when it changes, so adding a user, changing a password or removing a user takes effect without a restart. One middleware decides which requests need a user: every non-GET request except an exact allowlist, plus /new, /edit, /api/ws/lsp and /api/sync. Sessions are a stateless HMAC-signed cookie whose MAC covers the user's password hash, keyed by auth-secret in the configuration directory, so they survive restarts and a password change or removal signs that user out everywhere. The server refuses to start rather than run open when a named users file is missing or invalid, or when the users file or key would sit inside the recipe directory it publishes. Closes cooklang#312 Co-Authored-By: Claude Opus 5.5 <[email protected]>
German, Spanish, Basque, Dutch and Swedish, alongside the English and French that came with the sign-in page. Each follows its file's existing register and wording for adding, editing and deleting. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…iled sign-in logs Session cookies are stateless, so signing out only cleared the cookie in that browser: a copy of it (a shared computer, a proxy log) stayed valid for the rest of its 30 days. Each sign-in now carries a random 128-bit session id, covered by the MAC (cookie format `<user>:<expiry>:<id>:<mac>`, context bumped to v2). Signing out records that id in `revoked-sessions`, beside `auth-secret`, and the server refuses the session from then on, across restarts. Only verified, unexpired cookies are recorded and each entry is dropped once its cookie would have expired, so the list stays as short as the last 30 days of sign-outs. The user's other sign-ins are unaffected. A list the server cannot read stops it from starting rather than bringing revoked sessions back; with a temporary key the list lives in memory only. A failed sign-in is now logged without the username: people type their password into that field by mistake. The users file writer becomes the shared `auth::write_private_file` (atomic, 0600) so both files are written the same way. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01BUvontmCsKnp5q9r5NPcm8
Every change made through the server now prints one line on standard
output: when, who, and what.
2026-09-27 08:42:03 alice created recipe "Soups/Pea soup.cook"
2026-09-27 08:43:12 alice added "Soups/Pea soup.cook" ×2 to the shopping list
2026-09-27 08:44:05 alice removed "milk" from the "dairy" section of the pantry
2026-09-27 09:12:44 guest failed to sign in
It covers recipes and menus (created vs updated, deleted, title picture
set or removed, the /new form), the shopping list (add, add menu,
remove, clear, check, uncheck, compact), the pantry (add, update,
remove), linking to cook.md, and signing in and out. The actor is the
signed-in user, or `guest` without sign-in and for a failed sign-in,
which never shows the name typed.
It goes to stdout with println!, next to the startup lines, rather than
through tracing: tracing writes to stderr and shows only warnings unless
-v is given, so the existing "signed in" / "signed out" info lines were
invisible by default; they move here. Names and paths come from
requests and are Debug-quoted, so a newline in one cannot forge a line.
Each write handler takes Extension<Viewer>, which the auth middleware
inserts on every route, and records after the change succeeded.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01BUvontmCsKnp5q9r5NPcm8
6afa636 to
50b4ee5
Compare
dubadub
left a comment
There was a problem hiding this comment.
Thanks for taking it, it's a highly requested feature. I procrastinated and never felt I'm ready to implement that. Probably I overthink it.
It seems to me after reviewing other projects and open issues, people need more flexibility on that. And I was thinking to implement proper RBAC to allow different users access different paths and maybe limited write also. For example I'd allow my wife to write into the shopping list, but my friends will have read only access of my pubic recipes.
I think it's a good foundation we can build on top adding roles and fine control to define these roles.
Would this be a good base for finer-grained access (roles, private recipes, folder access)?Short answer: yes for authentication and coarse roles, only partly for per-folder or per-recipe access. No change is needed in this PR to keep either option open, but per-path access would be a separate, larger refactor, not an extension of the middleware. What carries over as-is
What doesn't carry over: private recipes and folder accessThe middleware decides from method + URL. Per-recipe access needs a decision per file, and in this server a recipe is reached through far more than its own URL:
So private recipes need enforcement at the data-access layer, not at the router edge: one accessor (roughly A few design points I'd settle before starting:
Suggested path
|
Since sign-in landed (0e8dacf, #534), a page left open after its visitor's sign-in ended keeps the controls of a signed-in user. What they do with them was refused without a word: a shopping list tick unticked itself, and other writes showed the middleware's English error with no way to sign in again. The middleware now marks its API 401 and 403 with `X-Cook-Refused: sign-in|role` and writes their `error` in the visitor's language (unchanged in English). static/js/sign-in-notice.js watches every write a page sends and, on a marked refusal, shows one notice: for a 401, that the change was not made, with a Sign in link back to the page; for a 403, the translated role-forbidden text. Pages only get the notice when a users file is in use. Closes #675 Co-authored-by: Claude Opus 5.5 <[email protected]>
Closes #312.
What this does
cook servercan now require sign-in before anything changes, while staying open to readers. It is opt-in: with no users configured, the server behaves exactly as it does today.cook server user add alice # asks for alice's password, twice cook server --hostOnce a users file exists:
401/ sent to sign in401/api/ws/lsp), CookCloud sync controls401Guests get a Sign in link in the nav, and the controls that change things are hidden: New Recipe, Edit, Add to shopping list, Clear/Remove, the shopping-list ticks, pantry add/edit/delete, the sync section, and the matching keyboard shortcuts. Opening
/edit/…or/newsends a guest to/loginand back afterwards.Activity log
Every change made through the server prints a line on stdout (so it shows up in
docker logs), saying when, who, and what:/newform), the shopping list (add, add menu, remove, clear, check, uncheck, compact), the pantry (add, update, remove), linking to cook.md, and signing in and out.guestwithout sign-in and for a failed sign-in. A failed sign-in never shows the name that was typed, since that is sometimes the password.println!next to the startup lines, rather thantracing. Tracing writes to stderr and shows only warnings unless-vis given, so the earliersigned ininfo lines were invisible by default.Extension<Viewer>, which the middleware inserts on every route, and records once the change has succeeded.CLAUDE.mdnotes the rule for new write routes.Users are managed on the server only
There is no sign-up and no password change in the browser. Users live in
users.tomlin the configuration directory (or wherever--users-file/COOK_USERS_FILEpoints), managed with:toml_edit, so an admin's comments survive, and write it atomically.[users]table keeps sign-in on with nobody able to sign in, i.e. a read-only site.Design notes
src/server/auth/middleware.rs), layered inside the--url-prefixnest, decides which requests need a user:POST /api/shopping_list(it only computes a list),/api/reload(a no-op),/loginand/logout;/new,/edit/…,/api/ws/lsp,/api/sync/….So a write route added later is protected without anyone remembering to list it.
api()is untouched, so the router-scan tests inapi_docs.rsstill pass.cook_session=<user>:<expiry>:<id>:<HMAC-SHA256>, where<id>is 128 random bits unique to the sign-in. It is set withHttpOnly; SameSite=Lax; Path=<prefix or />; Max-Age=30d, plusSecurebehindX-Forwarded-Proto: https.auth-secretin the configuration directory (0600 on Unix), so sessions survive restarts, and deleting it signs everyone out.revoked-sessionsbesideauth-secret(0600, written atomically), and an entry is dropped once the cookie would have expired anyway. Only verified, unexpired cookies are recorded, so the list stays as short as the last 30 days of sign-outs. A list the server cannot read stops it from starting, rather than bringing the signed-out sessions back./api/staticserves that directory, dotfiles included, so the hashes would be public and the key would let anyone forge a session./loginand/logoutare POSTs, so the existingwrite_guardcovers them like every other write.argon2,password-hash,blake2,hmac.sha20.10,console,toml_edit,subtleandrand_corewere already there. All are optional, behind theserverfeature. argon2 and blake2 getopt-level = 3in the dev profile, because unoptimized argon2 takes seconds per sign-in.Relation to #334
@le-yams's plan in #334 was a useful map of the routes and the pitfalls, thank you. This implementation differs in a few deliberate ways:
--enable-authflag;cook server user …instead of hand-editing hashes;Other open PRs
/api/ws/lspat all; fix(server): refuse cross-site WebSocket connections to the language server #524 adds the Origin check for the signed-in case and for servers without sign-in.ServerArgsand the server docs, so whichever lands second needs a small rebase.PUT/DELETE /api/recipe_image/…routes are protected by default, with no change needed.Docs
docs/server.mdgets new "Signing in to make changes" and "Activity log" sections.README.mdgetscook server userexamples, a Sign-in in a container section, andCOOK_USERS_FILEunder Configuration. The container section coversCOOK_CONFIG_DIRon a volume,mkdir configfirst, and adding users withdocker compose execwithout a restart.docker-compose.ymlgets the same lines, commented out.docs/api.md(regenerated) describes the cookie flow for scripts and the401status.CLAUDE.mdgets notes on the middleware rule and on recording each change in the activity log.Tests
Unit tests: activity-line formatting and quoting, users-file parsing and validation, comment-preserving edits, cookie sign/verify (tampering, expiry, password change, removed user, unique session ids), the signed-out-session list (reload, expiry pruning, malformed file), the
requires_usertable,nextsanitising, key-file handling, the inside-the-recipe-directory check, and clap parsing ofcook server <dir>againstcook server user ….tests/server_auth_test.rs, 17 end-to-end tests against a realcook server:guest;--url-prefix(cookiePath=/cook);COOK_USERS_FILE;usercommands andhash-password;Checks run:
cargo fmt --all -- --checkcargo clippy --workspace --all-targets --all-features -- -D warningscargo clippy --no-default-features --features server,lsp --all-targets -- -D warningscargo test --workspacecargo test --no-default-featuresManual, in a browser: guest and signed-in views, live reload, and a session surviving a restart.
Container: the README steps, run with Podman on an image built from this branch:
COOK_CONFIG_DIR=/configon a volume;401, and a signed-in user can save;exec … user add boblets bob sign in with no restart;exec … user remove bobends his session;Not covered:
console::Term::read_secure_line); every test pipes the password in.mkdir configadvice: Podman on Windows does not enforce ownership on bind mounts.Playwright (shopping list, pantry, editor, navigation, recipe display) against a server without users: 44 passed. The 2 failures are the known Windows-only step-image tests, which build image URLs with
\; that is fixed on a separate branch and has nothing to do with this change. CI runs Linux.🤖 Generated with Claude Code