forge
Explore
Log in

Don't you dare go Hollow

Passkeys (WebAuthn) for sign-in, settings and admin

Browse files at this commit

c4e716920e3790bd91c617629da793d1a3b49747Ahmet Kaan GümüşParent: 71b8f62
  • feat
    • passkeys (WebAuthn) for sign-in, settings and admin
Show full message
✨ feat: passkeys (WebAuthn) for sign-in, settings and admin
Cargo.lockmodified+364 -3
@@ -284,6 +284,45 @@ version = "0.7.8"
284 source = "registry+https://github.com/rust-lang/crates.io-index"284 source = "registry+https://github.com/rust-lang/crates.io-index"
285 checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"285 checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
286 286
287+[[package]]
288+name = "asn1-rs"
289+version = "0.6.2"
290+source = "registry+https://github.com/rust-lang/crates.io-index"
291+checksum = "5493c3bedbacf7fd7382c6346bbd66687d12bbaad3a89a2d2c303ee6cf20b048"
292+dependencies = [
293+ "asn1-rs-derive",
294+ "asn1-rs-impl",
295+ "displaydoc",
296+ "nom 7.1.3",
297+ "num-traits",
298+ "rusticata-macros",
299+ "thiserror 1.0.69",
300+ "time",
301+]
302+
303+[[package]]
304+name = "asn1-rs-derive"
305+version = "0.5.1"
306+source = "registry+https://github.com/rust-lang/crates.io-index"
307+checksum = "965c2d33e53cb6b267e148a4cb0760bc01f4904c1cd4bb4002a085bb016d1490"
308+dependencies = [
309+ "proc-macro2",
310+ "quote",
311+ "syn 2.0.119",
312+ "synstructure 0.13.2",
313+]
314+
315+[[package]]
316+name = "asn1-rs-impl"
317+version = "0.2.0"
318+source = "registry+https://github.com/rust-lang/crates.io-index"
319+checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"
320+dependencies = [
321+ "proc-macro2",
322+ "quote",
323+ "syn 2.0.119",
324+]
325+
287 [[package]]326 [[package]]
288 name = "assoc"327 name = "assoc"
289 version = "0.1.3"328 version = "0.1.3"
@@ -302,6 +341,28 @@ dependencies = [
302 "tokio",341 "tokio",
303 ]342 ]
304 343
344+[[package]]
345+name = "async-stream"
346+version = "0.3.6"
347+source = "registry+https://github.com/rust-lang/crates.io-index"
348+checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476"
349+dependencies = [
350+ "async-stream-impl",
351+ "futures-core",
352+ "pin-project-lite",
353+]
354+
355+[[package]]
356+name = "async-stream-impl"
357+version = "0.3.6"
358+source = "registry+https://github.com/rust-lang/crates.io-index"
359+checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d"
360+dependencies = [
361+ "proc-macro2",
362+ "quote",
363+ "syn 2.0.119",
364+]
365+
305 [[package]]366 [[package]]
306 name = "async-trait"367 name = "async-trait"
307 version = "0.1.92"368 version = "0.1.92"
@@ -355,6 +416,12 @@ version = "1.0.0"
355 source = "registry+https://github.com/rust-lang/crates.io-index"416 source = "registry+https://github.com/rust-lang/crates.io-index"
356 checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6"417 checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6"
357 418
419+[[package]]
420+name = "base64"
421+version = "0.21.7"
422+source = "registry+https://github.com/rust-lang/crates.io-index"
423+checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
424+
358 [[package]]425 [[package]]
359 name = "base64"426 name = "base64"
360 version = "0.22.1"427 version = "0.22.1"
@@ -373,6 +440,17 @@ version = "1.8.3"
373 source = "registry+https://github.com/rust-lang/crates.io-index"440 source = "registry+https://github.com/rust-lang/crates.io-index"
374 checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"441 checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
375 442
443+[[package]]
444+name = "base64urlsafedata"
445+version = "0.5.5"
446+source = "registry+https://github.com/rust-lang/crates.io-index"
447+checksum = "b08e33815c87d8cadcddb1e74ac307368a3751fbe40c961538afa21a1899f21c"
448+dependencies = [
449+ "base64 0.21.7",
450+ "pastey 0.1.1",
451+ "serde",
452+]
453+
376 [[package]]454 [[package]]
377 name = "bcrypt-pbkdf"455 name = "bcrypt-pbkdf"
378 version = "0.11.0"456 version = "0.11.0"
@@ -1386,6 +1464,20 @@ dependencies = [
1386 "zeroize",1464 "zeroize",
1387 ]1465 ]
1388 1466
1467+[[package]]
1468+name = "der-parser"
1469+version = "9.0.0"
1470+source = "registry+https://github.com/rust-lang/crates.io-index"
1471+checksum = "5cd0a5c643689626bec213c4d8bd4d96acc8ffdb4ad4bb6bc16abf27d5f4b553"
1472+dependencies = [
1473+ "asn1-rs",
1474+ "displaydoc",
1475+ "nom 7.1.3",
1476+ "num-bigint 0.4.8",
1477+ "num-traits",
1478+ "rusticata-macros",
1479+]
1480+
1389 [[package]]1481 [[package]]
1390 name = "deranged"1482 name = "deranged"
1391 version = "0.5.9"1483 version = "0.5.9"
@@ -1856,6 +1948,21 @@ version = "0.2.0"
1856 source = "registry+https://github.com/rust-lang/crates.io-index"1948 source = "registry+https://github.com/rust-lang/crates.io-index"
1857 checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"1949 checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
1858 1950
1951+[[package]]
1952+name = "foreign-types"
1953+version = "0.3.2"
1954+source = "registry+https://github.com/rust-lang/crates.io-index"
1955+checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
1956+dependencies = [
1957+ "foreign-types-shared",
1958+]
1959+
1960+[[package]]
1961+name = "foreign-types-shared"
1962+version = "0.1.1"
1963+source = "registry+https://github.com/rust-lang/crates.io-index"
1964+checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
1965+
1859 [[package]]1966 [[package]]
1860 name = "forge-ci"1967 name = "forge-ci"
1861 version = "0.1.0"1968 version = "0.1.0"
@@ -2016,6 +2123,9 @@ dependencies = [
2016 "tracing",2123 "tracing",
2017 "tracing-subscriber",2124 "tracing-subscriber",
2018 "ulid",2125 "ulid",
2126+ "webauthn-authenticator-rs",
2127+ "webauthn-rs",
2128+ "webauthn-rs-proto",
2019 "zip",2129 "zip",
2020 ]2130 ]
2021 2131
@@ -3128,6 +3238,17 @@ dependencies = [
3128 "tracing",3238 "tracing",
3129 ]3239 ]
3130 3240
3241+[[package]]
3242+name = "half"
3243+version = "2.7.1"
3244+source = "registry+https://github.com/rust-lang/crates.io-index"
3245+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
3246+dependencies = [
3247+ "cfg-if",
3248+ "crunchy",
3249+ "zerocopy",
3250+]
3251+
3131 [[package]]3252 [[package]]
3132 name = "hash32"3253 name = "hash32"
3133 version = "0.3.1"3254 version = "0.3.1"
@@ -4514,6 +4635,17 @@ version = "0.2.2"
4514 source = "registry+https://github.com/rust-lang/crates.io-index"4635 source = "registry+https://github.com/rust-lang/crates.io-index"
4515 checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"4636 checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
4516 4637
4638+[[package]]
4639+name = "num-derive"
4640+version = "0.4.2"
4641+source = "registry+https://github.com/rust-lang/crates.io-index"
4642+checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
4643+dependencies = [
4644+ "proc-macro2",
4645+ "quote",
4646+ "syn 2.0.119",
4647+]
4648+
4517 [[package]]4649 [[package]]
4518 name = "num-integer"4650 name = "num-integer"
4519 version = "0.1.47"4651 version = "0.1.47"
@@ -4617,6 +4749,15 @@ dependencies = [
4617 "thiserror 2.0.21",4749 "thiserror 2.0.21",
4618 ]4750 ]
4619 4751
4752+[[package]]
4753+name = "oid-registry"
4754+version = "0.7.1"
4755+source = "registry+https://github.com/rust-lang/crates.io-index"
4756+checksum = "a8d8034d9489cdaf79228eb9f6a3b8d7bb32ba00d6645ebd48eef4077ceb5bd9"
4757+dependencies = [
4758+ "asn1-rs",
4759+]
4760+
4620 [[package]]4761 [[package]]
4621 name = "olpc-cjson"4762 name = "olpc-cjson"
4622 version = "0.1.4"4763 version = "0.1.4"
@@ -4674,12 +4815,49 @@ version = "0.3.1"
4674 source = "registry+https://github.com/rust-lang/crates.io-index"4815 source = "registry+https://github.com/rust-lang/crates.io-index"
4675 checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"4816 checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
4676 4817
4818+[[package]]
4819+name = "openssl"
4820+version = "0.10.81"
4821+source = "registry+https://github.com/rust-lang/crates.io-index"
4822+checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45"
4823+dependencies = [
4824+ "bitflags 2.13.2",
4825+ "cfg-if",
4826+ "foreign-types",
4827+ "libc",
4828+ "openssl-macros",
4829+ "openssl-sys",
4830+]
4831+
4832+[[package]]
4833+name = "openssl-macros"
4834+version = "0.1.1"
4835+source = "registry+https://github.com/rust-lang/crates.io-index"
4836+checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
4837+dependencies = [
4838+ "proc-macro2",
4839+ "quote",
4840+ "syn 2.0.119",
4841+]
4842+
4677 [[package]]4843 [[package]]
4678 name = "openssl-probe"4844 name = "openssl-probe"
4679 version = "0.2.1"4845 version = "0.2.1"
4680 source = "registry+https://github.com/rust-lang/crates.io-index"4846 source = "registry+https://github.com/rust-lang/crates.io-index"
4681 checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"4847 checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
4682 4848
4849+[[package]]
4850+name = "openssl-sys"
4851+version = "0.9.117"
4852+source = "registry+https://github.com/rust-lang/crates.io-index"
4853+checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"
4854+dependencies = [
4855+ "cc",
4856+ "libc",
4857+ "pkg-config",
4858+ "vcpkg",
4859+]
4860+
4683 [[package]]4861 [[package]]
4684 name = "ordered-float"4862 name = "ordered-float"
4685 version = "5.5.0"4863 version = "5.5.0"
@@ -4813,6 +4991,12 @@ version = "1.0.15"
4813 source = "registry+https://github.com/rust-lang/crates.io-index"4991 source = "registry+https://github.com/rust-lang/crates.io-index"
4814 checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"4992 checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
4815 4993
4994+[[package]]
4995+name = "pastey"
4996+version = "0.1.1"
4997+source = "registry+https://github.com/rust-lang/crates.io-index"
4998+checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"
4999+
4816 [[package]]5000 [[package]]
4817 name = "pastey"5001 name = "pastey"
4818 version = "0.2.3"5002 version = "0.2.3"
@@ -5928,6 +6112,15 @@ dependencies = [
5928 "semver",6112 "semver",
5929 ]6113 ]
5930 6114
6115+[[package]]
6116+name = "rusticata-macros"
6117+version = "4.1.0"
6118+source = "registry+https://github.com/rust-lang/crates.io-index"
6119+checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"
6120+dependencies = [
6121+ "nom 7.1.3",
6122+]
6123+
5931 [[package]]6124 [[package]]
5932 name = "rustix"6125 name = "rustix"
5933 version = "0.38.44"6126 version = "0.38.44"
@@ -6202,6 +6395,26 @@ dependencies = [
6202 "serde_derive",6395 "serde_derive",
6203 ]6396 ]
6204 6397
6398+[[package]]
6399+name = "serde_bytes"
6400+version = "0.11.19"
6401+source = "registry+https://github.com/rust-lang/crates.io-index"
6402+checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8"
6403+dependencies = [
6404+ "serde",
6405+ "serde_core",
6406+]
6407+
6408+[[package]]
6409+name = "serde_cbor_2"
6410+version = "0.13.0"
6411+source = "registry+https://github.com/rust-lang/crates.io-index"
6412+checksum = "34aec2709de9078e077090abd848e967abab63c9fb3fdb5d4799ad359d8d482c"
6413+dependencies = [
6414+ "half",
6415+ "serde",
6416+]
6417+
6205 [[package]]6418 [[package]]
6206 name = "serde_core"6419 name = "serde_core"
6207 version = "1.0.229"6420 version = "1.0.229"
@@ -6762,6 +6975,17 @@ dependencies = [
6762 "futures-core",6975 "futures-core",
6763 ]6976 ]
6764 6977
6978+[[package]]
6979+name = "synstructure"
6980+version = "0.13.2"
6981+source = "registry+https://github.com/rust-lang/crates.io-index"
6982+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
6983+dependencies = [
6984+ "proc-macro2",
6985+ "quote",
6986+ "syn 2.0.119",
6987+]
6988+
6765 [[package]]6989 [[package]]
6766 name = "synstructure"6990 name = "synstructure"
6767 version = "0.14.0"6991 version = "0.14.0"
@@ -7126,6 +7350,18 @@ dependencies = [
7126 "tokio",7350 "tokio",
7127 ]7351 ]
7128 7352
7353+[[package]]
7354+name = "tokio-stream"
7355+version = "0.1.19"
7356+source = "registry+https://github.com/rust-lang/crates.io-index"
7357+checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b"
7358+dependencies = [
7359+ "futures-core",
7360+ "pin-project-lite",
7361+ "tokio",
7362+ "tokio-util",
7363+]
7364+
7129 [[package]]7365 [[package]]
7130 name = "tokio-tungstenite"7366 name = "tokio-tungstenite"
7131 version = "0.29.0"7367 version = "0.29.0"
@@ -7742,7 +7978,7 @@ dependencies = [
7742 "num-traits",7978 "num-traits",
7743 "pack1",7979 "pack1",
7744 "parking_lot",7980 "parking_lot",
7745- "pastey",7981+ "pastey 0.2.3",
7746 "polling",7982 "polling",
7747 "rand 0.9.5",7983 "rand 0.9.5",
7748 "rapidhash",7984 "rapidhash",
@@ -8052,6 +8288,7 @@ dependencies = [
8052 "idna",8288 "idna",
8053 "percent-encoding",8289 "percent-encoding",
8054 "serde",8290 "serde",
8291+ "serde_derive",
8055 ]8292 ]
8056 8293
8057 [[package]]8294 [[package]]
@@ -8097,6 +8334,12 @@ version = "0.1.1"
8097 source = "registry+https://github.com/rust-lang/crates.io-index"8334 source = "registry+https://github.com/rust-lang/crates.io-index"
8098 checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"8335 checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
8099 8336
8337+[[package]]
8338+name = "vcpkg"
8339+version = "0.2.15"
8340+source = "registry+https://github.com/rust-lang/crates.io-index"
8341+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
8342+
8100 [[package]]8343 [[package]]
8101 name = "version_check"8344 name = "version_check"
8102 version = "0.9.5"8345 version = "0.9.5"
@@ -8250,6 +8493,107 @@ dependencies = [
8250 "string_cache_codegen 0.11.2",8493 "string_cache_codegen 0.11.2",
8251 ]8494 ]
8252 8495
8496+[[package]]
8497+name = "webauthn-attestation-ca"
8498+version = "0.5.5"
8499+source = "registry+https://github.com/rust-lang/crates.io-index"
8500+checksum = "6475c0bbd1a3f04afaa3e98880408c5be61680c5e6bd3c6f8c250990d5d3e18e"
8501+dependencies = [
8502+ "base64urlsafedata",
8503+ "openssl",
8504+ "openssl-sys",
8505+ "serde",
8506+ "tracing",
8507+ "uuid",
8508+]
8509+
8510+[[package]]
8511+name = "webauthn-authenticator-rs"
8512+version = "0.5.5"
8513+source = "registry+https://github.com/rust-lang/crates.io-index"
8514+checksum = "779e9c80ff248c7e12ea967f909249101f6e86f70fccd742d4b66c490c1710b4"
8515+dependencies = [
8516+ "async-stream",
8517+ "async-trait",
8518+ "base64 0.21.7",
8519+ "base64urlsafedata",
8520+ "bitflags 1.3.2",
8521+ "futures",
8522+ "hex",
8523+ "nom 7.1.3",
8524+ "num-derive",
8525+ "num-traits",
8526+ "openssl",
8527+ "openssl-sys",
8528+ "serde",
8529+ "serde_bytes",
8530+ "serde_cbor_2",
8531+ "serde_json",
8532+ "thiserror 1.0.69",
8533+ "tokio",
8534+ "tokio-stream",
8535+ "tracing",
8536+ "unicode-normalization",
8537+ "url",
8538+ "uuid",
8539+ "webauthn-rs-core",
8540+ "webauthn-rs-proto",
8541+]
8542+
8543+[[package]]
8544+name = "webauthn-rs"
8545+version = "0.5.5"
8546+source = "registry+https://github.com/rust-lang/crates.io-index"
8547+checksum = "6c548915e0e92ee946bbf2aecf01ea21bef53d974b0793cc6732ba81a03fc422"
8548+dependencies = [
8549+ "base64urlsafedata",
8550+ "serde",
8551+ "tracing",
8552+ "url",
8553+ "uuid",
8554+ "webauthn-rs-core",
8555+]
8556+
8557+[[package]]
8558+name = "webauthn-rs-core"
8559+version = "0.5.5"
8560+source = "registry+https://github.com/rust-lang/crates.io-index"
8561+checksum = "296d2d501feb715d80b8e186fb88bab1073bca17f460303a1013d17b673bea6a"
8562+dependencies = [
8563+ "base64 0.21.7",
8564+ "base64urlsafedata",
8565+ "der-parser",
8566+ "hex",
8567+ "nom 7.1.3",
8568+ "openssl",
8569+ "openssl-sys",
8570+ "rand 0.9.5",
8571+ "rand_chacha 0.9.0",
8572+ "serde",
8573+ "serde_cbor_2",
8574+ "serde_json",
8575+ "thiserror 1.0.69",
8576+ "tracing",
8577+ "url",
8578+ "uuid",
8579+ "webauthn-attestation-ca",
8580+ "webauthn-rs-proto",
8581+ "x509-parser",
8582+]
8583+
8584+[[package]]
8585+name = "webauthn-rs-proto"
8586+version = "0.5.5"
8587+source = "registry+https://github.com/rust-lang/crates.io-index"
8588+checksum = "c37393beac9c1ed1ca6dbb30b1e01783fb316ab3a45d90ecd48c99052dd7ef1e"
8589+dependencies = [
8590+ "base64 0.21.7",
8591+ "base64urlsafedata",
8592+ "serde",
8593+ "serde_json",
8594+ "url",
8595+]
8596+
8253 [[package]]8597 [[package]]
8254 name = "webpki-root-certs"8598 name = "webpki-root-certs"
8255 version = "1.0.9"8599 version = "1.0.9"
@@ -8566,6 +8910,23 @@ dependencies = [
8566 "tap",8910 "tap",
8567 ]8911 ]
8568 8912
8913+[[package]]
8914+name = "x509-parser"
8915+version = "0.16.0"
8916+source = "registry+https://github.com/rust-lang/crates.io-index"
8917+checksum = "fcbc162f30700d6f3f82a24bf7cc62ffe7caea42c0b2cba8bf7f3ae50cf51f69"
8918+dependencies = [
8919+ "asn1-rs",
8920+ "data-encoding",
8921+ "der-parser",
8922+ "lazy_static",
8923+ "nom 7.1.3",
8924+ "oid-registry",
8925+ "rusticata-macros",
8926+ "thiserror 1.0.69",
8927+ "time",
8928+]
8929+
8569 [[package]]8930 [[package]]
8570 name = "xattr"8931 name = "xattr"
8571 version = "1.6.1"8932 version = "1.6.1"
@@ -8611,7 +8972,7 @@ dependencies = [
8611 "proc-macro2",8972 "proc-macro2",
8612 "quote",8973 "quote",
8613 "syn 3.0.9",8974 "syn 3.0.9",
8614- "synstructure",8975+ "synstructure 0.14.0",
8615 ]8976 ]
8616 8977
8617 [[package]]8978 [[package]]
@@ -8652,7 +9013,7 @@ dependencies = [
8652 "proc-macro2",9013 "proc-macro2",
8653 "quote",9014 "quote",
8654 "syn 3.0.9",9015 "syn 3.0.9",
8655- "synstructure",9016+ "synstructure 0.14.0",
8656 ]9017 ]
8657 9018
8658 [[package]]9019 [[package]]
crates/forge-core/migrations/0058_passkeys.sqladded+15 -0
@@ -0,0 +1,15 @@
1+-- WebAuthn passkeys. One row per registered credential. `credential_id` is the base64url
2+-- credential id, unique across accounts so a sign-in can find its owner without a username.
3+-- `passkey` is the serialized webauthn-rs Passkey (public key and sign counter). Applied by
4+-- store/migrate.rs.
5+
6+CREATE TABLE passkeys (
7+ id TEXT PRIMARY KEY,
8+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
9+ credential_id TEXT NOT NULL UNIQUE,
10+ passkey TEXT NOT NULL,
11+ name TEXT NOT NULL,
12+ created_at TEXT NOT NULL,
13+ last_used_at TEXT NULL
14+);
15+CREATE INDEX idx_passkeys_user ON passkeys(user_id);
crates/forge-core/src/audit.rsmodified+15 -0
@@ -110,6 +110,11 @@ pub enum AuditAction {
110 AdminGranted,110 AdminGranted,
111 AdminRevoked,111 AdminRevoked,
112 TotpDisabledByAdmin,112 TotpDisabledByAdmin,
113+ PasskeyAdded,
114+ PasskeyRenamed,
115+ PasskeyDeleted,
116+ PasskeysRemovedByAdmin,
117+ PasskeyLogin,
113 }118 }
114 119
115 impl AuditAction {120 impl AuditAction {
@@ -216,6 +221,11 @@ impl AuditAction {
216 AuditAction::AdminGranted,221 AuditAction::AdminGranted,
217 AuditAction::AdminRevoked,222 AuditAction::AdminRevoked,
218 AuditAction::TotpDisabledByAdmin,223 AuditAction::TotpDisabledByAdmin,
224+ AuditAction::PasskeyAdded,
225+ AuditAction::PasskeyRenamed,
226+ AuditAction::PasskeyDeleted,
227+ AuditAction::PasskeysRemovedByAdmin,
228+ AuditAction::PasskeyLogin,
219 ];229 ];
220 230
221 pub fn as_str(self) -> &'static str {231 pub fn as_str(self) -> &'static str {
@@ -321,6 +331,11 @@ impl AuditAction {
321 AuditAction::AdminGranted => "admin_granted",331 AuditAction::AdminGranted => "admin_granted",
322 AuditAction::AdminRevoked => "admin_revoked",332 AuditAction::AdminRevoked => "admin_revoked",
323 AuditAction::TotpDisabledByAdmin => "totp_disabled_by_admin",333 AuditAction::TotpDisabledByAdmin => "totp_disabled_by_admin",
334+ AuditAction::PasskeyAdded => "passkey_added",
335+ AuditAction::PasskeyRenamed => "passkey_renamed",
336+ AuditAction::PasskeyDeleted => "passkey_deleted",
337+ AuditAction::PasskeysRemovedByAdmin => "passkeys_removed_by_admin",
338+ AuditAction::PasskeyLogin => "passkey_login",
324 }339 }
325 }340 }
326 341
crates/forge-core/src/store/migrate.rsmodified+1 -0
@@ -97,6 +97,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
97 ),97 ),
98 (56, include_str!("../../migrations/0056_runner_build.sql")),98 (56, include_str!("../../migrations/0056_runner_build.sql")),
99 (57, include_str!("../../migrations/0057_runner_restart.sql")),99 (57, include_str!("../../migrations/0057_runner_restart.sql")),
100+ (58, include_str!("../../migrations/0058_passkeys.sql")),
100 ];101 ];
101 102
102 /// The highest migration version this binary knows about.103 /// The highest migration version this binary knows about.
crates/forge-core/src/store/mod.rsmodified+1 -0
@@ -22,6 +22,7 @@ pub mod mirrors;
22 pub mod notifications;22 pub mod notifications;
23 pub mod notifications_extra;23 pub mod notifications_extra;
24 pub mod orgs;24 pub mod orgs;
25+pub mod passkeys;
25 pub mod pinned;26 pub mod pinned;
26 pub mod profile_pins;27 pub mod profile_pins;
27 pub mod pulls;28 pub mod pulls;
crates/forge-core/src/store/passkeys.rsadded+293 -0
@@ -0,0 +1,293 @@
1+//! WebAuthn passkeys (migration 0058). The store keeps each credential as an opaque serialized
2+//! string; the web crate owns the format. Sign counts live inside that string, so an update
3+//! replaces it.
4+
5+use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id};
6+use crate::error::{Error, Result};
7+use crate::time::now_stamp;
8+
9+/// Most passkeys one account may hold.
10+pub const MAX_PASSKEYS: usize = 20;
11+/// Longest passkey name, in characters.
12+pub const MAX_NAME_CHARS: usize = 40;
13+
14+/// One registered passkey.
15+#[derive(Debug, Clone, PartialEq, Eq)]
16+pub struct PasskeyRow {
17+ pub id: String,
18+ pub user_id: String,
19+ /// Base64url credential id.
20+ pub credential_id: String,
21+ /// The serialized credential.
22+ pub passkey: String,
23+ pub name: String,
24+ pub created_at: String,
25+ pub last_used_at: Option<String>,
26+}
27+
28+const COLS: &str = "id, user_id, credential_id, passkey, name, created_at, last_used_at";
29+
30+fn map_row(row: &turso::Row) -> Result<PasskeyRow> {
31+ Ok(PasskeyRow {
32+ id: col_text(row, 0)?,
33+ user_id: col_text(row, 1)?,
34+ credential_id: col_text(row, 2)?,
35+ passkey: col_text(row, 3)?,
36+ name: col_text(row, 4)?,
37+ created_at: col_text(row, 5)?,
38+ last_used_at: col_opt_text(row, 6)?,
39+ })
40+}
41+
42+/// A trimmed passkey name, or the reason it is refused.
43+pub fn clean_name(name: &str) -> Result<String> {
44+ let name = name.trim();
45+ if name.is_empty()
46+ || name.chars().count() > MAX_NAME_CHARS
47+ || name.chars().any(char::is_control)
48+ {
49+ return Err(Error::Invalid(format!(
50+ "the name must be one line of 1 to {MAX_NAME_CHARS} characters"
51+ )));
52+ }
53+ Ok(name.to_owned())
54+}
55+
56+impl Store {
57+ /// The user's passkeys, oldest first.
58+ pub async fn list_passkeys(&self, user_id: &str) -> Result<Vec<PasskeyRow>> {
59+ let conn = self.read_conn().await;
60+ fetch_all(
61+ &conn,
62+ &format!("SELECT {COLS} FROM passkeys WHERE user_id = ?1 ORDER BY created_at, id"),
63+ (user_id.to_string(),),
64+ map_row,
65+ )
66+ .await
67+ }
68+
69+ pub async fn passkey_count(&self, user_id: &str) -> Result<i64> {
70+ let conn = self.read_conn().await;
71+ Ok(fetch_opt(
72+ &conn,
73+ "SELECT COUNT(*) FROM passkeys WHERE user_id = ?1",
74+ (user_id.to_string(),),
75+ |row| col_int(row, 0),
76+ )
77+ .await?
78+ .unwrap_or(0))
79+ }
80+
81+ /// The passkey with this credential id, whoever owns it.
82+ pub async fn passkey_by_credential(&self, credential_id: &str) -> Result<Option<PasskeyRow>> {
83+ let conn = self.read_conn().await;
84+ fetch_opt(
85+ &conn,
86+ &format!("SELECT {COLS} FROM passkeys WHERE credential_id = ?1 LIMIT 1"),
87+ (credential_id.to_string(),),
88+ map_row,
89+ )
90+ .await
91+ }
92+
93+ /// Stores a new passkey. Refused past `MAX_PASSKEYS` and for a credential id already stored.
94+ pub async fn add_passkey(
95+ &self,
96+ user_id: &str,
97+ credential_id: &str,
98+ passkey: &str,
99+ name: &str,
100+ ) -> Result<PasskeyRow> {
101+ let name = clean_name(name)?;
102+ let conn = self.inner.conn.lock().await;
103+ let held = fetch_opt(
104+ &conn,
105+ "SELECT COUNT(*) FROM passkeys WHERE user_id = ?1",
106+ (user_id.to_string(),),
107+ |row| col_int(row, 0),
108+ )
109+ .await?
110+ .unwrap_or(0);
111+ if usize::try_from(held).unwrap_or(usize::MAX) >= MAX_PASSKEYS {
112+ return Err(Error::Invalid(format!(
113+ "an account can hold at most {MAX_PASSKEYS} passkeys"
114+ )));
115+ }
116+ let taken = fetch_opt(
117+ &conn,
118+ "SELECT 1 FROM passkeys WHERE credential_id = ?1 LIMIT 1",
119+ (credential_id.to_string(),),
120+ |row| col_int(row, 0),
121+ )
122+ .await?;
123+ if taken.is_some() {
124+ return Err(Error::Conflict("this passkey is already registered".into()));
125+ }
126+ let row = PasskeyRow {
127+ id: new_id(),
128+ user_id: user_id.to_string(),
129+ credential_id: credential_id.to_string(),
130+ passkey: passkey.to_string(),
131+ name,
132+ created_at: now_stamp(),
133+ last_used_at: None,
134+ };
135+ conn.execute(
136+ "INSERT INTO passkeys (id, user_id, credential_id, passkey, name, created_at) \
137+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
138+ (
139+ row.id.clone(),
140+ row.user_id.clone(),
141+ row.credential_id.clone(),
142+ row.passkey.clone(),
143+ row.name.clone(),
144+ row.created_at.clone(),
145+ ),
146+ )
147+ .await
148+ .map_err(db_err)?;
149+ Ok(row)
150+ }
151+
152+ /// Records a sign-in: the updated serialized credential (with its new sign count) and the
153+ /// time of use.
154+ pub async fn touch_passkey(&self, id: &str, passkey: &str) -> Result<()> {
155+ let conn = self.inner.conn.lock().await;
156+ conn.execute(
157+ "UPDATE passkeys SET passkey = ?2, last_used_at = ?3 WHERE id = ?1",
158+ (id.to_string(), passkey.to_string(), now_stamp()),
159+ )
160+ .await
161+ .map_err(db_err)?;
162+ Ok(())
163+ }
164+
165+ /// Renames a passkey of `user_id`. Returns false when the user has no such passkey.
166+ pub async fn rename_passkey(&self, user_id: &str, id: &str, name: &str) -> Result<bool> {
167+ let name = clean_name(name)?;
168+ let conn = self.inner.conn.lock().await;
169+ let n = conn
170+ .execute(
171+ "UPDATE passkeys SET name = ?3 WHERE id = ?1 AND user_id = ?2",
172+ (id.to_string(), user_id.to_string(), name),
173+ )
174+ .await
175+ .map_err(db_err)?;
176+ Ok(n > 0)
177+ }
178+
179+ /// Deletes a passkey of `user_id`. Returns false when the user has no such passkey, which is
180+ /// also the answer for another account's passkey.
181+ pub async fn delete_passkey(&self, user_id: &str, id: &str) -> Result<bool> {
182+ let conn = self.inner.conn.lock().await;
183+ let n = conn
184+ .execute(
185+ "DELETE FROM passkeys WHERE id = ?1 AND user_id = ?2",
186+ (id.to_string(), user_id.to_string()),
187+ )
188+ .await
189+ .map_err(db_err)?;
190+ Ok(n > 0)
191+ }
192+
193+ /// Deletes every passkey of the user. Returns how many were removed.
194+ pub async fn delete_all_passkeys(&self, user_id: &str) -> Result<u64> {
195+ let conn = self.inner.conn.lock().await;
196+ conn.execute(
197+ "DELETE FROM passkeys WHERE user_id = ?1",
198+ (user_id.to_string(),),
199+ )
200+ .await
201+ .map_err(db_err)
202+ }
203+}
204+
205+#[cfg(test)]
206+mod tests {
207+ use super::*;
208+
209+ async fn store_with_users() -> (Store, String, String, tempfile::TempDir) {
210+ let dir = tempfile::tempdir().unwrap();
211+ let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
212+ let a = store
213+ .create_user("tahinli", None, "x", false)
214+ .await
215+ .unwrap();
216+ let b = store.create_user("other", None, "x", false).await.unwrap();
217+ (store, a.id, b.id, dir)
218+ }
219+
220+ #[tokio::test]
221+ async fn add_list_touch_rename_delete() {
222+ let (store, a, _b, _dir) = store_with_users().await;
223+ let row = store
224+ .add_passkey(&a, "cred-1", "{\"n\":1}", " Laptop ")
225+ .await
226+ .unwrap();
227+ assert_eq!(row.name, "Laptop");
228+ assert_eq!(store.passkey_count(&a).await.unwrap(), 1);
229+ let found = store
230+ .passkey_by_credential("cred-1")
231+ .await
232+ .unwrap()
233+ .unwrap();
234+ assert_eq!(found.user_id, a);
235+ assert!(found.last_used_at.is_none());
236+
237+ store.touch_passkey(&row.id, "{\"n\":2}").await.unwrap();
238+ let listed = store.list_passkeys(&a).await.unwrap();
239+ assert_eq!(listed[0].passkey, "{\"n\":2}");
240+ assert!(listed[0].last_used_at.is_some());
241+
242+ assert!(store.rename_passkey(&a, &row.id, "Phone").await.unwrap());
243+ assert_eq!(store.list_passkeys(&a).await.unwrap()[0].name, "Phone");
244+ assert!(store.rename_passkey(&a, &row.id, " ").await.is_err());
245+ assert!(store.delete_passkey(&a, &row.id).await.unwrap());
246+ assert_eq!(store.passkey_count(&a).await.unwrap(), 0);
247+ }
248+
249+ #[tokio::test]
250+ async fn other_accounts_cannot_rename_or_delete() {
251+ let (store, a, b, _dir) = store_with_users().await;
252+ let row = store
253+ .add_passkey(&a, "cred-1", "{}", "Laptop")
254+ .await
255+ .unwrap();
256+ assert!(!store.rename_passkey(&b, &row.id, "Mine").await.unwrap());
257+ assert!(!store.delete_passkey(&b, &row.id).await.unwrap());
258+ assert_eq!(store.list_passkeys(&a).await.unwrap()[0].name, "Laptop");
259+ }
260+
261+ #[tokio::test]
262+ async fn duplicate_credential_and_limit_are_refused() {
263+ let (store, a, b, _dir) = store_with_users().await;
264+ store.add_passkey(&a, "cred-1", "{}", "One").await.unwrap();
265+ assert!(matches!(
266+ store.add_passkey(&b, "cred-1", "{}", "Two").await,
267+ Err(Error::Conflict(_))
268+ ));
269+ for i in 1..MAX_PASSKEYS {
270+ store
271+ .add_passkey(&a, &format!("c{i}"), "{}", "More")
272+ .await
273+ .unwrap();
274+ }
275+ assert!(
276+ store
277+ .add_passkey(&a, "overflow", "{}", "More")
278+ .await
279+ .is_err()
280+ );
281+ }
282+
283+ #[tokio::test]
284+ async fn delete_all_removes_only_that_users_passkeys() {
285+ let (store, a, b, _dir) = store_with_users().await;
286+ store.add_passkey(&a, "c1", "{}", "One").await.unwrap();
287+ store.add_passkey(&a, "c2", "{}", "Two").await.unwrap();
288+ store.add_passkey(&b, "c3", "{}", "Three").await.unwrap();
289+ assert_eq!(store.delete_all_passkeys(&a).await.unwrap(), 2);
290+ assert_eq!(store.passkey_count(&a).await.unwrap(), 0);
291+ assert_eq!(store.passkey_count(&b).await.unwrap(), 1);
292+ }
293+}
crates/forge-core/src/store/user_delete.rsmodified+1 -0
@@ -120,6 +120,7 @@ const REMOVED: &[(&str, &str, &str)] = &[
120 ("profile pins", "profile_pins", "user_id"),120 ("profile pins", "profile_pins", "user_id"),
121 ("issue assignments", "issue_assignees", "user_id"),121 ("issue assignments", "issue_assignees", "user_id"),
122 ("recovery codes", "recovery_codes", "user_id"),122 ("recovery codes", "recovery_codes", "user_id"),
123+ ("passkeys", "passkeys", "user_id"),
123 ("avatar", "avatars", "user_id"),124 ("avatar", "avatars", "user_id"),
124 ("repo watches", "repo_watches", "user_id"),125 ("repo watches", "repo_watches", "user_id"),
125 ("issue subscriptions", "issue_subscriptions", "user_id"),126 ("issue subscriptions", "issue_subscriptions", "user_id"),
crates/forge-web/Cargo.tomlmodified+3 -0
@@ -55,6 +55,8 @@ lettre.workspace = true
55 zip = { workspace = true }55 zip = { workspace = true }
56 tar.workspace = true56 tar.workspace = true
57 flate2.workspace = true57 flate2.workspace = true
58+webauthn-rs = { version = "0.5.5", features = ["danger-allow-state-serialisation", "conditional-ui"] }
59+webauthn-rs-proto = "0.5.5"
58 60
59 [build-dependencies]61 [build-dependencies]
60 grass.workspace = true62 grass.workspace = true
@@ -66,3 +68,4 @@ tempfile.workspace = true
66 forge-runner = { workspace = true, features = ["test-host-executor"] }68 forge-runner = { workspace = true, features = ["test-host-executor"] }
67 image = { workspace = true }69 image = { workspace = true }
68 scraper = { workspace = true }70 scraper = { workspace = true }
71+webauthn-authenticator-rs = { version = "0.5.5", features = ["softpasskey"] }
crates/forge-web/assets/nav.jsmodified+217 -0
@@ -1798,3 +1798,220 @@
1798 }).observe(document.body, { childList: true, subtree: true });1798 }).observe(document.body, { childList: true, subtree: true });
1799 enhance();1799 enhance();
1800 })();1800 })();
1801+
1802+// Passkeys (WebAuthn). The add form on the security settings page and the "Sign in with a passkey"
1803+// button and conditional autofill on the login page. The server keeps the ceremony state; this only
1804+// moves the options and the browser's answer between the two, converting base64url to and from
1805+// buffers. Everything passkey related stays hidden unless the browser has PublicKeyCredential.
1806+(function () {
1807+ 'use strict';
1808+ if (window.__forgePasskeys) { return; }
1809+ window.__forgePasskeys = true;
1810+ if (!window.PublicKeyCredential || !navigator.credentials) { return; }
1811+
1812+ var TR = (document.documentElement.getAttribute('lang') || '').indexOf('tr') === 0;
1813+ var T = TR
1814+ ? { cancelled: 'Geçiş anahtarı isteği iptal edildi veya süresi doldu.', exists: 'Bu cihazdaki geçiş anahtarı zaten kayıtlı.', fail: 'Geçiş anahtarı işlemi başarısız. Yeniden deneyin.' }
1815+ : { cancelled: 'The passkey request was cancelled or timed out.', exists: 'A passkey from this device is already registered.', fail: 'The passkey step failed. Try again.' };
1816+
1817+ function toBuffer(text) {
1818+ var s = text.replace(/-/g, '+').replace(/_/g, '/');
1819+ while (s.length % 4) { s += '='; }
1820+ var bin = atob(s);
1821+ var out = new Uint8Array(bin.length);
1822+ for (var i = 0; i < bin.length; i++) { out[i] = bin.charCodeAt(i); }
1823+ return out.buffer;
1824+ }
1825+
1826+ function toText(buffer) {
1827+ var bytes = new Uint8Array(buffer);
1828+ var bin = '';
1829+ for (var i = 0; i < bytes.length; i++) { bin += String.fromCharCode(bytes[i]); }
1830+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
1831+ }
1832+
1833+ function creationOptions(pk) {
1834+ pk.challenge = toBuffer(pk.challenge);
1835+ pk.user.id = toBuffer(pk.user.id);
1836+ (pk.excludeCredentials || []).forEach(function (c) { c.id = toBuffer(c.id); });
1837+ return pk;
1838+ }
1839+
1840+ function requestOptions(pk) {
1841+ pk.challenge = toBuffer(pk.challenge);
1842+ (pk.allowCredentials || []).forEach(function (c) { c.id = toBuffer(c.id); });
1843+ return pk;
1844+ }
1845+
1846+ function registration(cred) {
1847+ return {
1848+ id: cred.id,
1849+ rawId: toText(cred.rawId),
1850+ type: cred.type,
1851+ response: {
1852+ attestationObject: toText(cred.response.attestationObject),
1853+ clientDataJSON: toText(cred.response.clientDataJSON),
1854+ transports: cred.response.getTransports ? cred.response.getTransports() : []
1855+ },
1856+ extensions: cred.getClientExtensionResults ? cred.getClientExtensionResults() : {}
1857+ };
1858+ }
1859+
1860+ function assertion(cred) {
1861+ var r = cred.response;
1862+ return {
1863+ id: cred.id,
1864+ rawId: toText(cred.rawId),
1865+ type: cred.type,
1866+ response: {
1867+ authenticatorData: toText(r.authenticatorData),
1868+ clientDataJSON: toText(r.clientDataJSON),
1869+ signature: toText(r.signature),
1870+ userHandle: r.userHandle ? toText(r.userHandle) : null
1871+ },
1872+ extensions: cred.getClientExtensionResults ? cred.getClientExtensionResults() : {}
1873+ };
1874+ }
1875+
1876+ // POSTs a form body and returns the JSON answer. A refusal throws { server: message }.
1877+ function post(url, fields) {
1878+ var body = new URLSearchParams();
1879+ Object.keys(fields).forEach(function (k) { body.set(k, fields[k]); });
1880+ return fetch(url, {
1881+ method: 'POST',
1882+ credentials: 'same-origin',
1883+ headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
1884+ body: body.toString()
1885+ }).then(function (r) {
1886+ return r.json().then(function (j) { return { ok: r.ok, json: j }; }, function () { return { ok: false, json: {} }; });
1887+ }).then(function (res) {
1888+ if (!res.ok) { throw { server: res.json && res.json.error ? res.json.error : T.fail }; }
1889+ return res.json;
1890+ });
1891+ }
1892+
1893+ function friendly(err) {
1894+ if (err && err.server) { return err.server; }
1895+ if (err && err.name === 'NotAllowedError') { return T.cancelled; }
1896+ if (err && err.name === 'InvalidStateError') { return T.exists; }
1897+ return T.fail;
1898+ }
1899+
1900+ function show(box, text) {
1901+ if (!box) { return; }
1902+ box.textContent = text || '';
1903+ box.hidden = !text;
1904+ }
1905+
1906+ // Soft move to the page that shows the result, through nav.js's own link handling.
1907+ function go(href) {
1908+ var a = document.createElement('a');
1909+ a.href = href;
1910+ a.style.display = 'none';
1911+ document.body.appendChild(a);
1912+ a.click();
1913+ a.remove();
1914+ }
1915+
1916+ // ---- settings: add a passkey ----
1917+
1918+ document.addEventListener('submit', function (e) {
1919+ var form = e.target;
1920+ if (!form || !form.hasAttribute || !form.hasAttribute('data-passkey-add')) { return; }
1921+ e.preventDefault();
1922+ if (form.__busy) { return; }
1923+ var box = form.querySelector('.passkey-error');
1924+ var button = form.querySelector('button[type=submit]');
1925+ var csrf = form.elements.csrf.value;
1926+ form.__busy = true;
1927+ if (button) { button.disabled = true; }
1928+ show(box, '');
1929+ post('/settings/security/passkeys/register/begin', { csrf: csrf, name: form.elements.name.value }).then(function (begun) {
1930+ return navigator.credentials.create({ publicKey: creationOptions(begun.options.publicKey) }).then(function (cred) {
1931+ if (!cred) { throw { name: 'NotAllowedError' }; }
1932+ return post('/settings/security/passkeys/register/finish', { csrf: csrf, id: begun.id, credential: JSON.stringify(registration(cred)) });
1933+ });
1934+ }).then(function () {
1935+ go('/settings/security?saved=passkey-added');
1936+ }).catch(function (err) {
1937+ show(box, friendly(err));
1938+ }).then(function () {
1939+ form.__busy = false;
1940+ if (button) { button.disabled = false; }
1941+ });
1942+ }, true);
1943+
1944+ // ---- login: button and conditional autofill ----
1945+
1946+ var conditional = null; // AbortController of the pending autofill request
1947+
1948+ function loginParts() {
1949+ var wrap = document.querySelector('[data-passkey-login]');
1950+ var form = document.querySelector('form[action="/login"]');
1951+ if (!wrap || !form || !form.elements.precsrf) { return null; }
1952+ return { wrap: wrap, form: form, box: wrap.querySelector('.passkey-error') };
1953+ }
1954+
1955+ // One sign-in: begin, ask the browser, finish, then go where `next` says.
1956+ function signIn(parts, auto) {
1957+ var precsrf = parts.form.elements.precsrf.value;
1958+ var next = parts.form.elements.next ? parts.form.elements.next.value : '/';
1959+ var ctl = new AbortController();
1960+ if (auto) { conditional = ctl; }
1961+ return post('/login/passkey/begin', { precsrf: precsrf }).then(function (begun) {
1962+ var opts = { publicKey: requestOptions(begun.options.publicKey), signal: ctl.signal };
1963+ if (auto) { opts.mediation = 'conditional'; }
1964+ return navigator.credentials.get(opts).then(function (cred) {
1965+ if (!cred) { throw { name: 'NotAllowedError' }; }
1966+ return post('/login/passkey/finish', { precsrf: precsrf, id: begun.id, next: next, credential: JSON.stringify(assertion(cred)) });
1967+ });
1968+ }).then(function (done) {
1969+ location.assign(done.next || '/');
1970+ });
1971+ }
1972+
1973+ function startAutofill(parts) {
1974+ if (!PublicKeyCredential.isConditionalMediationAvailable) { return; }
1975+ PublicKeyCredential.isConditionalMediationAvailable().then(function (yes) {
1976+ if (!yes || !document.contains(parts.wrap)) { return; }
1977+ signIn(parts, true).catch(function (err) {
1978+ // Aborted by the button, dismissed or unsupported: nothing to say. Only a server refusal shows.
1979+ if (err && err.server) { show(parts.box, err.server); }
1980+ });
1981+ }, function () { });
1982+ }
1983+
1984+ document.addEventListener('click', function (e) {
1985+ var t = e.target;
1986+ var btn = t && t.closest ? t.closest('[data-passkey-signin]') : null;
1987+ if (!btn) { return; }
1988+ e.preventDefault();
1989+ var parts = loginParts();
1990+ if (!parts || btn.disabled) { return; }
1991+ if (conditional) { conditional.abort(); conditional = null; }
1992+ btn.disabled = true;
1993+ show(parts.box, '');
1994+ signIn(parts, false).catch(function (err) {
1995+ show(parts.box, friendly(err));
1996+ btn.disabled = false;
1997+ });
1998+ });
1999+
2000+ // Shows the passkey parts that are in the page and starts the autofill request once.
2001+ function reveal() {
2002+ document.querySelectorAll('[data-passkey-add], [data-passkey-login]').forEach(function (el) { el.hidden = false; });
2003+ var parts = loginParts();
2004+ if (parts && !parts.wrap.__auto) {
2005+ parts.wrap.__auto = true;
2006+ startAutofill(parts);
2007+ }
2008+ }
2009+
2010+ var queued = false;
2011+ new MutationObserver(function () {
2012+ if (queued) { return; }
2013+ queued = true;
2014+ Promise.resolve().then(function () { queued = false; reveal(); });
2015+ }).observe(document.body, { childList: true, subtree: true });
2016+ reveal();
2017+})();
crates/forge-web/src/mail/account.rsmodified+39 -0
@@ -103,3 +103,42 @@ pub async fn send_password_changed(
103 .await?;103 .await?;
104 Ok(())104 Ok(())
105 }105 }
106+
107+/// Which passkey change a notice reports.
108+#[derive(Clone, Copy)]
109+pub enum PasskeyChange {
110+ Added,
111+ Removed,
112+}
113+
114+/// Queues a notice that a passkey was added or removed, to the user's verified address. A user
115+/// without a verified address gets nothing. `passkey_id` keeps two changes from sharing a key.
116+pub async fn send_passkey_notice(
117+ state: &AppState,
118+ user: &User,
119+ change: PasskeyChange,
120+ passkey_id: &str,
121+ name: &str,
122+) -> forge_core::Result<()> {
123+ let Some(address) = user.email.as_deref() else {
124+ return Ok(());
125+ };
126+ if !state.store.email_is_verified(&user.id).await? {
127+ return Ok(());
128+ }
129+ let (tag, (subject, body)) = match change {
130+ PasskeyChange::Added => ("added", templates::passkey_added(&user.username, name)),
131+ PasskeyChange::Removed => ("removed", templates::passkey_removed(&user.username, name)),
132+ };
133+ enqueue(
134+ state,
135+ &format!("passkey-{tag}:{}:{passkey_id}", user.id),
136+ MailKind::Other,
137+ Some(&user.id),
138+ address,
139+ &subject,
140+ &body,
141+ )
142+ .await?;
143+ Ok(())
144+}
crates/forge-web/src/mail/templates.rsmodified+25 -0
@@ -145,6 +145,31 @@ pub fn password_changed(username: &str) -> (String, String) {
145 )145 )
146 }146 }
147 147
148+/// The notice sent after a passkey is added to the account.
149+pub fn passkey_added(username: &str, name: &str) -> (String, String) {
150+ (
151+ "A passkey was added to your forge account".to_owned(),
152+ format!(
153+ "Hi {username},\n\nA passkey named \"{name}\" was just added to your forge \
154+ account. It can now be used to sign in. If that was you, nothing more to do. If it \
155+ was not you, remove the passkey from your security settings, change your password \
156+ and contact the administrator.\n"
157+ ),
158+ )
159+}
160+
161+/// The notice sent after a passkey is removed from the account.
162+pub fn passkey_removed(username: &str, name: &str) -> (String, String) {
163+ (
164+ "A passkey was removed from your forge account".to_owned(),
165+ format!(
166+ "Hi {username},\n\nThe passkey named \"{name}\" was just removed from your forge \
167+ account. If that was you, nothing more to do. If it was not you, change your \
168+ password now and contact the administrator.\n"
169+ ),
170+ )
171+}
172+
148 /// The email verification mail. The link works once and for 24 hours.173 /// The email verification mail. The link works once and for 24 hours.
149 pub fn email_verify(username: &str, link: &str) -> (String, String) {174 pub fn email_verify(username: &str, link: &str) -> (String, String) {
150 (175 (
crates/forge-web/src/pages/admin_user_detail.rsmodified+57 -0
@@ -22,6 +22,7 @@ use crate::i18n::admin::{self as g, K};
22 use crate::i18n::{self, Key, Lang};22 use crate::i18n::{self, Key, Lang};
23 use crate::pages::admin_users::admin_only;23 use crate::pages::admin_users::admin_only;
24 use crate::pages::issues_list::stamp_unix;24 use crate::pages::issues_list::stamp_unix;
25+use crate::pages::passkeys::s;
25 use crate::state::AppState;26 use crate::state::AppState;
26 use crate::views::{alert, enc, shell, user_facing_message};27 use crate::views::{alert, enc, shell, user_facing_message};
27 28
@@ -45,6 +46,7 @@ struct Detail {
45 target: User,46 target: User,
46 facts: AccountFacts,47 facts: AccountFacts,
47 suspension: Option<Suspension>,48 suspension: Option<Suspension>,
49+ passkeys: i64,
48 }50 }
49 51
50 /// What the page says above the facts after an action.52 /// What the page says above the facts after an action.
@@ -62,6 +64,7 @@ enum Action {
62 SetAdmin,64 SetAdmin,
63 ResetLink,65 ResetLink,
64 Disable2fa,66 Disable2fa,
67+ RemovePasskeys,
65 }68 }
66 69
67 fn is_ghost(user: &User) -> bool {70 fn is_ghost(user: &User) -> bool {
@@ -80,6 +83,7 @@ async fn load(cx: &Cx) -> Result<Detail> {
80 Ok(Detail {83 Ok(Detail {
81 facts: store.account_facts(&target.id).await?,84 facts: store.account_facts(&target.id).await?,
82 suspension: store.suspension(&target.id).await?,85 suspension: store.suspension(&target.id).await?,
86+ passkeys: store.passkey_count(&target.id).await?,
83 target,87 target,
84 })88 })
85 }89 }
@@ -91,6 +95,11 @@ fn done_text(lang: Lang, done: &str) -> Option<&'static str> {
91 "admin_on" => at(lang, A::OkAdminOn),95 "admin_on" => at(lang, A::OkAdminOn),
92 "admin_off" => at(lang, A::OkAdminOff),96 "admin_off" => at(lang, A::OkAdminOff),
93 "tfa_off" => at(lang, A::Ok2faDisabled),97 "tfa_off" => at(lang, A::Ok2faDisabled),
98+ "passkeys_off" => s(
99+ lang,
100+ "All passkeys removed.",
101+ "Tüm geçiş anahtarları kaldırıldı.",
102+ ),
94 _ => return None,103 _ => return None,
95 })104 })
96 }105 }
@@ -115,6 +124,7 @@ async fn detail_body(
115 target,124 target,
116 facts,125 facts,
117 suspension,126 suspension,
127+ passkeys,
118 } = detail;128 } = detail;
119 let base = format!("/admin/users/{}", enc(&target.id));129 let base = format!("/admin/users/{}", enc(&target.id));
120 let own = target.id == viewer_id;130 let own = target.id == viewer_id;
@@ -149,6 +159,8 @@ async fn detail_body(
149 let admin_action = format!("{base}/admin");159 let admin_action = format!("{base}/admin");
150 let reset_action = format!("{base}/reset-link");160 let reset_action = format!("{base}/reset-link");
151 let tfa_action = format!("{base}/disable-2fa");161 let tfa_action = format!("{base}/disable-2fa");
162+ let passkeys_action = format!("{base}/remove-passkeys");
163+ let passkey_count = passkeys.to_string();
152 let delete_href = format!("{base}/delete");164 let delete_href = format!("{base}/delete");
153 let Notice { done, error, link } = notice;165 let Notice { done, error, link } = notice;
154 Ok(view! {166 Ok(view! {
@@ -174,6 +186,7 @@ async fn detail_body(
174 <div><dt>(at(lang, A::LastLogin))</dt><dd>(last_login.as_str())</dd></div>186 <div><dt>(at(lang, A::LastLogin))</dt><dd>(last_login.as_str())</dd></div>
175 <div><dt>(at(lang, A::Repositories))</dt><dd>(repos.as_str())</dd></div>187 <div><dt>(at(lang, A::Repositories))</dt><dd>(repos.as_str())</dd></div>
176 <div><dt>(at(lang, A::TwoFactor))</dt><dd>(tfa)</dd></div>188 <div><dt>(at(lang, A::TwoFactor))</dt><dd>(tfa)</dd></div>
189+ <div><dt>(s(lang, "Passkeys", "Geçiş anahtarları"))</dt><dd>(passkey_count.as_str())</dd></div>
177 </dl>190 </dl>
178 </section>191 </section>
179 <section class="card">192 <section class="card">
@@ -230,6 +243,25 @@ async fn detail_body(
230 <p class="small">(at(lang, A::Off))</p>243 <p class="small">(at(lang, A::Off))</p>
231 }244 }
232 </div>245 </div>
246+ <div class="action-box">
247+ <h3>(s(lang, "Remove all passkeys", "Tüm geçiş anahtarlarını kaldır"))</h3>
248+ <p class="muted small">(s(lang, "For a user who lost their devices. They can still sign in with a password.", "Cihazlarını kaybeden kullanıcı için. Parolayla girmeye devam edebilir."))</p>
249+ if passkeys > 0 {
250+ <details class="confirm-inline">
251+ <summary class="button danger">(s(lang, "Remove all passkeys", "Tüm geçiş anahtarlarını kaldır"))</summary>
252+ <div class="confirm-pop">
253+ <p>(s(lang, "Remove every passkey of this user?", "Bu kullanıcının tüm geçiş anahtarları kaldırılsın mı?"))</p>
254+ <form method="post" action=(passkeys_action.as_str())>
255+ <input type="hidden" name="csrf" value=(csrf)>
256+ <button type="submit" class="danger">(s(lang, "Remove all", "Hepsini kaldır"))</button>
257+ <button type="button" data-close-details="">(s(lang, "Cancel", "Vazgeç"))</button>
258+ </form>
259+ </div>
260+ </details>
261+ } else {
262+ <p class="small">(at(lang, A::Off))</p>
263+ }
264+ </div>
233 </div>265 </div>
234 <p class="link-row">266 <p class="link-row">
235 <a href="/admin/users">(g::t(lang, K::BackToUsers))</a>267 <a href="/admin/users">(g::t(lang, K::BackToUsers))</a>
@@ -357,6 +389,26 @@ async fn perform(cx: &Cx, form: &ActionForm, action: Action) -> Result<(Outcome,
357 Outcome::Refused(at(lang, A::ErrNoEmail).to_owned())389 Outcome::Refused(at(lang, A::ErrNoEmail).to_owned())
358 }390 }
359 }391 }
392+ Action::RemovePasskeys => {
393+ let removed = store.delete_all_passkeys(&target.id).await?;
394+ if removed > 0 {
395+ audit(
396+ AuditAction::PasskeysRemovedByAdmin,
397+ serde_json::json!({ "count": removed }),
398+ )
399+ .await;
400+ Outcome::Done("passkeys_off")
401+ } else {
402+ Outcome::Refused(
403+ s(
404+ lang,
405+ "This user has no passkeys.",
406+ "Bu kullanıcının geçiş anahtarı yok.",
407+ )
408+ .to_owned(),
409+ )
410+ }
411+ }
360 };412 };
361 let detail = if matches!(outcome, Outcome::Done(_)) {413 let detail = if matches!(outcome, Outcome::Done(_)) {
362 detail414 detail
@@ -419,3 +471,8 @@ async fn reset_link(cx: &Cx, Form(form): Form<ActionForm>) -> Result<impl View>
419 async fn disable_2fa(cx: &Cx, Form(form): Form<ActionForm>) -> Result<impl View> {471 async fn disable_2fa(cx: &Cx, Form(form): Form<ActionForm>) -> Result<impl View> {
420 respond(cx, form, Action::Disable2fa).await472 respond(cx, form, Action::Disable2fa).await
421 }473 }
474+
475+#[page(POST "/admin/users/{user_id}/remove-passkeys")]
476+async fn remove_passkeys(cx: &Cx, Form(form): Form<ActionForm>) -> Result<impl View> {
477+ respond(cx, form, Action::RemovePasskeys).await
478+}
crates/forge-web/src/pages/login.rsmodified+10 -3
@@ -22,6 +22,7 @@ use crate::auth::{
22 };22 };
23 use crate::client_ip::client_ip;23 use crate::client_ip::client_ip;
24 use crate::i18n::{self, Key, Lang, t};24 use crate::i18n::{self, Key, Lang, t};
25+use crate::pages::passkeys::{available as passkeys_available, login_passkey};
25 use crate::state::AppState;26 use crate::state::AppState;
26 use crate::throttle::{self, LOGIN_IP_LIMIT, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT};27 use crate::throttle::{self, LOGIN_IP_LIMIT, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT};
27 use crate::views::{alert, shell};28 use crate::views::{alert, shell};
@@ -74,6 +75,7 @@ async fn login_form(
74 username: &str,75 username: &str,
75 precsrf: &str,76 precsrf: &str,
76 error: Option<String>,77 error: Option<String>,
78+ passkeys: bool,
77 ) -> Result<impl View> {79 ) -> Result<impl View> {
78 Ok(view! {80 Ok(view! {
79 <section class="card narrow">81 <section class="card narrow">
@@ -86,7 +88,7 @@ async fn login_form(
86 <input type="hidden" name="precsrf" value=(precsrf)>88 <input type="hidden" name="precsrf" value=(precsrf)>
87 <label>89 <label>
88 <span>(t(lang, Key::Username))</span>90 <span>(t(lang, Key::Username))</span>
89- <input type="text" name="username" value=(username) autocomplete="username" required=(true)>91+ <input type="text" name="username" value=(username) autocomplete="username webauthn" required=(true)>
90 </label>92 </label>
91 <label>93 <label>
92 <span>(t(lang, Key::Password))</span>94 <span>(t(lang, Key::Password))</span>
@@ -94,6 +96,9 @@ async fn login_form(
94 </label>96 </label>
95 <button type="submit" class="primary">(t(lang, Key::LogIn))</button>97 <button type="submit" class="primary">(t(lang, Key::LogIn))</button>
96 </form>98 </form>
99+ if passkeys {
100+ login_passkey(lang: lang)
101+ }
97 </section>102 </section>
98 })103 })
99 }104 }
@@ -107,8 +112,9 @@ async fn login_page(cx: &Cx) -> Result<impl View> {
107 let next = safe_next(next.as_deref()).to_owned();112 let next = safe_next(next.as_deref()).to_owned();
108 let precsrf = pre_csrf_token(cx);113 let precsrf = pre_csrf_token(cx);
109 let lang = i18n::lang(cx, None);114 let lang = i18n::lang(cx, None);
115+ let passkeys = passkeys_available(app_context::<AppState>(cx));
110 Ok(view! {116 Ok(view! {
111- shell(title: t(lang, Key::LogIn), viewer: None, login_form(lang: lang, next: next.as_str(), username: "", precsrf: precsrf.as_str(), error: None))117+ shell(title: t(lang, Key::LogIn), viewer: None, login_form(lang: lang, next: next.as_str(), username: "", precsrf: precsrf.as_str(), error: None, passkeys: passkeys))
112 })118 })
113 }119 }
114 120
@@ -251,11 +257,12 @@ async fn login_submit(cx: &Cx, Form(form): Form<LoginForm>) -> Result<impl View>
251 let next = safe_next(Some(&form.next)).to_owned();257 let next = safe_next(Some(&form.next)).to_owned();
252 let username = form.username.clone();258 let username = form.username.clone();
253 let precsrf = form.precsrf.clone();259 let precsrf = form.precsrf.clone();
260+ let passkeys = passkeys_available(state);
254 // The status and headers are view parts, so they apply to this page's response.261 // The status and headers are view parts, so they apply to this page's response.
255 Ok(view! {262 Ok(view! {
256 (status)263 (status)
257 (headers)264 (headers)
258- shell(title: t(lang, Key::LogIn), viewer: None, login_form(lang: lang, next: next.as_str(), username: username.as_str(), precsrf: precsrf.as_str(), error: Some(message)))265+ shell(title: t(lang, Key::LogIn), viewer: None, login_form(lang: lang, next: next.as_str(), username: username.as_str(), precsrf: precsrf.as_str(), error: Some(message), passkeys: passkeys))
259 })266 })
260 }267 }
261 268
crates/forge-web/src/pages/mod.rsmodified+3 -0
@@ -68,6 +68,9 @@ pub mod org_members;
68 pub mod org_new;68 pub mod org_new;
69 pub mod org_settings;69 pub mod org_settings;
70 pub mod org_teams;70 pub mod org_teams;
71+pub mod passkeys;
72+#[cfg(test)]
73+mod passkeys_tests;
71 pub mod profile;74 pub mod profile;
72 pub mod profile_pins;75 pub mod profile_pins;
73 pub mod pull_branch;76 pub mod pull_branch;
crates/forge-web/src/pages/passkeys.rsadded+761 -0
@@ -0,0 +1,761 @@
1+//! Passkeys (WebAuthn). The registration ceremony and the passkey list on the security settings
2+//! page, rename and delete, and the usernameless sign-in ceremony on the login page.
3+//!
4+//! The relying party id and origin come from the configured base URL. Ceremony state lives in
5+//! memory under a short-lived random id: a ceremony that outlives the process or five minutes
6+//! simply has to be started again. The browser calls are in `assets/nav.js`. A passkey sign-in
7+//! counts as two factors (possession and user verification), so it skips the TOTP step.
8+
9+use std::collections::HashMap;
10+use std::sync::{LazyLock, Mutex};
11+use std::time::{Duration, Instant};
12+
13+use base64::Engine;
14+use base64::engine::general_purpose::URL_SAFE_NO_PAD;
15+use forge_core::session::new_csrf_token;
16+use forge_core::store::passkeys::{MAX_PASSKEYS, PasskeyRow, clean_name};
17+use forge_core::time::stamp_to_unix;
18+use forge_core::{AuditAction, User};
19+use http::header::{HeaderValue, RETRY_AFTER};
20+use serde::Deserialize;
21+use serde_json::json;
22+use topcoat::Result;
23+use topcoat::context::{Cx, app_context};
24+use topcoat::router::content::Form;
25+use topcoat::router::error::{SeeOther, forbidden, not_found, see_other};
26+use topcoat::router::response::Response;
27+use topcoat::router::{StatusCode, path_param_segment, route};
28+use topcoat::view::{View, component, view};
29+use ulid::Ulid;
30+use webauthn_rs::prelude::{
31+ DiscoverableAuthentication, DiscoverableKey, Passkey, PasskeyRegistration, PublicKeyCredential,
32+ RegisterPublicKeyCredential, Url, Uuid, Webauthn, WebauthnBuilder,
33+};
34+use webauthn_rs_proto::ResidentKeyRequirement;
35+
36+use crate::api;
37+use crate::audit::{self, Actor, Target};
38+use crate::auth::{
39+ check_pre_csrf, clear_pending_login, clear_pre_csrf, login, require_csrf, safe_next, unix_now,
40+};
41+use crate::client_ip::client_ip;
42+use crate::i18n::{self, Key, Lang, t};
43+use crate::mail::account::{PasskeyChange, send_passkey_notice};
44+use crate::state::AppState;
45+use crate::throttle::{self, LOGIN_IP_LIMIT};
46+use crate::views::relative_time;
47+
48+/// How long a started ceremony stays valid.
49+const CEREMONY_TTL: Duration = Duration::from_secs(5 * 60);
50+/// Ceremonies held at once. A start past this is refused until old ones expire.
51+const CEREMONY_CAP: usize = 4096;
52+
53+/// Picks the English or Turkish text.
54+pub fn s(lang: Lang, en: &'static str, tr: &'static str) -> &'static str {
55+ match lang {
56+ Lang::En => en,
57+ Lang::Tr => tr,
58+ }
59+}
60+
61+// ---- relying party ----
62+
63+/// Why passkeys cannot be offered on this server.
64+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65+pub enum Unavailable {
66+ /// The base URL is not https, and its host is not `localhost`.
67+ NotHttps,
68+ /// The base URL has no domain name to use as the relying party id, such as an IP address.
69+ NoDomain,
70+}
71+
72+impl Unavailable {
73+ pub fn message(self, lang: Lang) -> &'static str {
74+ match self {
75+ Unavailable::NotHttps => s(
76+ lang,
77+ "Passkeys are off because the server's base URL is not https. Ask the administrator to serve forge over https (localhost is the only exception).",
78+ "Sunucunun temel adresi https olmadığı için geçiş anahtarları kapalı. Yöneticiden forge'u https üzerinden sunmasını isteyin (tek istisna localhost).",
79+ ),
80+ Unavailable::NoDomain => s(
81+ lang,
82+ "Passkeys are off because the server's base URL has no domain name. They cannot work on an IP address.",
83+ "Sunucunun temel adresinde alan adı olmadığı için geçiş anahtarları kapalı. IP adresinde çalışamazlar.",
84+ ),
85+ }
86+ }
87+}
88+
89+/// The WebAuthn relying party for `base_url`: its host is the id and its origin the only
90+/// accepted origin. https is required, except for `localhost`.
91+pub fn relying_party(base_url: &str) -> std::result::Result<Webauthn, Unavailable> {
92+ let url = Url::parse(base_url).map_err(|_| Unavailable::NoDomain)?;
93+ let secure =
94+ url.scheme() == "https" || (url.scheme() == "http" && url.host_str() == Some("localhost"));
95+ if !secure {
96+ return Err(Unavailable::NotHttps);
97+ }
98+ let domain = url.domain().ok_or(Unavailable::NoDomain)?.to_owned();
99+ let origin =
100+ Url::parse(&url.origin().ascii_serialization()).map_err(|_| Unavailable::NoDomain)?;
101+ WebauthnBuilder::new(&domain, &origin)
102+ .and_then(|builder| builder.rp_name("forge").build())
103+ .map_err(|_| Unavailable::NoDomain)
104+}
105+
106+/// Whether passkeys can be offered with the current base URL.
107+pub fn available(state: &AppState) -> bool {
108+ relying_party(&state.live().base_url).is_ok()
109+}
110+
111+// ---- ceremony state ----
112+
113+enum Ceremony {
114+ Register {
115+ user_id: String,
116+ name: String,
117+ state: PasskeyRegistration,
118+ },
119+ Login {
120+ state: DiscoverableAuthentication,
121+ },
122+}
123+
124+type Ceremonies = Mutex<HashMap<String, (Instant, Ceremony)>>;
125+
126+static CEREMONIES: LazyLock<Ceremonies> = LazyLock::new(|| Mutex::new(HashMap::new()));
127+
128+/// Keeps a started ceremony and returns its id, or `None` when too many are waiting.
129+fn stash(ceremony: Ceremony) -> Option<String> {
130+ let mut map = CEREMONIES.lock().unwrap_or_else(|e| e.into_inner());
131+ let now = Instant::now();
132+ map.retain(|_, (at, _)| now.duration_since(*at) < CEREMONY_TTL);
133+ if map.len() >= CEREMONY_CAP {
134+ return None;
135+ }
136+ let id = new_csrf_token();
137+ map.insert(id.clone(), (now, ceremony));
138+ Some(id)
139+}
140+
141+/// Removes and returns a ceremony. Each id works once.
142+fn take(id: &str) -> Option<Ceremony> {
143+ let mut map = CEREMONIES.lock().unwrap_or_else(|e| e.into_inner());
144+ let (at, ceremony) = map.remove(id)?;
145+ (Instant::now().duration_since(at) < CEREMONY_TTL).then_some(ceremony)
146+}
147+
148+// ---- helpers ----
149+
150+/// The WebAuthn user handle of an account: its ULID id as a UUID.
151+fn user_handle(user_id: &str) -> Option<Uuid> {
152+ Ulid::from_string(user_id)
153+ .ok()
154+ .map(|ulid| Uuid::from_u128(ulid.0))
155+}
156+
157+fn user_id_of(handle: Uuid) -> String {
158+ Ulid(handle.as_u128()).to_string()
159+}
160+
161+fn credential_key(passkey: &Passkey) -> String {
162+ URL_SAFE_NO_PAD.encode(passkey.cred_id().as_ref())
163+}
164+
165+fn parse_passkey(row: &PasskeyRow) -> Option<Passkey> {
166+ serde_json::from_str(&row.passkey).ok()
167+}
168+
169+fn failure(status: StatusCode, message: &str) -> Response {
170+ api::error(status, message)
171+}
172+
173+fn bad_request(message: &str) -> Response {
174+ failure(StatusCode::BAD_REQUEST, message)
175+}
176+
177+fn unavailable(lang: Lang, why: Unavailable) -> Response {
178+ failure(StatusCode::SERVICE_UNAVAILABLE, why.message(lang))
179+}
180+
181+fn generic_failure(lang: Lang) -> &'static str {
182+ s(
183+ lang,
184+ "Passkey sign-in failed. Try again or use your password.",
185+ "Geçiş anahtarıyla giriş başarısız. Yeniden deneyin veya parolanızı kullanın.",
186+ )
187+}
188+
189+fn expired(lang: Lang) -> &'static str {
190+ s(
191+ lang,
192+ "That passkey request expired. Try again.",
193+ "Bu geçiş anahtarı isteğinin süresi doldu. Yeniden deneyin.",
194+ )
195+}
196+
197+#[derive(Deserialize)]
198+struct BeginForm {
199+ #[serde(default)]
200+ csrf: String,
201+ #[serde(default)]
202+ name: String,
203+}
204+
205+#[derive(Deserialize)]
206+struct FinishForm {
207+ #[serde(default)]
208+ csrf: String,
209+ #[serde(default)]
210+ id: String,
211+ #[serde(default)]
212+ credential: String,
213+}
214+
215+#[derive(Deserialize)]
216+struct CsrfForm {
217+ #[serde(default)]
218+ csrf: String,
219+}
220+
221+#[derive(Deserialize)]
222+struct RenameForm {
223+ #[serde(default)]
224+ csrf: String,
225+ #[serde(default)]
226+ name: String,
227+}
228+
229+#[derive(Deserialize)]
230+struct LoginBeginForm {
231+ #[serde(default)]
232+ precsrf: String,
233+}
234+
235+#[derive(Deserialize)]
236+struct LoginFinishForm {
237+ #[serde(default)]
238+ precsrf: String,
239+ #[serde(default)]
240+ id: String,
241+ #[serde(default)]
242+ credential: String,
243+ #[serde(default)]
244+ next: String,
245+}
246+
247+// ---- registration ----
248+
249+/// Starts adding a passkey: validates the name and returns the browser's creation options.
250+#[route(POST "/settings/security/passkeys/register/begin")]
251+async fn register_begin(cx: &Cx, Form(form): Form<BeginForm>) -> Result<Response> {
252+ let viewer = require_csrf(cx, &form.csrf).await?;
253+ let state = app_context::<AppState>(cx);
254+ let lang = i18n::lang(cx, Some(&viewer.0));
255+ let user = &viewer.0;
256+ let webauthn = match relying_party(&state.live().base_url) {
257+ Ok(webauthn) => webauthn,
258+ Err(why) => return Ok(unavailable(lang, why)),
259+ };
260+ let Ok(name) = clean_name(&form.name) else {
261+ return Ok(bad_request(s(
262+ lang,
263+ "Give the passkey a name of 1 to 40 characters.",
264+ "Geçiş anahtarına 1 ile 40 karakter arasında bir ad verin.",
265+ )));
266+ };
267+ let held = state.store.list_passkeys(&user.id).await?;
268+ if held.len() >= MAX_PASSKEYS {
269+ return Ok(bad_request(s(
270+ lang,
271+ "This account has the most passkeys it can hold. Delete one first.",
272+ "Bu hesap tutabileceği en çok geçiş anahtarına ulaştı. Önce birini silin.",
273+ )));
274+ }
275+ let Some(handle) = user_handle(&user.id) else {
276+ return Ok(bad_request(generic_failure(lang)));
277+ };
278+ let exclude: Vec<_> = held
279+ .iter()
280+ .filter_map(parse_passkey)
281+ .map(|passkey| passkey.cred_id().clone())
282+ .collect();
283+ let (mut options, registration) = match webauthn.start_passkey_registration(
284+ handle,
285+ &user.username,
286+ &user.username,
287+ Some(exclude),
288+ ) {
289+ Ok(started) => started,
290+ Err(e) => {
291+ tracing::warn!(error = %e, "could not start a passkey registration");
292+ return Ok(bad_request(generic_failure(lang)));
293+ }
294+ };
295+ // Usernameless sign-in needs a discoverable credential, so ask for one.
296+ if let Some(selection) = options.public_key.authenticator_selection.as_mut() {
297+ selection.resident_key = Some(ResidentKeyRequirement::Required);
298+ selection.require_resident_key = true;
299+ }
300+ let Some(id) = stash(Ceremony::Register {
301+ user_id: user.id.clone(),
302+ name,
303+ state: registration,
304+ }) else {
305+ return Ok(failure(
306+ StatusCode::TOO_MANY_REQUESTS,
307+ t(lang, Key::ErrThrottled),
308+ ));
309+ };
310+ Ok(api::json(
311+ StatusCode::OK,
312+ &json!({ "id": id, "options": options }),
313+ ))
314+}
315+
316+/// Finishes adding a passkey: checks the browser's answer and stores the credential.
317+#[route(POST "/settings/security/passkeys/register/finish")]
318+async fn register_finish(cx: &Cx, Form(form): Form<FinishForm>) -> Result<Response> {
319+ let viewer = require_csrf(cx, &form.csrf).await?;
320+ let state = app_context::<AppState>(cx);
321+ let lang = i18n::lang(cx, Some(&viewer.0));
322+ let user = &viewer.0;
323+ let webauthn = match relying_party(&state.live().base_url) {
324+ Ok(webauthn) => webauthn,
325+ Err(why) => return Ok(unavailable(lang, why)),
326+ };
327+ let Some(Ceremony::Register {
328+ user_id,
329+ name,
330+ state: registration,
331+ }) = take(&form.id)
332+ else {
333+ return Ok(bad_request(expired(lang)));
334+ };
335+ if user_id != user.id {
336+ return Ok(bad_request(expired(lang)));
337+ }
338+ let Ok(credential) = serde_json::from_str::<RegisterPublicKeyCredential>(&form.credential)
339+ else {
340+ return Ok(bad_request(generic_failure(lang)));
341+ };
342+ let passkey = match webauthn.finish_passkey_registration(&credential, &registration) {
343+ Ok(passkey) => passkey,
344+ Err(e) => {
345+ tracing::warn!(error = %e, "passkey registration refused");
346+ return Ok(bad_request(s(
347+ lang,
348+ "The browser's answer was not accepted. Try again.",
349+ "Tarayıcının yanıtı kabul edilmedi. Yeniden deneyin.",
350+ )));
351+ }
352+ };
353+ let serialized = serde_json::to_string(&passkey)
354+ .map_err(|e| forge_core::Error::Crypto(format!("could not serialize the passkey: {e}")))?;
355+ let row = match state
356+ .store
357+ .add_passkey(&user.id, &credential_key(&passkey), &serialized, &name)
358+ .await
359+ {
360+ Ok(row) => row,
361+ Err(forge_core::Error::Conflict(_)) => {
362+ return Ok(failure(
363+ StatusCode::CONFLICT,
364+ s(
365+ lang,
366+ "This passkey is already registered.",
367+ "Bu geçiş anahtarı zaten kayıtlı.",
368+ ),
369+ ));
370+ }
371+ Err(forge_core::Error::Invalid(message)) => return Ok(bad_request(&message)),
372+ Err(e) => return Err(e.into()),
373+ };
374+ audit::record(
375+ &state.store,
376+ Some(cx),
377+ Actor::User(user),
378+ AuditAction::PasskeyAdded,
379+ Target::default(),
380+ json!({ "name": row.name }),
381+ )
382+ .await;
383+ if let Err(e) = send_passkey_notice(state, user, PasskeyChange::Added, &row.id, &row.name).await
384+ {
385+ tracing::warn!(error = %e, "could not queue the passkey notice");
386+ }
387+ Ok(api::json(StatusCode::OK, &json!({ "ok": true })))
388+}
389+
390+// ---- rename and delete ----
391+
392+#[route(POST "/settings/security/passkeys/{passkey_id}/rename")]
393+async fn rename(cx: &Cx, Form(form): Form<RenameForm>) -> Result<SeeOther> {
394+ let (user, _session) = require_csrf(cx, &form.csrf).await?;
395+ let state = app_context::<AppState>(cx);
396+ let id = path_param_segment(cx, "passkey_id").to_owned();
397+ let Ok(name) = clean_name(&form.name) else {
398+ return Ok(see_other("/settings/security?saved=passkey-bad-name"));
399+ };
400+ if !state.store.rename_passkey(&user.id, &id, &name).await? {
401+ return Err(not_found().into());
402+ }
403+ audit::record(
404+ &state.store,
405+ Some(cx),
406+ Actor::User(&user),
407+ AuditAction::PasskeyRenamed,
408+ Target::default(),
409+ json!({ "name": name }),
410+ )
411+ .await;
412+ Ok(see_other("/settings/security?saved=passkey-renamed"))
413+}
414+
415+#[route(POST "/settings/security/passkeys/{passkey_id}/delete")]
416+async fn delete(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> {
417+ let (user, _session) = require_csrf(cx, &form.csrf).await?;
418+ let state = app_context::<AppState>(cx);
419+ let id = path_param_segment(cx, "passkey_id").to_owned();
420+ // Only the owner's own list is searched, so another account's id looks like a missing one.
421+ let Some(row) = state
422+ .store
423+ .list_passkeys(&user.id)
424+ .await?
425+ .into_iter()
426+ .find(|row| row.id == id)
427+ else {
428+ return Err(not_found().into());
429+ };
430+ if !state.store.delete_passkey(&user.id, &id).await? {
431+ return Err(not_found().into());
432+ }
433+ audit::record(
434+ &state.store,
435+ Some(cx),
436+ Actor::User(&user),
437+ AuditAction::PasskeyDeleted,
438+ Target::default(),
439+ json!({ "name": row.name }),
440+ )
441+ .await;
442+ if let Err(e) =
443+ send_passkey_notice(state, &user, PasskeyChange::Removed, &row.id, &row.name).await
444+ {
445+ tracing::warn!(error = %e, "could not queue the passkey notice");
446+ }
447+ Ok(see_other("/settings/security?saved=passkey-deleted"))
448+}
449+
450+// ---- sign-in ----
451+
452+fn throttled(lang: Lang, retry: Duration) -> Response {
453+ let mut res = failure(StatusCode::TOO_MANY_REQUESTS, t(lang, Key::ErrThrottled));
454+ res.headers_mut()
455+ .insert(RETRY_AFTER, HeaderValue::from(retry.as_secs().max(1)));
456+ res
457+}
458+
459+/// Starts a usernameless sign-in and returns the browser's request options.
460+#[route(POST "/login/passkey/begin")]
461+async fn login_begin(cx: &Cx, Form(form): Form<LoginBeginForm>) -> Result<Response> {
462+ if !check_pre_csrf(cx, &form.precsrf) {
463+ return Err(forbidden().into());
464+ }
465+ let state = app_context::<AppState>(cx);
466+ let lang = i18n::lang(cx, None);
467+ let ip_key = throttle::ip_key("passkey-ip", client_ip(cx));
468+ if let Some(retry) = state
469+ .throttle
470+ .check(&ip_key, LOGIN_IP_LIMIT, Instant::now())
471+ {
472+ return Ok(throttled(lang, retry));
473+ }
474+ let webauthn = match relying_party(&state.live().base_url) {
475+ Ok(webauthn) => webauthn,
476+ Err(why) => return Ok(unavailable(lang, why)),
477+ };
478+ let (options, authentication) = match webauthn.start_discoverable_authentication() {
479+ Ok(started) => started,
480+ Err(e) => {
481+ tracing::warn!(error = %e, "could not start a passkey sign-in");
482+ return Ok(bad_request(generic_failure(lang)));
483+ }
484+ };
485+ let Some(id) = stash(Ceremony::Login {
486+ state: authentication,
487+ }) else {
488+ return Ok(failure(
489+ StatusCode::TOO_MANY_REQUESTS,
490+ t(lang, Key::ErrThrottled),
491+ ));
492+ };
493+ Ok(api::json(
494+ StatusCode::OK,
495+ &json!({ "id": id, "options": options }),
496+ ))
497+}
498+
499+/// Finishes a usernameless sign-in. A good answer signs in with no second step.
500+#[route(POST "/login/passkey/finish")]
501+async fn login_finish(cx: &Cx, Form(form): Form<LoginFinishForm>) -> Result<Response> {
502+ if !check_pre_csrf(cx, &form.precsrf) {
503+ return Err(forbidden().into());
504+ }
505+ let state = app_context::<AppState>(cx);
506+ let lang = i18n::lang(cx, None);
507+ let now = Instant::now();
508+ let ip_key = throttle::ip_key("passkey-ip", client_ip(cx));
509+ if let Some(retry) = state.throttle.check(&ip_key, LOGIN_IP_LIMIT, now) {
510+ return Ok(throttled(lang, retry));
511+ }
512+ let webauthn = match relying_party(&state.live().base_url) {
513+ Ok(webauthn) => webauthn,
514+ Err(why) => return Ok(unavailable(lang, why)),
515+ };
516+ let Some(Ceremony::Login {
517+ state: authentication,
518+ }) = take(&form.id)
519+ else {
520+ return Ok(bad_request(expired(lang)));
521+ };
522+ let denied = || {
523+ state.throttle.record_failure(&ip_key, now);
524+ failure(StatusCode::UNAUTHORIZED, generic_failure(lang))
525+ };
526+ let Ok(credential) = serde_json::from_str::<PublicKeyCredential>(&form.credential) else {
527+ return Ok(denied());
528+ };
529+ let Ok((handle, raw_id)) = webauthn.identify_discoverable_authentication(&credential) else {
530+ return Ok(denied());
531+ };
532+ let Some(row) = state
533+ .store
534+ .passkey_by_credential(&URL_SAFE_NO_PAD.encode(raw_id))
535+ .await?
536+ else {
537+ audit_failed(cx, state, None, "unknown_passkey").await;
538+ return Ok(denied());
539+ };
540+ // The handle the authenticator reports must be the account that owns the credential.
541+ let user = state
542+ .store
543+ .user_by_id(&row.user_id)
544+ .await?
545+ .filter(|user| !user.is_org() && user_id_of(handle) == user.id);
546+ let Some(user) = user else {
547+ audit_failed(cx, state, None, "wrong_user").await;
548+ return Ok(denied());
549+ };
550+ if let Some(suspension) = state.store.suspension(&user.id).await? {
551+ audit_failed(cx, state, Some(&user), "suspended").await;
552+ return Ok(failure(
553+ StatusCode::FORBIDDEN,
554+ &i18n::accounts::suspended_message(lang, &suspension.reason),
555+ ));
556+ }
557+ let rows = state.store.list_passkeys(&user.id).await?;
558+ let mut passkeys: Vec<(String, Passkey)> = rows
559+ .iter()
560+ .filter_map(|row| parse_passkey(row).map(|passkey| (row.id.clone(), passkey)))
561+ .collect();
562+ let keys: Vec<DiscoverableKey> = passkeys
563+ .iter()
564+ .map(|(_, passkey)| DiscoverableKey::from(passkey))
565+ .collect();
566+ let result =
567+ match webauthn.finish_discoverable_authentication(&credential, authentication, &keys) {
568+ Ok(result) => result,
569+ Err(e) => {
570+ tracing::warn!(error = %e, user = %user.username, "passkey sign-in refused");
571+ audit_failed(cx, state, Some(&user), "bad_assertion").await;
572+ return Ok(denied());
573+ }
574+ };
575+ // Keep the new sign count and mark the use.
576+ for (id, passkey) in &mut passkeys {
577+ if *id == row.id {
578+ passkey.update_credential(&result);
579+ if let Ok(serialized) = serde_json::to_string(passkey) {
580+ state.store.touch_passkey(id, &serialized).await?;
581+ }
582+ }
583+ }
584+ login(cx, &user).await?;
585+ audit::record(
586+ &state.store,
587+ Some(cx),
588+ Actor::User(&user),
589+ AuditAction::LoginSuccess,
590+ Target::default(),
591+ json!({ "passkey": true, "name": row.name }),
592+ )
593+ .await;
594+ clear_pending_login(cx);
595+ clear_pre_csrf(cx);
596+ let next = safe_next(Some(&form.next)).to_owned();
597+ Ok(api::json(
598+ StatusCode::OK,
599+ &json!({ "ok": true, "next": next }),
600+ ))
601+}
602+
603+async fn audit_failed(cx: &Cx, state: &AppState, user: Option<&User>, reason: &str) {
604+ let target = match user {
605+ Some(user) => Target {
606+ kind: "user",
607+ id: &user.id,
608+ name: &user.username,
609+ },
610+ None => Target::default(),
611+ };
612+ audit::record(
613+ &state.store,
614+ Some(cx),
615+ Actor::Anonymous,
616+ AuditAction::LoginFailed,
617+ target,
618+ json!({ "reason": reason, "passkey": true }),
619+ )
620+ .await;
621+}
622+
623+// ---- settings panel ----
624+
625+/// One passkey as the settings page lists it.
626+pub struct PasskeyItem {
627+ pub id: String,
628+ pub name: String,
629+ /// "Added 2026-10-18 · Last used 5 minutes ago".
630+ pub status: String,
631+}
632+
633+/// What the passkey section of the security page needs.
634+pub struct PasskeyPanel {
635+ pub items: Vec<PasskeyItem>,
636+ /// Why passkeys cannot be added here, when they cannot.
637+ pub problem: Option<Unavailable>,
638+}
639+
640+pub async fn build_panel(
641+ state: &AppState,
642+ lang: Lang,
643+ user_id: &str,
644+) -> forge_core::Result<PasskeyPanel> {
645+ let now = i64::try_from(unix_now()).unwrap_or(i64::MAX);
646+ let rows = state.store.list_passkeys(user_id).await?;
647+ let items = rows
648+ .into_iter()
649+ .map(|row| {
650+ let ago = row
651+ .last_used_at
652+ .as_deref()
653+ .and_then(stamp_to_unix)
654+ .map(|unix| relative_time(lang, unix, now));
655+ PasskeyItem {
656+ status: i18n::device_line(lang, row.created_at.get(..10), ago.as_deref()),
657+ id: row.id,
658+ name: row.name,
659+ }
660+ })
661+ .collect();
662+ Ok(PasskeyPanel {
663+ items,
664+ problem: relying_party(&state.live().base_url).err(),
665+ })
666+}
667+
668+/// The Passkeys block of the security page: the list, rename and delete, and the add form that
669+/// `nav.js` drives. The add form stays hidden until the browser proves it supports passkeys.
670+#[component]
671+pub async fn passkeys_panel(lang: Lang, csrf: &str, panel: PasskeyPanel) -> Result<impl View> {
672+ let PasskeyPanel { items, problem } = panel;
673+ let count = items.len();
674+ let pill_class = if count > 0 {
675+ "security-pill on"
676+ } else {
677+ "security-pill off"
678+ };
679+ let pill_text = count.to_string();
680+ let usable = problem.is_none();
681+ let problem_text = problem.map(|why| why.message(lang));
682+ Ok(view! {
683+ <div class="security-block" data-passkeys="">
684+ <div class="security-row">
685+ <svg class="security-icon" viewBox="0 0 24 24" aria-hidden="true"><circle cx="9" cy="8" r="4"/><path d="M2 21v-1a6 6 0 0 1 6-6h2"/><circle cx="18" cy="14" r="2.5"/><path d="M18 16.5V22M18 19h2"/></svg>
686+ <div class="security-row-main">
687+ <h2 class="security-row-title">
688+ <span>(s(lang, "Passkeys", "Geçiş anahtarları"))</span>
689+ <span class=(pill_class)>(pill_text.as_str())</span>
690+ </h2>
691+ if let Some(text) = problem_text {
692+ <p class="security-row-status warn">(text)</p>
693+ } else {
694+ <p class="security-row-status">(s(lang, "Sign in with your fingerprint, face or device PIN. A passkey counts as two factors, so it skips the code step.", "Parmak izi, yüz veya cihaz PIN'inizle giriş yapın. Geçiş anahtarı iki doğrulama sayılır, bu yüzden kod adımı atlanır."))</p>
695+ }
696+ </div>
697+ </div>
698+ if !items.is_empty() {
699+ <ul class="security-devices">
700+ for item in items.into_iter() {
701+ <li class="security-row security-device">
702+ <svg class="security-icon" viewBox="0 0 24 24" aria-hidden="true"><circle cx="9" cy="8" r="4"/><path d="M2 21v-1a6 6 0 0 1 6-6h2"/><circle cx="18" cy="14" r="2.5"/></svg>
703+ <div class="security-row-main">
704+ <p class="security-row-title">(item.name.as_str())</p>
705+ <p class="security-row-status">(item.status.as_str())</p>
706+ </div>
707+ <details class="security-action">
708+ <summary>(s(lang, "Rename", "Yeniden adlandır"))</summary>
709+ <div class="security-panel">
710+ <form method="post" action=(format!("/settings/security/passkeys/{}/rename", item.id)) class="stack">
711+ <input type="hidden" name="csrf" value=(csrf)>
712+ <label>
713+ <span>(s(lang, "Name", "Ad"))</span>
714+ <input type="text" name="name" value=(item.name.as_str()) maxlength="40" autocomplete="off" required=(true)>
715+ </label>
716+ <button type="submit" class="primary">(t(lang, Key::Save))</button>
717+ </form>
718+ </div>
719+ </details>
720+ <details class="confirm-inline">
721+ <summary class="button danger">(t(lang, Key::Delete))</summary>
722+ <div class="confirm-pop">
723+ <p>(s(lang, "Delete this passkey? You can no longer sign in with it.", "Bu geçiş anahtarı silinsin mi? Artık onunla giriş yapamazsınız."))</p>
724+ <form method="post" action=(format!("/settings/security/passkeys/{}/delete", item.id))>
725+ <input type="hidden" name="csrf" value=(csrf)>
726+ <button type="submit" class="danger">(t(lang, Key::Delete))</button>
727+ <button type="button" data-close-details="">(s(lang, "Cancel", "Vazgeç"))</button>
728+ </form>
729+ </div>
730+ </details>
731+ </li>
732+ }
733+ </ul>
734+ }
735+ if usable {
736+ <form data-hard="true" data-passkey-add="" hidden=(true) class="security-panel passkey-add stack" action="/settings/security" method="get">
737+ <input type="hidden" name="csrf" value=(csrf)>
738+ <label>
739+ <span>(s(lang, "Name for the new passkey", "Yeni geçiş anahtarının adı"))</span>
740+ <input type="text" name="name" maxlength="40" autocomplete="off" placeholder=(s(lang, "Laptop", "Dizüstü")) required=(true)>
741+ </label>
742+ <button type="submit" class="primary">(s(lang, "Add a passkey", "Geçiş anahtarı ekle"))</button>
743+ <p class="passkey-error" role="alert" hidden=(true)></p>
744+ </form>
745+ }
746+ </div>
747+ })
748+}
749+
750+/// The passkey button and its error line for the login page. Hidden until the browser proves it
751+/// supports passkeys.
752+#[component]
753+pub async fn login_passkey(lang: Lang) -> Result<impl View> {
754+ Ok(view! {
755+ <div class="passkey-login" data-passkey-login="" hidden=(true)>
756+ <p class="passkey-or muted small">(s(lang, "or", "veya"))</p>
757+ <button type="button" class="passkey-button" data-passkey-signin="">(s(lang, "Sign in with a passkey", "Geçiş anahtarıyla giriş yap"))</button>
758+ <p class="passkey-error" role="alert" hidden=(true)></p>
759+ </div>
760+ })
761+}
crates/forge-web/src/pages/passkeys_tests.rsadded+669 -0
@@ -0,0 +1,669 @@
1+//! Tests for passkeys: the registration and sign-in ceremonies against a software authenticator,
2+//! suspended and foreign accounts, the settings and admin surfaces, and the throttle.
3+
4+use std::net::SocketAddr;
5+use std::time::Instant;
6+
7+use forge_core::{AuditAction, AuditFilter, Store};
8+use topcoat::router::request::Request;
9+use topcoat::router::{Body, RemoteAddr, Router, to_bytes};
10+use webauthn_authenticator_rs::WebauthnAuthenticator;
11+use webauthn_authenticator_rs::softpasskey::SoftPasskey;
12+use webauthn_rs::prelude::Url;
13+use webauthn_rs_proto::{
14+ AllowCredentials, CreationChallengeResponse, PublicKeyCredential, RegisterPublicKeyCredential,
15+ RequestChallengeResponse,
16+};
17+
18+use crate::auth::SESSION_COOKIE;
19+use crate::state::AppState;
20+use crate::test_support::{app_router, create_session, test_state};
21+use crate::throttle::{self, LOGIN_IP_LIMIT};
22+
23+const ORIGIN: &str = "https://forge.test";
24+const CSRF: &str = "passkey-csrf";
25+const OWNER_TOKEN: &str = "passkey-owner";
26+const OTHER_TOKEN: &str = "passkey-other";
27+const ADMIN_TOKEN: &str = "passkey-admin";
28+
29+struct Fx {
30+ state: AppState,
31+ store: Store,
32+ router: Router,
33+ owner_id: String,
34+ other_id: String,
35+ admin_id: String,
36+ _dir: tempfile::TempDir,
37+}
38+
39+fn peer() -> SocketAddr {
40+ SocketAddr::from(([192, 0, 2, 77], 40000))
41+}
42+
43+async fn fixture_with(base_url: Option<&str>) -> Fx {
44+ let dir = tempfile::tempdir().unwrap();
45+ let mut state = test_state(dir.path()).await;
46+ if let Some(base_url) = base_url {
47+ let mut config = (*state.config).clone();
48+ config.base_url = base_url.into();
49+ state.set_config(config);
50+ }
51+ let store = state.store.clone();
52+ let owner = store
53+ .create_user("tahinli", None, "h", false)
54+ .await
55+ .unwrap();
56+ let other = store
57+ .create_user("mallory", None, "h", false)
58+ .await
59+ .unwrap();
60+ let admin = store.create_user("root", None, "h", true).await.unwrap();
61+ create_session(&store, &owner.id, OWNER_TOKEN, CSRF).await;
62+ create_session(&store, &other.id, OTHER_TOKEN, CSRF).await;
63+ create_session(&store, &admin.id, ADMIN_TOKEN, CSRF).await;
64+ Fx {
65+ router: app_router(state.clone()),
66+ state,
67+ store,
68+ owner_id: owner.id,
69+ other_id: other.id,
70+ admin_id: admin.id,
71+ _dir: dir,
72+ }
73+}
74+
75+async fn fixture() -> Fx {
76+ fixture_with(None).await
77+}
78+
79+struct Reply {
80+ status: u16,
81+ body: String,
82+ cookies: Vec<String>,
83+}
84+
85+impl Reply {
86+ fn json(&self) -> serde_json::Value {
87+ serde_json::from_str(&self.body).unwrap_or_else(|_| panic!("not json: {}", self.body))
88+ }
89+}
90+
91+async fn send(
92+ router: &Router,
93+ method: &str,
94+ uri: &str,
95+ cookie: Option<String>,
96+ form: &[(&str, &str)],
97+) -> Reply {
98+ let mut builder = Request::builder()
99+ .method(method)
100+ .uri(uri)
101+ .extension(RemoteAddr(peer()));
102+ if let Some(cookie) = cookie {
103+ builder = builder.header("cookie", cookie);
104+ }
105+ let body = if method == "POST" {
106+ builder = builder.header("content-type", "application/x-www-form-urlencoded");
107+ let mut ser = form_urlencoded::Serializer::new(String::new());
108+ for (k, v) in form {
109+ ser.append_pair(k, v);
110+ }
111+ Body::from(ser.finish())
112+ } else {
113+ Body::empty()
114+ };
115+ let res = router.handle(builder.body(body).unwrap()).await;
116+ let status = res.status().as_u16();
117+ let cookies = res
118+ .headers()
119+ .get_all("set-cookie")
120+ .iter()
121+ .filter_map(|v| v.to_str().ok().map(str::to_owned))
122+ .collect();
123+ let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
124+ Reply {
125+ status,
126+ body: String::from_utf8_lossy(&bytes).into_owned(),
127+ cookies,
128+ }
129+}
130+
131+fn session_cookie(token: &str) -> Option<String> {
132+ Some(format!("__Host-{SESSION_COOKIE}={token}"))
133+}
134+
135+/// Registers a passkey for the owner through both ceremony endpoints. Returns the authenticator.
136+async fn register(fx: &Fx, name: &str) -> WebauthnAuthenticator<SoftPasskey> {
137+ let begin = send(
138+ &fx.router,
139+ "POST",
140+ "/settings/security/passkeys/register/begin",
141+ session_cookie(OWNER_TOKEN),
142+ &[("csrf", CSRF), ("name", name)],
143+ )
144+ .await;
145+ assert_eq!(begin.status, 200, "{}", begin.body);
146+ let begun = begin.json();
147+ let mut options: CreationChallengeResponse =
148+ serde_json::from_value(begun["options"].clone()).unwrap();
149+ // The server asks for a discoverable credential; the software token cannot make one.
150+ let selection = options.public_key.authenticator_selection.as_mut().unwrap();
151+ assert!(selection.require_resident_key);
152+ selection.require_resident_key = false;
153+ let mut token = WebauthnAuthenticator::new(SoftPasskey::new(true));
154+ let credential: RegisterPublicKeyCredential = token
155+ .do_registration(Url::parse(ORIGIN).unwrap(), options)
156+ .unwrap();
157+ let finish = send(
158+ &fx.router,
159+ "POST",
160+ "/settings/security/passkeys/register/finish",
161+ session_cookie(OWNER_TOKEN),
162+ &[
163+ ("csrf", CSRF),
164+ ("id", begun["id"].as_str().unwrap()),
165+ ("credential", &serde_json::to_string(&credential).unwrap()),
166+ ],
167+ )
168+ .await;
169+ assert_eq!(finish.status, 200, "{}", finish.body);
170+ token
171+}
172+
173+/// The pre-session cookie pair and token a browser gets from `/login`.
174+async fn login_tokens(fx: &Fx) -> (String, String) {
175+ let page = send(&fx.router, "GET", "/login", None, &[]).await;
176+ let cookie = page
177+ .cookies
178+ .iter()
179+ .find(|c| c.contains("forge_precsrf"))
180+ .map(|c| c.split(';').next().unwrap().to_owned())
181+ .expect("precsrf cookie");
182+ let marker = "name=\"precsrf\" value=\"";
183+ let start = page.body.find(marker).expect("precsrf field") + marker.len();
184+ let end = page.body[start..].find('"').unwrap() + start;
185+ (cookie, page.body[start..end].to_owned())
186+}
187+
188+/// Starts a sign-in and answers it with `token`, as a browser would for a discoverable
189+/// credential. Returns the begin id and the answer JSON.
190+async fn answer_login(
191+ fx: &Fx,
192+ cookie: &str,
193+ precsrf: &str,
194+ token: &mut WebauthnAuthenticator<SoftPasskey>,
195+ credential_id: &str,
196+ user_id: &str,
197+) -> (String, String) {
198+ let begin = send(
199+ &fx.router,
200+ "POST",
201+ "/login/passkey/begin",
202+ Some(cookie.to_owned()),
203+ &[("precsrf", precsrf)],
204+ )
205+ .await;
206+ assert_eq!(begin.status, 200, "{}", begin.body);
207+ let begun = begin.json();
208+ let mut options: RequestChallengeResponse =
209+ serde_json::from_value(begun["options"].clone()).unwrap();
210+ assert!(options.public_key.allow_credentials.is_empty());
211+ // The software token needs the credential named; a real authenticator finds it itself.
212+ let raw = base64url_decode(credential_id);
213+ options.public_key.allow_credentials = vec![AllowCredentials {
214+ type_: "public-key".into(),
215+ id: raw.into(),
216+ transports: None,
217+ }];
218+ let mut answer: PublicKeyCredential = token
219+ .do_authentication(Url::parse(ORIGIN).unwrap(), options)
220+ .unwrap();
221+ let handle = uuid_bytes(user_id);
222+ answer.response.user_handle = Some(handle.into());
223+ (
224+ begun["id"].as_str().unwrap().to_owned(),
225+ serde_json::to_string(&answer).unwrap(),
226+ )
227+}
228+
229+fn base64url_decode(text: &str) -> Vec<u8> {
230+ use base64::Engine;
231+ base64::engine::general_purpose::URL_SAFE_NO_PAD
232+ .decode(text)
233+ .unwrap()
234+}
235+
236+fn uuid_bytes(user_id: &str) -> Vec<u8> {
237+ ulid::Ulid::from_string(user_id)
238+ .unwrap()
239+ .0
240+ .to_be_bytes()
241+ .to_vec()
242+}
243+
244+async fn finish_login(fx: &Fx, cookie: &str, precsrf: &str, id: &str, answer: &str) -> Reply {
245+ send(
246+ &fx.router,
247+ "POST",
248+ "/login/passkey/finish",
249+ Some(cookie.to_owned()),
250+ &[
251+ ("precsrf", precsrf),
252+ ("id", id),
253+ ("credential", answer),
254+ ("next", "/settings/security"),
255+ ],
256+ )
257+ .await
258+}
259+
260+fn has_session(reply: &Reply) -> bool {
261+ reply
262+ .cookies
263+ .iter()
264+ .any(|c| c.starts_with(&format!("__Host-{SESSION_COOKIE}=")) && !c.contains("Max-Age=0"))
265+}
266+
267+async fn audit_count(store: &Store, action: AuditAction) -> usize {
268+ let filter = AuditFilter {
269+ action: Some(action),
270+ ..Default::default()
271+ };
272+ store.list_audit(&filter, None, 50).await.unwrap().len()
273+}
274+
275+#[tokio::test]
276+async fn register_then_sign_in_skips_the_second_factor() {
277+ let fx = fixture().await;
278+ // Two-factor is on, yet a passkey sign-in goes straight in.
279+ let sealed = forge_core::secret::seal(&fx.state.key, &forge_core::totp::new_secret()).unwrap();
280+ fx.store
281+ .set_totp_secret(&fx.owner_id, &sealed)
282+ .await
283+ .unwrap();
284+ fx.store
285+ .enable_totp(&fx.owner_id, 1, &["hash".to_owned()])
286+ .await
287+ .unwrap();
288+
289+ let mut token = register(&fx, "Laptop").await;
290+ let rows = fx.store.list_passkeys(&fx.owner_id).await.unwrap();
291+ assert_eq!(rows.len(), 1);
292+ assert_eq!(rows[0].name, "Laptop");
293+ assert!(rows[0].last_used_at.is_none());
294+ assert_eq!(audit_count(&fx.store, AuditAction::PasskeyAdded).await, 1);
295+
296+ let (cookie, precsrf) = login_tokens(&fx).await;
297+ let (id, answer) = answer_login(
298+ &fx,
299+ &cookie,
300+ &precsrf,
301+ &mut token,
302+ &rows[0].credential_id,
303+ &fx.owner_id,
304+ )
305+ .await;
306+ let done = finish_login(&fx, &cookie, &precsrf, &id, &answer).await;
307+ assert_eq!(done.status, 200, "{}", done.body);
308+ assert_eq!(done.json()["next"], "/settings/security");
309+ assert!(has_session(&done), "a session cookie is set");
310+ assert!(
311+ !done.cookies.iter().any(|c| c.contains("pending")),
312+ "no pending second step"
313+ );
314+ let after = fx.store.list_passkeys(&fx.owner_id).await.unwrap();
315+ assert!(after[0].last_used_at.is_some());
316+ assert_eq!(audit_count(&fx.store, AuditAction::LoginSuccess).await, 1);
317+
318+ // The ceremony id works once.
319+ let again = finish_login(&fx, &cookie, &precsrf, &id, &answer).await;
320+ assert_eq!(again.status, 400);
321+ assert!(!has_session(&again));
322+}
323+
324+#[tokio::test]
325+async fn suspended_user_is_refused() {
326+ let fx = fixture().await;
327+ let mut token = register(&fx, "Laptop").await;
328+ let rows = fx.store.list_passkeys(&fx.owner_id).await.unwrap();
329+ fx.store
330+ .suspend_user(&fx.owner_id, "testing", Some(&fx.admin_id))
331+ .await
332+ .unwrap();
333+ let (cookie, precsrf) = login_tokens(&fx).await;
334+ let (id, answer) = answer_login(
335+ &fx,
336+ &cookie,
337+ &precsrf,
338+ &mut token,
339+ &rows[0].credential_id,
340+ &fx.owner_id,
341+ )
342+ .await;
343+ let done = finish_login(&fx, &cookie, &precsrf, &id, &answer).await;
344+ assert_eq!(done.status, 403, "{}", done.body);
345+ assert!(done.body.contains("testing"));
346+ assert!(!has_session(&done));
347+ assert_eq!(audit_count(&fx.store, AuditAction::LoginFailed).await, 1);
348+}
349+
350+#[tokio::test]
351+async fn an_answer_naming_another_account_is_refused() {
352+ let fx = fixture().await;
353+ let mut token = register(&fx, "Laptop").await;
354+ let rows = fx.store.list_passkeys(&fx.owner_id).await.unwrap();
355+ let (cookie, precsrf) = login_tokens(&fx).await;
356+ // A valid signature, but the user handle claims another account.
357+ let (id, answer) = answer_login(
358+ &fx,
359+ &cookie,
360+ &precsrf,
361+ &mut token,
362+ &rows[0].credential_id,
363+ &fx.other_id,
364+ )
365+ .await;
366+ let done = finish_login(&fx, &cookie, &precsrf, &id, &answer).await;
367+ assert_eq!(done.status, 401, "{}", done.body);
368+ assert!(!has_session(&done));
369+ assert_eq!(audit_count(&fx.store, AuditAction::LoginFailed).await, 1);
370+}
371+
372+#[tokio::test]
373+async fn sign_in_is_throttled_by_ip() {
374+ let fx = fixture().await;
375+ let (cookie, precsrf) = login_tokens(&fx).await;
376+ let key = throttle::ip_key("passkey-ip", peer().ip());
377+ for _ in 0..LOGIN_IP_LIMIT {
378+ fx.state.throttle.record_failure(&key, Instant::now());
379+ }
380+ let begin = send(
381+ &fx.router,
382+ "POST",
383+ "/login/passkey/begin",
384+ Some(cookie),
385+ &[("precsrf", &precsrf)],
386+ )
387+ .await;
388+ assert_eq!(begin.status, 429);
389+}
390+
391+#[tokio::test]
392+async fn sign_in_needs_the_pre_session_token() {
393+ let fx = fixture().await;
394+ let (cookie, _precsrf) = login_tokens(&fx).await;
395+ let begin = send(
396+ &fx.router,
397+ "POST",
398+ "/login/passkey/begin",
399+ Some(cookie),
400+ &[("precsrf", "wrong")],
401+ )
402+ .await;
403+ assert_eq!(begin.status, 403);
404+}
405+
406+#[tokio::test]
407+async fn delete_requires_ownership_and_is_audited() {
408+ let fx = fixture().await;
409+ register(&fx, "Laptop").await;
410+ let row = fx
411+ .store
412+ .list_passkeys(&fx.owner_id)
413+ .await
414+ .unwrap()
415+ .remove(0);
416+ let uri = format!("/settings/security/passkeys/{}/delete", row.id);
417+
418+ let foreign = send(
419+ &fx.router,
420+ "POST",
421+ &uri,
422+ session_cookie(OTHER_TOKEN),
423+ &[("csrf", CSRF)],
424+ )
425+ .await;
426+ assert_eq!(foreign.status, 404);
427+ assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 1);
428+
429+ let bad_csrf = send(
430+ &fx.router,
431+ "POST",
432+ &uri,
433+ session_cookie(OWNER_TOKEN),
434+ &[("csrf", "nope")],
435+ )
436+ .await;
437+ assert_eq!(bad_csrf.status, 403);
438+ assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 1);
439+
440+ let own = send(
441+ &fx.router,
442+ "POST",
443+ &uri,
444+ session_cookie(OWNER_TOKEN),
445+ &[("csrf", CSRF)],
446+ )
447+ .await;
448+ assert_eq!(own.status, 303);
449+ assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 0);
450+ assert_eq!(audit_count(&fx.store, AuditAction::PasskeyDeleted).await, 1);
451+}
452+
453+#[tokio::test]
454+async fn rename_requires_ownership() {
455+ let fx = fixture().await;
456+ register(&fx, "Laptop").await;
457+ let row = fx
458+ .store
459+ .list_passkeys(&fx.owner_id)
460+ .await
461+ .unwrap()
462+ .remove(0);
463+ let uri = format!("/settings/security/passkeys/{}/rename", row.id);
464+ let foreign = send(
465+ &fx.router,
466+ "POST",
467+ &uri,
468+ session_cookie(OTHER_TOKEN),
469+ &[("csrf", CSRF), ("name", "Mine")],
470+ )
471+ .await;
472+ assert_eq!(foreign.status, 404);
473+ let own = send(
474+ &fx.router,
475+ "POST",
476+ &uri,
477+ session_cookie(OWNER_TOKEN),
478+ &[("csrf", CSRF), ("name", "Phone")],
479+ )
480+ .await;
481+ assert_eq!(own.status, 303);
482+ assert_eq!(
483+ fx.store.list_passkeys(&fx.owner_id).await.unwrap()[0].name,
484+ "Phone"
485+ );
486+ assert_eq!(audit_count(&fx.store, AuditAction::PasskeyRenamed).await, 1);
487+}
488+
489+#[tokio::test]
490+async fn registration_ceremony_belongs_to_the_user_who_started_it() {
491+ let fx = fixture().await;
492+ let begin = send(
493+ &fx.router,
494+ "POST",
495+ "/settings/security/passkeys/register/begin",
496+ session_cookie(OWNER_TOKEN),
497+ &[("csrf", CSRF), ("name", "Laptop")],
498+ )
499+ .await;
500+ let id = begin.json()["id"].as_str().unwrap().to_owned();
501+ // Someone else cannot finish it, even before the credential is looked at.
502+ let finish = send(
503+ &fx.router,
504+ "POST",
505+ "/settings/security/passkeys/register/finish",
506+ session_cookie(OTHER_TOKEN),
507+ &[("csrf", CSRF), ("id", &id), ("credential", "{}")],
508+ )
509+ .await;
510+ assert_eq!(finish.status, 400);
511+ assert_eq!(fx.store.passkey_count(&fx.other_id).await.unwrap(), 0);
512+}
513+
514+#[tokio::test]
515+async fn begin_refuses_a_bad_name_a_bad_token_and_anonymous_callers() {
516+ let fx = fixture().await;
517+ let uri = "/settings/security/passkeys/register/begin";
518+ let blank = send(
519+ &fx.router,
520+ "POST",
521+ uri,
522+ session_cookie(OWNER_TOKEN),
523+ &[("csrf", CSRF), ("name", " ")],
524+ )
525+ .await;
526+ assert_eq!(blank.status, 400);
527+ let long = "x".repeat(41);
528+ let too_long = send(
529+ &fx.router,
530+ "POST",
531+ uri,
532+ session_cookie(OWNER_TOKEN),
533+ &[("csrf", CSRF), ("name", &long)],
534+ )
535+ .await;
536+ assert_eq!(too_long.status, 400);
537+ let bad = send(
538+ &fx.router,
539+ "POST",
540+ uri,
541+ session_cookie(OWNER_TOKEN),
542+ &[("csrf", "nope"), ("name", "Laptop")],
543+ )
544+ .await;
545+ assert_eq!(bad.status, 403);
546+ let anon = send(
547+ &fx.router,
548+ "POST",
549+ uri,
550+ None,
551+ &[("csrf", CSRF), ("name", "Laptop")],
552+ )
553+ .await;
554+ assert_eq!(anon.status, 303);
555+}
556+
557+#[tokio::test]
558+async fn insecure_base_url_turns_passkeys_off_with_a_message() {
559+ let fx = fixture_with(Some("http://forge.example/")).await;
560+ let begin = send(
561+ &fx.router,
562+ "POST",
563+ "/settings/security/passkeys/register/begin",
564+ session_cookie(OWNER_TOKEN),
565+ &[("csrf", CSRF), ("name", "Laptop")],
566+ )
567+ .await;
568+ assert_eq!(begin.status, 503);
569+ assert!(
570+ begin.json()["error"]
571+ .as_str()
572+ .unwrap()
573+ .contains("not https")
574+ );
575+
576+ let page = send(
577+ &fx.router,
578+ "GET",
579+ "/settings/security",
580+ session_cookie(OWNER_TOKEN),
581+ &[],
582+ )
583+ .await;
584+ assert!(page.body.contains("base URL is not https"));
585+ assert!(!page.body.contains("data-passkey-add"));
586+ let login = send(&fx.router, "GET", "/login", None, &[]).await;
587+ assert!(!login.body.contains("data-passkey-signin"));
588+}
589+
590+#[tokio::test]
591+async fn pages_show_the_passkey_ui() {
592+ let fx = fixture().await;
593+ register(&fx, "Laptop").await;
594+ let page = send(
595+ &fx.router,
596+ "GET",
597+ "/settings/security",
598+ session_cookie(OWNER_TOKEN),
599+ &[],
600+ )
601+ .await;
602+ assert!(page.body.contains("data-passkey-add"));
603+ assert!(page.body.contains("Laptop"));
604+ assert!(page.body.contains("confirm-inline"));
605+ let login = send(&fx.router, "GET", "/login", None, &[]).await;
606+ assert!(login.body.contains("data-passkey-signin"));
607+ assert!(login.body.contains("autocomplete=\"username webauthn\""));
608+ assert!(!login.body.contains('\u{2014}'));
609+}
610+
611+#[test]
612+fn relying_party_needs_https_or_localhost() {
613+ use super::passkeys::{Unavailable, relying_party};
614+ assert!(relying_party("https://forge.example/").is_ok());
615+ assert!(relying_party("https://forge.example:8443/").is_ok());
616+ assert!(relying_party("http://localhost:7660").is_ok());
617+ assert_eq!(
618+ relying_party("http://forge.example").err(),
619+ Some(Unavailable::NotHttps)
620+ );
621+ assert_eq!(
622+ relying_party("http://127.0.0.1:7660").err(),
623+ Some(Unavailable::NotHttps)
624+ );
625+ assert_eq!(
626+ relying_party("https://127.0.0.1").err(),
627+ Some(Unavailable::NoDomain)
628+ );
629+ assert_eq!(relying_party("nonsense").err(), Some(Unavailable::NoDomain));
630+}
631+
632+#[tokio::test]
633+async fn admin_removes_all_passkeys_with_an_audit_entry() {
634+ let fx = fixture().await;
635+ register(&fx, "Laptop").await;
636+ register(&fx, "Phone").await;
637+ assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 2);
638+ let detail = format!("/admin/users/{}", fx.owner_id);
639+ let page = send(&fx.router, "GET", &detail, session_cookie(ADMIN_TOKEN), &[]).await;
640+ assert_eq!(page.status, 200);
641+ assert!(page.body.contains("Remove all passkeys"));
642+
643+ let uri = format!("{detail}/remove-passkeys");
644+ let denied = send(
645+ &fx.router,
646+ "POST",
647+ &uri,
648+ session_cookie(OTHER_TOKEN),
649+ &[("csrf", CSRF)],
650+ )
651+ .await;
652+ assert_eq!(denied.status, 404);
653+ assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 2);
654+
655+ let done = send(
656+ &fx.router,
657+ "POST",
658+ &uri,
659+ session_cookie(ADMIN_TOKEN),
660+ &[("csrf", CSRF)],
661+ )
662+ .await;
663+ assert_eq!(done.status, 303);
664+ assert_eq!(fx.store.passkey_count(&fx.owner_id).await.unwrap(), 0);
665+ assert_eq!(
666+ audit_count(&fx.store, AuditAction::PasskeysRemovedByAdmin).await,
667+ 1
668+ );
669+}
crates/forge-web/src/pages/settings_security.rsmodified+17 -0
@@ -24,6 +24,7 @@ use crate::auth::{
24 verify_password_async, verify_second_factor,24 verify_password_async, verify_second_factor,
25 };25 };
26 use crate::i18n::{self, Key, Lang, password_too_long, password_too_short, t};26 use crate::i18n::{self, Key, Lang, password_too_long, password_too_short, t};
27+use crate::pages::passkeys::{PasskeyPanel, build_panel, passkeys_panel, s};
27 use crate::state::AppState;28 use crate::state::AppState;
28 use crate::throttle::{self, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT};29 use crate::throttle::{self, LOGIN_USER_LIMIT, TWO_FACTOR_USER_LIMIT};
29 use crate::views::{alert, relative_time, shell, user_facing_message};30 use crate::views::{alert, relative_time, shell, user_facing_message};
@@ -174,6 +175,7 @@ struct SecurityPage {
174 /// The enabled device. `None` when two-factor is off.175 /// The enabled device. `None` when two-factor is off.
175 two_factor: Option<DeviceView>,176 two_factor: Option<DeviceView>,
176 delete_error: Option<String>,177 delete_error: Option<String>,
178+ passkeys: PasskeyPanel,
177 /// Repositories still owned by the user. Deletion is refused while there are any.179 /// Repositories still owned by the user. Deletion is refused while there are any.
178 owned_repos: Vec<String>,180 owned_repos: Vec<String>,
179 }181 }
@@ -197,6 +199,7 @@ async fn security_body(page: SecurityPage) -> Result<impl View> {
197 password_changed,199 password_changed,
198 two_factor,200 two_factor,
199 delete_error,201 delete_error,
202+ passkeys,
200 owned_repos,203 owned_repos,
201 } = page;204 } = page;
202 let two_factor_on = two_factor.is_some();205 let two_factor_on = two_factor.is_some();
@@ -428,6 +431,7 @@ async fn security_body(page: SecurityPage) -> Result<impl View> {
428 </div>431 </div>
429 }432 }
430 </div>433 </div>
434+ passkeys_panel(lang: lang, csrf: csrf.as_str(), panel: passkeys)
431 </section>435 </section>
432 <section class="card security-card security-danger">436 <section class="card security-card security-danger">
433 <p class="security-danger-label">(t(lang, Key::DangerZone))</p>437 <p class="security-danger-label">(t(lang, Key::DangerZone))</p>
@@ -488,6 +492,18 @@ fn notice_for(lang: Lang, saved: Option<&str>) -> Option<&'static str> {
488 Some("email") => Some(t(lang, Key::OkEmailSaved)),492 Some("email") => Some(t(lang, Key::OkEmailSaved)),
489 Some("verify_sent") => Some(t(lang, Key::OkVerifySent)),493 Some("verify_sent") => Some(t(lang, Key::OkVerifySent)),
490 Some("2fa-off") => Some(t(lang, Key::OkTwoFactorOff)),494 Some("2fa-off") => Some(t(lang, Key::OkTwoFactorOff)),
495+ Some("passkey-added") => Some(s(lang, "Passkey added.", "Geçiş anahtarı eklendi.")),
496+ Some("passkey-renamed") => Some(s(
497+ lang,
498+ "Passkey renamed.",
499+ "Geçiş anahtarı yeniden adlandırıldı.",
500+ )),
501+ Some("passkey-deleted") => Some(s(lang, "Passkey deleted.", "Geçiş anahtarı silindi.")),
502+ Some("passkey-bad-name") => Some(s(
503+ lang,
504+ "A passkey name is 1 to 40 characters on one line.",
505+ "Geçiş anahtarı adı tek satırda 1 ile 40 karakter olmalı.",
506+ )),
491 _ => None,507 _ => None,
492 }508 }
493 }509 }
@@ -574,6 +590,7 @@ async fn build_page(
574 lang,590 lang,
575 csrf: viewer.1.csrf_token.clone(),591 csrf: viewer.1.csrf_token.clone(),
576 delete_error: shown.delete_error,592 delete_error: shown.delete_error,
593+ passkeys: build_panel(state, lang, &viewer.0.id).await?,
577 owned_repos,594 owned_repos,
578 email_verified,595 email_verified,
579 stored_email,596 stored_email,
style/main.scssmodified+54 -1
@@ -6235,6 +6235,58 @@ button.ci-job-last {
6235 }6235 }
6236 }6236 }
6237 6237
6238+// Passkeys: the add form sits under the list, aligned with the row text. Both the add form and the
6239+// login button stay hidden until nav.js sees that the browser supports passkeys.
6240+.passkey-add {
6241+ max-width: none;
6242+ margin: 0;
6243+ padding: 4px 20px 18px 56px;
6244+
6245+ &[hidden] {
6246+ display: none;
6247+ }
6248+}
6249+
6250+.passkey-error {
6251+ margin: 0;
6252+ color: var(--bad);
6253+ font-size: 0.875rem;
6254+
6255+ &[hidden] {
6256+ display: none;
6257+ }
6258+}
6259+
6260+.passkey-login {
6261+ display: flex;
6262+ flex-direction: column;
6263+ gap: 10px;
6264+ margin-top: 14px;
6265+
6266+ &[hidden] {
6267+ display: none;
6268+ }
6269+
6270+ .passkey-or {
6271+ display: flex;
6272+ align-items: center;
6273+ gap: 10px;
6274+ margin: 0;
6275+
6276+ &::before,
6277+ &::after {
6278+ content: "";
6279+ flex: 1;
6280+ height: 1px;
6281+ background: var(--border);
6282+ }
6283+ }
6284+
6285+ .passkey-button {
6286+ width: 100%;
6287+ }
6288+}
6289+
6238 .security-setup {6290 .security-setup {
6239 max-width: none;6291 max-width: none;
6240 margin: 0;6292 margin: 0;
@@ -6285,7 +6337,8 @@ button.ci-job-last {
6285 padding: 0 16px 14px 16px;6337 padding: 0 16px 14px 16px;
6286 }6338 }
6287 6339
6288- .security-setup {6340+ .security-setup,
6341+ .passkey-add {
6289 padding: 4px 16px 16px 16px;6342 padding: 4px 16px 16px 16px;
6290 }6343 }
6291 6344