Compare commits
3
Commits
0.3.0
..
4cbd5ef9cb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4cbd5ef9cb | ||
|
|
2542f010b1 | ||
|
|
b71bdb2d5d |
@@ -3,7 +3,3 @@
|
|||||||
/sustenance.db*
|
/sustenance.db*
|
||||||
/.env
|
/.env
|
||||||
/seed.json
|
/seed.json
|
||||||
/e2e/node_modules/
|
|
||||||
/e2e/test-results/
|
|
||||||
/e2e/playwright-report/
|
|
||||||
/test-results/
|
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
when:
|
|
||||||
event: [push, pull_request]
|
|
||||||
|
|
||||||
steps:
|
|
||||||
e2e-build:
|
|
||||||
image: rust:1
|
|
||||||
commands:
|
|
||||||
- cargo build
|
|
||||||
|
|
||||||
e2e-test:
|
|
||||||
image: node:24
|
|
||||||
directory: e2e
|
|
||||||
commands:
|
|
||||||
- apt-get update
|
|
||||||
- apt-get install -y --no-install-recommends ca-certificates fonts-liberation libasound2 libatk-bridge2.0-0 libatk1.0-0 libcups2 libdbus-1-3 libdrm2 libgbm1 libglib2.0-0 libgtk-3-0 libnspr4 libnss3 libpango-1.0-0 libx11-6 libxcb1 libxcomposite1 libxdamage1 libxext6 libxfixes3 libxkbcommon0 libxrandr2 xdg-utils
|
|
||||||
- npm install && npx playwright install chromium
|
|
||||||
- npx playwright test
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
when:
|
|
||||||
event: [push, pull_request]
|
|
||||||
|
|
||||||
steps:
|
|
||||||
fmt:
|
|
||||||
image: rust:1
|
|
||||||
commands:
|
|
||||||
- rustup component add rustfmt
|
|
||||||
- cargo fmt --all -- --check
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
when:
|
|
||||||
event: [push, pull_request]
|
|
||||||
|
|
||||||
steps:
|
|
||||||
test:
|
|
||||||
image: rust:1
|
|
||||||
commands:
|
|
||||||
- cargo test --all
|
|
||||||
Generated
+17
-580
@@ -68,7 +68,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
|
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"axum-core",
|
"axum-core",
|
||||||
"base64 0.22.1",
|
"base64",
|
||||||
"bytes",
|
"bytes",
|
||||||
"form_urlencoded",
|
"form_urlencoded",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
@@ -116,12 +116,6 @@ dependencies = [
|
|||||||
"tracing",
|
"tracing",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "base64"
|
|
||||||
version = "0.13.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "base64"
|
name = "base64"
|
||||||
version = "0.22.1"
|
version = "0.22.1"
|
||||||
@@ -139,9 +133,6 @@ name = "bitflags"
|
|||||||
version = "2.13.1"
|
version = "2.13.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
|
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
|
||||||
dependencies = [
|
|
||||||
"serde_core",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "blake2"
|
name = "blake2"
|
||||||
@@ -161,12 +152,6 @@ dependencies = [
|
|||||||
"generic-array",
|
"generic-array",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "byteorder"
|
|
||||||
version = "1.5.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bytes"
|
name = "bytes"
|
||||||
version = "1.12.1"
|
version = "1.12.1"
|
||||||
@@ -189,12 +174,6 @@ version = "1.0.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "const-oid"
|
|
||||||
version = "0.9.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cpufeatures"
|
name = "cpufeatures"
|
||||||
version = "0.2.17"
|
version = "0.2.17"
|
||||||
@@ -250,17 +229,6 @@ version = "2.11.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8"
|
checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "der"
|
|
||||||
version = "0.7.10"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
|
||||||
dependencies = [
|
|
||||||
"const-oid",
|
|
||||||
"pem-rfc7468",
|
|
||||||
"zeroize",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "digest"
|
name = "digest"
|
||||||
version = "0.10.7"
|
version = "0.10.7"
|
||||||
@@ -268,7 +236,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"block-buffer",
|
"block-buffer",
|
||||||
"const-oid",
|
|
||||||
"crypto-common",
|
"crypto-common",
|
||||||
"subtle",
|
"subtle",
|
||||||
]
|
]
|
||||||
@@ -315,17 +282,6 @@ dependencies = [
|
|||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "etcetera"
|
|
||||||
version = "0.8.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"home",
|
|
||||||
"windows-sys 0.48.0",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "event-listener"
|
name = "event-listener"
|
||||||
version = "5.4.2"
|
version = "5.4.2"
|
||||||
@@ -359,21 +315,6 @@ version = "0.1.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
|
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "foreign-types"
|
|
||||||
version = "0.3.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
|
|
||||||
dependencies = [
|
|
||||||
"foreign-types-shared",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "foreign-types-shared"
|
|
||||||
version = "0.1.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "form_urlencoded"
|
name = "form_urlencoded"
|
||||||
version = "1.2.2"
|
version = "1.2.2"
|
||||||
@@ -508,12 +449,6 @@ dependencies = [
|
|||||||
"wasip2",
|
"wasip2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "half"
|
|
||||||
version = "1.8.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "1b43ede17f21864e81be2fa654110bf1e793774238d86ef8555c37e6519c0403"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hashbrown"
|
name = "hashbrown"
|
||||||
version = "0.15.5"
|
version = "0.15.5"
|
||||||
@@ -552,33 +487,6 @@ version = "0.4.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "hkdf"
|
|
||||||
version = "0.12.4"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
|
|
||||||
dependencies = [
|
|
||||||
"hmac",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "hmac"
|
|
||||||
version = "0.12.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
|
||||||
dependencies = [
|
|
||||||
"digest",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "home"
|
|
||||||
version = "0.5.12"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
|
|
||||||
dependencies = [
|
|
||||||
"windows-sys 0.61.2",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "http"
|
name = "http"
|
||||||
version = "1.5.0"
|
version = "1.5.0"
|
||||||
@@ -789,9 +697,6 @@ name = "lazy_static"
|
|||||||
version = "1.5.0"
|
version = "1.5.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||||
dependencies = [
|
|
||||||
"spin",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libc"
|
name = "libc"
|
||||||
@@ -799,24 +704,6 @@ version = "0.2.189"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
|
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "libm"
|
|
||||||
version = "0.2.16"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "libredox"
|
|
||||||
version = "0.1.18"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652"
|
|
||||||
dependencies = [
|
|
||||||
"bitflags",
|
|
||||||
"libc",
|
|
||||||
"plain",
|
|
||||||
"redox_syscall 0.9.1",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libsqlite3-sys"
|
name = "libsqlite3-sys"
|
||||||
version = "0.30.1"
|
version = "0.30.1"
|
||||||
@@ -886,16 +773,6 @@ dependencies = [
|
|||||||
"syn 2.0.119",
|
"syn 2.0.119",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "md-5"
|
|
||||||
version = "0.10.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"digest",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "memchr"
|
name = "memchr"
|
||||||
version = "2.8.3"
|
version = "2.8.3"
|
||||||
@@ -918,12 +795,6 @@ dependencies = [
|
|||||||
"unicase",
|
"unicase",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "minimal-lexical"
|
|
||||||
version = "0.2.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mio"
|
name = "mio"
|
||||||
version = "1.2.2"
|
version = "1.2.2"
|
||||||
@@ -935,16 +806,6 @@ dependencies = [
|
|||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "nom"
|
|
||||||
version = "7.1.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
|
|
||||||
dependencies = [
|
|
||||||
"memchr",
|
|
||||||
"minimal-lexical",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "nu-ansi-term"
|
name = "nu-ansi-term"
|
||||||
version = "0.50.3"
|
version = "0.50.3"
|
||||||
@@ -954,41 +815,6 @@ dependencies = [
|
|||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "num-bigint-dig"
|
|
||||||
version = "0.8.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"
|
|
||||||
dependencies = [
|
|
||||||
"lazy_static",
|
|
||||||
"libm",
|
|
||||||
"num-integer",
|
|
||||||
"num-iter",
|
|
||||||
"num-traits",
|
|
||||||
"rand 0.8.7",
|
|
||||||
"smallvec",
|
|
||||||
"zeroize",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "num-integer"
|
|
||||||
version = "0.1.46"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
|
|
||||||
dependencies = [
|
|
||||||
"num-traits",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "num-iter"
|
|
||||||
version = "0.1.46"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
|
|
||||||
dependencies = [
|
|
||||||
"num-integer",
|
|
||||||
"num-traits",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "num-traits"
|
name = "num-traits"
|
||||||
version = "0.2.19"
|
version = "0.2.19"
|
||||||
@@ -996,7 +822,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"autocfg",
|
"autocfg",
|
||||||
"libm",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1005,43 +830,6 @@ version = "1.21.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "openssl"
|
|
||||||
version = "0.10.81"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45"
|
|
||||||
dependencies = [
|
|
||||||
"bitflags",
|
|
||||||
"cfg-if",
|
|
||||||
"foreign-types",
|
|
||||||
"libc",
|
|
||||||
"openssl-macros",
|
|
||||||
"openssl-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "openssl-macros"
|
|
||||||
version = "0.1.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 2.0.119",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "openssl-sys"
|
|
||||||
version = "0.9.117"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"
|
|
||||||
dependencies = [
|
|
||||||
"cc",
|
|
||||||
"libc",
|
|
||||||
"pkg-config",
|
|
||||||
"vcpkg",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "parking"
|
name = "parking"
|
||||||
version = "2.2.1"
|
version = "2.2.1"
|
||||||
@@ -1066,7 +854,7 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"libc",
|
"libc",
|
||||||
"redox_syscall 0.5.18",
|
"redox_syscall",
|
||||||
"smallvec",
|
"smallvec",
|
||||||
"windows-link",
|
"windows-link",
|
||||||
]
|
]
|
||||||
@@ -1082,15 +870,6 @@ dependencies = [
|
|||||||
"subtle",
|
"subtle",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "pem-rfc7468"
|
|
||||||
version = "0.7.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
|
|
||||||
dependencies = [
|
|
||||||
"base64ct",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "percent-encoding"
|
name = "percent-encoding"
|
||||||
version = "2.3.2"
|
version = "2.3.2"
|
||||||
@@ -1103,39 +882,12 @@ version = "0.2.17"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "pkcs1"
|
|
||||||
version = "0.7.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
|
|
||||||
dependencies = [
|
|
||||||
"der",
|
|
||||||
"pkcs8",
|
|
||||||
"spki",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "pkcs8"
|
|
||||||
version = "0.10.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
|
|
||||||
dependencies = [
|
|
||||||
"der",
|
|
||||||
"spki",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pkg-config"
|
name = "pkg-config"
|
||||||
version = "0.3.33"
|
version = "0.3.33"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
|
checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "plain"
|
|
||||||
version = "0.2.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "potential_utf"
|
name = "potential_utf"
|
||||||
version = "0.1.5"
|
version = "0.1.5"
|
||||||
@@ -1277,15 +1029,6 @@ dependencies = [
|
|||||||
"bitflags",
|
"bitflags",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "redox_syscall"
|
|
||||||
version = "0.9.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "07507be7b4a5f9f26eeb41eeaebb1f5a7ff29dfb29739facc21d35bf8b11c21e"
|
|
||||||
dependencies = [
|
|
||||||
"bitflags",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "regex-automata"
|
name = "regex-automata"
|
||||||
version = "0.4.16"
|
version = "0.4.16"
|
||||||
@@ -1317,26 +1060,6 @@ dependencies = [
|
|||||||
"windows-sys 0.52.0",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "rsa"
|
|
||||||
version = "0.9.10"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"
|
|
||||||
dependencies = [
|
|
||||||
"const-oid",
|
|
||||||
"digest",
|
|
||||||
"num-bigint-dig",
|
|
||||||
"num-integer",
|
|
||||||
"num-traits",
|
|
||||||
"pkcs1",
|
|
||||||
"pkcs8",
|
|
||||||
"rand_core 0.6.4",
|
|
||||||
"signature",
|
|
||||||
"spki",
|
|
||||||
"subtle",
|
|
||||||
"zeroize",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustls"
|
name = "rustls"
|
||||||
version = "0.23.43"
|
version = "0.23.43"
|
||||||
@@ -1393,16 +1116,6 @@ dependencies = [
|
|||||||
"serde_derive",
|
"serde_derive",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "serde_cbor"
|
|
||||||
version = "0.11.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2bef2ebfde456fb76bbcf9f59315333decc4fda0b2b44b420243c11e0f5ec1f5"
|
|
||||||
dependencies = [
|
|
||||||
"half",
|
|
||||||
"serde",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde_core"
|
name = "serde_core"
|
||||||
version = "1.0.229"
|
version = "1.0.229"
|
||||||
@@ -1506,16 +1219,6 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "signature"
|
|
||||||
version = "2.2.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
|
|
||||||
dependencies = [
|
|
||||||
"digest",
|
|
||||||
"rand_core 0.6.4",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "slab"
|
name = "slab"
|
||||||
version = "0.4.12"
|
version = "0.4.12"
|
||||||
@@ -1527,9 +1230,6 @@ name = "smallvec"
|
|||||||
version = "1.15.2"
|
version = "1.15.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
|
checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
|
||||||
dependencies = [
|
|
||||||
"serde",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "socket2"
|
name = "socket2"
|
||||||
@@ -1550,16 +1250,6 @@ dependencies = [
|
|||||||
"lock_api",
|
"lock_api",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "spki"
|
|
||||||
version = "0.7.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
|
|
||||||
dependencies = [
|
|
||||||
"base64ct",
|
|
||||||
"der",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sqlx"
|
name = "sqlx"
|
||||||
version = "0.8.6"
|
version = "0.8.6"
|
||||||
@@ -1568,8 +1258,6 @@ checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"sqlx-core",
|
"sqlx-core",
|
||||||
"sqlx-macros",
|
"sqlx-macros",
|
||||||
"sqlx-mysql",
|
|
||||||
"sqlx-postgres",
|
|
||||||
"sqlx-sqlite",
|
"sqlx-sqlite",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1579,7 +1267,7 @@ version = "0.8.6"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6"
|
checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64",
|
||||||
"bytes",
|
"bytes",
|
||||||
"crc",
|
"crc",
|
||||||
"crossbeam-queue",
|
"crossbeam-queue",
|
||||||
@@ -1598,10 +1286,9 @@ dependencies = [
|
|||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"rustls",
|
"rustls",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
|
||||||
"sha2",
|
"sha2",
|
||||||
"smallvec",
|
"smallvec",
|
||||||
"thiserror 2.0.19",
|
"thiserror",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-stream",
|
"tokio-stream",
|
||||||
"tracing",
|
"tracing",
|
||||||
@@ -1645,84 +1332,6 @@ dependencies = [
|
|||||||
"url",
|
"url",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "sqlx-mysql"
|
|
||||||
version = "0.8.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526"
|
|
||||||
dependencies = [
|
|
||||||
"atoi",
|
|
||||||
"base64 0.22.1",
|
|
||||||
"bitflags",
|
|
||||||
"byteorder",
|
|
||||||
"bytes",
|
|
||||||
"crc",
|
|
||||||
"digest",
|
|
||||||
"dotenvy",
|
|
||||||
"either",
|
|
||||||
"futures-channel",
|
|
||||||
"futures-core",
|
|
||||||
"futures-io",
|
|
||||||
"futures-util",
|
|
||||||
"generic-array",
|
|
||||||
"hex",
|
|
||||||
"hkdf",
|
|
||||||
"hmac",
|
|
||||||
"itoa",
|
|
||||||
"log",
|
|
||||||
"md-5",
|
|
||||||
"memchr",
|
|
||||||
"once_cell",
|
|
||||||
"percent-encoding",
|
|
||||||
"rand 0.8.7",
|
|
||||||
"rsa",
|
|
||||||
"sha1",
|
|
||||||
"sha2",
|
|
||||||
"smallvec",
|
|
||||||
"sqlx-core",
|
|
||||||
"stringprep",
|
|
||||||
"thiserror 2.0.19",
|
|
||||||
"tracing",
|
|
||||||
"whoami",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "sqlx-postgres"
|
|
||||||
version = "0.8.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46"
|
|
||||||
dependencies = [
|
|
||||||
"atoi",
|
|
||||||
"base64 0.22.1",
|
|
||||||
"bitflags",
|
|
||||||
"byteorder",
|
|
||||||
"crc",
|
|
||||||
"dotenvy",
|
|
||||||
"etcetera",
|
|
||||||
"futures-channel",
|
|
||||||
"futures-core",
|
|
||||||
"futures-util",
|
|
||||||
"hex",
|
|
||||||
"hkdf",
|
|
||||||
"hmac",
|
|
||||||
"home",
|
|
||||||
"itoa",
|
|
||||||
"log",
|
|
||||||
"md-5",
|
|
||||||
"memchr",
|
|
||||||
"once_cell",
|
|
||||||
"rand 0.8.7",
|
|
||||||
"serde",
|
|
||||||
"serde_json",
|
|
||||||
"sha2",
|
|
||||||
"smallvec",
|
|
||||||
"sqlx-core",
|
|
||||||
"stringprep",
|
|
||||||
"thiserror 2.0.19",
|
|
||||||
"tracing",
|
|
||||||
"whoami",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sqlx-sqlite"
|
name = "sqlx-sqlite"
|
||||||
version = "0.8.6"
|
version = "0.8.6"
|
||||||
@@ -1742,7 +1351,7 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
"serde_urlencoded",
|
"serde_urlencoded",
|
||||||
"sqlx-core",
|
"sqlx-core",
|
||||||
"thiserror 2.0.19",
|
"thiserror",
|
||||||
"tracing",
|
"tracing",
|
||||||
"url",
|
"url",
|
||||||
]
|
]
|
||||||
@@ -1753,17 +1362,6 @@ version = "1.2.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "stringprep"
|
|
||||||
version = "0.1.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1"
|
|
||||||
dependencies = [
|
|
||||||
"unicode-bidi",
|
|
||||||
"unicode-normalization",
|
|
||||||
"unicode-properties",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "subtle"
|
name = "subtle"
|
||||||
version = "2.6.1"
|
version = "2.6.1"
|
||||||
@@ -1772,12 +1370,11 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sustenance"
|
name = "sustenance"
|
||||||
version = "0.3.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"argon2",
|
"argon2",
|
||||||
"async-trait",
|
"async-trait",
|
||||||
"axum",
|
"axum",
|
||||||
"base64 0.22.1",
|
|
||||||
"futures-util",
|
"futures-util",
|
||||||
"hex",
|
"hex",
|
||||||
"maud",
|
"maud",
|
||||||
@@ -1787,14 +1384,12 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"sha2",
|
"sha2",
|
||||||
"sqlx",
|
"sqlx",
|
||||||
"thiserror 2.0.19",
|
"thiserror",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tower",
|
"tower",
|
||||||
"tower-http",
|
"tower-http",
|
||||||
"tracing",
|
"tracing",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
"url",
|
|
||||||
"webauthn-rs",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1836,33 +1431,13 @@ dependencies = [
|
|||||||
"syn 2.0.119",
|
"syn 2.0.119",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "thiserror"
|
|
||||||
version = "1.0.69"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
|
|
||||||
dependencies = [
|
|
||||||
"thiserror-impl 1.0.69",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "thiserror"
|
name = "thiserror"
|
||||||
version = "2.0.19"
|
version = "2.0.19"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9"
|
checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"thiserror-impl 2.0.19",
|
"thiserror-impl",
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "thiserror-impl"
|
|
||||||
version = "1.0.69"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 2.0.119",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1895,21 +1470,6 @@ dependencies = [
|
|||||||
"zerovec",
|
"zerovec",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "tinyvec"
|
|
||||||
version = "1.12.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f"
|
|
||||||
dependencies = [
|
|
||||||
"tinyvec_macros",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "tinyvec_macros"
|
|
||||||
version = "0.1.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tokio"
|
name = "tokio"
|
||||||
version = "1.53.1"
|
version = "1.53.1"
|
||||||
@@ -2103,7 +1663,7 @@ dependencies = [
|
|||||||
"log",
|
"log",
|
||||||
"rand 0.9.5",
|
"rand 0.9.5",
|
||||||
"sha1",
|
"sha1",
|
||||||
"thiserror 2.0.19",
|
"thiserror",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2118,33 +1678,12 @@ version = "2.9.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
|
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "unicode-bidi"
|
|
||||||
version = "0.3.18"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-ident"
|
name = "unicode-ident"
|
||||||
version = "1.0.24"
|
version = "1.0.24"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "unicode-normalization"
|
|
||||||
version = "0.1.25"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
|
|
||||||
dependencies = [
|
|
||||||
"tinyvec",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "unicode-properties"
|
|
||||||
version = "0.1.4"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-width"
|
name = "unicode-width"
|
||||||
version = "0.2.2"
|
version = "0.2.2"
|
||||||
@@ -2167,7 +1706,6 @@ dependencies = [
|
|||||||
"idna",
|
"idna",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_derive",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2209,31 +1747,6 @@ dependencies = [
|
|||||||
"wit-bindgen",
|
"wit-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "wasite"
|
|
||||||
version = "0.1.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "webauthn-rs"
|
|
||||||
version = "0.3.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "90b266eccb4b32595876f5c73ea443b0516da0b1df72ca07bc08ed9ba7f96ec1"
|
|
||||||
dependencies = [
|
|
||||||
"base64 0.13.1",
|
|
||||||
"nom",
|
|
||||||
"openssl",
|
|
||||||
"rand 0.8.7",
|
|
||||||
"serde",
|
|
||||||
"serde_cbor",
|
|
||||||
"serde_derive",
|
|
||||||
"serde_json",
|
|
||||||
"thiserror 1.0.69",
|
|
||||||
"tracing",
|
|
||||||
"url",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "webpki-roots"
|
name = "webpki-roots"
|
||||||
version = "0.26.11"
|
version = "0.26.11"
|
||||||
@@ -2252,38 +1765,19 @@ dependencies = [
|
|||||||
"rustls-pki-types",
|
"rustls-pki-types",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "whoami"
|
|
||||||
version = "1.6.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d"
|
|
||||||
dependencies = [
|
|
||||||
"libredox",
|
|
||||||
"wasite",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows-link"
|
name = "windows-link"
|
||||||
version = "0.2.1"
|
version = "0.2.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows-sys"
|
|
||||||
version = "0.48.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
|
|
||||||
dependencies = [
|
|
||||||
"windows-targets 0.48.5",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows-sys"
|
name = "windows-sys"
|
||||||
version = "0.52.0"
|
version = "0.52.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
|
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"windows-targets 0.52.6",
|
"windows-targets",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2295,67 +1789,34 @@ dependencies = [
|
|||||||
"windows-link",
|
"windows-link",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows-targets"
|
|
||||||
version = "0.48.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
|
|
||||||
dependencies = [
|
|
||||||
"windows_aarch64_gnullvm 0.48.5",
|
|
||||||
"windows_aarch64_msvc 0.48.5",
|
|
||||||
"windows_i686_gnu 0.48.5",
|
|
||||||
"windows_i686_msvc 0.48.5",
|
|
||||||
"windows_x86_64_gnu 0.48.5",
|
|
||||||
"windows_x86_64_gnullvm 0.48.5",
|
|
||||||
"windows_x86_64_msvc 0.48.5",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows-targets"
|
name = "windows-targets"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
|
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"windows_aarch64_gnullvm 0.52.6",
|
"windows_aarch64_gnullvm",
|
||||||
"windows_aarch64_msvc 0.52.6",
|
"windows_aarch64_msvc",
|
||||||
"windows_i686_gnu 0.52.6",
|
"windows_i686_gnu",
|
||||||
"windows_i686_gnullvm",
|
"windows_i686_gnullvm",
|
||||||
"windows_i686_msvc 0.52.6",
|
"windows_i686_msvc",
|
||||||
"windows_x86_64_gnu 0.52.6",
|
"windows_x86_64_gnu",
|
||||||
"windows_x86_64_gnullvm 0.52.6",
|
"windows_x86_64_gnullvm",
|
||||||
"windows_x86_64_msvc 0.52.6",
|
"windows_x86_64_msvc",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_aarch64_gnullvm"
|
|
||||||
version = "0.48.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_aarch64_gnullvm"
|
name = "windows_aarch64_gnullvm"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_aarch64_msvc"
|
|
||||||
version = "0.48.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_aarch64_msvc"
|
name = "windows_aarch64_msvc"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_i686_gnu"
|
|
||||||
version = "0.48.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_i686_gnu"
|
name = "windows_i686_gnu"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
@@ -2368,48 +1829,24 @@ version = "0.52.6"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_i686_msvc"
|
|
||||||
version = "0.48.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_i686_msvc"
|
name = "windows_i686_msvc"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_x86_64_gnu"
|
|
||||||
version = "0.48.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_x86_64_gnu"
|
name = "windows_x86_64_gnu"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_x86_64_gnullvm"
|
|
||||||
version = "0.48.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_x86_64_gnullvm"
|
name = "windows_x86_64_gnullvm"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_x86_64_msvc"
|
|
||||||
version = "0.48.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows_x86_64_msvc"
|
name = "windows_x86_64_msvc"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
|
|||||||
+2
-11
@@ -1,13 +1,12 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "sustenance"
|
name = "sustenance"
|
||||||
version = "0.3.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
argon2 = "0.5"
|
argon2 = "0.5"
|
||||||
async-trait = "0.1"
|
async-trait = "0.1"
|
||||||
axum = { version = "0.8", features = ["ws"] }
|
axum = { version = "0.8", features = ["ws"] }
|
||||||
base64 = "0.22"
|
|
||||||
futures-util = "0.3"
|
futures-util = "0.3"
|
||||||
hex = "0.4"
|
hex = "0.4"
|
||||||
maud = "0.27"
|
maud = "0.27"
|
||||||
@@ -16,18 +15,10 @@ rand = "0.8"
|
|||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
sha2 = "0.10"
|
sha2 = "0.10"
|
||||||
sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "sqlite", "macros", "migrate", "tls-rustls"] }
|
sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "sqlite", "macros", "tls-rustls"] }
|
||||||
thiserror = "2"
|
thiserror = "2"
|
||||||
tokio = { version = "1", features = ["full"] }
|
tokio = { version = "1", features = ["full"] }
|
||||||
tower = "0.5"
|
tower = "0.5"
|
||||||
tower-http = { version = "0.6", features = ["fs", "trace", "set-header"] }
|
tower-http = { version = "0.6", features = ["fs", "trace", "set-header"] }
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
url = "2"
|
|
||||||
webauthn-rs = "0.3"
|
|
||||||
|
|
||||||
[profile.release]
|
|
||||||
opt-level = "z"
|
|
||||||
strip = true
|
|
||||||
lto = true
|
|
||||||
codegen-units = 1
|
|
||||||
|
|||||||
@@ -8,13 +8,7 @@ A small shared grocery list built with Rust, Axum, Maud, htmx, WebSockets, and S
|
|||||||
cargo run
|
cargo run
|
||||||
```
|
```
|
||||||
|
|
||||||
Open <http://localhost:3000>. The application creates `sustenance.db` in the
|
Open <http://127.0.0.1:3000>. The application creates `sustenance.db` in the working directory on first start.
|
||||||
working directory on first start.
|
|
||||||
|
|
||||||
**Note:** use `localhost` (not `127.0.0.1`) when testing passkeys locally —
|
|
||||||
browsers reject IP addresses as WebAuthn RP IDs. The app defaults to
|
|
||||||
`localhost` for loopback hosts, so passkeys work out of the box when you access
|
|
||||||
the site via `http://localhost:3000`.
|
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
@@ -26,9 +20,7 @@ the site via `http://localhost:3000`.
|
|||||||
| `COOKIE_SECURE` | `false` | Add the `Secure` attribute to session cookies |
|
| `COOKIE_SECURE` | `false` | Add the `Secure` attribute to session cookies |
|
||||||
| `REGISTRATION_MODE` | `invite_only` | Use `open` for local development; otherwise registration requires a valid list invitation after the first account |
|
| `REGISTRATION_MODE` | `invite_only` | Use `open` for local development; otherwise registration requires a valid list invitation after the first account |
|
||||||
| `SEED_CONFIG` | `seed.json` | Optional JSON file with a default user to create when the database is first initialized |
|
| `SEED_CONFIG` | `seed.json` | Optional JSON file with a default user to create when the database is first initialized |
|
||||||
| `RP_ID` | derived from `PUBLIC_BASE_URL` | WebAuthn relying party ID (the host users access the site from) |
|
| `RUST_LOG` | `sustenance=debug,tower_http=info` | Log filter |
|
||||||
| `RP_NAME` | `Sustenance` | WebAuthn relying party name shown to users |
|
|
||||||
| `RUST_LOG` | `sustenance=info,tower_http=info` | Log filter; HTTP requests are logged at info level |
|
|
||||||
|
|
||||||
### Seeding a default user
|
### Seeding a default user
|
||||||
|
|
||||||
@@ -49,7 +41,6 @@ The file is optional — if it is missing or invalid, seeding is silently skippe
|
|||||||
## Current features
|
## Current features
|
||||||
|
|
||||||
- Email/password accounts with Argon2 password hashes
|
- Email/password accounts with Argon2 password hashes
|
||||||
- Optional WebAuthn passkeys for passwordless sign-in (managed from the account page)
|
|
||||||
- Cookie-backed sessions and CSRF tokens for list mutations
|
- Cookie-backed sessions and CSRF tokens for list mutations
|
||||||
- Shared lists with one-time, seven-day invitation links
|
- Shared lists with one-time, seven-day invitation links
|
||||||
- Invite-only registration by default after the first account
|
- Invite-only registration by default after the first account
|
||||||
@@ -71,23 +62,3 @@ cargo fmt --all -- --check
|
|||||||
cargo check
|
cargo check
|
||||||
cargo test
|
cargo test
|
||||||
```
|
```
|
||||||
|
|
||||||
### End-to-end tests (Playwright)
|
|
||||||
|
|
||||||
The e2e tests live in `e2e/` and use Playwright with a real browser. Each test
|
|
||||||
starts its own server against a fresh, throwaway database on a unique port, so
|
|
||||||
tests are fully isolated from each other and from your real `sustenance.db`.
|
|
||||||
|
|
||||||
The tests launch `target/debug/sustenance`, so build the server first:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
# one-time setup
|
|
||||||
cargo build
|
|
||||||
cd e2e
|
|
||||||
npm install
|
|
||||||
npx playwright install chromium
|
|
||||||
|
|
||||||
# run the tests (each test launches its own server against a fresh DB)
|
|
||||||
cd e2e
|
|
||||||
npx playwright test
|
|
||||||
```
|
|
||||||
|
|||||||
@@ -1,91 +0,0 @@
|
|||||||
import * as fs from 'node:fs/promises';
|
|
||||||
import { basename } from 'node:path';
|
|
||||||
|
|
||||||
function getEnv(name) {
|
|
||||||
const val = process.env[name];
|
|
||||||
if (!val) {
|
|
||||||
throw new Error(`Environment variable ${name} is empty`);
|
|
||||||
}
|
|
||||||
return val;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchJSON(url, options) {
|
|
||||||
const resp = await fetch(url, options);
|
|
||||||
if (!resp.ok) {
|
|
||||||
throw new Error(`Unexpected HTTP status: ${resp.status}`, {
|
|
||||||
cause: {
|
|
||||||
status: resp.status,
|
|
||||||
body: await resp.text(),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return await resp.json();
|
|
||||||
}
|
|
||||||
|
|
||||||
async function postJSON(url, token, payload) {
|
|
||||||
return fetchJSON(url, {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Authorization": `token ${token}`,
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
body: JSON.stringify(payload),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function postFile(url, token, files) {
|
|
||||||
const formData = new FormData();
|
|
||||||
for (const [name, path] of Object.entries(files)) {
|
|
||||||
const fileBuffer = await fs.readFile(path);
|
|
||||||
const fileObject = new File([fileBuffer], basename(path), { type: 'application/octet-stream' });
|
|
||||||
formData.append(name, fileObject)
|
|
||||||
}
|
|
||||||
return await fetchJSON(url, {
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Authorization": `token ${token}`,
|
|
||||||
},
|
|
||||||
body: formData,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function canRead(path) {
|
|
||||||
try {
|
|
||||||
await fs.access(path, fs.constants.R_OK);
|
|
||||||
return true;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function main() {
|
|
||||||
const path = process.argv[2];
|
|
||||||
if (!path || !canRead(path)) {
|
|
||||||
throw Error(`Path ${path} is undefined or inaccessible, use node release.js <path>`);
|
|
||||||
}
|
|
||||||
const token = getEnv("GITEA_RELEASE_TOKEN");
|
|
||||||
const tag = getEnv("CI_COMMIT_TAG");
|
|
||||||
const repo = getEnv("CI_REPO");
|
|
||||||
|
|
||||||
console.log("Creating release...");
|
|
||||||
const releaseData = await postJSON(`https://git.sbstp.ca/api/v1/repos/${repo}/releases`, token, {
|
|
||||||
name: `Release ${tag}`,
|
|
||||||
tag_name: tag,
|
|
||||||
target_commitish: tag,
|
|
||||||
draft: false,
|
|
||||||
prerelease: false,
|
|
||||||
});
|
|
||||||
console.log(`Created release ID ${releaseData.id}`);
|
|
||||||
|
|
||||||
console.log("Uploading asset...");
|
|
||||||
const assetData = await postFile(`https://git.sbstp.ca/api/v1/repos/${repo}/releases/${releaseData.id}/assets?name=${basename(path)}`, token, {
|
|
||||||
attachment: path,
|
|
||||||
});
|
|
||||||
console.log("Asset uploaded:", assetData);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await main();
|
|
||||||
} catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
}
|
|
||||||
-126
@@ -1,126 +0,0 @@
|
|||||||
import { test as base, expect, Page } from "@playwright/test";
|
|
||||||
import { spawn, ChildProcess } from "child_process";
|
|
||||||
import * as fs from "fs";
|
|
||||||
import * as os from "os";
|
|
||||||
import * as path from "path";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Starts a fresh Sustenance server against a unique, throwaway database on a
|
|
||||||
* unique port for each test, and tears it down afterwards. This gives every
|
|
||||||
* test a clean DB with no shared state between tests.
|
|
||||||
*/
|
|
||||||
export const test = base.extend<{ server: { baseURL: string }; page: Page }>({
|
|
||||||
server: [
|
|
||||||
async ({}, use) => {
|
|
||||||
const server = await startServer();
|
|
||||||
await use({ baseURL: server.baseURL });
|
|
||||||
await killTree(server.child);
|
|
||||||
// Clean up the DB files (including -wal / -shm).
|
|
||||||
for (const suffix of ["", "-wal", "-shm"]) {
|
|
||||||
fs.rmSync(server.dbPath + suffix, { force: true });
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{ scope: "test", auto: true },
|
|
||||||
],
|
|
||||||
|
|
||||||
// Provide a page whose baseURL points at this test's server.
|
|
||||||
page: async ({ browser, server }, use) => {
|
|
||||||
const context = await browser.newContext({ baseURL: server.baseURL });
|
|
||||||
const page = await context.newPage();
|
|
||||||
await use(page);
|
|
||||||
await context.close();
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
/** Starts a server, retrying on a fresh port if the first attempt fails to bind. */
|
|
||||||
async function startServer() {
|
|
||||||
for (let attempt = 0; attempt < 5; attempt++) {
|
|
||||||
const dbPath = path.join(
|
|
||||||
os.tmpdir(),
|
|
||||||
`sustenance-e2e-${process.pid}-${Date.now()}-${Math.random()
|
|
||||||
.toString(36)
|
|
||||||
.slice(2)}.db`,
|
|
||||||
);
|
|
||||||
const port = 20000 + Math.floor(Math.random() * 30000);
|
|
||||||
const baseURL = `http://localhost:${port}`;
|
|
||||||
|
|
||||||
const child = spawn(
|
|
||||||
path.resolve(__dirname, "..", "target", "debug", "sustenance"),
|
|
||||||
[],
|
|
||||||
{
|
|
||||||
env: {
|
|
||||||
...process.env,
|
|
||||||
DATABASE_PATH: dbPath,
|
|
||||||
REGISTRATION_MODE: "open",
|
|
||||||
BIND_ADDRESS: `127.0.0.1:${port}`,
|
|
||||||
PUBLIC_BASE_URL: baseURL,
|
|
||||||
// WebAuthn requires a valid domain for the RP ID; localhost is allowed.
|
|
||||||
RP_ID: "localhost",
|
|
||||||
// Point SEED_CONFIG at a nonexistent file so no default user is created.
|
|
||||||
SEED_CONFIG: path.join(os.tmpdir(), "sustenance-e2e-no-seed.json"),
|
|
||||||
},
|
|
||||||
stdio: ["ignore", "ignore", "pipe"],
|
|
||||||
// Run in its own process group so we can kill the whole tree.
|
|
||||||
detached: true,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
let stderr = "";
|
|
||||||
child.stderr?.on("data", (chunk) => {
|
|
||||||
stderr += chunk.toString();
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
await waitForServer(baseURL, child);
|
|
||||||
return { baseURL, child, dbPath };
|
|
||||||
} catch (error) {
|
|
||||||
// The server may have failed to bind (port collision). Clean up and retry.
|
|
||||||
await killTree(child);
|
|
||||||
for (const suffix of ["", "-wal", "-shm"]) {
|
|
||||||
fs.rmSync(dbPath + suffix, { force: true });
|
|
||||||
}
|
|
||||||
if (attempt === 4) {
|
|
||||||
throw new Error(
|
|
||||||
`server failed to start after retries; last stderr:\n${stderr}\n${error}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw new Error("unreachable");
|
|
||||||
}
|
|
||||||
|
|
||||||
async function waitForServer(baseURL: string, child: ChildProcess) {
|
|
||||||
const deadline = Date.now() + 60_000;
|
|
||||||
while (Date.now() < deadline) {
|
|
||||||
if (child.exitCode !== null) {
|
|
||||||
throw new Error(`server exited early with code ${child.exitCode}`);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const res = await fetch(baseURL + "/login");
|
|
||||||
if (res.ok) return;
|
|
||||||
} catch {
|
|
||||||
// not up yet
|
|
||||||
}
|
|
||||||
await new Promise((r) => setTimeout(r, 200));
|
|
||||||
}
|
|
||||||
throw new Error("timed out waiting for server to start");
|
|
||||||
}
|
|
||||||
|
|
||||||
async function killTree(child: ChildProcess) {
|
|
||||||
try {
|
|
||||||
process.kill(-child.pid!, "SIGTERM");
|
|
||||||
} catch {
|
|
||||||
child.kill("SIGTERM");
|
|
||||||
}
|
|
||||||
// Give it a moment to shut down gracefully, then force-kill if needed.
|
|
||||||
const exited = new Promise((resolve) => child.once("exit", resolve));
|
|
||||||
const timeout = new Promise((resolve) => setTimeout(resolve, 5000));
|
|
||||||
await Promise.race([exited, timeout]);
|
|
||||||
try {
|
|
||||||
process.kill(-child.pid!, "SIGKILL");
|
|
||||||
} catch {
|
|
||||||
/* already gone */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export { expect };
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
import { Page, expect } from "@playwright/test";
|
|
||||||
|
|
||||||
/** Registers a fresh account and lands on the lists page. */
|
|
||||||
export async function registerAndLogin(page: Page, email: string) {
|
|
||||||
await page.goto("/register");
|
|
||||||
await page.fill("#display-name", "Test User");
|
|
||||||
await page.fill("#email", email);
|
|
||||||
await page.fill("#password", "a-strong-password");
|
|
||||||
await page.click('button[type="submit"]');
|
|
||||||
await expect(page).toHaveURL(/\/lists/);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Creates a meal with the given name and markdown description. */
|
|
||||||
export async function createMeal(
|
|
||||||
page: Page,
|
|
||||||
name: string,
|
|
||||||
description: string,
|
|
||||||
category?: string,
|
|
||||||
) {
|
|
||||||
await page.goto("/meals/new");
|
|
||||||
await page.fill("#meal-name", name);
|
|
||||||
if (category) {
|
|
||||||
await page.selectOption("#meal-category", { label: category });
|
|
||||||
}
|
|
||||||
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 ?? "");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Generated
-90
@@ -1,90 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "sustenance-e2e",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"lockfileVersion": 3,
|
|
||||||
"requires": true,
|
|
||||||
"packages": {
|
|
||||||
"": {
|
|
||||||
"name": "sustenance-e2e",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"devDependencies": {
|
|
||||||
"@playwright/test": "^1.45.0",
|
|
||||||
"@types/node": "^26.1.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@playwright/test": {
|
|
||||||
"version": "1.62.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.62.1.tgz",
|
|
||||||
"integrity": "sha512-DTcUc8qii+cpHvtOwggMtBRMjKZHXYWdw8syRYu2vtzuq4Wxphqq4NfCs5Zt44L6mA8rfDfj+PHnxFc/FeK6mQ==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"playwright": "1.62.1"
|
|
||||||
},
|
|
||||||
"bin": {
|
|
||||||
"playwright": "cli.js"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@types/node": {
|
|
||||||
"version": "26.1.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.2.tgz",
|
|
||||||
"integrity": "sha512-Vu4a5UFA9rIIFJ7rB/Vaafh9lrCQszopTCx6KjFboXTGQbPNasehVR5TEiithSDGyd1DEiUByggTZsg8jukeIg==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"undici-types": "~8.3.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/fsevents": {
|
|
||||||
"version": "2.3.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
|
||||||
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
|
||||||
"dev": true,
|
|
||||||
"hasInstallScript": true,
|
|
||||||
"optional": true,
|
|
||||||
"os": [
|
|
||||||
"darwin"
|
|
||||||
],
|
|
||||||
"engines": {
|
|
||||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/playwright": {
|
|
||||||
"version": "1.62.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz",
|
|
||||||
"integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==",
|
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
|
||||||
"playwright-core": "1.62.1"
|
|
||||||
},
|
|
||||||
"bin": {
|
|
||||||
"playwright": "cli.js"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20"
|
|
||||||
},
|
|
||||||
"optionalDependencies": {
|
|
||||||
"fsevents": "2.3.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/playwright-core": {
|
|
||||||
"version": "1.62.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz",
|
|
||||||
"integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==",
|
|
||||||
"dev": true,
|
|
||||||
"bin": {
|
|
||||||
"playwright-core": "cli.js"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">=20"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/undici-types": {
|
|
||||||
"version": "8.3.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
|
|
||||||
"integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
|
|
||||||
"dev": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "sustenance-e2e",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"private": true,
|
|
||||||
"scripts": {
|
|
||||||
"test": "playwright test",
|
|
||||||
"test:headed": "playwright test --headed"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@playwright/test": "^1.45.0",
|
|
||||||
"@types/node": "^26.1.2"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
import { defineConfig } from "@playwright/test";
|
|
||||||
|
|
||||||
export default defineConfig({
|
|
||||||
testDir: "./tests",
|
|
||||||
timeout: 30_000,
|
|
||||||
retries: 2,
|
|
||||||
use: {
|
|
||||||
trace: "on-first-retry",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
import { expect } from "@playwright/test";
|
|
||||||
import { test } from "../fixtures";
|
|
||||||
import { registerAndLogin, createList, createMealWithIngredients } from "../helpers";
|
|
||||||
|
|
||||||
test("a user can add a meal's ingredients to a list via the picker", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createMealWithIngredients(page, "Spaghetti Bolognese", [
|
|
||||||
{ name: "Penne", quantity: "500g" },
|
|
||||||
{ name: "Tomato", quantity: "2" },
|
|
||||||
]);
|
|
||||||
await createList(page, "Weekly shop");
|
|
||||||
|
|
||||||
// Open the add-meal picker.
|
|
||||||
await page.click(".add-meal-button");
|
|
||||||
const picker = page.locator(".meal-picker-backdrop");
|
|
||||||
await expect(picker).toBeVisible();
|
|
||||||
await expect(picker.locator(".meal-picker-button").filter({ hasText: "Spaghetti Bolognese" })).toBeVisible();
|
|
||||||
|
|
||||||
// Select the meal.
|
|
||||||
await picker.locator(".meal-picker-button").filter({ hasText: "Spaghetti Bolognese" }).click();
|
|
||||||
|
|
||||||
// The picker closes and the meal's ingredients appear as items.
|
|
||||||
await expect(picker).toHaveCount(0);
|
|
||||||
await expect(page.locator(".item-row").filter({ hasText: "Penne" })).toBeVisible();
|
|
||||||
await expect(page.locator(".item-row").filter({ hasText: "Tomato" })).toBeVisible();
|
|
||||||
await expect(page.locator(".item-row").filter({ hasText: "Penne" }).locator(".item-qty")).toHaveText("(500g)");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the add-meal picker closes via the close button", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createMealWithIngredients(page, "Spaghetti Bolognese", [{ name: "Penne" }]);
|
|
||||||
await createList(page, "Weekly shop");
|
|
||||||
|
|
||||||
await page.click(".add-meal-button");
|
|
||||||
const picker = page.locator(".meal-picker-backdrop");
|
|
||||||
await expect(picker).toBeVisible();
|
|
||||||
|
|
||||||
await picker.locator(".meal-picker-close").click();
|
|
||||||
await expect(picker).toHaveCount(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the add-meal picker closes when clicking outside", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createMealWithIngredients(page, "Spaghetti Bolognese", [{ name: "Penne" }]);
|
|
||||||
await createList(page, "Weekly shop");
|
|
||||||
|
|
||||||
await page.click(".add-meal-button");
|
|
||||||
const picker = page.locator(".meal-picker-backdrop");
|
|
||||||
await expect(picker).toBeVisible();
|
|
||||||
|
|
||||||
// Click the backdrop itself (outside the modal card), at the viewport corner.
|
|
||||||
await page.mouse.click(10, 10);
|
|
||||||
await expect(picker).toHaveCount(0);
|
|
||||||
});
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
import { expect } from "@playwright/test";
|
|
||||||
import { test } from "../fixtures";
|
|
||||||
import { registerAndLogin } from "../helpers";
|
|
||||||
|
|
||||||
test("a user can register and log in", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await expect(page.locator("h1")).toContainText("Grocery lists");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a user can log out", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await page.click('button:has-text("Sign out")');
|
|
||||||
await expect(page).toHaveURL(/\/login/);
|
|
||||||
await expect(page.locator("h1")).toContainText("Welcome back");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a user can change their password", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await page.goto("/account");
|
|
||||||
await page.fill("#new-password", "a-new-strong-password");
|
|
||||||
await page.fill("#confirm-password", "a-new-strong-password");
|
|
||||||
await page.click('button:has-text("Update password")');
|
|
||||||
await expect(page.locator(".alert-success")).toContainText("updated");
|
|
||||||
|
|
||||||
// The old password no longer works; the new one does.
|
|
||||||
await page.click('button:has-text("Sign out")');
|
|
||||||
await page.fill("#email", "alice@example.com");
|
|
||||||
await page.fill("#password", "a-strong-password");
|
|
||||||
await page.click('button[type="submit"]');
|
|
||||||
await expect(page.locator(".alert-error")).toContainText("incorrect");
|
|
||||||
|
|
||||||
await page.fill("#email", "alice@example.com");
|
|
||||||
await page.fill("#password", "a-new-strong-password");
|
|
||||||
await page.click('button[type="submit"]');
|
|
||||||
await expect(page).toHaveURL(/\/lists/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("changing password rejects a mismatched confirmation", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await page.goto("/account");
|
|
||||||
await page.fill("#new-password", "a-new-strong-password");
|
|
||||||
await page.fill("#confirm-password", "a-different-password");
|
|
||||||
await page.click('button:has-text("Update password")');
|
|
||||||
await expect(page.locator(".alert-error")).toContainText("do not match");
|
|
||||||
});
|
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
import { expect } from "@playwright/test";
|
|
||||||
import { test } from "../fixtures";
|
|
||||||
import { registerAndLogin, createList, addItem } from "../helpers";
|
|
||||||
|
|
||||||
test("a user can create a list", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
|
|
||||||
await createList(page, "Weekly shop");
|
|
||||||
|
|
||||||
await expect(page.locator("h1")).toContainText("Weekly shop");
|
|
||||||
await expect(page.locator(".empty-items")).toBeVisible();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a user can add an item with a quantity", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createList(page, "Weekly shop");
|
|
||||||
|
|
||||||
await addItem(page, "Apple", "2");
|
|
||||||
|
|
||||||
// Quantity renders in parens to the left of the name.
|
|
||||||
const row = page.locator(".item-row").filter({ hasText: "Apple" });
|
|
||||||
await expect(row.locator(".item-qty")).toHaveText("(2)");
|
|
||||||
await expect(row.locator("strong")).toHaveText("Apple");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a user can check off an item", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createList(page, "Weekly shop");
|
|
||||||
await addItem(page, "Apple");
|
|
||||||
|
|
||||||
const row = page.locator(".item-row").filter({ hasText: "Apple" });
|
|
||||||
await row.locator(".check-button").click();
|
|
||||||
|
|
||||||
await expect(row).toHaveClass(/is-checked/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("clicking an item's text toggles the checkbox", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createList(page, "Weekly shop");
|
|
||||||
await addItem(page, "Apple");
|
|
||||||
|
|
||||||
const row = page.locator(".item-row").filter({ hasText: "Apple" });
|
|
||||||
await row.locator(".item-copy").click();
|
|
||||||
|
|
||||||
await expect(row).toHaveClass(/is-checked/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a user can edit an item via the actions modal", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createList(page, "Weekly shop");
|
|
||||||
await addItem(page, "Apple", "2");
|
|
||||||
|
|
||||||
const row = page.locator(".item-row").filter({ hasText: "Apple" });
|
|
||||||
await row.locator(".item-actions-button").click();
|
|
||||||
|
|
||||||
const dialog = row.locator("dialog.item-modal");
|
|
||||||
await expect(dialog).toBeVisible();
|
|
||||||
await dialog.locator('[id^="item-edit-name"]').fill("Banana");
|
|
||||||
await dialog.locator('[id^="item-edit-quantity"]').fill("6");
|
|
||||||
await dialog.locator('[id^="item-edit-save"]').click();
|
|
||||||
|
|
||||||
const updated = page.locator(".item-row").filter({ hasText: "Banana" });
|
|
||||||
await expect(updated).toBeVisible();
|
|
||||||
await expect(updated.locator(".item-qty")).toHaveText("(6)");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a user can delete an item via the actions modal", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createList(page, "Weekly shop");
|
|
||||||
await addItem(page, "Apple");
|
|
||||||
|
|
||||||
const row = page.locator(".item-row").filter({ hasText: "Apple" });
|
|
||||||
await row.locator(".item-actions-button").click();
|
|
||||||
|
|
||||||
const dialog = row.locator("dialog.item-modal");
|
|
||||||
await expect(dialog).toBeVisible();
|
|
||||||
await dialog.locator('[id^="item-edit-delete"]').click();
|
|
||||||
|
|
||||||
await expect(page.locator(".item-row").filter({ hasText: "Apple" })).toHaveCount(0);
|
|
||||||
await expect(page.locator(".empty-items")).toBeVisible();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a user can add a category", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createList(page, "Weekly shop");
|
|
||||||
|
|
||||||
await page.fill("#category-name", "Bakery");
|
|
||||||
await page.click("#add-category-button");
|
|
||||||
|
|
||||||
await expect(page.locator(".category-chip").filter({ hasText: "Bakery" })).toBeVisible();
|
|
||||||
});
|
|
||||||
@@ -1,111 +0,0 @@
|
|||||||
import { expect } from "@playwright/test";
|
|
||||||
import { test } from "../fixtures";
|
|
||||||
import { registerAndLogin, createMeal } from "../helpers";
|
|
||||||
|
|
||||||
test("meals are grouped under their category on the meals page", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
|
|
||||||
await createMeal(page, "Beef Stew", "", "Beef");
|
|
||||||
await createMeal(page, "Chicken Curry", "", "Chicken");
|
|
||||||
await createMeal(page, "Plain Rice", "");
|
|
||||||
|
|
||||||
await page.goto("/meals");
|
|
||||||
|
|
||||||
// Each category appears as a heading with its meals beneath it.
|
|
||||||
const beef = page.locator(".category-group").filter({ hasText: "Beef" });
|
|
||||||
await expect(beef.locator(".category-heading")).toContainText("Beef");
|
|
||||||
await expect(beef.locator(".list-card").filter({ hasText: "Beef Stew" })).toBeVisible();
|
|
||||||
|
|
||||||
const chicken = page.locator(".category-group").filter({ hasText: "Chicken" });
|
|
||||||
await expect(chicken.locator(".list-card").filter({ hasText: "Chicken Curry" })).toBeVisible();
|
|
||||||
|
|
||||||
// Uncategorized meals land in their own group.
|
|
||||||
const uncategorized = page.locator(".category-group").filter({ hasText: "Uncategorized" });
|
|
||||||
await expect(uncategorized.locator(".list-card").filter({ hasText: "Plain Rice" })).toBeVisible();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a user can create a meal category", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
|
|
||||||
await page.goto("/meals");
|
|
||||||
await page.fill('form[action="/meals/categories"] input[name="name"]', "Breakfast");
|
|
||||||
await page.click('form[action="/meals/categories"] button[type="submit"]');
|
|
||||||
|
|
||||||
await expect(page).toHaveURL(/\/meals$/);
|
|
||||||
await expect(page.locator(".meal-category-name").filter({ hasText: "Breakfast" })).toBeVisible();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a user can delete a meal category and its meals become uncategorized", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
|
|
||||||
// Create a custom category and a meal in it.
|
|
||||||
await page.goto("/meals");
|
|
||||||
await page.fill('form[action="/meals/categories"] input[name="name"]', "Breakfast");
|
|
||||||
await page.click('form[action="/meals/categories"] button[type="submit"]');
|
|
||||||
await expect(page).toHaveURL(/\/meals$/);
|
|
||||||
|
|
||||||
await createMeal(page, "Pancakes", "", "Breakfast");
|
|
||||||
|
|
||||||
// Delete the category.
|
|
||||||
await page.goto("/meals");
|
|
||||||
const row = page.locator(".meal-category-row").filter({ hasText: "Breakfast" });
|
|
||||||
await row.locator(".meal-category-delete").click();
|
|
||||||
await expect(page).toHaveURL(/\/meals$/);
|
|
||||||
|
|
||||||
// The category is gone and the meal is now uncategorized.
|
|
||||||
await expect(page.locator(".meal-category-name").filter({ hasText: "Breakfast" })).toHaveCount(0);
|
|
||||||
const uncategorized = page.locator(".category-group").filter({ hasText: "Uncategorized" });
|
|
||||||
await expect(uncategorized.locator(".list-card").filter({ hasText: "Pancakes" })).toBeVisible();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a user can change a meal's category via the edit modal", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createMeal(page, "Beef Stew", "", "Beef");
|
|
||||||
|
|
||||||
await page.click('button:has-text("Edit")');
|
|
||||||
const dialog = page.locator("dialog#meal-edit-modal");
|
|
||||||
await expect(dialog).toBeVisible();
|
|
||||||
await dialog.locator("#meal-edit-category").selectOption({ label: "Chicken" });
|
|
||||||
await dialog.locator("#meal-edit-save").click();
|
|
||||||
|
|
||||||
await expect(page).toHaveURL(/\/meals\/\d+/);
|
|
||||||
await page.goto("/meals");
|
|
||||||
|
|
||||||
const chicken = page.locator(".category-group").filter({
|
|
||||||
has: page.locator(".category-heading", { hasText: "Chicken" }),
|
|
||||||
});
|
|
||||||
await expect(chicken.locator(".list-card").filter({ hasText: "Beef Stew" })).toBeVisible();
|
|
||||||
const beef = page.locator(".category-group").filter({
|
|
||||||
has: page.locator(".category-heading", { hasText: "Beef" }),
|
|
||||||
});
|
|
||||||
await expect(beef.locator(".list-card").filter({ hasText: "Beef Stew" })).toHaveCount(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a meal's category is shown on its page", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createMeal(page, "Beef Stew", "", "Beef");
|
|
||||||
|
|
||||||
await expect(page.locator(".meal-category-label")).toHaveText("(Beef)");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("the add-meal picker groups meals by category", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createMeal(page, "Beef Stew", "", "Beef");
|
|
||||||
await createMeal(page, "Chicken Curry", "", "Chicken");
|
|
||||||
|
|
||||||
// Go to a list to open the picker.
|
|
||||||
await page.goto("/lists");
|
|
||||||
await page.fill("#list-name", "Weekly shop");
|
|
||||||
await page.click('button:has-text("Create list")');
|
|
||||||
await expect(page).toHaveURL(/\/lists\/\d+/);
|
|
||||||
|
|
||||||
await page.click(".add-meal-button");
|
|
||||||
const picker = page.locator(".meal-picker-backdrop");
|
|
||||||
await expect(picker).toBeVisible();
|
|
||||||
|
|
||||||
const beef = picker.locator(".category-group").filter({ hasText: "Beef" });
|
|
||||||
await expect(beef.locator(".meal-picker-button").filter({ hasText: "Beef Stew" })).toBeVisible();
|
|
||||||
|
|
||||||
const chicken = picker.locator(".category-group").filter({ hasText: "Chicken" });
|
|
||||||
await expect(chicken.locator(".meal-picker-button").filter({ hasText: "Chicken Curry" })).toBeVisible();
|
|
||||||
});
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
import { expect } from "@playwright/test";
|
|
||||||
import { test } from "../fixtures";
|
|
||||||
import { registerAndLogin, createMeal, addIngredient } from "../helpers";
|
|
||||||
|
|
||||||
test("a user can add an ingredient to a meal", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createMeal(page, "Spaghetti Bolognese", "");
|
|
||||||
|
|
||||||
await addIngredient(page, "Penne", "500g");
|
|
||||||
|
|
||||||
const row = page.locator(".ingredient-list").filter({ hasText: "Penne" });
|
|
||||||
await expect(row.locator(".item-qty")).toHaveText("(500g)");
|
|
||||||
await expect(row.locator("strong")).toHaveText("Penne");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a user can edit a meal name and description via the modal", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createMeal(page, "Spaghetti Bolognese", "A classic.");
|
|
||||||
|
|
||||||
await page.click('button:has-text("Edit")');
|
|
||||||
const dialog = page.locator("dialog#meal-edit-modal");
|
|
||||||
await expect(dialog).toBeVisible();
|
|
||||||
await dialog.locator("#meal-edit-name").fill("Pasta al Pomodoro");
|
|
||||||
await dialog.locator("#meal-edit-description").fill("## Ingredients\n\nA simple tomato sauce.");
|
|
||||||
await dialog.locator("#meal-edit-save").click();
|
|
||||||
|
|
||||||
await expect(page.locator("h1")).toContainText("Pasta al Pomodoro");
|
|
||||||
await expect(page.locator(".markdown h2")).toContainText("Ingredients");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a user can delete a meal", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createMeal(page, "Spaghetti Bolognese", "");
|
|
||||||
|
|
||||||
await page.click('button:has-text("Delete")');
|
|
||||||
await expect(page).toHaveURL(/\/meals$/);
|
|
||||||
await expect(page.locator(".list-card").filter({ hasText: "Spaghetti Bolognese" })).toHaveCount(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a user can edit an ingredient via the actions modal", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createMeal(page, "Spaghetti Bolognese", "");
|
|
||||||
await addIngredient(page, "Penne", "500g");
|
|
||||||
|
|
||||||
const row = page.locator(".ingredient-list").filter({ hasText: "Penne" });
|
|
||||||
await row.locator(".item-actions-button").click();
|
|
||||||
|
|
||||||
const dialog = row.locator("dialog.item-modal");
|
|
||||||
await expect(dialog).toBeVisible();
|
|
||||||
await dialog.locator('[id^="ingredient-edit-name"]').fill("Rigatoni");
|
|
||||||
await dialog.locator('[id^="ingredient-edit-quantity"]').fill("400g");
|
|
||||||
await dialog.locator('[id^="ingredient-edit-save"]').click();
|
|
||||||
|
|
||||||
const updated = page.locator(".ingredient-list").filter({ hasText: "Rigatoni" });
|
|
||||||
await expect(updated).toBeVisible();
|
|
||||||
await expect(updated.locator(".item-qty")).toHaveText("(400g)");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("a user can delete an ingredient via the actions modal", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createMeal(page, "Spaghetti Bolognese", "");
|
|
||||||
await addIngredient(page, "Penne");
|
|
||||||
|
|
||||||
const row = page.locator(".ingredient-list").filter({ hasText: "Penne" });
|
|
||||||
await row.locator(".item-actions-button").click();
|
|
||||||
|
|
||||||
const dialog = row.locator("dialog.item-modal");
|
|
||||||
await expect(dialog).toBeVisible();
|
|
||||||
await dialog.locator('[id^="ingredient-edit-delete"]').click();
|
|
||||||
|
|
||||||
await expect(page.locator(".ingredient-list").filter({ hasText: "Penne" })).toHaveCount(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("ingredients are grouped under their categories", async ({ page }) => {
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createMeal(page, "Spaghetti Bolognese", "");
|
|
||||||
|
|
||||||
// Add an ingredient in the default "Produce" category.
|
|
||||||
await page.fill("#ingredient-name", "Tomato");
|
|
||||||
await page.selectOption("#ingredient-category", { label: "Produce" });
|
|
||||||
await page.click("#add-ingredient-button");
|
|
||||||
|
|
||||||
// Add one without a category.
|
|
||||||
await addIngredient(page, "Penne");
|
|
||||||
|
|
||||||
await expect(page.locator(".category-heading").filter({ hasText: "Produce" })).toBeVisible();
|
|
||||||
await expect(page.locator(".category-heading").filter({ hasText: "Uncategorized" })).toBeVisible();
|
|
||||||
});
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
import { expect } from "@playwright/test";
|
|
||||||
import { test } from "../fixtures";
|
|
||||||
import { registerAndLogin } from "../helpers";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Enables a virtual WebAuthn authenticator on the given context so the browser
|
|
||||||
* can complete passkey ceremonies without a real device.
|
|
||||||
*/
|
|
||||||
async function enableVirtualAuthenticator(context: any) {
|
|
||||||
const cdp = await context.newCDPSession(context.pages()[0]);
|
|
||||||
await cdp.send("WebAuthn.enable", { enableUI: false });
|
|
||||||
await cdp.send("WebAuthn.addVirtualAuthenticator", {
|
|
||||||
options: {
|
|
||||||
protocol: "ctap2",
|
|
||||||
transport: "internal",
|
|
||||||
hasResidentKey: true,
|
|
||||||
hasUserVerification: true,
|
|
||||||
isUserVerified: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
test("a user can register a passkey and sign in with it", async ({ page, browser, server }) => {
|
|
||||||
const context = await browser.newContext({ baseURL: server.baseURL });
|
|
||||||
const p = await context.newPage();
|
|
||||||
|
|
||||||
await enableVirtualAuthenticator(context);
|
|
||||||
|
|
||||||
// Register with a password first.
|
|
||||||
await registerAndLogin(p, "alice@example.com");
|
|
||||||
|
|
||||||
// Add a passkey from the account page.
|
|
||||||
await p.goto("/account");
|
|
||||||
await p.click("#add-passkey");
|
|
||||||
await expect(p.locator(".passkey-row")).toHaveCount(1);
|
|
||||||
|
|
||||||
// Log out.
|
|
||||||
await p.click('button:has-text("Sign out")');
|
|
||||||
await expect(p).toHaveURL(/\/login/);
|
|
||||||
|
|
||||||
// Sign in with the passkey without entering an email (userless sign-in).
|
|
||||||
await p.click("#passkey-login");
|
|
||||||
await expect(p).toHaveURL(/\/lists/);
|
|
||||||
|
|
||||||
await context.close();
|
|
||||||
});
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import { expect } from "@playwright/test";
|
|
||||||
import { test } from "../fixtures";
|
|
||||||
import { registerAndLogin, createList, addItem } from "../helpers";
|
|
||||||
|
|
||||||
test("a list updates live for another user via websocket", async ({ page, browser, server }) => {
|
|
||||||
// User A registers and creates a list.
|
|
||||||
await registerAndLogin(page, "alice@example.com");
|
|
||||||
await createList(page, "Weekly shop");
|
|
||||||
const listUrl = page.url();
|
|
||||||
|
|
||||||
// User B registers in a separate context (separate session).
|
|
||||||
const contextB = await browser.newContext({ baseURL: server.baseURL });
|
|
||||||
const pageB = await contextB.newPage();
|
|
||||||
await registerAndLogin(pageB, "bob@example.com");
|
|
||||||
|
|
||||||
// Both users open the same list.
|
|
||||||
await page.goto(listUrl);
|
|
||||||
await pageB.goto(listUrl);
|
|
||||||
|
|
||||||
// Give the websocket connections a moment to establish.
|
|
||||||
await page.waitForTimeout(500);
|
|
||||||
|
|
||||||
// User A adds an item.
|
|
||||||
await addItem(page, "Apple", "2");
|
|
||||||
|
|
||||||
// It should appear on User B's page without any reload.
|
|
||||||
await expect(pageB.locator(".item-row").filter({ hasText: "Apple" })).toBeVisible();
|
|
||||||
await expect(pageB.locator(".item-row").filter({ hasText: "Apple" }).locator(".item-qty")).toHaveText("(2)");
|
|
||||||
|
|
||||||
await contextB.close();
|
|
||||||
});
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
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);
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
CREATE TABLE meal_categories (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
|
||||||
position INTEGER NOT NULL DEFAULT 0,
|
|
||||||
created_at INTEGER NOT NULL
|
|
||||||
);
|
|
||||||
|
|
||||||
ALTER TABLE meals ADD COLUMN category_id INTEGER REFERENCES meal_categories(id) ON DELETE SET NULL;
|
|
||||||
|
|
||||||
CREATE INDEX meals_category_idx ON meals(category_id);
|
|
||||||
@@ -19,19 +19,6 @@ pub struct User {
|
|||||||
pub id: i64,
|
pub id: i64,
|
||||||
pub email: String,
|
pub email: String,
|
||||||
pub display_name: 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)]
|
#[derive(Clone, Debug)]
|
||||||
@@ -65,18 +52,11 @@ pub struct Category {
|
|||||||
pub name: String,
|
pub name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct MealCategory {
|
|
||||||
pub id: i64,
|
|
||||||
pub name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct Meal {
|
pub struct Meal {
|
||||||
pub id: i64,
|
pub id: i64,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub description: String,
|
pub description: String,
|
||||||
pub category_id: Option<i64>,
|
|
||||||
pub ingredients: Vec<MealIngredient>,
|
pub ingredients: Vec<MealIngredient>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+26
-281
@@ -5,7 +5,7 @@ use std::time::Duration;
|
|||||||
use axum::{
|
use axum::{
|
||||||
Router,
|
Router,
|
||||||
extract::{
|
extract::{
|
||||||
Form, FromRequest, FromRequestParts, Json, Path, Query, Request, State,
|
Form, FromRequest, FromRequestParts, Path, Query, Request, State,
|
||||||
ws::{Message, WebSocket, WebSocketUpgrade},
|
ws::{Message, WebSocket, WebSocketUpgrade},
|
||||||
},
|
},
|
||||||
http::{HeaderMap, HeaderValue, StatusCode, header, request::Parts},
|
http::{HeaderMap, HeaderValue, StatusCode, header, request::Parts},
|
||||||
@@ -16,21 +16,17 @@ use axum::{
|
|||||||
use futures_util::{SinkExt, StreamExt};
|
use futures_util::{SinkExt, StreamExt};
|
||||||
use serde::{Deserialize, de::DeserializeOwned};
|
use serde::{Deserialize, de::DeserializeOwned};
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
use tower_http::trace::{DefaultMakeSpan, DefaultOnResponse, TraceLayer};
|
use tower_http::{
|
||||||
use tracing::{Level, error, warn};
|
services::ServeDir,
|
||||||
|
set_header::SetResponseHeaderLayer,
|
||||||
|
trace::TraceLayer,
|
||||||
|
};
|
||||||
|
use tracing::{error, warn};
|
||||||
|
|
||||||
use crate::domain::{DomainError, SessionUser};
|
use crate::domain::{DomainError, SessionUser};
|
||||||
use crate::ports::{HubEvent, RealtimeNotifier};
|
use crate::ports::{HubEvent, RealtimeNotifier};
|
||||||
use crate::services::{AuthService, InvitationService, ListService, MealService};
|
use crate::services::{AuthService, InvitationService, ListService, MealService};
|
||||||
use crate::views;
|
use crate::views;
|
||||||
use crate::webauthn::WebAuthnService;
|
|
||||||
|
|
||||||
/// The contents of `static/`, embedded into the binary at compile time so the
|
|
||||||
/// app can be shipped as a single executable without a separate static directory.
|
|
||||||
const STYLE_CSS: &[u8] = include_bytes!("../static/style.css");
|
|
||||||
const PASSKEY_LOGIN_JS: &[u8] = include_bytes!("../static/passkey-login.js");
|
|
||||||
const PASSKEY_REGISTER_JS: &[u8] = include_bytes!("../static/passkey-register.js");
|
|
||||||
const PASSWORD_TOGGLE_JS: &[u8] = include_bytes!("../static/password-toggle.js");
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
@@ -38,7 +34,6 @@ pub struct AppState {
|
|||||||
pub lists: Arc<ListService>,
|
pub lists: Arc<ListService>,
|
||||||
pub meals: Arc<MealService>,
|
pub meals: Arc<MealService>,
|
||||||
pub invitations: Arc<InvitationService>,
|
pub invitations: Arc<InvitationService>,
|
||||||
pub webauthn: Arc<WebAuthnService>,
|
|
||||||
pub realtime: Arc<dyn RealtimeNotifier>,
|
pub realtime: Arc<dyn RealtimeNotifier>,
|
||||||
pub cookie_secure: bool,
|
pub cookie_secure: bool,
|
||||||
pub public_base_url: String,
|
pub public_base_url: String,
|
||||||
@@ -57,13 +52,10 @@ pub enum AppError {
|
|||||||
impl IntoResponse for AppError {
|
impl IntoResponse for AppError {
|
||||||
fn into_response(self) -> Response {
|
fn into_response(self) -> Response {
|
||||||
match self {
|
match self {
|
||||||
AppError::Database(error) => {
|
AppError::Database(_) => status_html_response(
|
||||||
error!(%error, "request failed");
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
status_html_response(
|
views::error_page("500", "Something went wrong."),
|
||||||
StatusCode::INTERNAL_SERVER_ERROR,
|
),
|
||||||
views::error_page("500", "Something went wrong."),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
AppError::BadRequest(message) => {
|
AppError::BadRequest(message) => {
|
||||||
status_html_response(StatusCode::BAD_REQUEST, views::error_page("400", &message))
|
status_html_response(StatusCode::BAD_REQUEST, views::error_page("400", &message))
|
||||||
}
|
}
|
||||||
@@ -81,19 +73,6 @@ pub fn build_router(state: AppState) -> Router {
|
|||||||
.route("/login", get(login_page).post(login))
|
.route("/login", get(login_page).post(login))
|
||||||
.route("/register", get(register_page).post(register))
|
.route("/register", get(register_page).post(register))
|
||||||
.route("/logout", post(logout))
|
.route("/logout", post(logout))
|
||||||
.route("/account", get(account_page))
|
|
||||||
.route("/auth/passkey/register/start", post(passkey_register_start))
|
|
||||||
.route(
|
|
||||||
"/auth/passkey/register/finish",
|
|
||||||
post(passkey_register_finish),
|
|
||||||
)
|
|
||||||
.route("/auth/passkey/login/start", post(passkey_login_start))
|
|
||||||
.route("/auth/passkey/login/finish", post(passkey_login_finish))
|
|
||||||
.route(
|
|
||||||
"/account/passkeys/{passkey_id}/delete",
|
|
||||||
post(delete_passkey),
|
|
||||||
)
|
|
||||||
.route("/account/password", post(change_password))
|
|
||||||
.route("/lists", get(lists_page).post(create_list))
|
.route("/lists", get(lists_page).post(create_list))
|
||||||
.route("/lists/{list_id}", get(list_page))
|
.route("/lists/{list_id}", get(list_page))
|
||||||
.route("/lists/{list_id}/items", post(add_item))
|
.route("/lists/{list_id}/items", post(add_item))
|
||||||
@@ -104,33 +83,26 @@ pub fn build_router(state: AppState) -> Router {
|
|||||||
.route("/invitations", post(create_invitation))
|
.route("/invitations", post(create_invitation))
|
||||||
.route("/meals", get(meals_page).post(create_meal))
|
.route("/meals", get(meals_page).post(create_meal))
|
||||||
.route("/meals/new", get(new_meal_page))
|
.route("/meals/new", get(new_meal_page))
|
||||||
.route("/meals/categories", post(create_meal_category))
|
|
||||||
.route(
|
|
||||||
"/meals/categories/{category_id}/delete",
|
|
||||||
post(delete_meal_category),
|
|
||||||
)
|
|
||||||
.route("/meals/{meal_id}", get(meal_page))
|
.route("/meals/{meal_id}", get(meal_page))
|
||||||
.route("/meals/{meal_id}/edit", post(edit_meal))
|
.route("/meals/{meal_id}/edit", post(edit_meal))
|
||||||
.route("/meals/{meal_id}/delete", post(delete_meal))
|
.route("/meals/{meal_id}/delete", post(delete_meal))
|
||||||
.route("/meals/{meal_id}/ingredients", post(add_ingredient))
|
.route("/meals/{meal_id}/ingredients", post(add_ingredient))
|
||||||
.route(
|
.route("/meals/{meal_id}/ingredients/{ingredient_id}/edit", post(edit_ingredient))
|
||||||
"/meals/{meal_id}/ingredients/{ingredient_id}/edit",
|
.route("/meals/{meal_id}/ingredients/{ingredient_id}/delete", post(delete_ingredient))
|
||||||
post(edit_ingredient),
|
|
||||||
)
|
|
||||||
.route(
|
|
||||||
"/meals/{meal_id}/ingredients/{ingredient_id}/delete",
|
|
||||||
post(delete_ingredient),
|
|
||||||
)
|
|
||||||
.route("/lists/{list_id}/add-meal", post(add_meal_to_list))
|
.route("/lists/{list_id}/add-meal", post(add_meal_to_list))
|
||||||
.route("/lists/{list_id}/stream", get(list_stream))
|
.route("/lists/{list_id}/stream", get(list_stream))
|
||||||
.route("/invite/{token}", get(invitation_page))
|
.route("/invite/{token}", get(invitation_page))
|
||||||
.route("/invite/{token}/accept", post(accept_invitation))
|
.route("/invite/{token}/accept", post(accept_invitation))
|
||||||
.route("/static/{path}", get(static_asset))
|
.nest_service(
|
||||||
.layer(
|
"/static",
|
||||||
TraceLayer::new_for_http()
|
tower::ServiceBuilder::new()
|
||||||
.make_span_with(DefaultMakeSpan::new().level(Level::INFO))
|
.layer(SetResponseHeaderLayer::overriding(
|
||||||
.on_response(DefaultOnResponse::new().level(Level::INFO)),
|
header::CACHE_CONTROL,
|
||||||
|
HeaderValue::from_static("public, max-age=0, must-revalidate"),
|
||||||
|
))
|
||||||
|
.service(ServeDir::new("static")),
|
||||||
)
|
)
|
||||||
|
.layer(TraceLayer::new_for_http())
|
||||||
.layer(middleware::from_fn(log_response_status))
|
.layer(middleware::from_fn(log_response_status))
|
||||||
.with_state(state)
|
.with_state(state)
|
||||||
}
|
}
|
||||||
@@ -253,48 +225,11 @@ struct CategoryForm {
|
|||||||
csrf: String,
|
csrf: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct PasskeyRegisterStartForm {
|
|
||||||
csrf: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct PasskeyRegisterFinishForm {
|
|
||||||
csrf: String,
|
|
||||||
response: webauthn_rs::proto::RegisterPublicKeyCredential,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct PasskeyLoginStartForm {
|
|
||||||
#[serde(default)]
|
|
||||||
email: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct PasskeyLoginFinishForm {
|
|
||||||
token: String,
|
|
||||||
response: webauthn_rs::proto::PublicKeyCredential,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct DeletePasskeyForm {
|
|
||||||
csrf: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ChangePasswordForm {
|
|
||||||
csrf: String,
|
|
||||||
new_password: String,
|
|
||||||
confirm_password: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
struct MealForm {
|
struct MealForm {
|
||||||
name: String,
|
name: String,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
description: String,
|
description: String,
|
||||||
#[serde(default)]
|
|
||||||
category_id: Option<String>,
|
|
||||||
csrf: String,
|
csrf: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -325,18 +260,6 @@ async fn home() -> Redirect {
|
|||||||
Redirect::to("/lists")
|
Redirect::to("/lists")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Serves a file embedded in the binary from the `static/` folder.
|
|
||||||
async fn static_asset(Path(path): Path<String>) -> Response {
|
|
||||||
let (mime, data) = match path.as_str() {
|
|
||||||
"style.css" => ("text/css", STYLE_CSS),
|
|
||||||
"passkey-login.js" => ("application/javascript", PASSKEY_LOGIN_JS),
|
|
||||||
"passkey-register.js" => ("application/javascript", PASSKEY_REGISTER_JS),
|
|
||||||
"password-toggle.js" => ("application/javascript", PASSWORD_TOGGLE_JS),
|
|
||||||
_ => return StatusCode::NOT_FOUND.into_response(),
|
|
||||||
};
|
|
||||||
([(header::CONTENT_TYPE, mime)], data).into_response()
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn log_response_status(request: Request, next: Next) -> Response {
|
async fn log_response_status(request: Request, next: Next) -> Response {
|
||||||
let method = request.method().clone();
|
let method = request.method().clone();
|
||||||
let uri = request.uri().clone();
|
let uri = request.uri().clone();
|
||||||
@@ -456,134 +379,6 @@ async fn logout(State(state): State<AppState>, user: CurrentUser) -> Result<Resp
|
|||||||
Ok(response)
|
Ok(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn account_page(
|
|
||||||
State(state): State<AppState>,
|
|
||||||
user: CurrentUser,
|
|
||||||
) -> Result<Response, AppError> {
|
|
||||||
let passkeys = state.webauthn.list_passkeys(user.session.user.id).await?;
|
|
||||||
Ok(html_response(views::account_page(
|
|
||||||
&user.session.user,
|
|
||||||
&passkeys,
|
|
||||||
&user.session.csrf_token,
|
|
||||||
None,
|
|
||||||
false,
|
|
||||||
)))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn change_password(
|
|
||||||
State(state): State<AppState>,
|
|
||||||
user: CurrentUser,
|
|
||||||
LoggedForm(form): LoggedForm<ChangePasswordForm>,
|
|
||||||
) -> Result<Response, AppError> {
|
|
||||||
verify_csrf(&user, &form.csrf)?;
|
|
||||||
let passkeys = state.webauthn.list_passkeys(user.session.user.id).await?;
|
|
||||||
let render = |error: Option<&str>, success: bool| {
|
|
||||||
html_response(views::account_page(
|
|
||||||
&user.session.user,
|
|
||||||
&passkeys,
|
|
||||||
&user.session.csrf_token,
|
|
||||||
error,
|
|
||||||
success,
|
|
||||||
))
|
|
||||||
};
|
|
||||||
|
|
||||||
if form.new_password != form.confirm_password {
|
|
||||||
return Ok(render(
|
|
||||||
Some("New password and confirmation do not match."),
|
|
||||||
false,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
state
|
|
||||||
.auth
|
|
||||||
.change_password(user.session.user.id, form.new_password)
|
|
||||||
.await?;
|
|
||||||
Ok(render(None, true))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn passkey_register_start(
|
|
||||||
State(state): State<AppState>,
|
|
||||||
user: CurrentUser,
|
|
||||||
Json(form): Json<PasskeyRegisterStartForm>,
|
|
||||||
) -> Result<Response, AppError> {
|
|
||||||
verify_csrf(&user, &form.csrf)?;
|
|
||||||
let challenge = state
|
|
||||||
.webauthn
|
|
||||||
.start_registration(&user.session.user)
|
|
||||||
.map_err(AppError::Database)?;
|
|
||||||
Ok(Json(challenge).into_response())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn passkey_register_finish(
|
|
||||||
State(state): State<AppState>,
|
|
||||||
user: CurrentUser,
|
|
||||||
Json(form): Json<PasskeyRegisterFinishForm>,
|
|
||||||
) -> Result<Response, AppError> {
|
|
||||||
verify_csrf(&user, &form.csrf)?;
|
|
||||||
state
|
|
||||||
.webauthn
|
|
||||||
.finish_registration(&user.session.user, form.response)
|
|
||||||
.await?;
|
|
||||||
Ok(Redirect::to("/account").into_response())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn passkey_login_start(
|
|
||||||
State(state): State<AppState>,
|
|
||||||
Json(form): Json<PasskeyLoginStartForm>,
|
|
||||||
) -> Result<Response, AppError> {
|
|
||||||
let email = form.email.trim().to_lowercase();
|
|
||||||
let (challenge, token) = if email.is_empty() {
|
|
||||||
// Userless sign-in: no email needed, the authenticator selects a
|
|
||||||
// discoverable credential and returns a user handle.
|
|
||||||
state
|
|
||||||
.webauthn
|
|
||||||
.start_userless_authentication()
|
|
||||||
.await
|
|
||||||
.map_err(AppError::Database)?
|
|
||||||
} else {
|
|
||||||
let Some((user, _)) = state.auth.find_user_by_email(email).await? else {
|
|
||||||
return Err(AppError::NotFound);
|
|
||||||
};
|
|
||||||
state
|
|
||||||
.webauthn
|
|
||||||
.start_authentication(user.id)
|
|
||||||
.await
|
|
||||||
.map_err(AppError::Database)?
|
|
||||||
};
|
|
||||||
Ok(
|
|
||||||
Json(serde_json::json!({ "token": token, "publicKey": challenge.public_key }))
|
|
||||||
.into_response(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn passkey_login_finish(
|
|
||||||
State(state): State<AppState>,
|
|
||||||
Json(form): Json<PasskeyLoginFinishForm>,
|
|
||||||
) -> Result<Response, AppError> {
|
|
||||||
let user_id = state
|
|
||||||
.webauthn
|
|
||||||
.finish_authentication(form.token, form.response)
|
|
||||||
.await?;
|
|
||||||
let (session_token, _) = state.auth.create_session_for_user(user_id).await?;
|
|
||||||
let mut response = Redirect::to("/lists").into_response();
|
|
||||||
set_session_cookie(&mut response, &session_token, state.cookie_secure);
|
|
||||||
Ok(response)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn delete_passkey(
|
|
||||||
State(state): State<AppState>,
|
|
||||||
user: CurrentUser,
|
|
||||||
Path(passkey_id): Path<i64>,
|
|
||||||
LoggedForm(form): LoggedForm<DeletePasskeyForm>,
|
|
||||||
) -> Result<Response, AppError> {
|
|
||||||
verify_csrf(&user, &form.csrf)?;
|
|
||||||
state
|
|
||||||
.webauthn
|
|
||||||
.delete_passkey(user.session.user.id, passkey_id)
|
|
||||||
.await?;
|
|
||||||
Ok(Redirect::to("/account").into_response())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn lists_page(
|
async fn lists_page(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
user: CurrentUser,
|
user: CurrentUser,
|
||||||
@@ -731,65 +526,26 @@ async fn create_category(
|
|||||||
Ok(Redirect::to("/lists").into_response())
|
Ok(Redirect::to("/lists").into_response())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn create_meal_category(
|
|
||||||
State(state): State<AppState>,
|
|
||||||
user: CurrentUser,
|
|
||||||
LoggedForm(form): LoggedForm<CategoryForm>,
|
|
||||||
) -> Result<Response, AppError> {
|
|
||||||
verify_csrf(&user, &form.csrf)?;
|
|
||||||
let name = form.name.trim().to_owned();
|
|
||||||
if name.is_empty() || name.chars().count() > 60 {
|
|
||||||
return Err(AppError::BadRequest(
|
|
||||||
"Category names must be between 1 and 60 characters.".into(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
state.meals.create_meal_category(name).await?;
|
|
||||||
Ok(Redirect::to("/meals").into_response())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn delete_meal_category(
|
|
||||||
State(state): State<AppState>,
|
|
||||||
user: CurrentUser,
|
|
||||||
Path(category_id): Path<i64>,
|
|
||||||
LoggedForm(form): LoggedForm<CsrfForm>,
|
|
||||||
) -> Result<Response, AppError> {
|
|
||||||
verify_csrf(&user, &form.csrf)?;
|
|
||||||
state.meals.delete_meal_category(category_id).await?;
|
|
||||||
Ok(Redirect::to("/meals").into_response())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn meals_page(
|
async fn meals_page(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
user: CurrentUser,
|
user: CurrentUser,
|
||||||
Query(query): Query<MealPickerQuery>,
|
Query(query): Query<MealPickerQuery>,
|
||||||
) -> Result<Response, AppError> {
|
) -> Result<Response, AppError> {
|
||||||
let meals = state.meals.list_meals().await?;
|
let meals = state.meals.list_meals().await?;
|
||||||
let meal_categories = state.meals.list_meal_categories().await?;
|
|
||||||
if let Some(list_id) = query.picker {
|
if let Some(list_id) = query.picker {
|
||||||
return Ok(html_response(views::meal_picker(
|
return Ok(html_response(views::meal_picker(
|
||||||
&meals,
|
&meals,
|
||||||
&meal_categories,
|
|
||||||
list_id,
|
list_id,
|
||||||
&user.session.csrf_token,
|
&user.session.csrf_token,
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
Ok(html_response(views::meals_page(
|
Ok(html_response(views::meals_page(&user.session.user, &meals)))
|
||||||
&user.session.user,
|
|
||||||
&meals,
|
|
||||||
&meal_categories,
|
|
||||||
&user.session.csrf_token,
|
|
||||||
)))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn new_meal_page(
|
async fn new_meal_page(user: CurrentUser) -> Result<Response, AppError> {
|
||||||
State(state): State<AppState>,
|
|
||||||
user: CurrentUser,
|
|
||||||
) -> Result<Response, AppError> {
|
|
||||||
let meal_categories = state.meals.list_meal_categories().await?;
|
|
||||||
Ok(html_response(views::meal_form_page(
|
Ok(html_response(views::meal_form_page(
|
||||||
&user.session.user,
|
&user.session.user,
|
||||||
None,
|
None,
|
||||||
&meal_categories,
|
|
||||||
&user.session.csrf_token,
|
&user.session.csrf_token,
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
@@ -808,11 +564,7 @@ async fn create_meal(
|
|||||||
}
|
}
|
||||||
let meal = state
|
let meal = state
|
||||||
.meals
|
.meals
|
||||||
.create_meal(
|
.create_meal(name, form.description.trim().to_owned())
|
||||||
name,
|
|
||||||
form.description.trim().to_owned(),
|
|
||||||
parse_category_id(form.category_id),
|
|
||||||
)
|
|
||||||
.await?;
|
.await?;
|
||||||
Ok(Redirect::to(&format!("/meals/{}", meal.id)).into_response())
|
Ok(Redirect::to(&format!("/meals/{}", meal.id)).into_response())
|
||||||
}
|
}
|
||||||
@@ -828,12 +580,10 @@ async fn meal_page(
|
|||||||
.await?
|
.await?
|
||||||
.ok_or(AppError::NotFound)?;
|
.ok_or(AppError::NotFound)?;
|
||||||
let categories = state.lists.categories().await?;
|
let categories = state.lists.categories().await?;
|
||||||
let meal_categories = state.meals.list_meal_categories().await?;
|
|
||||||
Ok(html_response(views::meal_page(
|
Ok(html_response(views::meal_page(
|
||||||
&user.session.user,
|
&user.session.user,
|
||||||
&meal,
|
&meal,
|
||||||
&categories,
|
&categories,
|
||||||
&meal_categories,
|
|
||||||
&user.session.csrf_token,
|
&user.session.csrf_token,
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
@@ -853,12 +603,7 @@ async fn edit_meal(
|
|||||||
}
|
}
|
||||||
state
|
state
|
||||||
.meals
|
.meals
|
||||||
.update_meal(
|
.update_meal(meal_id, name, form.description.trim().to_owned())
|
||||||
meal_id,
|
|
||||||
name,
|
|
||||||
form.description.trim().to_owned(),
|
|
||||||
parse_category_id(form.category_id),
|
|
||||||
)
|
|
||||||
.await?;
|
.await?;
|
||||||
Ok(Redirect::to(&format!("/meals/{meal_id}")).into_response())
|
Ok(Redirect::to(&format!("/meals/{meal_id}")).into_response())
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -35,7 +35,7 @@ impl RealtimeNotifier for InMemoryHub {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
let connection_id = hex::encode(crate::security::new_secret());
|
let connection_id = crate::security::new_secret();
|
||||||
let already_present = room
|
let already_present = room
|
||||||
.connections
|
.connections
|
||||||
.values()
|
.values()
|
||||||
|
|||||||
+8
-45
@@ -7,7 +7,6 @@ mod seed;
|
|||||||
mod services;
|
mod services;
|
||||||
mod sqlite;
|
mod sqlite;
|
||||||
mod views;
|
mod views;
|
||||||
mod webauthn;
|
|
||||||
|
|
||||||
use std::env;
|
use std::env;
|
||||||
use std::path::Path as FilePath;
|
use std::path::Path as FilePath;
|
||||||
@@ -20,37 +19,29 @@ use crate::http::{AppState, build_router};
|
|||||||
use crate::hub::InMemoryHub;
|
use crate::hub::InMemoryHub;
|
||||||
use crate::ports::{
|
use crate::ports::{
|
||||||
CategoryRepository, InvitationRepository, ItemRepository, ListRepository,
|
CategoryRepository, InvitationRepository, ItemRepository, ListRepository,
|
||||||
MealCategoryRepository, MealIngredientRepository, MealRepository, PasskeyRepository,
|
MealIngredientRepository, MealRepository, PasswordHasher, RealtimeNotifier, SessionRepository,
|
||||||
PasswordHasher, RealtimeNotifier, SessionRepository, TokenGenerator, UserRepository,
|
TokenGenerator, UserRepository,
|
||||||
};
|
};
|
||||||
use crate::security::{Argon2PasswordHasher, RandomTokenGenerator};
|
use crate::security::{Argon2PasswordHasher, RandomTokenGenerator};
|
||||||
use crate::services::{AuthService, InvitationService, ListService, MealService, RegistrationMode};
|
use crate::services::{AuthService, InvitationService, ListService, MealService, RegistrationMode};
|
||||||
use crate::sqlite::{
|
use crate::sqlite::{
|
||||||
SqliteCategoryRepository, SqliteDatabase, SqliteInvitationRepository, SqliteItemRepository,
|
SqliteCategoryRepository, SqliteInvitationRepository, SqliteItemRepository,
|
||||||
SqliteListRepository, SqliteMealCategoryRepository, SqliteMealIngredientRepository,
|
SqliteListRepository, SqliteMealIngredientRepository, SqliteMealRepository,
|
||||||
SqliteMealRepository, SqlitePasskeyRepository, SqliteSessionRepository, SqliteUserRepository,
|
SqliteSessionRepository, SqliteDatabase, SqliteUserRepository,
|
||||||
};
|
};
|
||||||
use crate::webauthn::{AppWebauthnConfig, WebAuthnService};
|
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
tracing_subscriber::fmt()
|
tracing_subscriber::fmt()
|
||||||
.with_env_filter(
|
.with_env_filter(
|
||||||
env::var("RUST_LOG").unwrap_or_else(|_| "sustenance=info,tower_http=info".into()),
|
env::var("RUST_LOG").unwrap_or_else(|_| "sustenance=debug,tower_http=info".into()),
|
||||||
)
|
)
|
||||||
.init();
|
.init();
|
||||||
|
|
||||||
let database_path = env::var("DATABASE_PATH").unwrap_or_else(|_| "sustenance.db".into());
|
let database_path = env::var("DATABASE_PATH").unwrap_or_else(|_| "sustenance.db".into());
|
||||||
let bind_address = env::var("BIND_ADDRESS").unwrap_or_else(|_| "127.0.0.1:3000".into());
|
let bind_address = env::var("BIND_ADDRESS").unwrap_or_else(|_| "127.0.0.1:3000".into());
|
||||||
// For loopback hosts, advertise `localhost` so WebAuthn works locally (browsers
|
let public_base_url =
|
||||||
// reject IP addresses as RP IDs). Access the app via http://localhost:PORT.
|
env::var("PUBLIC_BASE_URL").unwrap_or_else(|_| format!("http://{}", bind_address));
|
||||||
let bind_host = bind_address.split(':').next().unwrap_or("127.0.0.1");
|
|
||||||
let is_loopback = bind_host == "127.0.0.1" || bind_host == "::1" || bind_host == "localhost";
|
|
||||||
let public_host = if is_loopback { "localhost" } else { bind_host };
|
|
||||||
let public_base_url = env::var("PUBLIC_BASE_URL").unwrap_or_else(|_| {
|
|
||||||
let port = bind_address.rsplit(':').next().unwrap_or("3000");
|
|
||||||
format!("http://{}:{}", public_host, port)
|
|
||||||
});
|
|
||||||
let cookie_secure = env::var("COOKIE_SECURE")
|
let cookie_secure = env::var("COOKIE_SECURE")
|
||||||
.map(|value| value == "1" || value.eq_ignore_ascii_case("true"))
|
.map(|value| value == "1" || value.eq_ignore_ascii_case("true"))
|
||||||
.unwrap_or(false);
|
.unwrap_or(false);
|
||||||
@@ -77,9 +68,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
let meals: Arc<dyn MealRepository> = Arc::new(SqliteMealRepository);
|
let meals: Arc<dyn MealRepository> = Arc::new(SqliteMealRepository);
|
||||||
let meal_ingredients: Arc<dyn MealIngredientRepository> =
|
let meal_ingredients: Arc<dyn MealIngredientRepository> =
|
||||||
Arc::new(SqliteMealIngredientRepository);
|
Arc::new(SqliteMealIngredientRepository);
|
||||||
let meal_categories: Arc<dyn MealCategoryRepository> = Arc::new(SqliteMealCategoryRepository);
|
|
||||||
let invitations: Arc<dyn InvitationRepository> = Arc::new(SqliteInvitationRepository);
|
let invitations: Arc<dyn InvitationRepository> = Arc::new(SqliteInvitationRepository);
|
||||||
let passkeys: Arc<dyn PasskeyRepository> = Arc::new(SqlitePasskeyRepository);
|
|
||||||
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2PasswordHasher);
|
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2PasswordHasher);
|
||||||
let tokens: Arc<dyn TokenGenerator> = Arc::new(RandomTokenGenerator);
|
let tokens: Arc<dyn TokenGenerator> = Arc::new(RandomTokenGenerator);
|
||||||
let realtime: Arc<dyn RealtimeNotifier> = Arc::new(InMemoryHub::default());
|
let realtime: Arc<dyn RealtimeNotifier> = Arc::new(InMemoryHub::default());
|
||||||
@@ -108,36 +97,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
db.clone(),
|
db.clone(),
|
||||||
Arc::clone(&meals),
|
Arc::clone(&meals),
|
||||||
Arc::clone(&meal_ingredients),
|
Arc::clone(&meal_ingredients),
|
||||||
Arc::clone(&meal_categories),
|
|
||||||
Arc::clone(&lists),
|
Arc::clone(&lists),
|
||||||
Arc::clone(&items),
|
Arc::clone(&items),
|
||||||
Arc::clone(&realtime),
|
Arc::clone(&realtime),
|
||||||
));
|
));
|
||||||
|
|
||||||
// WebAuthn config from env vars. RP_ID must match the host users access the site from.
|
|
||||||
let rp_id = env::var("RP_ID").unwrap_or_else(|_| {
|
|
||||||
let host = public_base_url
|
|
||||||
.trim_start_matches("http://")
|
|
||||||
.trim_start_matches("https://")
|
|
||||||
.split('/')
|
|
||||||
.next()
|
|
||||||
.unwrap_or("localhost")
|
|
||||||
.split(':')
|
|
||||||
.next()
|
|
||||||
.unwrap_or("localhost")
|
|
||||||
.to_owned();
|
|
||||||
host
|
|
||||||
});
|
|
||||||
let rp_name = env::var("RP_NAME").unwrap_or_else(|_| "Sustenance".into());
|
|
||||||
let origin =
|
|
||||||
url::Url::parse(&public_base_url).map_err(|e| format!("invalid PUBLIC_BASE_URL: {e}"))?;
|
|
||||||
let webauthn_service = Arc::new(WebAuthnService::new(
|
|
||||||
db.clone(),
|
|
||||||
AppWebauthnConfig::new(rp_id, rp_name, origin),
|
|
||||||
Arc::clone(&users),
|
|
||||||
Arc::clone(&passkeys),
|
|
||||||
));
|
|
||||||
|
|
||||||
let seed_path = env::var("SEED_CONFIG").unwrap_or_else(|_| "seed.json".into());
|
let seed_path = env::var("SEED_CONFIG").unwrap_or_else(|_| "seed.json".into());
|
||||||
seed::seed_if_needed(&db, &users, &hasher, FilePath::new(&seed_path)).await;
|
seed::seed_if_needed(&db, &users, &hasher, FilePath::new(&seed_path)).await;
|
||||||
|
|
||||||
@@ -146,7 +110,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
lists: lists_service,
|
lists: lists_service,
|
||||||
meals: meals_service,
|
meals: meals_service,
|
||||||
invitations: invitations_service,
|
invitations: invitations_service,
|
||||||
webauthn: webauthn_service,
|
|
||||||
realtime,
|
realtime,
|
||||||
cookie_secure,
|
cookie_secure,
|
||||||
public_base_url,
|
public_base_url,
|
||||||
|
|||||||
+12
-59
@@ -2,8 +2,8 @@ use async_trait::async_trait;
|
|||||||
use sqlx::SqliteConnection;
|
use sqlx::SqliteConnection;
|
||||||
|
|
||||||
use crate::domain::{
|
use crate::domain::{
|
||||||
Category, DomainResult, GroceryList, Item, Meal, MealCategory, MealIngredient, Passkey,
|
Category, DomainResult, GroceryList, Item, Meal, MealIngredient, PresenceUser, SessionUser,
|
||||||
PresenceUser, SessionUser, User,
|
User,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Repositories take `&mut SqliteConnection` (which a `Transaction` derefs to),
|
/// Repositories take `&mut SqliteConnection` (which a `Transaction` derefs to),
|
||||||
@@ -24,48 +24,9 @@ pub trait UserRepository: Send + Sync {
|
|||||||
txn: &mut SqliteConnection,
|
txn: &mut SqliteConnection,
|
||||||
email: String,
|
email: String,
|
||||||
) -> DomainResult<Option<(User, String)>>;
|
) -> DomainResult<Option<(User, String)>>;
|
||||||
async fn find_user_by_handle(
|
|
||||||
&self,
|
|
||||||
txn: &mut SqliteConnection,
|
|
||||||
user_handle: Vec<u8>,
|
|
||||||
) -> DomainResult<Option<User>>;
|
|
||||||
async fn update_password_hash(
|
|
||||||
&self,
|
|
||||||
txn: &mut SqliteConnection,
|
|
||||||
user_id: i64,
|
|
||||||
password_hash: String,
|
|
||||||
) -> DomainResult<()>;
|
|
||||||
async fn has_users(&self, txn: &mut SqliteConnection) -> DomainResult<bool>;
|
async fn has_users(&self, txn: &mut SqliteConnection) -> DomainResult<bool>;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
pub trait PasskeyRepository: Send + Sync {
|
|
||||||
async fn create_passkey(
|
|
||||||
&self,
|
|
||||||
txn: &mut SqliteConnection,
|
|
||||||
user_id: i64,
|
|
||||||
credential_id: String,
|
|
||||||
credential: String,
|
|
||||||
counter: i64,
|
|
||||||
) -> DomainResult<Passkey>;
|
|
||||||
async fn find_by_credential_id(
|
|
||||||
&self,
|
|
||||||
txn: &mut SqliteConnection,
|
|
||||||
credential_id: String,
|
|
||||||
) -> DomainResult<Option<Passkey>>;
|
|
||||||
async fn list_for_user(
|
|
||||||
&self,
|
|
||||||
txn: &mut SqliteConnection,
|
|
||||||
user_id: i64,
|
|
||||||
) -> DomainResult<Vec<Passkey>>;
|
|
||||||
async fn delete_passkey(
|
|
||||||
&self,
|
|
||||||
txn: &mut SqliteConnection,
|
|
||||||
user_id: i64,
|
|
||||||
passkey_id: i64,
|
|
||||||
) -> DomainResult<()>;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait SessionRepository: Send + Sync {
|
pub trait SessionRepository: Send + Sync {
|
||||||
async fn create_session(
|
async fn create_session(
|
||||||
@@ -103,7 +64,16 @@ pub trait ListRepository: Send + Sync {
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait CategoryRepository: Send + Sync {
|
pub trait CategoryRepository: Send + Sync {
|
||||||
async fn categories(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<Category>>;
|
async fn categories(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<Category>>;
|
||||||
async fn create_category(&self, txn: &mut SqliteConnection, name: String) -> DomainResult<i64>;
|
async fn create_category(
|
||||||
|
&self,
|
||||||
|
txn: &mut SqliteConnection,
|
||||||
|
name: String,
|
||||||
|
) -> DomainResult<i64>;
|
||||||
|
async fn category_by_name(
|
||||||
|
&self,
|
||||||
|
txn: &mut SqliteConnection,
|
||||||
|
name: String,
|
||||||
|
) -> DomainResult<Option<Category>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A single item to insert in bulk, without a per-item revision bump.
|
/// A single item to insert in bulk, without a per-item revision bump.
|
||||||
@@ -174,21 +144,6 @@ pub trait InvitationRepository: Send + Sync {
|
|||||||
) -> DomainResult<()>;
|
) -> DomainResult<()>;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
pub trait MealCategoryRepository: Send + Sync {
|
|
||||||
async fn meal_categories(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<MealCategory>>;
|
|
||||||
async fn create_meal_category(
|
|
||||||
&self,
|
|
||||||
txn: &mut SqliteConnection,
|
|
||||||
name: String,
|
|
||||||
) -> DomainResult<i64>;
|
|
||||||
async fn delete_meal_category(
|
|
||||||
&self,
|
|
||||||
txn: &mut SqliteConnection,
|
|
||||||
category_id: i64,
|
|
||||||
) -> DomainResult<()>;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait MealRepository: Send + Sync {
|
pub trait MealRepository: Send + Sync {
|
||||||
async fn create_meal(
|
async fn create_meal(
|
||||||
@@ -196,7 +151,6 @@ pub trait MealRepository: Send + Sync {
|
|||||||
txn: &mut SqliteConnection,
|
txn: &mut SqliteConnection,
|
||||||
name: String,
|
name: String,
|
||||||
description: String,
|
description: String,
|
||||||
category_id: Option<i64>,
|
|
||||||
) -> DomainResult<Meal>;
|
) -> DomainResult<Meal>;
|
||||||
async fn get_meal(
|
async fn get_meal(
|
||||||
&self,
|
&self,
|
||||||
@@ -210,7 +164,6 @@ pub trait MealRepository: Send + Sync {
|
|||||||
meal_id: i64,
|
meal_id: i64,
|
||||||
name: String,
|
name: String,
|
||||||
description: String,
|
description: String,
|
||||||
category_id: Option<i64>,
|
|
||||||
) -> DomainResult<()>;
|
) -> DomainResult<()>;
|
||||||
async fn delete_meal(&self, txn: &mut SqliteConnection, meal_id: i64) -> DomainResult<()>;
|
async fn delete_meal(&self, txn: &mut SqliteConnection, meal_id: i64) -> DomainResult<()>;
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-5
@@ -37,14 +37,12 @@ pub struct RandomTokenGenerator;
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl TokenGenerator for RandomTokenGenerator {
|
impl TokenGenerator for RandomTokenGenerator {
|
||||||
fn generate(&self) -> String {
|
fn generate(&self) -> String {
|
||||||
hex::encode(new_secret())
|
new_secret()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Generates 32 cryptographically random bytes. Callers that need a
|
pub fn new_secret() -> String {
|
||||||
/// client-facing string should hex-encode the result.
|
|
||||||
pub fn new_secret() -> Vec<u8> {
|
|
||||||
let mut bytes = [0_u8; 32];
|
let mut bytes = [0_u8; 32];
|
||||||
OsRng.fill_bytes(&mut bytes);
|
OsRng.fill_bytes(&mut bytes);
|
||||||
bytes.to_vec()
|
hex::encode(bytes)
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-81
@@ -1,12 +1,12 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use crate::domain::{
|
use crate::domain::{
|
||||||
DomainError, DomainResult, GroceryList, Item, Meal, MealCategory, SessionUser, User,
|
DomainError, DomainResult, GroceryList, Item, Meal, SessionUser, User,
|
||||||
};
|
};
|
||||||
use crate::ports::{
|
use crate::ports::{
|
||||||
CategoryRepository, InvitationRepository, ItemRepository, ListRepository,
|
CategoryRepository, InvitationRepository, ItemRepository, ListRepository, MealIngredientRepository,
|
||||||
MealCategoryRepository, MealIngredientRepository, MealRepository, NewItem, PasswordHasher,
|
MealRepository, NewItem, PasswordHasher, RealtimeNotifier, SessionRepository, TokenGenerator,
|
||||||
RealtimeNotifier, SessionRepository, TokenGenerator, UserRepository,
|
UserRepository,
|
||||||
};
|
};
|
||||||
use crate::sqlite::SqliteDatabase;
|
use crate::sqlite::SqliteDatabase;
|
||||||
|
|
||||||
@@ -127,20 +127,6 @@ impl AuthService {
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn find_user_by_email(&self, email: String) -> DomainResult<Option<(User, String)>> {
|
|
||||||
let users = Arc::clone(&self.users);
|
|
||||||
self.db
|
|
||||||
.run(move |txn| Box::pin(async move { users.find_user_by_email(txn, email).await }))
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn create_session_for_user(&self, user_id: i64) -> DomainResult<(String, String)> {
|
|
||||||
let sessions = Arc::clone(&self.sessions);
|
|
||||||
self.db
|
|
||||||
.run(move |txn| Box::pin(async move { sessions.create_session(txn, user_id).await }))
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn logout(&self, session_token: String) -> DomainResult<()> {
|
pub async fn logout(&self, session_token: String) -> DomainResult<()> {
|
||||||
let sessions = Arc::clone(&self.sessions);
|
let sessions = Arc::clone(&self.sessions);
|
||||||
self.db
|
self.db
|
||||||
@@ -149,22 +135,6 @@ impl AuthService {
|
|||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Replaces the user's password hash with a freshly hashed new password.
|
|
||||||
/// No current-password check is performed because the account page is
|
|
||||||
/// already authenticated and this app has no email capabilities.
|
|
||||||
pub async fn change_password(&self, user_id: i64, new_password: String) -> DomainResult<()> {
|
|
||||||
let users = Arc::clone(&self.users);
|
|
||||||
let hasher = Arc::clone(&self.hasher);
|
|
||||||
self.db
|
|
||||||
.run(move |txn| {
|
|
||||||
Box::pin(async move {
|
|
||||||
let new_hash = hasher.hash(&new_password)?;
|
|
||||||
users.update_password_hash(txn, user_id, new_hash).await
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct ListService {
|
pub struct ListService {
|
||||||
@@ -315,7 +285,6 @@ pub struct MealService {
|
|||||||
db: SqliteDatabase,
|
db: SqliteDatabase,
|
||||||
meals: Arc<dyn MealRepository>,
|
meals: Arc<dyn MealRepository>,
|
||||||
ingredients: Arc<dyn MealIngredientRepository>,
|
ingredients: Arc<dyn MealIngredientRepository>,
|
||||||
meal_categories: Arc<dyn MealCategoryRepository>,
|
|
||||||
lists: Arc<dyn ListRepository>,
|
lists: Arc<dyn ListRepository>,
|
||||||
items: Arc<dyn ItemRepository>,
|
items: Arc<dyn ItemRepository>,
|
||||||
realtime: Arc<dyn RealtimeNotifier>,
|
realtime: Arc<dyn RealtimeNotifier>,
|
||||||
@@ -326,7 +295,6 @@ impl MealService {
|
|||||||
db: SqliteDatabase,
|
db: SqliteDatabase,
|
||||||
meals: Arc<dyn MealRepository>,
|
meals: Arc<dyn MealRepository>,
|
||||||
ingredients: Arc<dyn MealIngredientRepository>,
|
ingredients: Arc<dyn MealIngredientRepository>,
|
||||||
meal_categories: Arc<dyn MealCategoryRepository>,
|
|
||||||
lists: Arc<dyn ListRepository>,
|
lists: Arc<dyn ListRepository>,
|
||||||
items: Arc<dyn ItemRepository>,
|
items: Arc<dyn ItemRepository>,
|
||||||
realtime: Arc<dyn RealtimeNotifier>,
|
realtime: Arc<dyn RealtimeNotifier>,
|
||||||
@@ -335,26 +303,16 @@ impl MealService {
|
|||||||
db,
|
db,
|
||||||
meals,
|
meals,
|
||||||
ingredients,
|
ingredients,
|
||||||
meal_categories,
|
|
||||||
lists,
|
lists,
|
||||||
items,
|
items,
|
||||||
realtime,
|
realtime,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn create_meal(
|
pub async fn create_meal(&self, name: String, description: String) -> DomainResult<Meal> {
|
||||||
&self,
|
|
||||||
name: String,
|
|
||||||
description: String,
|
|
||||||
category_id: Option<i64>,
|
|
||||||
) -> DomainResult<Meal> {
|
|
||||||
let meals = Arc::clone(&self.meals);
|
let meals = Arc::clone(&self.meals);
|
||||||
self.db
|
self.db
|
||||||
.run(move |txn| {
|
.run(move |txn| Box::pin(async move { meals.create_meal(txn, name, description).await }))
|
||||||
Box::pin(
|
|
||||||
async move { meals.create_meal(txn, name, description, category_id).await },
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -377,43 +335,11 @@ impl MealService {
|
|||||||
meal_id: i64,
|
meal_id: i64,
|
||||||
name: String,
|
name: String,
|
||||||
description: String,
|
description: String,
|
||||||
category_id: Option<i64>,
|
|
||||||
) -> DomainResult<()> {
|
) -> DomainResult<()> {
|
||||||
let meals = Arc::clone(&self.meals);
|
let meals = Arc::clone(&self.meals);
|
||||||
self.db
|
self.db
|
||||||
.run(move |txn| {
|
.run(move |txn| {
|
||||||
Box::pin(async move {
|
Box::pin(async move { meals.update_meal(txn, meal_id, name, description).await })
|
||||||
meals
|
|
||||||
.update_meal(txn, meal_id, name, description, category_id)
|
|
||||||
.await
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn list_meal_categories(&self) -> DomainResult<Vec<MealCategory>> {
|
|
||||||
let meal_categories = Arc::clone(&self.meal_categories);
|
|
||||||
self.db
|
|
||||||
.run(move |txn| Box::pin(async move { meal_categories.meal_categories(txn).await }))
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn create_meal_category(&self, name: String) -> DomainResult<i64> {
|
|
||||||
let meal_categories = Arc::clone(&self.meal_categories);
|
|
||||||
self.db
|
|
||||||
.run(move |txn| {
|
|
||||||
Box::pin(async move { meal_categories.create_meal_category(txn, name).await })
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn delete_meal_category(&self, category_id: i64) -> DomainResult<()> {
|
|
||||||
let meal_categories = Arc::clone(&self.meal_categories);
|
|
||||||
self.db
|
|
||||||
.run(move |txn| {
|
|
||||||
Box::pin(
|
|
||||||
async move { meal_categories.delete_meal_category(txn, category_id).await },
|
|
||||||
)
|
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|||||||
+140
-520
@@ -7,18 +7,14 @@ use sha2::{Digest, Sha256};
|
|||||||
use sqlx::{Connection, Row, SqliteConnection, SqlitePool, sqlite::SqliteConnectOptions};
|
use sqlx::{Connection, Row, SqliteConnection, SqlitePool, sqlite::SqliteConnectOptions};
|
||||||
|
|
||||||
use crate::domain::{
|
use crate::domain::{
|
||||||
Category, DomainError, DomainResult, GroceryList, Item, Meal, MealCategory, MealIngredient,
|
Category, DomainError, DomainResult, GroceryList, Item, Meal, MealIngredient, SessionUser,
|
||||||
Passkey, SessionUser, User,
|
User,
|
||||||
};
|
};
|
||||||
use crate::ports::{
|
use crate::ports::{
|
||||||
CategoryRepository, InvitationRepository, ItemRepository, ListRepository,
|
CategoryRepository, InvitationRepository, ItemRepository, ListRepository, MealIngredientRepository,
|
||||||
MealCategoryRepository, MealIngredientRepository, MealRepository, NewItem, PasskeyRepository,
|
MealRepository, NewItem, SessionRepository, UserRepository,
|
||||||
SessionRepository, UserRepository,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/// The embedded SQL migrations, applied automatically on startup.
|
|
||||||
static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!();
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct SqliteDatabase {
|
pub struct SqliteDatabase {
|
||||||
pool: SqlitePool,
|
pool: SqlitePool,
|
||||||
@@ -33,9 +29,8 @@ impl SqliteDatabase {
|
|||||||
.busy_timeout(std::time::Duration::from_secs(5))
|
.busy_timeout(std::time::Duration::from_secs(5))
|
||||||
.create_if_missing(true);
|
.create_if_missing(true);
|
||||||
let pool = SqlitePool::connect_with(options).await.map_err(db_error)?;
|
let pool = SqlitePool::connect_with(options).await.map_err(db_error)?;
|
||||||
MIGRATOR.run(&pool).await.map_err(migrate_error)?;
|
migrate(&pool).await?;
|
||||||
seed_default_categories(&pool).await?;
|
seed_default_categories(&pool).await?;
|
||||||
seed_default_meal_categories(&pool).await?;
|
|
||||||
Ok(Self { pool })
|
Ok(Self { pool })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,9 +55,8 @@ impl SqliteDatabase {
|
|||||||
.busy_timeout(std::time::Duration::from_secs(5))
|
.busy_timeout(std::time::Duration::from_secs(5))
|
||||||
.create_if_missing(true);
|
.create_if_missing(true);
|
||||||
let pool = SqlitePool::connect_with(options).await.map_err(db_error)?;
|
let pool = SqlitePool::connect_with(options).await.map_err(db_error)?;
|
||||||
MIGRATOR.run(&pool).await.map_err(migrate_error)?;
|
migrate(&pool).await?;
|
||||||
seed_default_categories(&pool).await?;
|
seed_default_categories(&pool).await?;
|
||||||
seed_default_meal_categories(&pool).await?;
|
|
||||||
Ok(Self { pool })
|
Ok(Self { pool })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -97,6 +91,77 @@ impl SqliteDatabase {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn migrate(pool: &SqlitePool) -> DomainResult<()> {
|
||||||
|
sqlx::raw_sql(
|
||||||
|
"CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
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 INTEGER 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 INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
revision INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS 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 IF NOT EXISTS invitations (
|
||||||
|
token_hash TEXT PRIMARY KEY,
|
||||||
|
created_by INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
expires_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS 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 IF NOT EXISTS 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 IF NOT EXISTS 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 IF NOT EXISTS items_list_idx ON items(list_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS meal_ingredients_meal_idx ON meal_ingredients(meal_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS sessions_user_idx ON sessions(user_id);",
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await
|
||||||
|
.map_err(db_error)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Inserts the default global categories once, if the categories table is empty.
|
/// Inserts the default global categories once, if the categories table is empty.
|
||||||
async fn seed_default_categories(pool: &SqlitePool) -> DomainResult<()> {
|
async fn seed_default_categories(pool: &SqlitePool) -> DomainResult<()> {
|
||||||
let count: i64 = sqlx::query("SELECT COUNT(*) FROM categories")
|
let count: i64 = sqlx::query("SELECT COUNT(*) FROM categories")
|
||||||
@@ -119,28 +184,6 @@ async fn seed_default_categories(pool: &SqlitePool) -> DomainResult<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Inserts the default meal categories once, if the meal_categories table is empty.
|
|
||||||
async fn seed_default_meal_categories(pool: &SqlitePool) -> DomainResult<()> {
|
|
||||||
let count: i64 = sqlx::query("SELECT COUNT(*) FROM meal_categories")
|
|
||||||
.fetch_one(pool)
|
|
||||||
.await
|
|
||||||
.map_err(db_error)?
|
|
||||||
.get(0);
|
|
||||||
if count > 0 {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
for (position, category_name) in DEFAULT_MEAL_CATEGORIES.iter().enumerate() {
|
|
||||||
sqlx::query("INSERT INTO meal_categories (name, position, created_at) VALUES (?1, ?2, ?3)")
|
|
||||||
.bind(category_name)
|
|
||||||
.bind(position as i64)
|
|
||||||
.bind(now())
|
|
||||||
.execute(pool)
|
|
||||||
.await
|
|
||||||
.map_err(db_error)?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
pub struct SqliteUserRepository;
|
pub struct SqliteUserRepository;
|
||||||
|
|
||||||
@@ -153,17 +196,13 @@ impl UserRepository for SqliteUserRepository {
|
|||||||
display_name: String,
|
display_name: String,
|
||||||
password_hash: String,
|
password_hash: String,
|
||||||
) -> DomainResult<User> {
|
) -> DomainResult<User> {
|
||||||
// Generate a random, high-entropy user handle per the WebAuthn spec so
|
|
||||||
// the value embedded in authenticators is opaque and unguessable.
|
|
||||||
let user_handle = new_user_handle();
|
|
||||||
let result = sqlx::query(
|
let result = sqlx::query(
|
||||||
"INSERT INTO users (email, display_name, password_hash, user_handle, created_at)
|
"INSERT INTO users (email, display_name, password_hash, created_at)
|
||||||
VALUES (?1, ?2, ?3, ?4, ?5)",
|
VALUES (?1, ?2, ?3, ?4)",
|
||||||
)
|
)
|
||||||
.bind(&email)
|
.bind(&email)
|
||||||
.bind(&display_name)
|
.bind(&display_name)
|
||||||
.bind(&password_hash)
|
.bind(&password_hash)
|
||||||
.bind(&user_handle)
|
|
||||||
.bind(now())
|
.bind(now())
|
||||||
.execute(&mut *txn)
|
.execute(&mut *txn)
|
||||||
.await;
|
.await;
|
||||||
@@ -178,7 +217,6 @@ impl UserRepository for SqliteUserRepository {
|
|||||||
id,
|
id,
|
||||||
email,
|
email,
|
||||||
display_name,
|
display_name,
|
||||||
user_handle,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
Err(error) if is_unique_violation(&error) => Err(DomainError::Conflict),
|
Err(error) if is_unique_violation(&error) => Err(DomainError::Conflict),
|
||||||
@@ -192,7 +230,7 @@ impl UserRepository for SqliteUserRepository {
|
|||||||
email: String,
|
email: String,
|
||||||
) -> DomainResult<Option<(User, String)>> {
|
) -> DomainResult<Option<(User, String)>> {
|
||||||
let row = sqlx::query(
|
let row = sqlx::query(
|
||||||
"SELECT id, email, display_name, user_handle, password_hash
|
"SELECT id, email, display_name, password_hash
|
||||||
FROM users WHERE email = ?1 COLLATE NOCASE",
|
FROM users WHERE email = ?1 COLLATE NOCASE",
|
||||||
)
|
)
|
||||||
.bind(&email)
|
.bind(&email)
|
||||||
@@ -205,49 +243,12 @@ impl UserRepository for SqliteUserRepository {
|
|||||||
id: row.get(0),
|
id: row.get(0),
|
||||||
email: row.get(1),
|
email: row.get(1),
|
||||||
display_name: row.get(2),
|
display_name: row.get(2),
|
||||||
user_handle: row.get(3),
|
|
||||||
},
|
},
|
||||||
row.get(4),
|
row.get(3),
|
||||||
)
|
)
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn find_user_by_handle(
|
|
||||||
&self,
|
|
||||||
txn: &mut SqliteConnection,
|
|
||||||
user_handle: Vec<u8>,
|
|
||||||
) -> DomainResult<Option<User>> {
|
|
||||||
let row = sqlx::query(
|
|
||||||
"SELECT id, email, display_name, user_handle
|
|
||||||
FROM users WHERE user_handle = ?1",
|
|
||||||
)
|
|
||||||
.bind(&user_handle)
|
|
||||||
.fetch_optional(&mut *txn)
|
|
||||||
.await
|
|
||||||
.map_err(db_error)?;
|
|
||||||
Ok(row.map(|row| User {
|
|
||||||
id: row.get(0),
|
|
||||||
email: row.get(1),
|
|
||||||
display_name: row.get(2),
|
|
||||||
user_handle: row.get(3),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn update_password_hash(
|
|
||||||
&self,
|
|
||||||
txn: &mut SqliteConnection,
|
|
||||||
user_id: i64,
|
|
||||||
password_hash: String,
|
|
||||||
) -> DomainResult<()> {
|
|
||||||
sqlx::query("UPDATE users SET password_hash = ?1 WHERE id = ?2")
|
|
||||||
.bind(&password_hash)
|
|
||||||
.bind(user_id)
|
|
||||||
.execute(&mut *txn)
|
|
||||||
.await
|
|
||||||
.map_err(db_error)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn has_users(&self, txn: &mut SqliteConnection) -> DomainResult<bool> {
|
async fn has_users(&self, txn: &mut SqliteConnection) -> DomainResult<bool> {
|
||||||
let row = sqlx::query("SELECT EXISTS(SELECT 1 FROM users)")
|
let row = sqlx::query("SELECT EXISTS(SELECT 1 FROM users)")
|
||||||
.fetch_one(&mut *txn)
|
.fetch_one(&mut *txn)
|
||||||
@@ -257,117 +258,6 @@ impl UserRepository for SqliteUserRepository {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
|
||||||
pub struct SqlitePasskeyRepository;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl PasskeyRepository for SqlitePasskeyRepository {
|
|
||||||
async fn create_passkey(
|
|
||||||
&self,
|
|
||||||
txn: &mut SqliteConnection,
|
|
||||||
user_id: i64,
|
|
||||||
credential_id: String,
|
|
||||||
credential: String,
|
|
||||||
counter: i64,
|
|
||||||
) -> DomainResult<Passkey> {
|
|
||||||
let result = sqlx::query(
|
|
||||||
"INSERT INTO passkeys (user_id, credential_id, credential, counter, created_at)
|
|
||||||
VALUES (?1, ?2, ?3, ?4, ?5)",
|
|
||||||
)
|
|
||||||
.bind(user_id)
|
|
||||||
.bind(&credential_id)
|
|
||||||
.bind(&credential)
|
|
||||||
.bind(counter)
|
|
||||||
.bind(now())
|
|
||||||
.execute(&mut *txn)
|
|
||||||
.await;
|
|
||||||
match result {
|
|
||||||
Ok(_) => {
|
|
||||||
let id = sqlx::query("SELECT last_insert_rowid()")
|
|
||||||
.fetch_one(&mut *txn)
|
|
||||||
.await
|
|
||||||
.map_err(db_error)?
|
|
||||||
.get::<i64, _>(0);
|
|
||||||
Ok(Passkey {
|
|
||||||
id,
|
|
||||||
user_id,
|
|
||||||
credential_id,
|
|
||||||
credential,
|
|
||||||
counter,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
Err(error) if is_unique_violation(&error) => Err(DomainError::Conflict),
|
|
||||||
Err(error) => Err(db_error(error)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn find_by_credential_id(
|
|
||||||
&self,
|
|
||||||
txn: &mut SqliteConnection,
|
|
||||||
credential_id: String,
|
|
||||||
) -> DomainResult<Option<Passkey>> {
|
|
||||||
let row = sqlx::query(
|
|
||||||
"SELECT id, user_id, credential_id, credential, counter
|
|
||||||
FROM passkeys WHERE credential_id = ?1",
|
|
||||||
)
|
|
||||||
.bind(&credential_id)
|
|
||||||
.fetch_optional(&mut *txn)
|
|
||||||
.await
|
|
||||||
.map_err(db_error)?;
|
|
||||||
Ok(row.map(|row| Passkey {
|
|
||||||
id: row.get(0),
|
|
||||||
user_id: row.get(1),
|
|
||||||
credential_id: row.get(2),
|
|
||||||
credential: row.get(3),
|
|
||||||
counter: row.get(4),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn list_for_user(
|
|
||||||
&self,
|
|
||||||
txn: &mut SqliteConnection,
|
|
||||||
user_id: i64,
|
|
||||||
) -> DomainResult<Vec<Passkey>> {
|
|
||||||
let rows = sqlx::query(
|
|
||||||
"SELECT id, user_id, credential_id, credential, counter
|
|
||||||
FROM passkeys WHERE user_id = ?1 ORDER BY id ASC",
|
|
||||||
)
|
|
||||||
.bind(user_id)
|
|
||||||
.fetch_all(&mut *txn)
|
|
||||||
.await
|
|
||||||
.map_err(db_error)?;
|
|
||||||
Ok(rows
|
|
||||||
.into_iter()
|
|
||||||
.map(|row| Passkey {
|
|
||||||
id: row.get(0),
|
|
||||||
user_id: row.get(1),
|
|
||||||
credential_id: row.get(2),
|
|
||||||
credential: row.get(3),
|
|
||||||
counter: row.get(4),
|
|
||||||
})
|
|
||||||
.collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn delete_passkey(
|
|
||||||
&self,
|
|
||||||
txn: &mut SqliteConnection,
|
|
||||||
user_id: i64,
|
|
||||||
passkey_id: i64,
|
|
||||||
) -> DomainResult<()> {
|
|
||||||
let changed = sqlx::query("DELETE FROM passkeys WHERE id = ?1 AND user_id = ?2")
|
|
||||||
.bind(passkey_id)
|
|
||||||
.bind(user_id)
|
|
||||||
.execute(&mut *txn)
|
|
||||||
.await
|
|
||||||
.map_err(db_error)?
|
|
||||||
.rows_affected();
|
|
||||||
if changed == 0 {
|
|
||||||
return Err(DomainError::NotFound);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
pub struct SqliteSessionRepository;
|
pub struct SqliteSessionRepository;
|
||||||
|
|
||||||
@@ -378,15 +268,15 @@ impl SessionRepository for SqliteSessionRepository {
|
|||||||
txn: &mut SqliteConnection,
|
txn: &mut SqliteConnection,
|
||||||
user_id: i64,
|
user_id: i64,
|
||||||
) -> DomainResult<(String, String)> {
|
) -> DomainResult<(String, String)> {
|
||||||
let session_token = hex::encode(crate::security::new_secret());
|
let session_token = crate::security::new_secret();
|
||||||
let csrf_token = hex::encode(crate::security::new_secret());
|
let csrf_token = crate::security::new_secret();
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO sessions (token_hash, user_id, csrf_token, expires_at)
|
"INSERT INTO sessions (token_hash, user_id, csrf_token, expires_at)
|
||||||
VALUES (?1, ?2, ?3, ?4)",
|
VALUES (?1, ?2, ?3, ?4)",
|
||||||
)
|
)
|
||||||
.bind(hash_secret(&session_token))
|
.bind(hash_secret(&session_token))
|
||||||
.bind(user_id)
|
.bind(user_id)
|
||||||
.bind(hex::decode(&csrf_token).expect("csrf_token is valid hex"))
|
.bind(&csrf_token)
|
||||||
.bind(now() + 60 * 60 * 24 * 30)
|
.bind(now() + 60 * 60 * 24 * 30)
|
||||||
.execute(&mut *txn)
|
.execute(&mut *txn)
|
||||||
.await
|
.await
|
||||||
@@ -400,7 +290,7 @@ impl SessionRepository for SqliteSessionRepository {
|
|||||||
session_token: String,
|
session_token: String,
|
||||||
) -> DomainResult<Option<SessionUser>> {
|
) -> DomainResult<Option<SessionUser>> {
|
||||||
let row = sqlx::query(
|
let row = sqlx::query(
|
||||||
"SELECT u.id, u.email, u.display_name, u.user_handle, s.csrf_token
|
"SELECT u.id, u.email, u.display_name, s.csrf_token
|
||||||
FROM sessions s
|
FROM sessions s
|
||||||
JOIN users u ON u.id = s.user_id
|
JOIN users u ON u.id = s.user_id
|
||||||
WHERE s.token_hash = ?1 AND s.expires_at > ?2",
|
WHERE s.token_hash = ?1 AND s.expires_at > ?2",
|
||||||
@@ -415,9 +305,8 @@ impl SessionRepository for SqliteSessionRepository {
|
|||||||
id: row.get(0),
|
id: row.get(0),
|
||||||
email: row.get(1),
|
email: row.get(1),
|
||||||
display_name: row.get(2),
|
display_name: row.get(2),
|
||||||
user_handle: row.get(3),
|
|
||||||
},
|
},
|
||||||
csrf_token: hex::encode(row.get::<Vec<u8>, _>(4)),
|
csrf_token: row.get(3),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -527,7 +416,11 @@ impl CategoryRepository for SqliteCategoryRepository {
|
|||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn create_category(&self, txn: &mut SqliteConnection, name: String) -> DomainResult<i64> {
|
async fn create_category(
|
||||||
|
&self,
|
||||||
|
txn: &mut SqliteConnection,
|
||||||
|
name: String,
|
||||||
|
) -> DomainResult<i64> {
|
||||||
let position: i64 = sqlx::query("SELECT COALESCE(MAX(position), -1) + 1 FROM categories")
|
let position: i64 = sqlx::query("SELECT COALESCE(MAX(position), -1) + 1 FROM categories")
|
||||||
.fetch_one(&mut *txn)
|
.fetch_one(&mut *txn)
|
||||||
.await
|
.await
|
||||||
@@ -554,6 +447,26 @@ impl CategoryRepository for SqliteCategoryRepository {
|
|||||||
.get::<i64, _>(0);
|
.get::<i64, _>(0);
|
||||||
Ok(id)
|
Ok(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn category_by_name(
|
||||||
|
&self,
|
||||||
|
txn: &mut SqliteConnection,
|
||||||
|
name: String,
|
||||||
|
) -> DomainResult<Option<Category>> {
|
||||||
|
let row = sqlx::query(
|
||||||
|
"SELECT id, name
|
||||||
|
FROM categories
|
||||||
|
WHERE name = ?1 COLLATE NOCASE",
|
||||||
|
)
|
||||||
|
.bind(&name)
|
||||||
|
.fetch_optional(&mut *txn)
|
||||||
|
.await
|
||||||
|
.map_err(db_error)?;
|
||||||
|
Ok(row.map(|row| Category {
|
||||||
|
id: row.get(0),
|
||||||
|
name: row.get(1),
|
||||||
|
}))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
@@ -803,79 +716,6 @@ impl InvitationRepository for SqliteInvitationRepository {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
|
||||||
pub struct SqliteMealCategoryRepository;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl MealCategoryRepository for SqliteMealCategoryRepository {
|
|
||||||
async fn meal_categories(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<MealCategory>> {
|
|
||||||
let rows = sqlx::query(
|
|
||||||
"SELECT id, name
|
|
||||||
FROM meal_categories
|
|
||||||
ORDER BY position ASC, name COLLATE NOCASE ASC",
|
|
||||||
)
|
|
||||||
.fetch_all(&mut *txn)
|
|
||||||
.await
|
|
||||||
.map_err(db_error)?;
|
|
||||||
Ok(rows
|
|
||||||
.into_iter()
|
|
||||||
.map(|row| MealCategory {
|
|
||||||
id: row.get(0),
|
|
||||||
name: row.get(1),
|
|
||||||
})
|
|
||||||
.collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn create_meal_category(
|
|
||||||
&self,
|
|
||||||
txn: &mut SqliteConnection,
|
|
||||||
name: String,
|
|
||||||
) -> DomainResult<i64> {
|
|
||||||
let position: i64 =
|
|
||||||
sqlx::query("SELECT COALESCE(MAX(position), -1) + 1 FROM meal_categories")
|
|
||||||
.fetch_one(&mut *txn)
|
|
||||||
.await
|
|
||||||
.map_err(db_error)?
|
|
||||||
.get(0);
|
|
||||||
let result = sqlx::query(
|
|
||||||
"INSERT INTO meal_categories (name, position, created_at)
|
|
||||||
VALUES (?1, ?2, ?3)",
|
|
||||||
)
|
|
||||||
.bind(&name)
|
|
||||||
.bind(position)
|
|
||||||
.bind(now())
|
|
||||||
.execute(&mut *txn)
|
|
||||||
.await;
|
|
||||||
match result {
|
|
||||||
Ok(_) => {}
|
|
||||||
Err(error) if is_unique_violation(&error) => return Err(DomainError::Conflict),
|
|
||||||
Err(error) => return Err(db_error(error)),
|
|
||||||
}
|
|
||||||
Ok(sqlx::query("SELECT last_insert_rowid()")
|
|
||||||
.fetch_one(&mut *txn)
|
|
||||||
.await
|
|
||||||
.map_err(db_error)?
|
|
||||||
.get::<i64, _>(0))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn delete_meal_category(
|
|
||||||
&self,
|
|
||||||
txn: &mut SqliteConnection,
|
|
||||||
category_id: i64,
|
|
||||||
) -> DomainResult<()> {
|
|
||||||
let changed = sqlx::query("DELETE FROM meal_categories WHERE id = ?1")
|
|
||||||
.bind(category_id)
|
|
||||||
.execute(&mut *txn)
|
|
||||||
.await
|
|
||||||
.map_err(db_error)?
|
|
||||||
.rows_affected();
|
|
||||||
if changed == 0 {
|
|
||||||
return Err(DomainError::NotFound);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
pub struct SqliteMealRepository;
|
pub struct SqliteMealRepository;
|
||||||
|
|
||||||
@@ -886,16 +726,14 @@ impl MealRepository for SqliteMealRepository {
|
|||||||
txn: &mut SqliteConnection,
|
txn: &mut SqliteConnection,
|
||||||
name: String,
|
name: String,
|
||||||
description: String,
|
description: String,
|
||||||
category_id: Option<i64>,
|
|
||||||
) -> DomainResult<Meal> {
|
) -> DomainResult<Meal> {
|
||||||
let now = now();
|
let now = now();
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO meals (name, description, category_id, created_at, updated_at)
|
"INSERT INTO meals (name, description, created_at, updated_at)
|
||||||
VALUES (?1, ?2, ?3, ?4, ?4)",
|
VALUES (?1, ?2, ?3, ?3)",
|
||||||
)
|
)
|
||||||
.bind(&name)
|
.bind(&name)
|
||||||
.bind(&description)
|
.bind(&description)
|
||||||
.bind(category_id)
|
|
||||||
.bind(now)
|
.bind(now)
|
||||||
.execute(&mut *txn)
|
.execute(&mut *txn)
|
||||||
.await
|
.await
|
||||||
@@ -909,7 +747,6 @@ impl MealRepository for SqliteMealRepository {
|
|||||||
id,
|
id,
|
||||||
name,
|
name,
|
||||||
description,
|
description,
|
||||||
category_id,
|
|
||||||
ingredients: Vec::new(),
|
ingredients: Vec::new(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -920,7 +757,7 @@ impl MealRepository for SqliteMealRepository {
|
|||||||
meal_id: i64,
|
meal_id: i64,
|
||||||
) -> DomainResult<Option<Meal>> {
|
) -> DomainResult<Option<Meal>> {
|
||||||
let row = sqlx::query(
|
let row = sqlx::query(
|
||||||
"SELECT id, name, description, category_id
|
"SELECT id, name, description
|
||||||
FROM meals
|
FROM meals
|
||||||
WHERE id = ?1",
|
WHERE id = ?1",
|
||||||
)
|
)
|
||||||
@@ -935,7 +772,6 @@ impl MealRepository for SqliteMealRepository {
|
|||||||
id: row.get(0),
|
id: row.get(0),
|
||||||
name: row.get(1),
|
name: row.get(1),
|
||||||
description: row.get(2),
|
description: row.get(2),
|
||||||
category_id: row.get(3),
|
|
||||||
ingredients: Vec::new(),
|
ingredients: Vec::new(),
|
||||||
};
|
};
|
||||||
let ingredients = SqliteMealIngredientRepository
|
let ingredients = SqliteMealIngredientRepository
|
||||||
@@ -949,7 +785,7 @@ impl MealRepository for SqliteMealRepository {
|
|||||||
|
|
||||||
async fn list_meals(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<Meal>> {
|
async fn list_meals(&self, txn: &mut SqliteConnection) -> DomainResult<Vec<Meal>> {
|
||||||
let rows = sqlx::query(
|
let rows = sqlx::query(
|
||||||
"SELECT id, name, description, category_id
|
"SELECT id, name, description
|
||||||
FROM meals
|
FROM meals
|
||||||
ORDER BY name COLLATE NOCASE ASC",
|
ORDER BY name COLLATE NOCASE ASC",
|
||||||
)
|
)
|
||||||
@@ -962,7 +798,6 @@ impl MealRepository for SqliteMealRepository {
|
|||||||
id: row.get(0),
|
id: row.get(0),
|
||||||
name: row.get(1),
|
name: row.get(1),
|
||||||
description: row.get(2),
|
description: row.get(2),
|
||||||
category_id: row.get(3),
|
|
||||||
ingredients: Vec::new(),
|
ingredients: Vec::new(),
|
||||||
};
|
};
|
||||||
let ingredients = SqliteMealIngredientRepository
|
let ingredients = SqliteMealIngredientRepository
|
||||||
@@ -982,16 +817,14 @@ impl MealRepository for SqliteMealRepository {
|
|||||||
meal_id: i64,
|
meal_id: i64,
|
||||||
name: String,
|
name: String,
|
||||||
description: String,
|
description: String,
|
||||||
category_id: Option<i64>,
|
|
||||||
) -> DomainResult<()> {
|
) -> DomainResult<()> {
|
||||||
let changed = sqlx::query(
|
let changed = sqlx::query(
|
||||||
"UPDATE meals
|
"UPDATE meals
|
||||||
SET name = ?1, description = ?2, category_id = ?3, updated_at = ?4
|
SET name = ?1, description = ?2, updated_at = ?3
|
||||||
WHERE id = ?5",
|
WHERE id = ?4",
|
||||||
)
|
)
|
||||||
.bind(&name)
|
.bind(&name)
|
||||||
.bind(&description)
|
.bind(&description)
|
||||||
.bind(category_id)
|
|
||||||
.bind(now())
|
.bind(now())
|
||||||
.bind(meal_id)
|
.bind(meal_id)
|
||||||
.execute(&mut *txn)
|
.execute(&mut *txn)
|
||||||
@@ -1142,7 +975,10 @@ impl MealIngredientRepository for SqliteMealIngredientRepository {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn ensure_category(txn: &mut SqliteConnection, category_id: Option<i64>) -> DomainResult<()> {
|
async fn ensure_category(
|
||||||
|
txn: &mut SqliteConnection,
|
||||||
|
category_id: Option<i64>,
|
||||||
|
) -> DomainResult<()> {
|
||||||
let Some(category_id) = category_id else {
|
let Some(category_id) = category_id else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
@@ -1180,13 +1016,10 @@ const DEFAULT_CATEGORIES: &[&str] = &[
|
|||||||
"Household",
|
"Household",
|
||||||
];
|
];
|
||||||
|
|
||||||
const DEFAULT_MEAL_CATEGORIES: &[&str] =
|
fn hash_secret(secret: &str) -> String {
|
||||||
&["Beef", "Chicken", "Pasta", "Sandwiches", "Salads", "Soups"];
|
|
||||||
|
|
||||||
fn hash_secret(secret: &str) -> Vec<u8> {
|
|
||||||
let mut hasher = Sha256::new();
|
let mut hasher = Sha256::new();
|
||||||
hasher.update(secret.as_bytes());
|
hasher.update(secret.as_bytes());
|
||||||
hasher.finalize().to_vec()
|
hex::encode(hasher.finalize())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn now() -> i64 {
|
fn now() -> i64 {
|
||||||
@@ -1196,17 +1029,6 @@ fn now() -> i64 {
|
|||||||
.as_secs() as i64
|
.as_secs() as i64
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A random, high-entropy user handle used as the WebAuthn userHandle.
|
|
||||||
/// 32 random bytes, which is exactly the 64-byte maximum the WebAuthn spec
|
|
||||||
/// allows for a userHandle while still providing 256 bits of entropy. Opaque
|
|
||||||
/// and unguessable per the spec. Stored as raw bytes.
|
|
||||||
fn new_user_handle() -> Vec<u8> {
|
|
||||||
use rand::RngCore;
|
|
||||||
let mut bytes = [0_u8; 32];
|
|
||||||
rand::rngs::OsRng.fill_bytes(&mut bytes);
|
|
||||||
bytes.to_vec()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_unique_violation(error: &sqlx::Error) -> bool {
|
fn is_unique_violation(error: &sqlx::Error) -> bool {
|
||||||
error
|
error
|
||||||
.as_database_error()
|
.as_database_error()
|
||||||
@@ -1218,10 +1040,6 @@ fn db_error(error: sqlx::Error) -> DomainError {
|
|||||||
DomainError::Database(error.to_string())
|
DomainError::Database(error.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn migrate_error(error: sqlx::migrate::MigrateError) -> DomainError {
|
|
||||||
DomainError::Database(error.to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -1563,7 +1381,11 @@ mod tests {
|
|||||||
let id = db
|
let id = db
|
||||||
.run(move |txn| {
|
.run(move |txn| {
|
||||||
let categories = categories.clone();
|
let categories = categories.clone();
|
||||||
Box::pin(async move { categories.create_category(txn, "Bakery".into()).await })
|
Box::pin(async move {
|
||||||
|
categories
|
||||||
|
.create_category(txn, "Bakery".into())
|
||||||
|
.await
|
||||||
|
})
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -1578,125 +1400,34 @@ mod tests {
|
|||||||
let db = setup().await;
|
let db = setup().await;
|
||||||
let categories = SqliteCategoryRepository;
|
let categories = SqliteCategoryRepository;
|
||||||
let result = db
|
let result = db
|
||||||
.run(move |txn| {
|
|
||||||
let categories = categories.clone();
|
|
||||||
Box::pin(async move { categories.create_category(txn, "Produce".into()).await })
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
assert!(matches!(result, Err(DomainError::Conflict)));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- MealCategoryRepository ----
|
|
||||||
|
|
||||||
async fn get_meal_categories(db: &SqliteDatabase) -> Vec<MealCategory> {
|
|
||||||
let categories = SqliteMealCategoryRepository;
|
|
||||||
db.run(move |txn| {
|
|
||||||
let categories = categories.clone();
|
|
||||||
Box::pin(async move { categories.meal_categories(txn).await })
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn meal_categories_are_seeded_with_defaults() {
|
|
||||||
let db = setup().await;
|
|
||||||
let categories = get_meal_categories(&db).await;
|
|
||||||
let names = categories
|
|
||||||
.iter()
|
|
||||||
.map(|c| c.name.as_str())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
assert!(names.contains(&"Beef"));
|
|
||||||
assert!(names.contains(&"Chicken"));
|
|
||||||
assert!(names.contains(&"Pasta"));
|
|
||||||
assert!(names.contains(&"Sandwiches"));
|
|
||||||
assert!(names.contains(&"Salads"));
|
|
||||||
assert!(names.contains(&"Soups"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn create_meal_category_returns_id_and_lists() {
|
|
||||||
let db = setup().await;
|
|
||||||
let categories = SqliteMealCategoryRepository;
|
|
||||||
let id = db
|
|
||||||
.run(move |txn| {
|
.run(move |txn| {
|
||||||
let categories = categories.clone();
|
let categories = categories.clone();
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
categories
|
categories
|
||||||
.create_meal_category(txn, "Breakfast".into())
|
.create_category(txn, "Produce".into())
|
||||||
.await
|
.await
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
assert!(id > 0);
|
|
||||||
let cats = get_meal_categories(&db).await;
|
|
||||||
assert!(cats.iter().any(|c| c.id == id && c.name == "Breakfast"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn create_duplicate_meal_category_conflicts() {
|
|
||||||
let db = setup().await;
|
|
||||||
let categories = SqliteMealCategoryRepository;
|
|
||||||
let result = db
|
|
||||||
.run(move |txn| {
|
|
||||||
let categories = categories.clone();
|
|
||||||
Box::pin(async move { categories.create_meal_category(txn, "Beef".into()).await })
|
|
||||||
})
|
|
||||||
.await;
|
.await;
|
||||||
assert!(matches!(result, Err(DomainError::Conflict)));
|
assert!(matches!(result, Err(DomainError::Conflict)));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn delete_meal_category_cascades_to_null_on_meals() {
|
async fn category_by_name_resolves_globally() {
|
||||||
let db = setup().await;
|
let db = setup().await;
|
||||||
let categories = SqliteMealCategoryRepository;
|
let categories = SqliteCategoryRepository;
|
||||||
let category_id = db
|
let found = db
|
||||||
.run(move |txn| {
|
.run(move |txn| {
|
||||||
let categories = categories.clone();
|
let categories = categories.clone();
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
categories
|
categories
|
||||||
.create_meal_category(txn, "Breakfast".into())
|
.category_by_name(txn, "produce".into())
|
||||||
.await
|
.await
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let meal = create_meal(&db, "Pancakes").await;
|
assert_eq!(found.unwrap().name, "Produce");
|
||||||
let meals = SqliteMealRepository;
|
|
||||||
db.run(move |txn| {
|
|
||||||
let meals = meals.clone();
|
|
||||||
Box::pin(async move {
|
|
||||||
meals
|
|
||||||
.update_meal(
|
|
||||||
txn,
|
|
||||||
meal.id,
|
|
||||||
"Pancakes".into(),
|
|
||||||
String::new(),
|
|
||||||
Some(category_id),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
db.run(move |txn| {
|
|
||||||
let categories = categories.clone();
|
|
||||||
Box::pin(async move { categories.delete_meal_category(txn, category_id).await })
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let fetched = db
|
|
||||||
.run(move |txn| {
|
|
||||||
let meals = meals.clone();
|
|
||||||
Box::pin(async move { meals.get_meal(txn, meal.id).await })
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(fetched.category_id, None);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- ItemRepository ----
|
// ---- ItemRepository ----
|
||||||
@@ -2048,7 +1779,7 @@ mod tests {
|
|||||||
let name = name.to_owned();
|
let name = name.to_owned();
|
||||||
db.run(move |txn| {
|
db.run(move |txn| {
|
||||||
let meals = meals.clone();
|
let meals = meals.clone();
|
||||||
Box::pin(async move { meals.create_meal(txn, name, String::new(), None).await })
|
Box::pin(async move { meals.create_meal(txn, name, String::new()).await })
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@@ -2166,13 +1897,7 @@ mod tests {
|
|||||||
let meals = meals.clone();
|
let meals = meals.clone();
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
meals
|
meals
|
||||||
.update_meal(
|
.update_meal(txn, meal.id, "Pasta al pomodoro".into(), "desc".into())
|
||||||
txn,
|
|
||||||
meal.id,
|
|
||||||
"Pasta al pomodoro".into(),
|
|
||||||
"desc".into(),
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
.await
|
.await
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -2199,7 +1924,7 @@ mod tests {
|
|||||||
let meals = meals.clone();
|
let meals = meals.clone();
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
meals
|
meals
|
||||||
.update_meal(txn, 9999, "X".into(), String::new(), None)
|
.update_meal(txn, 9999, "X".into(), String::new())
|
||||||
.await
|
.await
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -2252,14 +1977,7 @@ mod tests {
|
|||||||
let ingredients = ingredients.clone();
|
let ingredients = ingredients.clone();
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
ingredients
|
ingredients
|
||||||
.add_ingredient(
|
.add_ingredient(txn, meal.id, "X".into(), String::new(), String::new(), Some(9999))
|
||||||
txn,
|
|
||||||
meal.id,
|
|
||||||
"X".into(),
|
|
||||||
String::new(),
|
|
||||||
String::new(),
|
|
||||||
Some(9999),
|
|
||||||
)
|
|
||||||
.await
|
.await
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -2336,110 +2054,12 @@ mod tests {
|
|||||||
let result = db
|
let result = db
|
||||||
.run(move |txn| {
|
.run(move |txn| {
|
||||||
let ingredients = ingredients.clone();
|
let ingredients = ingredients.clone();
|
||||||
Box::pin(async move { ingredients.delete_ingredient(txn, meal.id, 9999).await })
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
assert!(matches!(result, Err(DomainError::NotFound)));
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- PasskeyRepository ----
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn passkey_crud_roundtrip() {
|
|
||||||
let db = setup().await;
|
|
||||||
let user = create_user(&db, "alice@example.com").await;
|
|
||||||
let passkeys = SqlitePasskeyRepository;
|
|
||||||
|
|
||||||
let created = db
|
|
||||||
.run(move |txn| {
|
|
||||||
let passkeys = passkeys.clone();
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
passkeys
|
ingredients
|
||||||
.create_passkey(txn, user.id, "cred-1".into(), "{}".into(), 0)
|
.delete_ingredient(txn, meal.id, 9999)
|
||||||
.await
|
.await
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
assert!(created.id > 0);
|
|
||||||
assert_eq!(created.user_id, user.id);
|
|
||||||
assert_eq!(created.credential_id, "cred-1");
|
|
||||||
|
|
||||||
let found = db
|
|
||||||
.run(move |txn| {
|
|
||||||
let passkeys = passkeys.clone();
|
|
||||||
Box::pin(async move { passkeys.find_by_credential_id(txn, "cred-1".into()).await })
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(found.id, created.id);
|
|
||||||
|
|
||||||
let listed = db
|
|
||||||
.run(move |txn| {
|
|
||||||
let passkeys = passkeys.clone();
|
|
||||||
Box::pin(async move { passkeys.list_for_user(txn, user.id).await })
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(listed.len(), 1);
|
|
||||||
|
|
||||||
db.run(move |txn| {
|
|
||||||
let passkeys = passkeys.clone();
|
|
||||||
Box::pin(async move { passkeys.delete_passkey(txn, user.id, created.id).await })
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let after = db
|
|
||||||
.run(move |txn| {
|
|
||||||
let passkeys = passkeys.clone();
|
|
||||||
Box::pin(async move { passkeys.list_for_user(txn, user.id).await })
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
assert!(after.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn duplicate_passkey_credential_id_conflicts() {
|
|
||||||
let db = setup().await;
|
|
||||||
let user = create_user(&db, "alice@example.com").await;
|
|
||||||
let passkeys = SqlitePasskeyRepository;
|
|
||||||
db.run(move |txn| {
|
|
||||||
let passkeys = passkeys.clone();
|
|
||||||
Box::pin(async move {
|
|
||||||
passkeys
|
|
||||||
.create_passkey(txn, user.id, "cred-1".into(), "{}".into(), 0)
|
|
||||||
.await
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let result = db
|
|
||||||
.run(move |txn| {
|
|
||||||
let passkeys = passkeys.clone();
|
|
||||||
Box::pin(async move {
|
|
||||||
passkeys
|
|
||||||
.create_passkey(txn, user.id, "cred-1".into(), "{}".into(), 0)
|
|
||||||
.await
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
assert!(matches!(result, Err(DomainError::Conflict)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn delete_missing_passkey_fails() {
|
|
||||||
let db = setup().await;
|
|
||||||
let user = create_user(&db, "alice@example.com").await;
|
|
||||||
let passkeys = SqlitePasskeyRepository;
|
|
||||||
let result = db
|
|
||||||
.run(move |txn| {
|
|
||||||
let passkeys = passkeys.clone();
|
|
||||||
Box::pin(async move { passkeys.delete_passkey(txn, user.id, 9999).await })
|
|
||||||
})
|
|
||||||
.await;
|
.await;
|
||||||
assert!(matches!(result, Err(DomainError::NotFound)));
|
assert!(matches!(result, Err(DomainError::NotFound)));
|
||||||
}
|
}
|
||||||
|
|||||||
+79
-293
@@ -3,7 +3,7 @@ use pulldown_cmark::{Options, Parser, html as cmark_html};
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
domain::PresenceUser,
|
domain::PresenceUser,
|
||||||
domain::{Category, GroceryList, Item, Meal, MealCategory, MealIngredient, Passkey, User},
|
domain::{Category, GroceryList, Item, Meal, MealIngredient, User},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn login_page(error: Option<&str>, invite: Option<&str>) -> Markup {
|
pub fn login_page(error: Option<&str>, invite: Option<&str>) -> Markup {
|
||||||
@@ -23,20 +23,13 @@ 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" autofocus;
|
input id="email" name="email" type="email" autocomplete="email" required autofocus;
|
||||||
label for="password" { "Password" }
|
label for="password" { "Password" }
|
||||||
div class="password-field" {
|
input id="password" name="password" type="password" autocomplete="current-password" required;
|
||||||
input id="password" name="password" type="password" autocomplete="current-password" required;
|
|
||||||
button class="password-toggle" type="button" data-toggle-for="password" aria-label="Show password" { "Show" }
|
|
||||||
}
|
|
||||||
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/password-toggle.js" {}
|
|
||||||
script src="/static/passkey-login.js" {}
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -62,15 +55,11 @@ 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" }
|
||||||
div class="password-field" {
|
input id="password" name="password" type="password" autocomplete="new-password" required;
|
||||||
input id="password" name="password" type="password" autocomplete="new-password" required;
|
|
||||||
button class="password-toggle" type="button" data-toggle-for="password" aria-label="Show password" { "Show" }
|
|
||||||
}
|
|
||||||
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" } }
|
||||||
}
|
}
|
||||||
script src="/static/password-toggle.js" {}
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -90,84 +79,6 @@ pub fn registration_closed_page() -> Markup {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn account_page(
|
|
||||||
user: &User,
|
|
||||||
passkeys: &[Passkey],
|
|
||||||
csrf_token: &str,
|
|
||||||
password_error: Option<&str>,
|
|
||||||
password_success: bool,
|
|
||||||
) -> 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" }
|
|
||||||
}
|
|
||||||
section class="panel" {
|
|
||||||
div class="panel-heading" {
|
|
||||||
h2 { "Password" }
|
|
||||||
}
|
|
||||||
p { "Set a new password for your account." }
|
|
||||||
@if let Some(error) = password_error {
|
|
||||||
div class="alert alert-error" role="alert" { (error) }
|
|
||||||
}
|
|
||||||
@if password_success {
|
|
||||||
div class="alert alert-success" role="alert" { "Your password has been updated." }
|
|
||||||
}
|
|
||||||
form method="post" action="/account/password" class="stack" {
|
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
|
||||||
label for="new-password" { "New password" }
|
|
||||||
div class="password-field" {
|
|
||||||
input id="new-password" name="new_password" type="password" autocomplete="new-password" required;
|
|
||||||
button class="password-toggle" type="button" data-toggle-for="new-password" aria-label="Show password" { "Show" }
|
|
||||||
}
|
|
||||||
label for="confirm-password" { "Confirm new password" }
|
|
||||||
div class="password-field" {
|
|
||||||
input id="confirm-password" name="confirm_password" type="password" autocomplete="new-password" required;
|
|
||||||
button class="password-toggle" type="button" data-toggle-for="confirm-password" aria-label="Show password" { "Show" }
|
|
||||||
}
|
|
||||||
button class="button button-primary" type="submit" { "Update password" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
script src="/static/password-toggle.js" {}
|
|
||||||
script src="/static/passkey-register.js" {}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn lists_page(user: &User, lists: &[GroceryList], csrf_token: &str) -> Markup {
|
pub fn lists_page(user: &User, lists: &[GroceryList], csrf_token: &str) -> Markup {
|
||||||
page(
|
page(
|
||||||
"Your lists",
|
"Your lists",
|
||||||
@@ -234,12 +145,7 @@ pub fn lists_page(user: &User, lists: &[GroceryList], csrf_token: &str) -> Marku
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn meals_page(
|
pub fn meals_page(user: &User, meals: &[Meal]) -> Markup {
|
||||||
user: &User,
|
|
||||||
meals: &[Meal],
|
|
||||||
meal_categories: &[MealCategory],
|
|
||||||
csrf_token: &str,
|
|
||||||
) -> Markup {
|
|
||||||
page(
|
page(
|
||||||
"Meals",
|
"Meals",
|
||||||
Some(user),
|
Some(user),
|
||||||
@@ -252,13 +158,6 @@ pub fn meals_page(
|
|||||||
}
|
}
|
||||||
a class="button button-primary" href="/meals/new" { "New meal" }
|
a class="button button-primary" href="/meals/new" { "New meal" }
|
||||||
}
|
}
|
||||||
@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." }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
div class="dashboard-grid" {
|
div class="dashboard-grid" {
|
||||||
section class="panel" {
|
section class="panel" {
|
||||||
div class="panel-heading" {
|
div class="panel-heading" {
|
||||||
@@ -266,52 +165,21 @@ pub fn meals_page(
|
|||||||
span class="count-badge" { (meals.len()) }
|
span class="count-badge" { (meals.len()) }
|
||||||
}
|
}
|
||||||
@if meals.is_empty() {
|
@if meals.is_empty() {
|
||||||
p class="muted" { "Create a meal to get started." }
|
div class="empty-state" {
|
||||||
|
div class="empty-mark" { "🍽" }
|
||||||
|
h3 { "No meals yet" }
|
||||||
|
p { "Create a meal to reuse its ingredients across your lists." }
|
||||||
|
}
|
||||||
} @else {
|
} @else {
|
||||||
@for (category_name, category_meals) in meal_groups(meals, meal_categories) {
|
div class="list-cards" {
|
||||||
div class="category-group" {
|
@for meal in meals {
|
||||||
div class="category-heading" {
|
a class="list-card" href=(format!("/meals/{}", meal.id)) {
|
||||||
h3 { (category_name) " (" (category_meals.len()) ")" }
|
span class="list-card-icon" { "🍽" }
|
||||||
}
|
span class="list-card-copy" {
|
||||||
div class="list-cards" {
|
strong { (meal.name) }
|
||||||
@for meal in category_meals {
|
small { (meal.ingredients.len()) " ingredients" }
|
||||||
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" { "→" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
aside class="side-column" {
|
|
||||||
section class="panel categories-panel" {
|
|
||||||
div class="panel-heading" {
|
|
||||||
h2 { "Meal categories" }
|
|
||||||
}
|
|
||||||
p { "Organize meals by type." }
|
|
||||||
form method="post" action="/meals/categories" class="category-form" {
|
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
|
||||||
input name="name" type="text" maxlength="60" placeholder="New category" required;
|
|
||||||
button class="button button-small button-secondary" type="submit" { "Add" }
|
|
||||||
}
|
|
||||||
@if meal_categories.is_empty() {
|
|
||||||
p class="muted category-empty" { "No categories yet." }
|
|
||||||
} @else {
|
|
||||||
div class="meal-category-list" {
|
|
||||||
@for category in meal_categories {
|
|
||||||
div class="meal-category-row" {
|
|
||||||
span class="meal-category-name" { (category.name) }
|
|
||||||
form method="post" action=(format!("/meals/categories/{}/delete", category.id)) {
|
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
|
||||||
button class="meal-category-delete" type="submit" aria-label=(format!("Delete {}", category.name)) { "✕" }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
span class="list-card-arrow" { "→" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -322,47 +190,7 @@ pub fn meals_page(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn meal_groups<'a>(
|
pub fn meal_picker(meals: &[Meal], list_id: i64, csrf_token: &str) -> Markup {
|
||||||
meals: &'a [Meal],
|
|
||||||
meal_categories: &[MealCategory],
|
|
||||||
) -> Vec<(String, Vec<&'a Meal>)> {
|
|
||||||
let mut groups = Vec::new();
|
|
||||||
for category in meal_categories {
|
|
||||||
let in_category = meals
|
|
||||||
.iter()
|
|
||||||
.filter(|meal| meal.category_id == Some(category.id))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
if !in_category.is_empty() {
|
|
||||||
groups.push((category.name.clone(), in_category));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let uncategorized = meals
|
|
||||||
.iter()
|
|
||||||
.filter(|meal| meal.category_id.is_none())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
if !uncategorized.is_empty() {
|
|
||||||
groups.push(("Uncategorized".into(), uncategorized));
|
|
||||||
}
|
|
||||||
groups
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the display name of a meal's category, if it has one.
|
|
||||||
fn meal_category_name(meal: &Meal, meal_categories: &[MealCategory]) -> Option<String> {
|
|
||||||
meal.category_id.and_then(|id| {
|
|
||||||
meal_categories
|
|
||||||
.iter()
|
|
||||||
.find(|category| category.id == id)
|
|
||||||
.map(|category| category.name.clone())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn meal_picker(
|
|
||||||
meals: &[Meal],
|
|
||||||
meal_categories: &[MealCategory],
|
|
||||||
list_id: i64,
|
|
||||||
csrf_token: &str,
|
|
||||||
) -> Markup {
|
|
||||||
html! {
|
html! {
|
||||||
div class="meal-picker-backdrop" onclick="if (event.target === this) this.remove()" {
|
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-modal" role="dialog" aria-modal="true" aria-label="Add a meal" {
|
||||||
@@ -382,30 +210,23 @@ pub fn meal_picker(
|
|||||||
}
|
}
|
||||||
} @else {
|
} @else {
|
||||||
div class="meal-picker-list" {
|
div class="meal-picker-list" {
|
||||||
@for (category_name, category_meals) in meal_groups(meals, meal_categories) {
|
@for meal in meals {
|
||||||
div class="category-group" {
|
form
|
||||||
div class="category-heading" {
|
hx-post=(format!("/lists/{}/add-meal", list_id))
|
||||||
h3 { (category_name) }
|
hx-target="#list-items"
|
||||||
}
|
hx-swap="outerHTML"
|
||||||
@for meal in category_meals {
|
hx-on::after-request="if (event.detail.successful) this.closest('.meal-picker-backdrop').remove()"
|
||||||
form
|
class="meal-picker-row"
|
||||||
hx-post=(format!("/lists/{}/add-meal", list_id))
|
{
|
||||||
hx-target="#list-items"
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
hx-swap="outerHTML"
|
input type="hidden" name="meal_id" value=(meal.id);
|
||||||
hx-on::after-request="if (event.detail.successful) this.closest('.meal-picker-backdrop').remove()"
|
button class="meal-picker-button" type="submit" {
|
||||||
class="meal-picker-row"
|
span class="meal-picker-icon" { "🍽" }
|
||||||
{
|
span class="meal-picker-copy" {
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
strong { (meal.name) }
|
||||||
input type="hidden" name="meal_id" value=(meal.id);
|
small { (meal.ingredients.len()) " ingredients" }
|
||||||
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" }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
span class="meal-picker-add" { "Add" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -419,24 +240,16 @@ pub fn meal_picker(
|
|||||||
pub fn meal_form_page(
|
pub fn meal_form_page(
|
||||||
user: &User,
|
user: &User,
|
||||||
meal: Option<&Meal>,
|
meal: Option<&Meal>,
|
||||||
meal_categories: &[MealCategory],
|
|
||||||
csrf_token: &str,
|
csrf_token: &str,
|
||||||
) -> Markup {
|
) -> Markup {
|
||||||
let (title, action, name, description, category_id) = match meal {
|
let (title, action, name, description) = match meal {
|
||||||
Some(meal) => (
|
Some(meal) => (
|
||||||
"Edit meal",
|
"Edit meal",
|
||||||
format!("/meals/{}/edit", meal.id),
|
format!("/meals/{}/edit", meal.id),
|
||||||
meal.name.clone(),
|
meal.name.clone(),
|
||||||
meal.description.clone(),
|
meal.description.clone(),
|
||||||
meal.category_id,
|
|
||||||
),
|
|
||||||
None => (
|
|
||||||
"New meal",
|
|
||||||
"/meals".into(),
|
|
||||||
String::new(),
|
|
||||||
String::new(),
|
|
||||||
None,
|
|
||||||
),
|
),
|
||||||
|
None => ("New meal", "/meals".into(), String::new(), String::new()),
|
||||||
};
|
};
|
||||||
page(
|
page(
|
||||||
title,
|
title,
|
||||||
@@ -451,21 +264,6 @@ pub fn meal_form_page(
|
|||||||
input type="hidden" name="csrf" value=(csrf_token);
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
label for="meal-name" { "Name" }
|
label for="meal-name" { "Name" }
|
||||||
input id="meal-name" name="name" type="text" maxlength="120" value=(name) required;
|
input id="meal-name" name="name" type="text" maxlength="120" value=(name) required;
|
||||||
label for="meal-category" { "Category" }
|
|
||||||
select id="meal-category" name="category_id" {
|
|
||||||
@if category_id.is_none() {
|
|
||||||
option value="" selected { "Uncategorized" }
|
|
||||||
} @else {
|
|
||||||
option value="" { "Uncategorized" }
|
|
||||||
}
|
|
||||||
@for category in meal_categories {
|
|
||||||
@if category_id == Some(category.id) {
|
|
||||||
option value=(category.id) selected { (category.name) }
|
|
||||||
} @else {
|
|
||||||
option value=(category.id) { (category.name) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
label for="meal-description" { "Description (markdown)" }
|
label for="meal-description" { "Description (markdown)" }
|
||||||
textarea id="meal-description" name="description" rows="8" { (description) }
|
textarea id="meal-description" name="description" rows="8" { (description) }
|
||||||
button class="button button-primary" type="submit" { "Save meal" }
|
button class="button button-primary" type="submit" { "Save meal" }
|
||||||
@@ -482,7 +280,6 @@ pub fn meal_page(
|
|||||||
user: &User,
|
user: &User,
|
||||||
meal: &Meal,
|
meal: &Meal,
|
||||||
categories: &[Category],
|
categories: &[Category],
|
||||||
meal_categories: &[MealCategory],
|
|
||||||
csrf_token: &str,
|
csrf_token: &str,
|
||||||
) -> Markup {
|
) -> Markup {
|
||||||
page(
|
page(
|
||||||
@@ -508,25 +305,10 @@ pub fn meal_page(
|
|||||||
form method="post" action=(format!("/meals/{}/edit", meal.id)) class="stack" {
|
form method="post" action=(format!("/meals/{}/edit", meal.id)) class="stack" {
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
label { "Name" }
|
label { "Name" }
|
||||||
input id="meal-edit-name" name="name" value=(meal.name) maxlength="120" required;
|
input name="name" value=(meal.name) maxlength="120" required;
|
||||||
label { "Category" }
|
|
||||||
select id="meal-edit-category" name="category_id" {
|
|
||||||
@if meal.category_id.is_none() {
|
|
||||||
option value="" selected { "Uncategorized" }
|
|
||||||
} @else {
|
|
||||||
option value="" { "Uncategorized" }
|
|
||||||
}
|
|
||||||
@for category in meal_categories {
|
|
||||||
@if meal.category_id == Some(category.id) {
|
|
||||||
option value=(category.id) selected { (category.name) }
|
|
||||||
} @else {
|
|
||||||
option value=(category.id) { (category.name) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
label { "Description (markdown)" }
|
label { "Description (markdown)" }
|
||||||
textarea id="meal-edit-description" name="description" rows="8" { (meal.description) }
|
textarea name="description" rows="8" { (meal.description) }
|
||||||
button id="meal-edit-save" class="button button-primary" type="submit" { "Save meal" }
|
button class="button button-primary" type="submit" { "Save meal" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -535,7 +317,7 @@ pub fn meal_page(
|
|||||||
div class="list-heading" {
|
div class="list-heading" {
|
||||||
div {
|
div {
|
||||||
p class="eyebrow" { "MEAL" }
|
p class="eyebrow" { "MEAL" }
|
||||||
h1 { (meal.name) @if let Some(category_name) = meal_category_name(meal, meal_categories) { span class="meal-category-label" { "(" (category_name) ")" } } }
|
h1 { (meal.name) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@if meal.description.is_empty() {
|
@if meal.description.is_empty() {
|
||||||
@@ -543,7 +325,7 @@ pub fn meal_page(
|
|||||||
} @else {
|
} @else {
|
||||||
div class="markdown" { (render_markdown(&meal.description)) }
|
div class="markdown" { (render_markdown(&meal.description)) }
|
||||||
}
|
}
|
||||||
hr class="ingredients-divider" {}
|
h2 class="category-heading" { "Ingredients" }
|
||||||
@if meal.ingredients.is_empty() {
|
@if meal.ingredients.is_empty() {
|
||||||
p class="muted" { "No ingredients yet." }
|
p class="muted" { "No ingredients yet." }
|
||||||
} @else {
|
} @else {
|
||||||
@@ -557,19 +339,19 @@ pub fn meal_page(
|
|||||||
aside class="side-column" {
|
aside class="side-column" {
|
||||||
section class="panel" {
|
section class="panel" {
|
||||||
div class="panel-heading" { h2 { "Add ingredient" } }
|
div class="panel-heading" { h2 { "Add ingredient" } }
|
||||||
form id="add-ingredient-form" method="post" action=(format!("/meals/{}/ingredients", meal.id)) class="stack" {
|
form method="post" action=(format!("/meals/{}/ingredients", meal.id)) class="stack" {
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
label { "Name" }
|
label { "Name" }
|
||||||
input id="ingredient-name" name="name" type="text" maxlength="120" required;
|
input name="name" type="text" maxlength="120" required;
|
||||||
|
label { "Quantity" }
|
||||||
|
input name="quantity" type="text" maxlength="40";
|
||||||
|
label { "Note" }
|
||||||
|
input name="note" type="text" maxlength="120";
|
||||||
label { "Category" }
|
label { "Category" }
|
||||||
select id="ingredient-category" name="category_id" {
|
select name="category_id" {
|
||||||
(category_options(categories, None))
|
(category_options(categories, None))
|
||||||
}
|
}
|
||||||
label { "Quantity" }
|
button class="button button-primary" type="submit" { "Add ingredient" }
|
||||||
input id="ingredient-quantity" name="quantity" type="text" maxlength="40";
|
|
||||||
label { "Note" }
|
|
||||||
input id="ingredient-note" name="note" type="text" maxlength="120";
|
|
||||||
button id="add-ingredient-button" class="button button-primary" type="submit" { "Add ingredient" }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -609,20 +391,20 @@ fn ingredient_row(
|
|||||||
{
|
{
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
label { "Name" }
|
label { "Name" }
|
||||||
input id=(format!("ingredient-edit-name-{}", ingredient.id)) name="name" value=(ingredient.name) maxlength="120" required;
|
input name="name" value=(ingredient.name) maxlength="120" required;
|
||||||
|
label { "Quantity" }
|
||||||
|
input name="quantity" value=(ingredient.quantity) maxlength="40";
|
||||||
|
label { "Note" }
|
||||||
|
input name="note" value=(ingredient.note) maxlength="120";
|
||||||
label { "Category" }
|
label { "Category" }
|
||||||
select id=(format!("ingredient-edit-category-{}", ingredient.id)) name="category_id" {
|
select name="category_id" {
|
||||||
(category_options(categories, ingredient.category_id))
|
(category_options(categories, ingredient.category_id))
|
||||||
}
|
}
|
||||||
label { "Quantity" }
|
button class="button button-primary" type="submit" { "Save" }
|
||||||
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";
|
|
||||||
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)) {
|
form method="post" action=(format!("/meals/{}/ingredients/{}/delete", meal_id, ingredient.id)) {
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
button id=(format!("ingredient-edit-delete-{}", ingredient.id)) class="button button-danger" type="submit" { "Remove" }
|
button class="danger-link" type="submit" { "Remove" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -791,11 +573,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;
|
||||||
select id="item-category" name="category_id" aria-label="Category" {
|
input name="quantity" type="text" maxlength="40" placeholder="Qty" aria-label="Quantity";
|
||||||
|
select name="category_id" aria-label="Category" {
|
||||||
(category_options(categories, None))
|
(category_options(categories, None))
|
||||||
}
|
}
|
||||||
input id="item-quantity" name="quantity" type="text" maxlength="40" placeholder="Qty" aria-label="Quantity";
|
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))
|
||||||
}
|
}
|
||||||
@@ -891,11 +673,11 @@ fn item_row(item: &Item, categories: &[Category], csrf_token: &str) -> Markup {
|
|||||||
{
|
{
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
input type="hidden" name="checked" value=(next_checked);
|
input type="hidden" name="checked" value=(next_checked);
|
||||||
button id=(format!("item-check-{}", item.id)) class="check-button" type="submit" aria-label=(if item.checked { "Mark unchecked" } else { "Mark complete" }) {
|
button class="check-button" type="submit" aria-label=(if item.checked { "Mark unchecked" } else { "Mark complete" }) {
|
||||||
@if item.checked { "✓" } @else { "" }
|
@if item.checked { "✓" } @else { "" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
label class="item-copy" for=(format!("item-check-{}", item.id)) {
|
div class="item-copy" {
|
||||||
@if !item.quantity.is_empty() {
|
@if !item.quantity.is_empty() {
|
||||||
span class="item-qty" { "(" (item.quantity) ")" }
|
span class="item-qty" { "(" (item.quantity) ")" }
|
||||||
}
|
}
|
||||||
@@ -919,16 +701,16 @@ 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);
|
||||||
label { "Name" }
|
label { "Name" }
|
||||||
input id=(format!("item-edit-name-{}", item.id)) name="name" value=(item.name) maxlength="120" required;
|
input name="name" value=(item.name) maxlength="120" required;
|
||||||
|
label { "Quantity" }
|
||||||
|
input name="quantity" value=(item.quantity) maxlength="40";
|
||||||
|
label { "Note" }
|
||||||
|
input name="note" value=(item.note) maxlength="120";
|
||||||
label { "Category" }
|
label { "Category" }
|
||||||
select id=(format!("item-edit-category-{}", item.id)) name="category_id" {
|
select name="category_id" {
|
||||||
(category_options(categories, item.category_id))
|
(category_options(categories, item.category_id))
|
||||||
}
|
}
|
||||||
label { "Quantity" }
|
button class="button button-primary" type="submit" { "Save" }
|
||||||
input id=(format!("item-edit-quantity-{}", item.id)) name="quantity" value=(item.quantity) maxlength="40";
|
|
||||||
label { "Note" }
|
|
||||||
input id=(format!("item-edit-note-{}", item.id)) name="note" value=(item.note) maxlength="120";
|
|
||||||
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))
|
||||||
@@ -936,7 +718,7 @@ fn item_row(item: &Item, categories: &[Category], csrf_token: &str) -> Markup {
|
|||||||
hx-swap="outerHTML"
|
hx-swap="outerHTML"
|
||||||
{
|
{
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
button id=(format!("item-edit-delete-{}", item.id)) class="button button-danger" type="submit" { "Remove item" }
|
button class="danger-link" type="submit" { "Remove item" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -961,7 +743,11 @@ fn category_options(categories: &[Category], selected: Option<i64>) -> Markup {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn categories_panel(categories: &[Category], csrf_token: &str, out_of_band: bool) -> Markup {
|
pub fn categories_panel(
|
||||||
|
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" }
|
||||||
@@ -976,8 +762,8 @@ pub fn categories_panel(categories: &[Category], csrf_token: &str, out_of_band:
|
|||||||
class="category-form"
|
class="category-form"
|
||||||
{
|
{
|
||||||
input type="hidden" name="csrf" value=(csrf_token);
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
input id="category-name" name="name" type="text" maxlength="60" placeholder="Add a category" required;
|
input name="name" type="text" maxlength="60" placeholder="Add a category" required;
|
||||||
button id="add-category-button" class="button button-small button-secondary" type="submit" { "Add" }
|
button class="button button-small button-secondary" type="submit" { "Add" }
|
||||||
}
|
}
|
||||||
@if categories.is_empty() {
|
@if categories.is_empty() {
|
||||||
p class="muted category-empty" { "No categories yet." }
|
p class="muted category-empty" { "No categories yet." }
|
||||||
@@ -1134,7 +920,7 @@ fn page(title: &str, user: Option<&User>, content: Markup) -> Markup {
|
|||||||
a href="/meals" { "Meals" }
|
a href="/meals" { "Meals" }
|
||||||
}
|
}
|
||||||
div class="account-nav" {
|
div class="account-nav" {
|
||||||
a class="user-name" href="/account" { (user.display_name) }
|
span class="user-name" { (user.display_name) }
|
||||||
form method="post" action="/logout" {
|
form method="post" action="/logout" {
|
||||||
button class="text-button" type="submit" { "Sign out" }
|
button class="text-button" type="submit" { "Sign out" }
|
||||||
}
|
}
|
||||||
|
|||||||
-340
@@ -1,340 +0,0 @@
|
|||||||
use std::collections::HashMap;
|
|
||||||
use std::sync::{Arc, Mutex};
|
|
||||||
|
|
||||||
use webauthn_rs::{
|
|
||||||
Webauthn,
|
|
||||||
core::{AuthenticationState, RegistrationState, WebauthnConfig},
|
|
||||||
error::WebauthnError as WanError,
|
|
||||||
proto::{
|
|
||||||
CreationChallengeResponse, Credential, PublicKeyCredential, RegisterPublicKeyCredential,
|
|
||||||
RequestChallengeResponse, 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())
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
function b64ToBytes(b64) {
|
|
||||||
const bin = atob(b64.replace(/-/g, "+").replace(/_/g, "/"));
|
|
||||||
const bytes = new Uint8Array(bin.length);
|
|
||||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
|
||||||
return bytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
document.getElementById("passkey-login").addEventListener("click", async () => {
|
|
||||||
const email = document.getElementById("email").value.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";
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
function b64ToBytes(b64) {
|
|
||||||
const bin = atob(b64.replace(/-/g, "+").replace(/_/g, "/"));
|
|
||||||
const bytes = new Uint8Array(bin.length);
|
|
||||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
|
||||||
return bytes;
|
|
||||||
}
|
|
||||||
|
|
||||||
document.getElementById("add-passkey").addEventListener("click", async () => {
|
|
||||||
const csrf = document.getElementById("add-passkey").dataset.csrf;
|
|
||||||
const start = await fetch("/auth/passkey/register/start", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ csrf }),
|
|
||||||
});
|
|
||||||
const options = await start.json();
|
|
||||||
const pk = options.publicKey;
|
|
||||||
pk.challenge = b64ToBytes(pk.challenge);
|
|
||||||
pk.user.id = b64ToBytes(pk.user.id);
|
|
||||||
if (pk.excludeCredentials) {
|
|
||||||
pk.excludeCredentials.forEach((c) => (c.id = b64ToBytes(c.id)));
|
|
||||||
}
|
|
||||||
const credential = await navigator.credentials.create(options);
|
|
||||||
const response = { csrf, response: credential };
|
|
||||||
const finish = await fetch("/auth/passkey/register/finish", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify(response),
|
|
||||||
});
|
|
||||||
if (finish.ok) {
|
|
||||||
window.location.href = "/account";
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
// Toggle password visibility so users can check for typos, especially on mobile.
|
|
||||||
document.querySelectorAll(".password-toggle").forEach(function (button) {
|
|
||||||
button.addEventListener("pointerdown", function (event) {
|
|
||||||
// Toggle on press (not click) for an instant response. preventScroll avoids
|
|
||||||
// a scroll-to-input animation that makes rapid toggling feel laggy, and
|
|
||||||
// keeping focus on the input keeps the mobile keyboard open.
|
|
||||||
event.preventDefault();
|
|
||||||
var input = document.getElementById(button.getAttribute("data-toggle-for"));
|
|
||||||
if (!input) return;
|
|
||||||
var showing = input.type === "text";
|
|
||||||
input.type = showing ? "password" : "text";
|
|
||||||
button.textContent = showing ? "Show" : "Hide";
|
|
||||||
button.setAttribute("aria-label", showing ? "Show password" : "Hide password");
|
|
||||||
input.focus({ preventScroll: true });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
+2
-29
@@ -51,8 +51,7 @@ a { color: inherit; }
|
|||||||
}
|
}
|
||||||
.site-nav a:hover { color: var(--ink); background: #eef2ea; }
|
.site-nav a:hover { color: var(--ink); background: #eef2ea; }
|
||||||
.account-nav { display: flex; align-items: center; gap: 16px; color: var(--muted); font-size: .9rem; }
|
.account-nav { display: flex; align-items: center; gap: 16px; color: var(--muted); font-size: .9rem; }
|
||||||
.user-name { color: var(--ink); font-weight: 700; text-decoration: none; }
|
.user-name { color: var(--ink); font-weight: 700; }
|
||||||
.user-name:hover { color: var(--deep-sage); }
|
|
||||||
.text-button { border: 0; padding: 0; color: var(--deep-sage); background: transparent; cursor: pointer; font-weight: 700; }
|
.text-button { border: 0; padding: 0; color: var(--deep-sage); background: transparent; cursor: pointer; font-weight: 700; }
|
||||||
|
|
||||||
.site-main { width: min(1120px, calc(100% - 40px)); margin: 30px auto 80px; }
|
.site-main { width: min(1120px, calc(100% - 40px)); margin: 30px auto 80px; }
|
||||||
@@ -75,14 +74,6 @@ h3 { margin-bottom: 6px; font-size: 1rem; }
|
|||||||
.stack label { color: var(--muted); font-size: .82rem; font-weight: 700; }
|
.stack label { color: var(--muted); font-size: .82rem; font-weight: 700; }
|
||||||
input { width: 100%; min-height: 46px; padding: 10px 13px; border: 1px solid var(--line); border-radius: 12px; outline: none; color: var(--ink); background: #fff; }
|
input { width: 100%; min-height: 46px; padding: 10px 13px; border: 1px solid var(--line); border-radius: 12px; outline: none; color: var(--ink); background: #fff; }
|
||||||
input:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85, 113, 93, .12); }
|
input:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85, 113, 93, .12); }
|
||||||
.password-field { position: relative; }
|
|
||||||
.password-field input { padding-right: 64px; }
|
|
||||||
.password-toggle { position: absolute; top: 50%; right: 8px; transform: translateY(-50%); min-height: 32px; padding: 5px 10px; border: 0; border-radius: 9px; cursor: pointer; color: var(--deep-sage); background: #e7f0e1; font-weight: 800; font-size: .78rem; }
|
|
||||||
.password-toggle:hover { background: #dbe9d2; }
|
|
||||||
select { width: 100%; min-height: 46px; padding: 10px 34px 10px 13px; border: 1px solid var(--line); border-radius: 12px; outline: none; color: var(--ink); background: #fff; font: inherit; appearance: none; -webkit-appearance: none; background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path d='M4 6l4 4 4-4' fill='none' stroke='%2355715d' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/></svg>"); background-repeat: no-repeat; background-position: right 12px center; }
|
|
||||||
select:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85, 113, 93, .12); }
|
|
||||||
select option { color: var(--ink); background: #fff; }
|
|
||||||
select option:checked { color: var(--deep-sage); font-weight: 700; }
|
|
||||||
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 { 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); }
|
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; }
|
||||||
@@ -105,17 +96,10 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
|
|||||||
|
|
||||||
.auth-card { width: min(100%, 480px); margin: 7vh auto 0; padding: clamp(27px, 6vw, 54px); border: 1px solid var(--line); border-radius: 28px; background: rgba(255, 253, 248, .9); box-shadow: var(--shadow); }
|
.auth-card { width: min(100%, 480px); margin: 7vh auto 0; padding: clamp(27px, 6vw, 54px); border: 1px solid var(--line); border-radius: 28px; background: rgba(255, 253, 248, .9); box-shadow: var(--shadow); }
|
||||||
.auth-card .button { margin-top: 11px; }
|
.auth-card .button { margin-top: 11px; }
|
||||||
.auth-divider { display: flex; align-items: center; gap: 12px; margin: 20px 0 4px; color: var(--muted); font-size: .8rem; }
|
|
||||||
.auth-divider::before, .auth-divider::after { content: ""; flex: 1; height: 1px; background: var(--line); }
|
|
||||||
.passkey-list { display: grid; gap: 8px; margin-bottom: 16px; }
|
|
||||||
.passkey-row { display: flex; align-items: center; gap: 12px; padding: 12px; border: 1px solid var(--line); border-radius: 14px; background: #fff; }
|
|
||||||
.passkey-row .item-copy { flex: 1; }
|
|
||||||
.passkey-row small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
||||||
.auth-switch { margin: 25px 0 0; color: var(--muted); font-size: .9rem; text-align: center; }
|
.auth-switch { margin: 25px 0 0; color: var(--muted); font-size: .9rem; text-align: center; }
|
||||||
.auth-switch a { color: var(--deep-sage); font-weight: 800; }
|
.auth-switch a { color: var(--deep-sage); font-weight: 800; }
|
||||||
.alert { margin-bottom: 18px; padding: 12px 14px; border-radius: 12px; font-size: .9rem; }
|
.alert { margin-bottom: 18px; padding: 12px 14px; border-radius: 12px; font-size: .9rem; }
|
||||||
.alert-error { color: #874d40; background: #fbe7e0; }
|
.alert-error { color: #874d40; background: #fbe7e0; }
|
||||||
.alert-success { color: #3d6b4f; background: #e4f2e6; }
|
|
||||||
|
|
||||||
.list-topbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 27px; }
|
.list-topbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 27px; }
|
||||||
.back-link { color: var(--muted); font-size: .85rem; font-weight: 700; text-decoration: none; }
|
.back-link { color: var(--muted); font-size: .85rem; font-weight: 700; text-decoration: none; }
|
||||||
@@ -135,8 +119,7 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
|
|||||||
.list-heading { display: flex; justify-content: space-between; margin-bottom: 25px; }
|
.list-heading { display: flex; justify-content: space-between; margin-bottom: 25px; }
|
||||||
.list-heading h1 { max-width: 100%; margin-bottom: 5px; overflow-wrap: anywhere; font-size: clamp(1.45rem, 2.8vw, 2.05rem); }
|
.list-heading h1 { max-width: 100%; margin-bottom: 5px; overflow-wrap: anywhere; font-size: clamp(1.45rem, 2.8vw, 2.05rem); }
|
||||||
.list-meta { margin: 0; color: var(--muted); font-size: .85rem; }
|
.list-meta { margin: 0; color: var(--muted); font-size: .85rem; }
|
||||||
.meal-category-label { margin-left: 10px; color: var(--muted); font-size: .8em; font-weight: 500; white-space: nowrap; }
|
.add-item-form { display: grid; grid-template-columns: minmax(0, 1fr) 90px 145px auto; gap: 8px; margin-bottom: 19px; }
|
||||||
.add-item-form { display: grid; grid-template-columns: minmax(0, 1fr) 145px 90px auto; gap: 8px; margin-bottom: 19px; }
|
|
||||||
.add-item-form input { min-height: 50px; }
|
.add-item-form input { min-height: 50px; }
|
||||||
.add-item-form select { min-height: 50px; }
|
.add-item-form select { min-height: 50px; }
|
||||||
.add-button { min-height: 50px; }
|
.add-button { min-height: 50px; }
|
||||||
@@ -144,7 +127,6 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
|
|||||||
.item-list { display: grid; gap: 6px; }
|
.item-list { display: grid; gap: 6px; }
|
||||||
.category-group + .category-group { margin-top: 18px; }
|
.category-group + .category-group { margin-top: 18px; }
|
||||||
.category-heading { margin: 0 7px 4px; color: var(--deep-sage); font-size: .72rem; letter-spacing: .12em; text-transform: uppercase; }
|
.category-heading { margin: 0 7px 4px; color: var(--deep-sage); font-size: .72rem; letter-spacing: .12em; text-transform: uppercase; }
|
||||||
.ingredients-divider { margin: 26px 0 18px; border: 0; border-top: 1px solid var(--line); }
|
|
||||||
.item-row { display: flex; align-items: center; gap: 12px; min-height: 66px; padding: 9px 7px 9px 10px; border-bottom: 1px solid #edf0e6; }
|
.item-row { display: flex; align-items: center; gap: 12px; min-height: 66px; padding: 9px 7px 9px 10px; border-bottom: 1px solid #edf0e6; }
|
||||||
.item-row:last-child { border-bottom: 0; }
|
.item-row:last-child { border-bottom: 0; }
|
||||||
.check-form { flex: 0 0 auto; }
|
.check-form { flex: 0 0 auto; }
|
||||||
@@ -218,8 +200,6 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
|
|||||||
.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; }
|
||||||
.button-danger { width: 100%; color: var(--coral); background: #fbeae4; }
|
|
||||||
.button-danger:hover { background: #f7ddd4; }
|
|
||||||
.empty-items { padding: 34px 10px 18px; color: var(--muted); text-align: center; }
|
.empty-items { padding: 34px 10px 18px; color: var(--muted); text-align: center; }
|
||||||
.empty-items-icon { display: block; margin-bottom: 7px; color: var(--yellow); font-size: 1.7rem; }
|
.empty-items-icon { display: block; margin-bottom: 7px; color: var(--yellow); font-size: 1.7rem; }
|
||||||
.empty-items p { margin-bottom: 2px; color: var(--ink); font-weight: 800; }
|
.empty-items p { margin-bottom: 2px; color: var(--ink); font-weight: 800; }
|
||||||
@@ -230,13 +210,6 @@ textarea:focus { border-color: var(--deep-sage); box-shadow: 0 0 0 4px rgba(85,
|
|||||||
.category-form input { min-height: 38px; padding: 7px 10px; font-size: .84rem; }
|
.category-form input { min-height: 38px; padding: 7px 10px; font-size: .84rem; }
|
||||||
.category-list { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 14px; }
|
.category-list { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 14px; }
|
||||||
.category-chip { padding: 5px 9px; border-radius: 99px; color: var(--deep-sage); background: #edf3e8; font-size: .72rem; font-weight: 800; }
|
.category-chip { padding: 5px 9px; border-radius: 99px; color: var(--deep-sage); background: #edf3e8; font-size: .72rem; font-weight: 800; }
|
||||||
/* Meal categories side panel */
|
|
||||||
.meal-category-list { display: grid; gap: 2px; margin-top: 14px; }
|
|
||||||
.meal-category-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 7px 4px; border-bottom: 1px solid #edf0e6; }
|
|
||||||
.meal-category-row:last-child { border-bottom: 0; }
|
|
||||||
.meal-category-name { font-size: .9rem; font-weight: 700; }
|
|
||||||
.meal-category-delete { padding: 2px 6px; border: 0; border-radius: 7px; color: var(--muted); background: transparent; cursor: pointer; font-size: .8rem; line-height: 1; }
|
|
||||||
.meal-category-delete:hover { color: var(--coral); background: #fbeae4; }
|
|
||||||
.category-empty { margin: 13px 0 0; font-size: .8rem; }
|
.category-empty { margin: 13px 0 0; font-size: .8rem; }
|
||||||
.category-result { margin-top: 10px; }
|
.category-result { margin-top: 10px; }
|
||||||
.category-success { margin: 0; color: var(--deep-sage); font-size: .76rem; font-weight: 800; }
|
.category-success { margin: 0; color: var(--deep-sage); font-size: .76rem; font-weight: 800; }
|
||||||
|
|||||||
Reference in New Issue
Block a user