add passkey support
This commit is contained in:
Generated
+140
-7
@@ -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",
|
"base64 0.22.1",
|
||||||
"bytes",
|
"bytes",
|
||||||
"form_urlencoded",
|
"form_urlencoded",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
@@ -116,6 +116,12 @@ 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"
|
||||||
@@ -315,6 +321,21 @@ 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"
|
||||||
@@ -449,6 +470,12 @@ 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"
|
||||||
@@ -795,6 +822,12 @@ 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"
|
||||||
@@ -806,6 +839,16 @@ 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"
|
||||||
@@ -830,6 +873,43 @@ 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"
|
||||||
@@ -1116,6 +1196,16 @@ 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"
|
||||||
@@ -1267,7 +1357,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",
|
"base64 0.22.1",
|
||||||
"bytes",
|
"bytes",
|
||||||
"crc",
|
"crc",
|
||||||
"crossbeam-queue",
|
"crossbeam-queue",
|
||||||
@@ -1288,7 +1378,7 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
"sha2",
|
"sha2",
|
||||||
"smallvec",
|
"smallvec",
|
||||||
"thiserror",
|
"thiserror 2.0.19",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-stream",
|
"tokio-stream",
|
||||||
"tracing",
|
"tracing",
|
||||||
@@ -1351,7 +1441,7 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
"serde_urlencoded",
|
"serde_urlencoded",
|
||||||
"sqlx-core",
|
"sqlx-core",
|
||||||
"thiserror",
|
"thiserror 2.0.19",
|
||||||
"tracing",
|
"tracing",
|
||||||
"url",
|
"url",
|
||||||
]
|
]
|
||||||
@@ -1375,6 +1465,7 @@ dependencies = [
|
|||||||
"argon2",
|
"argon2",
|
||||||
"async-trait",
|
"async-trait",
|
||||||
"axum",
|
"axum",
|
||||||
|
"base64 0.22.1",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
"hex",
|
"hex",
|
||||||
"maud",
|
"maud",
|
||||||
@@ -1384,12 +1475,14 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"sha2",
|
"sha2",
|
||||||
"sqlx",
|
"sqlx",
|
||||||
"thiserror",
|
"thiserror 2.0.19",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tower",
|
"tower",
|
||||||
"tower-http",
|
"tower-http",
|
||||||
"tracing",
|
"tracing",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
|
"url",
|
||||||
|
"webauthn-rs",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1431,13 +1524,33 @@ 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",
|
"thiserror-impl 2.0.19",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[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]]
|
||||||
@@ -1663,7 +1776,7 @@ dependencies = [
|
|||||||
"log",
|
"log",
|
||||||
"rand 0.9.5",
|
"rand 0.9.5",
|
||||||
"sha1",
|
"sha1",
|
||||||
"thiserror",
|
"thiserror 2.0.19",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1706,6 +1819,7 @@ dependencies = [
|
|||||||
"idna",
|
"idna",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"serde",
|
"serde",
|
||||||
|
"serde_derive",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1747,6 +1861,25 @@ dependencies = [
|
|||||||
"wit-bindgen",
|
"wit-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "webauthn-rs"
|
||||||
|
version = "0.3.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "90b266eccb4b32595876f5c73ea443b0516da0b1df72ca07bc08ed9ba7f96ec1"
|
||||||
|
dependencies = [
|
||||||
|
"base64 0.13.1",
|
||||||
|
"nom",
|
||||||
|
"openssl",
|
||||||
|
"rand 0.8.7",
|
||||||
|
"serde",
|
||||||
|
"serde_cbor",
|
||||||
|
"serde_derive",
|
||||||
|
"serde_json",
|
||||||
|
"thiserror 1.0.69",
|
||||||
|
"tracing",
|
||||||
|
"url",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "webpki-roots"
|
name = "webpki-roots"
|
||||||
version = "0.26.11"
|
version = "0.26.11"
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ edition = "2024"
|
|||||||
argon2 = "0.5"
|
argon2 = "0.5"
|
||||||
async-trait = "0.1"
|
async-trait = "0.1"
|
||||||
axum = { version = "0.8", features = ["ws"] }
|
axum = { version = "0.8", features = ["ws"] }
|
||||||
|
base64 = "0.22"
|
||||||
futures-util = "0.3"
|
futures-util = "0.3"
|
||||||
hex = "0.4"
|
hex = "0.4"
|
||||||
maud = "0.27"
|
maud = "0.27"
|
||||||
@@ -22,3 +23,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"
|
||||||
|
|||||||
@@ -8,7 +8,13 @@ A small shared grocery list built with Rust, Axum, Maud, htmx, WebSockets, and S
|
|||||||
cargo run
|
cargo run
|
||||||
```
|
```
|
||||||
|
|
||||||
Open <http://127.0.0.1:3000>. The application creates `sustenance.db` in the working directory on first start.
|
Open <http://localhost:3000>. The application creates `sustenance.db` in the
|
||||||
|
working directory on first start.
|
||||||
|
|
||||||
|
**Note:** use `localhost` (not `127.0.0.1`) when testing passkeys locally —
|
||||||
|
browsers reject IP addresses as WebAuthn RP IDs. The app defaults to
|
||||||
|
`localhost` for loopback hosts, so passkeys work out of the box when you access
|
||||||
|
the site via `http://localhost:3000`.
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
@@ -20,6 +26,8 @@ Open <http://127.0.0.1:3000>. The application creates `sustenance.db` in the wor
|
|||||||
| `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) |
|
||||||
|
| `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 |
|
| `RUST_LOG` | `sustenance=info,tower_http=info` | Log filter; HTTP requests are logged at info level |
|
||||||
|
|
||||||
### Seeding a default user
|
### Seeding a default user
|
||||||
@@ -41,6 +49,7 @@ 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
|
||||||
|
|||||||
+4
-1
@@ -42,7 +42,7 @@ async function startServer() {
|
|||||||
.slice(2)}.db`,
|
.slice(2)}.db`,
|
||||||
);
|
);
|
||||||
const port = 20000 + Math.floor(Math.random() * 30000);
|
const port = 20000 + Math.floor(Math.random() * 30000);
|
||||||
const baseURL = `http://127.0.0.1:${port}`;
|
const baseURL = `http://localhost:${port}`;
|
||||||
|
|
||||||
const child = spawn(
|
const child = spawn(
|
||||||
path.resolve(__dirname, "..", "target", "debug", "sustenance"),
|
path.resolve(__dirname, "..", "target", "debug", "sustenance"),
|
||||||
@@ -53,6 +53,9 @@ async function startServer() {
|
|||||||
DATABASE_PATH: dbPath,
|
DATABASE_PATH: dbPath,
|
||||||
REGISTRATION_MODE: "open",
|
REGISTRATION_MODE: "open",
|
||||||
BIND_ADDRESS: `127.0.0.1:${port}`,
|
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.
|
// Point SEED_CONFIG at a nonexistent file so no default user is created.
|
||||||
SEED_CONFIG: path.join(os.tmpdir(), "sustenance-e2e-no-seed.json"),
|
SEED_CONFIG: path.join(os.tmpdir(), "sustenance-e2e-no-seed.json"),
|
||||||
},
|
},
|
||||||
|
|||||||
Generated
+17
-1
@@ -8,7 +8,8 @@
|
|||||||
"name": "sustenance-e2e",
|
"name": "sustenance-e2e",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@playwright/test": "^1.45.0"
|
"@playwright/test": "^1.45.0",
|
||||||
|
"@types/node": "^26.1.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@playwright/test": {
|
"node_modules/@playwright/test": {
|
||||||
@@ -26,6 +27,15 @@
|
|||||||
"node": ">=20"
|
"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": {
|
"node_modules/fsevents": {
|
||||||
"version": "2.3.2",
|
"version": "2.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||||
@@ -69,6 +79,12 @@
|
|||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20"
|
"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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-1
@@ -7,6 +7,7 @@
|
|||||||
"test:headed": "playwright test --headed"
|
"test:headed": "playwright test --headed"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@playwright/test": "^1.45.0"
|
"@playwright/test": "^1.45.0",
|
||||||
|
"@types/node": "^26.1.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { expect } from "@playwright/test";
|
||||||
|
import { test } from "../fixtures";
|
||||||
|
import { registerAndLogin } from "../helpers";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enables a virtual WebAuthn authenticator on the given context so the browser
|
||||||
|
* can complete passkey ceremonies without a real device.
|
||||||
|
*/
|
||||||
|
async function enableVirtualAuthenticator(context: any) {
|
||||||
|
const cdp = await context.newCDPSession(context.pages()[0]);
|
||||||
|
await cdp.send("WebAuthn.enable", { enableUI: false });
|
||||||
|
await cdp.send("WebAuthn.addVirtualAuthenticator", {
|
||||||
|
options: {
|
||||||
|
protocol: "ctap2",
|
||||||
|
transport: "internal",
|
||||||
|
hasResidentKey: true,
|
||||||
|
hasUserVerification: true,
|
||||||
|
isUserVerified: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test("a user can register a passkey and sign in with it", async ({ page, browser, server }) => {
|
||||||
|
const context = await browser.newContext({ baseURL: server.baseURL });
|
||||||
|
const p = await context.newPage();
|
||||||
|
|
||||||
|
await enableVirtualAuthenticator(context);
|
||||||
|
|
||||||
|
// Register with a password first.
|
||||||
|
await registerAndLogin(p, "alice@example.com");
|
||||||
|
|
||||||
|
// Add a passkey from the account page.
|
||||||
|
await p.goto("/account");
|
||||||
|
await p.click("#add-passkey");
|
||||||
|
await expect(p.locator(".passkey-row")).toHaveCount(1);
|
||||||
|
|
||||||
|
// Log out.
|
||||||
|
await p.click('button:has-text("Sign out")');
|
||||||
|
await expect(p).toHaveURL(/\/login/);
|
||||||
|
|
||||||
|
// Sign in with the passkey.
|
||||||
|
await p.fill("#email", "alice@example.com");
|
||||||
|
await p.click("#passkey-login");
|
||||||
|
await expect(p).toHaveURL(/\/lists/);
|
||||||
|
|
||||||
|
await context.close();
|
||||||
|
});
|
||||||
@@ -21,6 +21,15 @@ pub struct User {
|
|||||||
pub display_name: String,
|
pub display_name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Passkey {
|
||||||
|
pub id: i64,
|
||||||
|
pub user_id: i64,
|
||||||
|
pub credential_id: String,
|
||||||
|
pub credential: String,
|
||||||
|
pub counter: i64,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct SessionUser {
|
pub struct SessionUser {
|
||||||
pub user: User,
|
pub user: User,
|
||||||
|
|||||||
+134
-5
@@ -5,7 +5,7 @@ use std::time::Duration;
|
|||||||
use axum::{
|
use axum::{
|
||||||
Router,
|
Router,
|
||||||
extract::{
|
extract::{
|
||||||
Form, FromRequest, FromRequestParts, Path, Query, Request, State,
|
Form, FromRequest, FromRequestParts, Json, 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},
|
||||||
@@ -27,6 +27,7 @@ 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;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
@@ -34,6 +35,7 @@ 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,
|
||||||
@@ -52,10 +54,13 @@ 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(_) => status_html_response(
|
AppError::Database(error) => {
|
||||||
StatusCode::INTERNAL_SERVER_ERROR,
|
error!(%error, "request failed");
|
||||||
views::error_page("500", "Something went wrong."),
|
status_html_response(
|
||||||
),
|
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))
|
||||||
}
|
}
|
||||||
@@ -73,6 +78,18 @@ pub fn build_router(state: AppState) -> Router {
|
|||||||
.route("/login", get(login_page).post(login))
|
.route("/login", get(login_page).post(login))
|
||||||
.route("/register", get(register_page).post(register))
|
.route("/register", get(register_page).post(register))
|
||||||
.route("/logout", post(logout))
|
.route("/logout", post(logout))
|
||||||
|
.route("/account", get(account_page))
|
||||||
|
.route("/auth/passkey/register/start", post(passkey_register_start))
|
||||||
|
.route(
|
||||||
|
"/auth/passkey/register/finish",
|
||||||
|
post(passkey_register_finish),
|
||||||
|
)
|
||||||
|
.route("/auth/passkey/login/start", post(passkey_login_start))
|
||||||
|
.route("/auth/passkey/login/finish", post(passkey_login_finish))
|
||||||
|
.route(
|
||||||
|
"/account/passkeys/{passkey_id}/delete",
|
||||||
|
post(delete_passkey),
|
||||||
|
)
|
||||||
.route("/lists", get(lists_page).post(create_list))
|
.route("/lists", get(lists_page).post(create_list))
|
||||||
.route("/lists/{list_id}", get(list_page))
|
.route("/lists/{list_id}", get(list_page))
|
||||||
.route("/lists/{list_id}/items", post(add_item))
|
.route("/lists/{list_id}/items", post(add_item))
|
||||||
@@ -235,6 +252,32 @@ struct CategoryForm {
|
|||||||
csrf: String,
|
csrf: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct PasskeyRegisterStartForm {
|
||||||
|
csrf: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct PasskeyRegisterFinishForm {
|
||||||
|
csrf: String,
|
||||||
|
response: webauthn_rs::proto::RegisterPublicKeyCredential,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct PasskeyLoginStartForm {
|
||||||
|
email: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct PasskeyLoginFinishForm {
|
||||||
|
response: webauthn_rs::proto::PublicKeyCredential,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct DeletePasskeyForm {
|
||||||
|
csrf: String,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
struct MealForm {
|
struct MealForm {
|
||||||
name: String,
|
name: String,
|
||||||
@@ -389,6 +432,92 @@ async fn logout(State(state): State<AppState>, user: CurrentUser) -> Result<Resp
|
|||||||
Ok(response)
|
Ok(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn account_page(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
user: CurrentUser,
|
||||||
|
) -> Result<Response, AppError> {
|
||||||
|
let passkeys = state.webauthn.list_passkeys(user.session.user.id).await?;
|
||||||
|
Ok(html_response(views::account_page(
|
||||||
|
&user.session.user,
|
||||||
|
&passkeys,
|
||||||
|
&user.session.csrf_token,
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn passkey_register_start(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
user: CurrentUser,
|
||||||
|
Json(form): Json<PasskeyRegisterStartForm>,
|
||||||
|
) -> Result<Response, AppError> {
|
||||||
|
verify_csrf(&user, &form.csrf)?;
|
||||||
|
let challenge = state
|
||||||
|
.webauthn
|
||||||
|
.start_registration(&user.session.user)
|
||||||
|
.map_err(AppError::Database)?;
|
||||||
|
Ok(Json(challenge).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn passkey_register_finish(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
user: CurrentUser,
|
||||||
|
Json(form): Json<PasskeyRegisterFinishForm>,
|
||||||
|
) -> Result<Response, AppError> {
|
||||||
|
verify_csrf(&user, &form.csrf)?;
|
||||||
|
state
|
||||||
|
.webauthn
|
||||||
|
.finish_registration(&user.session.user, form.response)
|
||||||
|
.await?;
|
||||||
|
Ok(Redirect::to("/account").into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn passkey_login_start(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Json(form): Json<PasskeyLoginStartForm>,
|
||||||
|
) -> Result<Response, AppError> {
|
||||||
|
let email = form.email.trim().to_lowercase();
|
||||||
|
let Some((user, _)) = state.auth.find_user_by_email(email).await? else {
|
||||||
|
return Err(AppError::NotFound);
|
||||||
|
};
|
||||||
|
let challenge = state
|
||||||
|
.webauthn
|
||||||
|
.start_authentication(user.id)
|
||||||
|
.await
|
||||||
|
.map_err(AppError::Database)?;
|
||||||
|
Ok(Json(challenge).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn passkey_login_finish(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Json(form): Json<PasskeyLoginFinishForm>,
|
||||||
|
) -> Result<Response, AppError> {
|
||||||
|
let user_id = state
|
||||||
|
.webauthn
|
||||||
|
.resolve_user_id_for_assertion(&form.response)
|
||||||
|
.await?;
|
||||||
|
state
|
||||||
|
.webauthn
|
||||||
|
.finish_authentication(user_id, form.response)
|
||||||
|
.await?;
|
||||||
|
let (session_token, _) = state.auth.create_session_for_user(user_id).await?;
|
||||||
|
let mut response = Redirect::to("/lists").into_response();
|
||||||
|
set_session_cookie(&mut response, &session_token, state.cookie_secure);
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete_passkey(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
user: CurrentUser,
|
||||||
|
Path(passkey_id): Path<i64>,
|
||||||
|
LoggedForm(form): LoggedForm<DeletePasskeyForm>,
|
||||||
|
) -> Result<Response, AppError> {
|
||||||
|
verify_csrf(&user, &form.csrf)?;
|
||||||
|
state
|
||||||
|
.webauthn
|
||||||
|
.delete_passkey(user.session.user.id, passkey_id)
|
||||||
|
.await?;
|
||||||
|
Ok(Redirect::to("/account").into_response())
|
||||||
|
}
|
||||||
|
|
||||||
async fn lists_page(
|
async fn lists_page(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
user: CurrentUser,
|
user: CurrentUser,
|
||||||
|
|||||||
+39
-5
@@ -7,6 +7,7 @@ mod seed;
|
|||||||
mod services;
|
mod services;
|
||||||
mod sqlite;
|
mod sqlite;
|
||||||
mod views;
|
mod views;
|
||||||
|
mod webauthn;
|
||||||
|
|
||||||
use std::env;
|
use std::env;
|
||||||
use std::path::Path as FilePath;
|
use std::path::Path as FilePath;
|
||||||
@@ -19,16 +20,17 @@ 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,
|
||||||
MealIngredientRepository, MealRepository, PasswordHasher, RealtimeNotifier, SessionRepository,
|
MealIngredientRepository, MealRepository, PasskeyRepository, PasswordHasher, RealtimeNotifier,
|
||||||
TokenGenerator, UserRepository,
|
SessionRepository, TokenGenerator, UserRepository,
|
||||||
};
|
};
|
||||||
use crate::security::{Argon2PasswordHasher, RandomTokenGenerator};
|
use crate::security::{Argon2PasswordHasher, RandomTokenGenerator};
|
||||||
use crate::services::{AuthService, InvitationService, ListService, MealService, RegistrationMode};
|
use crate::services::{AuthService, InvitationService, ListService, MealService, RegistrationMode};
|
||||||
use crate::sqlite::{
|
use crate::sqlite::{
|
||||||
SqliteCategoryRepository, SqliteDatabase, SqliteInvitationRepository, SqliteItemRepository,
|
SqliteCategoryRepository, SqliteDatabase, SqliteInvitationRepository, SqliteItemRepository,
|
||||||
SqliteListRepository, SqliteMealIngredientRepository, SqliteMealRepository,
|
SqliteListRepository, SqliteMealIngredientRepository, SqliteMealRepository,
|
||||||
SqliteSessionRepository, SqliteUserRepository,
|
SqlitePasskeyRepository, SqliteSessionRepository, SqliteUserRepository,
|
||||||
};
|
};
|
||||||
|
use crate::webauthn::{AppWebauthnConfig, WebAuthnService};
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
@@ -40,8 +42,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
|
|
||||||
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());
|
||||||
let public_base_url =
|
// For loopback hosts, advertise `localhost` so WebAuthn works locally (browsers
|
||||||
env::var("PUBLIC_BASE_URL").unwrap_or_else(|_| format!("http://{}", bind_address));
|
// reject IP addresses as RP IDs). Access the app via http://localhost:PORT.
|
||||||
|
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);
|
||||||
@@ -69,6 +78,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
let meal_ingredients: Arc<dyn MealIngredientRepository> =
|
let meal_ingredients: Arc<dyn MealIngredientRepository> =
|
||||||
Arc::new(SqliteMealIngredientRepository);
|
Arc::new(SqliteMealIngredientRepository);
|
||||||
let invitations: Arc<dyn InvitationRepository> = Arc::new(SqliteInvitationRepository);
|
let invitations: Arc<dyn InvitationRepository> = Arc::new(SqliteInvitationRepository);
|
||||||
|
let passkeys: Arc<dyn PasskeyRepository> = Arc::new(SqlitePasskeyRepository);
|
||||||
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2PasswordHasher);
|
let hasher: Arc<dyn PasswordHasher> = Arc::new(Argon2PasswordHasher);
|
||||||
let tokens: Arc<dyn TokenGenerator> = Arc::new(RandomTokenGenerator);
|
let tokens: Arc<dyn TokenGenerator> = Arc::new(RandomTokenGenerator);
|
||||||
let realtime: Arc<dyn RealtimeNotifier> = Arc::new(InMemoryHub::default());
|
let realtime: Arc<dyn RealtimeNotifier> = Arc::new(InMemoryHub::default());
|
||||||
@@ -102,6 +112,29 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
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(&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;
|
||||||
|
|
||||||
@@ -110,6 +143,7 @@ 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,
|
||||||
|
|||||||
+30
-2
@@ -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, MealIngredient, PresenceUser, SessionUser,
|
Category, DomainResult, GroceryList, Item, Meal, MealIngredient, Passkey, PresenceUser,
|
||||||
User,
|
SessionUser, User,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Repositories take `&mut SqliteConnection` (which a `Transaction` derefs to),
|
/// Repositories take `&mut SqliteConnection` (which a `Transaction` derefs to),
|
||||||
@@ -27,6 +27,34 @@ pub trait UserRepository: Send + Sync {
|
|||||||
async fn has_users(&self, txn: &mut SqliteConnection) -> DomainResult<bool>;
|
async fn has_users(&self, txn: &mut SqliteConnection) -> DomainResult<bool>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait PasskeyRepository: Send + Sync {
|
||||||
|
async fn create_passkey(
|
||||||
|
&self,
|
||||||
|
txn: &mut SqliteConnection,
|
||||||
|
user_id: i64,
|
||||||
|
credential_id: String,
|
||||||
|
credential: String,
|
||||||
|
counter: i64,
|
||||||
|
) -> DomainResult<Passkey>;
|
||||||
|
async fn find_by_credential_id(
|
||||||
|
&self,
|
||||||
|
txn: &mut SqliteConnection,
|
||||||
|
credential_id: String,
|
||||||
|
) -> DomainResult<Option<Passkey>>;
|
||||||
|
async fn list_for_user(
|
||||||
|
&self,
|
||||||
|
txn: &mut SqliteConnection,
|
||||||
|
user_id: i64,
|
||||||
|
) -> DomainResult<Vec<Passkey>>;
|
||||||
|
async fn delete_passkey(
|
||||||
|
&self,
|
||||||
|
txn: &mut SqliteConnection,
|
||||||
|
user_id: i64,
|
||||||
|
passkey_id: i64,
|
||||||
|
) -> DomainResult<()>;
|
||||||
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait SessionRepository: Send + Sync {
|
pub trait SessionRepository: Send + Sync {
|
||||||
async fn create_session(
|
async fn create_session(
|
||||||
|
|||||||
@@ -125,6 +125,20 @@ 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
|
||||||
|
|||||||
+225
-2
@@ -7,11 +7,13 @@ 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, MealIngredient, SessionUser, User,
|
Category, DomainError, DomainResult, GroceryList, Item, Meal, MealIngredient, Passkey,
|
||||||
|
SessionUser, User,
|
||||||
};
|
};
|
||||||
use crate::ports::{
|
use crate::ports::{
|
||||||
CategoryRepository, InvitationRepository, ItemRepository, ListRepository,
|
CategoryRepository, InvitationRepository, ItemRepository, ListRepository,
|
||||||
MealIngredientRepository, MealRepository, NewItem, SessionRepository, UserRepository,
|
MealIngredientRepository, MealRepository, NewItem, PasskeyRepository, SessionRepository,
|
||||||
|
UserRepository,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@@ -105,6 +107,14 @@ async fn migrate(pool: &SqlitePool) -> DomainResult<()> {
|
|||||||
csrf_token TEXT NOT NULL,
|
csrf_token TEXT NOT NULL,
|
||||||
expires_at INTEGER NOT NULL
|
expires_at INTEGER NOT NULL
|
||||||
);
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS 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 IF NOT EXISTS lists (
|
CREATE TABLE IF NOT EXISTS lists (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
name TEXT NOT NULL,
|
name TEXT NOT NULL,
|
||||||
@@ -257,6 +267,117 @@ 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;
|
||||||
|
|
||||||
@@ -2012,4 +2133,106 @@ mod tests {
|
|||||||
.await;
|
.await;
|
||||||
assert!(matches!(result, Err(DomainError::NotFound)));
|
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 {
|
||||||
|
passkeys
|
||||||
|
.create_passkey(txn, user.id, "cred-1".into(), "{}".into(), 0)
|
||||||
|
.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;
|
||||||
|
assert!(matches!(result, Err(DomainError::NotFound)));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+50
-2
@@ -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, MealIngredient, User},
|
domain::{Category, GroceryList, Item, Meal, MealIngredient, Passkey, User},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn login_page(error: Option<&str>, invite: Option<&str>) -> Markup {
|
pub fn login_page(error: Option<&str>, invite: Option<&str>) -> Markup {
|
||||||
@@ -28,8 +28,11 @@ pub fn login_page(error: Option<&str>, invite: Option<&str>) -> Markup {
|
|||||||
input id="password" name="password" type="password" autocomplete="current-password" required;
|
input id="password" name="password" type="password" autocomplete="current-password" required;
|
||||||
button class="button button-primary" type="submit" { "Sign in" }
|
button class="button button-primary" type="submit" { "Sign in" }
|
||||||
}
|
}
|
||||||
|
div class="auth-divider" { span { "or" } }
|
||||||
|
button id="passkey-login" class="button button-secondary" type="button" { "Sign in with a passkey" }
|
||||||
p class="auth-switch" { "Need an account? " a href="/register" { "Create one" } }
|
p class="auth-switch" { "Need an account? " a href="/register" { "Create one" } }
|
||||||
}
|
}
|
||||||
|
script src="/static/passkey-login.js" {}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -79,6 +82,51 @@ pub fn registration_closed_page() -> Markup {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn account_page(user: &User, passkeys: &[Passkey], csrf_token: &str) -> Markup {
|
||||||
|
page(
|
||||||
|
"Account",
|
||||||
|
Some(user),
|
||||||
|
html! {
|
||||||
|
div class="page-heading" {
|
||||||
|
div {
|
||||||
|
p class="eyebrow" { "ACCOUNT" }
|
||||||
|
h1 { "Account" }
|
||||||
|
p class="lede" { "Manage your sign-in methods." }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
div class="dashboard-grid" {
|
||||||
|
section class="panel" {
|
||||||
|
div class="panel-heading" {
|
||||||
|
h2 { "Passkeys" }
|
||||||
|
span class="count-badge" { (passkeys.len()) }
|
||||||
|
}
|
||||||
|
p { "Passkeys let you sign in without a password using your device." }
|
||||||
|
@if passkeys.is_empty() {
|
||||||
|
p class="muted" { "You have no passkeys yet." }
|
||||||
|
} @else {
|
||||||
|
div class="passkey-list" {
|
||||||
|
@for passkey in passkeys {
|
||||||
|
div class="passkey-row" {
|
||||||
|
div class="item-copy" {
|
||||||
|
strong { "Passkey" }
|
||||||
|
small { (passkey.credential_id) }
|
||||||
|
}
|
||||||
|
form method="post" action=(format!("/account/passkeys/{}/delete", passkey.id)) {
|
||||||
|
input type="hidden" name="csrf" value=(csrf_token);
|
||||||
|
button class="danger-link" type="submit" { "Remove" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
button id="add-passkey" class="button button-primary" type="button" data-csrf=(csrf_token) { "Add a passkey" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
script src="/static/passkey-register.js" {}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn lists_page(user: &User, lists: &[GroceryList], csrf_token: &str) -> Markup {
|
pub fn lists_page(user: &User, lists: &[GroceryList], csrf_token: &str) -> Markup {
|
||||||
page(
|
page(
|
||||||
"Your lists",
|
"Your lists",
|
||||||
@@ -907,7 +955,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" {
|
||||||
span class="user-name" { (user.display_name) }
|
a class="user-name" href="/account" { (user.display_name) }
|
||||||
form method="post" action="/logout" {
|
form method="post" action="/logout" {
|
||||||
button class="text-button" type="submit" { "Sign out" }
|
button class="text-button" type="submit" { "Sign out" }
|
||||||
}
|
}
|
||||||
|
|||||||
+271
@@ -0,0 +1,271 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use webauthn_rs::{
|
||||||
|
Webauthn,
|
||||||
|
core::{AuthenticationState, RegistrationState, WebauthnConfig},
|
||||||
|
error::WebauthnError as WanError,
|
||||||
|
proto::{
|
||||||
|
CreationChallengeResponse, Credential, PublicKeyCredential, RegisterPublicKeyCredential,
|
||||||
|
RequestChallengeResponse,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::domain::{DomainError, DomainResult, Passkey as DbPasskey, User};
|
||||||
|
use crate::ports::PasskeyRepository;
|
||||||
|
use crate::sqlite::SqliteDatabase;
|
||||||
|
|
||||||
|
/// Site-specific WebAuthn configuration, derived from env vars.
|
||||||
|
pub struct AppWebauthnConfig {
|
||||||
|
rp_id: String,
|
||||||
|
rp_name: String,
|
||||||
|
origin: url::Url,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppWebauthnConfig {
|
||||||
|
pub fn new(rp_id: String, rp_name: String, origin: url::Url) -> Self {
|
||||||
|
Self {
|
||||||
|
rp_id,
|
||||||
|
rp_name,
|
||||||
|
origin,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WebauthnConfig for AppWebauthnConfig {
|
||||||
|
fn get_relying_party_name(&self) -> &str {
|
||||||
|
&self.rp_name
|
||||||
|
}
|
||||||
|
fn get_origin(&self) -> &url::Url {
|
||||||
|
&self.origin
|
||||||
|
}
|
||||||
|
fn get_relying_party_id(&self) -> &str {
|
||||||
|
&self.rp_id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A single-use, in-memory challenge store keyed by user id.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct ChallengeStore {
|
||||||
|
registrations: HashMap<i64, RegistrationState>,
|
||||||
|
authentications: HashMap<i64, AuthenticationState>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct WebAuthnService {
|
||||||
|
db: SqliteDatabase,
|
||||||
|
webauthn: Webauthn<AppWebauthnConfig>,
|
||||||
|
passkeys: Arc<dyn PasskeyRepository>,
|
||||||
|
challenges: Mutex<ChallengeStore>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WebAuthnService {
|
||||||
|
pub fn new(
|
||||||
|
db: SqliteDatabase,
|
||||||
|
config: AppWebauthnConfig,
|
||||||
|
passkeys: Arc<dyn PasskeyRepository>,
|
||||||
|
) -> Self {
|
||||||
|
let webauthn = Webauthn::new(config);
|
||||||
|
Self {
|
||||||
|
db,
|
||||||
|
webauthn,
|
||||||
|
passkeys,
|
||||||
|
challenges: Mutex::new(ChallengeStore::default()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start a passkey registration ceremony for an authenticated user.
|
||||||
|
pub fn start_registration(&self, user: &User) -> DomainResult<CreationChallengeResponse> {
|
||||||
|
let (challenge, state) = self
|
||||||
|
.webauthn
|
||||||
|
.generate_challenge_register(&user.display_name, true)
|
||||||
|
.map_err(webauthn_error)?;
|
||||||
|
self.challenges
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| DomainError::Database("challenge lock poisoned".into()))?
|
||||||
|
.registrations
|
||||||
|
.insert(user.id, state);
|
||||||
|
Ok(challenge)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finish a passkey registration ceremony and persist the credential.
|
||||||
|
pub async fn finish_registration(
|
||||||
|
&self,
|
||||||
|
user: &User,
|
||||||
|
response: RegisterPublicKeyCredential,
|
||||||
|
) -> DomainResult<()> {
|
||||||
|
let state = self
|
||||||
|
.challenges
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| DomainError::Database("challenge lock poisoned".into()))?
|
||||||
|
.registrations
|
||||||
|
.remove(&user.id)
|
||||||
|
.ok_or(DomainError::NotFound)?;
|
||||||
|
|
||||||
|
let passkeys = Arc::clone(&self.passkeys);
|
||||||
|
let credential_id = response.raw_id.0.clone();
|
||||||
|
let user_id = user.id;
|
||||||
|
let credential = self
|
||||||
|
.webauthn
|
||||||
|
.register_credential(&response, &state, |_| Ok(false))
|
||||||
|
.map_err(webauthn_error)?;
|
||||||
|
|
||||||
|
let serialized = serde_json::to_string(&credential.0)
|
||||||
|
.map_err(|e| DomainError::Database(e.to_string()))?;
|
||||||
|
let credential_id_b64 = base64_url(&credential_id);
|
||||||
|
let counter = credential.0.counter as i64;
|
||||||
|
|
||||||
|
self.db
|
||||||
|
.run(move |txn| {
|
||||||
|
let passkeys = passkeys.clone();
|
||||||
|
Box::pin(async move {
|
||||||
|
passkeys
|
||||||
|
.create_passkey(txn, user_id, credential_id_b64, serialized, counter)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start a passkey authentication ceremony for a user.
|
||||||
|
pub async fn start_authentication(
|
||||||
|
&self,
|
||||||
|
user_id: i64,
|
||||||
|
) -> DomainResult<RequestChallengeResponse> {
|
||||||
|
let passkeys = Arc::clone(&self.passkeys);
|
||||||
|
let db = self.db.clone();
|
||||||
|
let credentials: Vec<Credential> = db
|
||||||
|
.run(move |txn| {
|
||||||
|
let passkeys = passkeys.clone();
|
||||||
|
Box::pin(async move {
|
||||||
|
let rows = passkeys.list_for_user(txn, user_id).await?;
|
||||||
|
let mut creds = Vec::new();
|
||||||
|
for row in rows {
|
||||||
|
let cred: Credential = serde_json::from_str(&row.credential)
|
||||||
|
.map_err(|e| DomainError::Database(e.to_string()))?;
|
||||||
|
creds.push(cred);
|
||||||
|
}
|
||||||
|
Ok(creds)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
if credentials.is_empty() {
|
||||||
|
return Err(DomainError::NotFound);
|
||||||
|
}
|
||||||
|
let (challenge, state) = self
|
||||||
|
.webauthn
|
||||||
|
.generate_challenge_authenticate(credentials)
|
||||||
|
.map_err(webauthn_error)?;
|
||||||
|
self.challenges
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| DomainError::Database("challenge lock poisoned".into()))?
|
||||||
|
.authentications
|
||||||
|
.insert(user_id, state);
|
||||||
|
Ok(challenge)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finish a passkey authentication ceremony.
|
||||||
|
pub async fn finish_authentication(
|
||||||
|
&self,
|
||||||
|
user_id: i64,
|
||||||
|
response: PublicKeyCredential,
|
||||||
|
) -> DomainResult<()> {
|
||||||
|
let state = self
|
||||||
|
.challenges
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| DomainError::Database("challenge lock poisoned".into()))?
|
||||||
|
.authentications
|
||||||
|
.remove(&user_id)
|
||||||
|
.ok_or(DomainError::NotFound)?;
|
||||||
|
|
||||||
|
let (cred_id, auth_data) = self
|
||||||
|
.webauthn
|
||||||
|
.authenticate_credential(&response, &state)
|
||||||
|
.map_err(|e| {
|
||||||
|
tracing::error!(%e, "webauthn authenticate_credential failed");
|
||||||
|
webauthn_error(e)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let passkeys = Arc::clone(&self.passkeys);
|
||||||
|
let db = self.db.clone();
|
||||||
|
let credential_id_b64 = base64_url(cred_id);
|
||||||
|
db.run(move |txn| {
|
||||||
|
let passkeys = passkeys.clone();
|
||||||
|
Box::pin(async move {
|
||||||
|
let stored = passkeys
|
||||||
|
.find_by_credential_id(txn, credential_id_b64)
|
||||||
|
.await?
|
||||||
|
.ok_or(DomainError::NotFound)?;
|
||||||
|
let mut cred: Credential = serde_json::from_str(&stored.credential)
|
||||||
|
.map_err(|e| DomainError::Database(e.to_string()))?;
|
||||||
|
cred.counter = auth_data.counter;
|
||||||
|
let serialized = serde_json::to_string(&cred)
|
||||||
|
.map_err(|e| DomainError::Database(e.to_string()))?;
|
||||||
|
sqlx::query("UPDATE passkeys SET credential = ?1 WHERE id = ?2")
|
||||||
|
.bind(&serialized)
|
||||||
|
.bind(stored.id)
|
||||||
|
.execute(&mut *txn)
|
||||||
|
.await
|
||||||
|
.map_err(db_error)?;
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// List the passkeys registered to a user.
|
||||||
|
pub async fn list_passkeys(&self, user_id: i64) -> DomainResult<Vec<DbPasskey>> {
|
||||||
|
let passkeys = Arc::clone(&self.passkeys);
|
||||||
|
self.db
|
||||||
|
.run(move |txn| {
|
||||||
|
let passkeys = passkeys.clone();
|
||||||
|
Box::pin(async move { passkeys.list_for_user(txn, user_id).await })
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delete a passkey owned by a user.
|
||||||
|
pub async fn delete_passkey(&self, user_id: i64, passkey_id: i64) -> DomainResult<()> {
|
||||||
|
let passkeys = Arc::clone(&self.passkeys);
|
||||||
|
self.db
|
||||||
|
.run(move |txn| {
|
||||||
|
let passkeys = passkeys.clone();
|
||||||
|
Box::pin(async move { passkeys.delete_passkey(txn, user_id, passkey_id).await })
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve the user id that owns the credential in an assertion response.
|
||||||
|
pub async fn resolve_user_id_for_assertion(
|
||||||
|
&self,
|
||||||
|
response: &PublicKeyCredential,
|
||||||
|
) -> DomainResult<i64> {
|
||||||
|
let passkeys = Arc::clone(&self.passkeys);
|
||||||
|
let db = self.db.clone();
|
||||||
|
let credential_id_b64 = base64_url(&response.raw_id.0);
|
||||||
|
db.run(move |txn| {
|
||||||
|
let passkeys = passkeys.clone();
|
||||||
|
Box::pin(async move {
|
||||||
|
let stored = passkeys
|
||||||
|
.find_by_credential_id(txn, credential_id_b64)
|
||||||
|
.await?
|
||||||
|
.ok_or(DomainError::NotFound)?;
|
||||||
|
Ok(stored.user_id)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn base64_url(bytes: &[u8]) -> String {
|
||||||
|
use base64::Engine;
|
||||||
|
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn webauthn_error(error: WanError) -> DomainError {
|
||||||
|
DomainError::Database(error.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn db_error(error: sqlx::Error) -> DomainError {
|
||||||
|
DomainError::Database(error.to_string())
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
function b64ToBytes(b64) {
|
||||||
|
const bin = atob(b64.replace(/-/g, "+").replace(/_/g, "/"));
|
||||||
|
const bytes = new Uint8Array(bin.length);
|
||||||
|
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById("passkey-login").addEventListener("click", async () => {
|
||||||
|
const email = document.getElementById("email").value;
|
||||||
|
if (!email) {
|
||||||
|
alert("Enter your email first.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const start = await fetch("/auth/passkey/login/start", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ email }),
|
||||||
|
});
|
||||||
|
if (!start.ok) {
|
||||||
|
alert("No passkey found for that email.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const options = await start.json();
|
||||||
|
const pk = options.publicKey;
|
||||||
|
pk.challenge = b64ToBytes(pk.challenge);
|
||||||
|
if (pk.allowCredentials) {
|
||||||
|
pk.allowCredentials.forEach((c) => (c.id = b64ToBytes(c.id)));
|
||||||
|
}
|
||||||
|
const credential = await navigator.credentials.get(options);
|
||||||
|
const finish = await fetch("/auth/passkey/login/finish", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ response: credential }),
|
||||||
|
});
|
||||||
|
if (finish.ok) {
|
||||||
|
window.location.href = "/lists";
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
function b64ToBytes(b64) {
|
||||||
|
const bin = atob(b64.replace(/-/g, "+").replace(/_/g, "/"));
|
||||||
|
const bytes = new Uint8Array(bin.length);
|
||||||
|
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById("add-passkey").addEventListener("click", async () => {
|
||||||
|
const csrf = document.getElementById("add-passkey").dataset.csrf;
|
||||||
|
const start = await fetch("/auth/passkey/register/start", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ csrf }),
|
||||||
|
});
|
||||||
|
const options = await start.json();
|
||||||
|
const pk = options.publicKey;
|
||||||
|
pk.challenge = b64ToBytes(pk.challenge);
|
||||||
|
pk.user.id = b64ToBytes(pk.user.id);
|
||||||
|
if (pk.excludeCredentials) {
|
||||||
|
pk.excludeCredentials.forEach((c) => (c.id = b64ToBytes(c.id)));
|
||||||
|
}
|
||||||
|
const credential = await navigator.credentials.create(options);
|
||||||
|
const response = { csrf, response: credential };
|
||||||
|
const finish = await fetch("/auth/passkey/register/finish", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(response),
|
||||||
|
});
|
||||||
|
if (finish.ok) {
|
||||||
|
window.location.href = "/account";
|
||||||
|
}
|
||||||
|
});
|
||||||
+8
-1
@@ -51,7 +51,8 @@ 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; }
|
.user-name { color: var(--ink); font-weight: 700; text-decoration: none; }
|
||||||
|
.user-name:hover { color: var(--deep-sage); }
|
||||||
.text-button { border: 0; padding: 0; color: var(--deep-sage); background: transparent; cursor: pointer; font-weight: 700; }
|
.text-button { border: 0; padding: 0; color: var(--deep-sage); background: transparent; cursor: pointer; font-weight: 700; }
|
||||||
|
|
||||||
.site-main { width: min(1120px, calc(100% - 40px)); margin: 30px auto 80px; }
|
.site-main { width: min(1120px, calc(100% - 40px)); margin: 30px auto 80px; }
|
||||||
@@ -96,6 +97,12 @@ 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; }
|
||||||
|
|||||||
Reference in New Issue
Block a user