forge
Explore
Log in

Don't you dare go Hollow

OIDC single sign-on — provider, client crate, izlek migration

Browse files at this commit

d7200e03b621e0e4831954d02e37ee4fe35761cbAhmet Kaan GümüşParent: 174f7c2
  • feat
    • OIDC single sign-on — provider, client crate, izlek migration
Show full message
feat: OIDC single sign-on — provider, client crate, izlek migration

- im-core: turso store (users, invites, sessions, OIDC clients, auth codes,
  refresh tokens, signing keys), argon2 passwords ported from izlek-core,
  RFC 6238 TOTP (hmac 0.13 + sha1 0.11), hand-rolled RS256 JWT over rsa 0.9,
  XChaCha20-Poly1305 sealing under im.key
- im-web: topcoat server — login / TOTP / invite / enroll pages in İzlek's
  instrument skin (style/main.scss, grass build.rs), OIDC authorize + token +
  userinfo + JWKS + discovery, CLI: invite, create-client
- im-client: drop-in OIDC client for topcoat apps — PKCE S256, JWKS-validated
  id_tokens, transparent refresh rotation, encrypted session cookie, demo
  example app
- im-migrate: one-time izlek.db import, argon2 hashes verbatim, mapping CSV

Verified live in a browser: invite -> password -> TOTP enrolment (QR) ->
demo app OIDC handshake (silent via central session) and a full interactive
password+TOTP login landing on the app's protected page with claims.
.gitignoreadded+8 -0
@@ -0,0 +1,8 @@
1+/target
2+/im.db
3+/im.db-shm
4+/im.db-wal
5+/im.key
6+/im-migrate-mapping.csv
7+/public/*
8+!/public/.gitkeep
Cargo.lockadded+5330 -0

Diff too large; view file

@@ -0,0 +1,5330 @@
1+# This file is automatically @generated by Cargo.
2+# It is not intended for manual editing.
3+version = 4
4+
5+[[package]]
6+name = "adler2"
7+version = "2.0.1"
8+source = "registry+https://github.com/rust-lang/crates.io-index"
9+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
10+
11+[[package]]
12+name = "aead"
13+version = "0.5.2"
14+source = "registry+https://github.com/rust-lang/crates.io-index"
15+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
16+dependencies = [
17+ "crypto-common 0.1.7",
18+ "generic-array",
19+]
20+
21+[[package]]
22+name = "aegis"
23+version = "0.9.15"
24+source = "registry+https://github.com/rust-lang/crates.io-index"
25+checksum = "58541132f980da31e9aa99f7bdee69bc84bf1e168b9b91ef2dbe8abb7b4ce5dd"
26+dependencies = [
27+ "cc",
28+ "softaes",
29+]
30+
31+[[package]]
32+name = "aes"
33+version = "0.8.4"
34+source = "registry+https://github.com/rust-lang/crates.io-index"
35+checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
36+dependencies = [
37+ "cfg-if",
38+ "cipher",
39+ "cpufeatures 0.2.17",
40+]
41+
42+[[package]]
43+name = "aes-gcm"
44+version = "0.10.3"
45+source = "registry+https://github.com/rust-lang/crates.io-index"
46+checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
47+dependencies = [
48+ "aead",
49+ "aes",
50+ "cipher",
51+ "ctr",
52+ "ghash",
53+ "subtle",
54+]
55+
56+[[package]]
57+name = "ahash"
58+version = "0.8.12"
59+source = "registry+https://github.com/rust-lang/crates.io-index"
60+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
61+dependencies = [
62+ "cfg-if",
63+ "once_cell",
64+ "version_check",
65+ "zerocopy",
66+]
67+
68+[[package]]
69+name = "aho-corasick"
70+version = "1.1.5"
71+source = "registry+https://github.com/rust-lang/crates.io-index"
72+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
73+dependencies = [
74+ "memchr",
75+]
76+
77+[[package]]
78+name = "alloc-no-stdlib"
79+version = "2.0.4"
80+source = "registry+https://github.com/rust-lang/crates.io-index"
81+checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
82+
83+[[package]]
84+name = "alloc-stdlib"
85+version = "0.2.4"
86+source = "registry+https://github.com/rust-lang/crates.io-index"
87+checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
88+dependencies = [
89+ "alloc-no-stdlib",
90+]
91+
92+[[package]]
93+name = "allocator-api2"
94+version = "0.2.21"
95+source = "registry+https://github.com/rust-lang/crates.io-index"
96+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
97+
98+[[package]]
99+name = "allocator-api2"
100+version = "0.4.0"
101+source = "registry+https://github.com/rust-lang/crates.io-index"
102+checksum = "c880a97d28a3681c0267bd29cff89621202715b065127cd445fa0f0fe0aa2880"
103+
104+[[package]]
105+name = "android_system_properties"
106+version = "0.1.6"
107+source = "registry+https://github.com/rust-lang/crates.io-index"
108+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
109+dependencies = [
110+ "libc",
111+]
112+
113+[[package]]
114+name = "anstream"
115+version = "1.0.0"
116+source = "registry+https://github.com/rust-lang/crates.io-index"
117+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
118+dependencies = [
119+ "anstyle",
120+ "anstyle-parse",
121+ "anstyle-query",
122+ "anstyle-wincon",
123+ "colorchoice",
124+ "is_terminal_polyfill",
125+ "utf8parse",
126+]
127+
128+[[package]]
129+name = "anstyle"
130+version = "1.0.14"
131+source = "registry+https://github.com/rust-lang/crates.io-index"
132+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
133+
134+[[package]]
135+name = "anstyle-parse"
136+version = "1.0.0"
137+source = "registry+https://github.com/rust-lang/crates.io-index"
138+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
139+dependencies = [
140+ "utf8parse",
141+]
142+
143+[[package]]
144+name = "anstyle-query"
145+version = "1.1.5"
146+source = "registry+https://github.com/rust-lang/crates.io-index"
147+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
148+dependencies = [
149+ "windows-sys 0.61.2",
150+]
151+
152+[[package]]
153+name = "anstyle-wincon"
154+version = "3.0.11"
155+source = "registry+https://github.com/rust-lang/crates.io-index"
156+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
157+dependencies = [
158+ "anstyle",
159+ "once_cell_polyfill",
160+ "windows-sys 0.61.2",
161+]
162+
163+[[package]]
164+name = "antithesis_sdk"
165+version = "0.2.9"
166+source = "registry+https://github.com/rust-lang/crates.io-index"
167+checksum = "08410fcac93669a476c006cd6c4512ac1e2b30fd117231a5d55d8a2c76599b82"
168+dependencies = [
169+ "libc",
170+ "libloading",
171+ "linkme",
172+ "once_cell",
173+ "rand 0.8.8",
174+ "rustc_version_runtime",
175+ "serde",
176+ "serde_json",
177+]
178+
179+[[package]]
180+name = "anyhow"
181+version = "1.0.104"
182+source = "registry+https://github.com/rust-lang/crates.io-index"
183+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
184+
185+[[package]]
186+name = "anymap3"
187+version = "1.1.0"
188+source = "registry+https://github.com/rust-lang/crates.io-index"
189+checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9"
190+
191+[[package]]
192+name = "arc-swap"
193+version = "1.9.2"
194+source = "registry+https://github.com/rust-lang/crates.io-index"
195+checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b"
196+dependencies = [
197+ "rustversion",
198+]
199+
200+[[package]]
201+name = "argon2"
202+version = "0.6.0"
203+source = "registry+https://github.com/rust-lang/crates.io-index"
204+checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c"
205+dependencies = [
206+ "base64ct",
207+ "blake2",
208+ "cpufeatures 0.3.1",
209+ "password-hash",
210+]
211+
212+[[package]]
213+name = "aristo"
214+version = "0.4.1"
215+source = "registry+https://github.com/rust-lang/crates.io-index"
216+checksum = "fcdeefa800110050103e2459a2f8dbdbd560ad046e30f1f87e24ce19c2cb8bde"
217+dependencies = [
218+ "aristo-macros",
219+]
220+
221+[[package]]
222+name = "aristo-macros"
223+version = "0.4.1"
224+source = "registry+https://github.com/rust-lang/crates.io-index"
225+checksum = "d64a66d21a80182b35b1741997a6d2456911f54b7eb1918aa4e2382fc205268d"
226+dependencies = [
227+ "proc-macro2",
228+ "quote",
229+ "syn 2.0.119",
230+]
231+
232+[[package]]
233+name = "assoc"
234+version = "0.1.3"
235+source = "registry+https://github.com/rust-lang/crates.io-index"
236+checksum = "bfdc70193dadb9d7287fa4b633f15f90c876915b31f6af17da307fc59c9859a8"
237+
238+[[package]]
239+name = "async-compression"
240+version = "0.4.44"
241+source = "registry+https://github.com/rust-lang/crates.io-index"
242+checksum = "515a1f282e33d55983c499d7e9e87082e81cbc32974825bf9032f928392d5844"
243+dependencies = [
244+ "compression-codecs",
245+ "compression-core",
246+ "pin-project-lite",
247+ "tokio",
248+]
249+
250+[[package]]
251+name = "async-trait"
252+version = "0.1.92"
253+source = "registry+https://github.com/rust-lang/crates.io-index"
254+checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
255+dependencies = [
256+ "proc-macro2",
257+ "quote",
258+ "syn 3.0.4",
259+]
260+
261+[[package]]
262+name = "atomic-waker"
263+version = "1.1.2"
264+source = "registry+https://github.com/rust-lang/crates.io-index"
265+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
266+
267+[[package]]
268+name = "autocfg"
269+version = "1.5.1"
270+source = "registry+https://github.com/rust-lang/crates.io-index"
271+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
272+
273+[[package]]
274+name = "aws-lc-rs"
275+version = "1.18.1"
276+source = "registry+https://github.com/rust-lang/crates.io-index"
277+checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e"
278+dependencies = [
279+ "aws-lc-sys",
280+ "zeroize",
281+]
282+
283+[[package]]
284+name = "aws-lc-sys"
285+version = "0.45.0"
286+source = "registry+https://github.com/rust-lang/crates.io-index"
287+checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27"
288+dependencies = [
289+ "cc",
290+ "cmake",
291+ "dunce",
292+ "fs_extra",
293+ "pkg-config",
294+]
295+
296+[[package]]
297+name = "base64"
298+version = "0.22.1"
299+source = "registry+https://github.com/rust-lang/crates.io-index"
300+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
301+
302+[[package]]
303+name = "base64"
304+version = "0.23.1"
305+source = "registry+https://github.com/rust-lang/crates.io-index"
306+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
307+
308+[[package]]
309+name = "base64ct"
310+version = "1.8.3"
311+source = "registry+https://github.com/rust-lang/crates.io-index"
312+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
313+
314+[[package]]
315+name = "bigdecimal"
316+version = "0.4.10"
317+source = "registry+https://github.com/rust-lang/crates.io-index"
318+checksum = "4d6867f1565b3aad85681f1015055b087fcfd840d6aeee6eee7f2da317603695"
319+dependencies = [
320+ "autocfg",
321+ "libm",
322+ "num-bigint",
323+ "num-integer",
324+ "num-traits",
325+]
326+
327+[[package]]
328+name = "bindgen"
329+version = "0.69.5"
330+source = "registry+https://github.com/rust-lang/crates.io-index"
331+checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088"
332+dependencies = [
333+ "bitflags",
334+ "cexpr",
335+ "clang-sys",
336+ "itertools 0.12.1",
337+ "lazy_static",
338+ "lazycell",
339+ "log",
340+ "prettyplease 0.2.37",
341+ "proc-macro2",
342+ "quote",
343+ "regex",
344+ "rustc-hash 1.1.0",
345+ "shlex 1.3.0",
346+ "syn 2.0.119",
347+ "which",
348+]
349+
350+[[package]]
351+name = "bitflags"
352+version = "2.13.1"
353+source = "registry+https://github.com/rust-lang/crates.io-index"
354+checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
355+
356+[[package]]
357+name = "bitpacking"
358+version = "0.9.3"
359+source = "registry+https://github.com/rust-lang/crates.io-index"
360+checksum = "96a7139abd3d9cebf8cd6f920a389cf3dc9576172e32f4563f188cae3c3eb019"
361+dependencies = [
362+ "crunchy",
363+]
364+
365+[[package]]
366+name = "bitvec"
367+version = "1.1.1"
368+source = "registry+https://github.com/rust-lang/crates.io-index"
369+checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837"
370+dependencies = [
371+ "funty",
372+ "radium",
373+ "tap",
374+ "wyz",
375+]
376+
377+[[package]]
378+name = "blake2"
379+version = "0.11.0"
380+source = "registry+https://github.com/rust-lang/crates.io-index"
381+checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f"
382+dependencies = [
383+ "digest 0.11.3",
384+]
385+
386+[[package]]
387+name = "block-buffer"
388+version = "0.10.4"
389+source = "registry+https://github.com/rust-lang/crates.io-index"
390+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
391+dependencies = [
392+ "generic-array",
393+]
394+
395+[[package]]
396+name = "block-buffer"
397+version = "0.12.1"
398+source = "registry+https://github.com/rust-lang/crates.io-index"
399+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
400+dependencies = [
401+ "hybrid-array",
402+]
403+
404+[[package]]
405+name = "bon"
406+version = "3.10.0"
407+source = "registry+https://github.com/rust-lang/crates.io-index"
408+checksum = "9e3fac94a66da67200398458a25412bcc3f9b6443b5119a6cad9cf3ccfcd8cc6"
409+dependencies = [
410+ "bon-macros",
411+]
412+
413+[[package]]
414+name = "bon-macros"
415+version = "3.10.0"
416+source = "registry+https://github.com/rust-lang/crates.io-index"
417+checksum = "d4654961ad0494e4774c5c60b4cb4cd0ae9b9d92d039d901638b1dba97ebebf5"
418+dependencies = [
419+ "darling",
420+ "ident_case",
421+ "prettyplease 0.3.0",
422+ "proc-macro2",
423+ "quote",
424+ "syn 3.0.4",
425+]
426+
427+[[package]]
428+name = "branches"
429+version = "0.4.6"
430+source = "registry+https://github.com/rust-lang/crates.io-index"
431+checksum = "7436b21fd6195415058eb41c9090e156b556bc7e0377bb57c5c026a421521525"
432+dependencies = [
433+ "rustc_version",
434+]
435+
436+[[package]]
437+name = "brotli"
438+version = "8.0.4"
439+source = "registry+https://github.com/rust-lang/crates.io-index"
440+checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
441+dependencies = [
442+ "alloc-no-stdlib",
443+ "alloc-stdlib",
444+ "brotli-decompressor",
445+]
446+
447+[[package]]
448+name = "brotli-decompressor"
449+version = "5.0.3"
450+source = "registry+https://github.com/rust-lang/crates.io-index"
451+checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
452+dependencies = [
453+ "alloc-no-stdlib",
454+ "alloc-stdlib",
455+]
456+
457+[[package]]
458+name = "bumpalo"
459+version = "3.20.3"
460+source = "registry+https://github.com/rust-lang/crates.io-index"
461+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
462+
463+[[package]]
464+name = "bytemuck"
465+version = "1.25.2"
466+source = "registry+https://github.com/rust-lang/crates.io-index"
467+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
468+dependencies = [
469+ "bytemuck_derive",
470+]
471+
472+[[package]]
473+name = "bytemuck_derive"
474+version = "1.12.0"
475+source = "registry+https://github.com/rust-lang/crates.io-index"
476+checksum = "fc0e56a716f1e132ff6bf4bdac1c944a3fcdc1cae65f70a4a2a1ac3b401d2d1f"
477+dependencies = [
478+ "proc-macro2",
479+ "quote",
480+ "syn 3.0.4",
481+]
482+
483+[[package]]
484+name = "byteorder"
485+version = "1.5.0"
486+source = "registry+https://github.com/rust-lang/crates.io-index"
487+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
488+
489+[[package]]
490+name = "bytes"
491+version = "1.12.1"
492+source = "registry+https://github.com/rust-lang/crates.io-index"
493+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
494+
495+[[package]]
496+name = "cc"
497+version = "1.4.4"
498+source = "registry+https://github.com/rust-lang/crates.io-index"
499+checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273"
500+dependencies = [
501+ "find-msvc-tools",
502+ "jobserver",
503+ "libc",
504+ "shlex 2.0.1",
505+]
506+
507+[[package]]
508+name = "census"
509+version = "0.4.2"
510+source = "registry+https://github.com/rust-lang/crates.io-index"
511+checksum = "4f4c707c6a209cbe82d10abd08e1ea8995e9ea937d2550646e02798948992be0"
512+
513+[[package]]
514+name = "cexpr"
515+version = "0.6.0"
516+source = "registry+https://github.com/rust-lang/crates.io-index"
517+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
518+dependencies = [
519+ "nom 7.1.3",
520+]
521+
522+[[package]]
523+name = "cfg-if"
524+version = "1.0.4"
525+source = "registry+https://github.com/rust-lang/crates.io-index"
526+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
527+
528+[[package]]
529+name = "cfg_aliases"
530+version = "0.2.2"
531+source = "registry+https://github.com/rust-lang/crates.io-index"
532+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
533+
534+[[package]]
535+name = "cfg_block"
536+version = "0.1.1"
537+source = "registry+https://github.com/rust-lang/crates.io-index"
538+checksum = "18758054972164c3264f7c8386f5fc6da6114cb46b619fd365d4e3b2dc3ae487"
539+
540+[[package]]
541+name = "chacha20"
542+version = "0.9.1"
543+source = "registry+https://github.com/rust-lang/crates.io-index"
544+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
545+dependencies = [
546+ "cfg-if",
547+ "cipher",
548+ "cpufeatures 0.2.17",
549+]
550+
551+[[package]]
552+name = "chacha20"
553+version = "0.10.2"
554+source = "registry+https://github.com/rust-lang/crates.io-index"
555+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
556+dependencies = [
557+ "cfg-if",
558+ "cpufeatures 0.3.1",
559+ "rand_core 0.10.1",
560+]
561+
562+[[package]]
563+name = "chacha20poly1305"
564+version = "0.10.1"
565+source = "registry+https://github.com/rust-lang/crates.io-index"
566+checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
567+dependencies = [
568+ "aead",
569+ "chacha20 0.9.1",
570+ "cipher",
571+ "poly1305",
572+ "zeroize",
573+]
574+
575+[[package]]
576+name = "chrono"
577+version = "0.4.45"
578+source = "registry+https://github.com/rust-lang/crates.io-index"
579+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
580+dependencies = [
581+ "iana-time-zone",
582+ "js-sys",
583+ "num-traits",
584+ "wasm-bindgen",
585+ "windows-link",
586+]
587+
588+[[package]]
589+name = "cipher"
590+version = "0.4.4"
591+source = "registry+https://github.com/rust-lang/crates.io-index"
592+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
593+dependencies = [
594+ "crypto-common 0.1.7",
595+ "inout",
596+ "zeroize",
597+]
598+
599+[[package]]
600+name = "clang-sys"
601+version = "1.9.1"
602+source = "registry+https://github.com/rust-lang/crates.io-index"
603+checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
604+dependencies = [
605+ "glob",
606+ "libc",
607+ "libloading",
608+]
609+
610+[[package]]
611+name = "clap"
612+version = "4.6.6"
613+source = "registry+https://github.com/rust-lang/crates.io-index"
614+checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca"
615+dependencies = [
616+ "clap_builder",
617+]
618+
619+[[package]]
620+name = "clap_builder"
621+version = "4.6.6"
622+source = "registry+https://github.com/rust-lang/crates.io-index"
623+checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889"
624+dependencies = [
625+ "anstream",
626+ "anstyle",
627+ "clap_lex",
628+ "strsim",
629+]
630+
631+[[package]]
632+name = "clap_lex"
633+version = "1.1.0"
634+source = "registry+https://github.com/rust-lang/crates.io-index"
635+checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
636+
637+[[package]]
638+name = "cmake"
639+version = "0.1.58"
640+source = "registry+https://github.com/rust-lang/crates.io-index"
641+checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"
642+dependencies = [
643+ "cc",
644+]
645+
646+[[package]]
647+name = "cmov"
648+version = "0.5.4"
649+source = "registry+https://github.com/rust-lang/crates.io-index"
650+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
651+
652+[[package]]
653+name = "codemap"
654+version = "0.1.3"
655+source = "registry+https://github.com/rust-lang/crates.io-index"
656+checksum = "b9e769b5c8c8283982a987c6e948e540254f1058d5a74b8794914d4ef5fc2a24"
657+
658+[[package]]
659+name = "colorchoice"
660+version = "1.0.5"
661+source = "registry+https://github.com/rust-lang/crates.io-index"
662+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
663+
664+[[package]]
665+name = "combine"
666+version = "4.6.8"
667+source = "registry+https://github.com/rust-lang/crates.io-index"
668+checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e"
669+dependencies = [
670+ "bytes",
671+ "memchr",
672+]
673+
674+[[package]]
675+name = "compression-codecs"
676+version = "0.4.39"
677+source = "registry+https://github.com/rust-lang/crates.io-index"
678+checksum = "2fe67f2944eef52fc7b106b8c9450d243a88701a0c065f7f57235e76abaed7df"
679+dependencies = [
680+ "brotli",
681+ "compression-core",
682+ "flate2",
683+ "memchr",
684+]
685+
686+[[package]]
687+name = "compression-core"
688+version = "0.4.33"
689+source = "registry+https://github.com/rust-lang/crates.io-index"
690+checksum = "6e8ccc4ea9f6acc32d102c0f6d471d11d913ad15f20c04de743374861fa1d414"
691+
692+[[package]]
693+name = "concurrent-queue"
694+version = "2.5.0"
695+source = "registry+https://github.com/rust-lang/crates.io-index"
696+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
697+dependencies = [
698+ "crossbeam-utils",
699+]
700+
701+[[package]]
702+name = "const-oid"
703+version = "0.9.6"
704+source = "registry+https://github.com/rust-lang/crates.io-index"
705+checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
706+
707+[[package]]
708+name = "const-oid"
709+version = "0.10.2"
710+source = "registry+https://github.com/rust-lang/crates.io-index"
711+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
712+
713+[[package]]
714+name = "cookie"
715+version = "0.18.2"
716+source = "registry+https://github.com/rust-lang/crates.io-index"
717+checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"
718+dependencies = [
719+ "aes-gcm",
720+ "base64 0.22.1",
721+ "hkdf",
722+ "hmac 0.12.1",
723+ "percent-encoding",
724+ "rand 0.8.8",
725+ "sha2 0.10.9",
726+ "subtle",
727+ "time",
728+ "version_check",
729+]
730+
731+[[package]]
732+name = "core-foundation"
733+version = "0.10.1"
734+source = "registry+https://github.com/rust-lang/crates.io-index"
735+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
736+dependencies = [
737+ "core-foundation-sys",
738+ "libc",
739+]
740+
741+[[package]]
742+name = "core-foundation-sys"
743+version = "0.8.7"
744+source = "registry+https://github.com/rust-lang/crates.io-index"
745+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
746+
747+[[package]]
748+name = "cpufeatures"
749+version = "0.2.17"
750+source = "registry+https://github.com/rust-lang/crates.io-index"
751+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
752+dependencies = [
753+ "libc",
754+]
755+
756+[[package]]
757+name = "cpufeatures"
758+version = "0.3.1"
759+source = "registry+https://github.com/rust-lang/crates.io-index"
760+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
761+dependencies = [
762+ "libc",
763+]
764+
765+[[package]]
766+name = "crc32c"
767+version = "0.6.8"
768+source = "registry+https://github.com/rust-lang/crates.io-index"
769+checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47"
770+dependencies = [
771+ "rustc_version",
772+]
773+
774+[[package]]
775+name = "crc32fast"
776+version = "1.5.1"
777+source = "registry+https://github.com/rust-lang/crates.io-index"
778+checksum = "8498c871161e1742aaa9d52551b2d6ebdd4c3d45a3be423e3728f33b955be550"
779+dependencies = [
780+ "cfg-if",
781+]
782+
783+[[package]]
784+name = "crossbeam-channel"
785+version = "0.5.16"
786+source = "registry+https://github.com/rust-lang/crates.io-index"
787+checksum = "d85363c37faeca707aef026efa9f3b34d077bce547e48f770770625c6013679e"
788+dependencies = [
789+ "crossbeam-utils",
790+]
791+
792+[[package]]
793+name = "crossbeam-deque"
794+version = "0.8.7"
795+source = "registry+https://github.com/rust-lang/crates.io-index"
796+checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"
797+dependencies = [
798+ "crossbeam-epoch",
799+ "crossbeam-utils",
800+]
801+
802+[[package]]
803+name = "crossbeam-epoch"
804+version = "0.9.20"
805+source = "registry+https://github.com/rust-lang/crates.io-index"
806+checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"
807+dependencies = [
808+ "crossbeam-utils",
809+]
810+
811+[[package]]
812+name = "crossbeam-utils"
813+version = "0.8.22"
814+source = "registry+https://github.com/rust-lang/crates.io-index"
815+checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
816+
817+[[package]]
818+name = "crunchy"
819+version = "0.2.4"
820+source = "registry+https://github.com/rust-lang/crates.io-index"
821+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
822+
823+[[package]]
824+name = "crypto-common"
825+version = "0.1.7"
826+source = "registry+https://github.com/rust-lang/crates.io-index"
827+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
828+dependencies = [
829+ "generic-array",
830+ "rand_core 0.6.4",
831+ "typenum",
832+]
833+
834+[[package]]
835+name = "crypto-common"
836+version = "0.2.2"
837+source = "registry+https://github.com/rust-lang/crates.io-index"
838+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
839+dependencies = [
840+ "hybrid-array",
841+]
842+
843+[[package]]
844+name = "ctr"
845+version = "0.9.2"
846+source = "registry+https://github.com/rust-lang/crates.io-index"
847+checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
848+dependencies = [
849+ "cipher",
850+]
851+
852+[[package]]
853+name = "ctutils"
854+version = "0.4.2"
855+source = "registry+https://github.com/rust-lang/crates.io-index"
856+checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"
857+dependencies = [
858+ "cmov",
859+]
860+
861+[[package]]
862+name = "darling"
863+version = "0.24.1"
864+source = "registry+https://github.com/rust-lang/crates.io-index"
865+checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
866+dependencies = [
867+ "darling_core",
868+ "darling_macro",
869+]
870+
871+[[package]]
872+name = "darling_core"
873+version = "0.24.1"
874+source = "registry+https://github.com/rust-lang/crates.io-index"
875+checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
876+dependencies = [
877+ "ident_case",
878+ "proc-macro2",
879+ "quote",
880+ "strsim",
881+ "syn 3.0.4",
882+]
883+
884+[[package]]
885+name = "darling_macro"
886+version = "0.24.1"
887+source = "registry+https://github.com/rust-lang/crates.io-index"
888+checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
889+dependencies = [
890+ "darling_core",
891+ "quote",
892+ "syn 3.0.4",
893+]
894+
895+[[package]]
896+name = "data-encoding"
897+version = "2.11.1"
898+source = "registry+https://github.com/rust-lang/crates.io-index"
899+checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
900+
901+[[package]]
902+name = "datasketches"
903+version = "0.2.0"
904+source = "registry+https://github.com/rust-lang/crates.io-index"
905+checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745"
906+
907+[[package]]
908+name = "der"
909+version = "0.7.10"
910+source = "registry+https://github.com/rust-lang/crates.io-index"
911+checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
912+dependencies = [
913+ "const-oid 0.9.6",
914+ "pem-rfc7468",
915+ "zeroize",
916+]
917+
918+[[package]]
919+name = "deranged"
920+version = "0.5.8"
921+source = "registry+https://github.com/rust-lang/crates.io-index"
922+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
923+dependencies = [
924+ "serde_core",
925+]
926+
927+[[package]]
928+name = "digest"
929+version = "0.10.7"
930+source = "registry+https://github.com/rust-lang/crates.io-index"
931+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
932+dependencies = [
933+ "block-buffer 0.10.4",
934+ "const-oid 0.9.6",
935+ "crypto-common 0.1.7",
936+ "subtle",
937+]
938+
939+[[package]]
940+name = "digest"
941+version = "0.11.3"
942+source = "registry+https://github.com/rust-lang/crates.io-index"
943+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
944+dependencies = [
945+ "block-buffer 0.12.1",
946+ "const-oid 0.10.2",
947+ "crypto-common 0.2.2",
948+ "ctutils",
949+]
950+
951+[[package]]
952+name = "displaydoc"
953+version = "0.2.7"
954+source = "registry+https://github.com/rust-lang/crates.io-index"
955+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
956+dependencies = [
957+ "proc-macro2",
958+ "quote",
959+ "syn 3.0.4",
960+]
961+
962+[[package]]
963+name = "downcast-rs"
964+version = "2.0.2"
965+source = "registry+https://github.com/rust-lang/crates.io-index"
966+checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc"
967+
968+[[package]]
969+name = "dunce"
970+version = "1.0.5"
971+source = "registry+https://github.com/rust-lang/crates.io-index"
972+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
973+
974+[[package]]
975+name = "either"
976+version = "1.18.0"
977+source = "registry+https://github.com/rust-lang/crates.io-index"
978+checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
979+
980+[[package]]
981+name = "elsa"
982+version = "1.11.2"
983+source = "registry+https://github.com/rust-lang/crates.io-index"
984+checksum = "9abf33c656a7256451ebb7d0082c5a471820c31269e49d807c538c252352186e"
985+dependencies = [
986+ "stable_deref_trait",
987+]
988+
989+[[package]]
990+name = "email-encoding"
991+version = "0.4.2"
992+source = "registry+https://github.com/rust-lang/crates.io-index"
993+checksum = "420b9da095f052ea597503e39073b5b3c522f7db933fbac202d91d24492693fd"
994+dependencies = [
995+ "base64 0.23.1",
996+ "memchr",
997+]
998+
999+[[package]]
1000+name = "email_address"
1001+version = "0.2.9"
1002+source = "registry+https://github.com/rust-lang/crates.io-index"
1003+checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449"
1004+
1005+[[package]]
1006+name = "env_filter"
1007+version = "2.0.0"
1008+source = "registry+https://github.com/rust-lang/crates.io-index"
1009+checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217"
1010+dependencies = [
1011+ "log",
1012+ "regex",
1013+]
1014+
1015+[[package]]
1016+name = "env_logger"
1017+version = "0.11.11"
1018+source = "registry+https://github.com/rust-lang/crates.io-index"
1019+checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6"
1020+dependencies = [
1021+ "env_filter",
1022+ "log",
1023+]
1024+
1025+[[package]]
1026+name = "equivalent"
1027+version = "1.0.2"
1028+source = "registry+https://github.com/rust-lang/crates.io-index"
1029+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
1030+
1031+[[package]]
1032+name = "erased-serde"
1033+version = "0.4.10"
1034+source = "registry+https://github.com/rust-lang/crates.io-index"
1035+checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
1036+dependencies = [
1037+ "serde",
1038+ "serde_core",
1039+ "typeid",
1040+]
1041+
1042+[[package]]
1043+name = "errno"
1044+version = "0.3.14"
1045+source = "registry+https://github.com/rust-lang/crates.io-index"
1046+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
1047+dependencies = [
1048+ "libc",
1049+ "windows-sys 0.61.2",
1050+]
1051+
1052+[[package]]
1053+name = "fallible-iterator"
1054+version = "0.3.0"
1055+source = "registry+https://github.com/rust-lang/crates.io-index"
1056+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
1057+
1058+[[package]]
1059+name = "fastbloom"
1060+version = "0.14.1"
1061+source = "registry+https://github.com/rust-lang/crates.io-index"
1062+checksum = "4e7f34442dbe69c60fe8eaf58a8cafff81a1f278816d8ab4db255b3bef4ac3c4"
1063+dependencies = [
1064+ "getrandom 0.3.4",
1065+ "libm",
1066+ "siphasher",
1067+]
1068+
1069+[[package]]
1070+name = "fastdivide"
1071+version = "0.4.2"
1072+source = "registry+https://github.com/rust-lang/crates.io-index"
1073+checksum = "9afc2bd4d5a73106dd53d10d73d3401c2f32730ba2c0b93ddb888a8983680471"
1074+
1075+[[package]]
1076+name = "fastrand"
1077+version = "2.5.0"
1078+source = "registry+https://github.com/rust-lang/crates.io-index"
1079+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
1080+
1081+[[package]]
1082+name = "find-msvc-tools"
1083+version = "0.1.11"
1084+source = "registry+https://github.com/rust-lang/crates.io-index"
1085+checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890"
1086+
1087+[[package]]
1088+name = "flate2"
1089+version = "1.1.10"
1090+source = "registry+https://github.com/rust-lang/crates.io-index"
1091+checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
1092+dependencies = [
1093+ "crc32fast",
1094+ "miniz_oxide",
1095+ "zlib-rs",
1096+]
1097+
1098+[[package]]
1099+name = "fnv"
1100+version = "1.0.7"
1101+source = "registry+https://github.com/rust-lang/crates.io-index"
1102+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
1103+
1104+[[package]]
1105+name = "foldhash"
1106+version = "0.2.0"
1107+source = "registry+https://github.com/rust-lang/crates.io-index"
1108+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
1109+
1110+[[package]]
1111+name = "form_urlencoded"
1112+version = "1.2.2"
1113+source = "registry+https://github.com/rust-lang/crates.io-index"
1114+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
1115+dependencies = [
1116+ "percent-encoding",
1117+]
1118+
1119+[[package]]
1120+name = "fs4"
1121+version = "0.13.1"
1122+source = "registry+https://github.com/rust-lang/crates.io-index"
1123+checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4"
1124+dependencies = [
1125+ "rustix 1.1.4",
1126+ "windows-sys 0.59.0",
1127+]
1128+
1129+[[package]]
1130+name = "fs_extra"
1131+version = "1.3.0"
1132+source = "registry+https://github.com/rust-lang/crates.io-index"
1133+checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
1134+
1135+[[package]]
1136+name = "funty"
1137+version = "2.0.0"
1138+source = "registry+https://github.com/rust-lang/crates.io-index"
1139+checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
1140+
1141+[[package]]
1142+name = "futures-channel"
1143+version = "0.3.34"
1144+source = "registry+https://github.com/rust-lang/crates.io-index"
1145+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
1146+dependencies = [
1147+ "futures-core",
1148+]
1149+
1150+[[package]]
1151+name = "futures-core"
1152+version = "0.3.34"
1153+source = "registry+https://github.com/rust-lang/crates.io-index"
1154+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
1155+
1156+[[package]]
1157+name = "futures-io"
1158+version = "0.3.34"
1159+source = "registry+https://github.com/rust-lang/crates.io-index"
1160+checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
1161+
1162+[[package]]
1163+name = "futures-macro"
1164+version = "0.3.34"
1165+source = "registry+https://github.com/rust-lang/crates.io-index"
1166+checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
1167+dependencies = [
1168+ "proc-macro2",
1169+ "quote",
1170+ "syn 3.0.4",
1171+]
1172+
1173+[[package]]
1174+name = "futures-sink"
1175+version = "0.3.34"
1176+source = "registry+https://github.com/rust-lang/crates.io-index"
1177+checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"
1178+
1179+[[package]]
1180+name = "futures-task"
1181+version = "0.3.34"
1182+source = "registry+https://github.com/rust-lang/crates.io-index"
1183+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
1184+
1185+[[package]]
1186+name = "futures-util"
1187+version = "0.3.34"
1188+source = "registry+https://github.com/rust-lang/crates.io-index"
1189+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
1190+dependencies = [
1191+ "futures-core",
1192+ "futures-io",
1193+ "futures-macro",
1194+ "futures-sink",
1195+ "futures-task",
1196+ "memchr",
1197+ "pin-project-lite",
1198+ "slab",
1199+]
1200+
1201+[[package]]
1202+name = "genawaiter"
1203+version = "0.99.1"
1204+source = "registry+https://github.com/rust-lang/crates.io-index"
1205+checksum = "c86bd0361bcbde39b13475e6e36cb24c329964aa2611be285289d1e4b751c1a0"
1206+dependencies = [
1207+ "genawaiter-macro",
1208+]
1209+
1210+[[package]]
1211+name = "genawaiter-macro"
1212+version = "0.99.1"
1213+source = "registry+https://github.com/rust-lang/crates.io-index"
1214+checksum = "0b32dfe1fdfc0bbde1f22a5da25355514b5e450c33a6af6770884c8750aedfbc"
1215+
1216+[[package]]
1217+name = "generator"
1218+version = "0.8.9"
1219+source = "registry+https://github.com/rust-lang/crates.io-index"
1220+checksum = "b3b854b0e584ead1a33f18b2fcad7cf7be18b3875c78816b753639aa501513ae"
1221+dependencies = [
1222+ "cc",
1223+ "cfg-if",
1224+ "libc",
1225+ "log",
1226+ "rustversion",
1227+ "windows-link",
1228+ "windows-result",
1229+]
1230+
1231+[[package]]
1232+name = "generic-array"
1233+version = "0.14.7"
1234+source = "registry+https://github.com/rust-lang/crates.io-index"
1235+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
1236+dependencies = [
1237+ "typenum",
1238+ "version_check",
1239+]
1240+
1241+[[package]]
1242+name = "getrandom"
1243+version = "0.2.17"
1244+source = "registry+https://github.com/rust-lang/crates.io-index"
1245+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
1246+dependencies = [
1247+ "cfg-if",
1248+ "js-sys",
1249+ "libc",
1250+ "wasi",
1251+ "wasm-bindgen",
1252+]
1253+
1254+[[package]]
1255+name = "getrandom"
1256+version = "0.3.4"
1257+source = "registry+https://github.com/rust-lang/crates.io-index"
1258+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
1259+dependencies = [
1260+ "cfg-if",
1261+ "js-sys",
1262+ "libc",
1263+ "r-efi 5.3.0",
1264+ "wasip2",
1265+ "wasm-bindgen",
1266+]
1267+
1268+[[package]]
1269+name = "getrandom"
1270+version = "0.4.3"
1271+source = "registry+https://github.com/rust-lang/crates.io-index"
1272+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
1273+dependencies = [
1274+ "cfg-if",
1275+ "js-sys",
1276+ "libc",
1277+ "r-efi 6.0.0",
1278+ "rand_core 0.10.1",
1279+ "wasm-bindgen",
1280+]
1281+
1282+[[package]]
1283+name = "ghash"
1284+version = "0.5.1"
1285+source = "registry+https://github.com/rust-lang/crates.io-index"
1286+checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
1287+dependencies = [
1288+ "opaque-debug",
1289+ "polyval",
1290+]
1291+
1292+[[package]]
1293+name = "glob"
1294+version = "0.3.4"
1295+source = "registry+https://github.com/rust-lang/crates.io-index"
1296+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
1297+
1298+[[package]]
1299+name = "grass"
1300+version = "0.13.4"
1301+source = "registry+https://github.com/rust-lang/crates.io-index"
1302+checksum = "f7a68216437ef68f0738e48d6c7bb9e6e6a92237e001b03d838314b068f33c94"
1303+dependencies = [
1304+ "clap",
1305+ "getrandom 0.2.17",
1306+ "grass_compiler",
1307+]
1308+
1309+[[package]]
1310+name = "grass_compiler"
1311+version = "0.13.4"
1312+source = "registry+https://github.com/rust-lang/crates.io-index"
1313+checksum = "2d9e3df7f0222ce5184154973d247c591d9aadc28ce7a73c6cd31100c9facff6"
1314+dependencies = [
1315+ "codemap",
1316+ "indexmap",
1317+ "lasso",
1318+ "once_cell",
1319+ "phf",
1320+ "rand 0.8.8",
1321+]
1322+
1323+[[package]]
1324+name = "h2"
1325+version = "0.4.19"
1326+source = "registry+https://github.com/rust-lang/crates.io-index"
1327+checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16"
1328+dependencies = [
1329+ "atomic-waker",
1330+ "bytes",
1331+ "fnv",
1332+ "futures-core",
1333+ "futures-sink",
1334+ "http",
1335+ "indexmap",
1336+ "slab",
1337+ "tokio",
1338+ "tokio-util",
1339+ "tracing",
1340+]
1341+
1342+[[package]]
1343+name = "hashbrown"
1344+version = "0.14.5"
1345+source = "registry+https://github.com/rust-lang/crates.io-index"
1346+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
1347+dependencies = [
1348+ "ahash",
1349+ "allocator-api2 0.2.21",
1350+]
1351+
1352+[[package]]
1353+name = "hashbrown"
1354+version = "0.16.1"
1355+source = "registry+https://github.com/rust-lang/crates.io-index"
1356+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
1357+dependencies = [
1358+ "allocator-api2 0.2.21",
1359+ "equivalent",
1360+ "foldhash",
1361+]
1362+
1363+[[package]]
1364+name = "hashbrown"
1365+version = "0.17.1"
1366+source = "registry+https://github.com/rust-lang/crates.io-index"
1367+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
1368+
1369+[[package]]
1370+name = "heck"
1371+version = "0.5.0"
1372+source = "registry+https://github.com/rust-lang/crates.io-index"
1373+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
1374+
1375+[[package]]
1376+name = "hermit-abi"
1377+version = "0.5.3"
1378+source = "registry+https://github.com/rust-lang/crates.io-index"
1379+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
1380+
1381+[[package]]
1382+name = "hex"
1383+version = "0.4.3"
1384+source = "registry+https://github.com/rust-lang/crates.io-index"
1385+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
1386+
1387+[[package]]
1388+name = "hkdf"
1389+version = "0.12.4"
1390+source = "registry+https://github.com/rust-lang/crates.io-index"
1391+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
1392+dependencies = [
1393+ "hmac 0.12.1",
1394+]
1395+
1396+[[package]]
1397+name = "hmac"
1398+version = "0.12.1"
1399+source = "registry+https://github.com/rust-lang/crates.io-index"
1400+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
1401+dependencies = [
1402+ "digest 0.10.7",
1403+]
1404+
1405+[[package]]
1406+name = "hmac"
1407+version = "0.13.0"
1408+source = "registry+https://github.com/rust-lang/crates.io-index"
1409+checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
1410+dependencies = [
1411+ "digest 0.11.3",
1412+]
1413+
1414+[[package]]
1415+name = "home"
1416+version = "0.5.12"
1417+source = "registry+https://github.com/rust-lang/crates.io-index"
1418+checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
1419+dependencies = [
1420+ "windows-sys 0.61.2",
1421+]
1422+
1423+[[package]]
1424+name = "hostname"
1425+version = "0.4.2"
1426+source = "registry+https://github.com/rust-lang/crates.io-index"
1427+checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd"
1428+dependencies = [
1429+ "cfg-if",
1430+ "libc",
1431+ "windows-link",
1432+]
1433+
1434+[[package]]
1435+name = "htmlescape"
1436+version = "0.3.1"
1437+source = "registry+https://github.com/rust-lang/crates.io-index"
1438+checksum = "e9025058dae765dee5070ec375f591e2ba14638c63feff74f13805a72e523163"
1439+
1440+[[package]]
1441+name = "http"
1442+version = "1.5.0"
1443+source = "registry+https://github.com/rust-lang/crates.io-index"
1444+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
1445+dependencies = [
1446+ "bytes",
1447+ "itoa",
1448+]
1449+
1450+[[package]]
1451+name = "http-body"
1452+version = "1.1.0"
1453+source = "registry+https://github.com/rust-lang/crates.io-index"
1454+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
1455+dependencies = [
1456+ "bytes",
1457+ "http",
1458+]
1459+
1460+[[package]]
1461+name = "http-body-util"
1462+version = "0.1.5"
1463+source = "registry+https://github.com/rust-lang/crates.io-index"
1464+checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
1465+dependencies = [
1466+ "bytes",
1467+ "futures-core",
1468+ "http",
1469+ "http-body",
1470+ "pin-project-lite",
1471+]
1472+
1473+[[package]]
1474+name = "httparse"
1475+version = "1.10.1"
1476+source = "registry+https://github.com/rust-lang/crates.io-index"
1477+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
1478+
1479+[[package]]
1480+name = "httpdate"
1481+version = "1.0.3"
1482+source = "registry+https://github.com/rust-lang/crates.io-index"
1483+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
1484+
1485+[[package]]
1486+name = "hybrid-array"
1487+version = "0.4.14"
1488+source = "registry+https://github.com/rust-lang/crates.io-index"
1489+checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b"
1490+dependencies = [
1491+ "typenum",
1492+]
1493+
1494+[[package]]
1495+name = "hyper"
1496+version = "1.11.1"
1497+source = "registry+https://github.com/rust-lang/crates.io-index"
1498+checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43"
1499+dependencies = [
1500+ "atomic-waker",
1501+ "bytes",
1502+ "futures-channel",
1503+ "futures-core",
1504+ "h2",
1505+ "http",
1506+ "http-body",
1507+ "httparse",
1508+ "httpdate",
1509+ "itoa",
1510+ "pin-project-lite",
1511+ "smallvec",
1512+ "tokio",
1513+ "want",
1514+]
1515+
1516+[[package]]
1517+name = "hyper-rustls"
1518+version = "0.27.9"
1519+source = "registry+https://github.com/rust-lang/crates.io-index"
1520+checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"
1521+dependencies = [
1522+ "http",
1523+ "hyper",
1524+ "hyper-util",
1525+ "rustls",
1526+ "tokio",
1527+ "tokio-rustls",
1528+ "tower-service",
1529+]
1530+
1531+[[package]]
1532+name = "hyper-util"
1533+version = "0.1.20"
1534+source = "registry+https://github.com/rust-lang/crates.io-index"
1535+checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
1536+dependencies = [
1537+ "base64 0.22.1",
1538+ "bytes",
1539+ "futures-channel",
1540+ "futures-util",
1541+ "http",
1542+ "http-body",
1543+ "hyper",
1544+ "ipnet",
1545+ "libc",
1546+ "percent-encoding",
1547+ "pin-project-lite",
1548+ "socket2",
1549+ "tokio",
1550+ "tower-service",
1551+ "tracing",
1552+]
1553+
1554+[[package]]
1555+name = "iana-time-zone"
1556+version = "0.1.65"
1557+source = "registry+https://github.com/rust-lang/crates.io-index"
1558+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
1559+dependencies = [
1560+ "android_system_properties",
1561+ "core-foundation-sys",
1562+ "iana-time-zone-haiku",
1563+ "js-sys",
1564+ "log",
1565+ "wasm-bindgen",
1566+ "windows-core",
1567+]
1568+
1569+[[package]]
1570+name = "iana-time-zone-haiku"
1571+version = "0.1.2"
1572+source = "registry+https://github.com/rust-lang/crates.io-index"
1573+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
1574+dependencies = [
1575+ "cc",
1576+]
1577+
1578+[[package]]
1579+name = "icu_collator"
1580+version = "2.3.1"
1581+source = "registry+https://github.com/rust-lang/crates.io-index"
1582+checksum = "08984ed58ac439ebf3e13d2cf26b0c46a60afcd21721c1d14087c0b240344dda"
1583+dependencies = [
1584+ "icu_collator_data",
1585+ "icu_collections",
1586+ "icu_locale_core",
1587+ "icu_locale_fallback",
1588+ "icu_normalizer",
1589+ "icu_properties",
1590+ "icu_provider",
1591+ "smallvec",
1592+ "utf16_iter",
1593+ "utf8_iter",
1594+ "zerovec",
1595+]
1596+
1597+[[package]]
1598+name = "icu_collator_data"
1599+version = "2.3.0"
1600+source = "registry+https://github.com/rust-lang/crates.io-index"
1601+checksum = "f7d7e54efdddeb1208c08dd5d32b53a879ac00d2d3d051b2255fd26821d16368"
1602+
1603+[[package]]
1604+name = "icu_collections"
1605+version = "2.3.0"
1606+source = "registry+https://github.com/rust-lang/crates.io-index"
1607+checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
1608+dependencies = [
1609+ "displaydoc",
1610+ "potential_utf",
1611+ "utf8_iter",
1612+ "yoke",
1613+ "zerofrom",
1614+ "zerovec",
1615+]
1616+
1617+[[package]]
1618+name = "icu_locale"
1619+version = "2.3.1"
1620+source = "registry+https://github.com/rust-lang/crates.io-index"
1621+checksum = "785f595c61ef57169a467eeed7b4b6936a66f6cacbb116a96ee86da983251bf4"
1622+dependencies = [
1623+ "icu_collections",
1624+ "icu_locale_core",
1625+ "icu_locale_data",
1626+ "icu_locale_fallback",
1627+ "icu_provider",
1628+ "tinystr",
1629+ "zerovec",
1630+]
1631+
1632+[[package]]
1633+name = "icu_locale_core"
1634+version = "2.3.0"
1635+source = "registry+https://github.com/rust-lang/crates.io-index"
1636+checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
1637+dependencies = [
1638+ "displaydoc",
1639+ "litemap",
1640+ "serde",
1641+ "tinystr",
1642+ "writeable",
1643+ "zerovec",
1644+]
1645+
1646+[[package]]
1647+name = "icu_locale_data"
1648+version = "2.3.0"
1649+source = "registry+https://github.com/rust-lang/crates.io-index"
1650+checksum = "d37d91460e362a5cf58907cd7ce871411775ee6294e49a5cc8e6cec16dfa75ea"
1651+
1652+[[package]]
1653+name = "icu_locale_fallback"
1654+version = "2.3.0"
1655+source = "registry+https://github.com/rust-lang/crates.io-index"
1656+checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9"
1657+dependencies = [
1658+ "icu_locale_core",
1659+ "icu_locale_fallback_data",
1660+ "icu_provider",
1661+ "potential_utf",
1662+ "tinystr",
1663+ "zerovec",
1664+]
1665+
1666+[[package]]
1667+name = "icu_locale_fallback_data"
1668+version = "2.3.0"
1669+source = "registry+https://github.com/rust-lang/crates.io-index"
1670+checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8"
1671+
1672+[[package]]
1673+name = "icu_normalizer"
1674+version = "2.3.0"
1675+source = "registry+https://github.com/rust-lang/crates.io-index"
1676+checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"
1677+dependencies = [
1678+ "icu_collections",
1679+ "icu_normalizer_data",
1680+ "icu_properties",
1681+ "icu_provider",
1682+ "smallvec",
1683+ "utf16_iter",
1684+ "utf8_iter",
1685+ "write16",
1686+ "zerovec",
1687+]
1688+
1689+[[package]]
1690+name = "icu_normalizer_data"
1691+version = "2.3.0"
1692+source = "registry+https://github.com/rust-lang/crates.io-index"
1693+checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
1694+
1695+[[package]]
1696+name = "icu_properties"
1697+version = "2.3.0"
1698+source = "registry+https://github.com/rust-lang/crates.io-index"
1699+checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"
1700+dependencies = [
1701+ "displaydoc",
1702+ "icu_collections",
1703+ "icu_locale_core",
1704+ "icu_properties_data",
1705+ "icu_provider",
1706+ "zerotrie",
1707+ "zerovec",
1708+]
1709+
1710+[[package]]
1711+name = "icu_properties_data"
1712+version = "2.3.0"
1713+source = "registry+https://github.com/rust-lang/crates.io-index"
1714+checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"
1715+
1716+[[package]]
1717+name = "icu_provider"
1718+version = "2.3.1"
1719+source = "registry+https://github.com/rust-lang/crates.io-index"
1720+checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
1721+dependencies = [
1722+ "displaydoc",
1723+ "icu_locale_core",
1724+ "serde",
1725+ "stable_deref_trait",
1726+ "writeable",
1727+ "yoke",
1728+ "zerofrom",
1729+ "zerotrie",
1730+ "zerovec",
1731+]
1732+
1733+[[package]]
1734+name = "ident_case"
1735+version = "1.0.1"
1736+source = "registry+https://github.com/rust-lang/crates.io-index"
1737+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
1738+
1739+[[package]]
1740+name = "idna"
1741+version = "1.1.0"
1742+source = "registry+https://github.com/rust-lang/crates.io-index"
1743+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
1744+dependencies = [
1745+ "idna_adapter",
1746+ "smallvec",
1747+ "utf8_iter",
1748+]
1749+
1750+[[package]]
1751+name = "idna_adapter"
1752+version = "1.2.2"
1753+source = "registry+https://github.com/rust-lang/crates.io-index"
1754+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
1755+dependencies = [
1756+ "icu_normalizer",
1757+ "icu_properties",
1758+]
1759+
1760+[[package]]
1761+name = "im-client"
1762+version = "0.1.0"
1763+dependencies = [
1764+ "base64 0.22.1",
1765+ "chacha20poly1305",
1766+ "http",
1767+ "rand 0.10.2",
1768+ "rand_core 0.6.4",
1769+ "reqwest",
1770+ "rsa",
1771+ "serde",
1772+ "serde_json",
1773+ "sha2 0.10.9",
1774+ "sha2 0.11.0",
1775+ "subtle",
1776+ "thiserror",
1777+ "time",
1778+ "tokio",
1779+ "topcoat",
1780+]
1781+
1782+[[package]]
1783+name = "im-core"
1784+version = "0.1.0"
1785+dependencies = [
1786+ "argon2",
1787+ "base64 0.22.1",
1788+ "chacha20poly1305",
1789+ "data-encoding",
1790+ "hmac 0.13.0",
1791+ "rand 0.10.2",
1792+ "rand_core 0.6.4",
1793+ "rsa",
1794+ "serde",
1795+ "serde_json",
1796+ "sha1 0.11.0",
1797+ "sha2 0.10.9",
1798+ "sha2 0.11.0",
1799+ "subtle",
1800+ "tempfile",
1801+ "thiserror",
1802+ "time",
1803+ "tokio",
1804+ "turso",
1805+ "ulid",
1806+]
1807+
1808+[[package]]
1809+name = "im-migrate"
1810+version = "0.1.0"
1811+dependencies = [
1812+ "tempfile",
1813+ "thiserror",
1814+ "time",
1815+ "tokio",
1816+ "turso",
1817+ "ulid",
1818+]
1819+
1820+[[package]]
1821+name = "im-web"
1822+version = "0.1.0"
1823+dependencies = [
1824+ "base64 0.22.1",
1825+ "data-encoding",
1826+ "grass",
1827+ "http",
1828+ "im-core",
1829+ "lettre",
1830+ "qrcode",
1831+ "serde",
1832+ "serde_json",
1833+ "thiserror",
1834+ "time",
1835+ "tokio",
1836+ "toml",
1837+ "topcoat",
1838+ "ulid",
1839+]
1840+
1841+[[package]]
1842+name = "indexmap"
1843+version = "2.14.1"
1844+source = "registry+https://github.com/rust-lang/crates.io-index"
1845+checksum = "07aa2048142242915a31d35844fb311e0e53fcca590c3a0a40dcf1b841fa09eb"
1846+dependencies = [
1847+ "equivalent",
1848+ "hashbrown 0.17.1",
1849+]
1850+
1851+[[package]]
1852+name = "inout"
1853+version = "0.1.4"
1854+source = "registry+https://github.com/rust-lang/crates.io-index"
1855+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
1856+dependencies = [
1857+ "generic-array",
1858+]
1859+
1860+[[package]]
1861+name = "intrusive-collections"
1862+version = "0.9.7"
1863+source = "registry+https://github.com/rust-lang/crates.io-index"
1864+checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86"
1865+dependencies = [
1866+ "memoffset",
1867+]
1868+
1869+[[package]]
1870+name = "inventory"
1871+version = "0.3.24"
1872+source = "registry+https://github.com/rust-lang/crates.io-index"
1873+checksum = "a4f0c30c76f2f4ccee3fe55a2435f691ca00c0e4bd87abe4f4a851b1d4dac39b"
1874+dependencies = [
1875+ "rustversion",
1876+]
1877+
1878+[[package]]
1879+name = "io-uring"
1880+version = "0.7.14"
1881+source = "registry+https://github.com/rust-lang/crates.io-index"
1882+checksum = "d64d8ca234d152948ceaede1f419b6a83983a5ecccaac05fb337a809c96d3aa6"
1883+dependencies = [
1884+ "bitflags",
1885+ "cfg-if",
1886+ "libc",
1887+]
1888+
1889+[[package]]
1890+name = "ipnet"
1891+version = "2.12.1"
1892+source = "registry+https://github.com/rust-lang/crates.io-index"
1893+checksum = "6a756c3fac73139e83f14c2d742155dd2b78d3ee56597b419a0579b7bdd6dd78"
1894+
1895+[[package]]
1896+name = "is_terminal_polyfill"
1897+version = "1.70.2"
1898+source = "registry+https://github.com/rust-lang/crates.io-index"
1899+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
1900+
1901+[[package]]
1902+name = "itertools"
1903+version = "0.12.1"
1904+source = "registry+https://github.com/rust-lang/crates.io-index"
1905+checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"
1906+dependencies = [
1907+ "either",
1908+]
1909+
1910+[[package]]
1911+name = "itertools"
1912+version = "0.14.0"
1913+source = "registry+https://github.com/rust-lang/crates.io-index"
1914+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
1915+dependencies = [
1916+ "either",
1917+]
1918+
1919+[[package]]
1920+name = "itoa"
1921+version = "1.0.18"
1922+source = "registry+https://github.com/rust-lang/crates.io-index"
1923+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
1924+
1925+[[package]]
1926+name = "jni"
1927+version = "0.22.4"
1928+source = "registry+https://github.com/rust-lang/crates.io-index"
1929+checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
1930+dependencies = [
1931+ "cfg-if",
1932+ "combine",
1933+ "jni-macros",
1934+ "jni-sys",
1935+ "log",
1936+ "simd_cesu8",
1937+ "thiserror",
1938+ "walkdir",
1939+ "windows-link",
1940+]
1941+
1942+[[package]]
1943+name = "jni-macros"
1944+version = "0.22.4"
1945+source = "registry+https://github.com/rust-lang/crates.io-index"
1946+checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
1947+dependencies = [
1948+ "proc-macro2",
1949+ "quote",
1950+ "rustc_version",
1951+ "simd_cesu8",
1952+ "syn 2.0.119",
1953+]
1954+
1955+[[package]]
1956+name = "jni-sys"
1957+version = "0.4.1"
1958+source = "registry+https://github.com/rust-lang/crates.io-index"
1959+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
1960+dependencies = [
1961+ "jni-sys-macros",
1962+]
1963+
1964+[[package]]
1965+name = "jni-sys-macros"
1966+version = "0.4.1"
1967+source = "registry+https://github.com/rust-lang/crates.io-index"
1968+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
1969+dependencies = [
1970+ "quote",
1971+ "syn 2.0.119",
1972+]
1973+
1974+[[package]]
1975+name = "jobserver"
1976+version = "0.1.35"
1977+source = "registry+https://github.com/rust-lang/crates.io-index"
1978+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
1979+dependencies = [
1980+ "getrandom 0.4.3",
1981+ "libc",
1982+]
1983+
1984+[[package]]
1985+name = "js-sys"
1986+version = "0.3.104"
1987+source = "registry+https://github.com/rust-lang/crates.io-index"
1988+checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a"
1989+dependencies = [
1990+ "cfg-if",
1991+ "futures-util",
1992+ "wasm-bindgen",
1993+]
1994+
1995+[[package]]
1996+name = "lasso"
1997+version = "0.7.3"
1998+source = "registry+https://github.com/rust-lang/crates.io-index"
1999+checksum = "6e14eda50a3494b3bf7b9ce51c52434a761e383d7238ce1dd5dcec2fbc13e9fb"
2000+dependencies = [
Cargo.tomladded+45 -0
@@ -0,0 +1,45 @@
1+[workspace]
2+resolver = "3"
3+members = [
4+ "crates/im-core",
5+ "crates/im-web",
6+ "crates/im-client",
7+ "crates/im-migrate",
8+]
9+
10+[workspace.package]
11+version = "0.1.0"
12+edition = "2024"
13+repository = "https://github.com/DizeyLab/im"
14+
15+[workspace.dependencies]
16+im-core = { path = "crates/im-core", default-features = false }
17+serde = { version = "1.0.229", features = ["derive"] }
18+serde_json = "1.0.145"
19+thiserror = "2.0.20"
20+ulid = "1"
21+time = { version = "0.3.55", features = ["serde", "formatting", "parsing", "macros"] }
22+tokio = { version = "1.53.1", features = ["full"] }
23+turso = "=0.8.0-pre.7"
24+argon2 = "0.6.0"
25+rand = "0.10.2"
26+sha2 = "0.11.0"
27+subtle = "2.6.1"
28+chacha20poly1305 = "0.10.1"
29+base64 = "0.22.1"
30+toml = "1"
31+async-trait = "0.1.92"
32+
33+[profile.release]
34+codegen-units = 1
35+lto = true
36+
37+# What the deploy builds. Fat LTO and one codegen unit buy the last few
38+# percent by optimizing the whole program in a single non-parallel pass —
39+# worth it for something CPU-bound, not for a server whose time goes to
40+# SQLite, TLS and the network. Thin LTO still optimizes across crates, in
41+# parallel, so `release` stays available for when the trade is worth making.
42+[profile.dist]
43+inherits = "release"
44+lto = "thin"
45+codegen-units = 16
config/im.tomladded+12 -0
@@ -0,0 +1,12 @@
1+database = "im.db"
2+listen = "127.0.0.1:7650"
3+issuer = "http://127.0.0.1:7650"
4+
5+# Without an [smtp] table the server runs in dev mode: invite links are
6+# printed to stdout instead of mailed.
7+# [smtp]
8+# host = "smtp.example.com"
9+# port = 465
10+# username = "..."
11+# password = "..."
12+# from = "im <auth@example.com>"
crates/im-client/Cargo.tomladded+45 -0
@@ -0,0 +1,45 @@
1+[package]
2+name = "im-client"
3+version.workspace = true
4+edition.workspace = true
5+license.workspace = true
6+repository.workspace = true
7+description = "Drop-in OIDC client for topcoat apps authenticating against im"
8+
9+[dependencies]
10+topcoat = { version = "0.6.2", default-features = false, features = [
11+ "router",
12+ "cookie",
13+] }
14+serde.workspace = true
15+serde_json.workspace = true
16+thiserror.workspace = true
17+time.workspace = true
18+tokio.workspace = true
19+base64.workspace = true
20+rand.workspace = true
21+sha2.workspace = true
22+subtle.workspace = true
23+chacha20poly1305.workspace = true
24+# rsa 0.9 verifies through the digest 0.10 traits, so its hasher comes from
25+# the sha2 0.10 line; the workspace sha2 0.11 stays for PKCE.
26+sha2-for-rsa = { package = "sha2", version = "0.10", features = ["oid"] }
27+rsa = "0.9.10"
28+reqwest = { version = "0.13.4", default-features = false, features = [
29+ "rustls",
30+ "json",
31+ "form",
32+] }
33+
34+[dev-dependencies]
35+topcoat = { version = "0.6.2", default-features = false, features = [
36+ "router",
37+ "cookie",
38+ "view",
39+ "serve",
40+ "discover",
41+] }
42+http = "1.5"
43+# Tests generate their own RSA keys, and rsa 0.9's RNG is the rand_core 0.6
44+# line.
45+rand_core06 = { package = "rand_core", version = "0.6.4", features = ["getrandom"] }
crates/im-client/examples/demo.rsadded+66 -0
@@ -0,0 +1,66 @@
1+//! The smallest topcoat app that signs in through im. Used by the
2+//! integration smoke test, and the reference for every app that follows.
3+//!
4+//! ```sh
5+//! IM_ISSUER=http://127.0.0.1:7650 \
6+//! IM_CLIENT_ID=<from im-web create-client> \
7+//! IM_CLIENT_SECRET=<same> \
8+//! cargo run -p im-client --example demo
9+//! ```
10+//!
11+//! The cookie key below is a fixed development value so restarts keep
12+use topcoat::Result;
13+use topcoat::context::Cx;
14+use topcoat::cookie::RouterBuilderCookieExt;
15+use topcoat::router::response::{IntoResponse, Response};
16+use topcoat::router::{HeaderValue, Router, RouterBuilderDiscoverExt, StatusCode, header, route};
17+
18+const DEV_COOKIE_KEY: [u8; 32] = [42u8; 32];
19+
20+#[route(GET "/")]
21+async fn home(cx: &Cx) -> Result<String> {
22+ Ok(match im_client::current_user(cx).await {
23+ Some(user) => format!(
24+ "signed in as {} <{}>\n/me shows the claims, /auth/logout signs out of this app\n",
25+ user.name, user.email
26+ ),
27+ None => "not signed in\n/auth/login?next=/me to begin\n".to_string(),
28+ })
29+}
30+
31+#[route(GET "/me")]
32+async fn me(cx: &Cx) -> Result<Response> {
33+ match im_client::current_user(cx).await {
34+ Some(user) => {
35+ topcoat::router::content::Json(serde_json::to_value(user).unwrap()).into_response(cx)
36+ }
37+ None => (
38+ StatusCode::SEE_OTHER,
39+ [(
40+ header::LOCATION,
41+ HeaderValue::from_static("/auth/login?next=/me"),
42+ )],
43+ )
44+ .into_response(cx),
45+ }
46+}
47+
48+#[tokio::main]
49+async fn main() {
50+ let config = im_client::Config {
51+ issuer: std::env::var("IM_ISSUER").unwrap_or("http://127.0.0.1:7650".into()),
52+ client_id: std::env::var("IM_CLIENT_ID").expect("IM_CLIENT_ID"),
53+ client_secret: std::env::var("IM_CLIENT_SECRET").expect("IM_CLIENT_SECRET"),
54+ redirect_uri: "http://127.0.0.1:7656/auth/callback".into(),
55+ cookie_name: "demo_session".into(),
56+ cookie_key: DEV_COOKIE_KEY,
57+ };
58+ let router = im_client::mount(Router::builder().discover().cookies(), config).build();
59+ let listener = tokio::net::TcpListener::bind("127.0.0.1:7656")
60+ .await
61+ .expect("failed to bind 127.0.0.1:7656");
62+ println!("demo listening on http://127.0.0.1:7656");
63+ topcoat::serve_until(listener, router, std::future::pending())
64+ .await
65+ .expect("server error");
66+}
crates/im-client/src/lib.rsadded+710 -0
@@ -0,0 +1,710 @@
1+//! im-client: drop-in OIDC client for topcoat apps authenticating against im.
2+//!
3+//! An app adds three things: `im_client::mount(builder, config)` when it
4+//! builds its router, `.discover()` as usual (the `/auth/login`,
5+//! `/auth/callback`, `/auth/logout` routes register themselves), and
6+//! `im_client::current_user(cx)` wherever it needs the person.
7+//!
8+//! The model: im holds the central session; this crate holds the app's side
9+//! of it — an encrypted cookie with the identity claims and the refresh
10+//! token. When the access token ages out, `current_user` silently rotates it
11+//! against im; when im has revoked the central session, the rotation is
12+//! refused and the app sees a signed-out user.
13+
14+use base64::Engine;
15+use base64::engine::general_purpose::URL_SAFE_NO_PAD as b64url;
16+use chacha20poly1305::aead::Aead;
17+use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce};
18+use rand::Rng;
19+use serde::{Deserialize, Serialize};
20+use sha2::{Digest, Sha256};
21+use subtle::ConstantTimeEq;
22+use time::OffsetDateTime;
23+use topcoat::context::{Cx, try_app_context};
24+use topcoat::cookie::{Cookie, Cookies, cookie, cookies};
25+use topcoat::router::response::{IntoResponse, Response};
26+use topcoat::router::{HeaderValue, RouterBuilder, StatusCode, header, route};
27+
28+// ---------------------------------------------------------------------------
29+// Configuration and state
30+// ---------------------------------------------------------------------------
31+
32+/// Everything the app knows about its im registration. `client_secret` and
33+/// `cookie_key` are secrets: the first authenticates the app to im, the
34+/// second seals the browser cookies this crate writes.
35+#[derive(Clone)]
36+pub struct Config {
37+ /// im's base URL, e.g. `http://127.0.0.1:7650` or `https://auth.example.com`.
38+ pub issuer: String,
39+ pub client_id: String,
40+ pub client_secret: String,
41+ /// Must exactly match one of the URIs registered with im.
42+ pub redirect_uri: String,
43+ /// The app's session cookie name, e.g. `izlek_session`.
44+ pub cookie_name: String,
45+ /// 32 bytes, generated once per app and kept out of the repository.
46+ pub cookie_key: [u8; 32],
47+}
48+
49+/// The registered state: the config, one HTTP client, and the JWKS cache.
50+pub struct ImClient {
51+ config: Config,
52+ http: reqwest::Client,
53+ jwks: tokio::sync::RwLock<Option<JwksCache>>,
54+}
55+
56+struct JwksCache {
57+ fetched_at: OffsetDateTime,
58+ /// kid -> public key
59+ keys: Vec<(String, rsa::RsaPublicKey)>,
60+}
61+
62+#[derive(Debug, thiserror::Error)]
63+pub enum Error {
64+ #[error("http: {0}")]
65+ Http(String),
66+ #[error("im refused: {0}")]
67+ Refused(String),
68+ #[error("bad token: {0}")]
69+ Token(String),
70+}
71+
72+pub type Result<T, E = Error> = std::result::Result<T, E>;
73+
74+impl ImClient {
75+ pub fn new(config: Config) -> Self {
76+ ImClient {
77+ config,
78+ http: reqwest::Client::new(),
79+ jwks: tokio::sync::RwLock::new(None),
80+ }
81+ }
82+}
83+
84+/// Registers the client state on the router. The routes themselves register
85+/// through `discover()` — call it as usual.
86+pub fn mount(builder: RouterBuilder, config: Config) -> RouterBuilder {
87+ builder.app_context(ImClient::new(config))
88+}
89+
90+fn client(cx: &Cx) -> &ImClient {
91+ try_app_context::<ImClient>(cx).expect("im_client::mount was called on the router")
92+}
93+
94+/// The authenticated person, if this browser has one. Transparently refreshes
95+/// against im when the access token has aged out; `None` means signed out.
96+pub async fn current_user(cx: &Cx) -> Option<User> {
97+ let state = client(cx);
98+ let sealed = cookies(cx).get(&state.config.cookie_name)?;
99+ let mut session: Session = open_json(&state.config.cookie_key, sealed.value())?;
100+ if session.access_exp > OffsetDateTime::now_utc().unix_timestamp() {
101+ return Some(session.user());
102+ }
103+ match refresh(cx, state, &mut session).await {
104+ Ok(()) => {
105+ set_session_cookie(cx, state, &session);
106+ Some(session.user())
107+ }
108+ Err(_) => {
109+ clear_cookie(cx, &state.config.cookie_name);
110+ None
111+ }
112+ }
113+}
114+
115+/// Who this browser is, from the claims.
116+#[derive(Debug, Clone, Serialize, Deserialize)]
117+pub struct User {
118+ pub sub: String,
119+ pub email: String,
120+ pub name: String,
121+}
122+
123+// ---------------------------------------------------------------------------
124+// The app session cookie
125+// ---------------------------------------------------------------------------
126+
127+#[derive(Serialize, Deserialize)]
128+struct Session {
129+ user: User,
130+ refresh_token: String,
131+ access_exp: i64,
132+}
133+
134+impl Session {
135+ fn user(&self) -> User {
136+ self.user.clone()
137+ }
138+}
139+
140+/// The in-flight login: PKCE verifier, state, nonce, and where to land after.
141+#[derive(Serialize, Deserialize)]
142+struct InFlight {
143+ verifier: String,
144+ state: String,
145+ nonce: String,
146+ next: String,
147+ exp: i64,
148+}
149+
150+const IN_FLIGHT_MINUTES: i64 = 10;
151+
152+fn seal(key: &[u8; 32], plaintext: &[u8]) -> String {
153+ let cipher = XChaCha20Poly1305::new(key.into());
154+ let mut nonce_bytes = [0u8; 24];
155+ rand::rng().fill_bytes(&mut nonce_bytes);
156+ let ciphertext = cipher
157+ .encrypt(XNonce::from_slice(&nonce_bytes), plaintext)
158+ .expect("XChaCha20-Poly1305 cannot fail on a payload this small");
159+ let mut payload = nonce_bytes.to_vec();
160+ payload.extend_from_slice(&ciphertext);
161+ b64url.encode(payload)
162+}
163+
164+fn open(key: &[u8; 32], sealed: &str) -> Option<Vec<u8>> {
165+ let payload = b64url.decode(sealed).ok()?;
166+ if payload.len() < 24 {
167+ return None;
168+ }
169+ let (nonce_bytes, ciphertext) = payload.split_at(24);
170+ let cipher = XChaCha20Poly1305::new(key.into());
171+ cipher
172+ .decrypt(XNonce::from_slice(nonce_bytes), ciphertext)
173+ .ok()
174+}
175+
176+fn seal_json<T: Serialize>(key: &[u8; 32], value: &T) -> String {
177+ seal(key, &serde_json::to_vec(value).expect("plain data"))
178+}
179+
180+fn open_json<T: for<'de> Deserialize<'de>>(key: &[u8; 32], sealed: &str) -> Option<T> {
181+ serde_json::from_slice(&open(key, sealed)?).ok()
182+}
183+
184+fn app_cookies(cx: &Cx) -> impl Cookies {
185+ cookies(cx)
186+ .default_secure(client(cx).config.issuer.starts_with("https://"))
187+ .default_http_only(true)
188+ .default_same_site(topcoat::cookie::SameSite::Lax)
189+ .default_path("/")
190+}
191+
192+fn set_session_cookie(cx: &Cx, state: &ImClient, session: &Session) {
193+ let name = state.config.cookie_name.clone();
194+ app_cookies(cx).add(cookie! {
195+ name = seal_json(&state.config.cookie_key, session);
196+ Path = "/";
197+ HttpOnly;
198+ SameSite = Lax;
199+ MaxAge = time::Duration::days(30)
200+ });
201+}
202+
203+fn clear_cookie(cx: &Cx, name: &str) {
204+ app_cookies(cx).remove(Cookie::build((name.to_string(), "")).path("/").build());
205+}
206+
207+// ---------------------------------------------------------------------------
208+// Routes
209+// ---------------------------------------------------------------------------
210+
211+fn see(cx: &Cx, location: &str) -> Result<Response, topcoat::Error> {
212+ (
213+ StatusCode::SEE_OTHER,
214+ [(header::LOCATION, HeaderValue::from_str(location).unwrap())],
215+ )
216+ .into_response(cx)
217+}
218+
219+/// A `next` worth honoring: a local absolute path, never `//elsewhere`.
220+fn safe_next(raw: &str) -> &str {
221+ if raw.starts_with('/') && !raw.starts_with("//") {
222+ raw
223+ } else {
224+ "/"
225+ }
226+}
227+
228+/// A JWKS older than this is refreshed before the next validation.
229+const JWKS_TTL_SECONDS: i64 = 3600;
230+
231+async fn jwks_stale(state: &ImClient) -> bool {
232+ match state.jwks.read().await.as_ref() {
233+ None => true,
234+ Some(cache) => {
235+ cache.fetched_at < OffsetDateTime::now_utc() - time::Duration::seconds(JWKS_TTL_SECONDS)
236+ }
237+ }
238+}
239+
240+fn query_value(query: &str, key: &str) -> Option<String> {
241+ query.split('&').find_map(|pair| {
242+ let (k, v) = pair.split_once('=')?;
243+ (k == key).then(|| urldecode(v))
244+ })
245+}
246+
247+/// Percent-decodes a query value (`+` is a space, form-style).
248+fn urldecode(raw: &str) -> String {
249+ let bytes = raw.as_bytes();
250+ let mut out = Vec::with_capacity(bytes.len());
251+ let mut i = 0;
252+ while i < bytes.len() {
253+ match bytes[i] {
254+ b'+' => {
255+ out.push(b' ');
256+ i += 1;
257+ }
258+ b'%' if i + 2 < bytes.len() => {
259+ let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or("");
260+ match u8::from_str_radix(hex, 16) {
261+ Ok(byte) => {
262+ out.push(byte);
263+ i += 3;
264+ }
265+ Err(_) => {
266+ out.push(b'%');
267+ i += 1;
268+ }
269+ }
270+ }
271+ byte => {
272+ out.push(byte);
273+ i += 1;
274+ }
275+ }
276+ }
277+ String::from_utf8_lossy(&out).into_owned()
278+}
279+
280+fn random_b64(bytes: usize) -> String {
281+ let mut buf = vec![0u8; bytes];
282+ rand::rng().fill_bytes(&mut buf);
283+ b64url.encode(buf)
284+}
285+
286+/// Sends the browser to im's `/authorize` with a fresh PKCE pair.
287+#[route(GET "/auth/login")]
288+async fn im_login(cx: &Cx) -> Result<Response, topcoat::Error> {
289+ let state = client(cx);
290+ let query = topcoat::router::request::uri(cx)
291+ .query()
292+ .unwrap_or("")
293+ .to_string();
294+ let next = safe_next(query_value(&query, "next").as_deref().unwrap_or("/")).to_string();
295+
296+ let flight = InFlight {
297+ verifier: random_b64(32),
298+ state: random_b64(16),
299+ nonce: random_b64(16),
300+ next,
301+ exp: OffsetDateTime::now_utc().unix_timestamp() + IN_FLIGHT_MINUTES * 60,
302+ };
303+ let challenge = b64url.encode(Sha256::digest(flight.verifier.as_bytes()));
304+ let cookie_name = format!("{}_pkce", state.config.cookie_name);
305+ app_cookies(cx).add(cookie! {
306+ cookie_name = seal_json(&state.config.cookie_key, &flight);
307+ Path = "/";
308+ HttpOnly;
309+ SameSite = Lax;
310+ MaxAge = time::Duration::minutes(IN_FLIGHT_MINUTES)
311+ });
312+
313+ let url = format!(
314+ "{}/authorize?response_type=code&client_id={}&redirect_uri={}&scope=openid%20profile%20email&state={}&nonce={}&code_challenge={}&code_challenge_method=S256",
315+ state.config.issuer,
316+ state.config.client_id,
317+ urlencoded(&state.config.redirect_uri),
318+ flight.state,
319+ flight.nonce,
320+ challenge,
321+ );
322+ see(cx, &url)
323+}
324+
325+/// im's answer lands here: exchange the code, validate the id_token, mint
326+/// the app session.
327+#[route(GET "/auth/callback")]
328+async fn im_callback(cx: &Cx) -> Result<Response, topcoat::Error> {
329+ let state = client(cx);
330+ let query = topcoat::router::request::uri(cx)
331+ .query()
332+ .unwrap_or("")
333+ .to_string();
334+ if let Some(error) = query_value(&query, "error") {
335+ return see(cx, &format!("/?auth_error={error}"));
336+ }
337+ let (Some(code), Some(presented_state)) =
338+ (query_value(&query, "code"), query_value(&query, "state"))
339+ else {
340+ return see(cx, "/?auth_error=invalid_request");
341+ };
342+ let cookie_name = format!("{}_pkce", state.config.cookie_name);
343+ let flight: Option<InFlight> = cookies(cx)
344+ .get(&cookie_name)
345+ .and_then(|c| open_json(&state.config.cookie_key, c.value()));
346+ let Some(flight) = flight else {
347+ return see(cx, "/?auth_error=invalid_request");
348+ };
349+ clear_cookie(cx, &cookie_name);
350+ if flight.exp <= OffsetDateTime::now_utc().unix_timestamp()
351+ || flight
352+ .state
353+ .as_bytes()
354+ .ct_eq(presented_state.as_bytes())
355+ .unwrap_u8()
356+ != 1
357+ {
358+ return see(cx, "/?auth_error=invalid_state");
359+ }
360+
361+ match exchange_code(state, &code, &flight).await {
362+ Ok(session) => {
363+ set_session_cookie(cx, state, &session);
364+ see(cx, &flight.next)
365+ }
366+ Err(_) => see(cx, "/?auth_error=exchange_failed"),
367+ }
368+}
369+
370+/// Signs out of the app only. To end the central session too, post to im's
371+/// `/logout` — a link there is a silent re-login, by design.
372+#[route(GET "/auth/logout")]
373+async fn im_logout(cx: &Cx) -> Result<Response, topcoat::Error> {
374+ clear_cookie(cx, &client(cx).config.cookie_name);
375+ see(cx, "/")
376+}
377+
378+fn urlencoded(raw: &str) -> String {
379+ let mut out = String::with_capacity(raw.len());
380+ for byte in raw.bytes() {
381+ match byte {
382+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
383+ out.push(byte as char)
384+ }
385+ _ => out.push_str(&format!("%{byte:02X}")),
386+ }
387+ }
388+ out
389+}
390+
391+// ---------------------------------------------------------------------------
392+// Token exchange, refresh, validation
393+// ---------------------------------------------------------------------------
394+
395+#[derive(Deserialize)]
396+struct TokenAnswer {
397+ /// Present on the wire; the app reads identity from the id_token and
398+ /// never calls userinfo, so the access token is carried, not used.
399+ #[serde(rename = "access_token")]
400+ _access_token: String,
401+ refresh_token: String,
402+ id_token: String,
403+ expires_in: i64,
404+}
405+
406+async fn exchange_code(state: &ImClient, code: &str, flight: &InFlight) -> Result<Session> {
407+ let answer: TokenAnswer = state
408+ .http
409+ .post(format!("{}/token", state.config.issuer))
410+ .form(&[
411+ ("grant_type", "authorization_code"),
412+ ("code", code),
413+ ("redirect_uri", &state.config.redirect_uri),
414+ ("client_id", &state.config.client_id),
415+ ("client_secret", &state.config.client_secret),
416+ ("code_verifier", &flight.verifier),
417+ ])
418+ .send()
419+ .await
420+ .map_err(|e| Error::Http(e.to_string()))?
421+ .error_for_status()
422+ .map_err(|e| Error::Refused(e.to_string()))?
423+ .json()
424+ .await
425+ .map_err(|e| Error::Http(e.to_string()))?;
426+ let claims = validate_id_token(state, &answer.id_token).await?;
427+ if claims["nonce"].as_str() != Some(flight.nonce.as_str()) {
428+ return Err(Error::Token("nonce mismatch".into()));
429+ }
430+ Ok(session_from(&answer, claims))
431+}
432+
433+async fn refresh(cx: &Cx, state: &ImClient, session: &mut Session) -> Result<()> {
434+ let _ = cx;
435+ let answer: TokenAnswer = state
436+ .http
437+ .post(format!("{}/token", state.config.issuer))
438+ .form(&[
439+ ("grant_type", "refresh_token"),
440+ ("refresh_token", &session.refresh_token),
441+ ("client_id", &state.config.client_id),
442+ ("client_secret", &state.config.client_secret),
443+ ])
444+ .send()
445+ .await
446+ .map_err(|e| Error::Http(e.to_string()))?
447+ .error_for_status()
448+ .map_err(|e| Error::Refused(e.to_string()))?
449+ .json()
450+ .await
451+ .map_err(|e| Error::Http(e.to_string()))?;
452+ let claims = validate_id_token(state, &answer.id_token).await?;
453+ *session = session_from(&answer, claims);
454+ Ok(())
455+}
456+
457+fn session_from(answer: &TokenAnswer, claims: serde_json::Value) -> Session {
458+ Session {
459+ user: User {
460+ sub: claims["sub"].as_str().unwrap_or_default().to_string(),
461+ email: claims["email"].as_str().unwrap_or_default().to_string(),
462+ name: claims["name"].as_str().unwrap_or_default().to_string(),
463+ },
464+ refresh_token: answer.refresh_token.clone(),
465+ access_exp: OffsetDateTime::now_utc().unix_timestamp() + answer.expires_in,
466+ }
467+}
468+
469+/// Validates an id_token: RS256 against im's JWKS, issuer, audience, expiry.
470+/// The nonce is the caller's to check (only the callback holds one).
471+async fn validate_id_token(state: &ImClient, token: &str) -> Result<serde_json::Value> {
472+ let parts: Vec<&str> = token.split('.').collect();
473+ if parts.len() != 3 {
474+ return Err(Error::Token("not a compact JWT".into()));
475+ }
476+ let header: serde_json::Value = serde_json::from_slice(
477+ &b64url
478+ .decode(parts[0])
479+ .map_err(|e| Error::Token(e.to_string()))?,
480+ )
481+ .map_err(|e| Error::Token(e.to_string()))?;
482+ if header["alg"] != "RS256" {
483+ return Err(Error::Token("unexpected alg".into()));
484+ }
485+ let kid = header["kid"]
486+ .as_str()
487+ .ok_or_else(|| Error::Token("no kid".into()))?
488+ .to_string();
489+
490+ if jwks_stale(state).await {
491+ refetch_jwks(state).await?;
492+ }
493+ let key = match cached_key(state, &kid).await {
494+ Some(key) => key,
495+ None => {
496+ refetch_jwks(state).await?;
497+ cached_key(state, &kid)
498+ .await
499+ .ok_or_else(|| Error::Token("unknown kid after refetch".into()))?
500+ }
501+ };
502+
503+ verify_claims(&parts, &key, &state.config.issuer, &state.config.client_id)
504+}
505+
506+/// The pure half of [`validate_id_token`]: signature, issuer, audience,
507+/// expiry. Split out so the test suite signs its own tokens without standing
508+/// a server up.
509+fn verify_claims(
510+ parts: &[&str],
511+ key: &rsa::RsaPublicKey,
512+ issuer: &str,
513+ client_id: &str,
514+) -> Result<serde_json::Value> {
515+ use rsa::signature::Verifier;
516+ let signature_bytes = b64url
517+ .decode(parts[2])
518+ .map_err(|e| Error::Token(e.to_string()))?;
519+ let signature = rsa::pkcs1v15::Signature::try_from(signature_bytes.as_slice())
520+ .map_err(|e| Error::Token(e.to_string()))?;
521+ let verifying = rsa::pkcs1v15::VerifyingKey::<sha2_for_rsa::Sha256>::new(key.clone());
522+ verifying
523+ .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature)
524+ .map_err(|_| Error::Token("bad signature".into()))?;
525+
526+ let claims: serde_json::Value = serde_json::from_slice(
527+ &b64url
528+ .decode(parts[1])
529+ .map_err(|e| Error::Token(e.to_string()))?,
530+ )
531+ .map_err(|e| Error::Token(e.to_string()))?;
532+ if claims["iss"].as_str() != Some(issuer) {
533+ return Err(Error::Token("wrong issuer".into()));
534+ }
535+ if claims["aud"].as_str() != Some(client_id) {
536+ return Err(Error::Token("wrong audience".into()));
537+ }
538+ match claims["exp"].as_i64() {
539+ Some(exp) if exp > OffsetDateTime::now_utc().unix_timestamp() => {}
540+ _ => return Err(Error::Token("expired".into())),
541+ }
542+ Ok(claims)
543+}
544+
545+async fn cached_key(state: &ImClient, kid: &str) -> Option<rsa::RsaPublicKey> {
546+ state
547+ .jwks
548+ .read()
549+ .await
550+ .as_ref()?
551+ .keys
552+ .iter()
553+ .find(|(k, _)| k == kid)
554+ .map(|(_, key)| key.clone())
555+}
556+
557+/// Fetches and caches im's JWKS. Cached for an hour at most; an unknown kid
558+/// forces an immediate refetch above.
559+async fn refetch_jwks(state: &ImClient) -> Result<()> {
560+ let doc: serde_json::Value = state
561+ .http
562+ .get(format!("{}/jwks.json", state.config.issuer))
563+ .send()
564+ .await
565+ .map_err(|e| Error::Http(e.to_string()))?
566+ .error_for_status()
567+ .map_err(|e| Error::Refused(e.to_string()))?
568+ .json()
569+ .await
570+ .map_err(|e| Error::Http(e.to_string()))?;
571+ let mut keys = Vec::new();
572+ for jwk in doc["keys"].as_array().into_iter().flatten() {
573+ let (Some(kid), Some(n), Some(e)) =
574+ (jwk["kid"].as_str(), jwk["n"].as_str(), jwk["e"].as_str())
575+ else {
576+ continue;
577+ };
578+ let (Ok(n), Ok(e)) = (b64url.decode(n), b64url.decode(e)) else {
579+ continue;
580+ };
581+ let key = rsa::RsaPublicKey::new(
582+ rsa::BigUint::from_bytes_be(&n),
583+ rsa::BigUint::from_bytes_be(&e),
584+ )
585+ .map_err(|err| Error::Token(format!("bad jwk {kid}: {err}")))?;
586+ keys.push((kid.to_string(), key));
587+ }
588+ *state.jwks.write().await = Some(JwksCache {
589+ fetched_at: OffsetDateTime::now_utc(),
590+ keys,
591+ });
592+ Ok(())
593+}
594+
595+#[cfg(test)]
596+mod tests {
597+ use super::*;
598+ use rsa::signature::{SignatureEncoding, Signer};
599+
600+ fn keypair() -> (rsa::RsaPrivateKey, rsa::RsaPublicKey) {
601+ // 2048-bit generation is slow for a unit test; 1024 is the smallest
602+ // rsa 0.9 accepts and the signature math under test is identical.
603+ let private = rsa::RsaPrivateKey::new(&mut rand_core06::OsRng, 1024).unwrap();
604+ let public = private.to_public_key();
605+ (private, public)
606+ }
607+
608+ fn sign(claims: serde_json::Value, key: &rsa::RsaPrivateKey) -> String {
609+ let header = serde_json::json!({"alg": "RS256", "typ": "JWT", "kid": "test"});
610+ let mut out = b64url.encode(header.to_string());
611+ out.push('.');
612+ out.push_str(&b64url.encode(claims.to_string()));
613+ let signing = rsa::pkcs1v15::SigningKey::<sha2_for_rsa::Sha256>::new(key.clone());
614+ let signature = signing.sign(out.as_bytes());
615+ format!("{}.{}", out, b64url.encode(signature.to_bytes()))
616+ }
617+
618+ fn good_claims() -> serde_json::Value {
619+ serde_json::json!({
620+ "iss": "http://im.test",
621+ "sub": "user-1",
622+ "aud": "client-1",
623+ "exp": OffsetDateTime::now_utc().unix_timestamp() + 600,
624+ "iat": OffsetDateTime::now_utc().unix_timestamp(),
625+ "email": "ann@example.com",
626+ "name": "Ann",
627+ })
628+ }
629+
630+ #[test]
631+ fn valid_token_validates() {
632+ let (private, public) = keypair();
633+ let token = sign(good_claims(), &private);
634+ let parts: Vec<&str> = token.split('.').collect();
635+ let claims = verify_claims(&parts, &public, "http://im.test", "client-1").unwrap();
636+ assert_eq!(claims["sub"], "user-1");
637+ }
638+
639+ #[test]
640+ fn tampered_payload_rejected() {
641+ let (private, public) = keypair();
642+ let token = sign(good_claims(), &private);
643+ let parts: Vec<&str> = token.split('.').collect();
644+ let forged_payload = b64url.encode(r#"{"sub":"mallory"}"#);
645+ let forged = vec![parts[0], forged_payload.as_str(), parts[2]];
646+ assert!(verify_claims(&forged, &public, "http://im.test", "client-1").is_err());
647+ }
648+
649+ #[test]
650+ fn wrong_key_rejected() {
651+ let (private, _) = keypair();
652+ let (_, other_public) = keypair();
653+ let token = sign(good_claims(), &private);
654+ let parts: Vec<&str> = token.split('.').collect();
655+ assert!(verify_claims(&parts, &other_public, "http://im.test", "client-1").is_err());
656+ }
657+
658+ #[test]
659+ fn wrong_audience_rejected() {
660+ let (private, public) = keypair();
661+ let token = sign(good_claims(), &private);
662+ let parts: Vec<&str> = token.split('.').collect();
663+ assert!(verify_claims(&parts, &public, "http://im.test", "another-app").is_err());
664+ }
665+
666+ #[test]
667+ fn wrong_issuer_rejected() {
668+ let (private, public) = keypair();
669+ let token = sign(good_claims(), &private);
670+ let parts: Vec<&str> = token.split('.').collect();
671+ assert!(verify_claims(&parts, &public, "https://elsewhere.example", "client-1").is_err());
672+ }
673+
674+ #[test]
675+ fn expired_rejected() {
676+ let (private, public) = keypair();
677+ let mut claims = good_claims();
678+ claims["exp"] = (OffsetDateTime::now_utc().unix_timestamp() - 10).into();
679+ let token = sign(claims, &private);
680+ let parts: Vec<&str> = token.split('.').collect();
681+ assert!(verify_claims(&parts, &public, "http://im.test", "client-1").is_err());
682+ }
683+
684+ #[test]
685+ fn pkce_rfc7636_vector() {
686+ // RFC 7636 Appendix B.
687+ let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
688+ let challenge = b64url.encode(Sha256::digest(verifier.as_bytes()));
689+ assert_eq!(challenge, "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM");
690+ }
691+
692+ #[test]
693+ fn cookie_seal_roundtrip() {
694+ let key = [7u8; 32];
695+ let session = Session {
696+ user: User {
697+ sub: "u".into(),
698+ email: "e".into(),
699+ name: "n".into(),
700+ },
701+ refresh_token: "r".into(),
702+ access_exp: 1,
703+ };
704+ let sealed = seal_json(&key, &session);
705+ let back: Session = open_json(&key, &sealed).unwrap();
706+ assert_eq!(back.refresh_token, "r");
707+ assert!(open_json::<Session>(&[8u8; 32], &sealed).is_none());
708+ assert!(open_json::<Session>(&key, "garbage").is_none());
709+ }
710+}
crates/im-core/Cargo.tomladded+58 -0
@@ -0,0 +1,58 @@
1+[package]
2+name = "im-core"
3+version.workspace = true
4+edition.workspace = true
5+license.workspace = true
6+repository.workspace = true
7+description = "im domain model and storage: users, invites, sessions, OIDC material"
8+
9+[features]
10+# The domain vocabulary (record shapes, id wrappers) compiles anywhere.
11+# Everything that touches a database, a password or a CSPRNG lives behind
12+# `server` (same contract as izlek-core).
13+default = ["server"]
14+server = [
15+ "dep:argon2",
16+ "dep:base64",
17+ "dep:chacha20poly1305",
18+ "dep:data-encoding",
19+ "dep:hmac",
20+ "dep:rand",
21+ "dep:rand_core",
22+ "dep:rsa",
23+ "dep:sha1",
24+ "dep:sha2",
25+ "dep:sha2-for-rsa",
26+ "dep:subtle",
27+ "dep:tokio",
28+ "dep:turso",
29+ "dep:ulid",
30+]
31+
32+[dependencies]
33+argon2 = { workspace = true, optional = true }
34+base64 = { workspace = true, optional = true }
35+chacha20poly1305 = { workspace = true, optional = true }
36+data-encoding = { version = "2.11.1", optional = true }
37+hmac = { version = "0.13.0", optional = true }
38+rand = { workspace = true, optional = true }
39+# rsa 0.9 sits on the rand_core 0.6 / digest 0.10 trait lines, so its RNG
40+# and its hasher come from those lines, not the workspace's rand 0.10 /
41+# sha2 0.11. sha2 0.11 stays for token digests.
42+rand_core = { version = "0.6.4", features = ["getrandom"], optional = true }
43+rsa = { version = "0.9.10", optional = true }
44+sha1 = { version = "0.11.0", optional = true }
45+sha2 = { workspace = true, optional = true }
46+sha2-for-rsa = { package = "sha2", version = "0.10", features = ["oid"], optional = true }
47+subtle = { workspace = true, optional = true }
48+serde.workspace = true
49+serde_json.workspace = true
50+thiserror.workspace = true
51+time.workspace = true
52+tokio = { workspace = true, optional = true }
53+turso = { workspace = true, optional = true }
54+ulid = { workspace = true, optional = true }
55+
56+[dev-dependencies]
57+tokio.workspace = true
58+tempfile = "3"
crates/im-core/src/accounts.rsadded+510 -0
@@ -0,0 +1,510 @@
1+//! Accounts: passwords, invites, and the rules around them. Ported from
2+//! izlek-core's `auth.rs`/`accounts.rs` — same product family, same author.
3+//!
4+//! Two different jobs, deliberately kept apart:
5+//!
6+//! * **Passwords** are low-entropy and chosen by a person, so they go through
7+//! Argon2id with deliberately expensive parameters.
8+//! * **Tokens** — invites, session cookies, client secrets, auth codes — are
9+//! 256 bits from a CSPRNG. There is nothing to brute-force, so they are
10+//! stored as a plain SHA-256 digest.
11+
12+use argon2::password_hash::phc::PasswordHash;
13+use argon2::password_hash::{PasswordHasher, PasswordVerifier};
14+use argon2::{Algorithm, Argon2, Params, Version};
15+use base64::Engine;
16+use base64::engine::general_purpose::URL_SAFE_NO_PAD as base64url;
17+use rand::Rng;
18+use serde::{Deserialize, Serialize};
19+use sha2::{Digest, Sha256};
20+use subtle::ConstantTimeEq;
21+
22+use crate::model::{Invite, User, UserId};
23+use crate::store::{self, Result, Store, StoreError, backend};
24+
25+/// Argon2id at the OWASP Password Storage Cheat Sheet's recommended second
26+/// configuration: 19 MiB of memory, two iterations, one lane.
27+pub const ARGON2_MEMORY_KIB: u32 = 19 * 1024;
28+pub const ARGON2_ITERATIONS: u32 = 2;
29+pub const ARGON2_PARALLELISM: u32 = 1;
30+
31+/// How many bytes of randomness every token carries.
32+pub const TOKEN_BYTES: usize = 32;
33+
34+/// The shortest password this service accepts.
35+///
36+/// Named because the form that takes a new password carries it too — as
37+/// `minlength`, so the browser enforces the rule where it is being broken
38+/// rather than the server explaining it afterwards. Two places, one number.
39+pub const MIN_PASSWORD_CHARS: usize = 10;
40+
41+/// How long an invite stays valid.
42+pub const INVITE_DAYS: i64 = 7;
43+
44+/// A password rule the person's choice broke. The wording is the wording on
45+/// the invite-acceptance screen.
46+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
47+pub enum PasswordProblem {
48+ #[error("at least 10 characters")]
49+ TooShort,
50+ #[error("not your address or your name")]
51+ LooksLikeYou,
52+ /// The "new" password is the one already in force — the walk-away
53+ /// mistake, refused by name rather than silently succeeding.
54+ #[error("that's your current password")]
55+ IsCurrent,
56+}
57+
58+#[derive(Debug, thiserror::Error)]
59+pub enum AccountError {
60+ #[error("database: {0}")]
61+ Backend(String),
62+ #[error("wrong email or password")]
63+ InvalidCredentials,
64+ #[error("this invite is not valid")]
65+ InviteInvalid,
66+ #[error("this invite has expired")]
67+ InviteExpired,
68+ #[error("this invite was already used")]
69+ InviteSpent,
70+ #[error("an account with this address already exists")]
71+ EmailTaken,
72+ #[error("password: {0}")]
73+ Password(#[from] PasswordProblem),
74+ #[error("password hashing failed: {0}")]
75+ Hashing(String),
76+}
77+
78+impl From<StoreError> for AccountError {
79+ fn from(e: StoreError) -> Self {
80+ AccountError::Backend(e.to_string())
81+ }
82+}
83+
84+fn argon2() -> Argon2<'static> {
85+ let params = Params::new(
86+ ARGON2_MEMORY_KIB,
87+ ARGON2_ITERATIONS,
88+ ARGON2_PARALLELISM,
89+ None,
90+ )
91+ .expect("argon2 parameters are constants and are in range");
92+ Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
93+}
94+
95+/// Hashes a password into a PHC string, salt included.
96+pub fn hash_password(password: &str) -> std::result::Result<String, AccountError> {
97+ argon2()
98+ .hash_password(password.as_bytes())
99+ .map(|h| h.to_string())
100+ .map_err(|e| AccountError::Hashing(e.to_string()))
101+}
102+
103+/// Checks a password against a stored PHC string.
104+///
105+/// The parameters come from the stored hash, not from [`argon2`], so raising
106+/// the cost later does not lock anyone out — and hashes migrated from İzlek
107+/// verify unchanged.
108+pub fn verify_password(password: &str, phc: &str) -> bool {
109+ match PasswordHash::new(phc) {
110+ Ok(parsed) => argon2()
111+ .verify_password(password.as_bytes(), &parsed)
112+ .is_ok(),
113+ Err(_) => false,
114+ }
115+}
116+
117+/// A PHC string for a password nobody knows, used to keep the miss path as
118+/// expensive as the hit path.
119+///
120+/// Without this, "no such address" answers before Argon2 would have finished
121+/// and the response time tells an attacker what the wording refuses to.
122+pub fn dummy_password_hash() -> &'static str {
123+ // Minted once over 256 bits of randomness that was never written down.
124+ "$argon2id$v=19$m=19456,t=2,p=1$0JjUMrLBpJG7lzg5bxZhMQ$iGpGXBNDAaHV9jqDxDcCyuIEIV33kJ1IAPt0XCh753Q"
125+}
126+
127+/// Burns the same work a real verify would, and always fails.
128+///
129+/// Call this on every path where a lookup missed, before answering.
130+pub fn dummy_verify(password: &str) {
131+ let _ = verify_password(password, dummy_password_hash());
132+}
133+
134+/// A freshly minted secret. The plaintext exists only here and in the one
135+/// place that shows it; the database gets [`Token::hash`].
136+#[derive(Clone)]
137+pub struct Token {
138+ plaintext: String,
139+}
140+
141+impl Token {
142+ /// 256 bits from the thread CSPRNG, base64url-no-pad encoded.
143+ pub fn mint() -> Self {
144+ let mut bytes = [0u8; TOKEN_BYTES];
145+ rand::rng().fill_bytes(&mut bytes);
146+ Self {
147+ plaintext: base64url.encode(bytes),
148+ }
149+ }
150+
151+ /// The value that goes in the link or the cookie. Shown exactly once.
152+ pub fn expose(&self) -> &str {
153+ &self.plaintext
154+ }
155+
156+ /// The value that goes in the database.
157+ pub fn hash(&self) -> String {
158+ hash_token(&self.plaintext)
159+ }
160+}
161+
162+impl std::fmt::Debug for Token {
163+ /// A token must not reach a log through a stray `{:?}`.
164+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165+ f.write_str("Token(redacted)")
166+ }
167+}
168+
169+/// SHA-256 of a token, hex encoded. Tokens are full-entropy, so a fast digest
170+/// is the right primitive here.
171+pub fn hash_token(plaintext: &str) -> String {
172+ let mut hasher = Sha256::new();
173+ hasher.update(plaintext.as_bytes());
174+ hex(&hasher.finalize())
175+}
176+
177+/// Compares two token digests without leaking where they diverge.
178+pub fn digests_match(a: &str, b: &str) -> bool {
179+ a.as_bytes().ct_eq(b.as_bytes()).into()
180+}
181+
182+pub(crate) fn hex(bytes: &[u8]) -> String {
183+ let mut out = String::with_capacity(bytes.len() * 2);
184+ for byte in bytes {
185+ out.push_str(&format!("{byte:02x}"));
186+ }
187+ out
188+}
189+
190+/// The rules the invite-acceptance screen states, checked server-side.
191+pub fn check_password(
192+ password: &str,
193+ email: &str,
194+ display_name: &str,
195+) -> std::result::Result<(), PasswordProblem> {
196+ // Counted in characters, not bytes: a ten-character password is ten
197+ // characters whatever alphabet it is in.
198+ if password.chars().count() < MIN_PASSWORD_CHARS {
199+ return Err(PasswordProblem::TooShort);
200+ }
201+
202+ let folded = password.to_lowercase();
203+ let local_part = email.split('@').next().unwrap_or(email);
204+ let mut forbidden = vec![email.to_lowercase(), local_part.to_lowercase()];
205+ forbidden.extend(
206+ display_name
207+ .split_whitespace()
208+ .map(|word| word.to_lowercase()),
209+ );
210+ for needle in forbidden {
211+ // Short words ("de", "van") would forbid too much to be useful.
212+ if needle.chars().count() >= 3 && folded.contains(&needle) {
213+ return Err(PasswordProblem::LooksLikeYou);
214+ }
215+ }
216+ Ok(())
217+}
218+
219+// ---------------------------------------------------------------------------
220+// Invites and users
221+// ---------------------------------------------------------------------------
222+
223+/// Creates an invite for `email`, returning the raw token to put in the mail.
224+/// The row holds only its digest.
225+pub async fn create_invite(
226+ store: &Store,
227+ email: &str,
228+ invited_by: Option<UserId>,
229+) -> std::result::Result<Token, AccountError> {
230+ let token = Token::mint();
231+ let now = store::now();
232+ let expires = now + time::Duration::days(INVITE_DAYS);
233+ store
234+ .conn
235+ .execute(
236+ "INSERT INTO invites (token, email, invited_by, created_at, expires_at) \
237+ VALUES (?1, ?2, ?3, ?4, ?5)",
238+ turso::params![
239+ token.hash(),
240+ email,
241+ invited_by.map(|id| id.to_string()),
242+ store::stamp(now)?,
243+ store::stamp(expires)?,
244+ ],
245+ )
246+ .await
247+ .map_err(backend)?;
248+ Ok(token)
249+}
250+
251+/// Looks an invite up by its raw token. Expiry and spent-ness are the
252+/// caller's to rule on — this answers what the row says.
253+pub async fn invite_by_token(store: &Store, token: &str) -> Result<Option<Invite>> {
254+ let mut rows = store
255+ .conn
256+ .query(
257+ "SELECT email, invited_by, created_at, expires_at, accepted_at \
258+ FROM invites WHERE token = ?1",
259+ turso::params![hash_token(token)],
260+ )
261+ .await
262+ .map_err(backend)?;
263+ let Some(row) = rows.next().await.map_err(backend)? else {
264+ return Ok(None);
265+ };
266+ Ok(Some(Invite {
267+ email: store::text(&row, 0)?,
268+ invited_by: store::opt_text(&row, 1)?.map(UserId::from),
269+ created_at: store::parse_stamp(&store::text(&row, 2)?)?,
270+ expires_at: store::parse_stamp(&store::text(&row, 3)?)?,
271+ accepted_at: match store::opt_text(&row, 4)? {
272+ Some(raw) => Some(store::parse_stamp(&raw)?),
273+ None => None,
274+ },
275+ }))
276+}
277+
278+/// Turns a valid invite into a user. The invite is marked accepted in the
279+/// same transaction as the user insert, so a token can never mint two
280+/// accounts.
281+pub async fn create_user_from_invite(
282+ store: &Store,
283+ token: &str,
284+ name: &str,
285+ password: &str,
286+) -> std::result::Result<User, AccountError> {
287+ let invite = invite_by_token(store, token)
288+ .await?
289+ .ok_or(AccountError::InviteInvalid)?;
290+ if invite.accepted_at.is_some() {
291+ return Err(AccountError::InviteSpent);
292+ }
293+ if invite.expires_at < store::now() {
294+ return Err(AccountError::InviteExpired);
295+ }
296+ check_password(password, &invite.email, name)?;
297+ let user = User {
298+ id: UserId::mint(),
299+ email: invite.email.clone(),
300+ name: name.to_string(),
301+ totp_confirmed: false,
302+ disabled: false,
303+ created_at: store::now(),
304+ };
305+ let password_hash = hash_password(password)?;
306+
307+ store
308+ .conn
309+ .execute("BEGIN IMMEDIATE", ())
310+ .await
311+ .map_err(backend)?;
312+ let outcome = async {
313+ store
314+ .conn
315+ .execute(
316+ "INSERT INTO users (id, email, name, password_hash, created_at) \
317+ VALUES (?1, ?2, ?3, ?4, ?5)",
318+ turso::params![
319+ user.id.to_string(),
320+ user.email.clone(),
321+ user.name.clone(),
322+ password_hash,
323+ store::stamp(user.created_at)?,
324+ ],
325+ )
326+ .await
327+ .map_err(|e| {
328+ let text = e.to_string().to_lowercase();
329+ if text.contains("constraint") || text.contains("unique") {
330+ AccountError::EmailTaken
331+ } else {
332+ AccountError::Backend(e.to_string())
333+ }
334+ })?;
335+ store
336+ .conn
337+ .execute(
338+ "UPDATE invites SET accepted_at = ?1 WHERE token = ?2 AND accepted_at IS NULL",
339+ turso::params![store::stamp(store::now())?, hash_token(token)],
340+ )
341+ .await
342+ .map_err(|e| AccountError::Backend(e.to_string()))?;
343+ Ok::<_, AccountError>(())
344+ }
345+ .await;
346+ match outcome {
347+ Ok(()) => {
348+ store.conn.execute("COMMIT", ()).await.map_err(backend)?;
349+ Ok(user)
350+ }
351+ Err(e) => {
352+ let _ = store.conn.execute("ROLLBACK", ()).await;
353+ Err(e)
354+ }
355+ }
356+}
357+
358+/// Verifies an email+password pair, returning the user on success. Disabled
359+/// accounts are refused with the same wording as a wrong password, and every
360+/// miss path burns an Argon2 run so timing does not say which one it was.
361+pub async fn verify_login(
362+ store: &Store,
363+ email: &str,
364+ password: &str,
365+) -> std::result::Result<User, AccountError> {
366+ let mut rows = store
367+ .conn
368+ .query(
369+ "SELECT id, email, name, password_hash, totp_confirmed, disabled, created_at \
370+ FROM users WHERE email = ?1 COLLATE NOCASE",
371+ turso::params![email],
372+ )
373+ .await
374+ .map_err(backend)?;
375+ let Some(row) = rows.next().await.map_err(backend)? else {
376+ dummy_verify(password);
377+ return Err(AccountError::InvalidCredentials);
378+ };
379+ let user = User {
380+ id: UserId::from(store::text(&row, 0)?),
381+ email: store::text(&row, 1)?,
382+ name: store::text(&row, 2)?,
383+ totp_confirmed: store::int(&row, 4)? != 0,
384+ disabled: store::int(&row, 5)? != 0,
385+ created_at: store::parse_stamp(&store::text(&row, 6)?)?,
386+ };
387+ let phc = store::text(&row, 3)?;
388+ if !verify_password(password, &phc) || user.disabled {
389+ return Err(AccountError::InvalidCredentials);
390+ }
391+ Ok(user)
392+}
393+
394+/// Looks a user up by id — what sessions and tokens resolve to.
395+pub async fn user_by_id(store: &Store, id: &UserId) -> Result<Option<User>> {
396+ let mut rows = store
397+ .conn
398+ .query(
399+ "SELECT id, email, name, totp_confirmed, disabled, created_at \
400+ FROM users WHERE id = ?1",
401+ turso::params![id.to_string()],
402+ )
403+ .await
404+ .map_err(backend)?;
405+ let Some(row) = rows.next().await.map_err(backend)? else {
406+ return Ok(None);
407+ };
408+ Ok(Some(User {
409+ id: UserId::from(store::text(&row, 0)?),
410+ email: store::text(&row, 1)?,
411+ name: store::text(&row, 2)?,
412+ totp_confirmed: store::int(&row, 3)? != 0,
413+ disabled: store::int(&row, 4)? != 0,
414+ created_at: store::parse_stamp(&store::text(&row, 5)?)?,
415+ }))
416+}
417+
418+#[cfg(test)]
419+mod tests {
420+ use super::*;
421+
422+ async fn fixture() -> Store {
423+ Store::open(Path::new(":memory:")).await.unwrap()
424+ }
425+
426+ use std::path::Path;
427+
428+ #[test]
429+ fn password_roundtrip() {
430+ let phc = hash_password("correct horse battery staple").unwrap();
431+ assert!(verify_password("correct horse battery staple", &phc));
432+ assert!(!verify_password("wrong horse battery staple", &phc));
433+ }
434+
435+ #[test]
436+ fn password_rules() {
437+ assert_eq!(
438+ check_password("short", "a@b.c", "Ann"),
439+ Err(PasswordProblem::TooShort)
440+ );
441+ assert_eq!(
442+ check_password("ann.smith-99", "ann.smith@x.y", "Ann Smith"),
443+ Err(PasswordProblem::LooksLikeYou)
444+ );
445+ assert!(check_password("tDLr9!mZQ2xv", "ann.smith@x.y", "Ann Smith").is_ok());
446+ }
447+
448+ #[test]
449+ fn token_hash_is_not_the_token() {
450+ let token = Token::mint();
451+ assert_ne!(token.expose(), token.hash());
452+ assert_eq!(token.hash().len(), 64, "sha256 hex");
453+ }
454+
455+ #[tokio::test]
456+ async fn invite_to_user_to_login() {
457+ let store = fixture().await;
458+ let token = create_invite(&store, "ann@example.com", None)
459+ .await
460+ .unwrap();
461+ let invite = invite_by_token(&store, token.expose())
462+ .await
463+ .unwrap()
464+ .unwrap();
465+ assert_eq!(invite.email, "ann@example.com");
466+ assert!(invite.accepted_at.is_none());
467+
468+ let user = create_user_from_invite(&store, token.expose(), "Ann", "tDLr9!mZQ2xv")
469+ .await
470+ .unwrap();
471+ assert_eq!(user.email, "ann@example.com");
472+
473+ // The invite is spent: a second use is refused.
474+ assert!(matches!(
475+ create_user_from_invite(&store, token.expose(), "Ann", "tDLr9!mZQ2xv").await,
476+ Err(AccountError::InviteSpent)
477+ ));
478+
479+ let logged = verify_login(&store, "ANN@example.com", "tDLr9!mZQ2xv")
480+ .await
481+ .unwrap();
482+ assert_eq!(logged.id, user.id);
483+ assert!(matches!(
484+ verify_login(&store, "ann@example.com", "wrong-password").await,
485+ Err(AccountError::InvalidCredentials)
486+ ));
487+ assert!(matches!(
488+ verify_login(&store, "nobody@example.com", "tDLr9!mZQ2xv").await,
489+ Err(AccountError::InvalidCredentials)
490+ ));
491+ }
492+
493+ #[tokio::test]
494+ async fn duplicate_email_is_refused() {
495+ let store = fixture().await;
496+ let first = create_invite(&store, "ann@example.com", None)
497+ .await
498+ .unwrap();
499+ create_user_from_invite(&store, first.expose(), "Ann", "tDLr9!mZQ2xv")
500+ .await
501+ .unwrap();
502+ let second = create_invite(&store, "ann@example.com", None)
503+ .await
504+ .unwrap();
505+ assert!(matches!(
506+ create_user_from_invite(&store, second.expose(), "Ann Two", "tDLr9!mZQ2xv").await,
507+ Err(AccountError::EmailTaken)
508+ ));
509+ }
510+}
crates/im-core/src/keys.rsadded+156 -0
@@ -0,0 +1,156 @@
1+//! JWT signing keys: RSA-2048 pairs generated on first boot, sealed at rest,
2+//! published as a JWKS.
3+//!
4+//! The private half never leaves this module unsealed: the database holds the
5+//! XChaCha20-Poly1305 envelope of its PKCS#8 DER under `im.key`, and only
6+//! `active_signing_key` (signing) and `jwks` (the public half) cross the
7+//! boundary.
8+use rsa::pkcs8::{DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey};
9+use rsa::traits::PublicKeyParts;
10+use rsa::{RsaPrivateKey, RsaPublicKey};
11+use sha2::Digest;
12+
13+use crate::accounts::hex;
14+use crate::secret;
15+use crate::store::{self, Result, Store, StoreError, backend};
16+
17+/// The active signing key, generating and storing one on first boot.
18+///
19+/// `kid` is a fingerprint of the public half, so a key's id is stable across
20+/// restarts and a JWKS consumer can match header to key without guessing.
21+pub async fn active_signing_key(store: &Store) -> Result<(String, RsaPrivateKey)> {
22+ let mut rows = store
23+ .conn
24+ .query(
25+ "SELECT kid, private_der_enc FROM signing_keys WHERE active = 1 \
26+ ORDER BY created_at DESC LIMIT 1",
27+ (),
28+ )
29+ .await
30+ .map_err(backend)?;
31+ if let Some(row) = rows.next().await.map_err(backend)? {
32+ let kid = store::text(&row, 0)?;
33+ let sealed = store::text(&row, 1)?;
34+ let der = secret::open(store.key(), &sealed)
35+ .ok_or_else(|| StoreError::Corrupt("signing key does not open".into()))?;
36+ let key = RsaPrivateKey::from_pkcs8_der(&der)
37+ .map_err(|e| StoreError::Corrupt(format!("signing key: {e}")))?;
38+ return Ok((kid, key));
39+ }
40+
41+ let mut rng = rand_core::OsRng;
42+ let key = RsaPrivateKey::new(&mut rng, 2048)
43+ .map_err(|e| StoreError::Backend(format!("key generation: {e}")))?;
44+ let public_der = key
45+ .to_public_key()
46+ .to_public_key_der()
47+ .map_err(|e| StoreError::Backend(format!("public der: {e}")))?
48+ .as_bytes()
49+ .to_vec();
50+ let private_der = key
51+ .to_pkcs8_der()
52+ .map_err(|e| StoreError::Backend(format!("private der: {e}")))?
53+ .as_bytes()
54+ .to_vec();
55+ let kid = kid_of(&public_der);
56+ store
57+ .conn
58+ .execute(
59+ "INSERT INTO signing_keys (kid, private_der_enc, public_der, created_at) \
60+ VALUES (?1, ?2, ?3, ?4)",
61+ turso::params![
62+ kid.clone(),
63+ secret::seal(store.key(), &private_der),
64+ public_der,
65+ store::stamp(store::now())?,
66+ ],
67+ )
68+ .await
69+ .map_err(backend)?;
70+ Ok((kid, key))
71+}
72+
73+/// A key id: the first 16 hex of the public half's SHA-256.
74+fn kid_of(public_der: &[u8]) -> String {
75+ hex(&sha2::Sha256::digest(public_der))[..16].to_string()
76+}
77+
78+/// Every active public key as a JWKS document.
79+pub async fn jwks(store: &Store) -> Result<serde_json::Value> {
80+ use base64::Engine;
81+ let mut rows = store
82+ .conn
83+ .query(
84+ "SELECT kid, public_der FROM signing_keys WHERE active = 1 ORDER BY created_at",
85+ (),
86+ )
87+ .await
88+ .map_err(backend)?;
89+ let mut keys = Vec::new();
90+ while let Some(row) = rows.next().await.map_err(backend)? {
91+ let kid = store::text(&row, 0)?;
92+ let der = row.get::<Vec<u8>>(1).map_err(backend)?;
93+ let public = RsaPublicKey::from_public_key_der(&der)
94+ .map_err(|e| StoreError::Corrupt(format!("public key {kid}: {e}")))?;
95+ let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD;
96+ keys.push(serde_json::json!({
97+ "kty": "RSA",
98+ "use": "sig",
99+ "alg": "RS256",
100+ "kid": kid,
101+ "n": b64.encode(public.n().to_bytes_be()),
102+ "e": b64.encode(public.e().to_bytes_be()),
103+ }));
104+ }
105+ Ok(serde_json::json!({ "keys": keys }))
106+}
107+
108+/// The public half of an active key, by id — what JWT verification looks up.
109+pub async fn public_key_by_kid(store: &Store, kid: &str) -> Result<Option<RsaPublicKey>> {
110+ let mut rows = store
111+ .conn
112+ .query(
113+ "SELECT public_der FROM signing_keys WHERE kid = ?1 AND active = 1",
114+ turso::params![kid],
115+ )
116+ .await
117+ .map_err(backend)?;
118+ let Some(row) = rows.next().await.map_err(backend)? else {
119+ return Ok(None);
120+ };
121+ let der = row.get::<Vec<u8>>(0).map_err(backend)?;
122+ RsaPublicKey::from_public_key_der(&der)
123+ .map(Some)
124+ .map_err(|e| StoreError::Corrupt(format!("public key {kid}: {e}")))
125+}
126+
127+#[cfg(test)]
128+mod tests {
129+ use super::*;
130+
131+ #[tokio::test]
132+ async fn key_is_generated_once_and_reopened() {
133+ let dir = tempfile::tempdir().unwrap();
134+ let path = dir.path().join("im.db");
135+ let (kid, first) = {
136+ let store = Store::open(&path).await.unwrap();
137+ let (kid, key) = active_signing_key(&store).await.unwrap();
138+ // A second ask returns the same key rather than generating.
139+ let (kid2, _) = active_signing_key(&store).await.unwrap();
140+ assert_eq!(kid, kid2);
141+ (kid, key)
142+ };
143+ // A fresh store over the same database + im.key opens the same key.
144+ let store = Store::open(&path).await.unwrap();
145+ let (kid2, second) = active_signing_key(&store).await.unwrap();
146+ assert_eq!(kid, kid2);
147+ assert_eq!(first.to_public_key(), second.to_public_key());
148+
149+ let doc = jwks(&store).await.unwrap();
150+ let keys = doc["keys"].as_array().unwrap();
151+ assert_eq!(keys.len(), 1);
152+ assert_eq!(keys[0]["kid"].as_str().unwrap(), kid);
153+ assert_eq!(keys[0]["kty"], "RSA");
154+ assert_eq!(keys[0]["alg"], "RS256");
155+ }
156+}
crates/im-core/src/lib.rsadded+23 -0
@@ -0,0 +1,23 @@
1+//! im-core: domain model and storage for im, the IzlekLab SSO.
2+//!
3+//! `model` is the shared vocabulary (id wrappers, record shapes) and compiles
4+//! anywhere. Everything that touches a database, a password, a signing key or
5+//! a CSPRNG lives behind the `server` feature so none of it can ship to a
6+//! browser bundle — the same contract izlek-core keeps.
7+
8+#[cfg(feature = "server")]
9+pub mod accounts;
10+#[cfg(feature = "server")]
11+pub mod keys;
12+#[cfg(feature = "server")]
13+pub mod oidc;
14+#[cfg(feature = "server")]
15+mod secret;
16+#[cfg(feature = "server")]
17+pub mod sessions;
18+#[cfg(feature = "server")]
19+pub mod store;
20+#[cfg(feature = "server")]
21+pub mod totp;
22+
23+pub mod model;
crates/im-core/src/model.rsadded+100 -0
@@ -0,0 +1,100 @@
1+//! Record shapes shared by every im crate.
2+//!
3+//! No crypto, no database, no CSPRNG here: this module compiles anywhere,
4+//! including a browser bundle. Id wrappers are plain newtypes; minting lives
5+//! behind the `server` feature where `ulid` is available.
6+
7+use serde::{Deserialize, Serialize};
8+use time::OffsetDateTime;
9+
10+macro_rules! id_wrapper {
11+ ($name:ident, $doc:literal) => {
12+ #[doc = $doc]
13+ #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
14+ #[serde(transparent)]
15+ pub struct $name(pub String);
16+
17+ impl $name {
18+ /// A fresh ULID — sortable, URL-safe, unguessable enough for an id.
19+ #[cfg(feature = "server")]
20+ pub fn mint() -> Self {
21+ Self(ulid::Ulid::new().to_string())
22+ }
23+
24+ pub fn as_str(&self) -> &str {
25+ &self.0
26+ }
27+ }
28+
29+ impl std::fmt::Display for $name {
30+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31+ f.write_str(&self.0)
32+ }
33+ }
34+
35+ impl From<String> for $name {
36+ fn from(raw: String) -> Self {
37+ Self(raw)
38+ }
39+ }
40+ };
41+}
42+
43+id_wrapper!(UserId, "A user's id — the OIDC `sub` claim.");
44+id_wrapper!(ClientId, "An OIDC client's id.");
45+
46+/// A registered user. `password_hash` and the TOTP material never leave
47+/// `accounts`/`totp` — this shape is what the rest of the system sees.
48+#[derive(Debug, Clone, Serialize, Deserialize)]
49+pub struct User {
50+ pub id: UserId,
51+ pub email: String,
52+ pub name: String,
53+ pub totp_confirmed: bool,
54+ pub disabled: bool,
55+ pub created_at: OffsetDateTime,
56+}
57+
58+/// An outstanding (or spent) invite, as stored. The raw token exists only in
59+/// the mail that carried it; the row holds its digest.
60+#[derive(Debug, Clone)]
61+pub struct Invite {
62+ pub email: String,
63+ pub invited_by: Option<UserId>,
64+ pub created_at: OffsetDateTime,
65+ pub expires_at: OffsetDateTime,
66+ pub accepted_at: Option<OffsetDateTime>,
67+}
68+
69+/// An OIDC relying party registered with im.
70+#[derive(Debug, Clone)]
71+pub struct OidcClient {
72+ pub client_id: ClientId,
73+ pub name: String,
74+ pub secret_hash: String,
75+ pub redirect_uris: Vec<String>,
76+ pub created_at: OffsetDateTime,
77+}
78+
79+/// An authorization code mid-exchange. Consumed exactly once.
80+#[derive(Debug, Clone)]
81+pub struct AuthCode {
82+ pub client_id: ClientId,
83+ pub user_id: UserId,
84+ pub redirect_uri: String,
85+ pub nonce: Option<String>,
86+ pub code_challenge: String,
87+ /// The central session that minted this code — the refresh token issued
88+ /// off it binds to the same session, so logout kills the chain.
89+ pub session_hash: String,
90+ pub expires_at: OffsetDateTime,
91+}
92+
93+/// A refresh token row, post-lookup.
94+#[derive(Debug, Clone)]
95+pub struct RefreshToken {
96+ pub user_id: UserId,
97+ pub client_id: ClientId,
98+ pub session_hash: String,
99+ pub expires_at: OffsetDateTime,
100+}
crates/im-core/src/oidc.rsadded+552 -0
@@ -0,0 +1,552 @@
1+//! The OIDC provider half: relying-party registration, authorization codes,
2+//! refresh tokens, and the hand-rolled RS256 JWT the endpoints mint.
3+//!
4+//! JWT is hand-rolled on purpose: both ends of the wire are ours, the format
5+//! is `base64url(header).base64url(payload).base64url(signature)` and nothing
6+//! more, and a third crate in the trust path buys nothing.
7+
8+use base64::Engine;
9+use base64::engine::general_purpose::URL_SAFE_NO_PAD as b64url;
10+use rsa::RsaPrivateKey;
11+use rsa::signature::{SignatureEncoding, Signer};
12+
13+use crate::accounts::{Token, digests_match, hash_token};
14+use crate::model::{AuthCode, ClientId, OidcClient, RefreshToken, UserId};
15+use crate::store::{self, Result, Store, StoreError, backend};
16+
17+/// How long an authorization code lives, in seconds.
18+pub const CODE_SECONDS: i64 = 60;
19+/// How long an access/id token lives, in seconds.
20+pub const TOKEN_SECONDS: i64 = 15 * 60;
21+/// How long a refresh token lives.
22+pub const REFRESH_DAYS: i64 = 30;
23+
24+#[derive(Debug, thiserror::Error)]
25+pub enum OidcError {
26+ #[error("database: {0}")]
27+ Backend(String),
28+ #[error("unknown client")]
29+ UnknownClient,
30+ #[error("bad client secret")]
31+ BadSecret,
32+}
33+
34+impl From<StoreError> for OidcError {
35+ fn from(e: StoreError) -> Self {
36+ OidcError::Backend(e.to_string())
37+ }
38+}
39+
40+/// Signs `claims` into a compact RS256 JWT under `kid`.
41+pub fn sign_jwt(claims: &serde_json::Value, kid: &str, key: &RsaPrivateKey) -> String {
42+ let header = serde_json::json!({ "alg": "RS256", "typ": "JWT", "kid": kid });
43+ let mut out = b64url.encode(header.to_string());
44+ out.push('.');
45+ out.push_str(&b64url.encode(claims.to_string()));
46+ let signing = rsa::pkcs1v15::SigningKey::<sha2_for_rsa::Sha256>::new(key.clone());
47+ let signature = signing.sign(out.as_bytes());
48+ out.push('.');
49+ out.push_str(&b64url.encode(signature.to_bytes()));
50+ out
51+}
52+
53+// ---------------------------------------------------------------------------
54+// Clients
55+// ---------------------------------------------------------------------------
56+
57+/// Registers a relying party, returning its id and the raw client secret —
58+/// shown exactly once; the row holds the digest.
59+pub async fn create_client(
60+ store: &Store,
61+ name: &str,
62+ redirect_uris: Vec<String>,
63+) -> Result<(ClientId, Token)> {
64+ let id = ClientId::mint();
65+ let secret = Token::mint();
66+ store
67+ .conn
68+ .execute(
69+ "INSERT INTO oidc_clients (client_id, name, secret_hash, redirect_uris, created_at) \
70+ VALUES (?1, ?2, ?3, ?4, ?5)",
71+ turso::params![
72+ id.to_string(),
73+ name,
74+ secret.hash(),
75+ serde_json::to_string(&redirect_uris)
76+ .map_err(|e| StoreError::Corrupt(format!("redirect_uris: {e}")))?,
77+ store::stamp(store::now())?,
78+ ],
79+ )
80+ .await
81+ .map_err(backend)?;
82+ Ok((id, secret))
83+}
84+
85+/// Looks a client up by its public id.
86+pub async fn client_by_id(store: &Store, client_id: &str) -> Result<Option<OidcClient>> {
87+ let mut rows = store
88+ .conn
89+ .query(
90+ "SELECT client_id, name, secret_hash, redirect_uris, created_at \
91+ FROM oidc_clients WHERE client_id = ?1",
92+ turso::params![client_id],
93+ )
94+ .await
95+ .map_err(backend)?;
96+ let Some(row) = rows.next().await.map_err(backend)? else {
97+ return Ok(None);
98+ };
99+ Ok(Some(read_client(&row)?))
100+}
101+
102+fn read_client(row: &turso::Row) -> Result<OidcClient> {
103+ let uris_raw = store::text(row, 3)?;
104+ Ok(OidcClient {
105+ client_id: ClientId::from(store::text(row, 0)?),
106+ name: store::text(row, 1)?,
107+ secret_hash: store::text(row, 2)?,
108+ redirect_uris: serde_json::from_str(&uris_raw)
109+ .map_err(|e| StoreError::Corrupt(format!("redirect_uris {uris_raw:?}: {e}")))?,
110+ created_at: store::parse_stamp(&store::text(row, 4)?)?,
111+ })
112+}
113+
114+/// Constant-time client-secret check.
115+pub fn verify_client_secret(client: &OidcClient, secret: &str) -> bool {
116+ digests_match(&client.secret_hash, &hash_token(secret))
117+}
118+
119+// ---------------------------------------------------------------------------
120+// Authorization codes
121+// ---------------------------------------------------------------------------
122+
123+/// Mints an authorization code for a completed login. Raw code returned; the
124+/// row holds the digest.
125+pub async fn create_auth_code(
126+ store: &Store,
127+ client_id: &ClientId,
128+ user: &UserId,
129+ redirect_uri: &str,
130+ nonce: Option<String>,
131+ challenge: &str,
132+ session_hash: &str,
133+) -> Result<Token> {
134+ let code = Token::mint();
135+ store
136+ .conn
137+ .execute(
138+ "INSERT INTO auth_codes \
139+ (code_hash, client_id, user_id, redirect_uri, nonce, code_challenge, session_hash, expires_at) \
140+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
141+ turso::params![
142+ code.hash(),
143+ client_id.to_string(),
144+ user.to_string(),
145+ redirect_uri,
146+ nonce,
147+ challenge,
148+ session_hash,
149+ store::stamp(store::now() + time::Duration::seconds(CODE_SECONDS))?,
150+ ],
151+ )
152+ .await
153+ .map_err(backend)?;
154+ Ok(code)
155+}
156+
157+/// Consumes a code: returns its row exactly once. The SELECT and the
158+/// `consumed_at` stamp run inside one immediate transaction, so two parallel
159+/// exchanges of the same code cannot both succeed.
160+pub async fn consume_auth_code(store: &Store, code: &str) -> Result<Option<AuthCode>> {
161+ let hash = hash_token(code);
162+ store
163+ .conn
164+ .execute("BEGIN IMMEDIATE", ())
165+ .await
166+ .map_err(backend)?;
167+ let outcome = async {
168+ let mut rows = store
169+ .conn
170+ .query(
171+ "SELECT client_id, user_id, redirect_uri, nonce, code_challenge, session_hash, \
172+ expires_at, consumed_at FROM auth_codes WHERE code_hash = ?1",
173+ turso::params![hash.clone()],
174+ )
175+ .await
176+ .map_err(backend)?;
177+ let Some(row) = rows.next().await.map_err(backend)? else {
178+ return Ok(None);
179+ };
180+ if store::opt_text(&row, 7)?.is_some() {
181+ return Ok(None);
182+ }
183+ if store::parse_stamp(&store::text(&row, 6)?)? < store::now() {
184+ return Ok(None);
185+ }
186+ store
187+ .conn
188+ .execute(
189+ "UPDATE auth_codes SET consumed_at = ?1 WHERE code_hash = ?2",
190+ turso::params![store::stamp(store::now())?, hash],
191+ )
192+ .await
193+ .map_err(backend)?;
194+ Ok(Some(AuthCode {
195+ client_id: ClientId::from(store::text(&row, 0)?),
196+ user_id: UserId::from(store::text(&row, 1)?),
197+ redirect_uri: store::text(&row, 2)?,
198+ nonce: store::opt_text(&row, 3)?,
199+ code_challenge: store::text(&row, 4)?,
200+ session_hash: store::text(&row, 5)?,
201+ expires_at: store::parse_stamp(&store::text(&row, 6)?)?,
202+ }))
203+ }
204+ .await;
205+ match outcome {
206+ Ok(found) => {
207+ store.conn.execute("COMMIT", ()).await.map_err(backend)?;
208+ Ok(found)
209+ }
210+ Err(e) => {
211+ let _ = store.conn.execute("ROLLBACK", ()).await;
212+ Err(e)
213+ }
214+ }
215+}
216+
217+// ---------------------------------------------------------------------------
218+// Refresh tokens
219+// ---------------------------------------------------------------------------
220+
221+/// Issues a refresh token bound to the central session that minted it, so
222+/// revoking the session retires every token the apps are still holding.
223+pub async fn issue_refresh(
224+ store: &Store,
225+ user: &UserId,
226+ client_id: &ClientId,
227+ session_hash: &str,
228+) -> Result<Token> {
229+ let token = Token::mint();
230+ store
231+ .conn
232+ .execute(
233+ "INSERT INTO refresh_tokens \
234+ (token_hash, user_id, client_id, session_hash, expires_at) \
235+ VALUES (?1, ?2, ?3, ?4, ?5)",
236+ turso::params![
237+ token.hash(),
238+ user.to_string(),
239+ client_id.to_string(),
240+ session_hash,
241+ store::stamp(store::now() + time::Duration::days(REFRESH_DAYS))?,
242+ ],
243+ )
244+ .await
245+ .map_err(backend)?;
246+ Ok(token)
247+}
248+
249+/// Rotates a refresh token: the presented one is revoked, a fresh one is
250+/// minted against the same session, and the new raw token plus the old row
251+/// come back. `None` for unknown, expired, or revoked tokens — and for tokens
252+/// whose central session is gone, which is what makes SSO logout global.
253+pub async fn rotate_refresh(store: &Store, token: &str) -> Result<Option<(Token, RefreshToken)>> {
254+ let hash = hash_token(token);
255+ store
256+ .conn
257+ .execute("BEGIN IMMEDIATE", ())
258+ .await
259+ .map_err(backend)?;
260+ let outcome = async {
261+ let mut rows = store
262+ .conn
263+ .query(
264+ "SELECT user_id, client_id, session_hash, expires_at, revoked_at \
265+ FROM refresh_tokens WHERE token_hash = ?1",
266+ turso::params![hash.clone()],
267+ )
268+ .await
269+ .map_err(backend)?;
270+ let Some(row) = rows.next().await.map_err(backend)? else {
271+ return Ok(None);
272+ };
273+ if store::opt_text(&row, 4)?.is_some() {
274+ return Ok(None);
275+ }
276+ if store::parse_stamp(&store::text(&row, 3)?)? < store::now() {
277+ return Ok(None);
278+ }
279+ let record = RefreshToken {
280+ user_id: UserId::from(store::text(&row, 0)?),
281+ client_id: ClientId::from(store::text(&row, 1)?),
282+ session_hash: store::text(&row, 2)?,
283+ expires_at: store::parse_stamp(&store::text(&row, 3)?)?,
284+ };
285+ // The session that minted this token must still be alive.
286+ let mut sessions = store
287+ .conn
288+ .query(
289+ "SELECT expires_at, revoked_at FROM sessions WHERE token_hash = ?1",
290+ turso::params![record.session_hash.clone()],
291+ )
292+ .await
293+ .map_err(backend)?;
294+ let Some(session) = sessions.next().await.map_err(backend)? else {
295+ return Ok(None);
296+ };
297+ if store::opt_text(&session, 1)?.is_some() {
298+ return Ok(None);
299+ }
300+ if store::parse_stamp(&store::text(&session, 0)?)? < store::now() {
301+ return Ok(None);
302+ }
303+
304+ let now = store::stamp(store::now())?;
305+ store
306+ .conn
307+ .execute(
308+ "UPDATE refresh_tokens SET revoked_at = ?1 WHERE token_hash = ?2",
309+ turso::params![now.clone(), hash.clone()],
310+ )
311+ .await
312+ .map_err(backend)?;
313+ let fresh = issue_refresh(
314+ store,
315+ &record.user_id,
316+ &record.client_id,
317+ &record.session_hash,
318+ )
319+ .await?;
320+ Ok(Some((fresh, record)))
321+ }
322+ .await;
323+ match outcome {
324+ Ok(found) => {
325+ store.conn.execute("COMMIT", ()).await.map_err(backend)?;
326+ Ok(found)
327+ }
328+ Err(e) => {
329+ let _ = store.conn.execute("ROLLBACK", ()).await;
330+ Err(e)
331+ }
332+ }
333+}
334+
335+// ---------------------------------------------------------------------------
336+// Verification (the provider half: /userinfo and future introspection)
337+// ---------------------------------------------------------------------------
338+
339+/// RFC 7636 S256: `base64url(sha256(verifier))` must equal the challenge the
340+/// `/authorize` call stored.
341+pub fn pkce_matches(challenge: &str, verifier: &str) -> bool {
342+ use sha2::Digest;
343+ let computed = b64url.encode(sha2::Sha256::digest(verifier.as_bytes()));
344+ crate::accounts::digests_match(challenge, &computed)
345+}
346+
347+/// Verifies a compact JWT im minted: RS256 signature against the active key
348+/// named by `kid`, `aud` equal to `audience`, `exp` in the future. Returns
349+/// the claims on success, `None` for every way a token can fail — unknown
350+/// key, bad signature, wrong audience, expired — which all read the same to
351+/// the caller: this token does not authenticate anyone.
352+///
353+/// `iss` is the caller's to check: the issuer string is configuration the
354+/// core crate does not hold.
355+pub async fn verify_jwt(
356+ store: &Store,
357+ token: &str,
358+ audience: Option<&str>,
359+) -> Result<Option<serde_json::Value>> {
360+ use rsa::signature::Verifier;
361+
362+ let parts: Vec<&str> = token.split('.').collect();
363+ if parts.len() != 3 {
364+ return Ok(None);
365+ }
366+ let Ok(header_bytes) = b64url.decode(parts[0]) else {
367+ return Ok(None);
368+ };
369+ let Ok(header) = serde_json::from_slice::<serde_json::Value>(&header_bytes) else {
370+ return Ok(None);
371+ };
372+ if header["alg"] != "RS256" {
373+ return Ok(None);
374+ }
375+ let Some(kid) = header["kid"].as_str() else {
376+ return Ok(None);
377+ };
378+ let Some(public) = crate::keys::public_key_by_kid(store, kid).await? else {
379+ return Ok(None);
380+ };
381+ let Ok(signature_bytes) = b64url.decode(parts[2]) else {
382+ return Ok(None);
383+ };
384+ let Ok(signature) = rsa::pkcs1v15::Signature::try_from(signature_bytes.as_slice()) else {
385+ return Ok(None);
386+ };
387+ let verifying = rsa::pkcs1v15::VerifyingKey::<sha2_for_rsa::Sha256>::new(public);
388+ if verifying
389+ .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature)
390+ .is_err()
391+ {
392+ return Ok(None);
393+ }
394+ let Ok(claims_bytes) = b64url.decode(parts[1]) else {
395+ return Ok(None);
396+ };
397+ let Ok(claims) = serde_json::from_slice::<serde_json::Value>(&claims_bytes) else {
398+ return Ok(None);
399+ };
400+ if let Some(audience) = audience {
401+ if claims["aud"].as_str() != Some(audience) {
402+ return Ok(None);
403+ }
404+ }
405+ let Some(exp) = claims["exp"].as_i64() else {
406+ return Ok(None);
407+ };
408+ if exp <= store::now().unix_timestamp() {
409+ return Ok(None);
410+ }
411+ Ok(Some(claims))
412+}
413+
414+#[cfg(test)]
415+mod tests {
416+ use super::*;
417+ use crate::accounts::{create_invite, create_user_from_invite};
418+ use crate::sessions::create_session;
419+ use rsa::signature::Verifier;
420+ use std::path::Path;
421+
422+ async fn fixture() -> (Store, ClientId, UserId) {
423+ let store = Store::open(Path::new(":memory:")).await.unwrap();
424+ let (client_id, _secret) =
425+ create_client(&store, "demo", vec!["http://app/callback".into()])
426+ .await
427+ .unwrap();
428+ let invite = create_invite(&store, "ann@example.com", None)
429+ .await
430+ .unwrap();
431+ let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv")
432+ .await
433+ .unwrap();
434+ (store, client_id, user.id)
435+ }
436+
437+ #[tokio::test]
438+ async fn jwt_structure_and_signature() {
439+ let store = Store::open(Path::new(":memory:")).await.unwrap();
440+ let (kid, key) = crate::keys::active_signing_key(&store).await.unwrap();
441+ let token = sign_jwt(
442+ &serde_json::json!({ "iss": "im", "sub": "u1", "exp": 1i64 }),
443+ &kid,
444+ &key,
445+ );
446+ let parts: Vec<&str> = token.split('.').collect();
447+ assert_eq!(parts.len(), 3);
448+ let header: serde_json::Value =
449+ serde_json::from_slice(&b64url.decode(parts[0]).unwrap()).unwrap();
450+ assert_eq!(header["alg"], "RS256");
451+ assert_eq!(header["kid"].as_str().unwrap(), kid);
452+ let claims: serde_json::Value =
453+ serde_json::from_slice(&b64url.decode(parts[1]).unwrap()).unwrap();
454+ assert_eq!(claims["sub"], "u1");
455+
456+ let verifying =
457+ rsa::pkcs1v15::VerifyingKey::<sha2_for_rsa::Sha256>::new(key.to_public_key());
458+ let signature =
459+ rsa::pkcs1v15::Signature::try_from(b64url.decode(parts[2]).unwrap().as_slice())
460+ .unwrap();
461+ verifying
462+ .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature)
463+ .unwrap();
464+ // A tampered payload must not verify.
465+ let forged = format!("{}.{}", parts[0], b64url.encode(r#"{"sub":"mallory"}"#));
466+ assert!(verifying.verify(forged.as_bytes(), &signature).is_err());
467+ }
468+
469+ #[tokio::test]
470+ async fn auth_code_is_single_use() {
471+ let (store, client_id, user_id) = fixture().await;
472+ let code = create_auth_code(
473+ &store,
474+ &client_id,
475+ &user_id,
476+ "http://app/callback",
477+ None,
478+ "challenge",
479+ "session-hash",
480+ )
481+ .await
482+ .unwrap();
483+ let first = consume_auth_code(&store, code.expose()).await.unwrap();
484+ assert!(first.is_some());
485+ assert_eq!(first.unwrap().code_challenge, "challenge");
486+ assert!(
487+ consume_auth_code(&store, code.expose())
488+ .await
489+ .unwrap()
490+ .is_none()
491+ );
492+ }
493+
494+ #[tokio::test]
495+ async fn refresh_rotates_and_dies_with_session() {
496+ let (store, client_id, user_id) = fixture().await;
497+ let session = create_session(&store, &user_id).await.unwrap();
498+ let token = issue_refresh(&store, &user_id, &client_id, &session.hash())
499+ .await
500+ .unwrap();
501+
502+ let (fresh, old) = rotate_refresh(&store, token.expose())
503+ .await
504+ .unwrap()
505+ .unwrap();
506+ assert_eq!(old.user_id, user_id);
507+ // The old token is spent.
508+ assert!(
509+ rotate_refresh(&store, token.expose())
510+ .await
511+ .unwrap()
512+ .is_none()
513+ );
514+ // The fresh one works.
515+ assert!(
516+ rotate_refresh(&store, fresh.expose())
517+ .await
518+ .unwrap()
519+ .is_some()
520+ );
521+
522+ // Revoking the central session retires the refresh chain.
523+ let session2 = create_session(&store, &user_id).await.unwrap();
524+ let token2 = issue_refresh(&store, &user_id, &client_id, &session2.hash())
525+ .await
526+ .unwrap();
527+ crate::sessions::revoke_session(&store, session2.expose())
528+ .await
529+ .unwrap();
530+ assert!(
531+ rotate_refresh(&store, token2.expose())
532+ .await
533+ .unwrap()
534+ .is_none()
535+ );
536+ }
537+
538+ #[tokio::test]
539+ async fn client_secret_verifies_constant_time() {
540+ let (store, client_id, _) = fixture().await;
541+ let client = client_by_id(&store, &client_id.to_string())
542+ .await
543+ .unwrap()
544+ .unwrap();
545+ assert!(!verify_client_secret(&client, "wrong"));
546+ assert!(
547+ client
548+ .redirect_uris
549+ .contains(&"http://app/callback".to_string())
550+ );
551+ }
552+}
crates/im-core/src/secret.rsadded+153 -0
@@ -0,0 +1,153 @@
1+//! At-rest encryption for secrets, ported from izlek-core's `store/secret.rs`
2+//! (same product family, same author).
3+//!
4+//! The column holds ciphertext, and the key that opens it lives in a second
5+//! file (`im.key`, beside the database) that a database backup does not
6+//! automatically include.
7+//!
8+//! The envelope is `v1:` followed by base64 of a 24-byte XChaCha20-Poly1305
9+//! nonce and the sealed bytes it protects.
10+
11+use std::io;
12+use std::path::Path;
13+
14+use base64::Engine;
15+use base64::engine::general_purpose::STANDARD as base64;
16+use chacha20poly1305::aead::Aead;
17+use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce};
18+use rand::Rng;
19+
20+/// A key is 32 raw bytes; nothing here derives it from a password, because
21+/// there is no password to derive it from — it is the thing that protects
22+/// one.
23+pub const KEY_BYTES: usize = 32;
24+pub type Key = [u8; KEY_BYTES];
25+
26+const PREFIX: &str = "v1:";
27+const NONCE_BYTES: usize = 24;
28+
29+/// True for a value already in our envelope.
30+#[cfg(test)]
31+pub fn is_sealed(value: &str) -> bool {
32+ value.starts_with(PREFIX)
33+}
34+
35+/// Encrypts `plaintext` under `key`, returning the envelope ready to store.
36+///
37+/// A fresh random nonce is drawn every call, so sealing the same secret twice
38+/// gives two different strings. XChaCha20-Poly1305's 24-byte nonce is wide
39+/// enough that "draw at random and never track reuse" is safe for the volume
40+/// of writes an SSO produces.
41+pub fn seal(key: &Key, plaintext: &[u8]) -> String {
42+ let cipher = XChaCha20Poly1305::new(key.into());
43+ let mut nonce_bytes = [0u8; NONCE_BYTES];
44+ rand::rng().fill_bytes(&mut nonce_bytes);
45+ let nonce = XNonce::from_slice(&nonce_bytes);
46+ let ciphertext = cipher
47+ .encrypt(nonce, plaintext)
48+ .expect("XChaCha20-Poly1305 cannot fail to encrypt a plaintext this small");
49+ let mut payload = Vec::with_capacity(NONCE_BYTES + ciphertext.len());
50+ payload.extend_from_slice(&nonce_bytes);
51+ payload.extend_from_slice(&ciphertext);
52+ format!("{PREFIX}{}", base64.encode(payload))
53+}
54+
55+/// Reverses [`seal`]. `None` covers every way this can fail to come back —
56+/// not our prefix, not valid base64, too short to hold a nonce, wrong key,
57+/// or a tampered/truncated ciphertext that fails the Poly1305 tag check.
58+pub fn open(key: &Key, sealed: &str) -> Option<Vec<u8>> {
59+ let body = sealed.strip_prefix(PREFIX)?;
60+ let payload = base64.decode(body).ok()?;
61+ if payload.len() < NONCE_BYTES {
62+ return None;
63+ }
64+ let (nonce_bytes, ciphertext) = payload.split_at(NONCE_BYTES);
65+ let cipher = XChaCha20Poly1305::new(key.into());
66+ let nonce = XNonce::from_slice(nonce_bytes);
67+ cipher.decrypt(nonce, ciphertext).ok()
68+}
69+
70+/// Reads the key at `path`, generating and writing a fresh one (mode 0600,
71+/// where the platform has modes) if the file is not there yet.
72+///
73+/// Called once, at [`crate::store::Store::open`] — the key is loaded, not
74+/// re-read per query, so a corrupted key file is a boot-time failure, not a
75+/// per-request one.
76+pub fn load_or_create_key(path: &Path) -> io::Result<Key> {
77+ match std::fs::read(path) {
78+ Ok(bytes) => {
79+ let key: Key = bytes.try_into().map_err(|bytes: Vec<u8>| {
80+ io::Error::new(
81+ io::ErrorKind::InvalidData,
82+ format!(
83+ "{} holds {} bytes, not the {KEY_BYTES} of a key",
84+ path.display(),
85+ bytes.len()
86+ ),
87+ )
88+ })?;
89+ Ok(key)
90+ }
91+ Err(e) if e.kind() == io::ErrorKind::NotFound => {
92+ let mut key = [0u8; KEY_BYTES];
93+ rand::rng().fill_bytes(&mut key);
94+ std::fs::write(path, key)?;
95+ restrict(path)?;
96+ Ok(key)
97+ }
98+ Err(e) => Err(e),
99+ }
100+}
101+
102+/// Best-effort 0600; platforms without modes simply skip the call.
103+#[cfg(unix)]
104+fn restrict(path: &Path) -> io::Result<()> {
105+ use std::os::unix::fs::PermissionsExt;
106+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
107+}
108+
109+#[cfg(not(unix))]
110+fn restrict(_path: &Path) -> io::Result<()> {
111+ Ok(())
112+}
113+
114+#[cfg(test)]
115+mod tests {
116+ use super::*;
117+
118+ #[test]
119+ fn seal_roundtrip() {
120+ let key = [7u8; KEY_BYTES];
121+ let sealed = seal(&key, b"a totp secret");
122+ assert!(is_sealed(&sealed));
123+ assert_eq!(
124+ open(&key, &sealed).as_deref(),
125+ Some(b"a totp secret".as_slice())
126+ );
127+ }
128+
129+ #[test]
130+ fn seal_is_randomized() {
131+ let key = [7u8; KEY_BYTES];
132+ assert_ne!(seal(&key, b"same"), seal(&key, b"same"));
133+ }
134+
135+ #[test]
136+ fn open_rejects_garbage() {
137+ let key = [7u8; KEY_BYTES];
138+ assert_eq!(open(&key, "plaintext"), None);
139+ assert_eq!(open(&key, "v1:not-base64!!!"), None);
140+ assert_eq!(open(&key, "v1:c2hvcnQ"), None);
141+ let wrong = [8u8; KEY_BYTES];
142+ assert_eq!(open(&wrong, &seal(&key, b"x")), None);
143+ }
144+
145+ #[test]
146+ fn key_file_is_stable_across_opens() {
147+ let dir = tempfile::tempdir().unwrap();
148+ let path = dir.path().join("im.key");
149+ let first = load_or_create_key(&path).unwrap();
150+ let second = load_or_create_key(&path).unwrap();
151+ assert_eq!(first, second, "a second open reuses the same key");
152+ }
153+}
crates/im-core/src/sessions.rsadded+128 -0
@@ -0,0 +1,128 @@
1+//! Central sessions: the `im_session` cookie's server half.
2+//!
3+//! A session is what makes SSO single: once a browser holds one, every app's
4+//! `/authorize` round-trip is a silent redirect. Revoking a session also
5+//! revokes every refresh token bound to it — that is what "log me out
6+//! everywhere" means here.
7+
8+use crate::accounts::{Token, hash_token};
9+use crate::model::{User, UserId};
10+use crate::store::{self, Result, Store, backend};
11+
12+/// How long a central session lives.
13+pub const SESSION_DAYS: i64 = 30;
14+
15+/// Creates a session for `user`, returning the raw cookie token. The row
16+/// holds only its digest.
17+pub async fn create_session(store: &Store, user: &UserId) -> Result<Token> {
18+ let token = Token::mint();
19+ let now = store::now();
20+ store
21+ .conn
22+ .execute(
23+ "INSERT INTO sessions (token_hash, user_id, created_at, expires_at) \
24+ VALUES (?1, ?2, ?3, ?4)",
25+ turso::params![
26+ token.hash(),
27+ user.to_string(),
28+ store::stamp(now)?,
29+ store::stamp(now + time::Duration::days(SESSION_DAYS))?,
30+ ],
31+ )
32+ .await
33+ .map_err(backend)?;
34+ Ok(token)
35+}
36+
37+/// Resolves a raw cookie token to its user. `None` for unknown, expired,
38+/// revoked, or disabled — every one of them is "please log in again".
39+pub async fn resolve_session(store: &Store, token: &str) -> Result<Option<User>> {
40+ let mut rows = store
41+ .conn
42+ .query(
43+ "SELECT user_id, expires_at, revoked_at FROM sessions WHERE token_hash = ?1",
44+ turso::params![hash_token(token)],
45+ )
46+ .await
47+ .map_err(backend)?;
48+ let Some(row) = rows.next().await.map_err(backend)? else {
49+ return Ok(None);
50+ };
51+ if store::opt_text(&row, 2)?.is_some() {
52+ return Ok(None);
53+ }
54+ if store::parse_stamp(&store::text(&row, 1)?)? < store::now() {
55+ return Ok(None);
56+ }
57+ let user_id = UserId::from(store::text(&row, 0)?);
58+ match crate::accounts::user_by_id(store, &user_id).await? {
59+ Some(user) if !user.disabled => Ok(Some(user)),
60+ _ => Ok(None),
61+ }
62+}
63+
64+/// Revokes a session and every refresh token bound to it.
65+pub async fn revoke_session(store: &Store, token: &str) -> Result<()> {
66+ let now = store::stamp(store::now())?;
67+ let hash = hash_token(token);
68+ store
69+ .conn
70+ .execute(
71+ "UPDATE sessions SET revoked_at = ?1 WHERE token_hash = ?2 AND revoked_at IS NULL",
72+ turso::params![now.clone(), hash.clone()],
73+ )
74+ .await
75+ .map_err(backend)?;
76+ store
77+ .conn
78+ .execute(
79+ "UPDATE refresh_tokens SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL",
80+ turso::params![now, hash],
81+ )
82+ .await
83+ .map_err(backend)?;
84+ Ok(())
85+}
86+
87+#[cfg(test)]
88+mod tests {
89+ use super::*;
90+ use crate::accounts::{create_invite, create_user_from_invite};
91+ use std::path::Path;
92+
93+ async fn fixture() -> (Store, UserId) {
94+ let store = Store::open(Path::new(":memory:")).await.unwrap();
95+ let invite = create_invite(&store, "ann@example.com", None)
96+ .await
97+ .unwrap();
98+ let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv")
99+ .await
100+ .unwrap();
101+ (store, user.id)
102+ }
103+
104+ #[tokio::test]
105+ async fn session_roundtrip_and_revoke() {
106+ let (store, user_id) = fixture().await;
107+ let token = create_session(&store, &user_id).await.unwrap();
108+ let user = resolve_session(&store, token.expose())
109+ .await
110+ .unwrap()
111+ .unwrap();
112+ assert_eq!(user.id, user_id);
113+
114+ revoke_session(&store, token.expose()).await.unwrap();
115+ assert!(
116+ resolve_session(&store, token.expose())
117+ .await
118+ .unwrap()
119+ .is_none()
120+ );
121+ assert!(
122+ resolve_session(&store, "not-a-token")
123+ .await
124+ .unwrap()
125+ .is_none()
126+ );
127+ }
128+}
crates/im-core/src/store.rsadded+227 -0
@@ -0,0 +1,227 @@
1+//! The turso store: connection, schema, and the conventions every module
2+//! queries through.
3+
4+use std::path::Path;
5+
6+use time::OffsetDateTime;
7+use time::format_description::well_known::Rfc3339;
8+use turso::{Builder, Connection, Row};
9+
10+use crate::secret::{self, Key};
11+
12+#[derive(Debug, thiserror::Error)]
13+pub enum StoreError {
14+ #[error("database: {0}")]
15+ Backend(String),
16+ #[error("corrupt row: {0}")]
17+ Corrupt(String),
18+ #[error("io: {0}")]
19+ Io(#[from] std::io::Error),
20+}
21+
22+pub type Result<T, E = StoreError> = std::result::Result<T, E>;
23+
24+pub(crate) fn backend<E: std::fmt::Display>(e: E) -> StoreError {
25+ StoreError::Backend(e.to_string())
26+}
27+
28+/// The schema, authoritative. Every table is `IF NOT EXISTS` so `migrate()`
29+/// is idempotent and safe to run on every boot.
30+pub const SCHEMA: &str = "
31+CREATE TABLE IF NOT EXISTS users (
32+ id TEXT PRIMARY KEY,
33+ email TEXT NOT NULL UNIQUE COLLATE NOCASE,
34+ name TEXT NOT NULL,
35+ password_hash TEXT NOT NULL,
36+ totp_secret BLOB,
37+ totp_confirmed INTEGER NOT NULL DEFAULT 0,
38+ disabled INTEGER NOT NULL DEFAULT 0,
39+ created_at TEXT NOT NULL
40+);
41+CREATE TABLE IF NOT EXISTS invites (
42+ token TEXT PRIMARY KEY,
43+ email TEXT NOT NULL,
44+ invited_by TEXT,
45+ created_at TEXT NOT NULL,
46+ expires_at TEXT NOT NULL,
47+ accepted_at TEXT
48+);
49+CREATE TABLE IF NOT EXISTS sessions (
50+ token_hash TEXT PRIMARY KEY,
51+ user_id TEXT NOT NULL REFERENCES users(id),
52+ created_at TEXT NOT NULL,
53+ expires_at TEXT NOT NULL,
54+ revoked_at TEXT
55+);
56+CREATE TABLE IF NOT EXISTS oidc_clients (
57+ client_id TEXT PRIMARY KEY,
58+ name TEXT NOT NULL,
59+ secret_hash TEXT NOT NULL,
60+ redirect_uris TEXT NOT NULL,
61+ created_at TEXT NOT NULL
62+);
63+CREATE TABLE IF NOT EXISTS auth_codes (
64+ code_hash TEXT PRIMARY KEY,
65+ client_id TEXT NOT NULL REFERENCES oidc_clients(client_id),
66+ user_id TEXT NOT NULL REFERENCES users(id),
67+ redirect_uri TEXT NOT NULL,
68+ nonce TEXT,
69+ code_challenge TEXT NOT NULL,
70+ session_hash TEXT NOT NULL,
71+ expires_at TEXT NOT NULL,
72+ consumed_at TEXT
73+);
74+CREATE TABLE IF NOT EXISTS refresh_tokens (
75+ token_hash TEXT PRIMARY KEY,
76+ user_id TEXT NOT NULL REFERENCES users(id),
77+ client_id TEXT NOT NULL REFERENCES oidc_clients(client_id),
78+ session_hash TEXT NOT NULL REFERENCES sessions(token_hash),
79+ expires_at TEXT NOT NULL,
80+ revoked_at TEXT
81+);
82+CREATE TABLE IF NOT EXISTS signing_keys (
83+ kid TEXT PRIMARY KEY,
84+ private_der_enc BLOB NOT NULL,
85+ public_der BLOB NOT NULL,
86+ created_at TEXT NOT NULL,
87+ active INTEGER NOT NULL DEFAULT 1
88+);
89+";
90+
91+/// One database handle with the at-rest key beside it. Turso is a
92+/// single-writer engine; one connection per store, like izlek-core.
93+pub struct Store {
94+ pub(crate) conn: Connection,
95+ pub(crate) key: Key,
96+}
97+
98+impl Store {
99+ /// Opens (creating if needed) the database at `path` and runs the schema
100+ /// migration. `:memory:` gives a test store with a fresh throwaway key.
101+ pub async fn open(path: &Path) -> Result<Store> {
102+ let raw = path
103+ .to_str()
104+ .ok_or_else(|| StoreError::Corrupt("path is not utf-8".into()))?;
105+ let db = Builder::new_local(raw).build().await.map_err(backend)?;
106+ let conn = db.connect().map_err(backend)?;
107+ let store = Store {
108+ conn,
109+ key: load_key(path)?,
110+ };
111+ store.migrate().await?;
112+ Ok(store)
113+ }
114+
115+ /// Applies the schema inside one immediate transaction; safe to re-run.
116+ pub async fn migrate(&self) -> Result<()> {
117+ self.conn
118+ .execute("BEGIN IMMEDIATE", ())
119+ .await
120+ .map_err(backend)?;
121+ if let Err(e) = self.conn.execute_batch(SCHEMA).await {
122+ let _ = self.conn.execute("ROLLBACK", ()).await;
123+ return Err(backend(e));
124+ }
125+ self.conn.execute("COMMIT", ()).await.map_err(backend)?;
126+ Ok(())
127+ }
128+
129+ /// The at-rest encryption key for this database.
130+ pub(crate) fn key(&self) -> &Key {
131+ &self.key
132+ }
133+
134+ /// Seals a small value for a cookie (the pending-login marker), so its
135+ /// contents are neither readable nor forgeable client-side.
136+ pub fn seal_value(&self, plaintext: &[u8]) -> String {
137+ secret::seal(&self.key, plaintext)
138+ }
139+
140+ /// Reverses [`Store::seal_value`]; `None` for anything we did not seal.
141+ pub fn open_value(&self, sealed: &str) -> Option<Vec<u8>> {
142+ secret::open(&self.key, sealed)
143+ }
144+}
145+
146+/// The key for `path`'s database. `:memory:` has no directory to anchor a
147+/// sibling file to, so it gets a key generated fresh in memory — every
148+/// in-memory store is its own, unrelated encryption domain.
149+fn load_key(path: &Path) -> Result<Key> {
150+ if path.as_os_str() == ":memory:" {
151+ let mut key = [0u8; secret::KEY_BYTES];
152+ rand::Rng::fill_bytes(&mut rand::rng(), &mut key);
153+ return Ok(key);
154+ }
155+ let dir = path
156+ .parent()
157+ .filter(|d| !d.as_os_str().is_empty())
158+ .unwrap_or_else(|| Path::new("."));
159+ secret::load_or_create_key(&dir.join("im.key")).map_err(StoreError::Io)
160+}
161+
162+pub(crate) fn now() -> OffsetDateTime {
163+ OffsetDateTime::now_utc()
164+}
165+
166+pub(crate) fn stamp(at: OffsetDateTime) -> Result<String> {
167+ at.format(&Rfc3339)
168+ .map_err(|e| StoreError::Corrupt(format!("timestamp: {e}")))
169+}
170+
171+pub(crate) fn parse_stamp(raw: &str) -> Result<OffsetDateTime> {
172+ OffsetDateTime::parse(raw, &Rfc3339)
173+ .map_err(|e| StoreError::Corrupt(format!("timestamp {raw:?}: {e}")))
174+}
175+
176+pub(crate) fn text(row: &Row, idx: usize) -> Result<String> {
177+ row.get::<String>(idx).map_err(backend)
178+}
179+
180+pub(crate) fn opt_text(row: &Row, idx: usize) -> Result<Option<String>> {
181+ row.get::<Option<String>>(idx).map_err(backend)
182+}
183+pub(crate) fn int(row: &Row, idx: usize) -> Result<i64> {
184+ row.get::<i64>(idx).map_err(backend)
185+}
186+
187+#[cfg(test)]
188+mod tests {
189+ use super::*;
190+
191+ #[tokio::test]
192+ async fn migrate_is_idempotent() {
193+ let dir = tempfile::tempdir().unwrap();
194+ let path = dir.path().join("im.db");
195+ let store = Store::open(&path).await.unwrap();
196+ store.migrate().await.unwrap();
197+ store.migrate().await.unwrap();
198+ let mut rows = store
199+ .conn
200+ .query("SELECT name FROM sqlite_master WHERE type = 'table'", ())
201+ .await
202+ .unwrap();
203+ let mut tables = Vec::new();
204+ while let Some(row) = rows.next().await.unwrap() {
205+ tables.push(text(&row, 0).unwrap());
206+ }
207+ for expected in [
208+ "users",
209+ "invites",
210+ "sessions",
211+ "oidc_clients",
212+ "auth_codes",
213+ "refresh_tokens",
214+ "signing_keys",
215+ ] {
216+ assert!(tables.contains(&expected.to_string()), "missing {expected}");
217+ }
218+ }
219+
220+ #[tokio::test]
221+ async fn key_file_lives_beside_database() {
222+ let dir = tempfile::tempdir().unwrap();
223+ let path = dir.path().join("im.db");
224+ let _store = Store::open(&path).await.unwrap();
225+ assert!(dir.path().join("im.key").exists());
226+ }
227+}
crates/im-core/src/totp.rsadded+199 -0
@@ -0,0 +1,199 @@
1+//! TOTP (RFC 6238): the second factor. HMAC-SHA1, 30-second steps, 6 digits,
2+//! one step of clock drift accepted in either direction.
3+//!
4+//! The secret is 160 bits; the database holds it sealed (`secret.rs`), the
5+//! setup page shows it base32-encoded, and authenticator apps take the
6+//! `otpauth://` URI from [`totp_uri`].
7+
8+use crate::model::UserId;
9+use crate::secret;
10+use crate::store::{self, Result, Store, backend};
11+use data_encoding::BASE32_NOPAD;
12+use hmac::digest::KeyInit;
13+use hmac::{Hmac, Mac};
14+use sha1::Sha1;
15+use time::OffsetDateTime;
16+
17+/// How long one step is, in seconds.
18+pub const STEP_SECONDS: u64 = 30;
19+
20+/// A fresh 160-bit secret.
21+pub fn generate_secret() -> [u8; 20] {
22+ let mut secret = [0u8; 20];
23+ rand::Rng::fill_bytes(&mut rand::rng(), &mut secret);
24+ secret
25+}
26+
27+/// The secret in the form authenticator apps and humans copy: base32, no
28+/// padding, grouped every four characters.
29+pub fn display_secret(secret: &[u8; 20]) -> String {
30+ let raw = BASE32_NOPAD.encode(secret);
31+ raw.as_bytes()
32+ .chunks(4)
33+ .map(|chunk| std::str::from_utf8(chunk).unwrap())
34+ .collect::<Vec<_>>()
35+ .join(" ")
36+}
37+
38+/// The `otpauth://` URI a QR code carries.
39+pub fn totp_uri(issuer: &str, email: &str, secret: &[u8; 20]) -> String {
40+ let encoded = BASE32_NOPAD.encode(secret);
41+ format!(
42+ "otpauth://totp/{issuer}:{email}?secret={encoded}&issuer={issuer}&algorithm=SHA1&digits=6&period={STEP_SECONDS}"
43+ )
44+}
45+
46+/// The 6-digit code for `secret` at instant `at`.
47+pub fn totp_code(secret: &[u8; 20], at: OffsetDateTime) -> String {
48+ code_at_step(secret, at.unix_timestamp() as u64 / STEP_SECONDS)
49+}
50+
51+fn code_at_step(secret: &[u8; 20], step: u64) -> String {
52+ let mut mac =
53+ <Hmac<Sha1> as KeyInit>::new_from_slice(secret).expect("HMAC accepts keys of any length");
54+ mac.update(&step.to_be_bytes());
55+ let digest = mac.finalize().into_bytes();
56+ let offset = (digest[19] & 0x0f) as usize;
57+ let binary = u32::from_be_bytes([
58+ digest[offset] & 0x7f,
59+ digest[offset + 1],
60+ digest[offset + 2],
61+ digest[offset + 3],
62+ ]);
63+ format!("{:06}", binary % 1_000_000)
64+}
65+
66+/// Checks a user-typed code, accepting one step of drift either way. The
67+/// comparison runs over every candidate regardless of where the match is, so
68+/// the answer's timing does not narrow the search.
69+pub fn verify_totp(secret: &[u8; 20], code: &str, at: OffsetDateTime) -> bool {
70+ let step = at.unix_timestamp() as u64 / STEP_SECONDS;
71+ let mut found = false;
72+ for candidate in [step.wrapping_sub(1), step, step.wrapping_add(1)] {
73+ let expected = code_at_step(secret, candidate);
74+ found |=
75+ subtle::ConstantTimeEq::ct_eq(expected.as_bytes(), code.as_bytes()).unwrap_u8() == 1;
76+ }
77+ found
78+}
79+
80+// ---------------------------------------------------------------------------
81+// Storage
82+// ---------------------------------------------------------------------------
83+
84+/// Stores a freshly generated secret, sealed, unconfirmed until the user
85+/// proves their app agrees (`confirm_totp`).
86+pub async fn set_totp(store: &Store, user: &UserId, secret_bytes: &[u8; 20]) -> Result<()> {
87+ let sealed = secret::seal(store.key(), secret_bytes);
88+ store
89+ .conn
90+ .execute(
91+ "UPDATE users SET totp_secret = ?1, totp_confirmed = 0 WHERE id = ?2",
92+ turso::params![sealed, user.to_string()],
93+ )
94+ .await
95+ .map_err(backend)?;
96+ Ok(())
97+}
98+
99+/// Marks the stored secret confirmed — called after one successful code.
100+pub async fn confirm_totp(store: &Store, user: &UserId) -> Result<()> {
101+ store
102+ .conn
103+ .execute(
104+ "UPDATE users SET totp_confirmed = 1 WHERE id = ?1",
105+ turso::params![user.to_string()],
106+ )
107+ .await
108+ .map_err(backend)?;
109+ Ok(())
110+}
111+
112+/// The user's sealed secret, opened: `(secret, confirmed)`, or `None` when
113+/// TOTP was never set up. A sealed value that no longer opens (wrong key,
114+/// damaged ciphertext) reads as `None` — the user re-enrolls.
115+pub async fn totp_secret(store: &Store, user: &UserId) -> Result<Option<([u8; 20], bool)>> {
116+ let mut rows = store
117+ .conn
118+ .query(
119+ "SELECT totp_secret, totp_confirmed FROM users WHERE id = ?1",
120+ turso::params![user.to_string()],
121+ )
122+ .await
123+ .map_err(backend)?;
124+ let Some(row) = rows.next().await.map_err(backend)? else {
125+ return Ok(None);
126+ };
127+ let confirmed = store::int(&row, 1)? != 0;
128+ let Some(sealed) = store::opt_text(&row, 0)? else {
129+ return Ok(None);
130+ };
131+ let Some(bytes) = secret::open(store.key(), &sealed) else {
132+ return Ok(None);
133+ };
134+ let Ok(secret_bytes) = <[u8; 20]>::try_from(bytes.as_slice()) else {
135+ return Ok(None);
136+ };
137+ Ok(Some((secret_bytes, confirmed)))
138+}
139+
140+#[cfg(test)]
141+mod tests {
142+ use super::*;
143+ use crate::accounts::{create_invite, create_user_from_invite};
144+ use std::path::Path;
145+ use time::macros::datetime;
146+
147+ /// RFC 6238 Appendix B, SHA-1 test key "12345678901234567890".
148+ const RFC_KEY: &[u8; 20] = b"12345678901234567890";
149+
150+ #[test]
151+ fn rfc6238_sha1_vectors() {
152+ // (unix time, expected 6-digit truncation of the 8-digit vector)
153+ let cases = [
154+ (59i64, "94287082"),
155+ (1111111109, "07081804"),
156+ (1111111111, "14050471"),
157+ (1234567890, "89005924"),
158+ (2000000000, "69279037"),
159+ (20000000000, "65353130"),
160+ ];
161+ for (at, expected8) in cases {
162+ let step = at as u64 / STEP_SECONDS;
163+ let got = code_at_step(RFC_KEY, step);
164+ let expected = &expected8[2..];
165+ assert_eq!(got, expected, "at {at}");
166+ }
167+ }
168+
169+ #[test]
170+ fn verify_accepts_one_step_of_drift() {
171+ let at = datetime!(2026-09-03 12:00:00 UTC);
172+ let step = at.unix_timestamp() as u64 / STEP_SECONDS;
173+ for (delta, ok) in [(-1i64, true), (0, true), (1, true), (2, false), (-2, false)] {
174+ let code = code_at_step(RFC_KEY, (step as i64 + delta) as u64);
175+ assert_eq!(verify_totp(RFC_KEY, &code, at), ok, "delta {delta}");
176+ }
177+ }
178+
179+ #[tokio::test]
180+ async fn store_roundtrip_and_confirm() {
181+ let store = Store::open(Path::new(":memory:")).await.unwrap();
182+ let invite = create_invite(&store, "ann@example.com", None)
183+ .await
184+ .unwrap();
185+ let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv")
186+ .await
187+ .unwrap();
188+
189+ assert!(totp_secret(&store, &user.id).await.unwrap().is_none());
190+ let secret = generate_secret();
191+ set_totp(&store, &user.id, &secret).await.unwrap();
192+ let (stored, confirmed) = totp_secret(&store, &user.id).await.unwrap().unwrap();
193+ assert_eq!(stored, secret);
194+ assert!(!confirmed);
195+ confirm_totp(&store, &user.id).await.unwrap();
196+ let (_, confirmed) = totp_secret(&store, &user.id).await.unwrap().unwrap();
197+ assert!(confirmed);
198+ }
199+}
crates/im-migrate/Cargo.tomladded+17 -0
@@ -0,0 +1,17 @@
1+[package]
2+name = "im-migrate"
3+version.workspace = true
4+edition.workspace = true
5+license.workspace = true
6+repository.workspace = true
7+description = "One-time import of izlek.db accounts into an im database"
8+
9+[dependencies]
10+turso.workspace = true
11+tokio.workspace = true
12+thiserror.workspace = true
13+time.workspace = true
14+ulid.workspace = true
15+
16+[dev-dependencies]
17+tempfile = "3"
crates/im-migrate/src/main.rsadded+373 -0
@@ -0,0 +1,373 @@
1+//! im-migrate: one-time import of İzlek accounts into an im database.
2+//!
3+//! ```sh
4+//! im-migrate --izlek /path/izlek.db --im /path/im.db [--mapping /path/out.csv]
5+//! ```
6+//!
7+//! İzlek's `user` table keeps `password_hash` NULL for a member who never
8+//! signed in; those rows are skipped and reported, because there is no
9+//! password to migrate and the SSO's invite flow is their way in. Everyone
10+//! else crosses with the argon2 PHC string verbatim — it verifies unchanged.
11+//!
12+//! The mapping CSV (`izlek_user_id,im_sub`) is what İzlek's follow-up batch
13+//! uses to link its local rows to SSO subject ids. It covers every user that
14+//! exists in im afterwards, imported this run or already present.
15+
16+use std::path::{Path, PathBuf};
17+
18+use time::OffsetDateTime;
19+use time::format_description::well_known::Rfc3339;
20+use turso::Builder;
21+
22+/// im's schema, duplicated literally from im-core's `store::SCHEMA` — the
23+/// tool stays dependency-free of im-core so a build of this binary never
24+/// drags the argon2/rsa tree along.
25+const IM_SCHEMA: &str = "
26+CREATE TABLE IF NOT EXISTS users (
27+ id TEXT PRIMARY KEY,
28+ email TEXT NOT NULL UNIQUE COLLATE NOCASE,
29+ name TEXT NOT NULL,
30+ password_hash TEXT NOT NULL,
31+ totp_secret BLOB,
32+ totp_confirmed INTEGER NOT NULL DEFAULT 0,
33+ disabled INTEGER NOT NULL DEFAULT 0,
34+ created_at TEXT NOT NULL
35+);
36+CREATE TABLE IF NOT EXISTS invites (
37+ token TEXT PRIMARY KEY,
38+ email TEXT NOT NULL,
39+ invited_by TEXT,
40+ created_at TEXT NOT NULL,
41+ expires_at TEXT NOT NULL,
42+ accepted_at TEXT
43+);
44+CREATE TABLE IF NOT EXISTS sessions (
45+ token_hash TEXT PRIMARY KEY,
46+ user_id TEXT NOT NULL REFERENCES users(id),
47+ created_at TEXT NOT NULL,
48+ expires_at TEXT NOT NULL,
49+ revoked_at TEXT
50+);
51+CREATE TABLE IF NOT EXISTS oidc_clients (
52+ client_id TEXT PRIMARY KEY,
53+ name TEXT NOT NULL,
54+ secret_hash TEXT NOT NULL,
55+ redirect_uris TEXT NOT NULL,
56+ created_at TEXT NOT NULL
57+);
58+CREATE TABLE IF NOT EXISTS auth_codes (
59+ code_hash TEXT PRIMARY KEY,
60+ client_id TEXT NOT NULL REFERENCES oidc_clients(client_id),
61+ user_id TEXT NOT NULL REFERENCES users(id),
62+ redirect_uri TEXT NOT NULL,
63+ nonce TEXT,
64+ code_challenge TEXT NOT NULL,
65+ session_hash TEXT NOT NULL,
66+ expires_at TEXT NOT NULL,
67+ consumed_at TEXT
68+);
69+CREATE TABLE IF NOT EXISTS refresh_tokens (
70+ token_hash TEXT PRIMARY KEY,
71+ user_id TEXT NOT NULL REFERENCES users(id),
72+ client_id TEXT NOT NULL REFERENCES oidc_clients(client_id),
73+ session_hash TEXT NOT NULL REFERENCES sessions(token_hash),
74+ expires_at TEXT NOT NULL,
75+ revoked_at TEXT
76+);
77+CREATE TABLE IF NOT EXISTS signing_keys (
78+ kid TEXT PRIMARY KEY,
79+ private_der_enc BLOB NOT NULL,
80+ public_der BLOB NOT NULL,
81+ created_at TEXT NOT NULL,
82+ active INTEGER NOT NULL DEFAULT 1
83+);
84+";
85+
86+#[derive(Debug)]
87+struct Args {
88+ izlek: PathBuf,
89+ im: PathBuf,
90+ mapping: PathBuf,
91+}
92+
93+#[derive(Debug, thiserror::Error)]
94+enum MigrateError {
95+ #[error("{0}")]
96+ Usage(String),
97+ #[error("database: {0}")]
98+ Backend(String),
99+ #[error("io: {0}")]
100+ Io(#[from] std::io::Error),
101+}
102+
103+type Result<T, E = MigrateError> = std::result::Result<T, E>;
104+
105+fn backend<E: std::fmt::Display>(e: E) -> MigrateError {
106+ MigrateError::Backend(e.to_string())
107+}
108+
109+fn parse_args() -> Result<Args> {
110+ let mut izlek = None;
111+ let mut im = None;
112+ let mut mapping = None;
113+ let mut args = std::env::args().skip(1);
114+ while let Some(arg) = args.next() {
115+ match arg.as_str() {
116+ "--izlek" => izlek = args.next().map(PathBuf::from),
117+ "--im" => im = args.next().map(PathBuf::from),
118+ "--mapping" => mapping = args.next().map(PathBuf::from),
119+ other => {
120+ return Err(MigrateError::Usage(format!(
121+ "unknown option {other}\nusage: im-migrate --izlek <izlek.db> --im <im.db> [--mapping out.csv]"
122+ )));
123+ }
124+ }
125+ }
126+ match (izlek, im) {
127+ (Some(izlek), Some(im)) => Ok(Args {
128+ izlek,
129+ im,
130+ mapping: mapping.unwrap_or_else(|| PathBuf::from("im-migrate-mapping.csv")),
131+ }),
132+ _ => Err(MigrateError::Usage(
133+ "usage: im-migrate --izlek <izlek.db> --im <im.db> [--mapping out.csv]".into(),
134+ )),
135+ }
136+}
137+
138+/// One İzlek user row worth migrating.
139+struct IzlekUser {
140+ id: String,
141+ email: String,
142+ name: String,
143+ password_hash: String,
144+}
145+
146+async fn read_izlek_users(path: &Path) -> Result<(Vec<IzlekUser>, usize)> {
147+ let db = Builder::new_local(path.to_str().unwrap())
148+ .build()
149+ .await
150+ .map_err(backend)?;
151+ let conn = db.connect().map_err(backend)?;
152+ let mut rows = conn
153+ .query(
154+ "SELECT id, email, display_name, password_hash FROM user ORDER BY created_at",
155+ (),
156+ )
157+ .await
158+ .map_err(backend)?;
159+ let mut users = Vec::new();
160+ let mut skipped_no_password = 0;
161+ while let Some(row) = rows.next().await.map_err(backend)? {
162+ let hash: Option<String> = row.get(3).map_err(backend)?;
163+ let Some(hash) = hash else {
164+ skipped_no_password += 1;
165+ continue;
166+ };
167+ users.push(IzlekUser {
168+ id: row.get(0).map_err(backend)?,
169+ email: row.get(1).map_err(backend)?,
170+ name: row.get(2).map_err(backend)?,
171+ password_hash: hash,
172+ });
173+ }
174+ Ok((users, skipped_no_password))
175+}
176+
177+struct Report {
178+ imported: usize,
179+ already_present: usize,
180+ skipped_no_password: usize,
181+}
182+
183+async fn run(args: &Args) -> Result<Report> {
184+ let (users, skipped_no_password) = read_izlek_users(&args.izlek).await?;
185+
186+ let db = Builder::new_local(args.im.to_str().unwrap())
187+ .build()
188+ .await
189+ .map_err(backend)?;
190+ let conn = db.connect().map_err(backend)?;
191+ conn.execute_batch(IM_SCHEMA).await.map_err(backend)?;
192+
193+ let mut report = Report {
194+ imported: 0,
195+ already_present: 0,
196+ skipped_no_password,
197+ };
198+ let mut mapping = String::from("izlek_user_id,im_sub\n");
199+
200+ conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?;
201+ let outcome = async {
202+ for user in &users {
203+ let mut existing = conn
204+ .query(
205+ "SELECT id FROM users WHERE email = ?1 COLLATE NOCASE",
206+ turso::params![user.email.clone()],
207+ )
208+ .await
209+ .map_err(backend)?;
210+ if let Some(row) = existing.next().await.map_err(backend)? {
211+ let sub: String = row.get(0).map_err(backend)?;
212+ report.already_present += 1;
213+ mapping.push_str(&format!("{},{sub}\n", user.id));
214+ continue;
215+ }
216+ let sub = ulid::Ulid::new().to_string();
217+ conn.execute(
218+ "INSERT INTO users (id, email, name, password_hash, created_at) \
219+ VALUES (?1, ?2, ?3, ?4, ?5)",
220+ turso::params![
221+ sub.clone(),
222+ user.email.clone(),
223+ user.name.clone(),
224+ user.password_hash.clone(),
225+ OffsetDateTime::now_utc()
226+ .format(&Rfc3339)
227+ .map_err(backend)?,
228+ ],
229+ )
230+ .await
231+ .map_err(backend)?;
232+ report.imported += 1;
233+ mapping.push_str(&format!("{},{sub}\n", user.id));
234+ }
235+ Ok::<_, MigrateError>(())
236+ }
237+ .await;
238+ match outcome {
239+ Ok(()) => {
240+ conn.execute("COMMIT", ()).await.map_err(backend)?;
241+ }
242+ Err(e) => {
243+ let _ = conn.execute("ROLLBACK", ()).await;
244+ return Err(e);
245+ }
246+ }
247+
248+ std::fs::write(&args.mapping, mapping)?;
249+ Ok(report)
250+}
251+
252+#[tokio::main]
253+async fn main() {
254+ let args = match parse_args() {
255+ Ok(args) => args,
256+ Err(MigrateError::Usage(text)) => {
257+ eprintln!("{text}");
258+ std::process::exit(2);
259+ }
260+ Err(e) => {
261+ eprintln!("im-migrate: {e}");
262+ std::process::exit(1);
263+ }
264+ };
265+ match run(&args).await {
266+ Ok(report) => {
267+ println!(
268+ "im-migrate {} -> {}",
269+ args.izlek.display(),
270+ args.im.display()
271+ );
272+ println!(
273+ " {} imported, {} already present, {} skipped (never set a password)",
274+ report.imported, report.already_present, report.skipped_no_password
275+ );
276+ println!(" mapping {}", args.mapping.display());
277+ }
278+ Err(e) => {
279+ eprintln!("im-migrate: {e}");
280+ std::process::exit(1);
281+ }
282+ }
283+}
284+
285+#[cfg(test)]
286+mod tests {
287+ use super::*;
288+
289+ async fn seed_izlek(path: &Path) {
290+ let db = Builder::new_local(path.to_str().unwrap())
291+ .build()
292+ .await
293+ .unwrap();
294+ let conn = db.connect().unwrap();
295+ conn.execute_batch(
296+ "CREATE TABLE user (
297+ id TEXT PRIMARY KEY,
298+ workspace_id TEXT NOT NULL,
299+ email TEXT NOT NULL,
300+ display_name TEXT NOT NULL,
301+ role TEXT NOT NULL,
302+ password_hash TEXT,
303+ created_at TEXT NOT NULL
304+ );",
305+ )
306+ .await
307+ .unwrap();
308+ conn.execute(
309+ "INSERT INTO user VALUES ('iz-1', 'w1', 'ann@example.com', 'Ann', 'admin', \
310+ '$argon2id$v=19$m=19456,t=2,p=1$0JjUMrLBpJG7lzg5bxZhMQ$iGpGXBNDAaHV9jqDxDcCyuIEIV33kJ1IAPt0XCh753Q', '2026-01-01T00:00:00Z')",
311+ (),
312+ )
313+ .await
314+ .unwrap();
315+ conn.execute(
316+ "INSERT INTO user VALUES ('iz-2', 'w1', 'bob@example.com', 'Bob', 'member', NULL, '2026-01-02T00:00:00Z')",
317+ (),
318+ )
319+ .await
320+ .unwrap();
321+ }
322+
323+ #[tokio::test]
324+ async fn import_is_verbatim_and_idempotent() {
325+ let dir = tempfile::tempdir().unwrap();
326+ let izlek = dir.path().join("izlek.db");
327+ let im = dir.path().join("im.db");
328+ let mapping = dir.path().join("mapping.csv");
329+ seed_izlek(&izlek).await;
330+
331+ let args = Args {
332+ izlek: izlek.clone(),
333+ im: im.clone(),
334+ mapping: mapping.clone(),
335+ };
336+ let first = run(&args).await.unwrap();
337+ assert_eq!(first.imported, 1);
338+ assert_eq!(first.skipped_no_password, 1);
339+
340+ // Re-running imports nothing and still maps every user.
341+ let second = run(&args).await.unwrap();
342+ assert_eq!(second.imported, 0);
343+ assert_eq!(second.already_present, 1);
344+
345+ let csv = std::fs::read_to_string(&mapping).unwrap();
346+ assert!(csv.contains("iz-1,"), "mapping covers the imported user");
347+
348+ let db = Builder::new_local(im.to_str().unwrap())
349+ .build()
350+ .await
351+ .unwrap();
352+ let conn = db.connect().unwrap();
353+ let mut rows = conn
354+ .query(
355+ "SELECT email, name, password_hash, totp_confirmed, disabled FROM users",
356+ (),
357+ )
358+ .await
359+ .unwrap();
360+ let row = rows.next().await.unwrap().unwrap();
361+ let email: String = row.get(0).unwrap();
362+ let hash: String = row.get(2).unwrap();
363+ assert_eq!(email, "ann@example.com");
364+ assert_eq!(
365+ hash,
366+ "$argon2id$v=19$m=19456,t=2,p=1$0JjUMrLBpJG7lzg5bxZhMQ$iGpGXBNDAaHV9jqDxDcCyuIEIV33kJ1IAPt0XCh753Q",
367+ "the PHC string crosses verbatim"
368+ );
369+ assert_eq!(row.get::<i64>(3).unwrap(), 0);
370+ assert_eq!(row.get::<i64>(4).unwrap(), 0);
371+ assert!(rows.next().await.unwrap().is_none(), "exactly one row");
372+ }
373+}
crates/im-web/Cargo.tomladded+47 -0
@@ -0,0 +1,47 @@
1+[package]
2+name = "im-web"
3+version.workspace = true
4+edition.workspace = true
5+license.workspace = true
6+repository.workspace = true
7+description = "im web app: topcoat UI, OIDC endpoints and the server"
8+build = "build.rs"
9+
10+[dependencies]
11+topcoat = { version = "0.6.2", default-features = false, features = [
12+ "router",
13+ "view",
14+ "runtime",
15+ "asset",
16+ "cookie",
17+ "discover",
18+ "serve",
19+ "compression",
20+] }
21+im-core = { workspace = true, features = ["server"] }
22+serde.workspace = true
23+serde_json.workspace = true
24+time.workspace = true
25+thiserror.workspace = true
26+tokio.workspace = true
27+ulid.workspace = true
28+base64.workspace = true
29+toml.workspace = true
30+data-encoding = "2.11.1"
31+qrcode = { version = "0.14.1", default-features = false, features = ["svg"] }
32+# TLS through rustls with the ring provider: no OpenSSL on the deployment box,
33+# and no system certificate store to be missing inside a container.
34+lettre = { version = "0.11.23", default-features = false, features = [
35+ "smtp-transport",
36+ "builder",
37+ "tokio1-rustls",
38+ "ring",
39+ "webpki-roots",
40+ "pool",
41+] }
42+
43+[build-dependencies]
44+grass = "0.13"
45+
46+[dev-dependencies]
47+http = "1.5"
crates/im-web/assets/main.cssadded+341 -0
@@ -0,0 +1,341 @@
1+:root {
2+ color-scheme: light;
3+ --bg: #f2f2f0;
4+ --surface: #fbfbfa;
5+ --border: #dcdcd8;
6+ --border-strong: #d0d0cb;
7+ --border-soft: #d3d3ce;
8+ --ink: #1a1b1d;
9+ --muted: #6b7078;
10+ --muted-soft: #6b7078;
11+ --accent: #46557b;
12+ --accent-tint: #eef0f5;
13+ --accent-ink: #2f3c5c;
14+ --accent-strong: #5a6a94;
15+ --field-bg: #f5f5f3;
16+ --panel-sunken: #eeeeec;
17+ --danger: #a04a24;
18+ --danger-tint-alt: #fbf1ec;
19+ --danger-border-soft: #eddcd3;
20+ --positive: #5c7b46;
21+ --positive-tint: #eef3e9;
22+ --positive-border: #d3e0c6;
23+ --font-sans: system-ui, sans-serif;
24+ --font-mono: "IBM Plex Mono", ui-monospace, monospace;
25+ --control-h-lg: 40px;
26+ --radius: 3px;
27+ --radius-sm: var(--radius);
28+ --radius-lg: 3px;
29+ --shadow-2: none;
30+ --dur-fast: 120ms;
31+ --ease: ease-out;
32+}
33+
34+@media (prefers-color-scheme: dark) {
35+ :root {
36+ color-scheme: dark;
37+ --bg: #0d0e10;
38+ --surface: #14161a;
39+ --border: #23262c;
40+ --border-strong: #2e323a;
41+ --border-soft: #1f2226;
42+ --ink: #e6e4de;
43+ --muted: #7d8590;
44+ --muted-soft: #4a4f58;
45+ --accent: #8ba1e8;
46+ --accent-tint: rgba(139, 161, 232, 0.14);
47+ --accent-ink: #b9c6ee;
48+ --accent-strong: #7e93d9;
49+ --field-bg: #101216;
50+ --panel-sunken: #101216;
51+ --danger: #e0906a;
52+ --danger-tint-alt: rgba(224, 144, 106, 0.05);
53+ --danger-border-soft: rgba(224, 144, 106, 0.3);
54+ --positive: #9db98a;
55+ --positive-tint: rgba(157, 185, 138, 0.13);
56+ --positive-border: rgba(157, 185, 138, 0.4);
57+ }
58+}
59+* {
60+ box-sizing: border-box;
61+}
62+
63+body {
64+ margin: 0;
65+ background: var(--bg);
66+ color: var(--ink);
67+ font-family: var(--font-sans);
68+ font-size: 14px;
69+ line-height: 1.45;
70+ -webkit-font-smoothing: antialiased;
71+}
72+
73+a {
74+ color: var(--accent);
75+ transition: color var(--dur-fast) var(--ease);
76+}
77+a:hover {
78+ color: var(--accent-ink);
79+}
80+
81+body:has(.auth-stage) {
82+ height: 100vh;
83+ height: 100dvh;
84+ overflow: hidden;
85+ display: flex;
86+ flex-direction: column;
87+}
88+body:has(.auth-stage) > * {
89+ flex: none;
90+}
91+body:has(.auth-stage) > .auth-stage {
92+ flex: 1;
93+ min-height: 0;
94+ overflow-y: auto;
95+ scrollbar-width: none;
96+}
97+body:has(.auth-stage) > .auth-stage::-webkit-scrollbar {
98+ display: none;
99+}
100+
101+.auth-stage {
102+ min-height: 100vh;
103+ min-height: 100dvh;
104+ display: flex;
105+ align-items: center;
106+ justify-content: center;
107+ padding: 0 40px 40px;
108+}
109+
110+.auth-column {
111+ width: 520px;
112+ max-width: 100%;
113+ display: flex;
114+ flex-direction: column;
115+ gap: 10px;
116+}
117+
118+.wordmark {
119+ display: flex;
120+ align-items: center;
121+ justify-content: center;
122+ gap: 10px;
123+ text-decoration: none;
124+ color: inherit;
125+ padding: 6px 0;
126+}
127+.wordmark:hover {
128+ color: inherit;
129+}
130+.wordmark-mark {
131+ flex: none;
132+ display: block;
133+ width: 24px;
134+ height: 24px;
135+}
136+.wordmark-tittle {
137+ fill: var(--accent);
138+}
139+.wordmark-text {
140+ font-family: var(--font-mono);
141+ font-size: 18px;
142+ font-weight: 500;
143+ letter-spacing: 0.02em;
144+}
145+
146+.auth-card {
147+ background: var(--surface);
148+ border: 1px solid var(--border);
149+ border-radius: var(--radius-lg);
150+ padding: 28px;
151+ display: flex;
152+ flex-direction: column;
153+ gap: 18px;
154+ box-shadow: var(--shadow-2);
155+}
156+.auth-card form {
157+ display: flex;
158+ flex-direction: column;
159+ gap: 20px;
160+}
161+
162+.auth-head {
163+ display: flex;
164+ flex-direction: column;
165+ gap: 6px;
166+}
167+
168+.auth-title {
169+ font-size: 18px;
170+ font-weight: 600;
171+ letter-spacing: -0.01em;
172+}
173+
174+.auth-sub {
175+ font-size: 13px;
176+ color: var(--muted);
177+ line-height: 1.5;
178+}
179+
180+.auth-field {
181+ display: flex;
182+ flex-direction: column;
183+ gap: 6px;
184+}
185+
186+.auth-label {
187+ font-family: var(--font-mono);
188+ font-size: 10px;
189+ letter-spacing: 0.08em;
190+ color: var(--muted-soft);
191+}
192+
193+.auth-locked {
194+ display: flex;
195+ align-items: center;
196+ gap: 8px;
197+ height: 40px;
198+ padding: 0 12px;
199+ background: var(--panel-sunken);
200+ border: 1px solid var(--border-strong);
201+ border-radius: var(--radius);
202+}
203+
204+.auth-locked-value {
205+ font-family: var(--font-mono);
206+ font-size: 13px;
207+ color: var(--muted);
208+ flex-grow: 1;
209+}
210+
211+.auth-input {
212+ height: 40px;
213+ padding: 0 12px;
214+ background: var(--field-bg);
215+ border: 1px solid var(--border-strong);
216+ border-radius: var(--radius);
217+ color: var(--ink);
218+ font-family: var(--font-sans);
219+ font-size: 13px;
220+ width: 100%;
221+}
222+.auth-input:focus {
223+ outline: none;
224+ border-color: var(--accent);
225+ box-shadow: 0 0 0 2px var(--accent-tint);
226+}
227+.auth-input:focus-visible {
228+ outline: 2px solid var(--accent);
229+ outline-offset: 1px;
230+}
231+.auth-input:user-invalid {
232+ border-color: var(--danger);
233+}
234+
235+.auth-input-mono {
236+ font-family: var(--font-mono);
237+}
238+
239+.auth-submit {
240+ height: var(--control-h-lg);
241+ display: flex;
242+ align-items: center;
243+ justify-content: center;
244+ gap: 8px;
245+ background: var(--accent);
246+ color: var(--surface);
247+ border: 0;
248+ border-radius: var(--radius);
249+ cursor: pointer;
250+ font-family: var(--font-sans);
251+}
252+.auth-submit:disabled {
253+ opacity: 0.45;
254+ cursor: default;
255+}
256+.auth-submit:focus-visible {
257+ outline: 2px solid var(--accent-ink);
258+ outline-offset: 2px;
259+}
260+
261+.auth-submit-text {
262+ font-size: 13px;
263+ font-weight: 600;
264+}
265+
266+.auth-problem {
267+ font-size: 13px;
268+ color: var(--danger);
269+ background: var(--danger-tint-alt);
270+ border: 1px solid var(--danger-border-soft);
271+ border-radius: var(--radius);
272+ padding: 10px 12px;
273+}
274+
275+.auth-note {
276+ font-size: 13px;
277+ color: var(--muted);
278+ background: var(--panel-sunken);
279+ border: 1px solid var(--border-soft);
280+ border-radius: var(--radius);
281+ padding: 10px 12px;
282+}
283+
284+.auth-ok {
285+ font-size: 13px;
286+ color: var(--positive);
287+ background: var(--positive-tint);
288+ border: 1px solid var(--positive-border);
289+ border-radius: var(--radius);
290+ padding: 10px 12px;
291+}
292+
293+.auth-secret {
294+ font-family: var(--font-mono);
295+ font-size: 14px;
296+ letter-spacing: 0.06em;
297+ text-align: center;
298+ background: var(--panel-sunken);
299+ border: 1px solid var(--border-soft);
300+ border-radius: var(--radius);
301+ padding: 10px 12px;
302+ user-select: all;
303+}
304+
305+.auth-qr {
306+ display: flex;
307+ justify-content: center;
308+}
309+.auth-qr svg {
310+ width: 200px;
311+ height: 200px;
312+ background: #fff;
313+ border: 1px solid var(--border);
314+ border-radius: var(--radius);
315+ padding: 12px;
316+}
317+
318+.auth-alt {
319+ font-size: 12px;
320+ color: var(--muted);
321+ text-decoration: none;
322+ align-self: center;
323+}
324+.auth-alt:hover {
325+ color: var(--accent-ink);
326+}
327+
328+.auth-footer {
329+ font-family: var(--font-mono);
330+ font-size: 10px;
331+ letter-spacing: 0.08em;
332+ color: var(--muted-soft);
333+ text-align: center;
334+ padding-top: 4px;
335+}
336+
337+@media (max-width: 720px) {
338+ .auth-stage {
339+ padding: 0 16px 24px;
340+ }
341+}
crates/im-web/build.rsadded+17 -0
@@ -0,0 +1,17 @@
1+//! Compiles `style/main.scss` to `assets/main.css` under this crate's
2+//! manifest directory, where `asset!("assets/main.css")` in `layout.rs`
3+//! expects to find it. Crate-relative rather than `OUT_DIR`-relative so the
4+//! asset's id does not churn with every profile/build-hash — the same
5+//! contract izlek-web's build script keeps.
6+
7+fn main() {
8+ let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
9+ let scss = format!("{manifest_dir}/../../style/main.scss");
10+ println!("cargo:rerun-if-changed={scss}");
11+
12+ let css = grass::from_path(&scss, &grass::Options::default())
13+ .unwrap_or_else(|err| panic!("failed to compile {scss}: {err}"));
14+ let out_dir = format!("{manifest_dir}/assets");
15+ std::fs::create_dir_all(&out_dir).expect("failed to create assets/");
16+ std::fs::write(format!("{out_dir}/main.css"), &css).expect("failed to write assets/main.css");
17+}
crates/im-web/src/auth.rsadded+197 -0
@@ -0,0 +1,197 @@
1+//! The form handlers behind the pages. Every one answers a plain 303: the
2+//! page it lands on reads `?error=` / `?ok=` back on render — im serves no
3+//! client-side script, so there is no action value to answer with.
4+
5+use im_core::accounts::{self, AccountError};
6+use im_core::model::UserId;
7+use serde::Deserialize;
8+use topcoat::Result;
9+use topcoat::context::Cx;
10+use topcoat::router::content::Form;
11+use topcoat::router::{HeaderName, StatusCode, header, route};
12+
13+use crate::server::{self, PendingPurpose};
14+
15+type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>;
16+
17+fn see(location: String) -> Redirect {
18+ Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)]))
19+}
20+
21+/// Percent-encodes a value for a query pair. The `back` a login carries is
22+/// always a local `/authorize?...` URL, which is full of `?&=` of its own.
23+fn urlencode(raw: &str) -> String {
24+ let mut out = String::with_capacity(raw.len());
25+ for byte in raw.bytes() {
26+ match byte {
27+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
28+ out.push(byte as char)
29+ }
30+ _ => out.push_str(&format!("%{byte:02X}")),
31+ }
32+ }
33+ out
34+}
35+
36+/// A `back` worth honoring: a local absolute path, never `//elsewhere`.
37+/// Anything else — including a full URL — becomes the front door.
38+fn safe_back(raw: &str) -> &str {
39+ if raw.starts_with('/') && !raw.starts_with("//") {
40+ raw
41+ } else {
42+ "/"
43+ }
44+}
45+
46+#[derive(Deserialize)]
47+pub struct LoginForm {
48+ email: String,
49+ password: String,
50+ #[serde(default)]
51+ back: Option<String>,
52+}
53+
54+#[route(POST "/login")]
55+async fn login(cx: &Cx, Form(input): Form<LoginForm>) -> Redirect {
56+ let back = safe_back(input.back.as_deref().unwrap_or("/")).to_string();
57+ match accounts::verify_login(&server::app(cx).store, &input.email, &input.password).await {
58+ Ok(user) if user.totp_confirmed => {
59+ let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Login, back);
60+ server::set_pending_cookie(cx, sealed);
61+ see("/login/totp".to_string())
62+ }
63+ Ok(user) => {
64+ // Accounts enrol TOTP at invite time, so this is the path for one
65+ // created before that rule — sign it in, enrolment comes next.
66+ let token = im_core::sessions::create_session(&server::app(cx).store, &user.id).await?;
67+ server::set_session_cookie(cx, token.expose());
68+ see(back)
69+ }
70+ Err(_) => see(format!("/login?error=bad_login&back={}", urlencode(&back))),
71+ }
72+}
73+
74+#[derive(Deserialize)]
75+pub struct TotpForm {
76+ code: String,
77+}
78+
79+#[route(POST "/login/totp")]
80+async fn login_totp(cx: &Cx, Form(input): Form<TotpForm>) -> Redirect {
81+ let Some(pending) = server::opened_pending(cx) else {
82+ return see("/login".to_string());
83+ };
84+ if pending.purpose != PendingPurpose::Login {
85+ return see("/login".to_string());
86+ }
87+ let store = &server::app(cx).store;
88+ let user_id = UserId::from(pending.user.clone());
89+ let ok = match accounts::user_by_id(store, &user_id).await? {
90+ Some(user) => match im_core::totp::totp_secret(store, &user.id).await? {
91+ Some((secret, confirmed)) => {
92+ confirmed
93+ && im_core::totp::verify_totp(
94+ &secret,
95+ input.code.trim(),
96+ time::OffsetDateTime::now_utc(),
97+ )
98+ }
99+ None => false,
100+ },
101+ None => false,
102+ };
103+ if !ok {
104+ return see("/login/totp?error=bad_code".to_string());
105+ }
106+ let token = im_core::sessions::create_session(store, &user_id).await?;
107+ server::clear_pending_cookie(cx);
108+ server::set_session_cookie(cx, token.expose());
109+ see(pending.back)
110+}
111+
112+#[derive(Deserialize)]
113+pub struct InviteForm {
114+ token: String,
115+ name: String,
116+ password: String,
117+ password_confirm: String,
118+}
119+
120+#[route(POST "/invite")]
121+async fn invite(cx: &Cx, Form(input): Form<InviteForm>) -> Redirect {
122+ if input.password != input.password_confirm {
123+ return see(format!("/invite/{}?error=passwords_differ", input.token));
124+ }
125+ let store = &server::app(cx).store;
126+ let user = match accounts::create_user_from_invite(
127+ store,
128+ &input.token,
129+ input.name.trim(),
130+ &input.password,
131+ )
132+ .await
133+ {
134+ Ok(user) => user,
135+ Err(problem) => {
136+ let code = match problem {
137+ AccountError::InviteInvalid => "invite_invalid",
138+ AccountError::InviteExpired => "invite_expired",
139+ AccountError::InviteSpent => "invite_spent",
140+ AccountError::EmailTaken => "email_taken",
141+ AccountError::Password(im_core::accounts::PasswordProblem::TooShort) => {
142+ "password_too_short"
143+ }
144+ AccountError::Password(im_core::accounts::PasswordProblem::LooksLikeYou) => {
145+ "password_personal"
146+ }
147+ _ => {
148+ return Err(topcoat::Error::from(std::io::Error::other(
149+ problem.to_string(),
150+ )));
151+ }
152+ };
153+ return see(format!("/invite/{}?error={code}", input.token));
154+ }
155+ };
156+ // TOTP enrolment is not optional: the account exists from here, and the
157+ // enrolment page is the only way forward.
158+ let secret = im_core::totp::generate_secret();
159+ im_core::totp::set_totp(store, &user.id, &secret).await?;
160+ let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, "/".to_string());
161+ server::set_pending_cookie(cx, sealed);
162+ see("/enroll".to_string())
163+}
164+
165+#[route(POST "/enroll")]
166+async fn enroll(cx: &Cx, Form(input): Form<TotpForm>) -> Redirect {
167+ let Some(pending) = server::opened_pending(cx) else {
168+ return see("/login".to_string());
169+ };
170+ if pending.purpose != PendingPurpose::Enroll {
171+ return see("/login".to_string());
172+ }
173+ let store = &server::app(cx).store;
174+ let user_id = UserId::from(pending.user);
175+ let Some((secret, _)) = im_core::totp::totp_secret(store, &user_id).await? else {
176+ return see("/login?error=enroll_first".to_string());
177+ };
178+ if !im_core::totp::verify_totp(&secret, input.code.trim(), time::OffsetDateTime::now_utc()) {
179+ return see("/enroll?error=bad_code".to_string());
180+ }
181+ im_core::totp::confirm_totp(store, &user_id).await?;
182+ let token = im_core::sessions::create_session(store, &user_id).await?;
183+ server::clear_pending_cookie(cx);
184+ server::set_session_cookie(cx, token.expose());
185+ see("/?ok=enrolled".to_string())
186+}
187+
188+/// "Sign out everywhere": the central session dies, and with it every
189+/// refresh token any app is still holding — see `sessions::revoke_session`.
190+#[route(POST "/logout")]
191+async fn logout(cx: &Cx) -> Redirect {
192+ if let Some(token) = server::presented_session(cx) {
193+ im_core::sessions::revoke_session(&server::app(cx).store, &token).await?;
194+ }
195+ server::clear_session_cookie(cx);
196+ see("/".to_string())
197+}
crates/im-web/src/config.rsadded+95 -0
@@ -0,0 +1,95 @@
1+//! `config/im.toml`: read before anything is opened, written with development
2+//! defaults if it is not there yet — the same contract izlek-core's `Config`
3+//! keeps. A broken key stops the boot with its name in the message.
4+
5+use std::path::{Path, PathBuf};
6+
7+use serde::Deserialize;
8+
9+const PATH: &str = "config/im.toml";
10+
11+const DEFAULTS: &str = r#"database = "im.db"
12+listen = "127.0.0.1:7650"
13+issuer = "http://127.0.0.1:7650"
14+"#;
15+
16+#[derive(Clone)]
17+pub struct Config {
18+ pub database: PathBuf,
19+ pub listen: std::net::SocketAddr,
20+ /// The OIDC issuer — the public base URL every endpoint address and every
21+ /// `iss` claim derives from.
22+ pub issuer: String,
23+ pub smtp: Option<Smtp>,
24+}
25+
26+#[derive(Clone, Deserialize)]
27+pub struct Smtp {
28+ pub host: String,
29+ pub port: u16,
30+ pub username: String,
31+ pub password: String,
32+ pub from: String,
33+}
34+
35+#[derive(Deserialize)]
36+struct Raw {
37+ database: Option<String>,
38+ listen: Option<String>,
39+ issuer: Option<String>,
40+ smtp: Option<Smtp>,
41+}
42+
43+impl Config {
44+ pub fn load() -> std::result::Result<Config, String> {
45+ let path = Path::new(PATH);
46+ if !path.exists() {
47+ if let Some(dir) = path.parent() {
48+ std::fs::create_dir_all(dir)
49+ .map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
50+ }
51+ std::fs::write(path, DEFAULTS).map_err(|e| format!("cannot write {PATH}: {e}"))?;
52+ }
53+ let text = std::fs::read_to_string(path).map_err(|e| format!("cannot read {PATH}: {e}"))?;
54+ let raw: Raw = toml::from_str(&text).map_err(|e| format!("{PATH}: {e}"))?;
55+ let issuer = raw
56+ .issuer
57+ .unwrap_or_else(|| "http://127.0.0.1:7650".to_string());
58+ if !issuer.starts_with("http://") && !issuer.starts_with("https://") {
59+ return Err(format!("{PATH}: issuer {issuer:?} must be an http(s) URL"));
60+ }
61+ Ok(Config {
62+ database: PathBuf::from(raw.database.unwrap_or_else(|| "im.db".to_string())),
63+ listen: raw
64+ .listen
65+ .unwrap_or_else(|| "127.0.0.1:7650".to_string())
66+ .parse()
67+ .map_err(|e| format!("{PATH}: listen: {e}"))?,
68+ issuer: issuer.trim_end_matches('/').to_string(),
69+ smtp: raw.smtp,
70+ })
71+ }
72+
73+ /// Cookies are `Secure` only when the issuer is https — the dev issuer is
74+ /// plain http, and a Secure cookie over it would never stick.
75+ pub fn is_secure(&self) -> bool {
76+ self.issuer.starts_with("https://")
77+ }
78+
79+ /// The startup log lines: which file, which address, which issuer.
80+ pub fn report(&self) -> Vec<String> {
81+ vec![
82+ format!("database {}", self.database.display()),
83+ format!("listen {}", self.listen),
84+ format!("issuer {}", self.issuer),
85+ format!(
86+ "mail {}",
87+ if self.smtp.is_some() {
88+ "smtp"
89+ } else {
90+ "stdout (dev)"
91+ }
92+ ),
93+ ]
94+ }
95+}
crates/im-web/src/layout.rsadded+48 -0
@@ -0,0 +1,48 @@
1+//! The document shell every im page renders through. No hydration, no
2+//! runtime script: pages are plain HTML forms, posted hard.
3+
4+use topcoat::Result;
5+use topcoat::asset::{Asset, asset};
6+use topcoat::context::Cx;
7+use topcoat::view::view;
8+
9+/// `style/main.scss`, compiled by `build.rs` into `assets/main.css`.
10+const STYLE: Asset = asset!("assets/main.css");
11+
12+/// The mark, in the word as it is in the name: lower case, the Turkish
13+/// tittle. Text-only here — the auth card is the whole chrome.
14+pub async fn wordmark(cx: &Cx) -> Result {
15+ view! {
16+ cx =>
17+ <span class="wordmark">
18+ <span class="wordmark-text">"im"</span>
19+ </span>
20+ }
21+}
22+
23+/// A full document around an already-rendered stage — the same way
24+/// izlek-web's `#[layout]` receives its slot.
25+pub async fn shell(cx: &Cx, title: &str, stage: Result) -> Result {
26+ let stage = stage?;
27+ view! {
28+ cx =>
29+ <!DOCTYPE html>
30+ <html lang="en">
31+ <head>
32+ <meta charset="utf-8">
33+ <meta name="viewport" content="width=device-width, initial-scale=1">
34+ <link rel="preconnect" href="https://fonts.googleapis.com">
35+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="">
36+ <link
37+ rel="stylesheet"
38+ href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&display=swap"
39+ >
40+ <title>(title)</title>
41+ <link rel="stylesheet" href=(STYLE)>
42+ </head>
43+ <body>
44+ (stage)
45+ </body>
46+ </html>
47+ }
48+}
crates/im-web/src/main.rsadded+197 -0
@@ -0,0 +1,197 @@
1+//! im — the IzlekLab SSO. Server by default; `invite` and `create-client`
2+//! are the admin surface until there is a settings screen.
3+
4+use std::sync::Arc;
5+
6+use im_core::store::Store;
7+use topcoat::Result;
8+use topcoat::asset::RouterBuilderAssetExt;
9+use topcoat::cookie::RouterBuilderCookieExt;
10+use topcoat::router::{Router, RouterBuilderDiscoverExt, route};
11+
12+mod auth;
13+mod config;
14+mod layout;
15+mod oidc;
16+mod pages;
17+mod server;
18+
19+use config::Config;
20+
21+#[route(GET "/healthz")]
22+async fn healthz() -> Result<&'static str> {
23+ Ok("ok")
24+}
25+
26+#[tokio::main]
27+async fn main() {
28+ let args: Vec<String> = std::env::args().collect();
29+ let config = match Config::load() {
30+ Ok(config) => config,
31+ Err(problem) => {
32+ eprintln!("im: {problem}");
33+ std::process::exit(2);
34+ }
35+ };
36+
37+ match args.get(1).map(String::as_str) {
38+ None => serve(config).await,
39+ Some("invite") => {
40+ let Some(email) = args.get(2) else {
41+ eprintln!("usage: im-web invite <email>");
42+ std::process::exit(2);
43+ };
44+ invite(config, email).await;
45+ }
46+ Some("create-client") => {
47+ let (Some(name), uris) = (args.get(2), args.get(3..).unwrap_or(&[])) else {
48+ eprintln!("usage: im-web create-client <name> <redirect-uri> [more-uris...]");
49+ std::process::exit(2);
50+ };
51+ if uris.is_empty() {
52+ eprintln!("usage: im-web create-client <name> <redirect-uri> [more-uris...]");
53+ std::process::exit(2);
54+ }
55+ create_client(config, name, uris).await;
56+ }
57+ Some(other) => {
58+ eprintln!(
59+ "im: unknown command {other:?} (expected: invite, create-client, or none to serve)"
60+ );
61+ std::process::exit(2);
62+ }
63+ }
64+}
65+
66+async fn open_store(config: &Config) -> Arc<Store> {
67+ Arc::new(
68+ Store::open(&config.database)
69+ .await
70+ .expect("failed to open the database"),
71+ )
72+}
73+
74+/// `im-web invite <email>`: creates the invite, mails it when SMTP is
75+/// configured, prints the link otherwise (dev mode).
76+async fn invite(config: Config, email: &str) {
77+ let store = open_store(&config).await;
78+ let token = im_core::accounts::create_invite(&store, email, None)
79+ .await
80+ .expect("failed to create the invite");
81+ let link = format!("{}/invite/{}", config.issuer, token.expose());
82+ match build_mailer(&config) {
83+ Some(mailer) => {
84+ let message = lettre::Message::builder()
85+ .from(
86+ config
87+ .smtp
88+ .as_ref()
89+ .unwrap()
90+ .from
91+ .parse()
92+ .expect("smtp.from"),
93+ )
94+ .to(email.parse().expect("invite email"))
95+ .subject("You're invited")
96+ .body(format!(
97+ "You've been invited. This link is yours for {} days:\n\n{link}\n",
98+ im_core::accounts::INVITE_DAYS
99+ ))
100+ .expect("invite mail");
101+ use lettre::AsyncTransport;
102+ mailer
103+ .send(message)
104+ .await
105+ .expect("failed to send the invite");
106+ println!("im invite mailed to {email}");
107+ }
108+ None => println!("im invite for {email}: {link}"),
109+ }
110+}
111+
112+/// `im-web create-client <name> <uris...>`: registers a relying party and
113+/// prints the secret exactly once.
114+async fn create_client(config: Config, name: &str, uris: &[String]) {
115+ let store = open_store(&config).await;
116+ let (id, secret) = im_core::oidc::create_client(&store, name, uris.to_vec())
117+ .await
118+ .expect("failed to create the client");
119+ println!("im client {name}");
120+ println!(" client_id {id}");
121+ println!(" client_secret {}", secret.expose());
122+ println!(" (the secret is shown once; its digest is all the database keeps)");
123+}
124+
125+fn build_mailer(config: &Config) -> Option<lettre::AsyncSmtpTransport<lettre::Tokio1Executor>> {
126+ let smtp = config.smtp.as_ref()?;
127+ let creds = lettre::transport::smtp::authentication::Credentials::new(
128+ smtp.username.clone(),
129+ smtp.password.clone(),
130+ );
131+ Some(
132+ lettre::AsyncSmtpTransport::<lettre::Tokio1Executor>::relay(&smtp.host)
133+ .expect("smtp relay")
134+ .port(smtp.port)
135+ .credentials(creds)
136+ .build(),
137+ )
138+}
139+
140+async fn serve(config: Config) {
141+ for line in config.report() {
142+ println!("im {line}");
143+ }
144+ let store = open_store(&config).await;
145+ let app = server::App {
146+ store,
147+ config: config.clone(),
148+ };
149+
150+ // The bundle beside the executable is the only stylesheet this process
151+ // can serve — `topcoat asset bundle -p im-web` produces it.
152+ let bundle = topcoat::asset::AssetBundle::load().unwrap_or_else(|err| {
153+ eprintln!("im: the asset bundle beside the executable failed to load: {err}");
154+ eprintln!("im: run `topcoat asset bundle -p im-web` first");
155+ std::process::exit(2);
156+ });
157+
158+ let router = Router::builder()
159+ .discover()
160+ .cookies()
161+ .assets(bundle)
162+ .app_context(app)
163+ .build();
164+
165+ // `topcoat::start` binds HOST/PORT from the environment; the listen
166+ // address is a config/im.toml decision, so the listener is bound
167+ // explicitly against the same value the boot log just printed.
168+ let listener = tokio::net::TcpListener::bind(config.listen)
169+ .await
170+ .expect("failed to bind the listen address");
171+ topcoat::serve_until(listener, router, shutdown_signal())
172+ .await
173+ .expect("server error");
174+}
175+
176+/// Resolves when the process is asked to stop: Ctrl+C, or `SIGTERM` from a
177+/// service manager.
178+async fn shutdown_signal() {
179+ let ctrl_c = async {
180+ tokio::signal::ctrl_c()
181+ .await
182+ .expect("failed to install the Ctrl+C handler");
183+ };
184+ #[cfg(unix)]
185+ let terminate = async {
186+ tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
187+ .expect("failed to install the SIGTERM handler")
188+ .recv()
189+ .await;
190+ };
191+ #[cfg(not(unix))]
192+ let terminate = std::future::pending::<()>();
193+ tokio::select! {
194+ () = ctrl_c => {},
195+ () = terminate => {},
196+ }
197+}
crates/im-web/src/oidc.rsadded+361 -0
@@ -0,0 +1,361 @@
1+//! The OIDC surface: discovery, JWKS, authorize, token, userinfo. The pages
2+//! are for people; these are for apps — im-client first, any OIDC-speaking
3+//! client after.
4+
5+use im_core::model::{ClientId, UserId};
6+use im_core::oidc;
7+use serde::Deserialize;
8+use topcoat::Result;
9+use topcoat::context::Cx;
10+use topcoat::router::content::{Form, Json};
11+use topcoat::router::request::{headers, uri};
12+use topcoat::router::response::{IntoResponse, Response};
13+use topcoat::router::{HeaderValue, StatusCode, header, route};
14+
15+use crate::server::{self, App};
16+
17+fn app(cx: &Cx) -> &App {
18+ server::app(cx)
19+}
20+
21+/// A JSON OIDC error: `{"error": code}` with the matching status.
22+fn oidc_error(cx: &Cx, status: StatusCode, code: &str) -> Result<Response> {
23+ (status, Json(serde_json::json!({ "error": code }))).into_response(cx)
24+}
25+
26+#[route(GET "/.well-known/openid-configuration")]
27+async fn discovery(cx: &Cx) -> Result<Json<serde_json::Value>> {
28+ let issuer = &app(cx).config.issuer;
29+ Ok(Json(serde_json::json!({
30+ "issuer": issuer,
31+ "authorization_endpoint": format!("{issuer}/authorize"),
32+ "token_endpoint": format!("{issuer}/token"),
33+ "userinfo_endpoint": format!("{issuer}/userinfo"),
34+ "jwks_uri": format!("{issuer}/jwks.json"),
35+ "response_types_supported": ["code"],
36+ "grant_types_supported": ["authorization_code", "refresh_token"],
37+ "subject_types_supported": ["public"],
38+ "id_token_signing_alg_values_supported": ["RS256"],
39+ "scopes_supported": ["openid", "profile", "email"],
40+ "claims_supported": ["iss", "sub", "aud", "exp", "iat", "nonce", "email", "name"],
41+ "code_challenge_methods_supported": ["S256"],
42+ })))
43+}
44+
45+#[route(GET "/jwks.json")]
46+async fn jwks(cx: &Cx) -> Result<Json<serde_json::Value>> {
47+ Ok(Json(im_core::keys::jwks(&app(cx).store).await?))
48+}
49+
50+// ---------------------------------------------------------------------------
51+// /authorize
52+// ---------------------------------------------------------------------------
53+
54+/// The OIDC error redirect: only ever sent after the client AND the exact
55+/// redirect_uri have checked out — otherwise the answer is a bare 400, never
56+// a redirect to an address a stranger supplied.
57+fn authorize_error(
58+ cx: &Cx,
59+ redirect_uri: &str,
60+ state: Option<&str>,
61+ error: &str,
62+) -> Result<Response> {
63+ let sep = if redirect_uri.contains('?') { '&' } else { '?' };
64+ let mut location = format!("{redirect_uri}{sep}error={error}");
65+ if let Some(state) = state {
66+ location.push_str(&format!("&state={state}"));
67+ }
68+ (
69+ StatusCode::SEE_OTHER,
70+ [(
71+ header::LOCATION,
72+ HeaderValue::from_str(&location).unwrap_or_else(|_| HeaderValue::from_static("/")),
73+ )],
74+ )
75+ .into_response(cx)
76+}
77+
78+fn bad_request(cx: &Cx) -> Result<Response> {
79+ (StatusCode::BAD_REQUEST, "invalid request").into_response(cx)
80+}
81+
82+/// Percent-encodes a value for a query pair — the `back` a login carries is
83+/// a local `/authorize?...` URL, full of `?&=` of its own.
84+fn urlencode(raw: &str) -> String {
85+ let mut out = String::with_capacity(raw.len());
86+ for byte in raw.bytes() {
87+ match byte {
88+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
89+ out.push(byte as char)
90+ }
91+ _ => out.push_str(&format!("%{byte:02X}")),
92+ }
93+ }
94+ out
95+}
96+
97+#[route(GET "/authorize")]
98+async fn authorize(cx: &Cx) -> Result<Response> {
99+ let query = uri(cx).query().unwrap_or("").to_string();
100+ let get = |key: &str| crate::pages::query_value(&query, key);
101+
102+ // Client identity first: nothing redirects anywhere until both the client
103+ // and the exact redirect_uri are known-good.
104+ let Some(client_id) = get("client_id") else {
105+ return bad_request(cx);
106+ };
107+ let Some(client) = oidc::client_by_id(&app(cx).store, &client_id).await? else {
108+ return bad_request(cx);
109+ };
110+ let Some(redirect_uri) = get("redirect_uri") else {
111+ return bad_request(cx);
112+ };
113+ if !client.redirect_uris.contains(&redirect_uri) {
114+ return bad_request(cx);
115+ }
116+ let state = get("state");
117+
118+ if get("response_type").as_deref() != Some("code") {
119+ return authorize_error(
120+ cx,
121+ &redirect_uri,
122+ state.as_deref(),
123+ "unsupported_response_type",
124+ );
125+ }
126+ let scope = get("scope").unwrap_or_default();
127+ let scopes: Vec<&str> = scope.split(' ').collect();
128+ if !scopes.contains(&"openid")
129+ || !scopes
130+ .iter()
131+ .all(|s| ["openid", "profile", "email"].contains(s))
132+ {
133+ return authorize_error(cx, &redirect_uri, state.as_deref(), "invalid_scope");
134+ }
135+ let Some(challenge) = get("code_challenge") else {
136+ return authorize_error(cx, &redirect_uri, state.as_deref(), "invalid_request");
137+ };
138+ if get("code_challenge_method").as_deref() != Some("S256") {
139+ return authorize_error(cx, &redirect_uri, state.as_deref(), "invalid_request");
140+ }
141+
142+ // The central session is the whole point: a browser that already signed
143+ // in (password and second factor both behind it) gets its code without
144+ // seeing a form at all.
145+ let presented = server::presented_session(cx);
146+ let user = match &presented {
147+ Some(token) => im_core::sessions::resolve_session(&app(cx).store, token).await?,
148+ None => None,
149+ };
150+ let Some(user) = user else {
151+ let back = format!("/authorize?{query}");
152+ let location = format!("/login?back={}", urlencode(&back));
153+ return (
154+ StatusCode::SEE_OTHER,
155+ [(header::LOCATION, HeaderValue::from_str(&location).unwrap())],
156+ )
157+ .into_response(cx);
158+ };
159+ let session_hash = im_core::accounts::hash_token(presented.as_deref().unwrap_or_default());
160+ let code = oidc::create_auth_code(
161+ &app(cx).store,
162+ &client.client_id,
163+ &user.id,
164+ &redirect_uri,
165+ get("nonce"),
166+ &challenge,
167+ &session_hash,
168+ )
169+ .await?;
170+ let sep = if redirect_uri.contains('?') { '&' } else { '?' };
171+ let mut location = format!("{redirect_uri}{sep}code={}", code.expose());
172+ if let Some(state) = state {
173+ location.push_str(&format!("&state={state}"));
174+ }
175+ (
176+ StatusCode::SEE_OTHER,
177+ [(header::LOCATION, HeaderValue::from_str(&location).unwrap())],
178+ )
179+ .into_response(cx)
180+}
181+
182+// ---------------------------------------------------------------------------
183+// /token
184+// ---------------------------------------------------------------------------
185+
186+#[derive(Deserialize)]
187+struct TokenForm {
188+ grant_type: String,
189+ code: Option<String>,
190+ redirect_uri: Option<String>,
191+ client_id: Option<String>,
192+ client_secret: Option<String>,
193+ code_verifier: Option<String>,
194+ refresh_token: Option<String>,
195+}
196+
197+/// Signs the pair of tokens for `user` toward `client`.
198+async fn mint_tokens(
199+ cx: &Cx,
200+ user: &im_core::model::User,
201+ client_id: &ClientId,
202+ nonce: Option<String>,
203+) -> Result<(String, String)> {
204+ let now = time::OffsetDateTime::now_utc().unix_timestamp();
205+ let issuer = &app(cx).config.issuer;
206+ let (kid, key) = im_core::keys::active_signing_key(&app(cx).store).await?;
207+ let id_claims = serde_json::json!({
208+ "iss": issuer,
209+ "sub": user.id.as_str(),
210+ "aud": client_id.as_str(),
211+ "exp": now + oidc::TOKEN_SECONDS,
212+ "iat": now,
213+ "email": user.email,
214+ "name": user.name,
215+ "nonce": nonce,
216+ });
217+ let access_claims = serde_json::json!({
218+ "iss": issuer,
219+ "sub": user.id.as_str(),
220+ "aud": client_id.as_str(),
221+ "exp": now + oidc::TOKEN_SECONDS,
222+ "iat": now,
223+ "scope": "openid profile email",
224+ });
225+ Ok((
226+ oidc::sign_jwt(&access_claims, &kid, &key),
227+ oidc::sign_jwt(&id_claims, &kid, &key),
228+ ))
229+}
230+
231+fn token_answer(cx: &Cx, access: String, id: String, refresh: String) -> Result<Response> {
232+ Json(serde_json::json!({
233+ "access_token": access,
234+ "token_type": "Bearer",
235+ "expires_in": oidc::TOKEN_SECONDS,
236+ "refresh_token": refresh,
237+ "id_token": id,
238+ }))
239+ .into_response(cx)
240+}
241+
242+#[route(POST "/token")]
243+async fn exchange(cx: &Cx, Form(input): Form<TokenForm>) -> Result<Response> {
244+ let Some(client_id) = input.client_id else {
245+ return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_request");
246+ };
247+ let Some(client) = oidc::client_by_id(&app(cx).store, &client_id).await? else {
248+ return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_client");
249+ };
250+ let Some(secret) = input.client_secret else {
251+ return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_client");
252+ };
253+ if !oidc::verify_client_secret(&client, &secret) {
254+ return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_client");
255+ }
256+
257+ match input.grant_type.as_str() {
258+ "authorization_code" => {
259+ let (Some(code), Some(redirect_uri), Some(verifier)) =
260+ (input.code, input.redirect_uri, input.code_verifier)
261+ else {
262+ return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_request");
263+ };
264+ let Some(consumed) = oidc::consume_auth_code(&app(cx).store, &code).await? else {
265+ return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
266+ };
267+ if consumed.client_id != client.client_id
268+ || consumed.redirect_uri != redirect_uri
269+ || !oidc::pkce_matches(&consumed.code_challenge, &verifier)
270+ {
271+ return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
272+ }
273+ let Some(user) =
274+ im_core::accounts::user_by_id(&app(cx).store, &consumed.user_id).await?
275+ else {
276+ return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
277+ };
278+ if user.disabled {
279+ return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
280+ }
281+ let (access, id) = mint_tokens(cx, &user, &client.client_id, consumed.nonce).await?;
282+ let refresh = oidc::issue_refresh(
283+ &app(cx).store,
284+ &user.id,
285+ &client.client_id,
286+ &consumed.session_hash,
287+ )
288+ .await?;
289+ token_answer(cx, access, id, refresh.expose().to_string())
290+ }
291+ "refresh_token" => {
292+ let Some(presented) = input.refresh_token else {
293+ return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_request");
294+ };
295+ let Some((fresh, old)) = oidc::rotate_refresh(&app(cx).store, &presented).await? else {
296+ return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
297+ };
298+ if old.client_id != client.client_id {
299+ return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
300+ }
301+ let Some(user) = im_core::accounts::user_by_id(&app(cx).store, &old.user_id).await?
302+ else {
303+ return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
304+ };
305+ if user.disabled {
306+ return oidc_error(cx, StatusCode::BAD_REQUEST, "invalid_grant");
307+ }
308+ let (access, id) = mint_tokens(cx, &user, &client.client_id, None).await?;
309+ token_answer(cx, access, id, fresh.expose().to_string())
310+ }
311+ _ => oidc_error(cx, StatusCode::BAD_REQUEST, "unsupported_grant_type"),
312+ }
313+}
314+
315+// ---------------------------------------------------------------------------
316+// /userinfo
317+// ---------------------------------------------------------------------------
318+
319+#[route(GET "/userinfo")]
320+async fn userinfo(cx: &Cx) -> Result<Response> {
321+ let presented = headers(cx)
322+ .get(header::AUTHORIZATION)
323+ .and_then(|value| value.to_str().ok())
324+ .and_then(|value| value.strip_prefix("Bearer "))
325+ .map(str::to_string);
326+ let Some(presented) = presented else {
327+ return (
328+ StatusCode::UNAUTHORIZED,
329+ [(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer"))],
330+ )
331+ .into_response(cx);
332+ };
333+ // Signature and expiry first; the audience is checked against the client
334+ // registry, not a fixed value — any registered app may ask.
335+ let Some(claims) = oidc::verify_jwt(&app(cx).store, &presented, None).await? else {
336+ return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_token");
337+ };
338+ let Some(aud) = claims["aud"].as_str() else {
339+ return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_token");
340+ };
341+ if oidc::client_by_id(&app(cx).store, aud).await?.is_none() {
342+ return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_token");
343+ }
344+ let Some(sub) = claims["sub"].as_str() else {
345+ return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_token");
346+ };
347+ let Some(user) =
348+ im_core::accounts::user_by_id(&app(cx).store, &UserId::from(sub.to_string())).await?
349+ else {
350+ return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_token");
351+ };
352+ if user.disabled {
353+ return oidc_error(cx, StatusCode::UNAUTHORIZED, "invalid_token");
354+ }
355+ Json(serde_json::json!({
356+ "sub": user.id.as_str(),
357+ "email": user.email,
358+ "name": user.name,
359+ }))
360+ .into_response(cx)
361+}
crates/im-web/src/pages.rsadded+417 -0
@@ -0,0 +1,417 @@
1+//! The pages: sign-in, the second factor, invite acceptance, TOTP enrolment,
2+//! and the signed-in landing. Every page is server-rendered on every request;
3+//! a refused form post comes back as `?error=<code>` on the query and the
4+//! page reads it out.
5+
6+use im_core::accounts::MIN_PASSWORD_CHARS;
7+use topcoat::Result;
8+use topcoat::context::Cx;
9+use topcoat::router::error::see_other;
10+use topcoat::router::response::{IntoResponse, Response};
11+use topcoat::router::{page, path_param, route};
12+use topcoat::view::view;
13+
14+use crate::layout::{shell, wordmark};
15+use crate::server::{self, PendingPurpose};
16+
17+path_param!(token);
18+
19+/// What a refusal code reads as on the page. The code travels through the
20+/// URL; the sentence never does.
21+pub fn error_text(code: &str) -> &'static str {
22+ match code {
23+ "bad_login" => "Wrong email or password.",
24+ "bad_code" => "That code didn't match — try again.",
25+ "invite_invalid" => "This invite link is not valid.",
26+ "invite_expired" => "This invite has expired. Ask for a fresh one.",
27+ "invite_spent" => "This invite was already used.",
28+ "email_taken" => "An account with this address already exists.",
29+ "password_too_short" => "The password needs at least 10 characters.",
30+ "password_personal" => "The password can't contain your address or your name.",
31+ "passwords_differ" => "The two passwords don't match.",
32+ "enroll_first" => "Set up your second factor first.",
33+ _ => "Something went wrong. Try again.",
34+ }
35+}
36+
37+/// The refusal this request carries back, if any. Values come percent-
38+/// decoded: `redirect_uri=http%3A%2F%2F…` must equal the registered URI.
39+pub fn query_value(query: &str, key: &str) -> Option<String> {
40+ query.split('&').find_map(|pair| {
41+ let (k, v) = pair.split_once('=')?;
42+ (k == key).then(|| urldecode(v))
43+ })
44+}
45+
46+/// Percent-decodes a query value (`+` is a space, form-style).
47+pub fn urldecode(raw: &str) -> String {
48+ let bytes = raw.as_bytes();
49+ let mut out = Vec::with_capacity(bytes.len());
50+ let mut i = 0;
51+ while i < bytes.len() {
52+ match bytes[i] {
53+ b'+' => {
54+ out.push(b' ');
55+ i += 1;
56+ }
57+ b'%' if i + 2 < bytes.len() => {
58+ let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or("");
59+ match u8::from_str_radix(hex, 16) {
60+ Ok(byte) => {
61+ out.push(byte);
62+ i += 3;
63+ }
64+ Err(_) => {
65+ out.push(b'%');
66+ i += 1;
67+ }
68+ }
69+ }
70+ byte => {
71+ out.push(byte);
72+ i += 1;
73+ }
74+ }
75+ }
76+ String::from_utf8_lossy(&out).into_owned()
77+}
78+
79+fn current_query(cx: &Cx) -> String {
80+ topcoat::router::request::uri(cx)
81+ .query()
82+ .unwrap_or("")
83+ .to_string()
84+}
85+
86+/// The front door: the sign-in card, or the signed-in landing when the
87+/// browser already holds a session.
88+#[page("/")]
89+async fn landing(cx: &Cx) -> Result {
90+ match server::current_user(cx).await {
91+ Some(user) => signed_in(cx, &user).await,
92+ None => login_card(cx).await,
93+ }
94+}
95+
96+/// `/login` is the same card with a `back` it must keep: the `/authorize`
97+/// call the browser was in the middle of.
98+#[page("/login")]
99+async fn login(cx: &Cx) -> Result {
100+ login_card(cx).await
101+}
102+
103+async fn login_card(cx: &Cx) -> Result {
104+ let query = current_query(cx);
105+ let back = query_value(&query, "back").unwrap_or_else(|| "/".to_string());
106+ let error = query_value(&query, "error");
107+ let stage = view! {
108+ cx =>
109+ <main class="auth-stage">
110+ <div class="auth-column">
111+ (wordmark(cx).await?)
112+ <div class="auth-card">
113+ <div class="auth-head">
114+ <div class="auth-title">"Sign in"</div>
115+ <div class="auth-sub">"One account for everything IzlekLab."</div>
116+ </div>
117+ if let Some(code) = error {
118+ <div class="auth-problem">(error_text(&code))</div>
119+ }
120+ <form method="post" action="/login">
121+ <input type="hidden" name="back" value=(back)>
122+ <label class="auth-field">
123+ <span class="auth-label">"Email"</span>
124+ <input
125+ class="auth-input auth-input-mono"
126+ type="email"
127+ name="email"
128+ autocomplete="email"
129+ required=""
130+ >
131+ </label>
132+ <label class="auth-field">
133+ <span class="auth-label">"Password"</span>
134+ <input
135+ class="auth-input auth-input-mono"
136+ type="password"
137+ name="password"
138+ autocomplete="current-password"
139+ required=""
140+ >
141+ </label>
142+ <button class="auth-submit" type="submit">
143+ <span class="auth-submit-text">"Sign in"</span>
144+ </button>
145+ </form>
146+ </div>
147+ <div class="auth-footer">"im · IzlekLab SSO"</div>
148+ </div>
149+ </main>
150+ };
151+ shell(cx, "Sign in · im", stage).await
152+}
153+
154+/// The second factor. Reached only with a pending-login cookie; without one
155+/// the request starts over at the sign-in card.
156+#[route(GET "/login/totp")]
157+async fn totp(cx: &Cx) -> Result<Response> {
158+ match server::opened_pending(cx) {
159+ Some(pending) if pending.purpose == PendingPurpose::Login => {
160+ let query = current_query(cx);
161+ let error = query_value(&query, "error");
162+ let stage = view! {
163+ cx =>
164+ <main class="auth-stage">
165+ <div class="auth-column">
166+ (wordmark(cx).await?)
167+ <div class="auth-card">
168+ <div class="auth-head">
169+ <div class="auth-title">"Two-factor code"</div>
170+ <div class="auth-sub">"The 6-digit code from your authenticator."</div>
171+ </div>
172+ if let Some(code) = error {
173+ <div class="auth-problem">(error_text(&code))</div>
174+ }
175+ <form method="post" action="/login/totp">
176+ <label class="auth-field">
177+ <span class="auth-label">"Code"</span>
178+ <input
179+ class="auth-input auth-input-mono"
180+ type="text"
181+ name="code"
182+ inputmode="numeric"
183+ pattern="[0-9]{6}"
184+ autocomplete="one-time-code"
185+ required=""
186+ >
187+ </label>
188+ <button class="auth-submit" type="submit">
189+ <span class="auth-submit-text">"Verify"</span>
190+ </button>
191+ </form>
192+ </div>
193+ <div class="auth-footer">"im · IzlekLab SSO"</div>
194+ </div>
195+ </main>
196+ };
197+ shell(cx, "Two-factor · im", stage).await?.into_response(cx)
198+ }
199+ _ => see_other("/login").into_response(cx),
200+ }
201+}
202+
203+/// The invited member's first screen: name and password, address locked to
204+/// what the invite carries.
205+#[route(GET "/invite/{token}")]
206+async fn invite(cx: &Cx) -> Result<Response> {
207+ let token: &str = path_param::<Token>(cx);
208+ let invite = im_core::accounts::invite_by_token(&server::app(cx).store, token).await?;
209+ let query = current_query(cx);
210+ let error = query_value(&query, "error");
211+
212+ let usable = matches!(
213+ &invite,
214+ Some(invite) if invite.accepted_at.is_none() && invite.expires_at > time::OffsetDateTime::now_utc()
215+ );
216+ let stage = if usable {
217+ let invite = invite.expect("usable implies Some");
218+ view! {
219+ cx =>
220+ <main class="auth-stage">
221+ <div class="auth-column">
222+ (wordmark(cx).await?)
223+ <div class="auth-card">
224+ <div class="auth-head">
225+ <div class="auth-title">"You're invited"</div>
226+ <div class="auth-sub">"Pick a name and a password. Next step sets up two-factor sign-in."</div>
227+ </div>
228+ if let Some(code) = error {
229+ <div class="auth-problem">(error_text(&code))</div>
230+ }
231+ <form method="post" action="/invite">
232+ <input type="hidden" name="token" value=(token.to_string())>
233+ <div class="auth-field">
234+ <span class="auth-label">"Email"</span>
235+ <div class="auth-locked">
236+ <span class="auth-locked-value">(invite.email)</span>
237+ </div>
238+ </div>
239+ <label class="auth-field">
240+ <span class="auth-label">"Your name"</span>
241+ <input
242+ class="auth-input"
243+ type="text"
244+ name="name"
245+ autocomplete="name"
246+ required=""
247+ >
248+ </label>
249+ <label class="auth-field">
250+ <span class="auth-label">"Password"</span>
251+ <input
252+ class="auth-input auth-input-mono"
253+ type="password"
254+ name="password"
255+ autocomplete="new-password"
256+ minlength=(MIN_PASSWORD_CHARS.to_string())
257+ required=""
258+ >
259+ </label>
260+ <label class="auth-field">
261+ <span class="auth-label">"Password again"</span>
262+ <input
263+ class="auth-input auth-input-mono"
264+ type="password"
265+ name="password_confirm"
266+ autocomplete="new-password"
267+ minlength=(MIN_PASSWORD_CHARS.to_string())
268+ required=""
269+ >
270+ </label>
271+ <button class="auth-submit" type="submit">
272+ <span class="auth-submit-text">"Create account"</span>
273+ </button>
274+ </form>
275+ </div>
276+ <div class="auth-footer">"im · IzlekLab SSO"</div>
277+ </div>
278+ </main>
279+ }
280+ } else {
281+ let code = match &invite {
282+ None => "invite_invalid",
283+ Some(i) if i.accepted_at.is_some() => "invite_spent",
284+ _ => "invite_expired",
285+ };
286+ view! {
287+ cx =>
288+ <main class="auth-stage">
289+ <div class="auth-column">
290+ (wordmark(cx).await?)
291+ <div class="auth-card">
292+ <div class="auth-head">
293+ <div class="auth-title">"This link doesn't work"</div>
294+ </div>
295+ <div class="auth-problem">(error_text(code))</div>
296+ <a class="auth-alt" href="/">"Back to sign in"</a>
297+ </div>
298+ </div>
299+ </main>
300+ }
301+ };
302+ shell(cx, "You're invited · im", stage)
303+ .await?
304+ .into_response(cx)
305+}
306+
307+/// TOTP enrolment: the QR, the manual key, and the first code that proves
308+/// the authenticator agrees. Reached with a pending-enroll cookie, set when
309+/// the account was created.
310+#[route(GET "/enroll")]
311+async fn enroll(cx: &Cx) -> Result<Response> {
312+ let Some(pending) = server::opened_pending(cx) else {
313+ return see_other("/login").into_response(cx);
314+ };
315+ if pending.purpose != PendingPurpose::Enroll {
316+ return see_other("/login").into_response(cx);
317+ }
318+ let user = im_core::accounts::user_by_id(
319+ &server::app(cx).store,
320+ &im_core::model::UserId::from(pending.user.clone()),
321+ )
322+ .await?
323+ .ok_or_else(|| topcoat::Error::from(std::io::Error::other("pending user is gone")))?;
324+ let Some((secret, _confirmed)) =
325+ im_core::totp::totp_secret(&server::app(cx).store, &user.id).await?
326+ else {
327+ return see_other("/login?error=enroll_first").into_response(cx);
328+ };
329+
330+ let issuer = &server::app(cx).config.issuer;
331+ let uri = im_core::totp::totp_uri("im", &user.email, &secret);
332+ let qr = qrcode::QrCode::new(uri.as_bytes())
333+ .and_then(|code| {
334+ Ok::<_, qrcode::types::QrError>(
335+ code.render::<qrcode::render::svg::Color>()
336+ .min_dimensions(200, 200)
337+ .build(),
338+ )
339+ })
340+ .map_err(|e| topcoat::Error::from(std::io::Error::other(format!("qr: {e}"))))?;
341+ let manual = im_core::totp::display_secret(&secret);
342+ let _ = issuer;
343+ let query = current_query(cx);
344+ let error = query_value(&query, "error");
345+
346+ let stage = view! {
347+ cx =>
348+ <main class="auth-stage">
349+ <div class="auth-column">
350+ (wordmark(cx).await?)
351+ <div class="auth-card">
352+ <div class="auth-head">
353+ <div class="auth-title">"Set up two-factor"</div>
354+ <div class="auth-sub">"Scan with your authenticator, then type the 6-digit code it shows."</div>
355+ </div>
356+ if let Some(code) = error {
357+ <div class="auth-problem">(error_text(&code))</div>
358+ }
359+ <div class="auth-qr">(topcoat::view::Unescaped::new_unchecked(qr))</div>
360+ <div class="auth-secret">(manual)</div>
361+ <form method="post" action="/enroll">
362+ <label class="auth-field">
363+ <span class="auth-label">"Code"</span>
364+ <input
365+ class="auth-input auth-input-mono"
366+ type="text"
367+ name="code"
368+ inputmode="numeric"
369+ pattern="[0-9]{6}"
370+ autocomplete="one-time-code"
371+ required=""
372+ >
373+ </label>
374+ <button class="auth-submit" type="submit">
375+ <span class="auth-submit-text">"Confirm and sign in"</span>
376+ </button>
377+ </form>
378+ </div>
379+ <div class="auth-footer">"im · IzlekLab SSO"</div>
380+ </div>
381+ </main>
382+ };
383+ shell(cx, "Two-factor setup · im", stage)
384+ .await?
385+ .into_response(cx)
386+}
387+
388+/// The signed-in landing. im is an auth service, not an app: this page is
389+/// the proof of session, the way out, and nothing more.
390+async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result {
391+ let query = current_query(cx);
392+ let ok = query_value(&query, "ok");
393+ let stage = view! {
394+ cx =>
395+ <main class="auth-stage">
396+ <div class="auth-column">
397+ (wordmark(cx).await?)
398+ <div class="auth-card">
399+ <div class="auth-head">
400+ <div class="auth-title">(format!("Signed in as {}", user.name))</div>
401+ <div class="auth-sub">(user.email.clone())</div>
402+ </div>
403+ if ok.as_deref() == Some("enrolled") {
404+ <div class="auth-ok">"Two-factor sign-in is on. You're all set."</div>
405+ }
406+ <form method="post" action="/logout">
407+ <button class="auth-submit" type="submit">
408+ <span class="auth-submit-text">"Sign out everywhere"</span>
409+ </button>
410+ </form>
411+ </div>
412+ <div class="auth-footer">"im · IzlekLab SSO"</div>
413+ </div>
414+ </main>
415+ };
416+ shell(cx, "im", stage).await
417+}
crates/im-web/src/server.rsadded+149 -0
@@ -0,0 +1,149 @@
1+//! Shared request plumbing: the app context, the two cookies (`im_session`
2+//! for a completed login, `im_pending` for the ten minutes between password
3+//! and second factor), and the refusal codes a redirect carries back to the
4+//! page that posted the form.
5+//!
6+//! im serves no client-side script, so there is no refusal-carrying layer as
7+//! in İzlek: every form post answers a plain 303 whose query names the
8+//! refusal, and the page reads it back on render.
9+
10+use std::sync::Arc;
11+
12+use im_core::model::User;
13+use im_core::store::Store;
14+use topcoat::context::{Cx, try_app_context};
15+use topcoat::cookie::{Cookie, Cookies, cookie, cookies};
16+
17+use crate::config::Config;
18+
19+pub const SESSION_COOKIE: &str = "im_session";
20+pub const PENDING_COOKIE: &str = "im_pending";
21+
22+/// The pending marker's lifetime: long enough to find the authenticator,
23+/// short enough to not be a session.
24+pub const PENDING_MINUTES: i64 = 10;
25+
26+pub struct App {
27+ pub store: Arc<Store>,
28+ pub config: Config,
29+}
30+
31+pub fn app(cx: &Cx) -> &App {
32+ try_app_context::<App>(cx).expect("the router always carries the App")
33+}
34+
35+/// The application cookie jar, with the attributes every im cookie wants.
36+fn app_cookies(cx: &Cx) -> impl Cookies {
37+ cookies(cx)
38+ .default_secure(app(cx).config.is_secure())
39+ .default_http_only(true)
40+ .default_same_site(topcoat::cookie::SameSite::Lax)
41+ .default_path("/")
42+}
43+
44+/// The session cookie value this request presented, if it presented one.
45+pub fn presented_session(cx: &Cx) -> Option<String> {
46+ cookies(cx)
47+ .get(SESSION_COOKIE)
48+ .map(|c| c.value().to_string())
49+}
50+
51+pub fn presented_pending(cx: &Cx) -> Option<String> {
52+ cookies(cx)
53+ .get(PENDING_COOKIE)
54+ .map(|c| c.value().to_string())
55+}
56+
57+/// Writes the session cookie. `HttpOnly` so script cannot read it, `Secure`
58+/// (on https issuers) so it never crosses plain HTTP, `SameSite=Lax` so
59+/// another site's form cannot post with it — and so the top-level redirect
60+/// back from `/authorize` still carries it.
61+pub fn set_session_cookie(cx: &Cx, token: &str) {
62+ app_cookies(cx).add(cookie! {
63+ SESSION_COOKIE = token.to_owned();
64+ Path = "/";
65+ HttpOnly;
66+ SameSite = Lax;
67+ MaxAge = time::Duration::days(im_core::sessions::SESSION_DAYS)
68+ });
69+}
70+
71+pub fn set_pending_cookie(cx: &Cx, sealed: String) {
72+ app_cookies(cx).add(cookie! {
73+ PENDING_COOKIE = sealed;
74+ Path = "/";
75+ HttpOnly;
76+ SameSite = Lax;
77+ MaxAge = time::Duration::minutes(PENDING_MINUTES)
78+ });
79+}
80+
81+/// Removes the session cookie from this browser. The server-side revocation
82+/// is what actually ends the session; this only tidies the client.
83+pub fn clear_session_cookie(cx: &Cx) {
84+ app_cookies(cx).remove(Cookie::build((SESSION_COOKIE, "")).path("/").build());
85+}
86+
87+pub fn clear_pending_cookie(cx: &Cx) {
88+ app_cookies(cx).remove(Cookie::build((PENDING_COOKIE, "")).path("/").build());
89+}
90+
91+/// The person behind this request, resolved through the central session.
92+pub async fn current_user(cx: &Cx) -> Option<User> {
93+ let token = presented_session(cx)?;
94+ im_core::sessions::resolve_session(&app(cx).store, &token)
95+ .await
96+ .ok()
97+ .flatten()
98+}
99+
100+// ---------------------------------------------------------------------------
101+// The pending marker: between password and TOTP, between invite and enrolment
102+// ---------------------------------------------------------------------------
103+
104+#[derive(Debug, serde::Serialize, serde::Deserialize, PartialEq)]
105+#[serde(rename_all = "lowercase")]
106+pub enum PendingPurpose {
107+ /// Password verified, TOTP code still owed.
108+ Login,
109+ /// Account created, TOTP enrolment still owed.
110+ Enroll,
111+}
112+
113+#[derive(Debug, serde::Serialize, serde::Deserialize)]
114+pub struct Pending {
115+ pub user: String,
116+ pub purpose: PendingPurpose,
117+ /// The `/authorize` URL the login is in the middle of, urlencoded as it
118+ /// arrived; `/` when there is none.
119+ pub back: String,
120+ pub exp: i64,
121+}
122+
123+pub fn mint_pending(
124+ cx: &Cx,
125+ user: &im_core::model::UserId,
126+ purpose: PendingPurpose,
127+ back: String,
128+) -> String {
129+ let pending = Pending {
130+ user: user.to_string(),
131+ purpose,
132+ back,
133+ exp: time::OffsetDateTime::now_utc().unix_timestamp() + PENDING_MINUTES * 60,
134+ };
135+ let json = serde_json::to_string(&pending).expect("Pending is plain data");
136+ app(cx).store.seal_value(json.as_bytes())
137+}
138+
139+/// Opens the pending cookie this request presented. `None` for absent,
140+/// forged, or expired — all three mean "start the login over".
141+pub fn opened_pending(cx: &Cx) -> Option<Pending> {
142+ let sealed = presented_pending(cx)?;
143+ let bytes = app(cx).store.open_value(&sealed)?;
144+ let pending: Pending = serde_json::from_slice(&bytes).ok()?;
145+ if pending.exp <= time::OffsetDateTime::now_utc().unix_timestamp() {
146+ return None;
147+ }
148+ Some(pending)
149+}
style/main.scssadded+374 -0
@@ -0,0 +1,374 @@
1+// im — the IzlekLab SSO. One screen family: the auth card. The palette,
2+// rhythm and idioms are İzlek's "instrument" skin (warm-gray ground, quiet
3+// borders, the same accent family), lifted from izlek/style/main.scss so the
4+// two products read as one family.
5+//
6+// İzlek flips themes through a per-user `data-theme` setting; im has no
7+// settings screen, so dark follows `prefers-color-scheme`. The token set is
8+// the subset of İzlek's that the auth screens read.
9+
10+// Instrument, light (defaults; also the no-JS fallback).
11+:root {
12+ color-scheme: light;
13+ --bg: #f2f2f0;
14+ --surface: #fbfbfa;
15+ --border: #dcdcd8;
16+ --border-strong: #d0d0cb;
17+ --border-soft: #d3d3ce;
18+ --ink: #1a1b1d;
19+ --muted: #6b7078;
20+ --muted-soft: #6b7078;
21+ --accent: #46557b;
22+ --accent-tint: #eef0f5;
23+ --accent-ink: #2f3c5c;
24+ --accent-strong: #5a6a94;
25+
26+ --field-bg: #f5f5f3;
27+ --panel-sunken: #eeeeec;
28+
29+ --danger: #a04a24;
30+ --danger-tint-alt: #fbf1ec;
31+ --danger-border-soft: #eddcd3;
32+
33+ --positive: #5c7b46;
34+ --positive-tint: #eef3e9;
35+ --positive-border: #d3e0c6;
36+
37+ --font-sans: system-ui, sans-serif;
38+ --font-mono: 'IBM Plex Mono', ui-monospace, monospace;
39+
40+ --control-h-lg: 40px;
41+ --radius: 3px;
42+ --radius-sm: var(--radius);
43+ --radius-lg: 3px;
44+ --shadow-2: none;
45+
46+ --dur-fast: 120ms;
47+ --ease: ease-out;
48+}
49+
50+// Instrument, dark: near-black neutral-cool; tint fills go translucent and
51+// tint borders go alpha so the ground shows through.
52+@media (prefers-color-scheme: dark) {
53+ :root {
54+ color-scheme: dark;
55+ --bg: #0d0e10;
56+ --surface: #14161a;
57+ --border: #23262c;
58+ --border-strong: #2e323a;
59+ --border-soft: #1f2226;
60+ --ink: #e6e4de;
61+ --muted: #7d8590;
62+ --muted-soft: #4a4f58;
63+ --accent: #8ba1e8;
64+ --accent-tint: rgba(139, 161, 232, 0.14);
65+ --accent-ink: #b9c6ee;
66+ --accent-strong: #7e93d9;
67+
68+ --field-bg: #101216;
69+ --panel-sunken: #101216;
70+
71+ --danger: #e0906a;
72+ --danger-tint-alt: rgba(224, 144, 106, 0.05);
73+ --danger-border-soft: rgba(224, 144, 106, 0.3);
74+
75+ --positive: #9db98a;
76+ --positive-tint: rgba(157, 185, 138, 0.13);
77+ --positive-border: rgba(157, 185, 138, 0.4);
78+ }
79+}
80+
81+* { box-sizing: border-box; }
82+
83+body {
84+ margin: 0;
85+ background: var(--bg);
86+ color: var(--ink);
87+ font-family: var(--font-sans);
88+ font-size: 14px;
89+ line-height: 1.45;
90+ -webkit-font-smoothing: antialiased;
91+}
92+
93+a {
94+ color: var(--accent);
95+ transition: color var(--dur-fast) var(--ease);
96+ &:hover { color: var(--accent-ink); }
97+}
98+
99+// --- Account screens (the whole product, today) ----------------------------
100+
101+// The card centers in the viewport; a card taller than it (a landscape
102+// phone) pans inside the stage instead of growing the document.
103+body:has(.auth-stage) {
104+ height: 100vh;
105+ height: 100dvh;
106+ overflow: hidden;
107+ display: flex;
108+ flex-direction: column;
109+
110+ > * { flex: none; }
111+ > .auth-stage {
112+ flex: 1;
113+ min-height: 0;
114+ overflow-y: auto;
115+ scrollbar-width: none;
116+
117+ &::-webkit-scrollbar { display: none; }
118+ }
119+}
120+
121+.auth-stage {
122+ min-height: 100vh;
123+ min-height: 100dvh;
124+ display: flex;
125+ align-items: center;
126+ justify-content: center;
127+ padding: 0 40px 40px;
128+}
129+
130+.auth-column {
131+ width: 520px;
132+ max-width: 100%;
133+ display: flex;
134+ flex-direction: column;
135+ gap: 10px;
136+}
137+
138+// The brand lockup. Lower case, and not by taste: capitalised, the dotted
139+// `i` becomes `I` and the name reads as the English word. The tittle is the
140+// Turkish one, in the word as it is in the mark.
141+.wordmark {
142+ display: flex;
143+ align-items: center;
144+ justify-content: center;
145+ gap: 10px;
146+ text-decoration: none;
147+ color: inherit;
148+ padding: 6px 0;
149+
150+ &:hover { color: inherit; }
151+
152+ &-mark {
153+ flex: none;
154+ display: block;
155+ width: 24px;
156+ height: 24px;
157+ }
158+
159+ &-tittle { fill: var(--accent); }
160+
161+ &-text {
162+ font-family: var(--font-mono);
163+ font-size: 18px;
164+ font-weight: 500;
165+ letter-spacing: 0.02em;
166+ }
167+}
168+
169+.auth-card {
170+ background: var(--surface);
171+ border: 1px solid var(--border);
172+ border-radius: var(--radius-lg);
173+ padding: 28px;
174+ display: flex;
175+ flex-direction: column;
176+ gap: 18px;
177+ box-shadow: var(--shadow-2);
178+
179+ form {
180+ display: flex;
181+ flex-direction: column;
182+ gap: 20px;
183+ }
184+}
185+
186+.auth-head {
187+ display: flex;
188+ flex-direction: column;
189+ gap: 6px;
190+}
191+
192+.auth-title {
193+ font-size: 18px;
194+ font-weight: 600;
195+ letter-spacing: -0.01em;
196+}
197+
198+.auth-sub {
199+ font-size: 13px;
200+ color: var(--muted);
201+ line-height: 1.5;
202+}
203+
204+.auth-field {
205+ display: flex;
206+ flex-direction: column;
207+ gap: 6px;
208+}
209+
210+.auth-label {
211+ font-family: var(--font-mono);
212+ font-size: 10px;
213+ letter-spacing: 0.08em;
214+ color: var(--muted-soft);
215+}
216+
217+// The address an invited member signs in as: shown, never edited.
218+.auth-locked {
219+ display: flex;
220+ align-items: center;
221+ gap: 8px;
222+ height: 40px;
223+ padding: 0 12px;
224+ background: var(--panel-sunken);
225+ border: 1px solid var(--border-strong);
226+ border-radius: var(--radius);
227+}
228+
229+.auth-locked-value {
230+ font-family: var(--font-mono);
231+ font-size: 13px;
232+ color: var(--muted);
233+ flex-grow: 1;
234+}
235+
236+.auth-input {
237+ height: 40px;
238+ padding: 0 12px;
239+ background: var(--field-bg);
240+ border: 1px solid var(--border-strong);
241+ border-radius: var(--radius);
242+ color: var(--ink);
243+ font-family: var(--font-sans);
244+ font-size: 13px;
245+ width: 100%;
246+
247+ &:focus {
248+ outline: none;
249+ border-color: var(--accent);
250+ box-shadow: 0 0 0 2px var(--accent-tint);
251+ }
252+
253+ &:focus-visible {
254+ outline: 2px solid var(--accent);
255+ outline-offset: 1px;
256+ }
257+
258+ &:user-invalid {
259+ border-color: var(--danger);
260+ }
261+}
262+
263+.auth-input-mono {
264+ font-family: var(--font-mono);
265+}
266+
267+.auth-submit {
268+ height: var(--control-h-lg);
269+ display: flex;
270+ align-items: center;
271+ justify-content: center;
272+ gap: 8px;
273+ background: var(--accent);
274+ color: var(--surface);
275+ border: 0;
276+ border-radius: var(--radius);
277+ cursor: pointer;
278+ font-family: var(--font-sans);
279+
280+ &:disabled {
281+ opacity: 0.45;
282+ cursor: default;
283+ }
284+
285+ &:focus-visible {
286+ outline: 2px solid var(--accent-ink);
287+ outline-offset: 2px;
288+ }
289+}
290+
291+.auth-submit-text {
292+ font-size: 13px;
293+ font-weight: 600;
294+}
295+
296+.auth-problem {
297+ font-size: 13px;
298+ color: var(--danger);
299+ background: var(--danger-tint-alt);
300+ border: 1px solid var(--danger-border-soft);
301+ border-radius: var(--radius);
302+ padding: 10px 12px;
303+}
304+
305+.auth-note {
306+ font-size: 13px;
307+ color: var(--muted);
308+ background: var(--panel-sunken);
309+ border: 1px solid var(--border-soft);
310+ border-radius: var(--radius);
311+ padding: 10px 12px;
312+}
313+
314+// The one thing that says "this worked": a confirmed TOTP enrolment, an
315+// issued invite.
316+.auth-ok {
317+ font-size: 13px;
318+ color: var(--positive);
319+ background: var(--positive-tint);
320+ border: 1px solid var(--positive-border);
321+ border-radius: var(--radius);
322+ padding: 10px 12px;
323+}
324+
325+// The manual TOTP key: monospace, selectable, broken into four-letter groups.
326+.auth-secret {
327+ font-family: var(--font-mono);
328+ font-size: 14px;
329+ letter-spacing: 0.06em;
330+ text-align: center;
331+ background: var(--panel-sunken);
332+ border: 1px solid var(--border-soft);
333+ border-radius: var(--radius);
334+ padding: 10px 12px;
335+ user-select: all;
336+}
337+
338+// The enrolment QR, centered, with quiet ground so the modules stay scannable
339+// in either theme.
340+.auth-qr {
341+ display: flex;
342+ justify-content: center;
343+
344+ svg {
345+ width: 200px;
346+ height: 200px;
347+ background: #fff;
348+ border: 1px solid var(--border);
349+ border-radius: var(--radius);
350+ padding: 12px;
351+ }
352+}
353+
354+.auth-alt {
355+ font-size: 12px;
356+ color: var(--muted);
357+ text-decoration: none;
358+ align-self: center;
359+
360+ &:hover { color: var(--accent-ink); }
361+}
362+
363+.auth-footer {
364+ font-family: var(--font-mono);
365+ font-size: 10px;
366+ letter-spacing: 0.08em;
367+ color: var(--muted-soft);
368+ text-align: center;
369+ padding-top: 4px;
370+}
371+
372+@media (max-width: 720px) {
373+ .auth-stage { padding: 0 16px 24px; }
374+}