28 Commits
Author SHA1 Message Date
sbstp 3160a898be version 0.2.0 [skip ci]
ci/woodpecker/tag/release Pipeline was successful
2026-08-03 00:24:54 -04:00
sbstp 209363774c passwordless login + proper migrations
ci/woodpecker/push/e2e Pipeline was successful
ci/woodpecker/push/fmt Pipeline was successful
ci/woodpecker/push/test Pipeline was successful
2026-08-03 00:23:10 -04:00
sbstp 1291c5a33a embed assets and version 0.1.2
ci/woodpecker/push/e2e Pipeline was successful
ci/woodpecker/push/fmt Pipeline was successful
ci/woodpecker/push/test Pipeline was successful
ci/woodpecker/tag/release Pipeline was successful
2026-08-02 21:28:54 -04:00
sbstp d6c31375ae version 0.1.1 [skip ci]
ci/woodpecker/tag/release Pipeline was successful
2026-08-02 20:42:12 -04:00
sbstp a014ffc602 fix release ci [skip ci] 2026-08-02 20:41:38 -04:00
sbstp c80cc02798 add woodpecker release job [skip ci]
ci/woodpecker/tag/release Pipeline was canceled
2026-08-02 20:36:16 -04:00
sbstp fdd3e8c5da add passkey support
ci/woodpecker/push/e2e Pipeline failed
ci/woodpecker/push/fmt Pipeline was successful
ci/woodpecker/push/test Pipeline was successful
2026-08-02 16:46:52 -04:00
sbstp 04c9724c76 reduce e2e test flakiness
ci/woodpecker/push/e2e Pipeline was successful
ci/woodpecker/push/fmt Pipeline was successful
ci/woodpecker/push/test Pipeline was successful
2026-08-02 00:18:22 -04:00
sbstp a2134b93f1 cargo fmt
ci/woodpecker/push/e2e Pipeline was successful
ci/woodpecker/push/fmt Pipeline was successful
ci/woodpecker/push/test Pipeline was successful
2026-08-01 23:52:40 -04:00
sbstp 51dcff1202 fix logging issues
ci/woodpecker/push/e2e Pipeline was successful
ci/woodpecker/push/fmt Pipeline failed
ci/woodpecker/push/test Pipeline was successful
2026-08-01 23:42:26 -04:00
sbstp a7544f837e make list text clickable to toggle 2026-08-01 23:24:13 -04:00
sbstp 279cdb869d cargo fmt
ci/woodpecker/push/e2e Pipeline was successful
ci/woodpecker/push/fmt Pipeline was successful
ci/woodpecker/push/test Pipeline was successful
2026-08-01 23:05:37 -04:00
sbstp fbb49bc560 fix flaky e2e test 2026-08-01 23:05:20 -04:00
sbstp 7309971c74 websocket sync e2e test 2026-08-01 23:01:42 -04:00
sbstp 4adcfb1377 add meal e2e test
ci/woodpecker/push/e2e Pipeline failed
ci/woodpecker/push/fmt Pipeline failed
ci/woodpecker/push/test Pipeline was successful
2026-08-01 22:47:41 -04:00
sbstp 77a9d49eb4 add e2e tests for lists and meals 2026-08-01 22:40:43 -04:00
sbstp 2e0d76a9c2 fix fmt 2026-08-01 22:14:33 -04:00
sbstp b8a75ee2b1 fix e2e tests
ci/woodpecker/push/e2e Pipeline was successful
ci/woodpecker/push/fmt Pipeline failed
ci/woodpecker/push/test Pipeline was successful
2026-08-01 22:05:22 -04:00
sbstp 0324a97748 add woodpecker pipelines
ci/woodpecker/push/fmt Pipeline is pending
ci/woodpecker/push/test Pipeline is pending
ci/woodpecker/push/e2e Pipeline was canceled
2026-08-01 21:50:19 -04:00
sbstp 61ea97265c add playwright tests 2026-08-01 21:24:48 -04:00
sbstp 250a18cfbb remove dead code 2026-08-01 20:35:14 -04:00
sbstpandsbstp 9b32fd23a7 Add support for meals (#1)
Reviewed-on: #1
Co-authored-by: Simon Bernier St-Pierre <git.sbstp.ca@gmail.com>
2026-08-01 20:27:38 -04:00
sbstp 6a2cef2003 cleanup errors 2026-08-01 18:32:14 -04:00
sbstp 188ce23e67 hexagonal refactor 2026-08-01 18:27:22 -04:00
sbstp 6979cabe8b clean shutdown 2026-08-01 16:29:31 -04:00
sbstp 5e57c61e4b add seed ability 2026-08-01 16:15:55 -04:00
sbstp 2db105bd6f use autoincrement for IDs 2026-08-01 15:56:21 -04:00
sbstp 5da5fee942 simplify list ownership & invitations 2026-08-01 15:46:38 -04:00
36 changed files with 7792 additions and 2127 deletions
+5
View File
@@ -2,3 +2,8 @@
/sustenance.db /sustenance.db
/sustenance.db* /sustenance.db*
/.env /.env
/seed.json
/e2e/node_modules/
/e2e/test-results/
/e2e/playwright-report/
/test-results/
+17
View File
@@ -0,0 +1,17 @@
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
@@ -0,0 +1,9 @@
when:
event: [push, pull_request]
steps:
fmt:
image: rust:1
commands:
- rustup component add rustfmt
- cargo fmt --all -- --check
+17
View File
@@ -0,0 +1,17 @@
when:
- event: tag
steps:
build:
image: rust:1
commands:
- cargo build --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
@@ -0,0 +1,8 @@
when:
event: [push, pull_request]
steps:
test:
image: rust:1
commands:
- cargo test --all
Generated
+1289 -109
View File
File diff suppressed because it is too large Load Diff
+16 -4
View File
@@ -1,21 +1,33 @@
[package] [package]
name = "sustenance" name = "sustenance"
version = "0.1.0" version = "0.2.0"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
argon2 = "0.5" argon2 = "0.5"
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"
rusqlite = { version = "0.32", features = ["bundled"] }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10" sha2 = "0.10"
sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "sqlite", "macros", "migrate", "tls-rustls"] }
thiserror = "2" thiserror = "2"
tokio = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full"] }
tower-http = { version = "0.6", features = ["fs", "trace"] } tower = "0.5"
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"] }
uuid = { version = "1", features = ["v4"] } url = "2"
webauthn-rs = "0.3"
[profile.release]
opt-level = "z"
strip = true
lto = true
codegen-units = 1
+50 -3
View File
@@ -8,7 +8,13 @@ A small shared grocery list built with Rust, Axum, Maud, htmx, WebSockets, and S
cargo run cargo run
``` ```
Open <http://127.0.0.1:3000>. The application creates `sustenance.db` in the working directory on first start. Open <http://localhost:3000>. The application creates `sustenance.db` in the
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
@@ -19,17 +25,38 @@ Open <http://127.0.0.1:3000>. The application creates `sustenance.db` in the wor
| `PUBLIC_BASE_URL` | derived from `BIND_ADDRESS` | Base URL used in invitation links | | `PUBLIC_BASE_URL` | derived from `BIND_ADDRESS` | Base URL used in invitation links |
| `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 |
| `RUST_LOG` | `sustenance=debug,tower_http=info` | Log filter | | `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) |
| `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
If a JSON config file exists at the path given by `SEED_CONFIG` (default `seed.json`),
Sustenance creates the configured user on startup when the database has no users yet.
The file is optional — if it is missing or invalid, seeding is silently skipped.
```json
{
"user": {
"email": "you@example.com",
"display_name": "You",
"password": "a-strong-password"
}
}
```
## 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
- List-scoped categories with common defaults and custom category creation - Global categories with common defaults seeded at startup 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
@@ -44,3 +71,23 @@ 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
@@ -0,0 +1,91 @@
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
@@ -0,0 +1,126 @@
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
@@ -0,0 +1,60 @@
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
@@ -0,0 +1,90 @@
{
"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
@@ -0,0 +1,13 @@
{
"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
@@ -0,0 +1,10 @@
import { defineConfig } from "@playwright/test";
export default defineConfig({
testDir: "./tests",
timeout: 30_000,
retries: 2,
use: {
trace: "on-first-retry",
},
});
+54
View File
@@ -0,0 +1,54 @@
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
@@ -0,0 +1,15 @@
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
@@ -0,0 +1,91 @@
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
@@ -0,0 +1,88 @@
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();
});
+46
View File
@@ -0,0 +1,46 @@
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 without entering an email (userless sign-in).
await p.click("#passkey-login");
await expect(p).toHaveURL(/\/lists/);
await context.close();
});
+31
View File
@@ -0,0 +1,31 @@
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();
});
+81
View File
@@ -0,0 +1,81 @@
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
display_name TEXT NOT NULL,
password_hash TEXT NOT NULL,
user_handle BLOB NOT NULL UNIQUE,
created_at INTEGER NOT NULL
);
CREATE TABLE sessions (
token_hash BLOB PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
csrf_token BLOB NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE passkeys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
credential_id TEXT NOT NULL UNIQUE,
credential TEXT NOT NULL,
counter INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE lists (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
revision INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
position INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE invitations (
token_hash BLOB PRIMARY KEY,
created_by INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at INTEGER NOT NULL
);
CREATE TABLE items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
list_id INTEGER NOT NULL REFERENCES lists(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,
checked INTEGER NOT NULL DEFAULT 0,
version INTEGER NOT NULL DEFAULT 1,
position INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE meals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE 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,
position INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX items_list_idx ON items(list_id);
CREATE INDEX meal_ingredients_meal_idx ON meal_ingredients(meal_id);
CREATE INDEX sessions_user_idx ON sessions(user_id);
CREATE INDEX passkeys_user_idx ON passkeys(user_id);
-967
View File
@@ -1,967 +0,0 @@
use std::{
path::Path,
sync::{Arc, Mutex},
time::{SystemTime, UNIX_EPOCH},
};
use rand::{RngCore, rngs::OsRng};
use rusqlite::{Connection, OptionalExtension, params};
use sha2::{Digest, Sha256};
use thiserror::Error;
use uuid::Uuid;
#[derive(Debug, Error)]
pub enum DbError {
#[error("database error: {0}")]
Message(String),
#[error("record not found")]
NotFound,
#[error("record already exists")]
Conflict,
#[error("database worker failed: {0}")]
Worker(String),
}
pub type DbResult<T> = Result<T, DbError>;
#[derive(Clone)]
pub struct Database {
connection: Arc<Mutex<Connection>>,
}
#[derive(Clone, Debug)]
pub struct User {
pub id: String,
pub email: String,
pub display_name: String,
}
#[derive(Clone, Debug)]
pub struct SessionUser {
pub user: User,
pub csrf_token: String,
}
#[derive(Clone, Debug)]
pub struct GroceryList {
pub id: String,
pub name: String,
pub owner_id: String,
pub revision: i64,
}
#[derive(Clone, Debug)]
pub struct ListAccess {
pub list: GroceryList,
pub role: String,
}
#[derive(Clone, Debug)]
pub struct ListSummary {
pub list: GroceryList,
pub role: String,
}
#[derive(Clone, Debug)]
pub struct Item {
pub id: String,
pub list_id: String,
pub name: String,
pub quantity: String,
pub note: String,
pub category_id: Option<String>,
pub checked: bool,
pub version: i64,
}
#[derive(Clone, Debug)]
pub struct Category {
pub id: String,
pub name: String,
}
#[derive(Clone, Debug)]
pub struct InvitationInfo {
pub list_name: String,
}
impl Database {
pub fn open(path: impl AsRef<Path>) -> DbResult<Self> {
let connection = Connection::open(path).map_err(sql_error)?;
configure(&connection)?;
migrate(&connection)?;
Ok(Self {
connection: Arc::new(Mutex::new(connection)),
})
}
#[cfg(test)]
pub fn open_in_memory() -> DbResult<Self> {
Self::open(":memory:")
}
async fn call<T, F>(&self, operation: F) -> DbResult<T>
where
T: Send + 'static,
F: FnOnce(&mut Connection) -> DbResult<T> + Send + 'static,
{
let connection = Arc::clone(&self.connection);
tokio::task::spawn_blocking(move || {
let mut connection = connection
.lock()
.map_err(|error| DbError::Worker(error.to_string()))?;
operation(&mut connection)
})
.await
.map_err(|error| DbError::Worker(error.to_string()))?
}
pub async fn create_user(
&self,
email: String,
display_name: String,
password_hash: String,
) -> DbResult<User> {
self.call(move |connection| {
let user = User {
id: Uuid::new_v4().to_string(),
email,
display_name,
};
let result = connection.execute(
"INSERT INTO users (id, email, display_name, password_hash, created_at)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![user.id, user.email, user.display_name, password_hash, now()],
);
match result {
Ok(_) => Ok(user),
Err(error) if error.to_string().contains("UNIQUE") => Err(DbError::Conflict),
Err(error) => Err(sql_error(error)),
}
})
.await
}
pub async fn find_user_by_email(&self, email: String) -> DbResult<Option<(User, String)>> {
self.call(move |connection| {
connection
.query_row(
"SELECT id, email, display_name, password_hash
FROM users WHERE email = ?1 COLLATE NOCASE",
params![email],
|row| {
Ok((
User {
id: row.get(0)?,
email: row.get(1)?,
display_name: row.get(2)?,
},
row.get(3)?,
))
},
)
.optional()
.map_err(sql_error)
})
.await
}
pub async fn has_users(&self) -> DbResult<bool> {
self.call(|connection| {
connection
.query_row("SELECT EXISTS(SELECT 1 FROM users)", [], |row| {
Ok(row.get::<_, i64>(0)? != 0)
})
.map_err(sql_error)
})
.await
}
pub async fn create_session(&self, user_id: String) -> DbResult<(String, String)> {
self.call(move |connection| {
let session_token = new_secret();
let csrf_token = new_secret();
connection
.execute(
"INSERT INTO sessions (token_hash, user_id, csrf_token, expires_at)
VALUES (?1, ?2, ?3, ?4)",
params![
hash_secret(&session_token),
user_id,
csrf_token,
now() + 60 * 60 * 24 * 30
],
)
.map_err(sql_error)?;
Ok((session_token, csrf_token))
})
.await
}
pub async fn session_user(&self, session_token: String) -> DbResult<Option<SessionUser>> {
self.call(move |connection| {
connection
.query_row(
"SELECT u.id, u.email, u.display_name, s.csrf_token
FROM sessions s
JOIN users u ON u.id = s.user_id
WHERE s.token_hash = ?1 AND s.expires_at > ?2",
params![hash_secret(&session_token), now()],
|row| {
Ok(SessionUser {
user: User {
id: row.get(0)?,
email: row.get(1)?,
display_name: row.get(2)?,
},
csrf_token: row.get(3)?,
})
},
)
.optional()
.map_err(sql_error)
})
.await
}
pub async fn delete_session(&self, session_token: String) -> DbResult<()> {
self.call(move |connection| {
connection
.execute(
"DELETE FROM sessions WHERE token_hash = ?1",
params![hash_secret(&session_token)],
)
.map_err(sql_error)?;
Ok(())
})
.await
}
pub async fn list_summaries(&self, user_id: String) -> DbResult<Vec<ListSummary>> {
self.call(move |connection| {
let mut statement = connection
.prepare(
"SELECT l.id, l.name, l.owner_id, l.revision, m.role
FROM lists l
JOIN list_members m ON m.list_id = l.id
WHERE m.user_id = ?1
ORDER BY l.created_at DESC",
)
.map_err(sql_error)?;
let rows = statement
.query_map(params![user_id], |row| {
Ok(ListSummary {
list: GroceryList {
id: row.get(0)?,
name: row.get(1)?,
owner_id: row.get(2)?,
revision: row.get(3)?,
},
role: row.get(4)?,
})
})
.map_err(sql_error)?;
rows.collect::<Result<Vec<_>, _>>().map_err(sql_error)
})
.await
}
pub async fn create_list(&self, owner_id: String, name: String) -> DbResult<GroceryList> {
self.call(move |connection| {
let list = GroceryList {
id: Uuid::new_v4().to_string(),
name,
owner_id: owner_id.clone(),
revision: 0,
};
let transaction = connection.transaction().map_err(sql_error)?;
transaction
.execute(
"INSERT INTO lists (id, name, owner_id, revision, created_at)
VALUES (?1, ?2, ?3, 0, ?4)",
params![list.id, list.name, owner_id, now()],
)
.map_err(sql_error)?;
transaction
.execute(
"INSERT INTO list_members (list_id, user_id, role)
VALUES (?1, ?2, 'owner')",
params![list.id, list.owner_id],
)
.map_err(sql_error)?;
for (position, category_name) in DEFAULT_CATEGORIES.iter().enumerate() {
transaction
.execute(
"INSERT INTO categories (id, list_id, name, position, created_at)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![
Uuid::new_v4().to_string(),
list.id,
category_name,
position as i64,
now()
],
)
.map_err(sql_error)?;
}
transaction.commit().map_err(sql_error)?;
Ok(list)
})
.await
}
pub async fn list_access(
&self,
list_id: String,
user_id: String,
) -> DbResult<Option<ListAccess>> {
self.call(move |connection| {
connection
.query_row(
"SELECT l.id, l.name, l.owner_id, l.revision, m.role
FROM lists l
JOIN list_members m ON m.list_id = l.id
WHERE l.id = ?1 AND m.user_id = ?2",
params![list_id, user_id],
|row| {
Ok(ListAccess {
list: GroceryList {
id: row.get(0)?,
name: row.get(1)?,
owner_id: row.get(2)?,
revision: row.get(3)?,
},
role: row.get(4)?,
})
},
)
.optional()
.map_err(sql_error)
})
.await
}
pub async fn items(&self, list_id: String) -> DbResult<Vec<Item>> {
self.call(move |connection| {
let mut statement = connection
.prepare(
"SELECT id, list_id, name, quantity, note, category_id, checked, version
FROM items
WHERE list_id = ?1
ORDER BY position ASC, created_at ASC",
)
.map_err(sql_error)?;
let rows = statement
.query_map(params![list_id], |row| {
Ok(Item {
id: row.get(0)?,
list_id: row.get(1)?,
name: row.get(2)?,
quantity: row.get(3)?,
note: row.get(4)?,
category_id: row.get(5)?,
checked: row.get::<_, i64>(6)? != 0,
version: row.get(7)?,
})
})
.map_err(sql_error)?;
rows.collect::<Result<Vec<_>, _>>().map_err(sql_error)
})
.await
}
pub async fn categories(&self, list_id: String) -> DbResult<Vec<Category>> {
self.call(move |connection| {
let mut statement = connection
.prepare(
"SELECT id, name
FROM categories
WHERE list_id = ?1
ORDER BY position ASC, name COLLATE NOCASE ASC",
)
.map_err(sql_error)?;
let rows = statement
.query_map(params![list_id], |row| {
Ok(Category {
id: row.get(0)?,
name: row.get(1)?,
})
})
.map_err(sql_error)?;
rows.collect::<Result<Vec<_>, _>>().map_err(sql_error)
})
.await
}
pub async fn create_category(&self, list_id: String, name: String) -> DbResult<i64> {
self.call(move |connection| {
let transaction = connection.transaction().map_err(sql_error)?;
let position: i64 = transaction
.query_row(
"SELECT COALESCE(MAX(position), -1) + 1
FROM categories WHERE list_id = ?1",
params![list_id],
|row| row.get(0),
)
.map_err(sql_error)?;
let result = transaction.execute(
"INSERT INTO categories (id, list_id, name, position, created_at)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![Uuid::new_v4().to_string(), list_id, name, position, now()],
);
match result {
Ok(_) => {}
Err(error) if error.to_string().contains("UNIQUE") => {
return Err(DbError::Conflict);
}
Err(error) => return Err(sql_error(error)),
}
let revision = bump_revision(&transaction, &list_id)?;
transaction.commit().map_err(sql_error)?;
Ok(revision)
})
.await
}
pub async fn add_item(
&self,
list_id: String,
name: String,
quantity: String,
note: String,
category_id: Option<String>,
) -> DbResult<i64> {
self.call(move |connection| {
let transaction = connection.transaction().map_err(sql_error)?;
let category_id = category_id.filter(|category_id| !category_id.is_empty());
ensure_category(&transaction, &list_id, category_id.as_deref())?;
let position: i64 = transaction
.query_row(
"SELECT COALESCE(MAX(position), -1) + 1 FROM items WHERE list_id = ?1",
params![list_id],
|row| row.get(0),
)
.map_err(sql_error)?;
transaction
.execute(
"INSERT INTO items
(id, list_id, name, quantity, note, category_id, checked, version, position, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0, 1, ?7, ?8, ?8)",
params![
Uuid::new_v4().to_string(),
list_id,
name,
quantity,
note,
category_id,
position,
now()
],
)
.map_err(sql_error)?;
let revision = bump_revision(&transaction, &list_id)?;
transaction.commit().map_err(sql_error)?;
Ok(revision)
})
.await
}
pub async fn set_item_checked(
&self,
list_id: String,
item_id: String,
checked: bool,
) -> DbResult<i64> {
self.call(move |connection| {
let transaction = connection.transaction().map_err(sql_error)?;
let changed = transaction
.execute(
"UPDATE items
SET checked = ?1, version = version + 1, updated_at = ?2
WHERE id = ?3 AND list_id = ?4",
params![checked as i64, now(), item_id, list_id],
)
.map_err(sql_error)?;
if changed == 0 {
return Err(DbError::NotFound);
}
let revision = bump_revision(&transaction, &list_id)?;
transaction.commit().map_err(sql_error)?;
Ok(revision)
})
.await
}
pub async fn update_item(
&self,
list_id: String,
item_id: String,
name: String,
quantity: String,
note: String,
category_id: Option<String>,
) -> DbResult<i64> {
self.call(move |connection| {
let transaction = connection.transaction().map_err(sql_error)?;
let category_id = category_id.filter(|category_id| !category_id.is_empty());
ensure_category(&transaction, &list_id, category_id.as_deref())?;
let changed = transaction
.execute(
"UPDATE items
SET name = ?1, quantity = ?2, note = ?3, category_id = ?4,
version = version + 1, updated_at = ?5
WHERE id = ?6 AND list_id = ?7",
params![name, quantity, note, category_id, now(), item_id, list_id],
)
.map_err(sql_error)?;
if changed == 0 {
return Err(DbError::NotFound);
}
let revision = bump_revision(&transaction, &list_id)?;
transaction.commit().map_err(sql_error)?;
Ok(revision)
})
.await
}
pub async fn delete_item(&self, list_id: String, item_id: String) -> DbResult<i64> {
self.call(move |connection| {
let transaction = connection.transaction().map_err(sql_error)?;
let changed = transaction
.execute(
"DELETE FROM items WHERE id = ?1 AND list_id = ?2",
params![item_id, list_id],
)
.map_err(sql_error)?;
if changed == 0 {
return Err(DbError::NotFound);
}
let revision = bump_revision(&transaction, &list_id)?;
transaction.commit().map_err(sql_error)?;
Ok(revision)
})
.await
}
pub async fn create_invitation(
&self,
list_id: String,
created_by: String,
token: String,
) -> DbResult<i64> {
self.call(move |connection| {
let expires_at = now() + 60 * 60 * 24 * 7;
connection
.execute(
"INSERT INTO invitations (token_hash, list_id, created_by, expires_at)
VALUES (?1, ?2, ?3, ?4)",
params![hash_secret(&token), list_id, created_by, expires_at],
)
.map_err(sql_error)?;
Ok(expires_at)
})
.await
}
pub async fn invitation(&self, token: String) -> DbResult<Option<InvitationInfo>> {
self.call(move |connection| {
connection
.query_row(
"SELECT l.name
FROM invitations i
JOIN lists l ON l.id = i.list_id
WHERE i.token_hash = ?1 AND i.expires_at > ?2",
params![hash_secret(&token), now()],
|row| {
Ok(InvitationInfo {
list_name: row.get(0)?,
})
},
)
.optional()
.map_err(sql_error)
})
.await
}
pub async fn accept_invitation(&self, token: String, user_id: String) -> DbResult<String> {
self.call(move |connection| {
let transaction = connection.transaction().map_err(sql_error)?;
let invitation = transaction
.query_row(
"SELECT list_id FROM invitations
WHERE token_hash = ?1 AND expires_at > ?2",
params![hash_secret(&token), now()],
|row| row.get::<_, String>(0),
)
.optional()
.map_err(sql_error)?
.ok_or(DbError::NotFound)?;
transaction
.execute(
"INSERT OR IGNORE INTO list_members (list_id, user_id, role)
VALUES (?1, ?2, 'member')",
params![invitation, user_id],
)
.map_err(sql_error)?;
transaction
.execute(
"DELETE FROM invitations WHERE token_hash = ?1",
params![hash_secret(&token)],
)
.map_err(sql_error)?;
transaction.commit().map_err(sql_error)?;
Ok(invitation)
})
.await
}
}
fn configure(connection: &Connection) -> DbResult<()> {
connection
.pragma_update(None, "foreign_keys", true)
.map_err(sql_error)?;
connection
.pragma_update(None, "journal_mode", "WAL")
.map_err(sql_error)?;
connection
.busy_timeout(std::time::Duration::from_secs(5))
.map_err(sql_error)?;
Ok(())
}
fn migrate(connection: &Connection) -> DbResult<()> {
connection
.execute_batch(
"CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
display_name TEXT NOT NULL,
password_hash TEXT NOT NULL,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
token_hash TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
csrf_token TEXT NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS lists (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
owner_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
revision INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS list_members (
list_id TEXT NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
role TEXT NOT NULL CHECK (role IN ('owner', 'member')),
PRIMARY KEY (list_id, user_id)
);
CREATE TABLE IF NOT EXISTS categories (
id TEXT PRIMARY KEY,
list_id TEXT NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
name TEXT NOT NULL COLLATE NOCASE,
position INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
UNIQUE (list_id, name)
);
CREATE TABLE IF NOT EXISTS invitations (
token_hash TEXT PRIMARY KEY,
list_id TEXT NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
created_by TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS items (
id TEXT PRIMARY KEY,
list_id TEXT NOT NULL REFERENCES lists(id) ON DELETE CASCADE,
name TEXT NOT NULL,
quantity TEXT NOT NULL DEFAULT '',
note TEXT NOT NULL DEFAULT '',
category_id TEXT REFERENCES categories(id) ON DELETE SET NULL,
checked INTEGER NOT NULL DEFAULT 0,
version INTEGER NOT NULL DEFAULT 1,
position INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS items_list_idx ON items(list_id);
CREATE INDEX IF NOT EXISTS categories_list_idx ON categories(list_id);
CREATE INDEX IF NOT EXISTS sessions_user_idx ON sessions(user_id);
CREATE INDEX IF NOT EXISTS list_members_user_idx ON list_members(user_id);",
)
.map_err(sql_error)?;
if !has_column(connection, "items", "category_id")? {
connection
.execute(
"ALTER TABLE items ADD COLUMN category_id TEXT REFERENCES categories(id) ON DELETE SET NULL",
[],
)
.map_err(sql_error)?;
}
Ok(())
}
fn has_column(connection: &Connection, table: &str, wanted: &str) -> DbResult<bool> {
let mut statement = connection
.prepare(&format!("PRAGMA table_info({table})"))
.map_err(sql_error)?;
let mut rows = statement.query([]).map_err(sql_error)?;
while let Some(row) = rows.next().map_err(sql_error)? {
if row.get::<_, String>(1).map_err(sql_error)? == wanted {
return Ok(true);
}
}
Ok(false)
}
fn ensure_category(
transaction: &rusqlite::Transaction<'_>,
list_id: &str,
category_id: Option<&str>,
) -> DbResult<()> {
let Some(category_id) = category_id else {
return Ok(());
};
let exists = transaction
.query_row(
"SELECT 1 FROM categories WHERE id = ?1 AND list_id = ?2",
params![category_id, list_id],
|_| Ok(()),
)
.optional()
.map_err(sql_error)?;
if exists.is_none() {
return Err(DbError::NotFound);
}
Ok(())
}
const DEFAULT_CATEGORIES: &[&str] = &[
"Produce",
"Meat & seafood",
"Dairy & eggs",
"Pantry",
"Frozen",
"Household",
];
fn bump_revision(transaction: &rusqlite::Transaction<'_>, list_id: &str) -> DbResult<i64> {
transaction
.execute(
"UPDATE lists SET revision = revision + 1 WHERE id = ?1",
params![list_id],
)
.map_err(sql_error)?;
transaction
.query_row(
"SELECT revision FROM lists WHERE id = ?1",
params![list_id],
|row| row.get(0),
)
.map_err(sql_error)
}
fn sql_error(error: impl std::fmt::Display) -> DbError {
DbError::Message(error.to_string())
}
fn now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64
}
pub fn new_secret() -> String {
let mut bytes = [0_u8; 32];
OsRng.fill_bytes(&mut bytes);
hex::encode(bytes)
}
pub fn hash_secret(secret: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(secret.as_bytes());
hex::encode(hasher.finalize())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn creates_a_list_and_item() {
let database = Database::open_in_memory().unwrap();
let user = database
.create_user("test@example.com".into(), "Test User".into(), "hash".into())
.await
.unwrap();
let list = database
.create_list(user.id.clone(), "Weekly shop".into())
.await
.unwrap();
database
.add_item(
list.id.clone(),
"Milk".into(),
"2 litres".into(),
String::new(),
None,
)
.await
.unwrap();
let items = database.items(list.id).await.unwrap();
assert_eq!(items.len(), 1);
assert_eq!(items[0].name, "Milk");
}
#[tokio::test]
async fn sessions_and_invitations_are_scoped_to_users() {
let database = Database::open_in_memory().unwrap();
let owner = database
.create_user("owner@example.com".into(), "Owner".into(), "hash".into())
.await
.unwrap();
let member = database
.create_user("member@example.com".into(), "Member".into(), "hash".into())
.await
.unwrap();
let list = database
.create_list(owner.id.clone(), "Household".into())
.await
.unwrap();
assert_eq!(database.categories(list.id.clone()).await.unwrap().len(), 6);
let (session_token, csrf_token) = database.create_session(owner.id.clone()).await.unwrap();
let session = database
.session_user(session_token.clone())
.await
.unwrap()
.unwrap();
assert_eq!(session.user.id, owner.id);
assert_eq!(session.csrf_token, csrf_token);
let invitation_token = "test-invitation".to_owned();
database
.create_invitation(list.id.clone(), owner.id, invitation_token.clone())
.await
.unwrap();
assert_eq!(
database
.invitation(invitation_token.clone())
.await
.unwrap()
.unwrap()
.list_name,
"Household"
);
let accepted_list = database
.accept_invitation(invitation_token.clone(), member.id.clone())
.await
.unwrap();
assert_eq!(accepted_list, list.id);
assert!(
database
.invitation(invitation_token)
.await
.unwrap()
.is_none()
);
assert_eq!(
database
.list_access(list.id, member.id)
.await
.unwrap()
.unwrap()
.role,
"member"
);
}
#[tokio::test]
async fn checked_state_is_set_not_toggled() {
let database = Database::open_in_memory().unwrap();
let user = database
.create_user("check@example.com".into(), "Checker".into(), "hash".into())
.await
.unwrap();
let list = database.create_list(user.id, "List".into()).await.unwrap();
database
.add_item(
list.id.clone(),
"Coffee".into(),
String::new(),
String::new(),
None,
)
.await
.unwrap();
let item = database.items(list.id.clone()).await.unwrap().remove(0);
database
.set_item_checked(list.id.clone(), item.id.clone(), true)
.await
.unwrap();
database
.set_item_checked(list.id.clone(), item.id.clone(), true)
.await
.unwrap();
let item = database.items(list.id).await.unwrap().remove(0);
assert!(item.checked);
assert_eq!(item.version, 3);
}
#[tokio::test]
async fn checking_an_item_does_not_change_list_order() {
let database = Database::open_in_memory().unwrap();
let user = database
.create_user(
"order@example.com".into(),
"Order Tester".into(),
"hash".into(),
)
.await
.unwrap();
let list = database.create_list(user.id, "List".into()).await.unwrap();
database
.add_item(
list.id.clone(),
"First".into(),
String::new(),
String::new(),
None,
)
.await
.unwrap();
database
.add_item(
list.id.clone(),
"Second".into(),
String::new(),
String::new(),
None,
)
.await
.unwrap();
let first_item = database.items(list.id.clone()).await.unwrap().remove(0);
database
.set_item_checked(list.id.clone(), first_item.id, true)
.await
.unwrap();
let items = database.items(list.id).await.unwrap();
assert_eq!(items[0].name, "First");
assert!(items[0].checked);
assert_eq!(items[1].name, "Second");
}
}
+89
View File
@@ -0,0 +1,89 @@
use thiserror::Error;
#[derive(Debug, Error)]
pub enum DomainError {
#[error("database error: {0}")]
Database(String),
#[error("password error: {0}")]
Password(String),
#[error("record not found")]
NotFound,
#[error("record already exists")]
Conflict,
}
pub type DomainResult<T> = Result<T, DomainError>;
#[derive(Clone, Debug)]
pub struct User {
pub id: i64,
pub email: String,
pub display_name: String,
/// Opaque, random user handle used as the WebAuthn userHandle. Kept
/// high-entropy and unpredictable per the WebAuthn spec to avoid user
/// enumeration and cross-site correlation. Stored as raw bytes.
pub user_handle: Vec<u8>,
}
#[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)]
pub struct SessionUser {
pub user: User,
pub csrf_token: String,
}
#[derive(Clone, Debug)]
pub struct GroceryList {
pub id: i64,
pub name: String,
pub revision: i64,
}
#[derive(Clone, Debug)]
pub struct Item {
pub id: i64,
pub list_id: i64,
pub name: String,
pub quantity: String,
pub note: String,
pub category_id: Option<i64>,
pub checked: bool,
pub version: i64,
}
#[derive(Clone, Debug)]
pub struct Category {
pub id: i64,
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)]
pub struct PresenceUser {
pub user_id: i64,
pub display_name: String,
}
+1140
View File
File diff suppressed because it is too large Load Diff
+24 -41
View File
@@ -1,23 +1,15 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use async_trait::async_trait;
use tokio::sync::{Mutex, broadcast}; use tokio::sync::{Mutex, broadcast};
#[derive(Clone, Debug)] use crate::domain::PresenceUser;
pub struct PresenceUser { use crate::ports::{HubEvent, RealtimeNotifier, Subscription};
pub user_id: String,
pub display_name: String,
}
#[derive(Clone, Debug)]
pub enum HubEvent {
ListChanged { list_id: String, revision: i64 },
PresenceChanged { list_id: String },
}
#[derive(Debug)] #[derive(Debug)]
struct ConnectionInfo { struct ConnectionInfo {
user_id: String, user_id: i64,
display_name: String, display_name: String,
} }
@@ -26,26 +18,16 @@ struct Room {
connections: HashMap<String, ConnectionInfo>, connections: HashMap<String, ConnectionInfo>,
} }
pub struct Subscription {
pub connection_id: String,
pub receiver: broadcast::Receiver<HubEvent>,
pub presence: Vec<PresenceUser>,
}
#[derive(Clone, Default)] #[derive(Clone, Default)]
pub struct Hub { pub struct InMemoryHub {
rooms: Arc<Mutex<HashMap<String, Room>>>, rooms: Arc<Mutex<HashMap<i64, Room>>>,
} }
impl Hub { #[async_trait]
pub async fn join( impl RealtimeNotifier for InMemoryHub {
&self, async fn join(&self, list_id: i64, user_id: i64, display_name: String) -> Subscription {
list_id: String,
user_id: String,
display_name: String,
) -> Subscription {
let mut rooms = self.rooms.lock().await; let mut rooms = self.rooms.lock().await;
let room = rooms.entry(list_id.clone()).or_insert_with(|| { let room = rooms.entry(list_id).or_insert_with(|| {
let (sender, _) = broadcast::channel(64); let (sender, _) = broadcast::channel(64);
Room { Room {
sender, sender,
@@ -53,7 +35,7 @@ impl Hub {
} }
}); });
let connection_id = crate::db::new_secret(); let connection_id = hex::encode(crate::security::new_secret());
let already_present = room let already_present = room
.connections .connections
.values() .values()
@@ -79,10 +61,10 @@ impl Hub {
} }
} }
pub async fn leave(&self, list_id: &str, connection_id: &str) { async fn leave(&self, list_id: i64, connection_id: &str) {
let mut rooms = self.rooms.lock().await; let mut rooms = self.rooms.lock().await;
let mut remove_room = false; let mut remove_room = false;
if let Some(room) = rooms.get_mut(list_id) { if let Some(room) = rooms.get_mut(&list_id) {
let removed = room.connections.remove(connection_id); let removed = room.connections.remove(connection_id);
if let Some(removed) = removed { if let Some(removed) = removed {
let still_present = room let still_present = room
@@ -90,19 +72,17 @@ impl Hub {
.values() .values()
.any(|connection| connection.user_id == removed.user_id); .any(|connection| connection.user_id == removed.user_id);
if !still_present { if !still_present {
let _ = room.sender.send(HubEvent::PresenceChanged { let _ = room.sender.send(HubEvent::PresenceChanged { list_id });
list_id: list_id.to_owned(),
});
} }
} }
remove_room = room.connections.is_empty(); remove_room = room.connections.is_empty();
} }
if remove_room { if remove_room {
rooms.remove(list_id); rooms.remove(&list_id);
} }
} }
pub async fn publish_list_changed(&self, list_id: String, revision: i64) { async fn publish_list_changed(&self, list_id: i64, revision: i64) {
let rooms = self.rooms.lock().await; let rooms = self.rooms.lock().await;
if let Some(room) = rooms.get(&list_id) { if let Some(room) = rooms.get(&list_id) {
let _ = room let _ = room
@@ -111,19 +91,22 @@ impl Hub {
} }
} }
pub async fn presence(&self, list_id: &str) -> Vec<PresenceUser> { async fn presence(&self, list_id: i64) -> Vec<PresenceUser> {
let rooms = self.rooms.lock().await; let rooms = self.rooms.lock().await;
rooms.get(list_id).map(current_presence).unwrap_or_default() rooms
.get(&list_id)
.map(current_presence)
.unwrap_or_default()
} }
} }
fn current_presence(room: &Room) -> Vec<PresenceUser> { fn current_presence(room: &Room) -> Vec<PresenceUser> {
let mut users = HashMap::<String, PresenceUser>::new(); let mut users = HashMap::<i64, PresenceUser>::new();
for connection in room.connections.values() { for connection in room.connections.values() {
users users
.entry(connection.user_id.clone()) .entry(connection.user_id)
.or_insert_with(|| PresenceUser { .or_insert_with(|| PresenceUser {
user_id: connection.user_id.clone(), user_id: connection.user_id,
display_name: connection.display_name.clone(), display_name: connection.display_name.clone(),
}); });
} }
+137 -886
View File
File diff suppressed because it is too large Load Diff
+258
View File
@@ -0,0 +1,258 @@
use async_trait::async_trait;
use sqlx::SqliteConnection;
use crate::domain::{
Category, DomainResult, GroceryList, Item, Meal, MealIngredient, Passkey, PresenceUser,
SessionUser, User,
};
/// Repositories take `&mut SqliteConnection` (which a `Transaction` derefs to),
/// so several repositories can commit together atomically within a single
/// transaction coordinated by the unit of work.
#[async_trait]
pub trait UserRepository: Send + Sync {
async fn create_user(
&self,
txn: &mut SqliteConnection,
email: String,
display_name: String,
password_hash: String,
) -> DomainResult<User>;
async fn find_user_by_email(
&self,
txn: &mut SqliteConnection,
email: String,
) -> DomainResult<Option<(User, String)>>;
async fn find_user_by_handle(
&self,
txn: &mut SqliteConnection,
user_handle: Vec<u8>,
) -> DomainResult<Option<User>>;
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]
pub trait SessionRepository: Send + Sync {
async fn create_session(
&self,
txn: &mut SqliteConnection,
user_id: i64,
) -> DomainResult<(String, String)>;
async fn session_user(
&self,
txn: &mut SqliteConnection,
session_token: String,
) -> DomainResult<Option<SessionUser>>;
async fn delete_session(
&self,
txn: &mut SqliteConnection,
session_token: String,
) -> DomainResult<()>;
}
#[async_trait]
pub trait ListRepository: Send + Sync {
async fn list_summaries(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<GroceryList>>;
async fn create_list(
&self,
txn: &mut SqliteConnection,
name: String,
) -> DomainResult<GroceryList>;
async fn get_list(
&self,
txn: &mut SqliteConnection,
list_id: i64,
) -> DomainResult<Option<GroceryList>>;
}
#[async_trait]
pub trait CategoryRepository: Send + Sync {
async fn categories(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<Category>>;
async fn create_category(&self, txn: &mut SqliteConnection, name: String) -> DomainResult<i64>;
}
/// A single item to insert in bulk, without a per-item revision bump.
#[derive(Clone, Debug)]
pub struct NewItem {
pub name: String,
pub quantity: String,
pub note: String,
pub category_id: Option<i64>,
}
#[async_trait]
pub trait ItemRepository: Send + Sync {
async fn items(&self, txn: &mut SqliteConnection, list_id: i64) -> DomainResult<Vec<Item>>;
async fn add_item(
&self,
txn: &mut SqliteConnection,
list_id: i64,
name: String,
quantity: String,
note: String,
category_id: Option<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(
&self,
txn: &mut SqliteConnection,
list_id: i64,
item_id: i64,
checked: bool,
) -> DomainResult<i64>;
async fn update_item(
&self,
txn: &mut SqliteConnection,
list_id: i64,
item_id: i64,
name: String,
quantity: String,
note: String,
category_id: Option<i64>,
) -> DomainResult<i64>;
async fn delete_item(
&self,
txn: &mut SqliteConnection,
list_id: i64,
item_id: i64,
) -> DomainResult<i64>;
}
#[async_trait]
pub trait InvitationRepository: Send + Sync {
async fn create_invitation(
&self,
txn: &mut SqliteConnection,
created_by: i64,
token: String,
) -> DomainResult<i64>;
async fn invitation(&self, txn: &mut SqliteConnection, token: String) -> DomainResult<bool>;
async fn accept_invitation(
&self,
txn: &mut SqliteConnection,
token: String,
) -> 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]
pub trait PasswordHasher: Send + Sync {
fn hash(&self, password: &str) -> DomainResult<String>;
fn verify(&self, password: &str, encoded_hash: &str) -> DomainResult<bool>;
}
#[async_trait]
pub trait TokenGenerator: Send + Sync {
fn generate(&self) -> String;
}
#[async_trait]
pub trait RealtimeNotifier: Send + Sync {
async fn join(&self, list_id: i64, user_id: i64, display_name: String) -> Subscription;
async fn leave(&self, list_id: i64, connection_id: &str);
async fn publish_list_changed(&self, list_id: i64, revision: i64);
async fn presence(&self, list_id: i64) -> Vec<PresenceUser>;
}
pub struct Subscription {
pub connection_id: String,
pub receiver: tokio::sync::broadcast::Receiver<HubEvent>,
pub presence: Vec<PresenceUser>,
}
#[derive(Clone, Debug)]
pub enum HubEvent {
ListChanged { list_id: i64, revision: i64 },
PresenceChanged { list_id: i64 },
}
+50
View File
@@ -0,0 +1,50 @@
use argon2::{
Argon2,
password_hash::{
PasswordHash, PasswordHasher as Argon2Hasher, PasswordVerifier, SaltString,
rand_core::OsRng,
},
};
use async_trait::async_trait;
use rand::RngCore;
use crate::domain::{DomainError, DomainResult};
use crate::ports::{PasswordHasher, TokenGenerator};
pub struct Argon2PasswordHasher;
#[async_trait]
impl PasswordHasher for Argon2PasswordHasher {
fn hash(&self, password: &str) -> DomainResult<String> {
let salt = SaltString::generate(&mut OsRng);
Argon2::default()
.hash_password(password.as_bytes(), &salt)
.map(|hash| hash.to_string())
.map_err(|error| DomainError::Password(error.to_string()))
}
fn verify(&self, password: &str, encoded_hash: &str) -> DomainResult<bool> {
let hash = PasswordHash::new(encoded_hash)
.map_err(|error| DomainError::Password(error.to_string()))?;
Ok(Argon2::default()
.verify_password(password.as_bytes(), &hash)
.is_ok())
}
}
pub struct RandomTokenGenerator;
#[async_trait]
impl TokenGenerator for RandomTokenGenerator {
fn generate(&self) -> String {
hex::encode(new_secret())
}
}
/// Generates 32 cryptographically random bytes. Callers that need a
/// client-facing string should hex-encode the result.
pub fn new_secret() -> Vec<u8> {
let mut bytes = [0_u8; 32];
OsRng.fill_bytes(&mut bytes);
bytes.to_vec()
}
+90
View File
@@ -0,0 +1,90 @@
use std::path::Path;
use std::sync::Arc;
use serde::Deserialize;
use tracing::{info, warn};
use crate::ports::{PasswordHasher, UserRepository};
use crate::sqlite::SqliteDatabase;
#[derive(Debug, Deserialize)]
pub struct SeedConfig {
#[serde(default)]
pub user: Option<SeedUser>,
}
#[derive(Debug, Deserialize)]
pub struct SeedUser {
pub email: String,
pub display_name: String,
pub password: String,
}
/// Reads the seed config file and creates the configured default user if the
/// database has no users yet. The file is optional; if it does not exist (or
/// cannot be parsed) seeding is skipped.
pub async fn seed_if_needed(
db: &SqliteDatabase,
users: &Arc<dyn UserRepository>,
hasher: &Arc<dyn PasswordHasher>,
path: &Path,
) {
let Ok(contents) = std::fs::read_to_string(path) else {
return;
};
let config: SeedConfig = match serde_json::from_str(&contents) {
Ok(config) => config,
Err(error) => {
warn!(path = %path.display(), %error, "could not parse seed config; skipping");
return;
}
};
let Some(user) = config.user else {
return;
};
if user.email.trim().is_empty() {
warn!("seed user requires a non-empty email; skipping");
return;
}
let users_for_check = users.clone();
let has_users = match db
.run(move |txn| Box::pin(async move { users_for_check.has_users(txn).await }))
.await
{
Ok(has_users) => has_users,
Err(error) => {
warn!(%error, "could not check for existing users; skipping seed");
return;
}
};
if has_users {
info!("database already has users; skipping seed");
return;
}
let password_hash = match hasher.hash(&user.password) {
Ok(hash) => hash,
Err(error) => {
warn!(%error, "could not hash seed password; skipping");
return;
}
};
let users_for_create = users.clone();
match db
.run(move |txn| {
Box::pin(async move {
users_for_create
.create_user(
txn,
user.email.trim().to_lowercase(),
user.display_name.trim().to_owned(),
password_hash,
)
.await
})
})
.await
{
Ok(user) => info!(id = user.id, email = %user.email, "seeded default user"),
Err(error) => warn!(%error, "could not seed default user"),
}
}
+515
View File
@@ -0,0 +1,515 @@
use std::sync::Arc;
use crate::domain::{DomainError, DomainResult, GroceryList, Item, Meal, SessionUser, User};
use crate::ports::{
CategoryRepository, InvitationRepository, ItemRepository, ListRepository,
MealIngredientRepository, MealRepository, NewItem, PasswordHasher, RealtimeNotifier,
SessionRepository, TokenGenerator, UserRepository,
};
use crate::sqlite::SqliteDatabase;
pub struct AuthService {
db: SqliteDatabase,
users: Arc<dyn UserRepository>,
sessions: Arc<dyn SessionRepository>,
invitations: Arc<dyn InvitationRepository>,
hasher: Arc<dyn PasswordHasher>,
registration_mode: RegistrationMode,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum RegistrationMode {
Open,
InviteOnly,
}
impl AuthService {
pub fn new(
db: SqliteDatabase,
users: Arc<dyn UserRepository>,
sessions: Arc<dyn SessionRepository>,
invitations: Arc<dyn InvitationRepository>,
hasher: Arc<dyn PasswordHasher>,
registration_mode: RegistrationMode,
) -> Self {
Self {
db,
users,
sessions,
invitations,
hasher,
registration_mode,
}
}
pub async fn can_register(&self, invite: Option<&str>) -> DomainResult<bool> {
if self.registration_mode == RegistrationMode::Open {
return Ok(true);
}
let users = Arc::clone(&self.users);
let invitations = Arc::clone(&self.invitations);
let invite = invite.map(str::to_owned);
self.db
.run(move |txn| {
Box::pin(async move {
if !users.has_users(txn).await? {
return Ok(true);
}
let Some(invite) = invite.filter(|invite| !invite.is_empty()) else {
return Ok(false);
};
invitations.invitation(txn, invite).await
})
})
.await
}
pub async fn register(
&self,
display_name: String,
email: String,
password: String,
invite: Option<&str>,
) -> DomainResult<(User, String)> {
if !self.can_register(invite).await? {
return Err(DomainError::Conflict);
}
let password_hash = self.hasher.hash(&password)?;
let users = Arc::clone(&self.users);
let sessions = Arc::clone(&self.sessions);
self.db
.run(move |txn| {
Box::pin(async move {
let user = users
.create_user(txn, email, display_name, password_hash)
.await?;
let (session_token, _) = sessions.create_session(txn, user.id).await?;
Ok((user, session_token))
})
})
.await
}
pub async fn login(
&self,
email: String,
password: String,
) -> DomainResult<Option<(User, String)>> {
let users = Arc::clone(&self.users);
let sessions = Arc::clone(&self.sessions);
let hasher = Arc::clone(&self.hasher);
self.db
.run(move |txn| {
Box::pin(async move {
let Some((user, password_hash)) = users.find_user_by_email(txn, email).await?
else {
return Ok(None);
};
let valid = hasher.verify(&password, &password_hash)?;
if !valid {
return Ok(None);
}
let (session_token, _) = sessions.create_session(txn, user.id).await?;
Ok(Some((user, session_token)))
})
})
.await
}
pub async fn session_user(&self, session_token: String) -> DomainResult<Option<SessionUser>> {
let sessions = Arc::clone(&self.sessions);
self.db
.run(move |txn| {
Box::pin(async move { sessions.session_user(txn, session_token).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<()> {
let sessions = Arc::clone(&self.sessions);
self.db
.run(move |txn| {
Box::pin(async move { sessions.delete_session(txn, session_token).await })
})
.await
}
}
pub struct ListService {
db: SqliteDatabase,
lists: Arc<dyn ListRepository>,
categories: Arc<dyn CategoryRepository>,
items: Arc<dyn ItemRepository>,
realtime: Arc<dyn RealtimeNotifier>,
}
impl ListService {
pub fn new(
db: SqliteDatabase,
lists: Arc<dyn ListRepository>,
categories: Arc<dyn CategoryRepository>,
items: Arc<dyn ItemRepository>,
realtime: Arc<dyn RealtimeNotifier>,
) -> Self {
Self {
db,
lists,
categories,
items,
realtime,
}
}
pub async fn list_summaries(&self) -> DomainResult<Vec<GroceryList>> {
let lists = Arc::clone(&self.lists);
self.db
.run(move |txn| Box::pin(async move { lists.list_summaries(txn).await }))
.await
}
pub async fn create_list(&self, name: String) -> DomainResult<GroceryList> {
let lists = Arc::clone(&self.lists);
self.db
.run(move |txn| Box::pin(async move { lists.create_list(txn, name).await }))
.await
}
pub async fn get_list(&self, list_id: i64) -> DomainResult<Option<GroceryList>> {
let lists = Arc::clone(&self.lists);
self.db
.run(move |txn| Box::pin(async move { lists.get_list(txn, list_id).await }))
.await
}
pub async fn items(&self, list_id: i64) -> DomainResult<Vec<Item>> {
let items = Arc::clone(&self.items);
self.db
.run(move |txn| Box::pin(async move { items.items(txn, list_id).await }))
.await
}
pub async fn categories(&self) -> DomainResult<Vec<crate::domain::Category>> {
let categories = Arc::clone(&self.categories);
self.db
.run(move |txn| Box::pin(async move { categories.categories(txn).await }))
.await
}
pub async fn add_item(
&self,
list_id: i64,
name: String,
quantity: String,
note: String,
category_id: Option<i64>,
) -> DomainResult<i64> {
let items = Arc::clone(&self.items);
let revision = self
.db
.run(move |txn| {
Box::pin(async move {
items
.add_item(txn, list_id, name, quantity, note, category_id)
.await
})
})
.await?;
self.realtime.publish_list_changed(list_id, revision).await;
Ok(revision)
}
pub async fn set_item_checked(
&self,
list_id: i64,
item_id: i64,
checked: bool,
) -> DomainResult<i64> {
let items = Arc::clone(&self.items);
let revision = self
.db
.run(move |txn| {
Box::pin(
async move { items.set_item_checked(txn, list_id, item_id, checked).await },
)
})
.await?;
self.realtime.publish_list_changed(list_id, revision).await;
Ok(revision)
}
pub async fn update_item(
&self,
list_id: i64,
item_id: i64,
name: String,
quantity: String,
note: String,
category_id: Option<i64>,
) -> DomainResult<i64> {
let items = Arc::clone(&self.items);
let revision = self
.db
.run(move |txn| {
Box::pin(async move {
items
.update_item(txn, list_id, item_id, name, quantity, note, category_id)
.await
})
})
.await?;
self.realtime.publish_list_changed(list_id, revision).await;
Ok(revision)
}
pub async fn delete_item(&self, list_id: i64, item_id: i64) -> DomainResult<i64> {
let items = Arc::clone(&self.items);
let revision = self
.db
.run(move |txn| Box::pin(async move { items.delete_item(txn, list_id, item_id).await }))
.await?;
self.realtime.publish_list_changed(list_id, revision).await;
Ok(revision)
}
pub async fn create_category(&self, name: String) -> DomainResult<i64> {
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
.db
.run(move |txn| {
Box::pin(async move {
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?;
self.realtime.publish_list_changed(list_id, revision).await;
Ok(revision)
}
}
pub struct InvitationService {
db: SqliteDatabase,
invitations: Arc<dyn InvitationRepository>,
tokens: Arc<dyn TokenGenerator>,
}
impl InvitationService {
pub fn new(
db: SqliteDatabase,
invitations: Arc<dyn InvitationRepository>,
tokens: Arc<dyn TokenGenerator>,
) -> Self {
Self {
db,
invitations,
tokens,
}
}
pub async fn create_invitation(&self, created_by: i64) -> DomainResult<String> {
let token = self.tokens.generate();
let invitations = Arc::clone(&self.invitations);
self.db
.run(move |txn| {
Box::pin(async move {
invitations
.create_invitation(txn, created_by, token.clone())
.await?;
Ok(token)
})
})
.await
}
pub async fn invitation(&self, token: String) -> DomainResult<bool> {
let invitations = Arc::clone(&self.invitations);
self.db
.run(move |txn| Box::pin(async move { invitations.invitation(txn, token).await }))
.await
}
pub async fn accept_invitation(&self, token: String) -> DomainResult<()> {
let invitations = Arc::clone(&self.invitations);
self.db
.run(move |txn| {
Box::pin(async move { invitations.accept_invitation(txn, token).await })
})
.await
}
}
+2205
View File
File diff suppressed because it is too large Load Diff
+475 -107
View File
@@ -1,8 +1,9 @@
use maud::{DOCTYPE, Markup, html}; use maud::{DOCTYPE, Markup, html};
use pulldown_cmark::{Options, Parser, html as cmark_html};
use crate::{ use crate::{
db::{Category, GroceryList, InvitationInfo, Item, ListAccess, ListSummary, User}, domain::PresenceUser,
hub::PresenceUser, domain::{Category, GroceryList, Item, Meal, MealIngredient, Passkey, User},
}; };
pub fn login_page(error: Option<&str>, invite: Option<&str>) -> Markup { pub fn login_page(error: Option<&str>, invite: Option<&str>) -> Markup {
@@ -13,7 +14,7 @@ pub fn login_page(error: Option<&str>, invite: Option<&str>) -> Markup {
div class="auth-card" { div class="auth-card" {
p class="eyebrow" { "SUSTENANCE" } p class="eyebrow" { "SUSTENANCE" }
h1 { "Welcome back" } h1 { "Welcome back" }
p class="lede" { "Keep the household running, one item at a time." } p class="lede" { "Keep the shopping list in sync." }
@if let Some(error) = error { @if let Some(error) = error {
div class="alert alert-error" role="alert" { (error) } div class="alert alert-error" role="alert" { (error) }
} }
@@ -22,13 +23,16 @@ pub fn login_page(error: Option<&str>, invite: Option<&str>) -> Markup {
input type="hidden" name="invite" value=(invite); input type="hidden" name="invite" value=(invite);
} }
label for="email" { "Email" } label for="email" { "Email" }
input id="email" name="email" type="email" autocomplete="email" required autofocus; input id="email" name="email" type="email" autocomplete="email" autofocus;
label for="password" { "Password" } label for="password" { "Password" }
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" {}
}, },
) )
} }
@@ -54,7 +58,7 @@ pub fn register_page(error: Option<&str>, invite: Option<&str>) -> Markup {
label for="email" { "Email" } label for="email" { "Email" }
input id="email" name="email" type="email" autocomplete="email" required; input id="email" name="email" type="email" autocomplete="email" required;
label for="password" { "Password" } label for="password" { "Password" }
input id="password" name="password" type="password" autocomplete="new-password" minlength="8" required; input id="password" name="password" type="password" autocomplete="new-password" required;
button class="button button-primary" type="submit" { "Create account" } button class="button button-primary" type="submit" { "Create account" }
} }
p class="auth-switch" { "Already have an account? " a href="/login" { "Sign in" } } p class="auth-switch" { "Already have an account? " a href="/login" { "Sign in" } }
@@ -69,23 +73,68 @@ pub fn registration_closed_page() -> Markup {
None, None,
html! { html! {
div class="auth-card" { div class="auth-card" {
p class="eyebrow" { "PRIVATE HOUSEHOLD" } p class="eyebrow" { "PRIVATE LISTS" }
h1 { "Registration is invite-only" } h1 { "Registration is invite-only" }
p class="lede" { "Ask someone who owns a list to send you an invitation link." } p class="lede" { "Ask someone who uses the app to send you an invitation link." }
a class="button button-primary" href="/login" { "Back to sign in" } a class="button button-primary" href="/login" { "Back to sign in" }
} }
}, },
) )
} }
pub fn lists_page(user: &User, lists: &[ListSummary], csrf_token: &str) -> 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 {
page( page(
"Your lists", "Your lists",
Some(user), Some(user),
html! { html! {
div class="page-heading" { div class="page-heading" {
div { div {
p class="eyebrow" { "YOUR HOUSEHOLD" } p class="eyebrow" { "SHARED LISTS" }
h1 { "Grocery lists" } h1 { "Grocery lists" }
p class="lede" { "Everything you need, in one place." } p class="lede" { "Everything you need, in one place." }
} }
@@ -104,12 +153,11 @@ pub fn lists_page(user: &User, lists: &[ListSummary], csrf_token: &str) -> Marku
} }
} @else { } @else {
div class="list-cards" { div class="list-cards" {
@for summary in lists { @for list in lists {
a class="list-card" href=(format!("/lists/{}", summary.list.id)) { a class="list-card" href=(format!("/lists/{}", list.id)) {
span class="list-card-icon" { "" } span class="list-card-icon" { "" }
span class="list-card-copy" { span class="list-card-copy" {
strong { (summary.list.name) } strong { (list.name) }
small { @if summary.role == "owner" { "Owner" } @else { "Member" } }
} }
span class="list-card-arrow" { "" } span class="list-card-arrow" { "" }
} }
@@ -126,70 +174,400 @@ pub fn lists_page(user: &User, lists: &[ListSummary], csrf_token: &str) -> Marku
button class="button button-primary" type="submit" { "Create list" } button class="button button-primary" type="submit" { "Create list" }
} }
} }
section id="sharing" class="panel sharing-panel" {
div class="panel-heading" { h2 { "Invite someone" } }
p { "Create a one-time invite link so a new person can join." }
form
hx-post="/invitations"
hx-target="#invite-result"
hx-swap="innerHTML"
class="stack"
{
input type="hidden" name="csrf" value=(csrf_token);
button class="button button-secondary" type="submit" { "Create invite link" }
}
div id="invite-result" class="invite-result" {}
}
} }
}, },
) )
} }
pub fn list_page( pub fn meals_page(user: &User, meals: &[Meal]) -> Markup {
user: &User,
access: &ListAccess,
items: &[Item],
categories: &[Category],
presence: &[PresenceUser],
csrf_token: &str,
) -> Markup {
let is_owner = access.role == "owner";
page( page(
&access.list.name, "Meals",
Some(user), Some(user),
html! { html! {
div class="list-topbar" { div class="page-heading" {
a class="back-link" href="/lists" { "← All lists" } 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" { div class="list-topbar-actions" {
span class="live-pill" { span class="live-dot" {} "Live" } button type="button" class="button button-small button-quiet" onclick="document.getElementById('meal-edit-modal').showModal()" { "Edit" }
@if is_owner { form method="post" action=(format!("/meals/{}/delete", meal.id)) {
a class="button button-small button-quiet" href="#sharing" { "Share list" } 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(
user: &User,
list: &GroceryList,
items: &[Item],
categories: &[Category],
presence: &[PresenceUser],
csrf_token: &str,
) -> Markup {
page(
&list.name,
Some(user),
html! {
div class="list-topbar" {
a class="back-link" href="/lists" { "← All lists" }
div class="list-topbar-actions" {
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" {
div { div {
p class="eyebrow" { "SHARED LIST" } p class="eyebrow" { "SHARED LIST" }
h1 { (access.list.name) } h1 { (list.name) }
p class="list-meta" { (items.iter().filter(|item| !item.checked).count()) " items to get" } p class="list-meta" { (items.iter().filter(|item| !item.checked).count()) " items to get" }
} }
} }
(list_content_fragment(&access.list, items, categories, csrf_token, false)) (list_content_fragment(list, items, categories, csrf_token, false))
} }
aside class="side-column" { aside class="side-column" {
(presence_panel(presence, false)) (presence_panel(presence, false))
(categories_panel(&access.list, categories, csrf_token, false)) (categories_panel(categories, csrf_token, false))
@if is_owner {
section id="sharing" class="panel sharing-panel" {
div class="panel-heading" { h2 { "Share this list" } }
p { "Create a one-time invite link for someone you shop with." }
form
hx-post=(format!("/lists/{}/invitations", access.list.id))
hx-target="#invite-result"
hx-swap="innerHTML"
class="stack"
{
input type="hidden" name="csrf" value=(csrf_token);
button class="button button-secondary" type="submit" { "Create invite link" }
}
div id="invite-result" class="invite-result" {}
}
}
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." }
} }
} }
} }
div id="live-stream" class="live-stream" hx-ext="ws" ws-connect=(format!("/lists/{}/stream", access.list.id)) {} div id="live-stream" class="live-stream" hx-ext="ws" ws-connect=(format!("/lists/{}/stream", list.id)) {}
}, },
) )
} }
@@ -234,11 +612,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 name="quantity" type="text" maxlength="40" placeholder="Qty" aria-label="Quantity"; input id="item-quantity" name="quantity" type="text" maxlength="40" placeholder="Qty" aria-label="Quantity";
select name="category_id" aria-label="Category" { select id="item-category" name="category_id" aria-label="Category" {
(category_options(categories, None)) (category_options(categories, None))
} }
button class="button button-primary add-button" type="submit" { "+ Add" } button id="add-item-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))
} }
@@ -289,7 +667,7 @@ fn item_groups<'a>(items: &'a [Item], categories: &[Category]) -> Vec<(String, V
for category in categories { for category in categories {
let items_in_category = items let items_in_category = items
.iter() .iter()
.filter(|item| item.category_id.as_deref() == Some(category.id.as_str())) .filter(|item| item.category_id == Some(category.id))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
if !items_in_category.is_empty() { if !items_in_category.is_empty() {
groups.push((category.name.clone(), items_in_category)); groups.push((category.name.clone(), items_in_category));
@@ -334,41 +712,44 @@ 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 class="check-button" type="submit" aria-label=(if item.checked { "Mark unchecked" } else { "Mark complete" }) { button id=(format!("item-check-{}", item.id)) class="check-button" type="submit" aria-label=(if item.checked { "Mark unchecked" } else { "Mark complete" }) {
@if item.checked { "" } @else { "" } @if item.checked { "" } @else { "" }
} }
} }
div class="item-copy" { label class="item-copy" for=(format!("item-check-{}", item.id)) {
@if !item.quantity.is_empty() {
span class="item-qty" { "(" (item.quantity) ")" }
}
strong { (item.name) } strong { (item.name) }
@if !item.quantity.is_empty() || !item.note.is_empty() { @if !item.note.is_empty() {
small { small { (item.note) }
@if !item.quantity.is_empty() { (item.quantity) }
@if !item.quantity.is_empty() && !item.note.is_empty() { " · " }
@if !item.note.is_empty() { (item.note) }
}
} }
} }
details class="item-actions" { button type="button" class="item-actions-button" aria-label="Item actions" onclick=(format!("document.getElementById('item-edit-{}').showModal()", item.id)) { "•••" }
summary aria-label="Item actions" { "•••" } dialog id=(format!("item-edit-{}", item.id)) class="item-modal" {
div class="item-menu" { div class="item-modal-card" {
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="edit-form stack" class="stack"
{ {
input type="hidden" name="csrf" value=(csrf_token); input type="hidden" name="csrf" value=(csrf_token);
label { "Name" } label { "Name" }
input name="name" value=(item.name) maxlength="120" required; input id=(format!("item-edit-name-{}", item.id)) name="name" value=(item.name) maxlength="120" required;
label { "Quantity" } label { "Quantity" }
input name="quantity" value=(item.quantity) maxlength="40"; input id=(format!("item-edit-quantity-{}", item.id)) name="quantity" value=(item.quantity) maxlength="40";
label { "Note" } label { "Note" }
input name="note" value=(item.note) maxlength="120"; input id=(format!("item-edit-note-{}", item.id)) name="note" value=(item.note) maxlength="120";
label { "Category" } label { "Category" }
select name="category_id" { select id=(format!("item-edit-category-{}", item.id)) name="category_id" {
(category_options(categories, item.category_id.as_deref())) (category_options(categories, item.category_id))
} }
button class="button button-small button-secondary" type="submit" { "Save" } button id=(format!("item-edit-save-{}", item.id)) class="button button-primary" 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))
@@ -376,7 +757,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 class="danger-link" type="submit" { "Remove item" } button id=(format!("item-edit-delete-{}", item.id)) class="danger-link" type="submit" { "Remove item" }
} }
} }
} }
@@ -384,7 +765,7 @@ fn item_row(item: &Item, categories: &[Category], csrf_token: &str) -> Markup {
} }
} }
fn category_options(categories: &[Category], selected: Option<&str>) -> Markup { fn category_options(categories: &[Category], selected: Option<i64>) -> Markup {
html! { html! {
@if selected.is_none() { @if selected.is_none() {
option value="" selected { "No category" } option value="" selected { "No category" }
@@ -392,7 +773,7 @@ fn category_options(categories: &[Category], selected: Option<&str>) -> Markup {
option value="" { "No category" } option value="" { "No category" }
} }
@for category in categories { @for category in categories {
@if selected == Some(category.id.as_str()) { @if selected == Some(category.id) {
option value=(category.id) selected { (category.name) } option value=(category.id) selected { (category.name) }
} @else { } @else {
option value=(category.id) { (category.name) } option value=(category.id) { (category.name) }
@@ -401,12 +782,7 @@ fn category_options(categories: &[Category], selected: Option<&str>) -> Markup {
} }
} }
pub fn categories_panel( pub fn categories_panel(categories: &[Category], csrf_token: &str, out_of_band: bool) -> Markup {
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" }
@@ -414,15 +790,15 @@ pub fn categories_panel(
} }
p { "Organize items by aisle or shopping area." } p { "Organize items by aisle or shopping area." }
form form
hx-post=(format!("/lists/{}/categories", list.id)) hx-post="/categories"
hx-target="#category-result" hx-target="#category-result"
hx-swap="innerHTML" hx-swap="innerHTML"
hx-on::after-request="if (event.detail.successful) this.reset()" hx-on::after-request="if (event.detail.successful) window.location.reload()"
class="category-form" class="category-form"
{ {
input type="hidden" name="csrf" value=(csrf_token); input type="hidden" name="csrf" value=(csrf_token);
input name="name" type="text" maxlength="60" placeholder="Add a category" required; input id="category-name" name="name" type="text" maxlength="60" placeholder="Add a category" required;
button class="button button-small button-secondary" type="submit" { "Add" } button id="add-category-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." }
@@ -448,26 +824,14 @@ pub fn categories_panel(
} }
pub fn live_list_fragments( pub fn live_list_fragments(
access: &ListAccess, list: &GroceryList,
items: &[Item], items: &[Item],
categories: &[Category], categories: &[Category],
csrf_token: &str, csrf_token: &str,
) -> Markup { ) -> Markup {
html! { html! {
(list_content_fragment(&access.list, items, categories, csrf_token, true)) (list_content_fragment(list, items, categories, csrf_token, true))
(categories_panel(&access.list, categories, csrf_token, true)) (categories_panel(categories, csrf_token, true))
}
}
pub fn category_created(
access: &ListAccess,
items: &[Item],
categories: &[Category],
csrf_token: &str,
) -> Markup {
html! {
p class="category-success" { "Category added." }
(live_list_fragments(access, items, categories, csrf_token))
} }
} }
@@ -509,7 +873,6 @@ fn presence_content(presence: &[PresenceUser]) -> Markup {
} }
pub fn invite_page( pub fn invite_page(
info: &InvitationInfo,
user: Option<&User>, user: Option<&User>,
token: &str, token: &str,
error: Option<&str>, error: Option<&str>,
@@ -521,8 +884,8 @@ pub fn invite_page(
html! { html! {
div class="auth-card invite-card" { div class="auth-card invite-card" {
p class="eyebrow" { "YOU'RE INVITED" } p class="eyebrow" { "YOU'RE INVITED" }
h1 { "Join " (info.list_name) } h1 { "Join the shared lists" }
p class="lede" { "Shop together and keep the list in sync." } p class="lede" { "Shop together and keep all the lists in sync." }
@if let Some(error) = error { @if let Some(error) = error {
div class="alert alert-error" role="alert" { (error) } div class="alert alert-error" role="alert" { (error) }
} }
@@ -532,14 +895,15 @@ pub fn invite_page(
@if let Some(csrf_token) = csrf_token { @if let Some(csrf_token) = csrf_token {
input type="hidden" name="csrf" value=(csrf_token); input type="hidden" name="csrf" value=(csrf_token);
} }
button class="button button-primary" type="submit" { "Join list" } button class="button button-primary" type="submit" { "Join lists" }
} }
p class="muted" { "Want to join as a different person? Create a new account below." }
} @else { } @else {
p { "Sign in or create an account to accept this invite." } p { "Sign in or create an account to accept this invite." }
div class="invite-actions" { }
a class="button button-primary" href=(format!("/login?invite={}", token)) { "Sign in" } div class="invite-actions" {
a class="button button-secondary" href=(format!("/register?invite={}", token)) { "Create account" } a class="button button-primary" href=(format!("/register?invite={}", token)) { "Create account" }
} a class="button button-secondary" href=(format!("/login?invite={}", token)) { "Sign in" }
} }
} }
}, },
@@ -586,8 +950,12 @@ 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" {
span class="user-name" { (user.display_name) } a class="user-name" href="/account" { (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" }
} }
+340
View File
@@ -0,0 +1,340 @@
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, UserVerificationPolicy,
},
};
use crate::domain::{DomainError, DomainResult, Passkey as DbPasskey, User};
use crate::ports::{PasskeyRepository, UserRepository};
use crate::security::new_secret;
use crate::sqlite::SqliteDatabase;
/// Site-specific WebAuthn configuration, derived from env vars.
pub struct AppWebauthnConfig {
rp_id: String,
rp_name: String,
origin: url::Url,
require_resident_key: bool,
}
impl AppWebauthnConfig {
pub fn new(rp_id: String, rp_name: String, origin: url::Url) -> Self {
Self {
rp_id,
rp_name,
origin,
// Resident (discoverable) keys let users sign in without typing an
// email, because the authenticator can select the credential on its
// own and return the user handle.
require_resident_key: true,
}
}
}
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
}
fn get_require_resident_key(&self) -> bool {
self.require_resident_key
}
}
/// A single-use, in-memory challenge store. Registrations are keyed by user id;
/// authentications are keyed by a random token so that userless (discoverable)
/// ceremonies can be correlated back to the finish request.
#[derive(Default)]
struct ChallengeStore {
registrations: HashMap<i64, RegistrationState>,
authentications: HashMap<String, AuthenticationState>,
}
pub struct WebAuthnService {
db: SqliteDatabase,
webauthn: Webauthn<AppWebauthnConfig>,
users: Arc<dyn UserRepository>,
passkeys: Arc<dyn PasskeyRepository>,
challenges: Mutex<ChallengeStore>,
}
impl WebAuthnService {
pub fn new(
db: SqliteDatabase,
config: AppWebauthnConfig,
users: Arc<dyn UserRepository>,
passkeys: Arc<dyn PasskeyRepository>,
) -> Self {
let webauthn = Webauthn::new(config);
Self {
db,
webauthn,
users,
passkeys,
challenges: Mutex::new(ChallengeStore::default()),
}
}
/// Start a passkey registration ceremony for an authenticated user.
pub fn start_registration(&self, user: &User) -> DomainResult<CreationChallengeResponse> {
// Use the user's opaque, random user handle as the WebAuthn userHandle
// so that userless (discoverable) sign-in can resolve the owning user
// from the assertion's userHandle without exposing the numeric id.
let (challenge, state) = self
.webauthn
.generate_challenge_register_options(
user.user_handle.clone(),
user.email.clone(),
user.display_name.clone(),
None,
Some(UserVerificationPolicy::Required),
None,
)
.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 identified by email.
/// Returns the challenge and a token used to correlate the finish request.
pub async fn start_authentication(
&self,
user_id: i64,
) -> DomainResult<(RequestChallengeResponse, String)> {
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)?;
let token = hex::encode(new_secret());
self.challenges
.lock()
.map_err(|_| DomainError::Database("challenge lock poisoned".into()))?
.authentications
.insert(token.clone(), state);
Ok((challenge, token))
}
/// Start a userless passkey authentication ceremony. No email is required:
/// the authenticator selects a discoverable credential and returns a user
/// handle that we resolve to the owning user on finish.
pub async fn start_userless_authentication(
&self,
) -> DomainResult<(RequestChallengeResponse, String)> {
let (challenge, mut state) = self
.webauthn
.generate_challenge_authenticate_options(vec![], None)
.map_err(webauthn_error)?;
// With no allowCredentials the browser will offer any discoverable
// credential for this RP; the credential set is populated from the
// user handle once the assertion is received.
state.set_allowed_credentials(vec![]);
let token = hex::encode(new_secret());
self.challenges
.lock()
.map_err(|_| DomainError::Database("challenge lock poisoned".into()))?
.authentications
.insert(token.clone(), state);
Ok((challenge, token))
}
/// Finish a passkey authentication ceremony, resolving the owning user from
/// the credential id (and, for userless ceremonies, the user handle).
pub async fn finish_authentication(
&self,
token: String,
response: PublicKeyCredential,
) -> DomainResult<i64> {
let mut state = self
.challenges
.lock()
.map_err(|_| DomainError::Database("challenge lock poisoned".into()))?
.authentications
.remove(&token)
.ok_or(DomainError::NotFound)?;
// For userless ceremonies the assertion carries a user handle that
// identifies the user; load that user's credentials so the signature
// can be verified against the correct key.
if let Some(user_handle) = response.get_user_handle() {
let handle = user_handle.to_vec();
let users = Arc::clone(&self.users);
let db = self.db.clone();
let user_id = db
.run(move |txn| {
let users = users.clone();
Box::pin(async move {
let user = users
.find_user_by_handle(txn, handle)
.await?
.ok_or(DomainError::NotFound)?;
Ok(user.id)
})
})
.await?;
let passkeys = Arc::clone(&self.passkeys);
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?;
state.set_allowed_credentials(credentials);
}
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);
let user_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(stored.user_id)
})
})
.await?;
Ok(user_id)
}
/// 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
}
}
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())
}
+34
View File
@@ -0,0 +1,34 @@
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.trim();
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 account.");
return;
}
const data = await start.json();
const pk = data.publicKey;
pk.challenge = b64ToBytes(pk.challenge);
if (pk.allowCredentials) {
pk.allowCredentials.forEach((c) => (c.id = b64ToBytes(c.id)));
}
const credential = await navigator.credentials.get({ publicKey: pk });
const finish = await fetch("/auth/passkey/login/finish", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token: data.token, response: credential }),
});
if (finish.ok) {
window.location.href = "/lists";
}
});
+32
View File
@@ -0,0 +1,32 @@
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";
}
});
+196 -10
View File
@@ -39,8 +39,20 @@ 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; } .user-name { color: var(--ink); font-weight: 700; text-decoration: none; }
.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; }
@@ -63,6 +75,8 @@ 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); }
@@ -83,6 +97,12 @@ input:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85, 113
.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; }
@@ -94,6 +114,13 @@ input:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85, 113
.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; }
@@ -112,14 +139,71 @@ input:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85, 113
.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; flex: 1; min-width: 0; gap: 2px; } .item-copy { display: grid; grid-template-columns: auto 1fr; flex: 1; min-width: 0; gap: 2px 7px; align-items: baseline; }
.item-copy strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .item-copy strong { grid-column: 2; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.item-copy small { overflow: hidden; color: var(--muted); text-overflow: ellipsis; white-space: nowrap; font-size: .78rem; } .item-qty { grid-column: 1; grid-row: 1; color: var(--muted); font-weight: 700; white-space: nowrap; }
.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 { position: relative; } .item-actions-button {
.item-actions summary { padding: 7px 5px; color: var(--muted); cursor: pointer; list-style: none; font-size: .78rem; letter-spacing: 2px; } flex: 0 0 auto;
.item-actions summary::-webkit-details-marker { display: none; } padding: 7px 8px;
.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: 0;
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; }
@@ -153,9 +237,109 @@ input:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85, 113
.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: 20px 0; } .site-header { padding: 18px 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)); }
@@ -163,12 +347,14 @@ input:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85, 113
} }
@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; }