1 Commits
Author SHA1 Message Date
sbstp b71bdb2d5d plan 2026-08-01 18:53:09 -04:00
32 changed files with 359 additions and 3631 deletions
-4
View File
@@ -3,7 +3,3 @@
/sustenance.db* /sustenance.db*
/.env /.env
/seed.json /seed.json
/e2e/node_modules/
/e2e/test-results/
/e2e/playwright-report/
/test-results/
-17
View File
@@ -1,17 +0,0 @@
when:
event: [push, pull_request]
steps:
e2e-build:
image: rust:1
commands:
- cargo build
e2e-test:
image: node:24
directory: e2e
commands:
- apt-get update
- apt-get install -y --no-install-recommends ca-certificates fonts-liberation libasound2 libatk-bridge2.0-0 libatk1.0-0 libcups2 libdbus-1-3 libdrm2 libgbm1 libglib2.0-0 libgtk-3-0 libnspr4 libnss3 libpango-1.0-0 libx11-6 libxcb1 libxcomposite1 libxdamage1 libxext6 libxfixes3 libxkbcommon0 libxrandr2 xdg-utils
- npm install && npx playwright install chromium
- npx playwright test
-9
View File
@@ -1,9 +0,0 @@
when:
event: [push, pull_request]
steps:
fmt:
image: rust:1
commands:
- rustup component add rustfmt
- cargo fmt --all -- --check
-17
View File
@@ -1,17 +0,0 @@
when:
- event: tag
steps:
build:
image: rust:1
commands:
- cargo run --release
publish:
image: alpine:3.23
commands:
- apk add --no-cache nodejs
- node ci/release.js target/release/sustenance
environment:
GITEA_RELEASE_TOKEN:
from_secret: gitea_release_token
-8
View File
@@ -1,8 +0,0 @@
when:
event: [push, pull_request]
steps:
test:
image: rust:1
commands:
- cargo test --all
Generated
+7 -176
View File
@@ -68,7 +68,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
dependencies = [ dependencies = [
"axum-core", "axum-core",
"base64 0.22.1", "base64",
"bytes", "bytes",
"form_urlencoded", "form_urlencoded",
"futures-util", "futures-util",
@@ -116,12 +116,6 @@ dependencies = [
"tracing", "tracing",
] ]
[[package]]
name = "base64"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
[[package]] [[package]]
name = "base64" name = "base64"
version = "0.22.1" version = "0.22.1"
@@ -321,21 +315,6 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "foreign-types"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
dependencies = [
"foreign-types-shared",
]
[[package]]
name = "foreign-types-shared"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
[[package]] [[package]]
name = "form_urlencoded" name = "form_urlencoded"
version = "1.2.2" version = "1.2.2"
@@ -438,15 +417,6 @@ dependencies = [
"version_check", "version_check",
] ]
[[package]]
name = "getopts"
version = "0.2.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"
dependencies = [
"unicode-width",
]
[[package]] [[package]]
name = "getrandom" name = "getrandom"
version = "0.2.17" version = "0.2.17"
@@ -470,12 +440,6 @@ dependencies = [
"wasip2", "wasip2",
] ]
[[package]]
name = "half"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b43ede17f21864e81be2fa654110bf1e793774238d86ef8555c37e6519c0403"
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.15.5" version = "0.15.5"
@@ -822,12 +786,6 @@ dependencies = [
"unicase", "unicase",
] ]
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]] [[package]]
name = "mio" name = "mio"
version = "1.2.2" version = "1.2.2"
@@ -839,16 +797,6 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
]
[[package]] [[package]]
name = "nu-ansi-term" name = "nu-ansi-term"
version = "0.50.3" version = "0.50.3"
@@ -873,43 +821,6 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "openssl"
version = "0.10.81"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45"
dependencies = [
"bitflags",
"cfg-if",
"foreign-types",
"libc",
"openssl-macros",
"openssl-sys",
]
[[package]]
name = "openssl-macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "openssl-sys"
version = "0.9.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"
dependencies = [
"cc",
"libc",
"pkg-config",
"vcpkg",
]
[[package]] [[package]]
name = "parking" name = "parking"
version = "2.2.1" version = "2.2.1"
@@ -1007,25 +918,6 @@ dependencies = [
"version_check", "version_check",
] ]
[[package]]
name = "pulldown-cmark"
version = "0.13.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e"
dependencies = [
"bitflags",
"getopts",
"memchr",
"pulldown-cmark-escape",
"unicase",
]
[[package]]
name = "pulldown-cmark-escape"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.47" version = "1.0.47"
@@ -1196,16 +1088,6 @@ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]]
name = "serde_cbor"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bef2ebfde456fb76bbcf9f59315333decc4fda0b2b44b420243c11e0f5ec1f5"
dependencies = [
"half",
"serde",
]
[[package]] [[package]]
name = "serde_core" name = "serde_core"
version = "1.0.229" version = "1.0.229"
@@ -1357,7 +1239,7 @@ version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6"
dependencies = [ dependencies = [
"base64 0.22.1", "base64",
"bytes", "bytes",
"crc", "crc",
"crossbeam-queue", "crossbeam-queue",
@@ -1378,7 +1260,7 @@ dependencies = [
"serde", "serde",
"sha2", "sha2",
"smallvec", "smallvec",
"thiserror 2.0.19", "thiserror",
"tokio", "tokio",
"tokio-stream", "tokio-stream",
"tracing", "tracing",
@@ -1441,7 +1323,7 @@ dependencies = [
"serde", "serde",
"serde_urlencoded", "serde_urlencoded",
"sqlx-core", "sqlx-core",
"thiserror 2.0.19", "thiserror",
"tracing", "tracing",
"url", "url",
] ]
@@ -1465,24 +1347,19 @@ dependencies = [
"argon2", "argon2",
"async-trait", "async-trait",
"axum", "axum",
"base64 0.22.1",
"futures-util", "futures-util",
"hex", "hex",
"maud", "maud",
"pulldown-cmark",
"rand 0.8.7", "rand 0.8.7",
"serde", "serde",
"serde_json", "serde_json",
"sha2", "sha2",
"sqlx", "sqlx",
"thiserror 2.0.19", "thiserror",
"tokio", "tokio",
"tower",
"tower-http", "tower-http",
"tracing", "tracing",
"tracing-subscriber", "tracing-subscriber",
"url",
"webauthn-rs",
] ]
[[package]] [[package]]
@@ -1524,33 +1401,13 @@ dependencies = [
"syn 2.0.119", "syn 2.0.119",
] ]
[[package]]
name = "thiserror"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
dependencies = [
"thiserror-impl 1.0.69",
]
[[package]] [[package]]
name = "thiserror" name = "thiserror"
version = "2.0.19" version = "2.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9" checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9"
dependencies = [ dependencies = [
"thiserror-impl 2.0.19", "thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
] ]
[[package]] [[package]]
@@ -1776,7 +1633,7 @@ dependencies = [
"log", "log",
"rand 0.9.5", "rand 0.9.5",
"sha1", "sha1",
"thiserror 2.0.19", "thiserror",
] ]
[[package]] [[package]]
@@ -1797,12 +1654,6 @@ version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-width"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]] [[package]]
name = "untrusted" name = "untrusted"
version = "0.9.0" version = "0.9.0"
@@ -1819,7 +1670,6 @@ dependencies = [
"idna", "idna",
"percent-encoding", "percent-encoding",
"serde", "serde",
"serde_derive",
] ]
[[package]] [[package]]
@@ -1861,25 +1711,6 @@ dependencies = [
"wit-bindgen", "wit-bindgen",
] ]
[[package]]
name = "webauthn-rs"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90b266eccb4b32595876f5c73ea443b0516da0b1df72ca07bc08ed9ba7f96ec1"
dependencies = [
"base64 0.13.1",
"nom",
"openssl",
"rand 0.8.7",
"serde",
"serde_cbor",
"serde_derive",
"serde_json",
"thiserror 1.0.69",
"tracing",
"url",
]
[[package]] [[package]]
name = "webpki-roots" name = "webpki-roots"
version = "0.26.11" version = "0.26.11"
+1 -12
View File
@@ -7,11 +7,9 @@ edition = "2024"
argon2 = "0.5" argon2 = "0.5"
async-trait = "0.1" async-trait = "0.1"
axum = { version = "0.8", features = ["ws"] } axum = { version = "0.8", features = ["ws"] }
base64 = "0.22"
futures-util = "0.3" futures-util = "0.3"
hex = "0.4" hex = "0.4"
maud = "0.27" maud = "0.27"
pulldown-cmark = "0.13"
rand = "0.8" rand = "0.8"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
@@ -19,15 +17,6 @@ sha2 = "0.10"
sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "sqlite", "macros", "tls-rustls"] } sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "sqlite", "macros", "tls-rustls"] }
thiserror = "2" thiserror = "2"
tokio = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full"] }
tower = "0.5" tower-http = { version = "0.6", features = ["fs", "trace"] }
tower-http = { version = "0.6", features = ["fs", "trace", "set-header"] }
tracing = "0.1" tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] } tracing-subscriber = { version = "0.3", features = ["env-filter"] }
url = "2"
webauthn-rs = "0.3"
[profile.release]
opt-level = "z"
strip = true
lto = true
codegen-units = 1
+163
View File
@@ -0,0 +1,163 @@
# Meal Feature Plan
Status: planning (not yet implemented)
This plan adds the concept of a **meal** to Sustenance. A meal has a name, an
optional description/recipe (markdown), and a list of ingredients. Meals are
**global** (not owned by a single user) and **not collaborative** like grocery
lists. The core action is **"add a meal to a list"**, which expands the meal's
ingredients into regular list items.
The plan is split into parts so each can be implemented and tested independently.
---
## Part A — Refactor categories to be global
Currently `categories` are per-list (`categories.list_id`, with a
`UNIQUE (list_id, name)` constraint). Since meals are global and ingredients
reference categories, categories become global too.
### Schema change (in `migrate` in `src/sqlite.rs`)
```sql
categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
position INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
)
```
- Drop `list_id`; `name` becomes globally unique.
- `items.category_id` stays a FK to `categories(id)` — unchanged.
- **Migration concern:** the current `CREATE TABLE IF NOT EXISTS` won't alter an
existing DB. Need a real migration (or accept recreating the dev DB).
### Repo / port changes (`CategoryRepository` in `src/ports.rs`)
- `categories(txn)` → returns **all** global categories (no `list_id` param).
- `create_category(txn, name)` → global, no `list_id`, no per-list revision bump.
- Add `category_by_name(txn, name)` for resolving ingredient categories.
- `ListRepository::create_list` **no longer seeds** default categories (they're
global now). Default categories become a one-time seed at startup instead.
### Service / HTTP changes
- `ListService::categories()` no longer takes `list_id`.
- `create_category` handler moves from `/lists/{list_id}/categories` to a global
`/categories` route (or a categories management page).
- The list page's categories panel now shows the global category set.
- `create_category` no longer bumps a list revision (not list-scoped anymore),
so no realtime event for it.
---
## Part B — Meal data model
New tables (in `migrate` in `src/sqlite.rs`):
```sql
meals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '', -- markdown source
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
)
meal_ingredients (
id INTEGER PRIMARY KEY AUTOINCREMENT,
meal_id INTEGER NOT NULL REFERENCES meals(id) ON DELETE CASCADE,
name TEXT NOT NULL,
quantity TEXT NOT NULL DEFAULT '',
note TEXT NOT NULL DEFAULT '',
category_id INTEGER REFERENCES categories(id) ON DELETE SET NULL, -- global category FK
position INTEGER NOT NULL DEFAULT 0
)
```
- **No `user_id`** — meals are global (editable/accessible by all), matching lists.
- Ingredient categories reference the **global** `categories.id` directly
(thanks to Part A), no name-string resolution needed.
---
## Part C — Domain models (`src/domain.rs`)
- `Meal { id, name, description, ingredients: Vec<MealIngredient> }`
- `MealIngredient { id, name, quantity, note, category_id: Option<i64> }`
---
## Part D — Ports (`src/ports.rs`)
One repo per table, matching the existing pattern:
- `MealRepository``create_meal`, `get_meal`, `list_meals`, `update_meal`,
`delete_meal`
- `MealIngredientRepository``ingredients_for_meal`, `add_ingredient`,
`update_ingredient`, `delete_ingredient`
- Reuse `ListRepository`, `CategoryRepository`, `ItemRepository`.
---
## Part E — Services (`src/services.rs`)
- `MealService` — CRUD for meals + ingredients.
- **`add_meal_to_list(meal_id, list_id)`** in one unit of work:
1. Load the meal.
2. Verify the list exists.
3. Map each ingredient's `category_id` (already a global category id, so it's
valid on the list directly).
4. **Bulk-insert** all items via a new `ItemRepository::add_items_bulk`,
bumping the list revision **once** → one realtime event.
---
## Part F — HTTP + Views
### Routes (all require `CurrentUser`)
- `GET /meals` — list all meals
- `GET /meals/new`, `POST /meals` — create
- `GET /meals/{id}`, `POST /meals/{id}/edit` — view/edit
- `POST /meals/{id}/delete`
- `POST /meals/{id}/ingredients` — add ingredient
- `POST /meals/{id}/ingredients/{iid}/edit`, `.../delete`
- `POST /lists/{list_id}/add-meal` — add a meal's ingredients to a list
### Add-to-list lookup popup
On the list page, an "Add meal" button opens a modal/popup with a searchable
meal picker (htmx). Selecting a meal posts to `/lists/{list_id}/add-meal`.
Implemented as an htmx-powered modal that fetches a meal list/search fragment.
### Views (`src/views.rs`)
- Meals index page (`/meals`) listing all meals.
- Full-page create/edit forms (matches current htmx style).
- Meal detail page showing name, rendered description, and ingredients.
- Markdown rendered server-side with `pulldown-cmark`, no sanitization for now.
---
## Implementation order
1. **Part A** — category refactor (schema, repos, services, HTTP, views, tests).
Do this first since meals depend on global categories.
2. **Part B/C/D** — meal schema + domain + repos + tests.
3. **Part E**`MealService` CRUD + `add_meal_to_list` (bulk) + tests.
4. **Part F** — HTTP routes, views, and the add-meal lookup popup.
---
## Open decisions (to confirm before implementing)
1. **Migration handling for the category refactor** — since `CREATE TABLE IF NOT
EXISTS` won't reshape an existing DB, write a proper migration, or is it fine
to drop/recreate the dev DB?
2. **Category management UI** — with categories now global, do we want a
dedicated categories page (e.g. `/categories`) to add/rename/delete them, or
keep it minimal (just the add form on the list page, now creating global
categories)?
+3 -33
View File
@@ -8,13 +8,7 @@ A small shared grocery list built with Rust, Axum, Maud, htmx, WebSockets, and S
cargo run cargo run
``` ```
Open <http://localhost:3000>. The application creates `sustenance.db` in the Open <http://127.0.0.1:3000>. The application creates `sustenance.db` in the working directory on first start.
working directory on first start.
**Note:** use `localhost` (not `127.0.0.1`) when testing passkeys locally —
browsers reject IP addresses as WebAuthn RP IDs. The app defaults to
`localhost` for loopback hosts, so passkeys work out of the box when you access
the site via `http://localhost:3000`.
## Configuration ## Configuration
@@ -26,9 +20,7 @@ the site via `http://localhost:3000`.
| `COOKIE_SECURE` | `false` | Add the `Secure` attribute to session cookies | | `COOKIE_SECURE` | `false` | Add the `Secure` attribute to session cookies |
| `REGISTRATION_MODE` | `invite_only` | Use `open` for local development; otherwise registration requires a valid list invitation after the first account | | `REGISTRATION_MODE` | `invite_only` | Use `open` for local development; otherwise registration requires a valid list invitation after the first account |
| `SEED_CONFIG` | `seed.json` | Optional JSON file with a default user to create when the database is first initialized | | `SEED_CONFIG` | `seed.json` | Optional JSON file with a default user to create when the database is first initialized |
| `RP_ID` | derived from `PUBLIC_BASE_URL` | WebAuthn relying party ID (the host users access the site from) | | `RUST_LOG` | `sustenance=debug,tower_http=info` | Log filter |
| `RP_NAME` | `Sustenance` | WebAuthn relying party name shown to users |
| `RUST_LOG` | `sustenance=info,tower_http=info` | Log filter; HTTP requests are logged at info level |
### Seeding a default user ### Seeding a default user
@@ -49,14 +41,12 @@ The file is optional — if it is missing or invalid, seeding is silently skippe
## Current features ## Current features
- Email/password accounts with Argon2 password hashes - Email/password accounts with Argon2 password hashes
- Optional WebAuthn passkeys for passwordless sign-in (managed from the account page)
- Cookie-backed sessions and CSRF tokens for list mutations - Cookie-backed sessions and CSRF tokens for list mutations
- Shared lists with one-time, seven-day invitation links - Shared lists with one-time, seven-day invitation links
- Invite-only registration by default after the first account - Invite-only registration by default after the first account
- Add, edit, check, and delete grocery items - Add, edit, check, and delete grocery items
- Global categories with common defaults seeded at startup and custom category creation - List-scoped categories with common defaults and custom category creation
- Items grouped by category and assigned from the add/edit forms - Items grouped by category and assigned from the add/edit forms
- Meals with ingredients, markdown descriptions, and one-click "add meal to list"
- Server-authoritative last-write-wins updates - Server-authoritative last-write-wins updates
- Per-list WebSocket updates with server-rendered htmx fragments - Per-list WebSocket updates with server-rendered htmx fragments
- In-memory presence for members currently viewing a list - In-memory presence for members currently viewing a list
@@ -71,23 +61,3 @@ cargo fmt --all -- --check
cargo check cargo check
cargo test cargo test
``` ```
### End-to-end tests (Playwright)
The e2e tests live in `e2e/` and use Playwright with a real browser. Each test
starts its own server against a fresh, throwaway database on a unique port, so
tests are fully isolated from each other and from your real `sustenance.db`.
The tests launch `target/debug/sustenance`, so build the server first:
```sh
# one-time setup
cargo build
cd e2e
npm install
npx playwright install chromium
# run the tests (each test launches its own server against a fresh DB)
cd e2e
npx playwright test
```
-91
View File
@@ -1,91 +0,0 @@
import * as fs from 'node:fs/promises';
import { basename } from 'node:path';
function getEnv(name) {
const val = process.env[name];
if (!val) {
throw new Error(`Environment variable ${name} is empty`);
}
return val;
}
async function fetchJSON(url, options) {
const resp = await fetch(url, options);
if (!resp.ok) {
throw new Error(`Unexpected HTTP status: ${resp.status}`, {
cause: {
status: resp.status,
body: await resp.text(),
},
});
}
return await resp.json();
}
async function postJSON(url, token, payload) {
return fetchJSON(url, {
method: "POST",
headers: {
"Authorization": `token ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
}
async function postFile(url, token, files) {
const formData = new FormData();
for (const [name, path] of Object.entries(files)) {
const fileBuffer = await fs.readFile(path);
const fileObject = new File([fileBuffer], basename(path), { type: 'application/octet-stream' });
formData.append(name, fileObject)
}
return await fetchJSON(url, {
method: "POST",
headers: {
"Authorization": `token ${token}`,
},
body: formData,
});
}
async function canRead(path) {
try {
await fs.access(path, fs.constants.R_OK);
return true;
} catch {
return false;
}
}
async function main() {
const path = process.argv[2];
if (!path || !canRead(path)) {
throw Error(`Path ${path} is undefined or inaccessible, use node release.js <path>`);
}
const token = getEnv("GITEA_RELEASE_TOKEN");
const tag = getEnv("CI_COMMIT_TAG");
const repo = getEnv("CI_REPO");
console.log("Creating release...");
const releaseData = await postJSON(`https://git.sbstp.ca/api/v1/repos/${repo}/releases`, token, {
name: `Release ${tag}`,
tag_name: tag,
target_commitish: tag,
draft: false,
prerelease: false,
});
console.log(`Created release ID ${releaseData.id}`);
console.log("Uploading asset...");
const assetData = await postFile(`https://git.sbstp.ca/api/v1/repos/${repo}/releases/${releaseData.id}/assets?name=${basename(path)}`, token, {
attachment: path,
});
console.log("Asset uploaded:", assetData);
}
try {
await main();
} catch (err) {
console.error(err);
}
-126
View File
@@ -1,126 +0,0 @@
import { test as base, expect, Page } from "@playwright/test";
import { spawn, ChildProcess } from "child_process";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
/**
* Starts a fresh Sustenance server against a unique, throwaway database on a
* unique port for each test, and tears it down afterwards. This gives every
* test a clean DB with no shared state between tests.
*/
export const test = base.extend<{ server: { baseURL: string }; page: Page }>({
server: [
async ({}, use) => {
const server = await startServer();
await use({ baseURL: server.baseURL });
await killTree(server.child);
// Clean up the DB files (including -wal / -shm).
for (const suffix of ["", "-wal", "-shm"]) {
fs.rmSync(server.dbPath + suffix, { force: true });
}
},
{ scope: "test", auto: true },
],
// Provide a page whose baseURL points at this test's server.
page: async ({ browser, server }, use) => {
const context = await browser.newContext({ baseURL: server.baseURL });
const page = await context.newPage();
await use(page);
await context.close();
},
});
/** Starts a server, retrying on a fresh port if the first attempt fails to bind. */
async function startServer() {
for (let attempt = 0; attempt < 5; attempt++) {
const dbPath = path.join(
os.tmpdir(),
`sustenance-e2e-${process.pid}-${Date.now()}-${Math.random()
.toString(36)
.slice(2)}.db`,
);
const port = 20000 + Math.floor(Math.random() * 30000);
const baseURL = `http://localhost:${port}`;
const child = spawn(
path.resolve(__dirname, "..", "target", "debug", "sustenance"),
[],
{
env: {
...process.env,
DATABASE_PATH: dbPath,
REGISTRATION_MODE: "open",
BIND_ADDRESS: `127.0.0.1:${port}`,
PUBLIC_BASE_URL: baseURL,
// WebAuthn requires a valid domain for the RP ID; localhost is allowed.
RP_ID: "localhost",
// Point SEED_CONFIG at a nonexistent file so no default user is created.
SEED_CONFIG: path.join(os.tmpdir(), "sustenance-e2e-no-seed.json"),
},
stdio: ["ignore", "ignore", "pipe"],
// Run in its own process group so we can kill the whole tree.
detached: true,
},
);
let stderr = "";
child.stderr?.on("data", (chunk) => {
stderr += chunk.toString();
});
try {
await waitForServer(baseURL, child);
return { baseURL, child, dbPath };
} catch (error) {
// The server may have failed to bind (port collision). Clean up and retry.
await killTree(child);
for (const suffix of ["", "-wal", "-shm"]) {
fs.rmSync(dbPath + suffix, { force: true });
}
if (attempt === 4) {
throw new Error(
`server failed to start after retries; last stderr:\n${stderr}\n${error}`,
);
}
}
}
throw new Error("unreachable");
}
async function waitForServer(baseURL: string, child: ChildProcess) {
const deadline = Date.now() + 60_000;
while (Date.now() < deadline) {
if (child.exitCode !== null) {
throw new Error(`server exited early with code ${child.exitCode}`);
}
try {
const res = await fetch(baseURL + "/login");
if (res.ok) return;
} catch {
// not up yet
}
await new Promise((r) => setTimeout(r, 200));
}
throw new Error("timed out waiting for server to start");
}
async function killTree(child: ChildProcess) {
try {
process.kill(-child.pid!, "SIGTERM");
} catch {
child.kill("SIGTERM");
}
// Give it a moment to shut down gracefully, then force-kill if needed.
const exited = new Promise((resolve) => child.once("exit", resolve));
const timeout = new Promise((resolve) => setTimeout(resolve, 5000));
await Promise.race([exited, timeout]);
try {
process.kill(-child.pid!, "SIGKILL");
} catch {
/* already gone */
}
}
export { expect };
-60
View File
@@ -1,60 +0,0 @@
import { Page, expect } from "@playwright/test";
/** Registers a fresh account and lands on the lists page. */
export async function registerAndLogin(page: Page, email: string) {
await page.goto("/register");
await page.fill("#display-name", "Test User");
await page.fill("#email", email);
await page.fill("#password", "a-strong-password");
await page.click('button[type="submit"]');
await expect(page).toHaveURL(/\/lists/);
}
/** Creates a meal with the given name and markdown description. */
export async function createMeal(page: Page, name: string, description: string) {
await page.goto("/meals/new");
await page.fill("#meal-name", name);
await page.fill("#meal-description", description);
await page.click('button:has-text("Save meal")');
await expect(page).toHaveURL(/\/meals\/\d+/);
}
/** Creates a list and lands on its page. */
export async function createList(page: Page, name: string) {
await page.goto("/lists");
await page.fill("#list-name", name);
await page.click('button:has-text("Create list")');
await expect(page).toHaveURL(/\/lists\/\d+/);
}
/** Adds an item to the current list page. */
export async function addItem(page: Page, name: string, quantity = "") {
await page.fill("#item-name", name);
if (quantity) {
await page.fill("#item-quantity", quantity);
}
await page.click("#add-item-button");
await expect(page.locator(".item-row").filter({ hasText: name })).toBeVisible();
}
/** Adds an ingredient to the current meal page. */
export async function addIngredient(page: Page, name: string, quantity = "") {
await page.fill("#ingredient-name", name);
if (quantity) {
await page.fill("#ingredient-quantity", quantity);
}
await page.click("#add-ingredient-button");
await expect(page.locator(".ingredient-list").filter({ hasText: name })).toBeVisible();
}
/** Creates a meal and adds the given ingredients to it. */
export async function createMealWithIngredients(
page: Page,
name: string,
ingredients: Array<{ name: string; quantity?: string }>,
) {
await createMeal(page, name, "");
for (const ingredient of ingredients) {
await addIngredient(page, ingredient.name, ingredient.quantity ?? "");
}
}
-90
View File
@@ -1,90 +0,0 @@
{
"name": "sustenance-e2e",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sustenance-e2e",
"version": "1.0.0",
"devDependencies": {
"@playwright/test": "^1.45.0",
"@types/node": "^26.1.2"
}
},
"node_modules/@playwright/test": {
"version": "1.62.1",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.62.1.tgz",
"integrity": "sha512-DTcUc8qii+cpHvtOwggMtBRMjKZHXYWdw8syRYu2vtzuq4Wxphqq4NfCs5Zt44L6mA8rfDfj+PHnxFc/FeK6mQ==",
"dev": true,
"dependencies": {
"playwright": "1.62.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@types/node": {
"version": "26.1.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.2.tgz",
"integrity": "sha512-Vu4a5UFA9rIIFJ7rB/Vaafh9lrCQszopTCx6KjFboXTGQbPNasehVR5TEiithSDGyd1DEiUByggTZsg8jukeIg==",
"dev": true,
"dependencies": {
"undici-types": "~8.3.0"
}
},
"node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/playwright": {
"version": "1.62.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz",
"integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==",
"dev": true,
"dependencies": {
"playwright-core": "1.62.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.62.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz",
"integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==",
"dev": true,
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/undici-types": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
"integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
"dev": true
}
}
}
-13
View File
@@ -1,13 +0,0 @@
{
"name": "sustenance-e2e",
"version": "1.0.0",
"private": true,
"scripts": {
"test": "playwright test",
"test:headed": "playwright test --headed"
},
"devDependencies": {
"@playwright/test": "^1.45.0",
"@types/node": "^26.1.2"
}
}
-10
View File
@@ -1,10 +0,0 @@
import { defineConfig } from "@playwright/test";
export default defineConfig({
testDir: "./tests",
timeout: 30_000,
retries: 2,
use: {
trace: "on-first-retry",
},
});
-54
View File
@@ -1,54 +0,0 @@
import { expect } from "@playwright/test";
import { test } from "../fixtures";
import { registerAndLogin, createList, createMealWithIngredients } from "../helpers";
test("a user can add a meal's ingredients to a list via the picker", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createMealWithIngredients(page, "Spaghetti Bolognese", [
{ name: "Penne", quantity: "500g" },
{ name: "Tomato", quantity: "2" },
]);
await createList(page, "Weekly shop");
// Open the add-meal picker.
await page.click(".add-meal-button");
const picker = page.locator(".meal-picker-backdrop");
await expect(picker).toBeVisible();
await expect(picker.locator(".meal-picker-button").filter({ hasText: "Spaghetti Bolognese" })).toBeVisible();
// Select the meal.
await picker.locator(".meal-picker-button").filter({ hasText: "Spaghetti Bolognese" }).click();
// The picker closes and the meal's ingredients appear as items.
await expect(picker).toHaveCount(0);
await expect(page.locator(".item-row").filter({ hasText: "Penne" })).toBeVisible();
await expect(page.locator(".item-row").filter({ hasText: "Tomato" })).toBeVisible();
await expect(page.locator(".item-row").filter({ hasText: "Penne" }).locator(".item-qty")).toHaveText("(500g)");
});
test("the add-meal picker closes via the close button", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createMealWithIngredients(page, "Spaghetti Bolognese", [{ name: "Penne" }]);
await createList(page, "Weekly shop");
await page.click(".add-meal-button");
const picker = page.locator(".meal-picker-backdrop");
await expect(picker).toBeVisible();
await picker.locator(".meal-picker-close").click();
await expect(picker).toHaveCount(0);
});
test("the add-meal picker closes when clicking outside", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createMealWithIngredients(page, "Spaghetti Bolognese", [{ name: "Penne" }]);
await createList(page, "Weekly shop");
await page.click(".add-meal-button");
const picker = page.locator(".meal-picker-backdrop");
await expect(picker).toBeVisible();
// Click the backdrop itself (outside the modal card), at the viewport corner.
await page.mouse.click(10, 10);
await expect(picker).toHaveCount(0);
});
-15
View File
@@ -1,15 +0,0 @@
import { expect } from "@playwright/test";
import { test } from "../fixtures";
import { registerAndLogin } from "../helpers";
test("a user can register and log in", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await expect(page.locator("h1")).toContainText("Grocery lists");
});
test("a user can log out", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await page.click('button:has-text("Sign out")');
await expect(page).toHaveURL(/\/login/);
await expect(page.locator("h1")).toContainText("Welcome back");
});
-91
View File
@@ -1,91 +0,0 @@
import { expect } from "@playwright/test";
import { test } from "../fixtures";
import { registerAndLogin, createList, addItem } from "../helpers";
test("a user can create a list", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createList(page, "Weekly shop");
await expect(page.locator("h1")).toContainText("Weekly shop");
await expect(page.locator(".empty-items")).toBeVisible();
});
test("a user can add an item with a quantity", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createList(page, "Weekly shop");
await addItem(page, "Apple", "2");
// Quantity renders in parens to the left of the name.
const row = page.locator(".item-row").filter({ hasText: "Apple" });
await expect(row.locator(".item-qty")).toHaveText("(2)");
await expect(row.locator("strong")).toHaveText("Apple");
});
test("a user can check off an item", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createList(page, "Weekly shop");
await addItem(page, "Apple");
const row = page.locator(".item-row").filter({ hasText: "Apple" });
await row.locator(".check-button").click();
await expect(row).toHaveClass(/is-checked/);
});
test("clicking an item's text toggles the checkbox", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createList(page, "Weekly shop");
await addItem(page, "Apple");
const row = page.locator(".item-row").filter({ hasText: "Apple" });
await row.locator(".item-copy").click();
await expect(row).toHaveClass(/is-checked/);
});
test("a user can edit an item via the actions modal", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createList(page, "Weekly shop");
await addItem(page, "Apple", "2");
const row = page.locator(".item-row").filter({ hasText: "Apple" });
await row.locator(".item-actions-button").click();
const dialog = row.locator("dialog.item-modal");
await expect(dialog).toBeVisible();
await dialog.locator('[id^="item-edit-name"]').fill("Banana");
await dialog.locator('[id^="item-edit-quantity"]').fill("6");
await dialog.locator('[id^="item-edit-save"]').click();
const updated = page.locator(".item-row").filter({ hasText: "Banana" });
await expect(updated).toBeVisible();
await expect(updated.locator(".item-qty")).toHaveText("(6)");
});
test("a user can delete an item via the actions modal", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createList(page, "Weekly shop");
await addItem(page, "Apple");
const row = page.locator(".item-row").filter({ hasText: "Apple" });
await row.locator(".item-actions-button").click();
const dialog = row.locator("dialog.item-modal");
await expect(dialog).toBeVisible();
await dialog.locator('[id^="item-edit-delete"]').click();
await expect(page.locator(".item-row").filter({ hasText: "Apple" })).toHaveCount(0);
await expect(page.locator(".empty-items")).toBeVisible();
});
test("a user can add a category", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createList(page, "Weekly shop");
await page.fill("#category-name", "Bakery");
await page.click("#add-category-button");
await expect(page.locator(".category-chip").filter({ hasText: "Bakery" })).toBeVisible();
});
-88
View File
@@ -1,88 +0,0 @@
import { expect } from "@playwright/test";
import { test } from "../fixtures";
import { registerAndLogin, createMeal, addIngredient } from "../helpers";
test("a user can add an ingredient to a meal", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createMeal(page, "Spaghetti Bolognese", "");
await addIngredient(page, "Penne", "500g");
const row = page.locator(".ingredient-list").filter({ hasText: "Penne" });
await expect(row.locator(".item-qty")).toHaveText("(500g)");
await expect(row.locator("strong")).toHaveText("Penne");
});
test("a user can edit a meal name and description via the modal", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createMeal(page, "Spaghetti Bolognese", "A classic.");
await page.click('button:has-text("Edit")');
const dialog = page.locator("dialog#meal-edit-modal");
await expect(dialog).toBeVisible();
await dialog.locator("#meal-edit-name").fill("Pasta al Pomodoro");
await dialog.locator("#meal-edit-description").fill("## Ingredients\n\nA simple tomato sauce.");
await dialog.locator("#meal-edit-save").click();
await expect(page.locator("h1")).toContainText("Pasta al Pomodoro");
await expect(page.locator(".markdown h2")).toContainText("Ingredients");
});
test("a user can delete a meal", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createMeal(page, "Spaghetti Bolognese", "");
await page.click('button:has-text("Delete")');
await expect(page).toHaveURL(/\/meals$/);
await expect(page.locator(".list-card").filter({ hasText: "Spaghetti Bolognese" })).toHaveCount(0);
});
test("a user can edit an ingredient via the actions modal", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createMeal(page, "Spaghetti Bolognese", "");
await addIngredient(page, "Penne", "500g");
const row = page.locator(".ingredient-list").filter({ hasText: "Penne" });
await row.locator(".item-actions-button").click();
const dialog = row.locator("dialog.item-modal");
await expect(dialog).toBeVisible();
await dialog.locator('[id^="ingredient-edit-name"]').fill("Rigatoni");
await dialog.locator('[id^="ingredient-edit-quantity"]').fill("400g");
await dialog.locator('[id^="ingredient-edit-save"]').click();
const updated = page.locator(".ingredient-list").filter({ hasText: "Rigatoni" });
await expect(updated).toBeVisible();
await expect(updated.locator(".item-qty")).toHaveText("(400g)");
});
test("a user can delete an ingredient via the actions modal", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createMeal(page, "Spaghetti Bolognese", "");
await addIngredient(page, "Penne");
const row = page.locator(".ingredient-list").filter({ hasText: "Penne" });
await row.locator(".item-actions-button").click();
const dialog = row.locator("dialog.item-modal");
await expect(dialog).toBeVisible();
await dialog.locator('[id^="ingredient-edit-delete"]').click();
await expect(page.locator(".ingredient-list").filter({ hasText: "Penne" })).toHaveCount(0);
});
test("ingredients are grouped under their categories", async ({ page }) => {
await registerAndLogin(page, "alice@example.com");
await createMeal(page, "Spaghetti Bolognese", "");
// Add an ingredient in the default "Produce" category.
await page.fill("#ingredient-name", "Tomato");
await page.selectOption("#ingredient-category", { label: "Produce" });
await page.click("#add-ingredient-button");
// Add one without a category.
await addIngredient(page, "Penne");
await expect(page.locator(".category-heading").filter({ hasText: "Produce" })).toBeVisible();
await expect(page.locator(".category-heading").filter({ hasText: "Uncategorized" })).toBeVisible();
});
-47
View File
@@ -1,47 +0,0 @@
import { expect } from "@playwright/test";
import { test } from "../fixtures";
import { registerAndLogin } from "../helpers";
/**
* Enables a virtual WebAuthn authenticator on the given context so the browser
* can complete passkey ceremonies without a real device.
*/
async function enableVirtualAuthenticator(context: any) {
const cdp = await context.newCDPSession(context.pages()[0]);
await cdp.send("WebAuthn.enable", { enableUI: false });
await cdp.send("WebAuthn.addVirtualAuthenticator", {
options: {
protocol: "ctap2",
transport: "internal",
hasResidentKey: true,
hasUserVerification: true,
isUserVerified: true,
},
});
}
test("a user can register a passkey and sign in with it", async ({ page, browser, server }) => {
const context = await browser.newContext({ baseURL: server.baseURL });
const p = await context.newPage();
await enableVirtualAuthenticator(context);
// Register with a password first.
await registerAndLogin(p, "alice@example.com");
// Add a passkey from the account page.
await p.goto("/account");
await p.click("#add-passkey");
await expect(p.locator(".passkey-row")).toHaveCount(1);
// Log out.
await p.click('button:has-text("Sign out")');
await expect(p).toHaveURL(/\/login/);
// Sign in with the passkey.
await p.fill("#email", "alice@example.com");
await p.click("#passkey-login");
await expect(p).toHaveURL(/\/lists/);
await context.close();
});
-31
View File
@@ -1,31 +0,0 @@
import { expect } from "@playwright/test";
import { test } from "../fixtures";
import { registerAndLogin, createList, addItem } from "../helpers";
test("a list updates live for another user via websocket", async ({ page, browser, server }) => {
// User A registers and creates a list.
await registerAndLogin(page, "alice@example.com");
await createList(page, "Weekly shop");
const listUrl = page.url();
// User B registers in a separate context (separate session).
const contextB = await browser.newContext({ baseURL: server.baseURL });
const pageB = await contextB.newPage();
await registerAndLogin(pageB, "bob@example.com");
// Both users open the same list.
await page.goto(listUrl);
await pageB.goto(listUrl);
// Give the websocket connections a moment to establish.
await page.waitForTimeout(500);
// User A adds an item.
await addItem(page, "Apple", "2");
// It should appear on User B's page without any reload.
await expect(pageB.locator(".item-row").filter({ hasText: "Apple" })).toBeVisible();
await expect(pageB.locator(".item-row").filter({ hasText: "Apple" }).locator(".item-qty")).toHaveText("(2)");
await contextB.close();
});
-26
View File
@@ -21,15 +21,6 @@ pub struct User {
pub display_name: String, pub display_name: String,
} }
#[derive(Clone, Debug)]
pub struct Passkey {
pub id: i64,
pub user_id: i64,
pub credential_id: String,
pub credential: String,
pub counter: i64,
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct SessionUser { pub struct SessionUser {
pub user: User, pub user: User,
@@ -61,23 +52,6 @@ pub struct Category {
pub name: String, pub name: String,
} }
#[derive(Clone, Debug)]
pub struct Meal {
pub id: i64,
pub name: String,
pub description: String,
pub ingredients: Vec<MealIngredient>,
}
#[derive(Clone, Debug)]
pub struct MealIngredient {
pub id: i64,
pub name: String,
pub quantity: String,
pub note: String,
pub category_id: Option<i64>,
}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct PresenceUser { pub struct PresenceUser {
pub user_id: i64, pub user_id: i64,
+24 -377
View File
@@ -5,7 +5,7 @@ use std::time::Duration;
use axum::{ use axum::{
Router, Router,
extract::{ extract::{
Form, FromRequest, FromRequestParts, Json, Path, Query, Request, State, Form, FromRequest, FromRequestParts, Path, Query, Request, State,
ws::{Message, WebSocket, WebSocketUpgrade}, ws::{Message, WebSocket, WebSocketUpgrade},
}, },
http::{HeaderMap, HeaderValue, StatusCode, header, request::Parts}, http::{HeaderMap, HeaderValue, StatusCode, header, request::Parts},
@@ -16,26 +16,19 @@ use axum::{
use futures_util::{SinkExt, StreamExt}; use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, de::DeserializeOwned}; use serde::{Deserialize, de::DeserializeOwned};
use thiserror::Error; use thiserror::Error;
use tower_http::{ use tower_http::{services::ServeDir, trace::TraceLayer};
services::ServeDir, use tracing::{error, warn};
set_header::SetResponseHeaderLayer,
trace::{DefaultMakeSpan, DefaultOnResponse, TraceLayer},
};
use tracing::{Level, error, warn};
use crate::domain::{DomainError, SessionUser}; use crate::domain::{DomainError, SessionUser};
use crate::ports::{HubEvent, RealtimeNotifier}; use crate::ports::{HubEvent, RealtimeNotifier};
use crate::services::{AuthService, InvitationService, ListService, MealService}; use crate::services::{AuthService, InvitationService, ListService};
use crate::views; use crate::views;
use crate::webauthn::WebAuthnService;
#[derive(Clone)] #[derive(Clone)]
pub struct AppState { pub struct AppState {
pub auth: Arc<AuthService>, pub auth: Arc<AuthService>,
pub lists: Arc<ListService>, pub lists: Arc<ListService>,
pub meals: Arc<MealService>,
pub invitations: Arc<InvitationService>, pub invitations: Arc<InvitationService>,
pub webauthn: Arc<WebAuthnService>,
pub realtime: Arc<dyn RealtimeNotifier>, pub realtime: Arc<dyn RealtimeNotifier>,
pub cookie_secure: bool, pub cookie_secure: bool,
pub public_base_url: String, pub public_base_url: String,
@@ -54,13 +47,10 @@ pub enum AppError {
impl IntoResponse for AppError { impl IntoResponse for AppError {
fn into_response(self) -> Response { fn into_response(self) -> Response {
match self { match self {
AppError::Database(error) => { AppError::Database(_) => status_html_response(
error!(%error, "request failed"); StatusCode::INTERNAL_SERVER_ERROR,
status_html_response( views::error_page("500", "Something went wrong."),
StatusCode::INTERNAL_SERVER_ERROR, ),
views::error_page("500", "Something went wrong."),
)
}
AppError::BadRequest(message) => { AppError::BadRequest(message) => {
status_html_response(StatusCode::BAD_REQUEST, views::error_page("400", &message)) status_html_response(StatusCode::BAD_REQUEST, views::error_page("400", &message))
} }
@@ -78,58 +68,19 @@ pub fn build_router(state: AppState) -> Router {
.route("/login", get(login_page).post(login)) .route("/login", get(login_page).post(login))
.route("/register", get(register_page).post(register)) .route("/register", get(register_page).post(register))
.route("/logout", post(logout)) .route("/logout", post(logout))
.route("/account", get(account_page))
.route("/auth/passkey/register/start", post(passkey_register_start))
.route(
"/auth/passkey/register/finish",
post(passkey_register_finish),
)
.route("/auth/passkey/login/start", post(passkey_login_start))
.route("/auth/passkey/login/finish", post(passkey_login_finish))
.route(
"/account/passkeys/{passkey_id}/delete",
post(delete_passkey),
)
.route("/lists", get(lists_page).post(create_list)) .route("/lists", get(lists_page).post(create_list))
.route("/lists/{list_id}", get(list_page)) .route("/lists/{list_id}", get(list_page))
.route("/lists/{list_id}/items", post(add_item)) .route("/lists/{list_id}/items", post(add_item))
.route("/lists/{list_id}/items/{item_id}/check", post(check_item)) .route("/lists/{list_id}/items/{item_id}/check", post(check_item))
.route("/lists/{list_id}/items/{item_id}/edit", post(edit_item)) .route("/lists/{list_id}/items/{item_id}/edit", post(edit_item))
.route("/lists/{list_id}/items/{item_id}/delete", post(delete_item)) .route("/lists/{list_id}/items/{item_id}/delete", post(delete_item))
.route("/categories", post(create_category)) .route("/lists/{list_id}/categories", post(create_category))
.route("/invitations", post(create_invitation)) .route("/invitations", post(create_invitation))
.route("/meals", get(meals_page).post(create_meal))
.route("/meals/new", get(new_meal_page))
.route("/meals/{meal_id}", get(meal_page))
.route("/meals/{meal_id}/edit", post(edit_meal))
.route("/meals/{meal_id}/delete", post(delete_meal))
.route("/meals/{meal_id}/ingredients", post(add_ingredient))
.route(
"/meals/{meal_id}/ingredients/{ingredient_id}/edit",
post(edit_ingredient),
)
.route(
"/meals/{meal_id}/ingredients/{ingredient_id}/delete",
post(delete_ingredient),
)
.route("/lists/{list_id}/add-meal", post(add_meal_to_list))
.route("/lists/{list_id}/stream", get(list_stream)) .route("/lists/{list_id}/stream", get(list_stream))
.route("/invite/{token}", get(invitation_page)) .route("/invite/{token}", get(invitation_page))
.route("/invite/{token}/accept", post(accept_invitation)) .route("/invite/{token}/accept", post(accept_invitation))
.nest_service( .nest_service("/static", ServeDir::new("static"))
"/static", .layer(TraceLayer::new_for_http())
tower::ServiceBuilder::new()
.layer(SetResponseHeaderLayer::overriding(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=0, must-revalidate"),
))
.service(ServeDir::new("static")),
)
.layer(
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().level(Level::INFO))
.on_response(DefaultOnResponse::new().level(Level::INFO)),
)
.layer(middleware::from_fn(log_response_status)) .layer(middleware::from_fn(log_response_status))
.with_state(state) .with_state(state)
} }
@@ -252,63 +203,6 @@ struct CategoryForm {
csrf: String, csrf: String,
} }
#[derive(Debug, Deserialize)]
struct PasskeyRegisterStartForm {
csrf: String,
}
#[derive(Debug, Deserialize)]
struct PasskeyRegisterFinishForm {
csrf: String,
response: webauthn_rs::proto::RegisterPublicKeyCredential,
}
#[derive(Debug, Deserialize)]
struct PasskeyLoginStartForm {
email: String,
}
#[derive(Debug, Deserialize)]
struct PasskeyLoginFinishForm {
response: webauthn_rs::proto::PublicKeyCredential,
}
#[derive(Debug, Deserialize)]
struct DeletePasskeyForm {
csrf: String,
}
#[derive(Debug, Deserialize)]
struct MealForm {
name: String,
#[serde(default)]
description: String,
csrf: String,
}
#[derive(Debug, Deserialize)]
struct IngredientForm {
name: String,
#[serde(default)]
quantity: String,
#[serde(default)]
note: String,
#[serde(default)]
category_id: Option<String>,
csrf: String,
}
#[derive(Debug, Deserialize)]
struct AddMealForm {
meal_id: i64,
csrf: String,
}
#[derive(Debug, Deserialize)]
struct MealPickerQuery {
picker: Option<i64>,
}
async fn home() -> Redirect { async fn home() -> Redirect {
Redirect::to("/lists") Redirect::to("/lists")
} }
@@ -432,92 +326,6 @@ async fn logout(State(state): State<AppState>, user: CurrentUser) -> Result<Resp
Ok(response) Ok(response)
} }
async fn account_page(
State(state): State<AppState>,
user: CurrentUser,
) -> Result<Response, AppError> {
let passkeys = state.webauthn.list_passkeys(user.session.user.id).await?;
Ok(html_response(views::account_page(
&user.session.user,
&passkeys,
&user.session.csrf_token,
)))
}
async fn passkey_register_start(
State(state): State<AppState>,
user: CurrentUser,
Json(form): Json<PasskeyRegisterStartForm>,
) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?;
let challenge = state
.webauthn
.start_registration(&user.session.user)
.map_err(AppError::Database)?;
Ok(Json(challenge).into_response())
}
async fn passkey_register_finish(
State(state): State<AppState>,
user: CurrentUser,
Json(form): Json<PasskeyRegisterFinishForm>,
) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?;
state
.webauthn
.finish_registration(&user.session.user, form.response)
.await?;
Ok(Redirect::to("/account").into_response())
}
async fn passkey_login_start(
State(state): State<AppState>,
Json(form): Json<PasskeyLoginStartForm>,
) -> Result<Response, AppError> {
let email = form.email.trim().to_lowercase();
let Some((user, _)) = state.auth.find_user_by_email(email).await? else {
return Err(AppError::NotFound);
};
let challenge = state
.webauthn
.start_authentication(user.id)
.await
.map_err(AppError::Database)?;
Ok(Json(challenge).into_response())
}
async fn passkey_login_finish(
State(state): State<AppState>,
Json(form): Json<PasskeyLoginFinishForm>,
) -> Result<Response, AppError> {
let user_id = state
.webauthn
.resolve_user_id_for_assertion(&form.response)
.await?;
state
.webauthn
.finish_authentication(user_id, form.response)
.await?;
let (session_token, _) = state.auth.create_session_for_user(user_id).await?;
let mut response = Redirect::to("/lists").into_response();
set_session_cookie(&mut response, &session_token, state.cookie_secure);
Ok(response)
}
async fn delete_passkey(
State(state): State<AppState>,
user: CurrentUser,
Path(passkey_id): Path<i64>,
LoggedForm(form): LoggedForm<DeletePasskeyForm>,
) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?;
state
.webauthn
.delete_passkey(user.session.user.id, passkey_id)
.await?;
Ok(Redirect::to("/account").into_response())
}
async fn lists_page( async fn lists_page(
State(state): State<AppState>, State(state): State<AppState>,
user: CurrentUser, user: CurrentUser,
@@ -553,7 +361,7 @@ async fn list_page(
) -> Result<Response, AppError> { ) -> Result<Response, AppError> {
let access = require_list(&state, list_id).await?; let access = require_list(&state, list_id).await?;
let items = state.lists.items(list_id).await?; let items = state.lists.items(list_id).await?;
let categories = state.lists.categories().await?; let categories = state.lists.categories(list_id).await?;
let presence = state.realtime.presence(list_id).await; let presence = state.realtime.presence(list_id).await;
Ok(html_response(views::list_page( Ok(html_response(views::list_page(
&user.session.user, &user.session.user,
@@ -652,191 +460,30 @@ async fn delete_item(
async fn create_category( async fn create_category(
State(state): State<AppState>, State(state): State<AppState>,
user: CurrentUser, user: CurrentUser,
Path(list_id): Path<i64>,
LoggedForm(form): LoggedForm<CategoryForm>, LoggedForm(form): LoggedForm<CategoryForm>,
) -> Result<Response, AppError> { ) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?; verify_csrf(&user, &form.csrf)?;
require_list(&state, list_id).await?;
let name = form.name.trim().to_owned(); let name = form.name.trim().to_owned();
if name.is_empty() || name.chars().count() > 60 { if name.is_empty() || name.chars().count() > 60 {
return Err(AppError::BadRequest( return Err(AppError::BadRequest(
"Category names must be between 1 and 60 characters.".into(), "Category names must be between 1 and 60 characters.".into(),
)); ));
} }
state.lists.create_category(name).await?; state.lists.create_category(list_id, name).await?;
Ok(Redirect::to("/lists").into_response())
}
async fn meals_page( let access = require_list(&state, list_id).await?;
State(state): State<AppState>, let items = state.lists.items(list_id).await?;
user: CurrentUser, let categories = state.lists.categories(list_id).await?;
Query(query): Query<MealPickerQuery>, Ok(html_response(views::category_created(
) -> Result<Response, AppError> { &access,
let meals = state.meals.list_meals().await?; &items,
if let Some(list_id) = query.picker {
return Ok(html_response(views::meal_picker(
&meals,
list_id,
&user.session.csrf_token,
)));
}
Ok(html_response(views::meals_page(&user.session.user, &meals)))
}
async fn new_meal_page(user: CurrentUser) -> Result<Response, AppError> {
Ok(html_response(views::meal_form_page(
&user.session.user,
None,
&user.session.csrf_token,
)))
}
async fn create_meal(
State(state): State<AppState>,
user: CurrentUser,
LoggedForm(form): LoggedForm<MealForm>,
) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?;
let name = form.name.trim().to_owned();
if name.is_empty() || name.chars().count() > 120 {
return Err(AppError::BadRequest(
"Meal names must be between 1 and 120 characters.".into(),
));
}
let meal = state
.meals
.create_meal(name, form.description.trim().to_owned())
.await?;
Ok(Redirect::to(&format!("/meals/{}", meal.id)).into_response())
}
async fn meal_page(
State(state): State<AppState>,
user: CurrentUser,
Path(meal_id): Path<i64>,
) -> Result<Response, AppError> {
let meal = state
.meals
.get_meal(meal_id)
.await?
.ok_or(AppError::NotFound)?;
let categories = state.lists.categories().await?;
Ok(html_response(views::meal_page(
&user.session.user,
&meal,
&categories, &categories,
&user.session.csrf_token, &user.session.csrf_token,
))) )))
} }
async fn edit_meal(
State(state): State<AppState>,
user: CurrentUser,
Path(meal_id): Path<i64>,
LoggedForm(form): LoggedForm<MealForm>,
) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?;
let name = form.name.trim().to_owned();
if name.is_empty() || name.chars().count() > 120 {
return Err(AppError::BadRequest(
"Meal names must be between 1 and 120 characters.".into(),
));
}
state
.meals
.update_meal(meal_id, name, form.description.trim().to_owned())
.await?;
Ok(Redirect::to(&format!("/meals/{meal_id}")).into_response())
}
async fn delete_meal(
State(state): State<AppState>,
user: CurrentUser,
Path(meal_id): Path<i64>,
LoggedForm(form): LoggedForm<CsrfForm>,
) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?;
state.meals.delete_meal(meal_id).await?;
Ok(Redirect::to("/meals").into_response())
}
async fn add_ingredient(
State(state): State<AppState>,
user: CurrentUser,
Path(meal_id): Path<i64>,
LoggedForm(form): LoggedForm<IngredientForm>,
) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?;
let name = form.name.trim().to_owned();
if name.is_empty() || name.chars().count() > 120 {
return Err(AppError::BadRequest(
"Ingredient names must be between 1 and 120 characters.".into(),
));
}
state
.meals
.add_ingredient(
meal_id,
name,
form.quantity.trim().to_owned(),
form.note.trim().to_owned(),
parse_category_id(form.category_id),
)
.await?;
Ok(Redirect::to(&format!("/meals/{meal_id}")).into_response())
}
async fn edit_ingredient(
State(state): State<AppState>,
user: CurrentUser,
Path((meal_id, ingredient_id)): Path<(i64, i64)>,
LoggedForm(form): LoggedForm<IngredientForm>,
) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?;
let name = form.name.trim().to_owned();
if name.is_empty() || name.chars().count() > 120 {
return Err(AppError::BadRequest(
"Ingredient names must be between 1 and 120 characters.".into(),
));
}
state
.meals
.update_ingredient(
meal_id,
ingredient_id,
name,
form.quantity.trim().to_owned(),
form.note.trim().to_owned(),
parse_category_id(form.category_id),
)
.await?;
Ok(Redirect::to(&format!("/meals/{meal_id}")).into_response())
}
async fn delete_ingredient(
State(state): State<AppState>,
user: CurrentUser,
Path((meal_id, ingredient_id)): Path<(i64, i64)>,
LoggedForm(form): LoggedForm<CsrfForm>,
) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?;
state
.meals
.delete_ingredient(meal_id, ingredient_id)
.await?;
Ok(Redirect::to(&format!("/meals/{meal_id}")).into_response())
}
async fn add_meal_to_list(
State(state): State<AppState>,
user: CurrentUser,
Path(list_id): Path<i64>,
LoggedForm(form): LoggedForm<AddMealForm>,
) -> Result<Response, AppError> {
verify_csrf(&user, &form.csrf)?;
require_list(&state, list_id).await?;
state.meals.add_meal_to_list(form.meal_id, list_id).await?;
list_fragment_response(&state, &user, list_id).await
}
async fn create_invitation( async fn create_invitation(
State(state): State<AppState>, State(state): State<AppState>,
user: CurrentUser, user: CurrentUser,
@@ -1000,7 +647,7 @@ async fn websocket_snapshot(
) -> Result<String, AppError> { ) -> Result<String, AppError> {
let access = require_list(state, list_id).await?; let access = require_list(state, list_id).await?;
let items = state.lists.items(list_id).await?; let items = state.lists.items(list_id).await?;
let categories = state.lists.categories().await?; let categories = state.lists.categories(list_id).await?;
Ok( Ok(
views::live_list_fragments(&access, &items, &categories, &user.session.csrf_token) views::live_list_fragments(&access, &items, &categories, &user.session.csrf_token)
.into_string() .into_string()
@@ -1015,7 +662,7 @@ async fn websocket_list_update(
) -> Result<String, AppError> { ) -> Result<String, AppError> {
let access = require_list(state, list_id).await?; let access = require_list(state, list_id).await?;
let items = state.lists.items(list_id).await?; let items = state.lists.items(list_id).await?;
let categories = state.lists.categories().await?; let categories = state.lists.categories(list_id).await?;
Ok( Ok(
views::live_list_fragments(&access, &items, &categories, &user.session.csrf_token) views::live_list_fragments(&access, &items, &categories, &user.session.csrf_token)
.into_string(), .into_string(),
@@ -1029,7 +676,7 @@ async fn list_fragment_response(
) -> Result<Response, AppError> { ) -> Result<Response, AppError> {
let access = require_list(state, list_id).await?; let access = require_list(state, list_id).await?;
let items = state.lists.items(list_id).await?; let items = state.lists.items(list_id).await?;
let categories = state.lists.categories().await?; let categories = state.lists.categories(list_id).await?;
Ok(html_response(views::list_items_fragment( Ok(html_response(views::list_items_fragment(
&access, &access,
&items, &items,
+8 -56
View File
@@ -7,7 +7,6 @@ mod seed;
mod services; mod services;
mod sqlite; mod sqlite;
mod views; mod views;
mod webauthn;
use std::env; use std::env;
use std::path::Path as FilePath; use std::path::Path as FilePath;
@@ -19,38 +18,28 @@ use tracing::{info, warn};
use crate::http::{AppState, build_router}; use crate::http::{AppState, build_router};
use crate::hub::InMemoryHub; use crate::hub::InMemoryHub;
use crate::ports::{ use crate::ports::{
CategoryRepository, InvitationRepository, ItemRepository, ListRepository, CategoryRepository, InvitationRepository, ItemRepository, ListRepository, PasswordHasher,
MealIngredientRepository, MealRepository, PasskeyRepository, PasswordHasher, RealtimeNotifier, RealtimeNotifier, SessionRepository, TokenGenerator, UserRepository,
SessionRepository, TokenGenerator, UserRepository,
}; };
use crate::security::{Argon2PasswordHasher, RandomTokenGenerator}; use crate::security::{Argon2PasswordHasher, RandomTokenGenerator};
use crate::services::{AuthService, InvitationService, ListService, MealService, RegistrationMode}; use crate::services::{AuthService, InvitationService, ListService, RegistrationMode};
use crate::sqlite::{ use crate::sqlite::{
SqliteCategoryRepository, SqliteDatabase, SqliteInvitationRepository, SqliteItemRepository, SqliteCategoryRepository, SqliteInvitationRepository, SqliteItemRepository,
SqliteListRepository, SqliteMealIngredientRepository, SqliteMealRepository, SqliteListRepository, SqliteSessionRepository, SqliteDatabase, SqliteUserRepository,
SqlitePasskeyRepository, SqliteSessionRepository, SqliteUserRepository,
}; };
use crate::webauthn::{AppWebauthnConfig, WebAuthnService};
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> { async fn main() -> Result<(), Box<dyn std::error::Error>> {
tracing_subscriber::fmt() tracing_subscriber::fmt()
.with_env_filter( .with_env_filter(
env::var("RUST_LOG").unwrap_or_else(|_| "sustenance=info,tower_http=info".into()), env::var("RUST_LOG").unwrap_or_else(|_| "sustenance=debug,tower_http=info".into()),
) )
.init(); .init();
let database_path = env::var("DATABASE_PATH").unwrap_or_else(|_| "sustenance.db".into()); let database_path = env::var("DATABASE_PATH").unwrap_or_else(|_| "sustenance.db".into());
let bind_address = env::var("BIND_ADDRESS").unwrap_or_else(|_| "127.0.0.1:3000".into()); let bind_address = env::var("BIND_ADDRESS").unwrap_or_else(|_| "127.0.0.1:3000".into());
// For loopback hosts, advertise `localhost` so WebAuthn works locally (browsers let public_base_url =
// reject IP addresses as RP IDs). Access the app via http://localhost:PORT. env::var("PUBLIC_BASE_URL").unwrap_or_else(|_| format!("http://{}", bind_address));
let bind_host = bind_address.split(':').next().unwrap_or("127.0.0.1");
let is_loopback = bind_host == "127.0.0.1" || bind_host == "::1" || bind_host == "localhost";
let public_host = if is_loopback { "localhost" } else { bind_host };
let public_base_url = env::var("PUBLIC_BASE_URL").unwrap_or_else(|_| {
let port = bind_address.rsplit(':').next().unwrap_or("3000");
format!("http://{}:{}", public_host, port)
});
let cookie_secure = env::var("COOKIE_SECURE") let cookie_secure = env::var("COOKIE_SECURE")
.map(|value| value == "1" || value.eq_ignore_ascii_case("true")) .map(|value| value == "1" || value.eq_ignore_ascii_case("true"))
.unwrap_or(false); .unwrap_or(false);
@@ -74,11 +63,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let lists: Arc<dyn ListRepository> = Arc::new(SqliteListRepository); let lists: Arc<dyn ListRepository> = Arc::new(SqliteListRepository);
let categories: Arc<dyn CategoryRepository> = Arc::new(SqliteCategoryRepository); let categories: Arc<dyn CategoryRepository> = Arc::new(SqliteCategoryRepository);
let items: Arc<dyn ItemRepository> = Arc::new(SqliteItemRepository); let items: Arc<dyn ItemRepository> = Arc::new(SqliteItemRepository);
let meals: Arc<dyn MealRepository> = Arc::new(SqliteMealRepository);
let meal_ingredients: Arc<dyn MealIngredientRepository> =
Arc::new(SqliteMealIngredientRepository);
let invitations: Arc<dyn InvitationRepository> = Arc::new(SqliteInvitationRepository); let invitations: Arc<dyn InvitationRepository> = Arc::new(SqliteInvitationRepository);
let passkeys: Arc<dyn PasskeyRepository> = Arc::new(SqlitePasskeyRepository);
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2PasswordHasher); let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2PasswordHasher);
let tokens: Arc<dyn TokenGenerator> = Arc::new(RandomTokenGenerator); let tokens: Arc<dyn TokenGenerator> = Arc::new(RandomTokenGenerator);
let realtime: Arc<dyn RealtimeNotifier> = Arc::new(InMemoryHub::default()); let realtime: Arc<dyn RealtimeNotifier> = Arc::new(InMemoryHub::default());
@@ -103,37 +88,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Arc::clone(&invitations), Arc::clone(&invitations),
Arc::clone(&tokens), Arc::clone(&tokens),
)); ));
let meals_service = Arc::new(MealService::new(
db.clone(),
Arc::clone(&meals),
Arc::clone(&meal_ingredients),
Arc::clone(&lists),
Arc::clone(&items),
Arc::clone(&realtime),
));
// WebAuthn config from env vars. RP_ID must match the host users access the site from.
let rp_id = env::var("RP_ID").unwrap_or_else(|_| {
let host = public_base_url
.trim_start_matches("http://")
.trim_start_matches("https://")
.split('/')
.next()
.unwrap_or("localhost")
.split(':')
.next()
.unwrap_or("localhost")
.to_owned();
host
});
let rp_name = env::var("RP_NAME").unwrap_or_else(|_| "Sustenance".into());
let origin =
url::Url::parse(&public_base_url).map_err(|e| format!("invalid PUBLIC_BASE_URL: {e}"))?;
let webauthn_service = Arc::new(WebAuthnService::new(
db.clone(),
AppWebauthnConfig::new(rp_id, rp_name, origin),
Arc::clone(&passkeys),
));
let seed_path = env::var("SEED_CONFIG").unwrap_or_else(|_| "seed.json".into()); let seed_path = env::var("SEED_CONFIG").unwrap_or_else(|_| "seed.json".into());
seed::seed_if_needed(&db, &users, &hasher, FilePath::new(&seed_path)).await; seed::seed_if_needed(&db, &users, &hasher, FilePath::new(&seed_path)).await;
@@ -141,9 +95,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
let state = AppState { let state = AppState {
auth, auth,
lists: lists_service, lists: lists_service,
meals: meals_service,
invitations: invitations_service, invitations: invitations_service,
webauthn: webauthn_service,
realtime, realtime,
cookie_secure, cookie_secure,
public_base_url, public_base_url,
+12 -107
View File
@@ -1,10 +1,7 @@
use async_trait::async_trait; use async_trait::async_trait;
use sqlx::SqliteConnection; use sqlx::SqliteConnection;
use crate::domain::{ use crate::domain::{Category, DomainResult, GroceryList, Item, PresenceUser, SessionUser, User};
Category, DomainResult, GroceryList, Item, Meal, MealIngredient, Passkey, PresenceUser,
SessionUser, User,
};
/// Repositories take `&mut SqliteConnection` (which a `Transaction` derefs to), /// Repositories take `&mut SqliteConnection` (which a `Transaction` derefs to),
/// so several repositories can commit together atomically within a single /// so several repositories can commit together atomically within a single
@@ -27,34 +24,6 @@ pub trait UserRepository: Send + Sync {
async fn has_users(&self, txn: &mut SqliteConnection) -> DomainResult<bool>; async fn has_users(&self, txn: &mut SqliteConnection) -> DomainResult<bool>;
} }
#[async_trait]
pub trait PasskeyRepository: Send + Sync {
async fn create_passkey(
&self,
txn: &mut SqliteConnection,
user_id: i64,
credential_id: String,
credential: String,
counter: i64,
) -> DomainResult<Passkey>;
async fn find_by_credential_id(
&self,
txn: &mut SqliteConnection,
credential_id: String,
) -> DomainResult<Option<Passkey>>;
async fn list_for_user(
&self,
txn: &mut SqliteConnection,
user_id: i64,
) -> DomainResult<Vec<Passkey>>;
async fn delete_passkey(
&self,
txn: &mut SqliteConnection,
user_id: i64,
passkey_id: i64,
) -> DomainResult<()>;
}
#[async_trait] #[async_trait]
pub trait SessionRepository: Send + Sync { pub trait SessionRepository: Send + Sync {
async fn create_session( async fn create_session(
@@ -91,17 +60,17 @@ pub trait ListRepository: Send + Sync {
#[async_trait] #[async_trait]
pub trait CategoryRepository: Send + Sync { pub trait CategoryRepository: Send + Sync {
async fn categories(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<Category>>; async fn categories(
async fn create_category(&self, txn: &mut SqliteConnection, name: String) -> DomainResult<i64>; &self,
} txn: &mut SqliteConnection,
list_id: i64,
/// A single item to insert in bulk, without a per-item revision bump. ) -> DomainResult<Vec<Category>>;
#[derive(Clone, Debug)] async fn create_category(
pub struct NewItem { &self,
pub name: String, txn: &mut SqliteConnection,
pub quantity: String, list_id: i64,
pub note: String, name: String,
pub category_id: Option<i64>, ) -> DomainResult<i64>;
} }
#[async_trait] #[async_trait]
@@ -116,12 +85,6 @@ pub trait ItemRepository: Send + Sync {
note: String, note: String,
category_id: Option<i64>, category_id: Option<i64>,
) -> DomainResult<i64>; ) -> DomainResult<i64>;
async fn add_items_bulk(
&self,
txn: &mut SqliteConnection,
list_id: i64,
items: Vec<NewItem>,
) -> DomainResult<i64>;
async fn set_item_checked( async fn set_item_checked(
&self, &self,
txn: &mut SqliteConnection, txn: &mut SqliteConnection,
@@ -163,64 +126,6 @@ pub trait InvitationRepository: Send + Sync {
) -> DomainResult<()>; ) -> DomainResult<()>;
} }
#[async_trait]
pub trait MealRepository: Send + Sync {
async fn create_meal(
&self,
txn: &mut SqliteConnection,
name: String,
description: String,
) -> DomainResult<Meal>;
async fn get_meal(
&self,
txn: &mut SqliteConnection,
meal_id: i64,
) -> DomainResult<Option<Meal>>;
async fn list_meals(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<Meal>>;
async fn update_meal(
&self,
txn: &mut SqliteConnection,
meal_id: i64,
name: String,
description: String,
) -> DomainResult<()>;
async fn delete_meal(&self, txn: &mut SqliteConnection, meal_id: i64) -> DomainResult<()>;
}
#[async_trait]
pub trait MealIngredientRepository: Send + Sync {
async fn ingredients_for_meal(
&self,
txn: &mut SqliteConnection,
meal_id: i64,
) -> DomainResult<Vec<MealIngredient>>;
async fn add_ingredient(
&self,
txn: &mut SqliteConnection,
meal_id: i64,
name: String,
quantity: String,
note: String,
category_id: Option<i64>,
) -> DomainResult<i64>;
async fn update_ingredient(
&self,
txn: &mut SqliteConnection,
meal_id: i64,
ingredient_id: i64,
name: String,
quantity: String,
note: String,
category_id: Option<i64>,
) -> DomainResult<()>;
async fn delete_ingredient(
&self,
txn: &mut SqliteConnection,
meal_id: i64,
ingredient_id: i64,
) -> DomainResult<()>;
}
#[async_trait] #[async_trait]
pub trait PasswordHasher: Send + Sync { pub trait PasswordHasher: Send + Sync {
fn hash(&self, password: &str) -> DomainResult<String>; fn hash(&self, password: &str) -> DomainResult<String>;
+7 -187
View File
@@ -1,10 +1,9 @@
use std::sync::Arc; use std::sync::Arc;
use crate::domain::{DomainError, DomainResult, GroceryList, Item, Meal, SessionUser, User}; use crate::domain::{DomainError, DomainResult, GroceryList, Item, SessionUser, User};
use crate::ports::{ use crate::ports::{
CategoryRepository, InvitationRepository, ItemRepository, ListRepository, CategoryRepository, InvitationRepository, ItemRepository, ListRepository, PasswordHasher,
MealIngredientRepository, MealRepository, NewItem, PasswordHasher, RealtimeNotifier, RealtimeNotifier, SessionRepository, TokenGenerator, UserRepository,
SessionRepository, TokenGenerator, UserRepository,
}; };
use crate::sqlite::SqliteDatabase; use crate::sqlite::SqliteDatabase;
@@ -125,20 +124,6 @@ impl AuthService {
.await .await
} }
pub async fn find_user_by_email(&self, email: String) -> DomainResult<Option<(User, String)>> {
let users = Arc::clone(&self.users);
self.db
.run(move |txn| Box::pin(async move { users.find_user_by_email(txn, email).await }))
.await
}
pub async fn create_session_for_user(&self, user_id: i64) -> DomainResult<(String, String)> {
let sessions = Arc::clone(&self.sessions);
self.db
.run(move |txn| Box::pin(async move { sessions.create_session(txn, user_id).await }))
.await
}
pub async fn logout(&self, session_token: String) -> DomainResult<()> { pub async fn logout(&self, session_token: String) -> DomainResult<()> {
let sessions = Arc::clone(&self.sessions); let sessions = Arc::clone(&self.sessions);
self.db self.db
@@ -202,10 +187,10 @@ impl ListService {
.await .await
} }
pub async fn categories(&self) -> DomainResult<Vec<crate::domain::Category>> { pub async fn categories(&self, list_id: i64) -> DomainResult<Vec<crate::domain::Category>> {
let categories = Arc::clone(&self.categories); let categories = Arc::clone(&self.categories);
self.db self.db
.run(move |txn| Box::pin(async move { categories.categories(txn).await })) .run(move |txn| Box::pin(async move { categories.categories(txn, list_id).await }))
.await .await
} }
@@ -285,177 +270,12 @@ impl ListService {
Ok(revision) Ok(revision)
} }
pub async fn create_category(&self, name: String) -> DomainResult<i64> { pub async fn create_category(&self, list_id: i64, name: String) -> DomainResult<i64> {
let categories = Arc::clone(&self.categories); let categories = Arc::clone(&self.categories);
self.db
.run(move |txn| Box::pin(async move { categories.create_category(txn, name).await }))
.await
}
}
pub struct MealService {
db: SqliteDatabase,
meals: Arc<dyn MealRepository>,
ingredients: Arc<dyn MealIngredientRepository>,
lists: Arc<dyn ListRepository>,
items: Arc<dyn ItemRepository>,
realtime: Arc<dyn RealtimeNotifier>,
}
impl MealService {
pub fn new(
db: SqliteDatabase,
meals: Arc<dyn MealRepository>,
ingredients: Arc<dyn MealIngredientRepository>,
lists: Arc<dyn ListRepository>,
items: Arc<dyn ItemRepository>,
realtime: Arc<dyn RealtimeNotifier>,
) -> Self {
Self {
db,
meals,
ingredients,
lists,
items,
realtime,
}
}
pub async fn create_meal(&self, name: String, description: String) -> DomainResult<Meal> {
let meals = Arc::clone(&self.meals);
self.db
.run(move |txn| {
Box::pin(async move { meals.create_meal(txn, name, description).await })
})
.await
}
pub async fn get_meal(&self, meal_id: i64) -> DomainResult<Option<Meal>> {
let meals = Arc::clone(&self.meals);
self.db
.run(move |txn| Box::pin(async move { meals.get_meal(txn, meal_id).await }))
.await
}
pub async fn list_meals(&self) -> DomainResult<Vec<Meal>> {
let meals = Arc::clone(&self.meals);
self.db
.run(move |txn| Box::pin(async move { meals.list_meals(txn).await }))
.await
}
pub async fn update_meal(
&self,
meal_id: i64,
name: String,
description: String,
) -> DomainResult<()> {
let meals = Arc::clone(&self.meals);
self.db
.run(move |txn| {
Box::pin(async move { meals.update_meal(txn, meal_id, name, description).await })
})
.await
}
pub async fn delete_meal(&self, meal_id: i64) -> DomainResult<()> {
let meals = Arc::clone(&self.meals);
self.db
.run(move |txn| Box::pin(async move { meals.delete_meal(txn, meal_id).await }))
.await
}
pub async fn add_ingredient(
&self,
meal_id: i64,
name: String,
quantity: String,
note: String,
category_id: Option<i64>,
) -> DomainResult<i64> {
let ingredients = Arc::clone(&self.ingredients);
self.db
.run(move |txn| {
Box::pin(async move {
ingredients
.add_ingredient(txn, meal_id, name, quantity, note, category_id)
.await
})
})
.await
}
pub async fn update_ingredient(
&self,
meal_id: i64,
ingredient_id: i64,
name: String,
quantity: String,
note: String,
category_id: Option<i64>,
) -> DomainResult<()> {
let ingredients = Arc::clone(&self.ingredients);
self.db
.run(move |txn| {
Box::pin(async move {
ingredients
.update_ingredient(
txn,
meal_id,
ingredient_id,
name,
quantity,
note,
category_id,
)
.await
})
})
.await
}
pub async fn delete_ingredient(&self, meal_id: i64, ingredient_id: i64) -> DomainResult<()> {
let ingredients = Arc::clone(&self.ingredients);
self.db
.run(move |txn| {
Box::pin(async move {
ingredients
.delete_ingredient(txn, meal_id, ingredient_id)
.await
})
})
.await
}
/// Expands a meal's ingredients into items on a list in one unit of work,
/// bumping the list revision exactly once.
pub async fn add_meal_to_list(&self, meal_id: i64, list_id: i64) -> DomainResult<i64> {
let meals = Arc::clone(&self.meals);
let lists = Arc::clone(&self.lists);
let items = Arc::clone(&self.items);
let revision = self let revision = self
.db .db
.run(move |txn| { .run(move |txn| {
Box::pin(async move { Box::pin(async move { categories.create_category(txn, list_id, name).await })
let meal = meals
.get_meal(txn, meal_id)
.await?
.ok_or(DomainError::NotFound)?;
if lists.get_list(txn, list_id).await?.is_none() {
return Err(DomainError::NotFound);
}
let new_items = meal
.ingredients
.into_iter()
.map(|ingredient| NewItem {
name: ingredient.name,
quantity: ingredient.quantity,
note: ingredient.note,
category_id: ingredient.category_id,
})
.collect();
items.add_items_bulk(txn, list_id, new_items).await
})
}) })
.await?; .await?;
self.realtime.publish_list_changed(list_id, revision).await; self.realtime.publish_list_changed(list_id, revision).await;
+77 -927
View File
File diff suppressed because it is too large Load Diff
+47 -422
View File
@@ -1,9 +1,8 @@
use maud::{DOCTYPE, Markup, html}; use maud::{DOCTYPE, Markup, html};
use pulldown_cmark::{Options, Parser, html as cmark_html};
use crate::{ use crate::{
domain::PresenceUser, domain::PresenceUser,
domain::{Category, GroceryList, Item, Meal, MealIngredient, Passkey, User}, domain::{Category, GroceryList, Item, User},
}; };
pub fn login_page(error: Option<&str>, invite: Option<&str>) -> Markup { pub fn login_page(error: Option<&str>, invite: Option<&str>) -> Markup {
@@ -28,11 +27,8 @@ pub fn login_page(error: Option<&str>, invite: Option<&str>) -> Markup {
input id="password" name="password" type="password" autocomplete="current-password" required; input id="password" name="password" type="password" autocomplete="current-password" required;
button class="button button-primary" type="submit" { "Sign in" } button class="button button-primary" type="submit" { "Sign in" }
} }
div class="auth-divider" { span { "or" } }
button id="passkey-login" class="button button-secondary" type="button" { "Sign in with a passkey" }
p class="auth-switch" { "Need an account? " a href="/register" { "Create one" } } p class="auth-switch" { "Need an account? " a href="/register" { "Create one" } }
} }
script src="/static/passkey-login.js" {}
}, },
) )
} }
@@ -82,51 +78,6 @@ pub fn registration_closed_page() -> Markup {
) )
} }
pub fn account_page(user: &User, passkeys: &[Passkey], csrf_token: &str) -> Markup {
page(
"Account",
Some(user),
html! {
div class="page-heading" {
div {
p class="eyebrow" { "ACCOUNT" }
h1 { "Account" }
p class="lede" { "Manage your sign-in methods." }
}
}
div class="dashboard-grid" {
section class="panel" {
div class="panel-heading" {
h2 { "Passkeys" }
span class="count-badge" { (passkeys.len()) }
}
p { "Passkeys let you sign in without a password using your device." }
@if passkeys.is_empty() {
p class="muted" { "You have no passkeys yet." }
} @else {
div class="passkey-list" {
@for passkey in passkeys {
div class="passkey-row" {
div class="item-copy" {
strong { "Passkey" }
small { (passkey.credential_id) }
}
form method="post" action=(format!("/account/passkeys/{}/delete", passkey.id)) {
input type="hidden" name="csrf" value=(csrf_token);
button class="danger-link" type="submit" { "Remove" }
}
}
}
}
}
button id="add-passkey" class="button button-primary" type="button" data-csrf=(csrf_token) { "Add a passkey" }
}
}
script src="/static/passkey-register.js" {}
},
)
}
pub fn lists_page(user: &User, lists: &[GroceryList], csrf_token: &str) -> Markup { pub fn lists_page(user: &User, lists: &[GroceryList], csrf_token: &str) -> Markup {
page( page(
"Your lists", "Your lists",
@@ -193,340 +144,6 @@ pub fn lists_page(user: &User, lists: &[GroceryList], csrf_token: &str) -> Marku
) )
} }
pub fn meals_page(user: &User, meals: &[Meal]) -> Markup {
page(
"Meals",
Some(user),
html! {
div class="page-heading" {
div {
p class="eyebrow" { "MEAL LIBRARY" }
h1 { "Meals" }
p class="lede" { "Save a meal and add its ingredients to any list." }
}
a class="button button-primary" href="/meals/new" { "New meal" }
}
div class="dashboard-grid" {
section class="panel" {
div class="panel-heading" {
h2 { "All meals" }
span class="count-badge" { (meals.len()) }
}
@if meals.is_empty() {
div class="empty-state" {
div class="empty-mark" { "🍽" }
h3 { "No meals yet" }
p { "Create a meal to reuse its ingredients across your lists." }
}
} @else {
div class="list-cards" {
@for meal in meals {
a class="list-card" href=(format!("/meals/{}", meal.id)) {
span class="list-card-icon" { "🍽" }
span class="list-card-copy" {
strong { (meal.name) }
small { (meal.ingredients.len()) " ingredients" }
}
span class="list-card-arrow" { "" }
}
}
}
}
}
}
},
)
}
pub fn meal_picker(meals: &[Meal], list_id: i64, csrf_token: &str) -> Markup {
html! {
div class="meal-picker-backdrop" onclick="if (event.target === this) this.remove()" {
div class="meal-picker-modal" role="dialog" aria-modal="true" aria-label="Add a meal" {
div class="meal-picker-header" {
div {
p class="eyebrow" { "ADD TO LIST" }
h2 { "Add a meal" }
}
button class="meal-picker-close" type="button" aria-label="Close" onclick="this.closest('.meal-picker-backdrop').remove()" { "" }
}
@if meals.is_empty() {
div class="meal-picker-empty" {
span class="empty-mark" { "🍽" }
h3 { "No meals yet" }
p { "Create a meal first, then add it to any list." }
a class="button button-primary" href="/meals/new" { "Create a meal" }
}
} @else {
div class="meal-picker-list" {
@for meal in meals {
form
hx-post=(format!("/lists/{}/add-meal", list_id))
hx-target="#list-items"
hx-swap="outerHTML"
hx-on::after-request="if (event.detail.successful) this.closest('.meal-picker-backdrop').remove()"
class="meal-picker-row"
{
input type="hidden" name="csrf" value=(csrf_token);
input type="hidden" name="meal_id" value=(meal.id);
button class="meal-picker-button" type="submit" {
span class="meal-picker-icon" { "🍽" }
span class="meal-picker-copy" {
strong { (meal.name) }
small { (meal.ingredients.len()) " ingredients" }
}
span class="meal-picker-add" { "Add" }
}
}
}
}
}
}
}
}
}
pub fn meal_form_page(user: &User, meal: Option<&Meal>, csrf_token: &str) -> Markup {
let (title, action, name, description) = match meal {
Some(meal) => (
"Edit meal",
format!("/meals/{}/edit", meal.id),
meal.name.clone(),
meal.description.clone(),
),
None => ("New meal", "/meals".into(), String::new(), String::new()),
};
page(
title,
Some(user),
html! {
div class="page-heading" {
a class="back-link" href="/meals" { "← All meals" }
h1 { (title) }
}
section class="panel" {
form method="post" action=(action) class="stack" {
input type="hidden" name="csrf" value=(csrf_token);
label for="meal-name" { "Name" }
input id="meal-name" name="name" type="text" maxlength="120" value=(name) required;
label for="meal-description" { "Description (markdown)" }
textarea id="meal-description" name="description" rows="8" { (description) }
button class="button button-primary" type="submit" { "Save meal" }
}
}
@if meal.is_none() {
p class="muted" { "You can add ingredients after creating the meal." }
}
},
)
}
pub fn meal_page(user: &User, meal: &Meal, categories: &[Category], csrf_token: &str) -> Markup {
page(
&meal.name,
Some(user),
html! {
div class="page-heading" {
a class="back-link" href="/meals" { "← All meals" }
div class="list-topbar-actions" {
button type="button" class="button button-small button-quiet" onclick="document.getElementById('meal-edit-modal').showModal()" { "Edit" }
form method="post" action=(format!("/meals/{}/delete", meal.id)) {
input type="hidden" name="csrf" value=(csrf_token);
button class="danger-link" type="submit" { "Delete" }
}
}
}
dialog id="meal-edit-modal" class="item-modal" {
div class="item-modal-card" {
div class="item-modal-header" {
h3 { "Edit meal" }
button type="button" class="meal-picker-close" aria-label="Close" onclick="this.closest('dialog').close()" { "" }
}
form method="post" action=(format!("/meals/{}/edit", meal.id)) class="stack" {
input type="hidden" name="csrf" value=(csrf_token);
label { "Name" }
input id="meal-edit-name" name="name" value=(meal.name) maxlength="120" required;
label { "Description (markdown)" }
textarea id="meal-edit-description" name="description" rows="8" { (meal.description) }
button id="meal-edit-save" class="button button-primary" type="submit" { "Save meal" }
}
}
}
div class="list-layout" {
section class="panel list-panel" {
div class="list-heading" {
div {
p class="eyebrow" { "MEAL" }
h1 { (meal.name) }
}
}
@if meal.description.is_empty() {
p class="muted" { "No description." }
} @else {
div class="markdown" { (render_markdown(&meal.description)) }
}
h2 class="category-heading" { "Ingredients" }
@if meal.ingredients.is_empty() {
p class="muted" { "No ingredients yet." }
} @else {
div class="item-list" {
@for group in ingredient_groups(&meal.ingredients, categories) {
(ingredient_category_group(&group.0, &group.1, meal.id, categories, csrf_token))
}
}
}
}
aside class="side-column" {
section class="panel" {
div class="panel-heading" { h2 { "Add ingredient" } }
form id="add-ingredient-form" method="post" action=(format!("/meals/{}/ingredients", meal.id)) class="stack" {
input type="hidden" name="csrf" value=(csrf_token);
label { "Name" }
input id="ingredient-name" name="name" type="text" maxlength="120" required;
label { "Quantity" }
input id="ingredient-quantity" name="quantity" type="text" maxlength="40";
label { "Note" }
input id="ingredient-note" name="note" type="text" maxlength="120";
label { "Category" }
select id="ingredient-category" name="category_id" {
(category_options(categories, None))
}
button id="add-ingredient-button" class="button button-primary" type="submit" { "Add ingredient" }
}
}
}
}
},
)
}
fn ingredient_row(
ingredient: &MealIngredient,
meal_id: i64,
categories: &[Category],
csrf_token: &str,
) -> Markup {
html! {
div class="item-copy" {
@if !ingredient.quantity.is_empty() {
span class="item-qty" { "(" (ingredient.quantity) ")" }
}
strong { (ingredient.name) }
@if !ingredient.note.is_empty() {
small { (ingredient.note) }
}
}
button type="button" class="item-actions-button" aria-label="Ingredient actions" onclick=(format!("document.getElementById('ingredient-edit-{}').showModal()", ingredient.id)) { "•••" }
dialog id=(format!("ingredient-edit-{}", ingredient.id)) class="item-modal" {
div class="item-modal-card" {
div class="item-modal-header" {
h3 { (ingredient.name) }
button type="button" class="meal-picker-close" aria-label="Close" onclick="this.closest('dialog').close()" { "" }
}
form
hx-post=(format!("/meals/{}/ingredients/{}/edit", meal_id, ingredient.id))
hx-target="body"
hx-swap="outerHTML"
class="stack"
{
input type="hidden" name="csrf" value=(csrf_token);
label { "Name" }
input id=(format!("ingredient-edit-name-{}", ingredient.id)) name="name" value=(ingredient.name) maxlength="120" required;
label { "Quantity" }
input id=(format!("ingredient-edit-quantity-{}", ingredient.id)) name="quantity" value=(ingredient.quantity) maxlength="40";
label { "Note" }
input id=(format!("ingredient-edit-note-{}", ingredient.id)) name="note" value=(ingredient.note) maxlength="120";
label { "Category" }
select id=(format!("ingredient-edit-category-{}", ingredient.id)) name="category_id" {
(category_options(categories, ingredient.category_id))
}
button id=(format!("ingredient-edit-save-{}", ingredient.id)) class="button button-primary" type="submit" { "Save" }
}
form method="post" action=(format!("/meals/{}/ingredients/{}/delete", meal_id, ingredient.id)) {
input type="hidden" name="csrf" value=(csrf_token);
button id=(format!("ingredient-edit-delete-{}", ingredient.id)) class="danger-link" type="submit" { "Remove" }
}
}
}
}
}
fn ingredient_groups<'a>(
ingredients: &'a [MealIngredient],
categories: &[Category],
) -> Vec<(String, Vec<&'a MealIngredient>)> {
let mut groups = Vec::new();
for category in categories {
let in_category = ingredients
.iter()
.filter(|ingredient| ingredient.category_id == Some(category.id))
.collect::<Vec<_>>();
if !in_category.is_empty() {
groups.push((category.name.clone(), in_category));
}
}
let uncategorized = ingredients
.iter()
.filter(|ingredient| ingredient.category_id.is_none())
.collect::<Vec<_>>();
if !uncategorized.is_empty() {
groups.push(("Uncategorized".into(), uncategorized));
}
groups
}
fn ingredient_category_group(
name: &str,
ingredients: &[&MealIngredient],
meal_id: i64,
categories: &[Category],
csrf_token: &str,
) -> Markup {
html! {
section class="category-group" {
h2 class="category-heading" { (name) }
ul class="ingredient-list" {
@for ingredient in ingredients {
li {
(ingredient_row(ingredient, meal_id, categories, csrf_token))
}
}
}
}
}
}
fn render_markdown(source: &str) -> Markup {
let mut options = Options::empty();
options.insert(Options::ENABLE_STRIKETHROUGH);
let parser = Parser::new_ext(source, options);
let mut buffer = String::new();
cmark_html::push_html(&mut buffer, parser);
html! {
(maud::PreEscaped(buffer))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn render_markdown_turns_bullets_into_list_html() {
let html = render_markdown("- one\n- two\n").into_string();
assert!(html.contains("<ul>"), "expected <ul>, got: {html}");
assert!(html.contains("<li>"), "expected <li>, got: {html}");
assert!(!html.contains("* one"), "raw bullet leaked through: {html}");
}
#[test]
fn render_markdown_renders_emphasis() {
let html = render_markdown("**bold** and *italic*").into_string();
assert!(html.contains("<strong>"), "expected <strong>, got: {html}");
assert!(html.contains("<em>"), "expected <em>, got: {html}");
}
}
pub fn list_page( pub fn list_page(
user: &User, user: &User,
list: &GroceryList, list: &GroceryList,
@@ -543,10 +160,8 @@ pub fn list_page(
a class="back-link" href="/lists" { "← All lists" } a class="back-link" href="/lists" { "← All lists" }
div class="list-topbar-actions" { div class="list-topbar-actions" {
span class="live-pill" { span class="live-dot" {} "Live" } span class="live-pill" { span class="live-dot" {} "Live" }
button class="button button-small add-meal-button" hx-get=(format!("/meals?picker={}", list.id)) hx-target="#meal-picker" hx-swap="innerHTML" { "+ Add meal" }
} }
} }
div id="meal-picker" class="meal-picker" {}
div class="list-layout" { div class="list-layout" {
section class="panel list-panel" { section class="panel list-panel" {
div class="list-heading" { div class="list-heading" {
@@ -560,7 +175,7 @@ pub fn list_page(
} }
aside class="side-column" { aside class="side-column" {
(presence_panel(presence, false)) (presence_panel(presence, false))
(categories_panel(categories, csrf_token, false)) (categories_panel(list, categories, csrf_token, false))
section class="panel tip-panel" { section class="panel tip-panel" {
span class="tip-label" { "TIP" } span class="tip-label" { "TIP" }
p { "Check items off as you go. Everyone viewing this list will see it instantly." } p { "Check items off as you go. Everyone viewing this list will see it instantly." }
@@ -612,11 +227,11 @@ fn list_content(
input type="hidden" name="csrf" value=(csrf_token); input type="hidden" name="csrf" value=(csrf_token);
label class="sr-only" for="item-name" { "Item name" } label class="sr-only" for="item-name" { "Item name" }
input id="item-name" name="name" type="text" maxlength="120" placeholder="Add an item..." autocomplete="off" required; input id="item-name" name="name" type="text" maxlength="120" placeholder="Add an item..." autocomplete="off" required;
input id="item-quantity" name="quantity" type="text" maxlength="40" placeholder="Qty" aria-label="Quantity"; input name="quantity" type="text" maxlength="40" placeholder="Qty" aria-label="Quantity";
select id="item-category" name="category_id" aria-label="Category" { select name="category_id" aria-label="Category" {
(category_options(categories, None)) (category_options(categories, None))
} }
button id="add-item-button" class="button button-primary add-button" type="submit" { "+ Add" } button class="button button-primary add-button" type="submit" { "+ Add" }
} }
(list_items_fragment(list, items, categories, csrf_token, false)) (list_items_fragment(list, items, categories, csrf_token, false))
} }
@@ -712,44 +327,41 @@ fn item_row(item: &Item, categories: &[Category], csrf_token: &str) -> Markup {
{ {
input type="hidden" name="csrf" value=(csrf_token); input type="hidden" name="csrf" value=(csrf_token);
input type="hidden" name="checked" value=(next_checked); input type="hidden" name="checked" value=(next_checked);
button id=(format!("item-check-{}", item.id)) class="check-button" type="submit" aria-label=(if item.checked { "Mark unchecked" } else { "Mark complete" }) { button class="check-button" type="submit" aria-label=(if item.checked { "Mark unchecked" } else { "Mark complete" }) {
@if item.checked { "" } @else { "" } @if item.checked { "" } @else { "" }
} }
} }
label class="item-copy" for=(format!("item-check-{}", item.id)) { div class="item-copy" {
@if !item.quantity.is_empty() {
span class="item-qty" { "(" (item.quantity) ")" }
}
strong { (item.name) } strong { (item.name) }
@if !item.note.is_empty() { @if !item.quantity.is_empty() || !item.note.is_empty() {
small { (item.note) } small {
@if !item.quantity.is_empty() { (item.quantity) }
@if !item.quantity.is_empty() && !item.note.is_empty() { " · " }
@if !item.note.is_empty() { (item.note) }
}
} }
} }
button type="button" class="item-actions-button" aria-label="Item actions" onclick=(format!("document.getElementById('item-edit-{}').showModal()", item.id)) { "•••" } details class="item-actions" {
dialog id=(format!("item-edit-{}", item.id)) class="item-modal" { summary aria-label="Item actions" { "•••" }
div class="item-modal-card" { div class="item-menu" {
div class="item-modal-header" {
h3 { (item.name) }
button type="button" class="meal-picker-close" aria-label="Close" onclick="this.closest('dialog').close()" { "" }
}
form form
hx-post=(format!("/lists/{}/items/{}/edit", item.list_id, item.id)) hx-post=(format!("/lists/{}/items/{}/edit", item.list_id, item.id))
hx-target="#list-items" hx-target="#list-items"
hx-swap="outerHTML" hx-swap="outerHTML"
class="stack" class="edit-form stack"
{ {
input type="hidden" name="csrf" value=(csrf_token); input type="hidden" name="csrf" value=(csrf_token);
label { "Name" } label { "Name" }
input id=(format!("item-edit-name-{}", item.id)) name="name" value=(item.name) maxlength="120" required; input name="name" value=(item.name) maxlength="120" required;
label { "Quantity" } label { "Quantity" }
input id=(format!("item-edit-quantity-{}", item.id)) name="quantity" value=(item.quantity) maxlength="40"; input name="quantity" value=(item.quantity) maxlength="40";
label { "Note" } label { "Note" }
input id=(format!("item-edit-note-{}", item.id)) name="note" value=(item.note) maxlength="120"; input name="note" value=(item.note) maxlength="120";
label { "Category" } label { "Category" }
select id=(format!("item-edit-category-{}", item.id)) name="category_id" { select name="category_id" {
(category_options(categories, item.category_id)) (category_options(categories, item.category_id))
} }
button id=(format!("item-edit-save-{}", item.id)) class="button button-primary" type="submit" { "Save" } button class="button button-small button-secondary" type="submit" { "Save" }
} }
form form
hx-post=(format!("/lists/{}/items/{}/delete", item.list_id, item.id)) hx-post=(format!("/lists/{}/items/{}/delete", item.list_id, item.id))
@@ -757,7 +369,7 @@ fn item_row(item: &Item, categories: &[Category], csrf_token: &str) -> Markup {
hx-swap="outerHTML" hx-swap="outerHTML"
{ {
input type="hidden" name="csrf" value=(csrf_token); input type="hidden" name="csrf" value=(csrf_token);
button id=(format!("item-edit-delete-{}", item.id)) class="danger-link" type="submit" { "Remove item" } button class="danger-link" type="submit" { "Remove item" }
} }
} }
} }
@@ -782,7 +394,12 @@ fn category_options(categories: &[Category], selected: Option<i64>) -> Markup {
} }
} }
pub fn categories_panel(categories: &[Category], csrf_token: &str, out_of_band: bool) -> Markup { pub fn categories_panel(
list: &GroceryList,
categories: &[Category],
csrf_token: &str,
out_of_band: bool,
) -> Markup {
let panel = html! { let panel = html! {
div class="panel-heading" { div class="panel-heading" {
h2 { "Categories" } h2 { "Categories" }
@@ -790,15 +407,15 @@ pub fn categories_panel(categories: &[Category], csrf_token: &str, out_of_band:
} }
p { "Organize items by aisle or shopping area." } p { "Organize items by aisle or shopping area." }
form form
hx-post="/categories" hx-post=(format!("/lists/{}/categories", list.id))
hx-target="#category-result" hx-target="#category-result"
hx-swap="innerHTML" hx-swap="innerHTML"
hx-on::after-request="if (event.detail.successful) window.location.reload()" hx-on::after-request="if (event.detail.successful) this.reset()"
class="category-form" class="category-form"
{ {
input type="hidden" name="csrf" value=(csrf_token); input type="hidden" name="csrf" value=(csrf_token);
input id="category-name" name="name" type="text" maxlength="60" placeholder="Add a category" required; input name="name" type="text" maxlength="60" placeholder="Add a category" required;
button id="add-category-button" class="button button-small button-secondary" type="submit" { "Add" } button class="button button-small button-secondary" type="submit" { "Add" }
} }
@if categories.is_empty() { @if categories.is_empty() {
p class="muted category-empty" { "No categories yet." } p class="muted category-empty" { "No categories yet." }
@@ -831,7 +448,19 @@ pub fn live_list_fragments(
) -> Markup { ) -> Markup {
html! { html! {
(list_content_fragment(list, items, categories, csrf_token, true)) (list_content_fragment(list, items, categories, csrf_token, true))
(categories_panel(categories, csrf_token, true)) (categories_panel(list, categories, csrf_token, true))
}
}
pub fn category_created(
list: &GroceryList,
items: &[Item],
categories: &[Category],
csrf_token: &str,
) -> Markup {
html! {
p class="category-success" { "Category added." }
(live_list_fragments(list, items, categories, csrf_token))
} }
} }
@@ -950,12 +579,8 @@ fn page(title: &str, user: Option<&User>, content: Markup) -> Markup {
header class="site-header" { header class="site-header" {
a class="brand" href="/lists" { span class="brand-mark" { "S" } "Sustenance" } a class="brand" href="/lists" { span class="brand-mark" { "S" } "Sustenance" }
@if let Some(user) = user { @if let Some(user) = user {
nav class="site-nav" {
a href="/lists" { "Lists" }
a href="/meals" { "Meals" }
}
div class="account-nav" { div class="account-nav" {
a class="user-name" href="/account" { (user.display_name) } span class="user-name" { (user.display_name) }
form method="post" action="/logout" { form method="post" action="/logout" {
button class="text-button" type="submit" { "Sign out" } button class="text-button" type="submit" { "Sign out" }
} }
-271
View File
@@ -1,271 +0,0 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use webauthn_rs::{
Webauthn,
core::{AuthenticationState, RegistrationState, WebauthnConfig},
error::WebauthnError as WanError,
proto::{
CreationChallengeResponse, Credential, PublicKeyCredential, RegisterPublicKeyCredential,
RequestChallengeResponse,
},
};
use crate::domain::{DomainError, DomainResult, Passkey as DbPasskey, User};
use crate::ports::PasskeyRepository;
use crate::sqlite::SqliteDatabase;
/// Site-specific WebAuthn configuration, derived from env vars.
pub struct AppWebauthnConfig {
rp_id: String,
rp_name: String,
origin: url::Url,
}
impl AppWebauthnConfig {
pub fn new(rp_id: String, rp_name: String, origin: url::Url) -> Self {
Self {
rp_id,
rp_name,
origin,
}
}
}
impl WebauthnConfig for AppWebauthnConfig {
fn get_relying_party_name(&self) -> &str {
&self.rp_name
}
fn get_origin(&self) -> &url::Url {
&self.origin
}
fn get_relying_party_id(&self) -> &str {
&self.rp_id
}
}
/// A single-use, in-memory challenge store keyed by user id.
#[derive(Default)]
struct ChallengeStore {
registrations: HashMap<i64, RegistrationState>,
authentications: HashMap<i64, AuthenticationState>,
}
pub struct WebAuthnService {
db: SqliteDatabase,
webauthn: Webauthn<AppWebauthnConfig>,
passkeys: Arc<dyn PasskeyRepository>,
challenges: Mutex<ChallengeStore>,
}
impl WebAuthnService {
pub fn new(
db: SqliteDatabase,
config: AppWebauthnConfig,
passkeys: Arc<dyn PasskeyRepository>,
) -> Self {
let webauthn = Webauthn::new(config);
Self {
db,
webauthn,
passkeys,
challenges: Mutex::new(ChallengeStore::default()),
}
}
/// Start a passkey registration ceremony for an authenticated user.
pub fn start_registration(&self, user: &User) -> DomainResult<CreationChallengeResponse> {
let (challenge, state) = self
.webauthn
.generate_challenge_register(&user.display_name, true)
.map_err(webauthn_error)?;
self.challenges
.lock()
.map_err(|_| DomainError::Database("challenge lock poisoned".into()))?
.registrations
.insert(user.id, state);
Ok(challenge)
}
/// Finish a passkey registration ceremony and persist the credential.
pub async fn finish_registration(
&self,
user: &User,
response: RegisterPublicKeyCredential,
) -> DomainResult<()> {
let state = self
.challenges
.lock()
.map_err(|_| DomainError::Database("challenge lock poisoned".into()))?
.registrations
.remove(&user.id)
.ok_or(DomainError::NotFound)?;
let passkeys = Arc::clone(&self.passkeys);
let credential_id = response.raw_id.0.clone();
let user_id = user.id;
let credential = self
.webauthn
.register_credential(&response, &state, |_| Ok(false))
.map_err(webauthn_error)?;
let serialized = serde_json::to_string(&credential.0)
.map_err(|e| DomainError::Database(e.to_string()))?;
let credential_id_b64 = base64_url(&credential_id);
let counter = credential.0.counter as i64;
self.db
.run(move |txn| {
let passkeys = passkeys.clone();
Box::pin(async move {
passkeys
.create_passkey(txn, user_id, credential_id_b64, serialized, counter)
.await?;
Ok(())
})
})
.await
}
/// Start a passkey authentication ceremony for a user.
pub async fn start_authentication(
&self,
user_id: i64,
) -> DomainResult<RequestChallengeResponse> {
let passkeys = Arc::clone(&self.passkeys);
let db = self.db.clone();
let credentials: Vec<Credential> = db
.run(move |txn| {
let passkeys = passkeys.clone();
Box::pin(async move {
let rows = passkeys.list_for_user(txn, user_id).await?;
let mut creds = Vec::new();
for row in rows {
let cred: Credential = serde_json::from_str(&row.credential)
.map_err(|e| DomainError::Database(e.to_string()))?;
creds.push(cred);
}
Ok(creds)
})
})
.await?;
if credentials.is_empty() {
return Err(DomainError::NotFound);
}
let (challenge, state) = self
.webauthn
.generate_challenge_authenticate(credentials)
.map_err(webauthn_error)?;
self.challenges
.lock()
.map_err(|_| DomainError::Database("challenge lock poisoned".into()))?
.authentications
.insert(user_id, state);
Ok(challenge)
}
/// Finish a passkey authentication ceremony.
pub async fn finish_authentication(
&self,
user_id: i64,
response: PublicKeyCredential,
) -> DomainResult<()> {
let state = self
.challenges
.lock()
.map_err(|_| DomainError::Database("challenge lock poisoned".into()))?
.authentications
.remove(&user_id)
.ok_or(DomainError::NotFound)?;
let (cred_id, auth_data) = self
.webauthn
.authenticate_credential(&response, &state)
.map_err(|e| {
tracing::error!(%e, "webauthn authenticate_credential failed");
webauthn_error(e)
})?;
let passkeys = Arc::clone(&self.passkeys);
let db = self.db.clone();
let credential_id_b64 = base64_url(cred_id);
db.run(move |txn| {
let passkeys = passkeys.clone();
Box::pin(async move {
let stored = passkeys
.find_by_credential_id(txn, credential_id_b64)
.await?
.ok_or(DomainError::NotFound)?;
let mut cred: Credential = serde_json::from_str(&stored.credential)
.map_err(|e| DomainError::Database(e.to_string()))?;
cred.counter = auth_data.counter;
let serialized = serde_json::to_string(&cred)
.map_err(|e| DomainError::Database(e.to_string()))?;
sqlx::query("UPDATE passkeys SET credential = ?1 WHERE id = ?2")
.bind(&serialized)
.bind(stored.id)
.execute(&mut *txn)
.await
.map_err(db_error)?;
Ok(())
})
})
.await
}
/// List the passkeys registered to a user.
pub async fn list_passkeys(&self, user_id: i64) -> DomainResult<Vec<DbPasskey>> {
let passkeys = Arc::clone(&self.passkeys);
self.db
.run(move |txn| {
let passkeys = passkeys.clone();
Box::pin(async move { passkeys.list_for_user(txn, user_id).await })
})
.await
}
/// Delete a passkey owned by a user.
pub async fn delete_passkey(&self, user_id: i64, passkey_id: i64) -> DomainResult<()> {
let passkeys = Arc::clone(&self.passkeys);
self.db
.run(move |txn| {
let passkeys = passkeys.clone();
Box::pin(async move { passkeys.delete_passkey(txn, user_id, passkey_id).await })
})
.await
}
/// Resolve the user id that owns the credential in an assertion response.
pub async fn resolve_user_id_for_assertion(
&self,
response: &PublicKeyCredential,
) -> DomainResult<i64> {
let passkeys = Arc::clone(&self.passkeys);
let db = self.db.clone();
let credential_id_b64 = base64_url(&response.raw_id.0);
db.run(move |txn| {
let passkeys = passkeys.clone();
Box::pin(async move {
let stored = passkeys
.find_by_credential_id(txn, credential_id_b64)
.await?
.ok_or(DomainError::NotFound)?;
Ok(stored.user_id)
})
})
.await
}
}
fn base64_url(bytes: &[u8]) -> String {
use base64::Engine;
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)
}
fn webauthn_error(error: WanError) -> DomainError {
DomainError::Database(error.to_string())
}
fn db_error(error: sqlx::Error) -> DomainError {
DomainError::Database(error.to_string())
}
-38
View File
@@ -1,38 +0,0 @@
function b64ToBytes(b64) {
const bin = atob(b64.replace(/-/g, "+").replace(/_/g, "/"));
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
return bytes;
}
document.getElementById("passkey-login").addEventListener("click", async () => {
const email = document.getElementById("email").value;
if (!email) {
alert("Enter your email first.");
return;
}
const start = await fetch("/auth/passkey/login/start", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email }),
});
if (!start.ok) {
alert("No passkey found for that email.");
return;
}
const options = await start.json();
const pk = options.publicKey;
pk.challenge = b64ToBytes(pk.challenge);
if (pk.allowCredentials) {
pk.allowCredentials.forEach((c) => (c.id = b64ToBytes(c.id)));
}
const credential = await navigator.credentials.get(options);
const finish = await fetch("/auth/passkey/login/finish", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ response: credential }),
});
if (finish.ok) {
window.location.href = "/lists";
}
});
-32
View File
@@ -1,32 +0,0 @@
function b64ToBytes(b64) {
const bin = atob(b64.replace(/-/g, "+").replace(/_/g, "/"));
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
return bytes;
}
document.getElementById("add-passkey").addEventListener("click", async () => {
const csrf = document.getElementById("add-passkey").dataset.csrf;
const start = await fetch("/auth/passkey/register/start", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ csrf }),
});
const options = await start.json();
const pk = options.publicKey;
pk.challenge = b64ToBytes(pk.challenge);
pk.user.id = b64ToBytes(pk.user.id);
if (pk.excludeCredentials) {
pk.excludeCredentials.forEach((c) => (c.id = b64ToBytes(c.id)));
}
const credential = await navigator.credentials.create(options);
const response = { csrf, response: credential };
const finish = await fetch("/auth/passkey/register/finish", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(response),
});
if (finish.ok) {
window.location.href = "/account";
}
});
+10 -196
View File
@@ -39,20 +39,8 @@ a { color: inherit; }
.brand { display: inline-flex; align-items: center; gap: 10px; text-decoration: none; font-weight: 800; letter-spacing: -.03em; } .brand { display: inline-flex; align-items: center; gap: 10px; text-decoration: none; font-weight: 800; letter-spacing: -.03em; }
.brand-mark { display: grid; place-items: center; width: 32px; height: 32px; border-radius: 11px 11px 11px 3px; background: var(--deep-sage); color: white; transform: rotate(-6deg); } .brand-mark { display: grid; place-items: center; width: 32px; height: 32px; border-radius: 11px 11px 11px 3px; background: var(--deep-sage); color: white; transform: rotate(-6deg); }
.site-nav { display: flex; align-items: center; gap: 6px; }
.site-nav a {
padding: 8px 14px;
border-radius: 11px;
color: var(--muted);
text-decoration: none;
font-size: .9rem;
font-weight: 700;
transition: color .16s ease, background .16s ease;
}
.site-nav a:hover { color: var(--ink); background: #eef2ea; }
.account-nav { display: flex; align-items: center; gap: 16px; color: var(--muted); font-size: .9rem; } .account-nav { display: flex; align-items: center; gap: 16px; color: var(--muted); font-size: .9rem; }
.user-name { color: var(--ink); font-weight: 700; text-decoration: none; } .user-name { color: var(--ink); font-weight: 700; }
.user-name:hover { color: var(--deep-sage); }
.text-button { border: 0; padding: 0; color: var(--deep-sage); background: transparent; cursor: pointer; font-weight: 700; } .text-button { border: 0; padding: 0; color: var(--deep-sage); background: transparent; cursor: pointer; font-weight: 700; }
.site-main { width: min(1120px, calc(100% - 40px)); margin: 30px auto 80px; } .site-main { width: min(1120px, calc(100% - 40px)); margin: 30px auto 80px; }
@@ -75,8 +63,6 @@ h3 { margin-bottom: 6px; font-size: 1rem; }
.stack label { color: var(--muted); font-size: .82rem; font-weight: 700; } .stack label { color: var(--muted); font-size: .82rem; font-weight: 700; }
input { width: 100%; min-height: 46px; padding: 10px 13px; border: 1px solid var(--line); border-radius: 12px; outline: none; color: var(--ink); background: #fff; } input { width: 100%; min-height: 46px; padding: 10px 13px; border: 1px solid var(--line); border-radius: 12px; outline: none; color: var(--ink); background: #fff; }
input:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85, 113, 93, .12); } input:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85, 113, 93, .12); }
textarea { width: 100%; padding: 10px 13px; border: 1px solid var(--line); border-radius: 12px; outline: none; color: var(--ink); background: #fff; font: inherit; resize: vertical; }
textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85, 113, 93, .12); }
.button { display: inline-flex; align-items: center; justify-content: center; min-height: 44px; padding: 10px 17px; border: 0; border-radius: 12px; cursor: pointer; text-decoration: none; font-weight: 800; transition: transform .16s ease, box-shadow .16s ease, background .16s ease; } .button { display: inline-flex; align-items: center; justify-content: center; min-height: 44px; padding: 10px 17px; border: 0; border-radius: 12px; cursor: pointer; text-decoration: none; font-weight: 800; transition: transform .16s ease, box-shadow .16s ease, background .16s ease; }
.button:hover { transform: translateY(-1px); } .button:hover { transform: translateY(-1px); }
.button-primary { color: #fff; background: var(--deep-sage); box-shadow: 0 8px 18px rgba(85, 113, 93, .2); } .button-primary { color: #fff; background: var(--deep-sage); box-shadow: 0 8px 18px rgba(85, 113, 93, .2); }
@@ -97,12 +83,6 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
.auth-card { width: min(100%, 480px); margin: 7vh auto 0; padding: clamp(27px, 6vw, 54px); border: 1px solid var(--line); border-radius: 28px; background: rgba(255, 253, 248, .9); box-shadow: var(--shadow); } .auth-card { width: min(100%, 480px); margin: 7vh auto 0; padding: clamp(27px, 6vw, 54px); border: 1px solid var(--line); border-radius: 28px; background: rgba(255, 253, 248, .9); box-shadow: var(--shadow); }
.auth-card .button { margin-top: 11px; } .auth-card .button { margin-top: 11px; }
.auth-divider { display: flex; align-items: center; gap: 12px; margin: 20px 0 4px; color: var(--muted); font-size: .8rem; }
.auth-divider::before, .auth-divider::after { content: ""; flex: 1; height: 1px; background: var(--line); }
.passkey-list { display: grid; gap: 8px; margin-bottom: 16px; }
.passkey-row { display: flex; align-items: center; gap: 12px; padding: 12px; border: 1px solid var(--line); border-radius: 14px; background: #fff; }
.passkey-row .item-copy { flex: 1; }
.passkey-row small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.auth-switch { margin: 25px 0 0; color: var(--muted); font-size: .9rem; text-align: center; } .auth-switch { margin: 25px 0 0; color: var(--muted); font-size: .9rem; text-align: center; }
.auth-switch a { color: var(--deep-sage); font-weight: 800; } .auth-switch a { color: var(--deep-sage); font-weight: 800; }
.alert { margin-bottom: 18px; padding: 12px 14px; border-radius: 12px; font-size: .9rem; } .alert { margin-bottom: 18px; padding: 12px 14px; border-radius: 12px; font-size: .9rem; }
@@ -114,13 +94,6 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
.list-topbar-actions { display: flex; align-items: center; gap: 12px; } .list-topbar-actions { display: flex; align-items: center; gap: 12px; }
.live-pill { display: inline-flex; align-items: center; gap: 7px; color: var(--deep-sage); font-size: .78rem; font-weight: 800; } .live-pill { display: inline-flex; align-items: center; gap: 7px; color: var(--deep-sage); font-size: .78rem; font-weight: 800; }
.live-dot { width: 8px; height: 8px; border-radius: 50%; background: #75ae6e; box-shadow: 0 0 0 4px rgba(117, 174, 110, .15); } .live-dot { width: 8px; height: 8px; border-radius: 50%; background: #75ae6e; box-shadow: 0 0 0 4px rgba(117, 174, 110, .15); }
.add-meal-button {
color: #fff;
background: var(--deep-sage);
box-shadow: 0 8px 18px rgba(85, 113, 93, .25);
}
.add-meal-button:hover { transform: translateY(-2px); box-shadow: 0 12px 24px rgba(85, 113, 93, .32); }
.add-meal-button:active { transform: translateY(0); }
.list-layout { display: grid; grid-template-columns: minmax(0, 1.5fr) minmax(265px, .72fr); gap: 22px; align-items: start; } .list-layout { display: grid; grid-template-columns: minmax(0, 1.5fr) minmax(265px, .72fr); gap: 22px; align-items: start; }
.list-panel { min-width: 0; } .list-panel { min-width: 0; }
.list-heading { display: flex; justify-content: space-between; margin-bottom: 25px; } .list-heading { display: flex; justify-content: space-between; margin-bottom: 25px; }
@@ -139,71 +112,14 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
.check-form { flex: 0 0 auto; } .check-form { flex: 0 0 auto; }
.check-button { display: grid; place-items: center; width: 28px; height: 28px; padding: 0; border: 2px solid #c8d6c1; border-radius: 9px; color: #fff; background: transparent; cursor: pointer; font-size: .88rem; font-weight: 900; } .check-button { display: grid; place-items: center; width: 28px; height: 28px; padding: 0; border: 2px solid #c8d6c1; border-radius: 9px; color: #fff; background: transparent; cursor: pointer; font-size: .88rem; font-weight: 900; }
.is-checked .check-button { border-color: var(--deep-sage); background: var(--deep-sage); } .is-checked .check-button { border-color: var(--deep-sage); background: var(--deep-sage); }
.item-copy { display: grid; grid-template-columns: auto 1fr; flex: 1; min-width: 0; gap: 2px 7px; align-items: baseline; } .item-copy { display: grid; flex: 1; min-width: 0; gap: 2px; }
.item-copy strong { grid-column: 2; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .item-copy strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.item-qty { grid-column: 1; grid-row: 1; color: var(--muted); font-weight: 700; white-space: nowrap; } .item-copy small { overflow: hidden; color: var(--muted); text-overflow: ellipsis; white-space: nowrap; font-size: .78rem; }
.item-copy small { grid-column: 1 / -1; overflow: hidden; color: var(--muted); text-overflow: ellipsis; white-space: nowrap; font-size: .78rem; }
.is-checked .item-copy strong { color: var(--muted); text-decoration: line-through; } .is-checked .item-copy strong { color: var(--muted); text-decoration: line-through; }
.item-actions-button { .item-actions { position: relative; }
flex: 0 0 auto; .item-actions summary { padding: 7px 5px; color: var(--muted); cursor: pointer; list-style: none; font-size: .78rem; letter-spacing: 2px; }
padding: 7px 8px; .item-actions summary::-webkit-details-marker { display: none; }
border: 0; .item-menu { position: absolute; z-index: 2; right: 0; width: min(265px, 80vw); padding: 14px; border: 1px solid var(--line); border-radius: 15px; background: var(--card); box-shadow: var(--shadow); }
border-radius: 9px;
color: var(--muted);
background: transparent;
cursor: pointer;
font-size: .9rem;
letter-spacing: 2px;
line-height: 1;
}
.item-actions-button:hover { color: var(--ink); background: #f0f3ea; }
/* Rendered markdown (meal descriptions) */
.markdown { line-height: 1.6; color: var(--ink); }
.markdown p { margin: 0 0 12px; }
.markdown ul, .markdown ol { margin: 0 0 12px; padding-left: 22px; }
.markdown li { margin-bottom: 4px; }
.markdown h1, .markdown h2, .markdown h3, .markdown h4 { margin: 18px 0 8px; letter-spacing: -.02em; }
.markdown h1 { font-size: 1.5rem; }
.markdown h2 { font-size: 1.25rem; }
.markdown h3 { font-size: 1.1rem; }
.markdown code { padding: 2px 5px; border-radius: 6px; background: #eef2ea; font-size: .9em; }
.markdown pre { padding: 12px; border-radius: 12px; background: #eef2ea; overflow-x: auto; }
.markdown pre code { padding: 0; background: transparent; }
.markdown blockquote { margin: 0 0 12px; padding-left: 14px; border-left: 3px solid var(--sage); color: var(--muted); }
.markdown a { color: var(--deep-sage); text-decoration: underline; }
/* Meal ingredient list */
.ingredient-list { display: grid; gap: 6px; margin: 0; padding: 0; list-style: none; }
.ingredient-list li {
display: flex;
align-items: center;
gap: 12px;
min-height: 52px;
padding: 8px 6px 8px 4px;
border-bottom: 1px solid #edf0e6;
}
.ingredient-list li:last-child { border-bottom: 0; }
/* Item / ingredient edit modal */
.item-modal {
width: min(100%, 420px);
padding: 0;
border: 1px solid rgba(221, 225, 210, .9);
border-radius: 24px;
background: rgba(255, 253, 248, .98);
box-shadow: var(--shadow);
}
.item-modal::backdrop {
background: rgba(37, 53, 46, .28);
}
.item-modal-card { padding: 22px 24px 24px; }
.item-modal-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 18px;
}
.item-modal-header h3 { margin: 0; font-size: 1.15rem; letter-spacing: -.02em; }
.item-modal .stack { margin-bottom: 14px; }
.edit-form { margin-bottom: 12px; } .edit-form { margin-bottom: 12px; }
.edit-form input { min-height: 38px; padding: 7px 10px; font-size: .85rem; } .edit-form input { min-height: 38px; padding: 7px 10px; font-size: .85rem; }
.danger-link { padding: 0; border: 0; color: var(--coral); background: none; cursor: pointer; font-size: .8rem; font-weight: 800; } .danger-link { padding: 0; border: 0; color: var(--coral); background: none; cursor: pointer; font-size: .8rem; font-weight: 800; }
@@ -237,109 +153,9 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; } .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
/* Meal picker modal */
.meal-picker-backdrop {
position: fixed;
inset: 0;
z-index: 50;
display: grid;
place-items: center;
padding: 20px;
background: rgba(37, 53, 46, .28);
animation: meal-picker-fade .15s ease;
}
@keyframes meal-picker-fade { from { opacity: 0; } to { opacity: 1; } }
.meal-picker-modal {
width: min(100%, 460px);
max-height: min(78vh, 620px);
display: flex;
flex-direction: column;
overflow: hidden;
border: 1px solid rgba(221, 225, 210, .9);
border-radius: 24px;
background: rgba(255, 253, 248, .98);
box-shadow: var(--shadow);
animation: meal-picker-pop .18s ease;
}
@keyframes meal-picker-pop { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
.meal-picker-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
padding: 22px 24px 16px;
border-bottom: 1px solid #edf0e6;
}
.meal-picker-header .eyebrow { margin-bottom: 5px; }
.meal-picker-header h2 { margin-bottom: 0; font-size: 1.25rem; letter-spacing: -.02em; }
.meal-picker-close {
display: grid;
place-items: center;
flex: 0 0 auto;
width: 34px;
height: 34px;
padding: 0;
border: 1px solid var(--line);
border-radius: 11px;
color: var(--muted);
background: #fff;
cursor: pointer;
font-size: .9rem;
transition: color .16s ease, border-color .16s ease;
}
.meal-picker-close:hover { color: var(--ink); border-color: var(--sage); }
.meal-picker-list {
display: grid;
gap: 8px;
padding: 16px 24px 22px;
overflow-y: auto;
}
.meal-picker-row { margin: 0; }
.meal-picker-button {
display: flex;
align-items: center;
gap: 13px;
width: 100%;
padding: 12px 13px;
border: 1px solid var(--line);
border-radius: 16px;
color: var(--ink);
background: #fff;
cursor: pointer;
text-align: left;
transition: border-color .16s ease, transform .16s ease;
}
.meal-picker-button:hover { border-color: var(--sage); transform: translateX(2px); }
.meal-picker-icon {
display: grid;
place-items: center;
flex: 0 0 auto;
width: 38px;
height: 38px;
border-radius: 13px;
color: var(--deep-sage);
background: #eef4e9;
font-size: 1.1rem;
}
.meal-picker-copy { display: grid; flex: 1; min-width: 0; gap: 2px; }
.meal-picker-copy strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: .95rem; }
.meal-picker-copy small { color: var(--muted); font-size: .76rem; }
.meal-picker-add {
flex: 0 0 auto;
padding: 6px 12px;
border-radius: 99px;
color: var(--deep-sage);
background: #e7f0e1;
font-size: .74rem;
font-weight: 800;
}
.meal-picker-empty { padding: 34px 22px 30px; text-align: center; color: var(--muted); }
.meal-picker-empty h3 { color: var(--ink); }
.meal-picker-empty p { margin-bottom: 18px; }
@media (max-width: 780px) { @media (max-width: 780px) {
.site-header, .site-main, .site-footer { width: min(100% - 28px, 600px); } .site-header, .site-main, .site-footer { width: min(100% - 28px, 600px); }
.site-header { padding: 18px 0; } .site-header { padding: 20px 0; }
.site-main { margin-top: 20px; } .site-main { margin-top: 20px; }
.dashboard-grid, .list-layout { grid-template-columns: 1fr; } .dashboard-grid, .list-layout { grid-template-columns: 1fr; }
.side-column { grid-template-columns: repeat(2, minmax(0, 1fr)); } .side-column { grid-template-columns: repeat(2, minmax(0, 1fr)); }
@@ -347,14 +163,12 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
} }
@media (max-width: 500px) { @media (max-width: 500px) {
.site-header { flex-wrap: wrap; gap: 12px 16px; }
.site-nav { order: 3; width: 100%; justify-content: center; gap: 8px; }
.site-nav a { flex: 1; text-align: center; padding: 10px 8px; }
.account-nav { gap: 9px; } .account-nav { gap: 9px; }
.user-name { max-width: 90px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .user-name { max-width: 90px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.panel { padding: 20px 16px; border-radius: 20px; } .panel { padding: 20px 16px; border-radius: 20px; }
.page-heading { margin-bottom: 24px; } .page-heading { margin-bottom: 24px; }
.list-topbar { margin-bottom: 20px; } .list-topbar { margin-bottom: 20px; }
.list-topbar-actions .button { display: none; }
.list-heading h1 { font-size: clamp(1.45rem, 7vw, 1.75rem); } .list-heading h1 { font-size: clamp(1.45rem, 7vw, 1.75rem); }
.add-item-form { grid-template-columns: minmax(0, 1fr) 75px; } .add-item-form { grid-template-columns: minmax(0, 1fr) 75px; }
.add-button { grid-column: 1 / -1; } .add-button { grid-column: 1 / -1; }