From 209363774cc459923b331110f5b3626eaaa15273 Mon Sep 17 00:00:00 2001 From: Simon Bernier St-Pierre Date: Mon, 3 Aug 2026 00:23:10 -0400 Subject: [PATCH] passwordless login + proper migrations --- Cargo.lock | 448 +++++++++++++++++++++++++- Cargo.toml | 2 +- e2e/tests/passkey.spec.ts | 3 +- migrations/20240101000000_initial.sql | 81 +++++ src/domain.rs | 4 + src/http.rs | 37 ++- src/hub.rs | 2 +- src/main.rs | 1 + src/ports.rs | 5 + src/security.rs | 8 +- src/sqlite.rs | 151 ++++----- src/views.rs | 2 +- src/webauthn.rs | 181 +++++++---- static/passkey-login.js | 16 +- 14 files changed, 753 insertions(+), 188 deletions(-) create mode 100644 migrations/20240101000000_initial.sql diff --git a/Cargo.lock b/Cargo.lock index b6baecb..d59583a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -139,6 +139,9 @@ name = "bitflags" version = "2.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" +dependencies = [ + "serde_core", +] [[package]] name = "blake2" @@ -158,6 +161,12 @@ dependencies = [ "generic-array", ] +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "bytes" version = "1.12.1" @@ -180,6 +189,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -235,6 +250,17 @@ version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" 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]] name = "digest" version = "0.10.7" @@ -242,6 +268,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", + "const-oid", "crypto-common", "subtle", ] @@ -288,6 +315,17 @@ dependencies = [ "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]] name = "event-listener" version = "5.4.2" @@ -514,6 +552,33 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" 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]] name = "http" version = "1.5.0" @@ -724,6 +789,9 @@ name = "lazy_static" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin", +] [[package]] name = "libc" @@ -731,6 +799,24 @@ version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" 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]] name = "libsqlite3-sys" version = "0.30.1" @@ -800,6 +886,16 @@ dependencies = [ "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]] name = "memchr" version = "2.8.3" @@ -858,6 +954,41 @@ dependencies = [ "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]] name = "num-traits" version = "0.2.19" @@ -865,6 +996,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -934,7 +1066,7 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ "cfg-if", "libc", - "redox_syscall", + "redox_syscall 0.5.18", "smallvec", "windows-link", ] @@ -950,6 +1082,15 @@ dependencies = [ "subtle", ] +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -962,12 +1103,39 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" 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]] name = "pkg-config" version = "0.3.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + [[package]] name = "potential_utf" version = "0.1.5" @@ -1109,6 +1277,15 @@ dependencies = [ "bitflags", ] +[[package]] +name = "redox_syscall" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07507be7b4a5f9f26eeb41eeaebb1f5a7ff29dfb29739facc21d35bf8b11c21e" +dependencies = [ + "bitflags", +] + [[package]] name = "regex-automata" version = "0.4.16" @@ -1140,6 +1317,26 @@ dependencies = [ "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]] name = "rustls" version = "0.23.43" @@ -1309,6 +1506,16 @@ dependencies = [ "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]] name = "slab" version = "0.4.12" @@ -1320,6 +1527,9 @@ name = "smallvec" version = "1.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" +dependencies = [ + "serde", +] [[package]] name = "socket2" @@ -1340,6 +1550,16 @@ dependencies = [ "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]] name = "sqlx" version = "0.8.6" @@ -1348,6 +1568,8 @@ checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc" dependencies = [ "sqlx-core", "sqlx-macros", + "sqlx-mysql", + "sqlx-postgres", "sqlx-sqlite", ] @@ -1376,6 +1598,7 @@ dependencies = [ "percent-encoding", "rustls", "serde", + "serde_json", "sha2", "smallvec", "thiserror 2.0.19", @@ -1422,6 +1645,84 @@ dependencies = [ "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]] name = "sqlx-sqlite" version = "0.8.6" @@ -1452,6 +1753,17 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" 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]] name = "subtle" version = "2.6.1" @@ -1583,6 +1895,21 @@ dependencies = [ "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]] name = "tokio" version = "1.53.1" @@ -1791,12 +2118,33 @@ version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + [[package]] name = "unicode-ident" version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" 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]] name = "unicode-width" version = "0.2.2" @@ -1861,6 +2209,12 @@ dependencies = [ "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" @@ -1898,19 +2252,38 @@ dependencies = [ "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]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" 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]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -1922,34 +2295,67 @@ dependencies = [ "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]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -1962,24 +2368,48 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" 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]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" 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]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" 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]] name = "windows_x86_64_msvc" version = "0.52.6" diff --git a/Cargo.toml b/Cargo.toml index 2d62373..f9d4a2c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,7 @@ rand = "0.8" serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.10" -sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "sqlite", "macros", "tls-rustls"] } +sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "sqlite", "macros", "migrate", "tls-rustls"] } thiserror = "2" tokio = { version = "1", features = ["full"] } tower = "0.5" diff --git a/e2e/tests/passkey.spec.ts b/e2e/tests/passkey.spec.ts index c8dfb88..6f4fec4 100644 --- a/e2e/tests/passkey.spec.ts +++ b/e2e/tests/passkey.spec.ts @@ -38,8 +38,7 @@ test("a user can register a passkey and sign in with it", async ({ page, browser 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"); + // Sign in with the passkey without entering an email (userless sign-in). await p.click("#passkey-login"); await expect(p).toHaveURL(/\/lists/); diff --git a/migrations/20240101000000_initial.sql b/migrations/20240101000000_initial.sql new file mode 100644 index 0000000..d074360 --- /dev/null +++ b/migrations/20240101000000_initial.sql @@ -0,0 +1,81 @@ +CREATE TABLE users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + email TEXT NOT NULL UNIQUE COLLATE NOCASE, + display_name TEXT NOT NULL, + password_hash TEXT NOT NULL, + user_handle BLOB NOT NULL UNIQUE, + created_at INTEGER NOT NULL +); + +CREATE TABLE sessions ( + token_hash BLOB PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + csrf_token BLOB NOT NULL, + expires_at INTEGER NOT NULL +); + +CREATE TABLE passkeys ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + credential_id TEXT NOT NULL UNIQUE, + credential TEXT NOT NULL, + counter INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL +); + +CREATE TABLE lists ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + revision INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL +); + +CREATE TABLE categories ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL UNIQUE COLLATE NOCASE, + position INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL +); + +CREATE TABLE invitations ( + token_hash BLOB PRIMARY KEY, + created_by INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + expires_at INTEGER NOT NULL +); + +CREATE TABLE items ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + list_id INTEGER NOT NULL REFERENCES lists(id) ON DELETE CASCADE, + name TEXT NOT NULL, + quantity TEXT NOT NULL DEFAULT '', + note TEXT NOT NULL DEFAULT '', + category_id INTEGER REFERENCES categories(id) ON DELETE SET NULL, + checked INTEGER NOT NULL DEFAULT 0, + version INTEGER NOT NULL DEFAULT 1, + position INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL +); + +CREATE TABLE meals ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL +); + +CREATE TABLE meal_ingredients ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + meal_id INTEGER NOT NULL REFERENCES meals(id) ON DELETE CASCADE, + name TEXT NOT NULL, + quantity TEXT NOT NULL DEFAULT '', + note TEXT NOT NULL DEFAULT '', + category_id INTEGER REFERENCES categories(id) ON DELETE SET NULL, + position INTEGER NOT NULL DEFAULT 0 +); + +CREATE INDEX items_list_idx ON items(list_id); +CREATE INDEX meal_ingredients_meal_idx ON meal_ingredients(meal_id); +CREATE INDEX sessions_user_idx ON sessions(user_id); +CREATE INDEX passkeys_user_idx ON passkeys(user_id); diff --git a/src/domain.rs b/src/domain.rs index a632eb3..90e6ed3 100644 --- a/src/domain.rs +++ b/src/domain.rs @@ -19,6 +19,10 @@ pub struct User { pub id: i64, pub email: String, pub display_name: String, + /// Opaque, random user handle used as the WebAuthn userHandle. Kept + /// high-entropy and unpredictable per the WebAuthn spec to avoid user + /// enumeration and cross-site correlation. Stored as raw bytes. + pub user_handle: Vec, } #[derive(Clone, Debug)] diff --git a/src/http.rs b/src/http.rs index 86c92d1..e818b12 100644 --- a/src/http.rs +++ b/src/http.rs @@ -259,11 +259,13 @@ struct PasskeyRegisterFinishForm { #[derive(Debug, Deserialize)] struct PasskeyLoginStartForm { + #[serde(default)] email: String, } #[derive(Debug, Deserialize)] struct PasskeyLoginFinishForm { + token: String, response: webauthn_rs::proto::PublicKeyCredential, } @@ -480,15 +482,28 @@ async fn passkey_login_start( Json(form): Json, ) -> Result { 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, 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)? }; - let challenge = state - .webauthn - .start_authentication(user.id) - .await - .map_err(AppError::Database)?; - Ok(Json(challenge).into_response()) + Ok( + Json(serde_json::json!({ "token": token, "publicKey": challenge.public_key })) + .into_response(), + ) } async fn passkey_login_finish( @@ -497,11 +512,7 @@ async fn passkey_login_finish( ) -> Result { let user_id = state .webauthn - .resolve_user_id_for_assertion(&form.response) - .await?; - state - .webauthn - .finish_authentication(user_id, form.response) + .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(); diff --git a/src/hub.rs b/src/hub.rs index 9118ebb..e0eea09 100644 --- a/src/hub.rs +++ b/src/hub.rs @@ -35,7 +35,7 @@ impl RealtimeNotifier for InMemoryHub { } }); - let connection_id = crate::security::new_secret(); + let connection_id = hex::encode(crate::security::new_secret()); let already_present = room .connections .values() diff --git a/src/main.rs b/src/main.rs index 5f4ab0c..95b84b0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -132,6 +132,7 @@ async fn main() -> Result<(), Box> { let webauthn_service = Arc::new(WebAuthnService::new( db.clone(), AppWebauthnConfig::new(rp_id, rp_name, origin), + Arc::clone(&users), Arc::clone(&passkeys), )); diff --git a/src/ports.rs b/src/ports.rs index f888092..1801a35 100644 --- a/src/ports.rs +++ b/src/ports.rs @@ -24,6 +24,11 @@ pub trait UserRepository: Send + Sync { txn: &mut SqliteConnection, email: String, ) -> DomainResult>; + async fn find_user_by_handle( + &self, + txn: &mut SqliteConnection, + user_handle: Vec, + ) -> DomainResult>; async fn has_users(&self, txn: &mut SqliteConnection) -> DomainResult; } diff --git a/src/security.rs b/src/security.rs index 422871a..e0d257c 100644 --- a/src/security.rs +++ b/src/security.rs @@ -37,12 +37,14 @@ pub struct RandomTokenGenerator; #[async_trait] impl TokenGenerator for RandomTokenGenerator { fn generate(&self) -> String { - new_secret() + hex::encode(new_secret()) } } -pub fn new_secret() -> String { +/// Generates 32 cryptographically random bytes. Callers that need a +/// client-facing string should hex-encode the result. +pub fn new_secret() -> Vec { let mut bytes = [0_u8; 32]; OsRng.fill_bytes(&mut bytes); - hex::encode(bytes) + bytes.to_vec() } diff --git a/src/sqlite.rs b/src/sqlite.rs index c6b41cb..5610a9e 100644 --- a/src/sqlite.rs +++ b/src/sqlite.rs @@ -16,6 +16,9 @@ use crate::ports::{ UserRepository, }; +/// The embedded SQL migrations, applied automatically on startup. +static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!(); + #[derive(Clone)] pub struct SqliteDatabase { pool: SqlitePool, @@ -30,7 +33,7 @@ impl SqliteDatabase { .busy_timeout(std::time::Duration::from_secs(5)) .create_if_missing(true); let pool = SqlitePool::connect_with(options).await.map_err(db_error)?; - migrate(&pool).await?; + MIGRATOR.run(&pool).await.map_err(migrate_error)?; seed_default_categories(&pool).await?; Ok(Self { pool }) } @@ -56,7 +59,7 @@ impl SqliteDatabase { .busy_timeout(std::time::Duration::from_secs(5)) .create_if_missing(true); let pool = SqlitePool::connect_with(options).await.map_err(db_error)?; - migrate(&pool).await?; + MIGRATOR.run(&pool).await.map_err(migrate_error)?; seed_default_categories(&pool).await?; Ok(Self { pool }) } @@ -92,85 +95,6 @@ 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 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 ( - 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. async fn seed_default_categories(pool: &SqlitePool) -> DomainResult<()> { let count: i64 = sqlx::query("SELECT COUNT(*) FROM categories") @@ -205,13 +129,17 @@ impl UserRepository for SqliteUserRepository { display_name: String, password_hash: String, ) -> DomainResult { + // 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( - "INSERT INTO users (email, display_name, password_hash, created_at) - VALUES (?1, ?2, ?3, ?4)", + "INSERT INTO users (email, display_name, password_hash, user_handle, created_at) + VALUES (?1, ?2, ?3, ?4, ?5)", ) .bind(&email) .bind(&display_name) .bind(&password_hash) + .bind(&user_handle) .bind(now()) .execute(&mut *txn) .await; @@ -226,6 +154,7 @@ impl UserRepository for SqliteUserRepository { id, email, display_name, + user_handle, }) } Err(error) if is_unique_violation(&error) => Err(DomainError::Conflict), @@ -239,7 +168,7 @@ impl UserRepository for SqliteUserRepository { email: String, ) -> DomainResult> { let row = sqlx::query( - "SELECT id, email, display_name, password_hash + "SELECT id, email, display_name, user_handle, password_hash FROM users WHERE email = ?1 COLLATE NOCASE", ) .bind(&email) @@ -252,12 +181,34 @@ impl UserRepository for SqliteUserRepository { id: row.get(0), email: row.get(1), display_name: row.get(2), + user_handle: row.get(3), }, - row.get(3), + row.get(4), ) })) } + async fn find_user_by_handle( + &self, + txn: &mut SqliteConnection, + user_handle: Vec, + ) -> DomainResult> { + 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 has_users(&self, txn: &mut SqliteConnection) -> DomainResult { let row = sqlx::query("SELECT EXISTS(SELECT 1 FROM users)") .fetch_one(&mut *txn) @@ -388,15 +339,15 @@ impl SessionRepository for SqliteSessionRepository { txn: &mut SqliteConnection, user_id: i64, ) -> DomainResult<(String, String)> { - let session_token = crate::security::new_secret(); - let csrf_token = crate::security::new_secret(); + let session_token = hex::encode(crate::security::new_secret()); + let csrf_token = hex::encode(crate::security::new_secret()); sqlx::query( "INSERT INTO sessions (token_hash, user_id, csrf_token, expires_at) VALUES (?1, ?2, ?3, ?4)", ) .bind(hash_secret(&session_token)) .bind(user_id) - .bind(&csrf_token) + .bind(hex::decode(&csrf_token).expect("csrf_token is valid hex")) .bind(now() + 60 * 60 * 24 * 30) .execute(&mut *txn) .await @@ -410,7 +361,7 @@ impl SessionRepository for SqliteSessionRepository { session_token: String, ) -> DomainResult> { let row = sqlx::query( - "SELECT u.id, u.email, u.display_name, s.csrf_token + "SELECT u.id, u.email, u.display_name, u.user_handle, s.csrf_token FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = ?1 AND s.expires_at > ?2", @@ -425,8 +376,9 @@ impl SessionRepository for SqliteSessionRepository { id: row.get(0), email: row.get(1), display_name: row.get(2), + user_handle: row.get(3), }, - csrf_token: row.get(3), + csrf_token: hex::encode(row.get::, _>(4)), })) } @@ -1109,10 +1061,10 @@ const DEFAULT_CATEGORIES: &[&str] = &[ "Household", ]; -fn hash_secret(secret: &str) -> String { +fn hash_secret(secret: &str) -> Vec { let mut hasher = Sha256::new(); hasher.update(secret.as_bytes()); - hex::encode(hasher.finalize()) + hasher.finalize().to_vec() } fn now() -> i64 { @@ -1122,6 +1074,17 @@ fn now() -> 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 { + 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 { error .as_database_error() @@ -1133,6 +1096,10 @@ fn db_error(error: sqlx::Error) -> DomainError { DomainError::Database(error.to_string()) } +fn migrate_error(error: sqlx::migrate::MigrateError) -> DomainError { + DomainError::Database(error.to_string()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/views.rs b/src/views.rs index 2a5b1be..50d38c3 100644 --- a/src/views.rs +++ b/src/views.rs @@ -23,7 +23,7 @@ pub fn login_page(error: Option<&str>, invite: Option<&str>) -> Markup { input type="hidden" name="invite" value=(invite); } label for="email" { "Email" } - input id="email" name="email" type="email" autocomplete="email" required autofocus; + input id="email" name="email" type="email" autocomplete="email" autofocus; label for="password" { "Password" } input id="password" name="password" type="password" autocomplete="current-password" required; button class="button button-primary" type="submit" { "Sign in" } diff --git a/src/webauthn.rs b/src/webauthn.rs index f693634..ef6dcbb 100644 --- a/src/webauthn.rs +++ b/src/webauthn.rs @@ -7,12 +7,13 @@ use webauthn_rs::{ error::WebauthnError as WanError, proto::{ CreationChallengeResponse, Credential, PublicKeyCredential, RegisterPublicKeyCredential, - RequestChallengeResponse, + RequestChallengeResponse, UserVerificationPolicy, }, }; use crate::domain::{DomainError, DomainResult, Passkey as DbPasskey, User}; -use crate::ports::PasskeyRepository; +use crate::ports::{PasskeyRepository, UserRepository}; +use crate::security::new_secret; use crate::sqlite::SqliteDatabase; /// Site-specific WebAuthn configuration, derived from env vars. @@ -20,6 +21,7 @@ pub struct AppWebauthnConfig { rp_id: String, rp_name: String, origin: url::Url, + require_resident_key: bool, } impl AppWebauthnConfig { @@ -28,6 +30,10 @@ impl AppWebauthnConfig { 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, } } } @@ -42,18 +48,24 @@ impl WebauthnConfig for AppWebauthnConfig { 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 keyed by user id. +/// 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, - authentications: HashMap, + authentications: HashMap, } pub struct WebAuthnService { db: SqliteDatabase, webauthn: Webauthn, + users: Arc, passkeys: Arc, challenges: Mutex, } @@ -62,12 +74,14 @@ impl WebAuthnService { pub fn new( db: SqliteDatabase, config: AppWebauthnConfig, + users: Arc, passkeys: Arc, ) -> Self { let webauthn = Webauthn::new(config); Self { db, webauthn, + users, passkeys, challenges: Mutex::new(ChallengeStore::default()), } @@ -75,9 +89,19 @@ impl WebAuthnService { /// Start a passkey registration ceremony for an authenticated user. pub fn start_registration(&self, user: &User) -> DomainResult { + // 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(&user.display_name, true) + .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() @@ -127,11 +151,12 @@ impl WebAuthnService { .await } - /// Start a passkey authentication ceremony for a user. + /// 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 { + ) -> DomainResult<(RequestChallengeResponse, String)> { let passkeys = Arc::clone(&self.passkeys); let db = self.db.clone(); let credentials: Vec = db @@ -156,28 +181,91 @@ impl WebAuthnService { .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(user_id, state); - Ok(challenge) + .insert(token.clone(), state); + Ok((challenge, token)) } - /// Finish a passkey authentication ceremony. + /// 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, - user_id: i64, + token: String, response: PublicKeyCredential, - ) -> DomainResult<()> { - let state = self + ) -> DomainResult { + let mut state = self .challenges .lock() .map_err(|_| DomainError::Database("challenge lock poisoned".into()))? .authentications - .remove(&user_id) + .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 = 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) @@ -189,28 +277,30 @@ impl WebAuthnService { 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(()) + 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 + .await?; + Ok(user_id) } /// List the passkeys registered to a user. @@ -234,27 +324,6 @@ impl WebAuthnService { }) .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 { - 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 { diff --git a/static/passkey-login.js b/static/passkey-login.js index bc428fd..263afa8 100644 --- a/static/passkey-login.js +++ b/static/passkey-login.js @@ -6,31 +6,27 @@ function b64ToBytes(b64) { } document.getElementById("passkey-login").addEventListener("click", async () => { - const email = document.getElementById("email").value; - if (!email) { - alert("Enter your email first."); - return; - } + 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 email."); + alert("No passkey found for that account."); return; } - const options = await start.json(); - const pk = options.publicKey; + 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(options); + 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({ response: credential }), + body: JSON.stringify({ token: data.token, response: credential }), }); if (finish.ok) { window.location.href = "/lists";