fabrica

hanna/fabrica

feat(web): axum shell — layout, theming, auth, assets, healthz

7d9b1ab · hanna committed on 2026-07-25

Stand up the web server: axum 0.8 + maud templates + htmx (vendored, no
build step) + tower-http (compression, tracing, request-id). No TLS
feature, so ring stays out of the graph.

- Layout: slim top bar, off-canvas drawer, theme picker, footer; every
  page wrapped by one shell that works without JavaScript.
- Theming: base.css is structure-only against --fb-* tokens with no
  literal colours; embedded dark/light themes plus disk overrides from
  themes_dir; asset overrides from assets_dir; path traversal rejected;
  SIGHUP re-scans themes.
- Auth: sign-in/out over opaque session cookies (SHA-256 validated in the
  store), invite completion that sets the password, and a settings stub.
  CSRF is double-submit; every non-GET route is checked.
- Ops: /assets, /theme, /healthz (git + db status), /version; themed,
  self-contained error pages that never leak internals.

serve is wired in the binary (src/serve.rs) via a cli callback so no
library crate depends on web; it runs foreground with graceful shutdown.
13 handler tests via oneshot; driven end-to-end against a live server.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed by hannaSSH key fingerprint: SHA256:4g9cWhkAAw8gwqhJUcVbSnGEvdGwklW+1Aa/fMUu59k
22 files changed · +3030 −22UnifiedSplit
Cargo.lock +597 −4
@@ -155,6 +155,18 @@ dependencies = [
155]155]
156156
157[[package]]157[[package]]
158name = "async-compression"
159version = "0.4.42"
160source = "registry+https://github.com/rust-lang/crates.io-index"
161checksum = "e79b3f8a79cccc2898f31920fc69f304859b3bd567490f75ebf51ae1c792a9ac"
162dependencies = [
163 "compression-codecs",
164 "compression-core",
165 "pin-project-lite",
166 "tokio",
167]
168
169[[package]]
158name = "async-trait"170name = "async-trait"
159version = "0.1.91"171version = "0.1.91"
160source = "registry+https://github.com/rust-lang/crates.io-index"172source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -184,6 +196,12 @@ dependencies = [
184]196]
185197
186[[package]]198[[package]]
199name = "atomic-waker"
200version = "1.1.2"
201source = "registry+https://github.com/rust-lang/crates.io-index"
202checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
203
204[[package]]
187name = "auth"205name = "auth"
188version = "0.1.0"206version = "0.1.0"
189dependencies = [207dependencies = [
@@ -205,6 +223,80 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
205checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"223checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
206224
207[[package]]225[[package]]
226name = "axum"
227version = "0.8.9"
228source = "registry+https://github.com/rust-lang/crates.io-index"
229checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
230dependencies = [
231 "axum-core",
232 "bytes",
233 "form_urlencoded",
234 "futures-util",
235 "http",
236 "http-body",
237 "http-body-util",
238 "hyper",
239 "hyper-util",
240 "itoa",
241 "matchit",
242 "memchr",
243 "mime",
244 "percent-encoding",
245 "pin-project-lite",
246 "serde_core",
247 "serde_json",
248 "serde_path_to_error",
249 "serde_urlencoded",
250 "sync_wrapper",
251 "tokio",
252 "tower",
253 "tower-layer",
254 "tower-service",
255 "tracing",
256]
257
258[[package]]
259name = "axum-core"
260version = "0.5.6"
261source = "registry+https://github.com/rust-lang/crates.io-index"
262checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
263dependencies = [
264 "bytes",
265 "futures-core",
266 "http",
267 "http-body",
268 "http-body-util",
269 "mime",
270 "pin-project-lite",
271 "sync_wrapper",
272 "tower-layer",
273 "tower-service",
274 "tracing",
275]
276
277[[package]]
278name = "axum-extra"
279version = "0.12.6"
280source = "registry+https://github.com/rust-lang/crates.io-index"
281checksum = "be44683b41ccb9ab2d23a5230015c9c3c55be97a25e4428366de8873103f7970"
282dependencies = [
283 "axum",
284 "axum-core",
285 "bytes",
286 "cookie",
287 "futures-core",
288 "futures-util",
289 "http",
290 "http-body",
291 "http-body-util",
292 "mime",
293 "pin-project-lite",
294 "tower-layer",
295 "tower-service",
296 "tracing",
297]
298
299[[package]]
208name = "base16ct"300name = "base16ct"
209version = "0.2.0"301version = "0.2.0"
210source = "registry+https://github.com/rust-lang/crates.io-index"302source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -512,6 +604,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
512checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"604checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
513605
514[[package]]606[[package]]
607name = "compression-codecs"
608version = "0.4.38"
609source = "registry+https://github.com/rust-lang/crates.io-index"
610checksum = "ce2548391e9c1929c21bf6aa2680af86fe4c1b33e6cea9ac1cfeec0bd11218cf"
611dependencies = [
612 "compression-core",
613 "flate2",
614 "memchr",
615]
616
617[[package]]
618name = "compression-core"
619version = "0.4.32"
620source = "registry+https://github.com/rust-lang/crates.io-index"
621checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789"
622
623[[package]]
515name = "concurrent-queue"624name = "concurrent-queue"
516version = "2.5.0"625version = "2.5.0"
517source = "registry+https://github.com/rust-lang/crates.io-index"626source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -549,6 +658,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
549checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"658checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
550659
551[[package]]660[[package]]
661name = "const-oid"
662version = "0.10.2"
663source = "registry+https://github.com/rust-lang/crates.io-index"
664checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
665
666[[package]]
552name = "convert_case"667name = "convert_case"
553version = "0.10.0"668version = "0.10.0"
554source = "registry+https://github.com/rust-lang/crates.io-index"669source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -558,6 +673,17 @@ dependencies = [
558]673]
559674
560[[package]]675[[package]]
676name = "cookie"
677version = "0.18.1"
678source = "registry+https://github.com/rust-lang/crates.io-index"
679checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747"
680dependencies = [
681 "percent-encoding",
682 "time",
683 "version_check",
684]
685
686[[package]]
561name = "core-foundation"687name = "core-foundation"
562version = "0.10.1"688version = "0.10.1"
563source = "registry+https://github.com/rust-lang/crates.io-index"689source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -613,6 +739,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
613checksum = "fd121741cf3eb82c08dd3023eb55bf2665e5f60ec20f89760cf836ae4562e6a0"739checksum = "fd121741cf3eb82c08dd3023eb55bf2665e5f60ec20f89760cf836ae4562e6a0"
614740
615[[package]]741[[package]]
742name = "crc32fast"
743version = "1.5.0"
744source = "registry+https://github.com/rust-lang/crates.io-index"
745checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
746dependencies = [
747 "cfg-if",
748]
749
750[[package]]
616name = "crossbeam-channel"751name = "crossbeam-channel"
617version = "0.5.16"752version = "0.5.16"
618source = "registry+https://github.com/rust-lang/crates.io-index"753source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -789,12 +924,21 @@ version = "0.7.10"
789source = "registry+https://github.com/rust-lang/crates.io-index"924source = "registry+https://github.com/rust-lang/crates.io-index"
790checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"925checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
791dependencies = [926dependencies = [
792 "const-oid",927 "const-oid 0.9.6",
793 "pem-rfc7468",928 "pem-rfc7468",
794 "zeroize",929 "zeroize",
795]930]
796931
797[[package]]932[[package]]
933name = "deranged"
934version = "0.5.8"
935source = "registry+https://github.com/rust-lang/crates.io-index"
936checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
937dependencies = [
938 "powerfmt",
939]
940
941[[package]]
798name = "derive_builder"942name = "derive_builder"
799version = "0.20.2"943version = "0.20.2"
800source = "registry+https://github.com/rust-lang/crates.io-index"944source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -864,7 +1008,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
864checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"1008checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
865dependencies = [1009dependencies = [
866 "block-buffer 0.10.4",1010 "block-buffer 0.10.4",
867 "const-oid",1011 "const-oid 0.9.6",
868 "crypto-common 0.1.6",1012 "crypto-common 0.1.6",
869 "subtle",1013 "subtle",
870]1014]
@@ -876,6 +1020,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
876checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"1020checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
877dependencies = [1021dependencies = [
878 "block-buffer 0.12.1",1022 "block-buffer 0.12.1",
1023 "const-oid 0.10.2",
879 "crypto-common 0.2.2",1024 "crypto-common 0.2.2",
880 "ctutils",1025 "ctutils",
881]1026]
@@ -1062,7 +1207,12 @@ dependencies = [
1062name = "fabrica"1207name = "fabrica"
1063version = "0.1.0"1208version = "0.1.0"
1064dependencies = [1209dependencies = [
1210 "anyhow",
1065 "cli",1211 "cli",
1212 "config",
1213 "store",
1214 "tokio",
1215 "web",
1066]1216]
10671217
1068[[package]]1218[[package]]
@@ -1116,6 +1266,7 @@ version = "1.1.9"
1116source = "registry+https://github.com/rust-lang/crates.io-index"1266source = "registry+https://github.com/rust-lang/crates.io-index"
1117checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"1267checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
1118dependencies = [1268dependencies = [
1269 "crc32fast",
1119 "miniz_oxide",1270 "miniz_oxide",
1120 "zlib-rs",1271 "zlib-rs",
1121]1272]
@@ -1447,6 +1598,45 @@ dependencies = [
1447]1598]
14481599
1449[[package]]1600[[package]]
1601name = "http"
1602version = "1.4.2"
1603source = "registry+https://github.com/rust-lang/crates.io-index"
1604checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425"
1605dependencies = [
1606 "bytes",
1607 "itoa",
1608]
1609
1610[[package]]
1611name = "http-body"
1612version = "1.1.0"
1613source = "registry+https://github.com/rust-lang/crates.io-index"
1614checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
1615dependencies = [
1616 "bytes",
1617 "http",
1618]
1619
1620[[package]]
1621name = "http-body-util"
1622version = "0.1.4"
1623source = "registry+https://github.com/rust-lang/crates.io-index"
1624checksum = "e9f41fd6a08e4d4ec69df65976da761afd5ad5e58a9d4acb46bd1c953a9e3ff2"
1625dependencies = [
1626 "bytes",
1627 "futures-core",
1628 "http",
1629 "http-body",
1630 "pin-project-lite",
1631]
1632
1633[[package]]
1634name = "httparse"
1635version = "1.10.1"
1636source = "registry+https://github.com/rust-lang/crates.io-index"
1637checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
1638
1639[[package]]
1450name = "httpdate"1640name = "httpdate"
1451version = "1.0.3"1641version = "1.0.3"
1452source = "registry+https://github.com/rust-lang/crates.io-index"1642source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1462,6 +1652,41 @@ dependencies = [
1462]1652]
14631653
1464[[package]]1654[[package]]
1655name = "hyper"
1656version = "1.11.0"
1657source = "registry+https://github.com/rust-lang/crates.io-index"
1658checksum = "d22053281f852e11534f5198498373cbb59295120a20771d90f7ed1897490a72"
1659dependencies = [
1660 "atomic-waker",
1661 "bytes",
1662 "futures-channel",
1663 "futures-core",
1664 "http",
1665 "http-body",
1666 "httparse",
1667 "httpdate",
1668 "itoa",
1669 "pin-project-lite",
1670 "smallvec",
1671 "tokio",
1672]
1673
1674[[package]]
1675name = "hyper-util"
1676version = "0.1.20"
1677source = "registry+https://github.com/rust-lang/crates.io-index"
1678checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
1679dependencies = [
1680 "bytes",
1681 "http",
1682 "http-body",
1683 "hyper",
1684 "pin-project-lite",
1685 "tokio",
1686 "tower-service",
1687]
1688
1689[[package]]
1465name = "icu_collections"1690name = "icu_collections"
1466version = "2.1.1"1691version = "2.1.1"
1467source = "registry+https://github.com/rust-lang/crates.io-index"1692source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1815,6 +2040,45 @@ dependencies = [
1815]2040]
18162041
1817[[package]]2042[[package]]
2043name = "matchers"
2044version = "0.2.0"
2045source = "registry+https://github.com/rust-lang/crates.io-index"
2046checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
2047dependencies = [
2048 "regex-automata",
2049]
2050
2051[[package]]
2052name = "matchit"
2053version = "0.8.4"
2054source = "registry+https://github.com/rust-lang/crates.io-index"
2055checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
2056
2057[[package]]
2058name = "maud"
2059version = "0.27.0"
2060source = "registry+https://github.com/rust-lang/crates.io-index"
2061checksum = "8156733e27020ea5c684db5beac5d1d611e1272ab17901a49466294b84fc217e"
2062dependencies = [
2063 "axum-core",
2064 "http",
2065 "itoa",
2066 "maud_macros",
2067]
2068
2069[[package]]
2070name = "maud_macros"
2071version = "0.27.0"
2072source = "registry+https://github.com/rust-lang/crates.io-index"
2073checksum = "7261b00f3952f617899bc012e3dbd56e4f0110a038175929fa5d18e5a19913ca"
2074dependencies = [
2075 "proc-macro2",
2076 "proc-macro2-diagnostics",
2077 "quote",
2078 "syn 2.0.119",
2079]
2080
2081[[package]]
1818name = "md-5"2082name = "md-5"
1819version = "0.10.6"2083version = "0.10.6"
1820source = "registry+https://github.com/rust-lang/crates.io-index"2084source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1847,6 +2111,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
1847checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"2111checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
18482112
1849[[package]]2113[[package]]
2114name = "mime_guess"
2115version = "2.0.5"
2116source = "registry+https://github.com/rust-lang/crates.io-index"
2117checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
2118dependencies = [
2119 "mime",
2120 "unicase",
2121]
2122
2123[[package]]
1850name = "miniz_oxide"2124name = "miniz_oxide"
1851version = "0.8.9"2125version = "0.8.9"
1852source = "registry+https://github.com/rust-lang/crates.io-index"2126source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1918,6 +2192,15 @@ dependencies = [
1918]2192]
19192193
1920[[package]]2194[[package]]
2195name = "nu-ansi-term"
2196version = "0.50.3"
2197source = "registry+https://github.com/rust-lang/crates.io-index"
2198checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
2199dependencies = [
2200 "windows-sys 0.61.2",
2201]
2202
2203[[package]]
1921name = "num-bigint-dig"2204name = "num-bigint-dig"
1922version = "0.8.6"2205version = "0.8.6"
1923source = "registry+https://github.com/rust-lang/crates.io-index"2206source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1935,6 +2218,12 @@ dependencies = [
1935]2218]
19362219
1937[[package]]2220[[package]]
2221name = "num-conv"
2222version = "0.1.0"
2223source = "registry+https://github.com/rust-lang/crates.io-index"
2224checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"
2225
2226[[package]]
1938name = "num-integer"2227name = "num-integer"
1939version = "0.1.46"2228version = "0.1.46"
1940source = "registry+https://github.com/rust-lang/crates.io-index"2229source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2196,7 +2485,7 @@ dependencies = [
2196 "cast5",2485 "cast5",
2197 "cfb-mode",2486 "cfb-mode",
2198 "cipher",2487 "cipher",
2199 "const-oid",2488 "const-oid 0.9.6",
2200 "crc24",2489 "crc24",
2201 "curve25519-dalek",2490 "curve25519-dalek",
2202 "cx448",2491 "cx448",
@@ -2304,6 +2593,12 @@ dependencies = [
2304]2593]
23052594
2306[[package]]2595[[package]]
2596name = "powerfmt"
2597version = "0.2.0"
2598source = "registry+https://github.com/rust-lang/crates.io-index"
2599checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
2600
2601[[package]]
2307name = "ppv-lite86"2602name = "ppv-lite86"
2308version = "0.2.21"2603version = "0.2.21"
2309source = "registry+https://github.com/rust-lang/crates.io-index"2604source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2532,7 +2827,7 @@ version = "0.9.10"
2532source = "registry+https://github.com/rust-lang/crates.io-index"2827source = "registry+https://github.com/rust-lang/crates.io-index"
2533checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"2828checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"
2534dependencies = [2829dependencies = [
2535 "const-oid",2830 "const-oid 0.9.6",
2536 "digest 0.10.7",2831 "digest 0.10.7",
2537 "num-bigint-dig",2832 "num-bigint-dig",
2538 "num-integer",2833 "num-integer",
@@ -2558,6 +2853,41 @@ dependencies = [
2558]2853]
25592854
2560[[package]]2855[[package]]
2856name = "rust-embed"
2857version = "8.12.0"
2858source = "registry+https://github.com/rust-lang/crates.io-index"
2859checksum = "e9e7760e252aaba7b09f4be00e36476cf585bdb68a53552ac954cdf504ab4bc9"
2860dependencies = [
2861 "rust-embed-impl",
2862 "rust-embed-utils",
2863 "walkdir",
2864]
2865
2866[[package]]
2867name = "rust-embed-impl"
2868version = "8.12.0"
2869source = "registry+https://github.com/rust-lang/crates.io-index"
2870checksum = "3bcfc4d6f53af43755f7a723e4b6b8794fcce052a178dd8c6c1dadc5f5343097"
2871dependencies = [
2872 "mime_guess",
2873 "proc-macro2",
2874 "quote",
2875 "rust-embed-utils",
2876 "syn 2.0.119",
2877 "walkdir",
2878]
2879
2880[[package]]
2881name = "rust-embed-utils"
2882version = "8.12.0"
2883source = "registry+https://github.com/rust-lang/crates.io-index"
2884checksum = "42ffa149f6aa81b58a5b3011d01a857c4ed12c7a732d2c51947a4c7c692185f0"
2885dependencies = [
2886 "sha2 0.11.0",
2887 "walkdir",
2888]
2889
2890[[package]]
2561name = "rustc_version"2891name = "rustc_version"
2562version = "0.4.1"2892version = "0.4.1"
2563source = "registry+https://github.com/rust-lang/crates.io-index"2893source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2586,6 +2916,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
2586checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"2916checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
25872917
2588[[package]]2918[[package]]
2919name = "ryu"
2920version = "1.0.23"
2921source = "registry+https://github.com/rust-lang/crates.io-index"
2922checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
2923
2924[[package]]
2925name = "same-file"
2926version = "1.0.6"
2927source = "registry+https://github.com/rust-lang/crates.io-index"
2928checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
2929dependencies = [
2930 "winapi-util",
2931]
2932
2933[[package]]
2589name = "schannel"2934name = "schannel"
2590version = "0.1.29"2935version = "0.1.29"
2591source = "registry+https://github.com/rust-lang/crates.io-index"2936source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2688,6 +3033,17 @@ dependencies = [
2688]3033]
26893034
2690[[package]]3035[[package]]
3036name = "serde_path_to_error"
3037version = "0.1.20"
3038source = "registry+https://github.com/rust-lang/crates.io-index"
3039checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
3040dependencies = [
3041 "itoa",
3042 "serde",
3043 "serde_core",
3044]
3045
3046[[package]]
2691name = "serde_spanned"3047name = "serde_spanned"
2692version = "0.6.9"3048version = "0.6.9"
2693source = "registry+https://github.com/rust-lang/crates.io-index"3049source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2697,6 +3053,18 @@ dependencies = [
2697]3053]
26983054
2699[[package]]3055[[package]]
3056name = "serde_urlencoded"
3057version = "0.7.1"
3058source = "registry+https://github.com/rust-lang/crates.io-index"
3059checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
3060dependencies = [
3061 "form_urlencoded",
3062 "itoa",
3063 "ryu",
3064 "serde",
3065]
3066
3067[[package]]
2700name = "serdect"3068name = "serdect"
2701version = "0.2.0"3069version = "0.2.0"
2702source = "registry+https://github.com/rust-lang/crates.io-index"3070source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2782,12 +3150,31 @@ dependencies = [
2782]3150]
27833151
2784[[package]]3152[[package]]
3153name = "sharded-slab"
3154version = "0.1.7"
3155source = "registry+https://github.com/rust-lang/crates.io-index"
3156checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
3157dependencies = [
3158 "lazy_static",
3159]
3160
3161[[package]]
2785name = "shlex"3162name = "shlex"
2786version = "2.0.1"3163version = "2.0.1"
2787source = "registry+https://github.com/rust-lang/crates.io-index"3164source = "registry+https://github.com/rust-lang/crates.io-index"
2788checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"3165checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
27893166
2790[[package]]3167[[package]]
3168name = "signal-hook-registry"
3169version = "1.4.8"
3170source = "registry+https://github.com/rust-lang/crates.io-index"
3171checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
3172dependencies = [
3173 "errno",
3174 "libc",
3175]
3176
3177[[package]]
2791name = "signature"3178name = "signature"
2792version = "2.2.0"3179version = "2.2.0"
2793source = "registry+https://github.com/rust-lang/crates.io-index"3180source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3155,6 +3542,12 @@ dependencies = [
3155]3542]
31563543
3157[[package]]3544[[package]]
3545name = "sync_wrapper"
3546version = "1.0.2"
3547source = "registry+https://github.com/rust-lang/crates.io-index"
3548checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
3549
3550[[package]]
3158name = "synstructure"3551name = "synstructure"
3159version = "0.13.2"3552version = "0.13.2"
3160source = "registry+https://github.com/rust-lang/crates.io-index"3553source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3231,6 +3624,46 @@ dependencies = [
3231]3624]
32323625
3233[[package]]3626[[package]]
3627name = "thread_local"
3628version = "1.1.10"
3629source = "registry+https://github.com/rust-lang/crates.io-index"
3630checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"
3631dependencies = [
3632 "cfg-if",
3633]
3634
3635[[package]]
3636name = "time"
3637version = "0.3.45"
3638source = "registry+https://github.com/rust-lang/crates.io-index"
3639checksum = "f9e442fc33d7fdb45aa9bfeb312c095964abdf596f7567261062b2a7107aaabd"
3640dependencies = [
3641 "deranged",
3642 "itoa",
3643 "num-conv",
3644 "powerfmt",
3645 "serde_core",
3646 "time-core",
3647 "time-macros",
3648]
3649
3650[[package]]
3651name = "time-core"
3652version = "0.1.7"
3653source = "registry+https://github.com/rust-lang/crates.io-index"
3654checksum = "8b36ee98fd31ec7426d599183e8fe26932a8dc1fb76ddb6214d05493377d34ca"
3655
3656[[package]]
3657name = "time-macros"
3658version = "0.2.25"
3659source = "registry+https://github.com/rust-lang/crates.io-index"
3660checksum = "71e552d1249bf61ac2a52db88179fd0673def1e1ad8243a00d9ec9ed71fee3dd"
3661dependencies = [
3662 "num-conv",
3663 "time-core",
3664]
3665
3666[[package]]
3234name = "tinystr"3667name = "tinystr"
3235version = "0.8.3"3668version = "0.8.3"
3236source = "registry+https://github.com/rust-lang/crates.io-index"3669source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3265,6 +3698,7 @@ dependencies = [
3265 "libc",3698 "libc",
3266 "mio",3699 "mio",
3267 "pin-project-lite",3700 "pin-project-lite",
3701 "signal-hook-registry",
3268 "socket2",3702 "socket2",
3269 "tokio-macros",3703 "tokio-macros",
3270 "windows-sys 0.61.2",3704 "windows-sys 0.61.2",
@@ -3303,6 +3737,19 @@ dependencies = [
3303]3737]
33043738
3305[[package]]3739[[package]]
3740name = "tokio-util"
3741version = "0.7.19"
3742source = "registry+https://github.com/rust-lang/crates.io-index"
3743checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"
3744dependencies = [
3745 "bytes",
3746 "futures-core",
3747 "futures-sink",
3748 "pin-project-lite",
3749 "tokio",
3750]
3751
3752[[package]]
3306name = "toml"3753name = "toml"
3307version = "0.8.23"3754version = "0.8.23"
3308source = "registry+https://github.com/rust-lang/crates.io-index"3755source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3344,6 +3791,55 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
3344checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"3791checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
33453792
3346[[package]]3793[[package]]
3794name = "tower"
3795version = "0.5.3"
3796source = "registry+https://github.com/rust-lang/crates.io-index"
3797checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
3798dependencies = [
3799 "futures-core",
3800 "futures-util",
3801 "pin-project-lite",
3802 "sync_wrapper",
3803 "tokio",
3804 "tower-layer",
3805 "tower-service",
3806 "tracing",
3807]
3808
3809[[package]]
3810name = "tower-http"
3811version = "0.6.11"
3812source = "registry+https://github.com/rust-lang/crates.io-index"
3813checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
3814dependencies = [
3815 "async-compression",
3816 "bitflags",
3817 "bytes",
3818 "futures-core",
3819 "http",
3820 "http-body",
3821 "pin-project-lite",
3822 "tokio",
3823 "tokio-util",
3824 "tower-layer",
3825 "tower-service",
3826 "tracing",
3827 "uuid",
3828]
3829
3830[[package]]
3831name = "tower-layer"
3832version = "0.3.3"
3833source = "registry+https://github.com/rust-lang/crates.io-index"
3834checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
3835
3836[[package]]
3837name = "tower-service"
3838version = "0.3.3"
3839source = "registry+https://github.com/rust-lang/crates.io-index"
3840checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
3841
3842[[package]]
3347name = "tracing"3843name = "tracing"
3348version = "0.1.44"3844version = "0.1.44"
3349source = "registry+https://github.com/rust-lang/crates.io-index"3845source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3373,6 +3869,49 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
3373checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"3869checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
3374dependencies = [3870dependencies = [
3375 "once_cell",3871 "once_cell",
3872 "valuable",
3873]
3874
3875[[package]]
3876name = "tracing-log"
3877version = "0.2.0"
3878source = "registry+https://github.com/rust-lang/crates.io-index"
3879checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
3880dependencies = [
3881 "log",
3882 "once_cell",
3883 "tracing-core",
3884]
3885
3886[[package]]
3887name = "tracing-serde"
3888version = "0.2.0"
3889source = "registry+https://github.com/rust-lang/crates.io-index"
3890checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1"
3891dependencies = [
3892 "serde",
3893 "tracing-core",
3894]
3895
3896[[package]]
3897name = "tracing-subscriber"
3898version = "0.3.23"
3899source = "registry+https://github.com/rust-lang/crates.io-index"
3900checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
3901dependencies = [
3902 "matchers",
3903 "nu-ansi-term",
3904 "once_cell",
3905 "regex-automata",
3906 "serde",
3907 "serde_json",
3908 "sharded-slab",
3909 "smallvec",
3910 "thread_local",
3911 "tracing",
3912 "tracing-core",
3913 "tracing-log",
3914 "tracing-serde",
3376]3915]
33773916
3378[[package]]3917[[package]]
@@ -3440,6 +3979,12 @@ dependencies = [
3440]3979]
34413980
3442[[package]]3981[[package]]
3982name = "unicase"
3983version = "2.9.0"
3984source = "registry+https://github.com/rust-lang/crates.io-index"
3985checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
3986
3987[[package]]
3443name = "unicode-bidi"3988name = "unicode-bidi"
3444version = "0.3.18"3989version = "0.3.18"
3445source = "registry+https://github.com/rust-lang/crates.io-index"3990source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3530,6 +4075,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
3530checksum = "4e8257fbc510f0a46eb602c10215901938b5c2a7d5e70fc11483b1d3c9b5b18c"4075checksum = "4e8257fbc510f0a46eb602c10215901938b5c2a7d5e70fc11483b1d3c9b5b18c"
35314076
3532[[package]]4077[[package]]
4078name = "valuable"
4079version = "0.1.1"
4080source = "registry+https://github.com/rust-lang/crates.io-index"
4081checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
4082
4083[[package]]
3533name = "vcpkg"4084name = "vcpkg"
3534version = "0.2.15"4085version = "0.2.15"
3535source = "registry+https://github.com/rust-lang/crates.io-index"4086source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3542,6 +4093,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
3542checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"4093checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
35434094
3544[[package]]4095[[package]]
4096name = "walkdir"
4097version = "2.5.0"
4098source = "registry+https://github.com/rust-lang/crates.io-index"
4099checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
4100dependencies = [
4101 "same-file",
4102 "winapi-util",
4103]
4104
4105[[package]]
3545name = "wasi"4106name = "wasi"
3546version = "0.11.1+wasi-snapshot-preview1"4107version = "0.11.1+wasi-snapshot-preview1"
3547source = "registry+https://github.com/rust-lang/crates.io-index"4108source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -3604,6 +4165,29 @@ dependencies = [
3604[[package]]4165[[package]]
3605name = "web"4166name = "web"
3606version = "0.1.0"4167version = "0.1.0"
4168dependencies = [
4169 "auth",
4170 "axum",
4171 "axum-extra",
4172 "config",
4173 "git",
4174 "highlight",
4175 "mail",
4176 "maud",
4177 "mime_guess",
4178 "model",
4179 "rust-embed",
4180 "serde",
4181 "serde_json",
4182 "store",
4183 "thiserror 2.0.19",
4184 "time",
4185 "tokio",
4186 "tower",
4187 "tower-http",
4188 "tracing",
4189 "tracing-subscriber",
4190]
36074191
3608[[package]]4192[[package]]
3609name = "web-time"4193name = "web-time"
@@ -3622,6 +4206,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
3622checksum = "998767ef88740d1f5b0682a9c53c24431453923962269c2db68ee43788c5a40d"4206checksum = "998767ef88740d1f5b0682a9c53c24431453923962269c2db68ee43788c5a40d"
36234207
3624[[package]]4208[[package]]
4209name = "winapi-util"
4210version = "0.1.11"
4211source = "registry+https://github.com/rust-lang/crates.io-index"
4212checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
4213dependencies = [
4214 "windows-sys 0.61.2",
4215]
4216
4217[[package]]
3625name = "windows-link"4218name = "windows-link"
3626version = "0.2.1"4219version = "0.2.1"
3627source = "registry+https://github.com/rust-lang/crates.io-index"4220source = "registry+https://github.com/rust-lang/crates.io-index"
Cargo.toml +33 −1
@@ -14,7 +14,14 @@ name = "fabrica"
14path = "src/main.rs"14path = "src/main.rs"
1515
16[dependencies]16[dependencies]
17# The binary wires the servers together: `cli` owns the command tree and hands
18# `serve` back to us so that no library crate has to depend on `web`.
17cli = { path = "crates/cli" }19cli = { path = "crates/cli" }
20web = { path = "crates/web" }
21config = { path = "crates/config" }
22store = { path = "crates/store" }
23anyhow = { workspace = true }
24tokio = { workspace = true }
1825
19[lints]26[lints]
20workspace = true27workspace = true
@@ -70,7 +77,14 @@ sqlx = { version = "0.9", default-features = false, features = [
70 "macros",77 "macros",
71] }78] }
72ulid = "1"79ulid = "1"
73tokio = { version = "1", features = ["macros", "rt-multi-thread"] }80tokio = { version = "1", features = [
81 "macros",
82 "rt-multi-thread",
83 "signal",
84 "net",
85 "time",
86 "fs",
87] }
74tempfile = "3"88tempfile = "3"
75# Git object model (refs, trees, blobs, commits, diffs, signatures). Linked89# Git object model (refs, trees, blobs, commits, diffs, signatures). Linked
76# against the system libgit2 (1.9) via pkg-config; the Nix build sets90# against the system libgit2 (1.9) via pkg-config; the Nix build sets
@@ -111,6 +125,24 @@ lettre = { version = "0.11", default-features = false, features = [
111 "tokio1-native-tls",125 "tokio1-native-tls",
112 "hostname",126 "hostname",
113] }127] }
128# Web stack. No TLS/rustls features anywhere (TLS terminates at a reverse proxy),
129# so `ring` stays out of the graph. Versions are the current mutually-compatible
130# axum 0.8 set.
131axum = "0.8"
132axum-extra = { version = "0.12", features = ["cookie"] }
133maud = { version = "0.27", features = ["axum"] }
134tower = { version = "0.5", features = ["util"] }
135tower-http = { version = "0.6", features = [
136 "compression-gzip",
137 "trace",
138 "request-id",
139 "timeout",
140] }
141rust-embed = "8"
142mime_guess = "2"
143time = "0.3"
144tracing = "0.1"
145tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt", "json"] }
114146
115[workspace.lints.rust]147[workspace.lints.rust]
116unsafe_code = "forbid"148unsafe_code = "forbid"
assets/base.css +379 −0
@@ -0,0 +1,379 @@
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
4 *
5 * base.css — structure only. No literal colours: every colour is a `--fb-*`
6 * custom property a theme supplies. A theme that sets only the documented tokens
7 * yields a complete UI (docs/theming.md). System font stacks; no web fonts. */
8
9:root {
10 --fb-font-sans: system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial,
11 sans-serif;
12 --fb-font-mono: ui-monospace, "SF Mono", "JetBrains Mono", "Fira Code",
13 Menlo, Consolas, monospace;
14 --fb-radius: 6px;
15 --fb-gap: 1rem;
16 --fb-topbar-h: 3rem;
17}
18
19* {
20 box-sizing: border-box;
21}
22
23html {
24 color-scheme: var(--fb-color-scheme, dark);
25}
26
27body {
28 margin: 0;
29 font-family: var(--fb-font-sans);
30 font-size: 14px;
31 line-height: 1.5;
32 color: var(--fb-fg);
33 background: var(--fb-bg);
34 -webkit-font-smoothing: antialiased;
35}
36
37a {
38 color: var(--fb-accent);
39 text-decoration: none;
40}
41a:hover {
42 text-decoration: underline;
43}
44
45h1, h2, h3, h4 {
46 line-height: 1.25;
47 margin: 0 0 0.5em;
48}
49
50code, pre, .mono {
51 font-family: var(--fb-font-mono);
52}
53
54/* Accessibility: visible focus, skip link. */
55:focus-visible {
56 outline: 2px solid var(--fb-accent);
57 outline-offset: 2px;
58}
59.skip-link {
60 position: absolute;
61 left: -999px;
62 top: 0;
63 z-index: 100;
64 padding: 0.5rem 1rem;
65 background: var(--fb-bg-raised);
66 border: 1px solid var(--fb-border);
67}
68.skip-link:focus {
69 left: 0.5rem;
70 top: 0.5rem;
71}
72
73/* ---- Top bar ---- */
74.topbar {
75 display: flex;
76 align-items: center;
77 gap: 0.75rem;
78 height: var(--fb-topbar-h);
79 padding: 0 0.75rem;
80 border-bottom: 1px solid var(--fb-border);
81 background: var(--fb-bg-raised);
82 position: sticky;
83 top: 0;
84 z-index: 20;
85}
86.topbar .slug {
87 font-weight: 600;
88}
89.topbar .slug a {
90 color: var(--fb-fg);
91}
92.topbar .tabs {
93 display: flex;
94 gap: 0.25rem;
95 margin: 0 auto;
96 overflow-x: auto;
97}
98.topbar .tabs a {
99 padding: 0.35rem 0.7rem;
100 border-radius: var(--fb-radius);
101 color: var(--fb-fg-muted);
102 white-space: nowrap;
103}
104.topbar .tabs a:hover {
105 background: var(--fb-bg-inset);
106 text-decoration: none;
107}
108.topbar .tabs a[aria-current="page"] {
109 color: var(--fb-fg);
110 background: var(--fb-bg-inset);
111}
112
113.icon-btn {
114 display: inline-flex;
115 align-items: center;
116 justify-content: center;
117 width: 2rem;
118 height: 2rem;
119 padding: 0;
120 border: none;
121 border-radius: var(--fb-radius);
122 background: transparent;
123 color: var(--fb-fg);
124 cursor: pointer;
125}
126.icon-btn:hover {
127 background: var(--fb-bg-inset);
128}
129
130/* ---- Drawer (off-canvas nav) ---- */
131.drawer-backdrop {
132 display: none;
133 position: fixed;
134 inset: 0;
135 background: rgba(0, 0, 0, 0.5);
136 z-index: 30;
137}
138.drawer {
139 position: fixed;
140 top: 0;
141 left: 0;
142 bottom: 0;
143 width: 16rem;
144 max-width: 85vw;
145 transform: translateX(-100%);
146 transition: transform 0.15s ease;
147 background: var(--fb-bg-raised);
148 border-right: 1px solid var(--fb-border);
149 z-index: 40;
150 padding: 1rem;
151 overflow-y: auto;
152}
153body.drawer-open .drawer {
154 transform: translateX(0);
155}
156body.drawer-open .drawer-backdrop {
157 display: block;
158}
159.drawer h2 {
160 font-size: 1rem;
161}
162.drawer nav a,
163.drawer .drawer-item {
164 display: block;
165 padding: 0.4rem 0.5rem;
166 border-radius: var(--fb-radius);
167 color: var(--fb-fg);
168}
169.drawer nav a:hover {
170 background: var(--fb-bg-inset);
171 text-decoration: none;
172}
173.drawer hr {
174 border: none;
175 border-top: 1px solid var(--fb-border);
176 margin: 0.75rem 0;
177}
178
179/* ---- Layout ---- */
180.page {
181 max-width: 76rem;
182 margin: 0 auto;
183 padding: var(--fb-gap);
184}
185
186.card {
187 background: var(--fb-bg-raised);
188 border: 1px solid var(--fb-border);
189 border-radius: var(--fb-radius);
190 padding: 1rem;
191}
192
193.muted {
194 color: var(--fb-fg-muted);
195}
196
197/* ---- Buttons & forms ---- */
198.btn {
199 display: inline-flex;
200 align-items: center;
201 gap: 0.4rem;
202 padding: 0.4rem 0.8rem;
203 border: 1px solid var(--fb-border);
204 border-radius: var(--fb-radius);
205 background: var(--fb-bg-inset);
206 color: var(--fb-fg);
207 font: inherit;
208 cursor: pointer;
209}
210.btn:hover {
211 border-color: var(--fb-accent);
212 text-decoration: none;
213}
214.btn-primary {
215 background: var(--fb-accent);
216 border-color: var(--fb-accent);
217 color: var(--fb-accent-fg, #fff);
218}
219.btn-danger {
220 border-color: var(--fb-danger);
221 color: var(--fb-danger);
222}
223
224label {
225 display: block;
226 margin: 0.75rem 0 0.25rem;
227 font-weight: 600;
228}
229input[type="text"],
230input[type="password"],
231input[type="email"],
232input[type="search"],
233textarea,
234select {
235 width: 100%;
236 padding: 0.5rem;
237 font: inherit;
238 color: var(--fb-fg);
239 background: var(--fb-bg-inset);
240 border: 1px solid var(--fb-border);
241 border-radius: var(--fb-radius);
242}
243input:focus,
244textarea:focus,
245select:focus {
246 border-color: var(--fb-accent);
247 outline: none;
248}
249
250.form-narrow {
251 max-width: 24rem;
252 margin: 3rem auto;
253}
254
255/* ---- Flash / notices ---- */
256.notice {
257 padding: 0.6rem 0.8rem;
258 border-radius: var(--fb-radius);
259 border: 1px solid var(--fb-border);
260 background: var(--fb-bg-inset);
261 margin-bottom: 0.75rem;
262}
263.notice-error {
264 border-color: var(--fb-danger);
265}
266.notice-success {
267 border-color: var(--fb-success);
268}
269
270/* ---- Badges ---- */
271.badge {
272 display: inline-flex;
273 align-items: center;
274 gap: 0.25rem;
275 padding: 0.05rem 0.45rem;
276 font-size: 0.8em;
277 border-radius: 999px;
278 border: 1px solid var(--fb-border);
279}
280.badge-verified {
281 color: var(--fb-success);
282 border-color: var(--fb-success);
283}
284.badge-unverified {
285 color: var(--fb-warning);
286 border-color: var(--fb-warning);
287}
288.badge-private {
289 color: var(--fb-fg-muted);
290}
291
292/* ---- Repo/list rows ---- */
293.repo-list {
294 list-style: none;
295 margin: 0;
296 padding: 0;
297}
298.repo-list li {
299 padding: 0.75rem 0;
300 border-bottom: 1px solid var(--fb-border);
301}
302.repo-list .name {
303 font-weight: 600;
304 font-size: 1.05em;
305}
306
307/* ---- Tables ---- */
308table.list {
309 width: 100%;
310 border-collapse: collapse;
311}
312table.list th,
313table.list td {
314 text-align: left;
315 padding: 0.5rem 0.6rem;
316 border-bottom: 1px solid var(--fb-border);
317}
318table.list th {
319 color: var(--fb-fg-muted);
320 font-weight: 600;
321}
322
323/* ---- Code ---- */
324pre.code {
325 margin: 0;
326 padding: 0.75rem 1rem;
327 overflow-x: auto;
328 background: var(--fb-bg-inset);
329 border-radius: var(--fb-radius);
330}
331
332/* Highlight classes — coloured entirely by the theme's --fb-hl-* tokens. */
333.hl-keyword { color: var(--fb-hl-keyword); }
334.hl-function { color: var(--fb-hl-function); }
335.hl-type { color: var(--fb-hl-type); }
336.hl-string { color: var(--fb-hl-string); }
337.hl-number { color: var(--fb-hl-number); }
338.hl-comment { color: var(--fb-hl-comment); font-style: italic; }
339.hl-constant { color: var(--fb-hl-constant); }
340.hl-variable { color: var(--fb-hl-variable); }
341.hl-operator { color: var(--fb-hl-operator); }
342.hl-punctuation { color: var(--fb-hl-punctuation); }
343.hl-attribute { color: var(--fb-hl-attribute); }
344.hl-tag { color: var(--fb-hl-tag); }
345
346/* ---- Error page ---- */
347.error-page {
348 text-align: center;
349 padding: 5rem 1rem;
350}
351.error-page .code {
352 font-size: 4rem;
353 font-weight: 700;
354 color: var(--fb-fg-muted);
355}
356.error-page .req-id {
357 font-size: 0.85em;
358 color: var(--fb-fg-muted);
359}
360
361/* ---- Footer ---- */
362.footer {
363 max-width: 76rem;
364 margin: 2rem auto 1rem;
365 padding: 1rem var(--fb-gap) 0;
366 border-top: 1px solid var(--fb-border);
367 color: var(--fb-fg-muted);
368 font-size: 0.85em;
369}
370
371/* ---- Responsive: single breakpoint at 48rem ---- */
372@media (max-width: 48rem) {
373 .topbar .tabs {
374 margin: 0;
375 }
376 .page {
377 padding: 0.75rem;
378 }
379}
assets/fabrica.js +86 −0
@@ -0,0 +1,86 @@
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4//
5// Progressive enhancement only. Every interactive element works without this
6// file; it adds the mobile drawer, the theme picker, clipboard buttons, and a
7// couple of keyboard shortcuts. Kept small and dependency-free (< 200 lines).
8
9(function () {
10 "use strict";
11
12 // ---- Mobile nav drawer ----
13 function toggleDrawer(open) {
14 var body = document.body;
15 var isOpen = open === undefined ? !body.classList.contains("drawer-open") : open;
16 body.classList.toggle("drawer-open", isOpen);
17 var toggle = document.querySelector("[data-drawer-toggle]");
18 if (toggle) toggle.setAttribute("aria-expanded", isOpen ? "true" : "false");
19 }
20
21 document.addEventListener("click", function (e) {
22 var toggle = e.target.closest("[data-drawer-toggle]");
23 if (toggle) {
24 e.preventDefault();
25 toggleDrawer();
26 return;
27 }
28 if (e.target.closest("[data-drawer-close]") || e.target.classList.contains("drawer-backdrop")) {
29 toggleDrawer(false);
30 }
31 });
32
33 // ---- Theme picker ----
34 // Apply the chosen theme instantly for feedback, then submit the picker's form
35 // so the server persists the cookie and serves the matching stylesheet. Without
36 // JS the form's submit button does the same thing.
37 document.addEventListener("change", function (e) {
38 var picker = e.target.closest("[data-theme-picker]");
39 if (!picker) return;
40 var opt = picker.options[picker.selectedIndex];
41 var root = document.documentElement;
42 root.setAttribute("data-theme", picker.value);
43 if (opt && opt.getAttribute("data-scheme")) {
44 root.style.colorScheme = opt.getAttribute("data-scheme");
45 }
46 if (picker.form) picker.form.submit();
47 });
48
49 // ---- Clipboard buttons ----
50 document.addEventListener("click", function (e) {
51 var btn = e.target.closest("[data-clipboard]");
52 if (!btn) return;
53 e.preventDefault();
54 var text = btn.getAttribute("data-clipboard");
55 if (navigator.clipboard) {
56 navigator.clipboard.writeText(text).then(function () {
57 var old = btn.getAttribute("aria-label") || btn.textContent;
58 btn.setAttribute("aria-label", "Copied");
59 btn.classList.add("copied");
60 setTimeout(function () {
61 btn.setAttribute("aria-label", old);
62 btn.classList.remove("copied");
63 }, 1200);
64 });
65 }
66 });
67
68 // ---- Keyboard shortcuts ----
69 document.addEventListener("keydown", function (e) {
70 // Ignore when typing in a field.
71 var tag = (e.target.tagName || "").toLowerCase();
72 if (tag === "input" || tag === "textarea" || tag === "select" || e.target.isContentEditable) {
73 if (e.key === "Escape") e.target.blur();
74 return;
75 }
76 if (e.key === "/") {
77 var search = document.querySelector('input[type="search"], [data-search-input]');
78 if (search) {
79 e.preventDefault();
80 search.focus();
81 }
82 } else if (e.key === "Escape") {
83 toggleDrawer(false);
84 }
85 });
86})();
assets/htmx.min.js +1 −1
@@ -0,0 +1 @@
0 \ No newline at end of file1var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/<head(\s[^>]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('<body><template class="internal-htmx-wrapper">'+t+"</template></body>");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function D(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e<t.length;e++){n.push(t[e])}}return n}function se(t,n){if(t){for(let e=0;e<t.length;e++){n(t[e])}}}function X(e){const t=e.getBoundingClientRect();const n=t.top;const r=t.bottom;return n<window.innerHeight&&r>=0}function le(e){return e.getRootNode({composed:true})===document}function F(e){return e.trim().split(/\s+/)}function ce(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){O(e);return null}}function B(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function U(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return vn(ne().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function u(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return u(ne(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ne(),e)}}function E(){return window}function z(e,t){e=y(e);if(t){E().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function f(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ue(y(e));if(!e){return}if(n){E().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ue(y(e));if(!r){return}if(n){E().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function Z(e,t){e=y(e);se(e.parentElement.children,function(e){G(e,t)});K(ue(e),t)}function g(e,t){e=ue(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&ue(c(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function ge(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function p(t,r,n){if(r.indexOf("global ")===0){return p(t,r.slice(7),true)}t=y(t);const o=[];{let t=0;let n=0;for(let e=0;e<r.length;e++){const l=r[e];if(l===","&&t===0){o.push(r.substring(n,e));n=e+1;continue}if(l==="<"){t++}else if(l==="/"&&e<r.length-1&&r[e+1]===">"){t--}}if(n<r.length){o.push(r.substring(n))}}const i=[];const s=[];while(o.length>0){const r=ge(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),ge(r.substr(8)))}else if(r.indexOf("find ")===0){e=u(f(t),ge(r.substr(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,ge(r.substr(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,ge(r.substr(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=m(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=f(m(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=0;e<r.length;e++){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_PRECEDING){return o}}};var me=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=r.length-1;e>=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ae(e,t){if(typeof e!=="string"){return p(e,t)[0]}else{return p(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return u(f(t)||document,e)}else{return e}}function xe(e,t,n,r){if(k(t)){return{target:ne().body,event:J(e),listener:t,options:n}}else{return{target:y(e),event:J(t),listener:n,options:r}}}function ye(t,n,r,o){Vn(function(){const e=xe(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Vn(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=ne().createElement("output");function we(e,t){const n=re(e,t);if(n){if(n==="this"){return[Se(e,t)]}else{const r=p(e,n);if(r.length===0){O('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ue(o(e,function(e){return te(ue(e),t)!=null}))}function Ee(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Ce(t){const n=Q.config.attributesToSettle;for(let e=0;e<n.length;e++){if(t===n[e]){return true}}return false}function Oe(t,n){se(t.attributes,function(e){if(!n.hasAttribute(e.name)&&Ce(e.name)){t.removeAttribute(e.name)}});se(n.attributes,function(e){if(Ce(e.name)){t.setAttribute(e.name,e.value)}})}function Re(t,e){const n=Un(e);for(let e=0;e<n.length;e++){const r=n[e];try{if(r.isInlineSwap(t)){return true}}catch(e){O(e)}}return t==="outerHTML"}function He(e,o,i,t){t=t||ne();let n="#"+ee(o,"id");let s="outerHTML";if(e==="true"){}else if(e.indexOf(":")>0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=p(t,n,false);if(r){se(r,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!Re(s,e)){t=f(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=u("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=u("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){se(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){if(e.moveBefore){let e=u("#--htmx-preserve-pantry--");if(e==null){ne().body.insertAdjacentHTML("afterend","<div id='--htmx-preserve-pantry--'></div>");e=u("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Le(l,e,c){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=f(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ae(e){return function(){G(e,Q.config.addedClass);kt(ue(e));Ne(f(e));he(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function a(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n<e.length){t=(t<<5)-t+e.charCodeAt(n++)|0}return t}function Pe(t){let n=0;if(t.attributes){for(let e=0;e<t.attributes.length;e++){const r=t.attributes[e];if(r.value){n=Ie(r.name,n);n=Ie(r.value,n)}}}return n}function ke(t){const n=ie(t);if(n.onHandlers){for(let e=0;e<n.onHandlers.length;e++){const r=n.onHandlers[e];be(t,r.event,r.listener)}delete n.onHandlers}}function De(e){const t=ie(e);if(t.timeout){clearTimeout(t.timeout)}if(t.listenerInfos){se(t.listenerInfos,function(e){if(e.on){be(e.on,e.trigger,e.listener)}})}ke(e);se(Object.keys(t),function(e){if(e!=="firstInitCompleted")delete t[e]})}function b(e){he(e,"htmx:beforeCleanupElement");De(e);if(e.children){se(e.children,function(e){b(e)})}}function Me(t,e,n){if(t instanceof Element&&t.tagName==="BODY"){return Ve(t,e,n)}let r;const o=t.previousSibling;const i=c(t);if(!i){return}a(i,t,e,n);if(o==null){r=i.firstChild}else{r=o.nextSibling}n.elts=n.elts.filter(function(e){return e!==t});while(r&&r!==t){if(r instanceof Element){n.elts.push(r)}r=r.nextSibling}b(t);if(t instanceof Element){t.remove()}else{t.parentNode.removeChild(t)}}function Xe(e,t,n){return a(e,e.firstChild,t,n)}function Fe(e,t,n){return a(c(e),e,t,n)}function Be(e,t,n){return a(e,null,t,n)}function Ue(e,t,n){return a(c(e),e.nextSibling,t,n)}function je(e){b(e);const t=c(e);if(t){return t.removeChild(e)}}function Ve(e,t,n){const r=e.firstChild;a(e,r,t,n);if(r){while(r.nextSibling){b(r.nextSibling);e.removeChild(r.nextSibling)}b(r);e.removeChild(r)}}function _e(t,e,n,r,o){switch(t){case"none":return;case"outerHTML":Me(n,r,o);return;case"afterbegin":Xe(n,r,o);return;case"beforebegin":Fe(n,r,o);return;case"beforeend":Be(n,r,o);return;case"afterend":Ue(n,r,o);return;case"delete":je(n);return;default:var i=Un(e);for(let e=0;e<i.length;e++){const s=i[e];try{const l=s.handleSwap(t,n,r,o);if(l){if(Array.isArray(l)){for(let e=0;e<l.length;e++){const c=l[e];if(c.nodeType!==Node.TEXT_NODE&&c.nodeType!==Node.COMMENT_NODE){o.tasks.push(Ae(c))}}}return}}catch(e){O(e)}}if(t==="innerHTML"){Ve(n,r,o)}else{_e(Q.config.defaultSwapStyle,e,n,r,o)}}}function ze(e,n,r){var t=x(e,"[hx-swap-oob], [data-hx-swap-oob]");se(t,function(e){if(Q.config.allowNestedOobSwaps||e.parentElement===null){const t=te(e,"hx-swap-oob");if(t!=null){He(t,e,n,r)}}else{e.removeAttribute("hx-swap-oob");e.removeAttribute("data-hx-swap-oob")}});return t.length>0}function $e(e,t,r,o){if(!o){o={}}e=y(e);const i=o.contextElement?m(o.contextElement,false):ne();const n=document.activeElement;let s={};try{s={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const l=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=P(t);l.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t<u.length;t++){const a=u[t].split(":",2);let e=a[0].trim();if(e.indexOf("#")===0){e=e.substring(1)}const f=a[1]||"true";const h=n.querySelector("#"+e);if(h){He(f,h,l,i)}}}ze(n,l,i);se(x(n,"template"),function(e){if(e.content&&ze(e.content,l,i)){e.remove()}});if(o.select){const d=ne().createDocumentFragment();se(n.querySelectorAll(o.select),function(e){d.appendChild(e)});n=d}qe(n);_e(r.swapStyle,o.contextElement,e,n,l);Te()}if(s.elt&&!le(s.elt)&&ee(s.elt,"id")){const g=document.getElementById(ee(s.elt,"id"));const p={preventScroll:r.focusScroll!==undefined?!r.focusScroll:!Q.config.defaultFocusScroll};if(g){if(s.start&&g.setSelectionRange){try{g.setSelectionRange(s.start,s.end)}catch(e){}}g.focus(p)}}e.classList.remove(Q.config.swappingClass);se(l.elts,function(e){if(e.classList){e.classList.add(Q.config.settlingClass)}he(e,"htmx:afterSwap",o.eventInfo)});if(o.afterSwapCallback){o.afterSwapCallback()}if(!r.ignoreTitle){kn(l.title)}const c=function(){se(l.tasks,function(e){e.call()});se(l.elts,function(e){if(e.classList){e.classList.remove(Q.config.settlingClass)}he(e,"htmx:afterSettle",o.eventInfo)});if(o.anchor){const e=ue(y("#"+o.anchor));if(e){e.scrollIntoView({block:"start",behavior:"auto"})}}yn(l.elts,r);if(o.afterSettleCallback){o.afterSettleCallback()}};if(r.settleDelay>0){E().setTimeout(c,r.settleDelay)}else{c()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(D(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}he(n,i,e)}}}else{const s=r.split(",");for(let e=0;e<s.length;e++){he(n,s[e].trim(),[])}}}const Ke=/\s/;const v=/[\s,]/;const Ge=/[_$a-zA-Z]/;const We=/[_$a-zA-Z0-9]/;const Ze=['"',"'","/"];const w=/[^\s]/;const Ye=/[{(]/;const Qe=/[})]/;function et(e){const t=[];let n=0;while(n<e.length){if(Ge.exec(e.charAt(n))){var r=n;while(We.exec(e.charAt(n+1))){n++}t.push(e.substring(r,n+1))}else if(Ze.indexOf(e.charAt(n))!==-1){const o=e.charAt(n);var r=n;n++;while(n<e.length&&e.charAt(n)!==o){if(e.charAt(n)==="\\"){n++}n++}t.push(e.substring(r,n+1))}else{const i=e.charAt(n);t.push(i)}n++}return t}function tt(e,t,n){return Ge.exec(e.charAt(0))&&e!=="true"&&e!=="false"&&e!=="this"&&e!==n&&t!=="."}function nt(r,o,i){if(o[0]==="["){o.shift();let e=1;let t=" return (function("+i+"){ return (";let n=null;while(o.length>0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function C(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=C(e,Qe).trim();e.shift()}else{t=C(e,v)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{C(o,w);const l=o.length;const c=C(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};C(o,w);u.pollInterval=d(C(o,/[,\[\s]/));C(o,w);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=nt(e,o,"event");if(i){a.eventFilter=i}C(o,w);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(C(o,v))}else if(f==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=C(o,v);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=rt(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(C(o,v))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=C(o,v)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=rt(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=C(o,v)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!gt(n,e,Mt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ft(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=ne().location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){pt(t,function(e,t){const n=ue(e);if(at(n)){b(n);return}de(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ue(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(h(n,'input[type="submit"], button')&&(h(n,"[form]")||g(n,"form")!==null)){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function pt(l,c,e,u,a){const f=ie(l);let t;if(u.from){t=p(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}se(t,function(i){const s=function(e){if(!le(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(a||ht(e,l)){e.preventDefault()}if(gt(u,l,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ue(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=event.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){he(l,"htmx:trigger");c(l,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){he(l,"htmx:trigger");c(l,e)},u.delay)}else{he(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let xt=null;function yt(){if(!xt){xt=function(){mt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(mt){mt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&X(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;he(e,"htmx:trigger");t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;se(r,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(g(n,Q.config.disableSelector)){b(n);return}de(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){yt();pt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e<t.length;e++){const n=t[e];if(n.isIntersecting){he(r,"intersect");break}}},o);i.observe(ue(r));pt(ue(r),n,t,e)}else if(!t.firstInitCompleted&&e.trigger==="load"){if(!gt(e,r,Mt("load",{elt:r}))){vt(ue(r),n,t,e.delay)}}else if(e.pollInterval>0){t.polling=true;ct(ue(r),n,e)}else{pt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e<n.length;e++){const r=n[e].name;if(l(r,"hx-on:")||l(r,"data-hx-on:")||l(r,"hx-on-")||l(r,"data-hx-on-")){return true}}return false}const Ct=(new XPathEvaluator).createExpression('.//*[@*[ starts-with(name(), "hx-on:") or starts-with(name(), "data-hx-on:") or'+' starts-with(name(), "hx-on-") or starts-with(name(), "data-hx-on-") ]]');function Ot(e,t){if(Et(e)){t.push(ue(e))}const n=Ct.evaluate(e);let r=null;while(r=n.iterateNext())t.push(ue(r))}function Rt(e){const t=[];if(e instanceof DocumentFragment){for(const n of e.childNodes){Ot(n,t)}}else{Ot(e,t)}return t}function Ht(e){if(e.querySelectorAll){const n=", [hx-boost] a, [data-hx-boost] a, a[hx-boost], a[data-hx-boost]";const r=[];for(const i in Mn){const s=Mn[i];if(s.getSelectors){var t=s.getSelectors();if(t){r.push(t)}}}const o=e.querySelectorAll(H+n+", form, [type='submit'],"+" [hx-ext], [data-hx-ext], [hx-trigger], [data-hx-trigger]"+r.flat().map(e=>", "+e).join(""));return o}else{return[]}}function Tt(e){const t=g(ue(e.target),"button, input[type='submit']");const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Lt(e){const t=g(ue(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Nt(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function It(t){ke(t);for(let e=0;e<t.attributes.length;e++){const n=t.attributes[e].name;const r=t.attributes[e].value;if(l(n,"hx-on")||l(n,"data-hx-on")){const o=n.indexOf("-on")+3;const i=n.slice(o,o+1);if(i==="-"||i===":"){let e=n.slice(o+1);if(l(e,":")){e="htmx"+e}else if(l(e,"-")){e="htmx:"+e.slice(1)}else if(l(e,"htmx-")){e="htmx:"+e.slice(5)}Nt(t,e,r)}}}}function Pt(t){if(g(t,Q.config.disableSelector)){b(t);return}const n=ie(t);const e=Pe(t);if(n.initHash!==e){De(t);n.initHash=e;he(t,"htmx:beforeProcessNode");const r=st(t);const o=wt(t,n,r);if(!o){if(re(t,"hx-boost")==="true"){ft(t,n,r)}else if(s(t,"hx-trigger")){r.forEach(function(e){St(t,e,n,function(){})})}}if(t.tagName==="FORM"||ee(t,"type")==="submit"&&s(t,"form")){At(t)}n.firstInitCompleted=true;he(t,"htmx:afterProcessNode")}}function kt(e){e=y(e);if(g(e,Q.config.disableSelector)){b(e);return}Pt(e);se(Ht(e),function(e){Pt(e)});se(Rt(e),It)}function Dt(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function Mt(e,t){let n;if(window.CustomEvent&&typeof window.CustomEvent==="function"){n=new CustomEvent(e,{bubbles:true,cancelable:true,composed:true,detail:t})}else{n=ne().createEvent("CustomEvent");n.initCustomEvent(e,true,true,t)}return n}function fe(e,t,n){he(e,t,ce({error:t},n))}function Xt(e){return e==="htmx:afterProcessNode"}function Ft(e,t){se(Un(e),function(e){try{t(e)}catch(e){O(e)}})}function O(e){if(console.error){console.error(e)}else if(console.log){console.log("ERROR: ",e)}}function he(e,t,n){e=y(e);if(n==null){n={}}n.elt=e;const r=Mt(t,n);if(Q.logger&&!Xt(t)){Q.logger(e,t,n)}if(n.error){O(n.error);he(e,"htmx:error",{errorInfo:n})}let o=e.dispatchEvent(r);const i=Dt(t);if(o&&i!==t){const s=Mt(i,r.detail);o=o&&e.dispatchEvent(s)}Ft(ue(e),function(e){o=o&&(e.onEvent(t,r)!==false&&!r.defaultPrevented)});return o}let Bt=location.pathname+location.search;function Ut(){const e=ne().querySelector("[hx-history-elt],[data-hx-history-elt]");return e||ne().body}function jt(t,e){if(!B()){return}const n=_t(e);const r=ne().title;const o=window.scrollY;if(Q.config.historyCacheSize<=0){localStorage.removeItem("htmx-history-cache");return}t=U(t);const i=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e<i.length;e++){if(i[e].url===t){i.splice(e,1);break}}const s={url:t,content:n,title:r,scroll:o};he(ne().body,"htmx:historyItemCreated",{item:s,cache:i});i.push(s);while(i.length>Q.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Vt(t){if(!B()){return null}t=U(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e<n.length;e++){if(n[e].url===t){return n[e]}}return null}function _t(e){const t=Q.config.requestClass;const n=e.cloneNode(true);se(x(n,"."+t),function(e){G(e,t)});se(x(n,"[data-disabled-by-htmx]"),function(e){e.removeAttribute("disabled")});return n.innerHTML}function zt(){const e=Ut();const t=Bt||location.pathname+location.search;let n;try{n=ne().querySelector('[hx-history="false" i],[data-hx-history="false" i]')}catch(e){n=ne().querySelector('[hx-history="false"],[data-hx-history="false"]')}if(!n){he(ne().body,"htmx:beforeHistorySave",{path:t,historyElt:e});jt(t,e)}if(Q.config.historyEnabled)history.replaceState({htmx:true},ne().title,window.location.href)}function $t(e){if(Q.config.getCacheBusterParam){e=e.replace(/org\.htmx\.cache-buster=[^&]*&?/,"");if(Y(e,"&")||Y(e,"?")){e=e.slice(0,-1)}}if(Q.config.historyEnabled){history.pushState({htmx:true},"",e)}Bt=e}function Jt(e){if(Q.config.historyEnabled)history.replaceState({htmx:true},"",e);Bt=e}function Kt(e){se(e,function(e){e.call(undefined)})}function Gt(o){const e=new XMLHttpRequest;const i={path:o,xhr:e};he(ne().body,"htmx:historyCacheMiss",i);e.open("GET",o,true);e.setRequestHeader("HX-Request","true");e.setRequestHeader("HX-History-Restore-Request","true");e.setRequestHeader("HX-Current-URL",ne().location.href);e.onload=function(){if(this.status>=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=P(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=Ut();const r=xn(n);kn(e.title);qe(e);Ve(n,t,r);Te();Kt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Wt(e){zt();e=e||location.pathname+location.search;const t=Vt(e);if(t){const n=P(t.content);const r=Ut();const o=xn(r);kn(t.title);qe(n);Ve(r,n,o);Te();Kt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Gt(e)}}}function Zt(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Yt(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function Qt(e,t){se(e.concat(t),function(e){const t=ie(e);t.requestCount=(t.requestCount||1)-1});se(e,function(e){const t=ie(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function en(t,n){for(let e=0;e<t.length;e++){const r=t[e];if(r.isSameNode(n)){return true}}return false}function tn(e){const t=e;if(t.name===""||t.name==null||t.disabled||g(t,"fieldset[disabled]")){return false}if(t.type==="button"||t.type==="submit"||t.tagName==="image"||t.tagName==="reset"||t.tagName==="file"){return false}if(t.type==="checkbox"||t.type==="radio"){return t.checked}return true}function nn(t,e,n){if(t!=null&&e!=null){if(Array.isArray(e)){e.forEach(function(e){n.append(t,e)})}else{n.append(t,e)}}}function rn(t,n,r){if(t!=null&&n!=null){let e=r.getAll(t);if(Array.isArray(n)){e=e.filter(e=>n.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function on(t,n,r,o,i){if(o==null||en(t,o)){return}else{t.push(o)}if(tn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=M(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=M(o.files)}nn(s,e,n);if(i){sn(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){rn(e.name,e.value,n)}else{t.push(e)}if(i){sn(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}nn(t,e,n)})}}function sn(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function ln(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){on(n,o,i,g(e,"form"),l)}on(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=ee(u,"name");nn(a,u.value,o)}const c=we(e,"hx-include");se(c,function(e){on(n,r,i,ue(e),l);if(!h(e,"form")){se(f(e).querySelectorAll(ot),function(e){on(n,r,i,e,l)})}});ln(r,o);return{errors:i,formData:r,values:An(r)}}function un(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function an(e){e=qn(e);let n="";e.forEach(function(e,t){n=un(n,t,e)});return n}function fn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};bn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function dn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function gn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!dn(e)){r.show="top"}if(n){const s=F(n);if(s.length>0){for(let e=0;e<s.length;e++){const l=s[e];if(l.indexOf("swap:")===0){r.swapDelay=d(l.slice(5))}else if(l.indexOf("settle:")===0){r.settleDelay=d(l.slice(7))}else if(l.indexOf("transition:")===0){r.transition=l.slice(11)==="true"}else if(l.indexOf("ignoreTitle:")===0){r.ignoreTitle=l.slice(12)==="true"}else if(l.indexOf("scroll:")===0){const c=l.slice(7);var o=c.split(":");const u=o.pop();var i=o.length>0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{O("Unknown modifier in hx-swap: "+l)}}}}return r}function pn(e){return re(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function mn(t,n,r){let o=null;Ft(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(pn(n)){return ln(new FormData,qn(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function yn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ae(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ae(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function bn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return bn(ue(c(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function wn(e,t){return bn(e,"hx-vars",true,t)}function Sn(e,t){return bn(e,"hx-vals",false,t)}function En(e){return ce(wn(e),Sn(e))}function Cn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Rn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return de(t,n,null,null,{targetOverride:y(r)||ve,returnPromise:true})}else{let e=y(r.target);if(r.target&&!e||r.source&&!e&&!y(r.source)){e=ve}return de(t,n,y(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return de(t,n,null,null,{returnPromise:true})}}function Hn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Tn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ce({url:o,sameHost:r},n))}function qn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Ln(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}else{return e[t]}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Ln(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function de(t,n,r,o,i,D){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Dn;const X=i.select||null;if(!le(r)){oe(s);return e}const c=i.targetOverride||ue(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let u=ie(r);const a=u.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const A=ee(a,"formmethod");if(A!=null){if(A.toLowerCase()!=="dialog"){t=A}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ue(ae(r,I))}d=(N[1]||"drop").trim();u=ie(h);if(d==="drop"&&u.xhr&&u.abortable!==true){oe(s);return e}else if(d==="abort"){if(u.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");g=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(g==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;u.xhr=p;u.abortable=F;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var x=prompt(B);if(x===null||!he(r,"htmx:prompt",{prompt:x,target:c})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let y=fn(r,c,x);if(t!=="get"&&!pn(r)){y["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){y=ce(y,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){ln(j,qn(i.values))}const V=qn(En(r));const v=ln(j,V);let w=hn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=bn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:An(w),unfilteredFormData:v,unfilteredParameters:An(v),headers:y,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;y=C.headers;w=qn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let R=n;if(E){R=$;const Z=!w.keys().next().done;if(Z){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=an(w);if(O){R+="#"+O}}}if(!Tn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in y){if(y.hasOwnProperty(k)){const Y=y[k];Cn(p,k,Y)}}}const H={xhr:p,target:c,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Hn(r);H.pathInfo.responsePath=On(p);M(r,H);if(H.keepIndicators!==true){Qt(T,q)}he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ce({error:e},H));throw e}};p.onerror=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Zt(r);var q=Yt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:mn(p,r,w);p.send(J);return e}function Nn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const c=re(e,"hx-replace-url");const u=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function In(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Pn(e){for(var t=0;t<Q.config.responseHandling.length;t++){var n=Q.config.responseHandling[t];if(In(n,e.status)){return n}}return{swap:false}}function kn(e){if(e){const t=u("title");if(t){t.innerHTML=e}else{window.document.title=e}}}function Dn(o,i){const s=i.xhr;let l=i.target;const e=i.etc;const c=i.select;if(!he(o,"htmx:beforeOnLoad",i))return;if(R(s,/HX-Trigger:/i)){Je(s,"HX-Trigger",o)}if(R(s,/HX-Location:/i)){zt();let e=s.getResponseHeader("HX-Location");var t;if(e.indexOf("{")===0){t=S(e);e=t.path;delete t.path}Rn("get",e,t).then(function(){$t(e)});return}const n=R(s,/HX-Refresh:/i)&&s.getResponseHeader("HX-Refresh")==="true";if(R(s,/HX-Redirect:/i)){i.keepIndicators=true;location.href=s.getResponseHeader("HX-Redirect");n&&location.reload();return}if(n){i.keepIndicators=true;location.reload();return}if(R(s,/HX-Retarget:/i)){if(s.getResponseHeader("HX-Retarget")==="this"){i.target=o}else{i.target=ue(ae(o,s.getResponseHeader("HX-Retarget")))}}const u=Nn(o,i);const r=Pn(s);const a=r.swap;let f=!!r.error;let h=Q.config.ignoreTitle||r.ignoreTitle;let d=r.select;if(r.target){i.target=ue(ae(o,r.target))}var g=e.swapOverride;if(g==null&&r.swapOverride){g=r.swapOverride}if(R(s,/HX-Retarget:/i)){if(s.getResponseHeader("HX-Retarget")==="this"){i.target=o}else{i.target=ue(ae(o,s.getResponseHeader("HX-Retarget")))}}if(R(s,/HX-Reswap:/i)){g=s.getResponseHeader("HX-Reswap")}var p=s.response;var m=ce({shouldSwap:a,serverResponse:p,isError:f,ignoreTitle:h,selectOverride:d,swapOverride:g},i);if(r.event&&!he(l,r.event,m))return;if(!he(l,"htmx:beforeSwap",m))return;l=m.target;p=m.serverResponse;f=m.isError;h=m.ignoreTitle;d=m.selectOverride;g=m.swapOverride;i.target=l;i.failed=f;i.successful=!f;if(m.shouldSwap){if(s.status===286){lt(o)}Ft(o,function(e){p=e.transformResponse(p,s,o)});if(u.type){zt()}var x=gn(o,g);if(!x.hasOwnProperty("ignoreTitle")){x.ignoreTitle=h}l.classList.add(Q.config.swappingClass);let n=null;let r=null;if(c){d=c}if(R(s,/HX-Reselect:/i)){d=s.getResponseHeader("HX-Reselect")}const y=re(o,"hx-select-oob");const b=re(o,"hx-select");let e=function(){try{if(u.type){he(ne().body,"htmx:beforeHistoryUpdate",ce({history:u},i));if(u.type==="push"){$t(u.path);he(ne().body,"htmx:pushedIntoHistory",{path:u.path})}else{Jt(u.path);he(ne().body,"htmx:replacedInHistory",{path:u.path})}}$e(l,p,x,{select:d||b,selectOOB:y,eventInfo:i,anchor:i.pathInfo.anchor,contextElement:o,afterSwapCallback:function(){if(R(s,/HX-Trigger-After-Swap:/i)){let e=o;if(!le(o)){e=ne().body}Je(s,"HX-Trigger-After-Swap",e)}},afterSettleCallback:function(){if(R(s,/HX-Trigger-After-Settle:/i)){let e=o;if(!le(o)){e=ne().body}Je(s,"HX-Trigger-After-Settle",e)}oe(n)}})}catch(e){fe(o,"htmx:swapError",i);oe(r);throw e}};let t=Q.config.globalViewTransitions;if(x.hasOwnProperty("transition")){t=x.transition}if(t&&he(o,"htmx:beforeTransition",i)&&typeof Promise!=="undefined"&&document.startViewTransition){const v=new Promise(function(e,t){n=e;r=t});const w=e;e=function(){document.startViewTransition(function(){w();return v})}}if(x.swapDelay>0){E().setTimeout(e,x.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ce({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Mn={};function Xn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Fn(e,t){if(t.init){t.init(n)}Mn[e]=ce(Xn(),t)}function Bn(e){delete Mn[e]}function Un(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Mn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return Un(ue(c(e)),n,r)}var jn=false;ne().addEventListener("DOMContentLoaded",function(){jn=true});function Vn(e){if(jn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function _n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend","<style"+e+"> ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} </style>")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function $n(){const e=zn();if(e){Q.config=ce(Q.config,e)}}Vn(function(){$n();_n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Wt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}();
assets/themes/dark.css +45 −0
@@ -0,0 +1,45 @@
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
4 *
5 * dark — the default theme. Defines every documented --fb-* token; base.css is
6 * structure-only and reads exclusively from these. See docs/theming.md. */
7
8:root {
9 --fb-color-scheme: dark;
10
11 /* Surfaces & text */
12 --fb-bg: #0d1117;
13 --fb-bg-raised: #161b22;
14 --fb-bg-inset: #21262d;
15 --fb-border: #30363d;
16 --fb-fg: #e6edf3;
17 --fb-fg-muted: #8b949e;
18
19 /* Accents & status */
20 --fb-accent: #4493f8;
21 --fb-accent-fg: #ffffff;
22 --fb-success: #3fb950;
23 --fb-warning: #d29922;
24 --fb-danger: #f85149;
25
26 /* Diff row backgrounds & gutters */
27 --fb-diff-add-bg: rgba(63, 185, 80, 0.15);
28 --fb-diff-del-bg: rgba(248, 81, 73, 0.15);
29 --fb-diff-add-fg: #3fb950;
30 --fb-diff-del-fg: #f85149;
31
32 /* Syntax highlighting */
33 --fb-hl-keyword: #ff7b72;
34 --fb-hl-function: #d2a8ff;
35 --fb-hl-type: #7ee787;
36 --fb-hl-string: #a5d6ff;
37 --fb-hl-number: #79c0ff;
38 --fb-hl-comment: #8b949e;
39 --fb-hl-constant: #79c0ff;
40 --fb-hl-variable: #ffa657;
41 --fb-hl-operator: #ff7b72;
42 --fb-hl-punctuation: #c9d1d9;
43 --fb-hl-attribute: #7ee787;
44 --fb-hl-tag: #7ee787;
45}
assets/themes/light.css +44 −0
@@ -0,0 +1,44 @@
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
4 *
5 * light — the embedded light theme. Defines every documented --fb-* token. */
6
7:root {
8 --fb-color-scheme: light;
9
10 /* Surfaces & text */
11 --fb-bg: #ffffff;
12 --fb-bg-raised: #f6f8fa;
13 --fb-bg-inset: #eaeef2;
14 --fb-border: #d0d7de;
15 --fb-fg: #1f2328;
16 --fb-fg-muted: #656d76;
17
18 /* Accents & status */
19 --fb-accent: #0969da;
20 --fb-accent-fg: #ffffff;
21 --fb-success: #1a7f37;
22 --fb-warning: #9a6700;
23 --fb-danger: #cf222e;
24
25 /* Diff row backgrounds & gutters */
26 --fb-diff-add-bg: rgba(26, 127, 55, 0.12);
27 --fb-diff-del-bg: rgba(207, 34, 46, 0.12);
28 --fb-diff-add-fg: #1a7f37;
29 --fb-diff-del-fg: #cf222e;
30
31 /* Syntax highlighting */
32 --fb-hl-keyword: #cf222e;
33 --fb-hl-function: #8250df;
34 --fb-hl-type: #1a7f37;
35 --fb-hl-string: #0a3069;
36 --fb-hl-number: #0550ae;
37 --fb-hl-comment: #6e7781;
38 --fb-hl-constant: #0550ae;
39 --fb-hl-variable: #953800;
40 --fb-hl-operator: #cf222e;
41 --fb-hl-punctuation: #24292f;
42 --fb-hl-attribute: #1a7f37;
43 --fb-hl-tag: #116329;
44}
crates/cli/src/lib.rs +52 −7
@@ -86,6 +86,16 @@ enum Command {
86 #[command(subcommand)]86 #[command(subcommand)]
87 command: token_cmd::TokenCommand,87 command: token_cmd::TokenCommand,
88 },88 },
89 /// Run the HTTPS and SSH servers in the foreground.
90 Serve {
91 /// Double-fork into the background and write a pid file. (Not yet
92 /// implemented — systemd/Docker manage the foreground process.)
93 #[arg(long)]
94 detach: bool,
95 /// Skip applying pending migrations on startup.
96 #[arg(long)]
97 no_migrate: bool,
98 },
89 /// Apply pending database migrations.99 /// Apply pending database migrations.
90 Migrate,100 Migrate,
91 /// Check that the environment fabrica needs is present and healthy.101 /// Check that the environment fabrica needs is present and healthy.
@@ -96,15 +106,42 @@ enum Command {
96 },106 },
97}107}
98108
109/// The parsed request to run `fabrica serve`, handed to the serve callback the
110/// root binary supplies. This keeps `cli` free of any dependency on `web`/`ssh`
111/// (no crate may depend on `web`); the binary wires the servers together.
112#[derive(Debug, Clone)]
113pub struct ServeRequest {
114 /// The `--config` path.
115 pub config_path: Option<PathBuf>,
116 /// Double-fork into the background.
117 pub detach: bool,
118 /// Skip startup migrations.
119 pub no_migrate: bool,
120}
121
122/// Resolve the instance signing secret (generating and persisting it on first
123/// use), for the binary's serve wiring.
124///
125/// # Errors
126///
127/// Returns an error if the secret file cannot be read or written.
128pub fn resolve_secret(config: &config::Config) -> anyhow::Result<String> {
129 context::ensure_secret(config)
130}
131
99/// Parse arguments and dispatch to the requested subcommand.132/// Parse arguments and dispatch to the requested subcommand.
100///133///
101/// Returns the process exit code. Argument-parse failures are handled by clap134/// `serve` handles the `fabrica serve` command; the root binary supplies it so
102/// (which prints usage and exits); any other error is printed to stderr and135/// the servers (which live in `web`/`ssh`) are wired without `cli` depending on
103/// mapped to [`ExitCode::FAILURE`].136/// them. Returns the process exit code. Argument-parse failures are handled by
104#[must_use]137/// clap; any other error is printed to stderr and mapped to
105pub fn run() -> ExitCode {138/// [`ExitCode::FAILURE`].
139pub fn run<F>(serve: F) -> ExitCode
140where
141 F: FnOnce(ServeRequest) -> anyhow::Result<ExitCode>,
142{
106 let cli = Cli::parse();143 let cli = Cli::parse();
107 match dispatch(&cli) {144 match dispatch(&cli, serve) {
108 Ok(code) => code,145 Ok(code) => code,
109 Err(err) => {146 Err(err) => {
110 eprintln!("error: {err:#}");147 eprintln!("error: {err:#}");
@@ -114,8 +151,16 @@ pub fn run() -> ExitCode {
114}151}
115152
116/// Route a parsed [`Cli`] to its handler.153/// Route a parsed [`Cli`] to its handler.
117fn dispatch(cli: &Cli) -> anyhow::Result<ExitCode> {154fn dispatch<F>(cli: &Cli, serve: F) -> anyhow::Result<ExitCode>
155where
156 F: FnOnce(ServeRequest) -> anyhow::Result<ExitCode>,
157{
118 match &cli.command {158 match &cli.command {
159 Command::Serve { detach, no_migrate } => serve(ServeRequest {
160 config_path: cli.config.clone(),
161 detach: *detach,
162 no_migrate: *no_migrate,
163 }),
119 Command::Config { command } => config_cmd::run(command, cli.config.as_deref(), cli.json),164 Command::Config { command } => config_cmd::run(command, cli.config.as_deref(), cli.json),
120 Command::User { command } => user_cmd::run(command, cli.config.as_deref(), cli.json),165 Command::User { command } => user_cmd::run(command, cli.config.as_deref(), cli.json),
121 Command::Key { command } => key_cmd::run(command, cli.config.as_deref(), cli.json),166 Command::Key { command } => key_cmd::run(command, cli.config.as_deref(), cli.json),
crates/store/src/sessions.rs +0 −1
@@ -9,7 +9,6 @@
9//! filters on `expires_at` so an expired row is treated as absent.9//! filters on `expires_at` so an expired row is treated as absent.
1010
11use model::User;11use model::User;
12use sqlx::Row;
1312
14use crate::users::USER_COLUMNS;13use crate::users::USER_COLUMNS;
15use crate::{Store, StoreError, now_ms};14use crate::{Store, StoreError, now_ms};
crates/web/Cargo.toml +24 −0
@@ -10,6 +10,30 @@ repository.workspace = true
10publish.workspace = true10publish.workspace = true
1111
12[dependencies]12[dependencies]
13config = { workspace = true }
14store = { workspace = true }
15model = { workspace = true }
16auth = { workspace = true }
17mail = { workspace = true }
18git = { workspace = true }
19highlight = { workspace = true }
20axum = { workspace = true }
21axum-extra = { workspace = true }
22maud = { workspace = true }
23tower = { workspace = true }
24tower-http = { workspace = true }
25rust-embed = { workspace = true }
26mime_guess = { workspace = true }
27time = { workspace = true }
28serde = { workspace = true }
29serde_json = { workspace = true }
30thiserror = { workspace = true }
31tokio = { workspace = true }
32tracing = { workspace = true }
33tracing-subscriber = { workspace = true }
34
35[dev-dependencies]
36tower = { workspace = true, features = ["util"] }
1337
14[lints]38[lints]
15workspace = true39workspace = true
crates/web/src/assets.rs +244 −0
@@ -0,0 +1,244 @@
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Embedded assets, disk overrides, and the theme registry.
6//!
7//! `base.css`, `fabrica.js`, `htmx.min.js`, and the embedded themes are compiled
8//! into the binary with `rust-embed`. Any of them can be overridden by dropping a
9//! file of the same path in `ui.assets_dir`; themes additionally come from
10//! `ui.themes_dir`. Disk always wins over embedded, and path traversal is rejected.
11
12use std::path::{Path, PathBuf};
13
14use rust_embed::RustEmbed;
15
16/// The compiled-in assets, rooted at the repository `assets/` directory
17/// (relative to this crate's manifest).
18#[derive(RustEmbed)]
19#[folder = "../../assets"]
20struct Embedded;
21
22/// Whether a theme is light or dark, for the `color-scheme` hint and the picker.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum Scheme {
25 /// A dark theme.
26 Dark,
27 /// A light theme.
28 Light,
29}
30
31impl Scheme {
32 /// The CSS `color-scheme` keyword.
33 #[must_use]
34 pub fn as_str(self) -> &'static str {
35 match self {
36 Self::Dark => "dark",
37 Self::Light => "light",
38 }
39 }
40}
41
42/// A theme available for selection.
43#[derive(Debug, Clone)]
44pub struct ThemeInfo {
45 /// The theme name (its file stem).
46 pub name: String,
47 /// Light or dark.
48 pub scheme: Scheme,
49}
50
51/// Resolves assets and themes from disk (override) then the embedded set.
52#[derive(Clone)]
53#[allow(clippy::struct_field_names)] // `assets_dir` mirrors the `ui.assets_dir` config key.
54pub struct Assets {
55 assets_dir: PathBuf,
56 themes_dir: PathBuf,
57 themes: Vec<ThemeInfo>,
58}
59
60impl Assets {
61 /// Build the registry, scanning `themes_dir` and the embedded themes once.
62 #[must_use]
63 pub fn new(assets_dir: PathBuf, themes_dir: PathBuf) -> Self {
64 let mut this = Self {
65 assets_dir,
66 themes_dir,
67 themes: Vec::new(),
68 };
69 this.rescan();
70 this
71 }
72
73 /// Re-scan the themes directory (called on `SIGHUP`).
74 pub fn rescan(&mut self) {
75 let mut names: std::collections::BTreeMap<String, Scheme> =
76 std::collections::BTreeMap::new();
77
78 // Embedded themes first (lower priority).
79 for path in Embedded::iter() {
80 if let Some(name) = theme_name(&path) {
81 let scheme = Embedded::get(&path).map_or(Scheme::Dark, |f| scheme_of(&f.data));
82 names.insert(name, scheme);
83 }
84 }
85 // Disk themes override by name.
86 if let Ok(entries) = std::fs::read_dir(&self.themes_dir) {
87 for entry in entries.flatten() {
88 let path = entry.path();
89 if path.extension().and_then(|e| e.to_str()) == Some("css")
90 && let Some(stem) = path.file_stem().and_then(|s| s.to_str())
91 {
92 let scheme = std::fs::read(&path).map_or(Scheme::Dark, |d| scheme_of(&d));
93 names.insert(stem.to_string(), scheme);
94 }
95 }
96 }
97
98 self.themes = names
99 .into_iter()
100 .map(|(name, scheme)| ThemeInfo { name, scheme })
101 .collect();
102 }
103
104 /// The selectable themes, sorted by name.
105 #[must_use]
106 pub fn themes(&self) -> &[ThemeInfo] {
107 &self.themes
108 }
109
110 /// Look up a theme by name, returning its info.
111 #[must_use]
112 pub fn theme(&self, name: &str) -> Option<&ThemeInfo> {
113 self.themes.iter().find(|t| t.name == name)
114 }
115
116 /// The CSS bytes for a theme, disk overriding embedded.
117 #[must_use]
118 pub fn theme_css(&self, name: &str) -> Option<Vec<u8>> {
119 if !is_safe_component(name) {
120 return None;
121 }
122 let disk = self.themes_dir.join(format!("{name}.css"));
123 if let Ok(bytes) = std::fs::read(&disk) {
124 return Some(bytes);
125 }
126 Embedded::get(&format!("themes/{name}.css")).map(|f| f.data.into_owned())
127 }
128
129 /// Resolve a general asset by its request path (e.g. `base.css`,
130 /// `htmx.min.js`, `logo.svg`), disk overriding embedded. Returns the bytes and
131 /// a content type. Path traversal is rejected.
132 #[must_use]
133 pub fn asset(&self, rel: &str) -> Option<(Vec<u8>, &'static str)> {
134 let rel = rel.trim_start_matches('/');
135 if !is_safe_path(rel) {
136 return None;
137 }
138 let content_type = content_type_of(rel);
139 let disk = self.assets_dir.join(rel);
140 if disk.starts_with(&self.assets_dir)
141 && let Ok(bytes) = std::fs::read(&disk)
142 {
143 return Some((bytes, content_type));
144 }
145 Embedded::get(rel).map(|f| (f.data.into_owned(), content_type))
146 }
147}
148
149/// The theme name for an embedded path like `themes/dark.css`, or `None`.
150fn theme_name(path: &str) -> Option<String> {
151 let rest = path.strip_prefix("themes/")?;
152 let stem = rest.strip_suffix(".css")?;
153 (!stem.is_empty() && !stem.contains('/')).then(|| stem.to_string())
154}
155
156/// Read the `--fb-color-scheme` declaration from theme CSS, defaulting to dark.
157fn scheme_of(css: &[u8]) -> Scheme {
158 let text = String::from_utf8_lossy(css);
159 if let Some(idx) = text.find("--fb-color-scheme:") {
160 let after = text[idx + "--fb-color-scheme:".len()..].trim_start();
161 if after.starts_with("light") {
162 return Scheme::Light;
163 }
164 }
165 Scheme::Dark
166}
167
168/// Whether a single path component is safe (no separators, no `..`, non-empty).
169fn is_safe_component(name: &str) -> bool {
170 !name.is_empty() && !name.contains('/') && !name.contains('\\') && name != ".." && name != "."
171}
172
173/// Whether a relative asset path is safe (no traversal, no absolute, no `..`).
174fn is_safe_path(rel: &str) -> bool {
175 if rel.is_empty() {
176 return false;
177 }
178 !Path::new(rel).components().any(|c| {
179 matches!(
180 c,
181 std::path::Component::ParentDir
182 | std::path::Component::RootDir
183 | std::path::Component::Prefix(_)
184 )
185 })
186}
187
188/// A content type for a file, by extension.
189fn content_type_of(path: &str) -> &'static str {
190 match path.rsplit('.').next() {
191 Some("css") => "text/css; charset=utf-8",
192 Some("js") => "text/javascript; charset=utf-8",
193 Some("svg") => "image/svg+xml",
194 Some("ico") => "image/x-icon",
195 Some("png") => "image/png",
196 Some("woff2") => "font/woff2",
197 Some("json") => "application/json",
198 _ => "application/octet-stream",
199 }
200}
201
202#[cfg(test)]
203mod tests {
204 #![allow(clippy::unwrap_used)]
205
206 use super::*;
207
208 fn assets() -> Assets {
209 Assets::new(
210 PathBuf::from("/nonexistent-assets"),
211 PathBuf::from("/nonexistent-themes"),
212 )
213 }
214
215 #[test]
216 fn embedded_themes_are_registered_with_schemes() {
217 let a = assets();
218 let names: Vec<&str> = a.themes().iter().map(|t| t.name.as_str()).collect();
219 assert!(names.contains(&"dark"), "themes: {names:?}");
220 assert!(names.contains(&"light"));
221 assert_eq!(a.theme("dark").unwrap().scheme, Scheme::Dark);
222 assert_eq!(a.theme("light").unwrap().scheme, Scheme::Light);
223 }
224
225 #[test]
226 fn embedded_assets_resolve_with_content_types() {
227 let a = assets();
228 let (css, ct) = a.asset("base.css").unwrap();
229 assert!(!css.is_empty());
230 assert_eq!(ct, "text/css; charset=utf-8");
231 let (js, ct) = a.asset("htmx.min.js").unwrap();
232 assert!(!js.is_empty());
233 assert_eq!(ct, "text/javascript; charset=utf-8");
234 assert!(a.theme_css("dark").is_some());
235 }
236
237 #[test]
238 fn path_traversal_is_rejected() {
239 let a = assets();
240 assert!(a.asset("../Cargo.toml").is_none());
241 assert!(a.asset("/etc/passwd").is_none());
242 assert!(a.theme_css("../secret").is_none());
243 }
244}
crates/web/src/error.rs +125 −0
@@ -0,0 +1,125 @@
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! The application error type and its themed error pages.
6//!
7//! User-facing pages never expose internals: an internal error logs its detail
8//! (with a correlation id via `tracing`) and the page shows only the id. Error
9//! pages are self-contained — they link `base.css` and the default theme by stable
10//! URL, so they render even when produced by an extractor rejection with no access
11//! to application state.
12
13use axum::http::StatusCode;
14use axum::response::{Html, IntoResponse, Response};
15use maud::{DOCTYPE, Markup, html};
16
17/// A web-layer error mapped to a themed HTTP response.
18#[derive(Debug)]
19pub enum AppError {
20 /// 404 — also the "does not exist" response for private resources, so their
21 /// existence never leaks.
22 NotFound,
23 /// 401 — authentication required.
24 Unauthorized,
25 /// 403 — authenticated but not permitted.
26 Forbidden,
27 /// 400 — a malformed or invalid request.
28 BadRequest(String),
29 /// 500 — an unexpected internal failure. The detail is logged, never shown.
30 Internal(String),
31}
32
33/// A convenient result alias for handlers.
34pub type AppResult<T> = Result<T, AppError>;
35
36impl AppError {
37 /// Build an internal error from any displayable error, for `map_err`.
38 pub fn internal(err: impl std::fmt::Display) -> Self {
39 Self::Internal(err.to_string())
40 }
41}
42
43impl From<store::StoreError> for AppError {
44 fn from(err: store::StoreError) -> Self {
45 Self::Internal(err.to_string())
46 }
47}
48
49impl From<git::GitError> for AppError {
50 fn from(err: git::GitError) -> Self {
51 Self::internal(err)
52 }
53}
54
55impl IntoResponse for AppError {
56 fn into_response(self) -> Response {
57 let (status, heading, detail): (StatusCode, &str, String) = match self {
58 AppError::NotFound => (
59 StatusCode::NOT_FOUND,
60 "Not found",
61 "The page you were looking for does not exist.".to_string(),
62 ),
63 AppError::Unauthorized => (
64 StatusCode::UNAUTHORIZED,
65 "Sign in required",
66 "You need to sign in to view this page.".to_string(),
67 ),
68 AppError::Forbidden => (
69 StatusCode::FORBIDDEN,
70 "Forbidden",
71 "You do not have access to this page.".to_string(),
72 ),
73 AppError::BadRequest(msg) => (StatusCode::BAD_REQUEST, "Bad request", msg),
74 AppError::Internal(detail) => {
75 // Log the real detail with a short correlation id; show only the id.
76 let id = correlation_id();
77 tracing::error!(error.id = %id, error.detail = %detail, "internal error");
78 (
79 StatusCode::INTERNAL_SERVER_ERROR,
80 "Something went wrong",
81 format!("An internal error occurred. Reference: {id}"),
82 )
83 }
84 };
85 (
86 status,
87 Html(error_page(status.as_u16(), heading, &detail).into_string()),
88 )
89 .into_response()
90 }
91}
92
93/// A short, log-correlatable id. Derived from the monotonic-ish wall clock; it only
94/// needs to be unique enough to find the matching log line.
95fn correlation_id() -> String {
96 use std::time::{SystemTime, UNIX_EPOCH};
97 let nanos = SystemTime::now()
98 .duration_since(UNIX_EPOCH)
99 .map_or(0, |d| d.as_nanos());
100 format!("{nanos:x}")
101}
102
103/// A minimal, self-contained themed error page.
104fn error_page(code: u16, heading: &str, detail: &str) -> Markup {
105 html! {
106 (DOCTYPE)
107 html lang="en" {
108 head {
109 meta charset="utf-8";
110 meta name="viewport" content="width=device-width, initial-scale=1";
111 title { (code) " — " (heading) }
112 link rel="stylesheet" href="/assets/base.css";
113 link rel="stylesheet" href="/theme.css";
114 }
115 body {
116 div class="error-page" {
117 div class="code" { (code) }
118 h1 { (heading) }
119 p class="muted" { (detail) }
120 p { a href="/" { "Return home" } }
121 }
122 }
123 }
124 }
125}
crates/web/src/layout.rs +144 −0
@@ -0,0 +1,144 @@
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! The page shell: `<head>`, top bar, off-canvas drawer, theme picker, footer.
6//!
7//! Every full page is wrapped by [`page`]; htmx partials return fragments instead.
8//! Structure is server-rendered and works without JavaScript — the drawer is a
9//! `:target`-free CSS class toggled by `fabrica.js`, the theme picker is a real
10//! form, and every action is a link or form.
11
12use maud::{DOCTYPE, Markup, html};
13use model::User;
14
15use crate::assets::{Scheme, ThemeInfo};
16
17/// The per-request chrome data the shell needs.
18pub struct Chrome {
19 /// The instance name shown in the header and titles.
20 pub instance_name: String,
21 /// The current viewer, if signed in.
22 pub user: Option<User>,
23 /// The active theme name and scheme.
24 pub active_theme: String,
25 /// The active theme's light/dark scheme.
26 pub active_scheme: Scheme,
27 /// The themes offered by the picker.
28 pub themes: Vec<ThemeInfo>,
29 /// Whether the theme picker is shown.
30 pub allow_theme_choice: bool,
31 /// The current request path, for the theme form's return and nav highlighting.
32 pub path: String,
33 /// The CSRF token for this session, injected into htmx and forms.
34 pub csrf: String,
35}
36
37/// Wrap `body` in the full page shell with `title`.
38#[must_use]
39#[allow(clippy::needless_pass_by_value)] // `body` is an owned fragment the shell embeds.
40pub fn page(chrome: &Chrome, title: &str, body: Markup) -> Markup {
41 html! {
42 (DOCTYPE)
43 html lang="en" data-theme=(chrome.active_theme)
44 style={ "color-scheme: " (chrome.active_scheme.as_str()) } {
45 head {
46 meta charset="utf-8";
47 meta name="viewport" content="width=device-width, initial-scale=1";
48 title { (title) " · " (chrome.instance_name) }
49 link rel="stylesheet" href="/assets/base.css";
50 link rel="stylesheet" href={ "/theme/" (chrome.active_theme) ".css" };
51 // Operator-supplied overrides, injected after the theme.
52 link rel="stylesheet" href="/assets/custom.css";
53 script src="/assets/htmx.min.js" defer {}
54 script src="/assets/fabrica.js" defer {}
55 }
56 body hx-headers=(format!(r#"{{"X-CSRF-Token":"{}"}}"#, chrome.csrf)) {
57 a class="skip-link" href="#main" { "Skip to content" }
58 (topbar(chrome))
59 (drawer(chrome))
60 div class="drawer-backdrop" {}
61 main id="main" class="page" { (body) }
62 (footer(chrome))
63 }
64 }
65 }
66}
67
68/// The slim top bar.
69fn topbar(chrome: &Chrome) -> Markup {
70 html! {
71 header class="topbar" {
72 button class="icon-btn" type="button" data-drawer-toggle aria-label="Menu"
73 aria-expanded="false" { "☰" }
74 span class="slug" { a href="/" { (chrome.instance_name) } }
75 nav class="tabs" aria-label="Primary" {}
76 a class="icon-btn" href="/" aria-label="Home" { "⌂" }
77 }
78 }
79}
80
81/// The off-canvas navigation drawer.
82fn drawer(chrome: &Chrome) -> Markup {
83 html! {
84 aside class="drawer" aria-label="Navigation" {
85 h2 { (chrome.instance_name) }
86 nav {
87 a href="/" { "Home" }
88 @if let Some(user) = &chrome.user {
89 a href={ "/" (user.username) } { "Your repositories" }
90 }
91 }
92 hr;
93 @if chrome.allow_theme_choice && !chrome.themes.is_empty() {
94 (theme_picker(chrome))
95 hr;
96 }
97 nav {
98 @if chrome.user.is_some() {
99 a href="/settings" { "Settings" }
100 form method="post" action="/logout" {
101 input type="hidden" name="_csrf" value=(chrome.csrf);
102 button class="drawer-item" type="submit"
103 style="width:100%;text-align:left;border:none;background:none;color:inherit;cursor:pointer" {
104 "Log out"
105 }
106 }
107 } @else {
108 a href="/login" { "Sign in" }
109 }
110 }
111 }
112 }
113}
114
115/// The theme picker form (works without JS via the submit button).
116fn theme_picker(chrome: &Chrome) -> Markup {
117 html! {
118 form method="get" action="/settings/theme" {
119 label for="theme-select" { "Theme" }
120 input type="hidden" name="return" value=(chrome.path);
121 select id="theme-select" name="name" data-theme-picker {
122 @for theme in &chrome.themes {
123 option value=(theme.name)
124 data-scheme=(theme.scheme.as_str())
125 selected[theme.name == chrome.active_theme] {
126 (theme.name)
127 }
128 }
129 }
130 noscript { button class="btn" type="submit" { "Apply" } }
131 }
132 }
133}
134
135/// The page footer.
136fn footer(chrome: &Chrome) -> Markup {
137 html! {
138 footer class="footer" {
139 span { (chrome.instance_name) }
140 " · "
141 a href="/version" { "version" }
142 }
143 }
144}
crates/web/src/lib.rs +218 −1
@@ -2,4 +2,221 @@
2// License, v. 2.0. If a copy of the MPL was not distributed with this2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
44
5//! The web UI: server-rendered maud templates enhanced with htmx.5//! The web UI: server-rendered `maud` templates enhanced with htmx.
6//!
7//! [`AppState`] is the shared handle every route clones cheaply. [`serve`] builds
8//! the router, wires the tower-http middleware, and runs the server with graceful
9//! shutdown and a `SIGHUP` theme re-scan. Handlers live in [`pages`] (HTML) and
10//! [`serve`](mod@serve_assets) (assets/health). Every interactive element works
11//! without JavaScript; htmx only enhances.
12
13mod assets;
14mod error;
15mod layout;
16mod pages;
17#[path = "serve.rs"]
18mod serve_assets;
19mod session;
20#[cfg(test)]
21mod tests;
22
23use std::net::SocketAddr;
24use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard};
25
26use axum::Router;
27use axum::http::header::HeaderName;
28use axum::routing::{get, post};
29use config::Config;
30use mail::Mailer;
31use store::Store;
32use tower::ServiceBuilder;
33use tower_http::compression::CompressionLayer;
34use tower_http::request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer};
35use tower_http::trace::TraceLayer;
36
37use crate::assets::Assets;
38
39pub use crate::error::{AppError, AppResult};
40
41/// An error building or running the web server.
42#[derive(Debug, thiserror::Error)]
43pub enum WebError {
44 /// The mailer could not be constructed from configuration.
45 #[error("mail configuration error: {0}")]
46 Mail(String),
47 /// The server socket failed to bind or serve.
48 #[error(transparent)]
49 Io(#[from] std::io::Error),
50}
51
52/// The shared application state, cloned into every request. All fields are cheap
53/// to clone (reference-counted or pooled).
54#[derive(Clone)]
55pub struct AppState {
56 /// The effective configuration.
57 pub config: Arc<Config>,
58 /// The database handle.
59 pub store: Store,
60 /// The configured mailer (invite emails).
61 pub mailer: Arc<Mailer>,
62 /// The instance signing secret (API tokens, future session signing).
63 pub secret: Arc<String>,
64 /// Theme/asset registry, behind a lock so `SIGHUP` can re-scan it.
65 assets: Arc<RwLock<Assets>>,
66}
67
68impl AppState {
69 /// Build the shared state from configuration and an open store.
70 ///
71 /// # Errors
72 ///
73 /// Returns [`WebError::Mail`] if the mailer cannot be constructed.
74 pub fn build(config: Arc<Config>, store: Store, secret: String) -> Result<Self, WebError> {
75 let mailer = Mailer::build(&config.mail).map_err(|e| WebError::Mail(e.to_string()))?;
76 let assets = Assets::new(config.ui.assets_dir.clone(), config.ui.themes_dir.clone());
77 Ok(Self {
78 config,
79 store,
80 mailer: Arc::new(mailer),
81 secret: Arc::new(secret),
82 assets: Arc::new(RwLock::new(assets)),
83 })
84 }
85
86 /// A read guard over the asset registry, recovering from a poisoned lock.
87 fn assets(&self) -> RwLockReadGuard<'_, Assets> {
88 self.assets.read().unwrap_or_else(PoisonError::into_inner)
89 }
90
91 /// Re-scan the themes directory (invoked on `SIGHUP`).
92 fn rescan_assets(&self) {
93 let mut guard = self.assets.write().unwrap_or_else(PoisonError::into_inner);
94 guard.rescan();
95 }
96}
97
98/// Build the application router with all middleware wired.
99pub fn build_router(state: AppState) -> Router {
100 let x_request_id = HeaderName::from_static("x-request-id");
101
102 Router::new()
103 .route("/", get(pages::home))
104 .route("/login", get(pages::login_form).post(pages::login_submit))
105 .route("/logout", post(pages::logout))
106 .route(
107 "/invite/{token}",
108 get(pages::invite_form).post(pages::invite_submit),
109 )
110 .route("/settings", get(pages::settings))
111 .route("/settings/theme", get(pages::set_theme))
112 .route("/healthz", get(serve_assets::healthz))
113 .route("/version", get(serve_assets::version))
114 .route("/theme.css", get(serve_assets::theme_default))
115 .route("/theme/{file}", get(serve_assets::theme_named))
116 .route("/assets/{*path}", get(serve_assets::assets))
117 .layer(
118 ServiceBuilder::new()
119 .layer(SetRequestIdLayer::new(
120 x_request_id.clone(),
121 MakeRequestUuid,
122 ))
123 .layer(TraceLayer::new_for_http())
124 .layer(PropagateRequestIdLayer::new(x_request_id))
125 // No global request timeout: pack-transport routes (§3.3) stream
126 // arbitrarily long clones and must never be cut off. Per-route
127 // timeouts on non-git routes land in the polish phase.
128 .layer(CompressionLayer::new()),
129 )
130 .with_state(state)
131}
132
133/// Run the web server on `addr` until a shutdown signal arrives.
134///
135/// Installs a `SIGHUP` handler that re-scans the themes directory, and drains
136/// in-flight requests on `SIGTERM`/`SIGINT`.
137///
138/// # Errors
139///
140/// Returns [`WebError::Io`] if the listener cannot bind or serving fails.
141pub async fn serve(state: AppState, addr: SocketAddr) -> Result<(), WebError> {
142 init_tracing(&state.config);
143 spawn_sighup_rescan(state.clone());
144
145 let router = build_router(state);
146 let listener = tokio::net::TcpListener::bind(addr).await?;
147 tracing::info!(%addr, "fabrica web server listening");
148 axum::serve(listener, router)
149 .with_graceful_shutdown(shutdown_signal())
150 .await?;
151 Ok(())
152}
153
154/// Initialize the global tracing subscriber from the log configuration. Honours
155/// `RUST_LOG` when set; idempotent (a second call is a no-op).
156fn init_tracing(config: &Config) {
157 use config::LogFormat;
158 use tracing_subscriber::EnvFilter;
159
160 let level = match config.log.level {
161 config::LogLevel::Trace => "trace",
162 config::LogLevel::Debug => "debug",
163 config::LogLevel::Info => "info",
164 config::LogLevel::Warn => "warn",
165 config::LogLevel::Error => "error",
166 };
167 let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(level));
168 let builder = tracing_subscriber::fmt().with_env_filter(filter);
169 // `try_init` returns Err if a subscriber is already set; ignore it.
170 match config.log.format {
171 LogFormat::Json => {
172 let _ = builder.json().try_init();
173 }
174 LogFormat::Pretty => {
175 let _ = builder.try_init();
176 }
177 }
178}
179
180/// Spawn a task that re-scans themes on every `SIGHUP` (no-op off Unix).
181fn spawn_sighup_rescan(state: AppState) {
182 #[cfg(unix)]
183 tokio::spawn(async move {
184 use tokio::signal::unix::{SignalKind, signal};
185 let Ok(mut hup) = signal(SignalKind::hangup()) else {
186 tracing::warn!("could not install SIGHUP handler; theme re-scan disabled");
187 return;
188 };
189 while hup.recv().await.is_some() {
190 tracing::info!("SIGHUP: re-scanning themes");
191 state.rescan_assets();
192 }
193 });
194 #[cfg(not(unix))]
195 let _ = state;
196}
197
198/// A future that resolves on `SIGINT` or `SIGTERM`.
199async fn shutdown_signal() {
200 let ctrl_c = async {
201 let _ = tokio::signal::ctrl_c().await;
202 };
203
204 #[cfg(unix)]
205 let terminate = async {
206 use tokio::signal::unix::{SignalKind, signal};
207 match signal(SignalKind::terminate()) {
208 Ok(mut term) => {
209 term.recv().await;
210 }
211 Err(_) => std::future::pending::<()>().await,
212 }
213 };
214 #[cfg(not(unix))]
215 let terminate = std::future::pending::<()>();
216
217 tokio::select! {
218 () = ctrl_c => {},
219 () = terminate => {},
220 }
221 tracing::info!("shutdown signal received; draining");
222}
crates/web/src/pages.rs +460 −0
@@ -0,0 +1,460 @@
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! The HTML page handlers of the shell: home, sign-in/out, invite completion,
6//! settings, and the theme switch.
7
8use std::collections::HashMap;
9
10use axum::Form;
11use axum::extract::{Path, State};
12use axum::http::{HeaderMap, Uri, header};
13use axum::response::{IntoResponse, Redirect, Response};
14use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
15use maud::{Markup, html};
16use model::User;
17use serde::Deserialize;
18
19use crate::AppState;
20use crate::assets::Scheme;
21use crate::error::{AppError, AppResult};
22use crate::layout::{Chrome, page};
23use crate::session::{
24 MaybeUser, RequireUser, THEME_COOKIE, clear_cookie, ensure_csrf, session_cookie, verify_csrf,
25};
26
27/// Assemble the page chrome, ensuring the CSRF cookie and resolving the active
28/// theme from the visitor's cookie (falling back to the instance default).
29fn build_chrome(
30 state: &AppState,
31 jar: CookieJar,
32 user: Option<User>,
33 path: String,
34) -> (CookieJar, Chrome) {
35 let (jar, csrf) = ensure_csrf(jar, state.config.auth.cookie_secure);
36 let assets = state.assets();
37 let themes = assets.themes().to_vec();
38 let active = jar
39 .get(THEME_COOKIE)
40 .map(|c| c.value().to_string())
41 .filter(|name| assets.theme(name).is_some())
42 .unwrap_or_else(|| state.config.ui.theme.clone());
43 let scheme = assets.theme(&active).map_or(Scheme::Dark, |t| t.scheme);
44 drop(assets);
45
46 let chrome = Chrome {
47 instance_name: state.config.instance.name.clone(),
48 user,
49 active_theme: active,
50 active_scheme: scheme,
51 themes,
52 allow_theme_choice: state.config.ui.allow_theme_choice,
53 path,
54 csrf,
55 };
56 (jar, chrome)
57}
58
59/// `GET /` — your repositories and the public ones.
60pub async fn home(
61 State(state): State<AppState>,
62 MaybeUser(user): MaybeUser,
63 jar: CookieJar,
64 uri: Uri,
65) -> AppResult<Response> {
66 let (jar, chrome) = build_chrome(&state, jar, user.clone(), uri.path().to_string());
67 let body = home_body(&state, user.as_ref()).await?;
68 Ok((jar, page(&chrome, "Home", body)).into_response())
69}
70
71/// Render the home content: the viewer's own repos, plus public repos.
72async fn home_body(state: &AppState, user: Option<&User>) -> AppResult<Markup> {
73 let mine = match user {
74 Some(u) => state.store.repos_by_owner(&u.id).await?,
75 None => Vec::new(),
76 };
77 // Public repos, with owner names resolved for their links.
78 let all = state.store.list_repos().await?;
79 let public: Vec<_> = all.into_iter().filter(|r| !r.is_private).collect();
80 let mut owners: HashMap<String, String> = HashMap::new();
81 for repo in &public {
82 if !owners.contains_key(&repo.owner_id) {
83 let name = state
84 .store
85 .user_by_id(&repo.owner_id)
86 .await?
87 .map_or_else(|| repo.owner_id.clone(), |u| u.username);
88 owners.insert(repo.owner_id.clone(), name);
89 }
90 }
91
92 Ok(html! {
93 @if let Some(u) = user {
94 h1 { "Welcome, " (u.display_name.clone().unwrap_or_else(|| u.username.clone())) }
95 section {
96 h2 { "Your repositories" }
97 @if mine.is_empty() {
98 p class="muted" { "You have no repositories yet." }
99 } @else {
100 ul class="repo-list" {
101 @for repo in &mine {
102 li {
103 div class="name" {
104 a href={ "/" (u.username) "/" (repo.path) } { (repo.path) }
105 @if repo.is_private { " " span class="badge badge-private" { "private" } }
106 }
107 @if let Some(desc) = &repo.description { p class="muted" { (desc) } }
108 }
109 }
110 }
111 }
112 }
113 } @else {
114 h1 { "Welcome to " (state.config.instance.name) }
115 p { a class="btn btn-primary" href="/login" { "Sign in" } }
116 }
117 section {
118 h2 { "Public repositories" }
119 @if public.is_empty() {
120 p class="muted" { "No public repositories." }
121 } @else {
122 ul class="repo-list" {
123 @for repo in &public {
124 @let owner = owners.get(&repo.owner_id).cloned().unwrap_or_default();
125 li {
126 div class="name" {
127 a href={ "/" (owner) "/" (repo.path) } { (owner) "/" (repo.path) }
128 }
129 @if let Some(desc) = &repo.description { p class="muted" { (desc) } }
130 }
131 }
132 }
133 }
134 }
135 })
136}
137
138/// Sign-in form fields.
139#[derive(Debug, Deserialize)]
140pub struct LoginForm {
141 /// Username.
142 username: String,
143 /// Password.
144 password: String,
145 /// CSRF token (`_csrf`).
146 #[serde(rename = "_csrf")]
147 csrf: String,
148}
149
150/// `GET /login` — the sign-in form.
151pub async fn login_form(
152 State(state): State<AppState>,
153 MaybeUser(user): MaybeUser,
154 jar: CookieJar,
155 uri: Uri,
156) -> Response {
157 if user.is_some() {
158 return Redirect::to("/").into_response();
159 }
160 let (jar, chrome) = build_chrome(&state, jar, None, uri.path().to_string());
161 let body = login_body(&chrome.csrf, None);
162 (jar, page(&chrome, "Sign in", body)).into_response()
163}
164
165/// Render the login form with an optional error notice.
166fn login_body(csrf: &str, error: Option<&str>) -> Markup {
167 html! {
168 div class="form-narrow" {
169 h1 { "Sign in" }
170 @if let Some(err) = error {
171 div class="notice notice-error" { (err) }
172 }
173 form method="post" action="/login" {
174 input type="hidden" name="_csrf" value=(csrf);
175 label for="username" { "Username" }
176 input type="text" id="username" name="username" autocomplete="username" required;
177 label for="password" { "Password" }
178 input type="password" id="password" name="password"
179 autocomplete="current-password" required;
180 p { button class="btn btn-primary" type="submit" { "Sign in" } }
181 }
182 }
183 }
184}
185
186/// `POST /login` — verify credentials and open a session.
187pub async fn login_submit(
188 State(state): State<AppState>,
189 jar: CookieJar,
190 headers: HeaderMap,
191 Form(form): Form<LoginForm>,
192) -> Response {
193 if verify_csrf(&jar, &headers, Some(&form.csrf)).is_err() {
194 return AppError::Forbidden.into_response();
195 }
196
197 let user = state
198 .store
199 .user_by_username(&form.username)
200 .await
201 .ok()
202 .flatten();
203 let hash = user.as_ref().and_then(|u| u.password_hash.clone());
204 // Constant-time verify; a missing user still runs a dummy hash inside.
205 let ok = auth::verify_password(&form.password, hash.as_deref())
206 && user
207 .as_ref()
208 .is_some_and(|u| u.disabled_at.is_none() && u.password_hash.is_some());
209
210 let Some(user) = user.filter(|_| ok) else {
211 // Re-render the form with a generic error (no username enumeration).
212 let (jar, chrome) = build_chrome(&state, jar, None, "/login".to_string());
213 let body = login_body(&chrome.csrf, Some("Incorrect username or password."));
214 return (
215 axum::http::StatusCode::UNAUTHORIZED,
216 jar,
217 page(&chrome, "Sign in", body),
218 )
219 .into_response();
220 };
221
222 match open_session(&state, &jar, &user, &headers).await {
223 Ok(jar) => (jar, Redirect::to("/")).into_response(),
224 Err(err) => err.into_response(),
225 }
226}
227
228/// Mint a session, persist it, and return the jar with the session cookie set.
229async fn open_session(
230 state: &AppState,
231 jar: &CookieJar,
232 user: &User,
233 headers: &HeaderMap,
234) -> AppResult<CookieJar> {
235 let token = auth::new_session_token();
236 let ttl_ms = i64::from(state.config.auth.session_ttl_days).saturating_mul(86_400_000);
237 let user_agent = headers
238 .get(header::USER_AGENT)
239 .and_then(|v| v.to_str().ok())
240 .map(str::to_string);
241 state
242 .store
243 .create_session(store::NewSession {
244 id: token.id,
245 user_id: user.id.clone(),
246 user_agent,
247 ip: None,
248 expires_at: now_ms().saturating_add(ttl_ms),
249 })
250 .await?;
251 let cookie = session_cookie(
252 &state.config.auth.cookie_name,
253 token.cookie,
254 state.config.auth.session_ttl_days,
255 state.config.auth.cookie_secure,
256 );
257 Ok(jar.clone().add(cookie))
258}
259
260/// Logout form field.
261#[derive(Debug, Deserialize)]
262pub struct CsrfForm {
263 /// CSRF token (`_csrf`).
264 #[serde(rename = "_csrf")]
265 csrf: String,
266}
267
268/// `POST /logout` — destroy the session.
269pub async fn logout(
270 State(state): State<AppState>,
271 jar: CookieJar,
272 headers: HeaderMap,
273 Form(form): Form<CsrfForm>,
274) -> Response {
275 if verify_csrf(&jar, &headers, Some(&form.csrf)).is_err() {
276 return AppError::Forbidden.into_response();
277 }
278 if let Some(cookie) = jar.get(&state.config.auth.cookie_name) {
279 let session_id = auth::session_id(cookie.value());
280 let _ = state.store.delete_session(&session_id).await;
281 }
282 let jar = jar.add(clear_cookie(&state.config.auth.cookie_name));
283 (jar, Redirect::to("/login")).into_response()
284}
285
286/// Invite set-password form.
287#[derive(Debug, Deserialize)]
288pub struct InviteForm {
289 /// New password.
290 password: String,
291 /// Confirmation.
292 confirm: String,
293 /// CSRF token (`_csrf`).
294 #[serde(rename = "_csrf")]
295 csrf: String,
296}
297
298/// `GET /invite/{token}` — show the activation form, or an error if the invite is
299/// invalid, used, or expired.
300pub async fn invite_form(
301 State(state): State<AppState>,
302 jar: CookieJar,
303 uri: Uri,
304 Path(token): Path<String>,
305) -> AppResult<Response> {
306 let invite = live_invite(&state, &token).await?;
307 let _ = invite;
308 let (jar, chrome) = build_chrome(&state, jar, None, uri.path().to_string());
309 let body = html! {
310 div class="form-narrow" {
311 h1 { "Set your password" }
312 p class="muted" { "Choose a password to activate your account." }
313 form method="post" action={ "/invite/" (token) } {
314 input type="hidden" name="_csrf" value=(chrome.csrf);
315 label for="password" { "Password" }
316 input type="password" id="password" name="password"
317 autocomplete="new-password" required minlength="8";
318 label for="confirm" { "Confirm password" }
319 input type="password" id="confirm" name="confirm"
320 autocomplete="new-password" required;
321 p { button class="btn btn-primary" type="submit" { "Activate account" } }
322 }
323 }
324 };
325 Ok((jar, page(&chrome, "Activate", body)).into_response())
326}
327
328/// `POST /invite/{token}` — set the password, redeem the invite, and sign in.
329pub async fn invite_submit(
330 State(state): State<AppState>,
331 jar: CookieJar,
332 headers: HeaderMap,
333 Path(token): Path<String>,
334 Form(form): Form<InviteForm>,
335) -> Response {
336 if verify_csrf(&jar, &headers, Some(&form.csrf)).is_err() {
337 return AppError::Forbidden.into_response();
338 }
339 if form.password != form.confirm {
340 return AppError::BadRequest("Passwords do not match.".to_string()).into_response();
341 }
342 if form.password.len() < 8 {
343 return AppError::BadRequest("Password must be at least 8 characters.".to_string())
344 .into_response();
345 }
346
347 let result = async {
348 let invite = live_invite(&state, &token).await?;
349 let params = auth::HashParams {
350 m_cost: state.config.auth.argon2_m_cost,
351 t_cost: state.config.auth.argon2_t_cost,
352 p_cost: state.config.auth.argon2_p_cost,
353 };
354 let hash = auth::hash_password(&form.password, params).map_err(AppError::internal)?;
355 state
356 .store
357 .set_password(&invite.user_id, Some(&hash))
358 .await?;
359 state.store.mark_invite_used(&invite.id).await?;
360 let user = state
361 .store
362 .user_by_id(&invite.user_id)
363 .await?
364 .ok_or(AppError::NotFound)?;
365 open_session(&state, &jar, &user, &headers).await
366 }
367 .await;
368
369 match result {
370 Ok(jar) => (jar, Redirect::to("/")).into_response(),
371 Err(err) => err.into_response(),
372 }
373}
374
375/// Resolve a live (unredeemed, unexpired) invite for a raw token, or a themed
376/// error.
377async fn live_invite(state: &AppState, token: &str) -> AppResult<model::Invite> {
378 let hash = auth::session_id(token);
379 let invite = state
380 .store
381 .invite_by_token_hash(&hash)
382 .await?
383 .ok_or(AppError::NotFound)?;
384 if invite.used_at.is_some() {
385 return Err(AppError::BadRequest(
386 "This invite has already been used.".to_string(),
387 ));
388 }
389 if invite.expires_at <= now_ms() {
390 return Err(AppError::BadRequest("This invite has expired.".to_string()));
391 }
392 Ok(invite)
393}
394
395/// `GET /settings` — the viewer's profile summary.
396pub async fn settings(
397 State(state): State<AppState>,
398 RequireUser(user): RequireUser,
399 jar: CookieJar,
400 uri: Uri,
401) -> Response {
402 let (jar, chrome) = build_chrome(&state, jar, Some(user.clone()), uri.path().to_string());
403 let body = html! {
404 h1 { "Settings" }
405 div class="card" {
406 table class="list" {
407 tr { th { "Username" } td { (user.username) } }
408 tr { th { "Email" } td { (user.email) } }
409 tr { th { "Display name" } td { (user.display_name.clone().unwrap_or_default()) } }
410 tr { th { "Administrator" } td { (if user.is_admin { "yes" } else { "no" }) } }
411 }
412 }
413 p class="muted" { "Key and token management arrive with the settings pages." }
414 };
415 (jar, page(&chrome, "Settings", body)).into_response()
416}
417
418/// Theme-switch query.
419#[derive(Debug, Deserialize)]
420pub struct ThemeQuery {
421 /// The chosen theme name.
422 name: String,
423 /// Where to return afterwards (a local path).
424 #[serde(default)]
425 r#return: Option<String>,
426}
427
428/// `GET /settings/theme` — persist the chosen theme in a cookie and return. A
429/// preference, so a GET that sets a cookie is acceptable and works without JS.
430pub async fn set_theme(
431 State(state): State<AppState>,
432 jar: CookieJar,
433 axum::extract::Query(q): axum::extract::Query<ThemeQuery>,
434) -> Response {
435 // Only accept a known theme name.
436 if state.assets().theme(&q.name).is_none() {
437 return AppError::BadRequest("Unknown theme.".to_string()).into_response();
438 }
439 let cookie = Cookie::build((THEME_COOKIE, q.name))
440 .http_only(false)
441 .same_site(SameSite::Lax)
442 .secure(state.config.auth.cookie_secure)
443 .path("/")
444 .max_age(time::Duration::days(365))
445 .build();
446 // Only redirect to a local path, never an absolute URL (open-redirect guard).
447 let dest = q
448 .r#return
449 .filter(|r| r.starts_with('/') && !r.starts_with("//"))
450 .unwrap_or_else(|| "/".to_string());
451 (jar.add(cookie), Redirect::to(&dest)).into_response()
452}
453
454/// The current time in Unix milliseconds.
455fn now_ms() -> i64 {
456 use std::time::{SystemTime, UNIX_EPOCH};
457 SystemTime::now()
458 .duration_since(UNIX_EPOCH)
459 .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))
460}
crates/web/src/serve.rs +94 −0
@@ -0,0 +1,94 @@
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Static-asset, theme, and operational endpoints (`/assets`, `/theme`,
6//! `/healthz`, `/version`).
7
8use std::process::Command;
9
10use axum::Json;
11use axum::extract::{Path, State};
12use axum::http::{StatusCode, header};
13use axum::response::{IntoResponse, Response};
14
15use crate::AppState;
16
17/// Serve an embedded or disk-overridden asset by path.
18pub async fn assets(State(state): State<AppState>, Path(path): Path<String>) -> Response {
19 match state.assets().asset(&path) {
20 Some((bytes, content_type)) => (
21 [
22 (header::CONTENT_TYPE, content_type),
23 (header::CACHE_CONTROL, "public, max-age=3600"),
24 ],
25 bytes,
26 )
27 .into_response(),
28 None => StatusCode::NOT_FOUND.into_response(),
29 }
30}
31
32/// Serve a named theme stylesheet (`/theme/dark.css`).
33pub async fn theme_named(State(state): State<AppState>, Path(file): Path<String>) -> Response {
34 let name = file.strip_suffix(".css").unwrap_or(&file);
35 theme_response(&state, name)
36}
37
38/// Serve the instance default theme (`/theme.css`), used by self-contained error
39/// pages that do not know the visitor's chosen theme.
40pub async fn theme_default(State(state): State<AppState>) -> Response {
41 let name = state.config.ui.theme.clone();
42 theme_response(&state, &name)
43}
44
45/// Build a CSS response for theme `name`, or 404.
46fn theme_response(state: &AppState, name: &str) -> Response {
47 match state.assets().theme_css(name) {
48 Some(bytes) => (
49 [
50 (header::CONTENT_TYPE, "text/css; charset=utf-8"),
51 (header::CACHE_CONTROL, "public, max-age=3600"),
52 ],
53 bytes,
54 )
55 .into_response(),
56 None => StatusCode::NOT_FOUND.into_response(),
57 }
58}
59
60/// `/healthz` — liveness plus the git plumbing and database status.
61pub async fn healthz(State(state): State<AppState>) -> Response {
62 let git = git_version(&state.config.git.binary);
63 let db_ok = state.store.migrate().await.is_ok();
64 let healthy = git.is_some() && db_ok;
65 let body = serde_json::json!({
66 "status": if healthy { "ok" } else { "degraded" },
67 "git": git,
68 "git_binary": state.config.git.binary,
69 "database": if db_ok { "ok" } else { "error" },
70 });
71 let status = if healthy {
72 StatusCode::OK
73 } else {
74 StatusCode::SERVICE_UNAVAILABLE
75 };
76 (status, Json(body)).into_response()
77}
78
79/// `/version` — the instance name and build version.
80pub async fn version(State(state): State<AppState>) -> Json<serde_json::Value> {
81 Json(serde_json::json!({
82 "name": state.config.instance.name,
83 "version": env!("CARGO_PKG_VERSION"),
84 }))
85}
86
87/// Return the `git --version` string, or `None` if it cannot be run.
88fn git_version(binary: &str) -> Option<String> {
89 let output = Command::new(binary).arg("--version").output().ok()?;
90 output
91 .status
92 .success()
93 .then(|| String::from_utf8_lossy(&output.stdout).trim().to_string())
94}
crates/web/src/session.rs +136 −0
@@ -0,0 +1,136 @@
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Session cookies, viewer extraction, and CSRF.
6//!
7//! The session cookie carries an opaque 32-byte token; the database stores only
8//! its SHA-256, so lookup hashes the presented cookie and matches on the digest.
9//! CSRF uses the double-submit pattern: a non-`HttpOnly` `fabrica_csrf` cookie
10//! whose value must match an `X-CSRF-Token` header (injected into every htmx
11//! request by `hx-headers` on `<body>`) or a `_csrf` form field on non-GET routes.
12
13use axum::extract::FromRequestParts;
14use axum::http::HeaderMap;
15use axum::http::request::Parts;
16use axum::response::{IntoResponse, Redirect, Response};
17use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
18use model::User;
19
20use crate::AppState;
21use crate::error::AppError;
22
23/// The CSRF double-submit cookie name (non-`HttpOnly` by design).
24pub const CSRF_COOKIE: &str = "fabrica_csrf";
25/// The per-visitor theme cookie name.
26pub const THEME_COOKIE: &str = "fabrica_theme";
27
28/// The current viewer, or `None` when signed out. Never rejects.
29pub struct MaybeUser(pub Option<User>);
30
31impl FromRequestParts<AppState> for MaybeUser {
32 type Rejection = std::convert::Infallible;
33
34 async fn from_request_parts(
35 parts: &mut Parts,
36 state: &AppState,
37 ) -> Result<Self, Self::Rejection> {
38 let jar = CookieJar::from_headers(&parts.headers);
39 let Some(cookie) = jar.get(&state.config.auth.cookie_name) else {
40 return Ok(Self(None));
41 };
42 let session_id = auth::session_id(cookie.value());
43 let user = state
44 .store
45 .user_for_session(&session_id)
46 .await
47 .ok()
48 .flatten();
49 if user.is_some() {
50 // Best-effort last-seen bump; never fail the request over it.
51 let _ = state.store.touch_session(&session_id).await;
52 }
53 Ok(Self(user))
54 }
55}
56
57/// A signed-in viewer; unauthenticated requests are redirected to `/login`.
58pub struct RequireUser(pub User);
59
60impl FromRequestParts<AppState> for RequireUser {
61 type Rejection = Response;
62
63 async fn from_request_parts(
64 parts: &mut Parts,
65 state: &AppState,
66 ) -> Result<Self, Self::Rejection> {
67 let MaybeUser(user) = MaybeUser::from_request_parts(parts, state)
68 .await
69 .unwrap_or(MaybeUser(None));
70 match user {
71 Some(user) => Ok(Self(user)),
72 None => Err(Redirect::to("/login").into_response()),
73 }
74 }
75}
76
77/// Ensure the CSRF cookie exists, returning the (possibly updated) jar and the
78/// token to embed in forms and htmx headers. A stable token avoids invalidating
79/// forms opened in other tabs.
80pub fn ensure_csrf(jar: CookieJar, secure: bool) -> (CookieJar, String) {
81 if let Some(cookie) = jar.get(CSRF_COOKIE) {
82 return (jar.clone(), cookie.value().to_string());
83 }
84 let token = auth::new_secret();
85 let cookie = Cookie::build((CSRF_COOKIE, token.clone()))
86 .http_only(false)
87 .same_site(SameSite::Lax)
88 .secure(secure)
89 .path("/")
90 .build();
91 (jar.add(cookie), token)
92}
93
94/// Verify a non-GET request's CSRF token: the `fabrica_csrf` cookie must match the
95/// `X-CSRF-Token` header or the `form_token` (`_csrf` form field).
96///
97/// # Errors
98///
99/// Returns [`AppError::Forbidden`] if the tokens are missing or do not match.
100pub fn verify_csrf(
101 jar: &CookieJar,
102 headers: &HeaderMap,
103 form_token: Option<&str>,
104) -> Result<(), AppError> {
105 let cookie = jar.get(CSRF_COOKIE).map(|c| c.value().to_string());
106 let submitted = headers
107 .get("x-csrf-token")
108 .and_then(|v| v.to_str().ok())
109 .map(str::to_string)
110 .or_else(|| form_token.map(str::to_string));
111 match (cookie, submitted) {
112 (Some(a), Some(b)) if !a.is_empty() && a == b => Ok(()),
113 _ => Err(AppError::Forbidden),
114 }
115}
116
117/// Build the session cookie for a freshly minted token.
118#[must_use]
119pub fn session_cookie(name: &str, value: String, ttl_days: u32, secure: bool) -> Cookie<'static> {
120 Cookie::build((name.to_string(), value))
121 .http_only(true)
122 .same_site(SameSite::Lax)
123 .secure(secure)
124 .path("/")
125 .max_age(time::Duration::days(i64::from(ttl_days)))
126 .build()
127}
128
129/// Build a removal cookie for logout (empty value, immediate expiry).
130#[must_use]
131pub fn clear_cookie(name: &str) -> Cookie<'static> {
132 Cookie::build((name.to_string(), String::new()))
133 .path("/")
134 .max_age(time::Duration::ZERO)
135 .build()
136}
crates/web/src/tests.rs +238 −0
@@ -0,0 +1,238 @@
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Handler tests via `tower::ServiceExt::oneshot` — no network, no external
6//! services. They assert the shell renders, static assets and themes serve,
7//! CSRF is enforced on state-changing routes, and sign-in opens a session.
8
9#![allow(clippy::unwrap_used, clippy::expect_used)]
10
11use std::sync::Arc;
12
13use axum::Router;
14use axum::body::Body;
15use axum::http::{Request, StatusCode, header};
16use config::Config;
17use store::{NewUser, Store};
18use tower::ServiceExt as _;
19
20use crate::AppState;
21
22/// Build an app over an in-memory store with one admin-less user `ada` whose
23/// password is `secret12`.
24async fn app() -> (AppState, Router) {
25 let store = Store::connect("sqlite::memory:", 1).await.unwrap();
26 store.migrate().await.unwrap();
27
28 let hash = auth::hash_password("secret12", auth::HashParams::default()).unwrap();
29 store
30 .create_user(NewUser {
31 username: "ada".to_string(),
32 email: "ada@example.com".to_string(),
33 display_name: Some("Ada".to_string()),
34 password_hash: Some(hash),
35 is_admin: false,
36 must_change_password: false,
37 })
38 .await
39 .unwrap();
40
41 let mut config = Config::default();
42 config.instance.name = "Forge".to_string();
43 // Not HTTPS in tests, so don't demand Secure cookies.
44 config.auth.cookie_secure = false;
45
46 let state = AppState::build(Arc::new(config), store, "test-secret".to_string()).unwrap();
47 let router = crate::build_router(state.clone());
48 (state, router)
49}
50
51async fn body_string(response: axum::response::Response) -> String {
52 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
53 .await
54 .unwrap();
55 String::from_utf8_lossy(&bytes).into_owned()
56}
57
58fn get(uri: &str) -> Request<Body> {
59 Request::builder().uri(uri).body(Body::empty()).unwrap()
60}
61
62#[tokio::test]
63async fn home_renders_the_shell() {
64 let (_state, app) = app().await;
65 let res = app.oneshot(get("/")).await.unwrap();
66 assert_eq!(res.status(), StatusCode::OK);
67 let html = body_string(res).await;
68 assert!(html.contains("<!DOCTYPE html>"));
69 assert!(html.contains("Forge"), "instance name should appear");
70 assert!(html.contains("/assets/base.css"));
71 assert!(html.contains("/assets/htmx.min.js"));
72}
73
74#[tokio::test]
75async fn assets_and_themes_serve() {
76 let (_state, app) = app().await;
77
78 let css = app.clone().oneshot(get("/assets/base.css")).await.unwrap();
79 assert_eq!(css.status(), StatusCode::OK);
80 assert_eq!(
81 css.headers().get(header::CONTENT_TYPE).unwrap(),
82 "text/css; charset=utf-8"
83 );
84
85 let theme = app.clone().oneshot(get("/theme/dark.css")).await.unwrap();
86 assert_eq!(theme.status(), StatusCode::OK);
87 let body = body_string(theme).await;
88 assert!(body.contains("--fb-bg"));
89
90 let default = app.clone().oneshot(get("/theme.css")).await.unwrap();
91 assert_eq!(default.status(), StatusCode::OK);
92
93 let traversal = app.oneshot(get("/assets/../Cargo.toml")).await.unwrap();
94 assert_ne!(traversal.status(), StatusCode::OK);
95}
96
97#[tokio::test]
98async fn healthz_and_version_report() {
99 let (_state, app) = app().await;
100 let health = app.clone().oneshot(get("/healthz")).await.unwrap();
101 // git may or may not be present in the test env; either way it is valid JSON.
102 let body = body_string(health).await;
103 assert!(body.contains("\"database\":\"ok\""));
104
105 let version = app.oneshot(get("/version")).await.unwrap();
106 assert_eq!(version.status(), StatusCode::OK);
107 assert!(body_string(version).await.contains("\"name\":\"Forge\""));
108}
109
110#[tokio::test]
111async fn login_form_renders_with_a_csrf_token() {
112 let (_state, app) = app().await;
113 let res = app.oneshot(get("/login")).await.unwrap();
114 assert_eq!(res.status(), StatusCode::OK);
115 // The CSRF cookie is set, and its token is embedded in the form.
116 let set_cookie = res
117 .headers()
118 .get(header::SET_COOKIE)
119 .map(|v| v.to_str().unwrap().to_string())
120 .unwrap_or_default();
121 assert!(
122 set_cookie.contains("fabrica_csrf="),
123 "csrf cookie: {set_cookie:?}"
124 );
125 let html = body_string(res).await;
126 assert!(html.contains("name=\"_csrf\""));
127}
128
129#[tokio::test]
130async fn post_without_csrf_is_forbidden() {
131 let (_state, app) = app().await;
132 let req = Request::builder()
133 .method("POST")
134 .uri("/login")
135 .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
136 .body(Body::from("username=ada&password=secret12&_csrf=nope"))
137 .unwrap();
138 let res = app.oneshot(req).await.unwrap();
139 assert_eq!(res.status(), StatusCode::FORBIDDEN);
140}
141
142#[tokio::test]
143async fn login_with_matching_csrf_opens_a_session() {
144 let (_state, app) = app().await;
145
146 // First GET /login to obtain a CSRF cookie + token.
147 let form = app.clone().oneshot(get("/login")).await.unwrap();
148 let cookie = form
149 .headers()
150 .get(header::SET_COOKIE)
151 .unwrap()
152 .to_str()
153 .unwrap()
154 .to_string();
155 let token = cookie
156 .split("fabrica_csrf=")
157 .nth(1)
158 .and_then(|s| s.split(';').next())
159 .unwrap()
160 .to_string();
161
162 // POST with the cookie echoed and the token in the body → double-submit passes.
163 let req = Request::builder()
164 .method("POST")
165 .uri("/login")
166 .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
167 .header(header::COOKIE, format!("fabrica_csrf={token}"))
168 .body(Body::from(format!(
169 "username=ada&password=secret12&_csrf={token}"
170 )))
171 .unwrap();
172 let res = app.oneshot(req).await.unwrap();
173 assert_eq!(res.status(), StatusCode::SEE_OTHER, "redirect on success");
174 let set = res
175 .headers()
176 .get_all(header::SET_COOKIE)
177 .iter()
178 .map(|v| v.to_str().unwrap().to_string())
179 .collect::<Vec<_>>()
180 .join("\n");
181 assert!(
182 set.contains("fabrica_session="),
183 "session cookie set: {set:?}"
184 );
185}
186
187#[tokio::test]
188async fn bad_password_re_renders_unauthorized() {
189 let (_state, app) = app().await;
190 let form = app.clone().oneshot(get("/login")).await.unwrap();
191 let cookie = form
192 .headers()
193 .get(header::SET_COOKIE)
194 .unwrap()
195 .to_str()
196 .unwrap()
197 .to_string();
198 let token = cookie
199 .split("fabrica_csrf=")
200 .nth(1)
201 .and_then(|s| s.split(';').next())
202 .unwrap()
203 .to_string();
204
205 let req = Request::builder()
206 .method("POST")
207 .uri("/login")
208 .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
209 .header(header::COOKIE, format!("fabrica_csrf={token}"))
210 .body(Body::from(format!(
211 "username=ada&password=wrong&_csrf={token}"
212 )))
213 .unwrap();
214 let res = app.oneshot(req).await.unwrap();
215 assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
216}
217
218#[tokio::test]
219async fn invite_with_unknown_token_is_not_found() {
220 let (_state, app) = app().await;
221 let res = app.oneshot(get("/invite/does-not-exist")).await.unwrap();
222 assert_eq!(res.status(), StatusCode::NOT_FOUND);
223}
224
225#[tokio::test]
226async fn settings_redirects_when_signed_out() {
227 let (_state, app) = app().await;
228 let res = app.oneshot(get("/settings")).await.unwrap();
229 assert_eq!(res.status(), StatusCode::SEE_OTHER);
230 assert_eq!(res.headers().get(header::LOCATION).unwrap(), "/login");
231}
232
233#[tokio::test]
234async fn unknown_theme_is_rejected() {
235 let (_state, app) = app().await;
236 let res = app.oneshot(get("/settings/theme?name=nope")).await.unwrap();
237 assert_eq!(res.status(), StatusCode::BAD_REQUEST);
238}
docs/decisions.md +37 −0
@@ -410,3 +410,40 @@ dependency and keeps `ring` out of the graph. Backends are `smtp` (native-TLS
410`none` paths so `cargo test` needs no SMTP server. A **SHOULD** deviation logged410`none` paths so `cargo test` needs no SMTP server. A **SHOULD** deviation logged
411here. The invite token reuses `auth::new_session_token`'s shape (32 bytes,411here. The invite token reuses `auth::new_session_token`'s shape (32 bytes,
412base64url value emailed, SHA-256 stored).412base64url value emailed, SHA-256 stored).
413
414## 2026-07-25 — `serve` wired in the binary; `cli` never depends on `web`
415
416**Decision:** `fabrica serve` orchestration (load config → open store → build web
417state → run) lives in the root binary (`src/serve.rs`). `cli::run` takes a serve
418callback and hands back a `cli::ServeRequest`; the binary supplies the callback.
419`cli` exposes `resolve_secret` for the binary to reuse.
420
421**Alternatives:** Let `cli` depend on `web` and run the server directly.
422
423**Rationale:** The architecture rule is absolute — **no crate may depend on
424`web`** — and `serve` must start `web` (and later `ssh`/`api`). The only place
425those top-level crates can be tied together is the binary, which already depends on
426all of them. The callback keeps `cli` (the command tree) free of `web` while
427`main.rs` stays a thin wiring layer. `--detach` is accepted but not yet
428implemented (foreground is correct for systemd/Docker); deferred to deployment.
429
430## 2026-07-25 — Web stack: axum 0.8, plain cookies, no global timeout
431
432**Decision:** The web crate uses axum 0.8 + axum-extra cookies + maud + tower-http,
433with **no TLS/rustls feature anywhere** (TLS terminates at a reverse proxy), so
434`ring` stays out of the graph. Session and CSRF use **plain (unsigned) cookies**:
435the session cookie is an opaque 32-byte token validated by SHA-256 lookup in the
436`sessions` table; CSRF is double-submit (a non-`HttpOnly` `fabrica_csrf` cookie
437matched against the `X-CSRF-Token` header htmx injects, or a `_csrf` form field).
438There is **no global request timeout** layer.
439
440**Alternatives:** `SignedCookieJar` (needs a `Key` + `FromRef`); tower-cookies; a
441global `TimeoutLayer`.
442
443**Rationale:** The session token is already unguessable and DB-validated, so cookie
444signing adds machinery without materially improving security; double-submit CSRF
445needs a JS-readable cookie regardless. A global timeout is actively **wrong** for
446this app: pack-transport routes (§3.3) stream arbitrarily long clones and must
447never be cut off, so timeouts (if any) belong per-route on non-git paths, added in
448the polish phase. The theme picker is a real GET form (works without JS) that sets
449a `fabrica_theme` cookie; `SIGHUP` re-scans `themes_dir` via an `RwLock<Assets>`.
flake.nix +6 −4
@@ -34,15 +34,17 @@
3434
35 craneLib = (inputs.crane.mkLib pkgs).overrideToolchain fenixToolchain;35 craneLib = (inputs.crane.mkLib pkgs).overrideToolchain fenixToolchain;
3636
37 # Keep `.sql` migration files (embedded by `store` via `sqlx::migrate!`)37 # Keep files crane's default cargo-source filter would strip but the build
38 # and `.snap` insta snapshots (read by `highlight`'s snapshot tests) in38 # needs: `.sql` migrations (embedded by `store` via `sqlx::migrate!`),
39 # the build source: crane's default cargo-source filter would strip both.39 # `.snap` insta snapshots (read by `highlight`), and the web `assets/`
40 # (css/js/svg/… embedded by `web` via `rust-embed` at compile time).
40 src = pkgs.lib.cleanSourceWith {41 src = pkgs.lib.cleanSourceWith {
41 src = ./.;42 src = ./.;
42 name = "source";43 name = "source";
43 filter =44 filter =
44 path: type:45 path: type:
45 (builtins.match ".*\\.(sql|snap)$" path != null) || (craneLib.filterCargoSources path type);46 (builtins.match ".*\\.(sql|snap|css|js|svg|ico|png|woff2)$" path != null)
47 || (craneLib.filterCargoSources path type);
46 };48 };
4749
48 commonArgs = {50 commonArgs = {
src/main.rs +6 −3
@@ -4,11 +4,14 @@
44
5//! `fabrica` — a self-hosted git server.5//! `fabrica` — a self-hosted git server.
6//!6//!
7//! The binary is deliberately thin: it parses arguments and dispatches into the7//! The binary parses arguments through [`cli`] and dispatches. The one thing it
8//! [`cli`] crate, and nothing else lives here.8//! does beyond that is wire the servers together for `serve` (see [`serve`]), so
9//! that no library crate has to depend on `web`.
10
11mod serve;
912
10use std::process::ExitCode;13use std::process::ExitCode;
1114
12fn main() -> ExitCode {15fn main() -> ExitCode {
13 cli::run()16 cli::run(serve::run)
14}17}
src/serve.rs +61 −0
@@ -0,0 +1,61 @@
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! The `fabrica serve` wiring.
6//!
7//! This is the one place the top-level server crates are tied together — kept in
8//! the binary so that no library crate depends on `web` (or, later, `ssh`/`api`).
9//! `cli` parses the command and hands us a [`cli::ServeRequest`]; we load config,
10//! open the store, and run the web server.
11
12use std::net::SocketAddr;
13use std::process::ExitCode;
14use std::sync::Arc;
15
16use cli::ServeRequest;
17
18/// Handle `fabrica serve`.
19///
20/// # Errors
21///
22/// Returns an error if configuration is invalid, the store cannot be opened, the
23/// bind address cannot be parsed, or the server fails to run.
24pub fn run(req: ServeRequest) -> anyhow::Result<ExitCode> {
25 let runtime = tokio::runtime::Builder::new_multi_thread()
26 .enable_all()
27 .build()?;
28 runtime.block_on(async move {
29 if req.detach {
30 anyhow::bail!(
31 "--detach is not yet implemented; run in the foreground \
32 (systemd and Docker manage the process lifecycle)"
33 );
34 }
35
36 let loaded = config::load(req.config_path.as_deref())?;
37 for warning in &loaded.warnings {
38 eprintln!("warning: {warning}");
39 }
40
41 let store = store::Store::connect(
42 &loaded.config.database.url,
43 loaded.config.database.max_connections,
44 )
45 .await?;
46 if !req.no_migrate {
47 store.migrate().await?;
48 }
49
50 let secret = cli::resolve_secret(&loaded.config)?;
51 let addr: SocketAddr = format!(
52 "{}:{}",
53 loaded.config.server.address, loaded.config.server.port
54 )
55 .parse()?;
56
57 let state = web::AppState::build(Arc::new(loaded.config), store, secret)?;
58 web::serve(state, addr).await?;
59 Ok(ExitCode::SUCCESS)
60 })
61}