forge
Explore
Log in

Don't you dare go Hollow

🎉 init: workspace, im-core basics, store and initial schema

Browse files at this commit

a4cbd4be58bb9584e30799e2add742f9d372334aAhmet Kaan GümüşParent: 805e80d
.gitignoreadded+7 -0
@@ -0,0 +1,7 @@
1+target/
2+config/im.toml
3+data/
4+*.db
5+*.db-wal
6+*.db-shm
7+*.key
Cargo.lockadded+3527 -0

Diff too large; view file

@@ -0,0 +1,3527 @@
1+# This file is automatically @generated by Cargo.
2+# It is not intended for manual editing.
3+version = 4
4+
5+[[package]]
6+name = "aead"
7+version = "0.5.2"
8+source = "registry+https://github.com/rust-lang/crates.io-index"
9+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
10+dependencies = [
11+ "crypto-common 0.1.7",
12+ "generic-array",
13+]
14+
15+[[package]]
16+name = "aead"
17+version = "0.6.1"
18+source = "registry+https://github.com/rust-lang/crates.io-index"
19+checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"
20+dependencies = [
21+ "crypto-common 0.2.2",
22+ "inout 0.2.5",
23+]
24+
25+[[package]]
26+name = "aegis"
27+version = "0.9.20"
28+source = "registry+https://github.com/rust-lang/crates.io-index"
29+checksum = "41585f248ed9406567ae6d61ca2a55ed3dc7348e65203a01229881253acb95e3"
30+dependencies = [
31+ "cc",
32+ "softaes",
33+]
34+
35+[[package]]
36+name = "aes"
37+version = "0.8.4"
38+source = "registry+https://github.com/rust-lang/crates.io-index"
39+checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
40+dependencies = [
41+ "cfg-if",
42+ "cipher 0.4.4",
43+ "cpufeatures 0.2.17",
44+]
45+
46+[[package]]
47+name = "aes-gcm"
48+version = "0.10.3"
49+source = "registry+https://github.com/rust-lang/crates.io-index"
50+checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
51+dependencies = [
52+ "aead 0.5.2",
53+ "aes",
54+ "cipher 0.4.4",
55+ "ctr",
56+ "ghash",
57+ "subtle",
58+]
59+
60+[[package]]
61+name = "aho-corasick"
62+version = "1.1.5"
63+source = "registry+https://github.com/rust-lang/crates.io-index"
64+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
65+dependencies = [
66+ "memchr",
67+]
68+
69+[[package]]
70+name = "allocator-api2"
71+version = "0.2.21"
72+source = "registry+https://github.com/rust-lang/crates.io-index"
73+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
74+
75+[[package]]
76+name = "allocator-api2"
77+version = "0.4.0"
78+source = "registry+https://github.com/rust-lang/crates.io-index"
79+checksum = "c880a97d28a3681c0267bd29cff89621202715b065127cd445fa0f0fe0aa2880"
80+
81+[[package]]
82+name = "android_system_properties"
83+version = "0.1.6"
84+source = "registry+https://github.com/rust-lang/crates.io-index"
85+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
86+dependencies = [
87+ "libc",
88+]
89+
90+[[package]]
91+name = "antithesis_sdk"
92+version = "0.3.0"
93+source = "registry+https://github.com/rust-lang/crates.io-index"
94+checksum = "a8ed6751597568a284314fd9e2db420665898600109dedc7d8d9b588f00ae9c4"
95+dependencies = [
96+ "libc",
97+ "libloading",
98+ "linkme",
99+ "once_cell",
100+ "rand 0.8.8",
101+ "rustc_version_runtime",
102+ "serde",
103+ "serde_json",
104+]
105+
106+[[package]]
107+name = "anyhow"
108+version = "1.0.104"
109+source = "registry+https://github.com/rust-lang/crates.io-index"
110+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
111+
112+[[package]]
113+name = "arc-swap"
114+version = "1.9.3"
115+source = "registry+https://github.com/rust-lang/crates.io-index"
116+checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e"
117+dependencies = [
118+ "rustversion",
119+]
120+
121+[[package]]
122+name = "argon2"
123+version = "0.6.0"
124+source = "registry+https://github.com/rust-lang/crates.io-index"
125+checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c"
126+dependencies = [
127+ "base64ct",
128+ "blake2",
129+ "cpufeatures 0.3.1",
130+ "password-hash",
131+]
132+
133+[[package]]
134+name = "aristo"
135+version = "0.4.1"
136+source = "registry+https://github.com/rust-lang/crates.io-index"
137+checksum = "fcdeefa800110050103e2459a2f8dbdbd560ad046e30f1f87e24ce19c2cb8bde"
138+dependencies = [
139+ "aristo-macros",
140+]
141+
142+[[package]]
143+name = "aristo-macros"
144+version = "0.4.1"
145+source = "registry+https://github.com/rust-lang/crates.io-index"
146+checksum = "d64a66d21a80182b35b1741997a6d2456911f54b7eb1918aa4e2382fc205268d"
147+dependencies = [
148+ "proc-macro2",
149+ "quote",
150+ "syn 2.0.119",
151+]
152+
153+[[package]]
154+name = "assoc"
155+version = "0.1.3"
156+source = "registry+https://github.com/rust-lang/crates.io-index"
157+checksum = "bfdc70193dadb9d7287fa4b633f15f90c876915b31f6af17da307fc59c9859a8"
158+
159+[[package]]
160+name = "async-trait"
161+version = "0.1.92"
162+source = "registry+https://github.com/rust-lang/crates.io-index"
163+checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
164+dependencies = [
165+ "proc-macro2",
166+ "quote",
167+ "syn 3.0.9",
168+]
169+
170+[[package]]
171+name = "autocfg"
172+version = "1.5.1"
173+source = "registry+https://github.com/rust-lang/crates.io-index"
174+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
175+
176+[[package]]
177+name = "base64"
178+version = "0.22.1"
179+source = "registry+https://github.com/rust-lang/crates.io-index"
180+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
181+
182+[[package]]
183+name = "base64"
184+version = "0.23.1"
185+source = "registry+https://github.com/rust-lang/crates.io-index"
186+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
187+
188+[[package]]
189+name = "base64ct"
190+version = "1.8.3"
191+source = "registry+https://github.com/rust-lang/crates.io-index"
192+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
193+
194+[[package]]
195+name = "bigdecimal"
196+version = "0.4.11"
197+source = "registry+https://github.com/rust-lang/crates.io-index"
198+checksum = "8fa3f3d8cbf4dffcfe4991de61d012bef509a409ecbe9dd41049bfe32b4d4653"
199+dependencies = [
200+ "autocfg",
201+ "libm",
202+ "num-bigint",
203+ "num-integer",
204+ "num-traits",
205+]
206+
207+[[package]]
208+name = "bindgen"
209+version = "0.69.5"
210+source = "registry+https://github.com/rust-lang/crates.io-index"
211+checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088"
212+dependencies = [
213+ "bitflags",
214+ "cexpr",
215+ "clang-sys",
216+ "itertools 0.12.1",
217+ "lazy_static",
218+ "lazycell",
219+ "log",
220+ "prettyplease 0.2.37",
221+ "proc-macro2",
222+ "quote",
223+ "regex",
224+ "rustc-hash 1.1.0",
225+ "shlex 1.3.0",
226+ "syn 2.0.119",
227+ "which",
228+]
229+
230+[[package]]
231+name = "bitflags"
232+version = "2.13.2"
233+source = "registry+https://github.com/rust-lang/crates.io-index"
234+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
235+
236+[[package]]
237+name = "bitpacking"
238+version = "0.9.3"
239+source = "registry+https://github.com/rust-lang/crates.io-index"
240+checksum = "96a7139abd3d9cebf8cd6f920a389cf3dc9576172e32f4563f188cae3c3eb019"
241+dependencies = [
242+ "crunchy",
243+]
244+
245+[[package]]
246+name = "bitvec"
247+version = "1.1.1"
248+source = "registry+https://github.com/rust-lang/crates.io-index"
249+checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837"
250+dependencies = [
251+ "funty",
252+ "radium",
253+ "tap",
254+ "wyz",
255+]
256+
257+[[package]]
258+name = "blake2"
259+version = "0.11.0"
260+source = "registry+https://github.com/rust-lang/crates.io-index"
261+checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f"
262+dependencies = [
263+ "digest",
264+]
265+
266+[[package]]
267+name = "block-buffer"
268+version = "0.12.1"
269+source = "registry+https://github.com/rust-lang/crates.io-index"
270+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
271+dependencies = [
272+ "hybrid-array",
273+]
274+
275+[[package]]
276+name = "bon"
277+version = "3.10.3"
278+source = "registry+https://github.com/rust-lang/crates.io-index"
279+checksum = "a05442cd7005532d0cfedec676b5b9333d2b4c7c3afabe2b1a9ce2742fbe2ee6"
280+dependencies = [
281+ "bon-macros",
282+]
283+
284+[[package]]
285+name = "bon-macros"
286+version = "3.10.3"
287+source = "registry+https://github.com/rust-lang/crates.io-index"
288+checksum = "93833e97ac7c46ba97045afcf247238c27057538fcf2f06344662ddd5f567be6"
289+dependencies = [
290+ "darling",
291+ "ident_case",
292+ "prettyplease 0.3.0",
293+ "proc-macro2",
294+ "quote",
295+ "syn 3.0.9",
296+]
297+
298+[[package]]
299+name = "branches"
300+version = "0.4.6"
301+source = "registry+https://github.com/rust-lang/crates.io-index"
302+checksum = "7436b21fd6195415058eb41c9090e156b556bc7e0377bb57c5c026a421521525"
303+dependencies = [
304+ "rustc_version",
305+]
306+
307+[[package]]
308+name = "bumpalo"
309+version = "3.20.3"
310+source = "registry+https://github.com/rust-lang/crates.io-index"
311+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
312+
313+[[package]]
314+name = "bytemuck"
315+version = "1.25.2"
316+source = "registry+https://github.com/rust-lang/crates.io-index"
317+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
318+dependencies = [
319+ "bytemuck_derive",
320+]
321+
322+[[package]]
323+name = "bytemuck_derive"
324+version = "1.12.1"
325+source = "registry+https://github.com/rust-lang/crates.io-index"
326+checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
327+dependencies = [
328+ "proc-macro2",
329+ "quote",
330+ "syn 3.0.9",
331+]
332+
333+[[package]]
334+name = "byteorder"
335+version = "1.5.0"
336+source = "registry+https://github.com/rust-lang/crates.io-index"
337+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
338+
339+[[package]]
340+name = "bytes"
341+version = "1.12.1"
342+source = "registry+https://github.com/rust-lang/crates.io-index"
343+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
344+
345+[[package]]
346+name = "cc"
347+version = "1.10.0"
348+source = "registry+https://github.com/rust-lang/crates.io-index"
349+checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0"
350+dependencies = [
351+ "find-msvc-tools",
352+ "jobserver",
353+ "libc",
354+ "shlex 2.0.1",
355+]
356+
357+[[package]]
358+name = "census"
359+version = "0.4.2"
360+source = "registry+https://github.com/rust-lang/crates.io-index"
361+checksum = "4f4c707c6a209cbe82d10abd08e1ea8995e9ea937d2550646e02798948992be0"
362+
363+[[package]]
364+name = "cexpr"
365+version = "0.6.0"
366+source = "registry+https://github.com/rust-lang/crates.io-index"
367+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
368+dependencies = [
369+ "nom",
370+]
371+
372+[[package]]
373+name = "cfg-if"
374+version = "1.0.5"
375+source = "registry+https://github.com/rust-lang/crates.io-index"
376+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
377+
378+[[package]]
379+name = "cfg_aliases"
380+version = "0.2.2"
381+source = "registry+https://github.com/rust-lang/crates.io-index"
382+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
383+
384+[[package]]
385+name = "cfg_block"
386+version = "0.1.1"
387+source = "registry+https://github.com/rust-lang/crates.io-index"
388+checksum = "18758054972164c3264f7c8386f5fc6da6114cb46b619fd365d4e3b2dc3ae487"
389+
390+[[package]]
391+name = "chacha20"
392+version = "0.10.2"
393+source = "registry+https://github.com/rust-lang/crates.io-index"
394+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
395+dependencies = [
396+ "cfg-if",
397+ "cipher 0.5.2",
398+ "cpufeatures 0.3.1",
399+ "rand_core 0.10.1",
400+]
401+
402+[[package]]
403+name = "chacha20poly1305"
404+version = "0.11.0"
405+source = "registry+https://github.com/rust-lang/crates.io-index"
406+checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
407+dependencies = [
408+ "aead 0.6.1",
409+ "chacha20",
410+ "cipher 0.5.2",
411+ "poly1305",
412+]
413+
414+[[package]]
415+name = "chrono"
416+version = "0.4.45"
417+source = "registry+https://github.com/rust-lang/crates.io-index"
418+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
419+dependencies = [
420+ "iana-time-zone",
421+ "js-sys",
422+ "num-traits",
423+ "wasm-bindgen",
424+ "windows-link",
425+]
426+
427+[[package]]
428+name = "cipher"
429+version = "0.4.4"
430+source = "registry+https://github.com/rust-lang/crates.io-index"
431+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
432+dependencies = [
433+ "crypto-common 0.1.7",
434+ "inout 0.1.4",
435+]
436+
437+[[package]]
438+name = "cipher"
439+version = "0.5.2"
440+source = "registry+https://github.com/rust-lang/crates.io-index"
441+checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
442+dependencies = [
443+ "block-buffer",
444+ "crypto-common 0.2.2",
445+ "inout 0.2.5",
446+]
447+
448+[[package]]
449+name = "clang-sys"
450+version = "1.9.1"
451+source = "registry+https://github.com/rust-lang/crates.io-index"
452+checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
453+dependencies = [
454+ "glob",
455+ "libc",
456+ "libloading",
457+]
458+
459+[[package]]
460+name = "cmov"
461+version = "0.5.4"
462+source = "registry+https://github.com/rust-lang/crates.io-index"
463+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
464+
465+[[package]]
466+name = "concurrent-queue"
467+version = "2.5.0"
468+source = "registry+https://github.com/rust-lang/crates.io-index"
469+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
470+dependencies = [
471+ "crossbeam-utils",
472+]
473+
474+[[package]]
475+name = "const-oid"
476+version = "0.10.2"
477+source = "registry+https://github.com/rust-lang/crates.io-index"
478+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
479+
480+[[package]]
481+name = "core-foundation-sys"
482+version = "0.8.7"
483+source = "registry+https://github.com/rust-lang/crates.io-index"
484+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
485+
486+[[package]]
487+name = "cpufeatures"
488+version = "0.2.17"
489+source = "registry+https://github.com/rust-lang/crates.io-index"
490+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
491+dependencies = [
492+ "libc",
493+]
494+
495+[[package]]
496+name = "cpufeatures"
497+version = "0.3.1"
498+source = "registry+https://github.com/rust-lang/crates.io-index"
499+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
500+dependencies = [
501+ "libc",
502+]
503+
504+[[package]]
505+name = "crc32c"
506+version = "0.6.8"
507+source = "registry+https://github.com/rust-lang/crates.io-index"
508+checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47"
509+dependencies = [
510+ "rustc_version",
511+]
512+
513+[[package]]
514+name = "crc32fast"
515+version = "1.5.3"
516+source = "registry+https://github.com/rust-lang/crates.io-index"
517+checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055"
518+dependencies = [
519+ "cfg-if",
520+]
521+
522+[[package]]
523+name = "crossbeam-channel"
524+version = "0.5.17"
525+source = "registry+https://github.com/rust-lang/crates.io-index"
526+checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1"
527+dependencies = [
528+ "crossbeam-utils",
529+]
530+
531+[[package]]
532+name = "crossbeam-deque"
533+version = "0.8.8"
534+source = "registry+https://github.com/rust-lang/crates.io-index"
535+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
536+dependencies = [
537+ "crossbeam-epoch",
538+ "crossbeam-utils",
539+]
540+
541+[[package]]
542+name = "crossbeam-epoch"
543+version = "0.9.21"
544+source = "registry+https://github.com/rust-lang/crates.io-index"
545+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
546+dependencies = [
547+ "crossbeam-utils",
548+]
549+
550+[[package]]
551+name = "crossbeam-utils"
552+version = "0.8.23"
553+source = "registry+https://github.com/rust-lang/crates.io-index"
554+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
555+
556+[[package]]
557+name = "crunchy"
558+version = "0.2.4"
559+source = "registry+https://github.com/rust-lang/crates.io-index"
560+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
561+
562+[[package]]
563+name = "crypto-common"
564+version = "0.1.7"
565+source = "registry+https://github.com/rust-lang/crates.io-index"
566+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
567+dependencies = [
568+ "generic-array",
569+ "rand_core 0.6.4",
570+ "typenum",
571+]
572+
573+[[package]]
574+name = "crypto-common"
575+version = "0.2.2"
576+source = "registry+https://github.com/rust-lang/crates.io-index"
577+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
578+dependencies = [
579+ "getrandom 0.4.3",
580+ "hybrid-array",
581+ "rand_core 0.10.1",
582+]
583+
584+[[package]]
585+name = "ctr"
586+version = "0.9.2"
587+source = "registry+https://github.com/rust-lang/crates.io-index"
588+checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
589+dependencies = [
590+ "cipher 0.4.4",
591+]
592+
593+[[package]]
594+name = "ctutils"
595+version = "0.4.6"
596+source = "registry+https://github.com/rust-lang/crates.io-index"
597+checksum = "fe3e9d21d39e6f39ff46e03d5b621424f88ee23d8a1672c6bfc9ccc7f2da4f6a"
598+dependencies = [
599+ "cmov",
600+]
601+
602+[[package]]
603+name = "curve25519-dalek"
604+version = "5.0.0"
605+source = "registry+https://github.com/rust-lang/crates.io-index"
606+checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"
607+dependencies = [
608+ "cfg-if",
609+ "cpufeatures 0.3.1",
610+ "curve25519-dalek-derive",
611+ "digest",
612+ "fiat-crypto",
613+ "rand_core 0.10.1",
614+ "rustc_version",
615+ "subtle",
616+ "zeroize",
617+]
618+
619+[[package]]
620+name = "curve25519-dalek-derive"
621+version = "0.1.1"
622+source = "registry+https://github.com/rust-lang/crates.io-index"
623+checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
624+dependencies = [
625+ "proc-macro2",
626+ "quote",
627+ "syn 2.0.119",
628+]
629+
630+[[package]]
631+name = "darling"
632+version = "0.24.1"
633+source = "registry+https://github.com/rust-lang/crates.io-index"
634+checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
635+dependencies = [
636+ "darling_core",
637+ "darling_macro",
638+]
639+
640+[[package]]
641+name = "darling_core"
642+version = "0.24.1"
643+source = "registry+https://github.com/rust-lang/crates.io-index"
644+checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
645+dependencies = [
646+ "ident_case",
647+ "proc-macro2",
648+ "quote",
649+ "strsim",
650+ "syn 3.0.9",
651+]
652+
653+[[package]]
654+name = "darling_macro"
655+version = "0.24.1"
656+source = "registry+https://github.com/rust-lang/crates.io-index"
657+checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
658+dependencies = [
659+ "darling_core",
660+ "quote",
661+ "syn 3.0.9",
662+]
663+
664+[[package]]
665+name = "datasketches"
666+version = "0.2.0"
667+source = "registry+https://github.com/rust-lang/crates.io-index"
668+checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745"
669+
670+[[package]]
671+name = "deranged"
672+version = "0.5.9"
673+source = "registry+https://github.com/rust-lang/crates.io-index"
674+checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
675+dependencies = [
676+ "serde_core",
677+]
678+
679+[[package]]
680+name = "digest"
681+version = "0.11.3"
682+source = "registry+https://github.com/rust-lang/crates.io-index"
683+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
684+dependencies = [
685+ "block-buffer",
686+ "const-oid",
687+ "crypto-common 0.2.2",
688+ "ctutils",
689+]
690+
691+[[package]]
692+name = "displaydoc"
693+version = "0.2.7"
694+source = "registry+https://github.com/rust-lang/crates.io-index"
695+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
696+dependencies = [
697+ "proc-macro2",
698+ "quote",
699+ "syn 3.0.9",
700+]
701+
702+[[package]]
703+name = "downcast-rs"
704+version = "2.0.2"
705+source = "registry+https://github.com/rust-lang/crates.io-index"
706+checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc"
707+
708+[[package]]
709+name = "ed25519"
710+version = "3.0.0"
711+source = "registry+https://github.com/rust-lang/crates.io-index"
712+checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"
713+dependencies = [
714+ "signature",
715+]
716+
717+[[package]]
718+name = "ed25519-dalek"
719+version = "3.0.0"
720+source = "registry+https://github.com/rust-lang/crates.io-index"
721+checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
722+dependencies = [
723+ "curve25519-dalek",
724+ "ed25519",
725+ "rand_core 0.10.1",
726+ "sha2",
727+ "signature",
728+ "subtle",
729+ "zeroize",
730+]
731+
732+[[package]]
733+name = "either"
734+version = "1.19.0"
735+source = "registry+https://github.com/rust-lang/crates.io-index"
736+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
737+
738+[[package]]
739+name = "env_filter"
740+version = "2.0.0"
741+source = "registry+https://github.com/rust-lang/crates.io-index"
742+checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217"
743+dependencies = [
744+ "log",
745+ "regex",
746+]
747+
748+[[package]]
749+name = "env_logger"
750+version = "0.11.11"
751+source = "registry+https://github.com/rust-lang/crates.io-index"
752+checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6"
753+dependencies = [
754+ "env_filter",
755+ "log",
756+]
757+
758+[[package]]
759+name = "equivalent"
760+version = "1.0.3"
761+source = "registry+https://github.com/rust-lang/crates.io-index"
762+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
763+
764+[[package]]
765+name = "erased-serde"
766+version = "0.4.11"
767+source = "registry+https://github.com/rust-lang/crates.io-index"
768+checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66"
769+dependencies = [
770+ "serde",
771+ "serde_core",
772+ "typeid",
773+]
774+
775+[[package]]
776+name = "errno"
777+version = "0.3.14"
778+source = "registry+https://github.com/rust-lang/crates.io-index"
779+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
780+dependencies = [
781+ "libc",
782+ "windows-sys 0.61.2",
783+]
784+
785+[[package]]
786+name = "fallible-iterator"
787+version = "0.3.0"
788+source = "registry+https://github.com/rust-lang/crates.io-index"
789+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
790+
791+[[package]]
792+name = "fastbloom"
793+version = "0.14.1"
794+source = "registry+https://github.com/rust-lang/crates.io-index"
795+checksum = "4e7f34442dbe69c60fe8eaf58a8cafff81a1f278816d8ab4db255b3bef4ac3c4"
796+dependencies = [
797+ "getrandom 0.3.4",
798+ "libm",
799+ "siphasher",
800+]
801+
802+[[package]]
803+name = "fastdivide"
804+version = "0.4.2"
805+source = "registry+https://github.com/rust-lang/crates.io-index"
806+checksum = "9afc2bd4d5a73106dd53d10d73d3401c2f32730ba2c0b93ddb888a8983680471"
807+
808+[[package]]
809+name = "fastrand"
810+version = "2.5.0"
811+source = "registry+https://github.com/rust-lang/crates.io-index"
812+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
813+
814+[[package]]
815+name = "fiat-crypto"
816+version = "0.3.0"
817+source = "registry+https://github.com/rust-lang/crates.io-index"
818+checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"
819+
820+[[package]]
821+name = "find-msvc-tools"
822+version = "0.1.15"
823+source = "registry+https://github.com/rust-lang/crates.io-index"
824+checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
825+
826+[[package]]
827+name = "fnv"
828+version = "1.0.7"
829+source = "registry+https://github.com/rust-lang/crates.io-index"
830+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
831+
832+[[package]]
833+name = "foldhash"
834+version = "0.2.0"
835+source = "registry+https://github.com/rust-lang/crates.io-index"
836+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
837+
838+[[package]]
839+name = "fs4"
840+version = "0.13.1"
841+source = "registry+https://github.com/rust-lang/crates.io-index"
842+checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4"
843+dependencies = [
844+ "rustix 1.1.6",
845+ "windows-sys 0.59.0",
846+]
847+
848+[[package]]
849+name = "funty"
850+version = "2.0.0"
851+source = "registry+https://github.com/rust-lang/crates.io-index"
852+checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
853+
854+[[package]]
855+name = "futures-core"
856+version = "0.3.34"
857+source = "registry+https://github.com/rust-lang/crates.io-index"
858+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
859+
860+[[package]]
861+name = "futures-macro"
862+version = "0.3.34"
863+source = "registry+https://github.com/rust-lang/crates.io-index"
864+checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
865+dependencies = [
866+ "proc-macro2",
867+ "quote",
868+ "syn 3.0.9",
869+]
870+
871+[[package]]
872+name = "futures-task"
873+version = "0.3.34"
874+source = "registry+https://github.com/rust-lang/crates.io-index"
875+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
876+
877+[[package]]
878+name = "futures-util"
879+version = "0.3.34"
880+source = "registry+https://github.com/rust-lang/crates.io-index"
881+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
882+dependencies = [
883+ "futures-core",
884+ "futures-macro",
885+ "futures-task",
886+ "pin-project-lite",
887+ "slab",
888+]
889+
890+[[package]]
891+name = "genawaiter"
892+version = "0.99.1"
893+source = "registry+https://github.com/rust-lang/crates.io-index"
894+checksum = "c86bd0361bcbde39b13475e6e36cb24c329964aa2611be285289d1e4b751c1a0"
895+dependencies = [
896+ "genawaiter-macro",
897+]
898+
899+[[package]]
900+name = "genawaiter-macro"
901+version = "0.99.1"
902+source = "registry+https://github.com/rust-lang/crates.io-index"
903+checksum = "0b32dfe1fdfc0bbde1f22a5da25355514b5e450c33a6af6770884c8750aedfbc"
904+
905+[[package]]
906+name = "generator"
907+version = "0.8.11"
908+source = "registry+https://github.com/rust-lang/crates.io-index"
909+checksum = "1be81b31c9ce4caf7f3178eeb90662bb1864d3ad363ec6bdada3201adff19c37"
910+dependencies = [
911+ "cc",
912+ "cfg-if",
913+ "libc",
914+ "log",
915+ "rustversion",
916+ "windows-link",
917+ "windows-result",
918+]
919+
920+[[package]]
921+name = "generic-array"
922+version = "0.14.7"
923+source = "registry+https://github.com/rust-lang/crates.io-index"
924+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
925+dependencies = [
926+ "typenum",
927+ "version_check",
928+]
929+
930+[[package]]
931+name = "getrandom"
932+version = "0.2.17"
933+source = "registry+https://github.com/rust-lang/crates.io-index"
934+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
935+dependencies = [
936+ "cfg-if",
937+ "js-sys",
938+ "libc",
939+ "wasi",
940+ "wasm-bindgen",
941+]
942+
943+[[package]]
944+name = "getrandom"
945+version = "0.3.4"
946+source = "registry+https://github.com/rust-lang/crates.io-index"
947+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
948+dependencies = [
949+ "cfg-if",
950+ "js-sys",
951+ "libc",
952+ "r-efi 5.3.0",
953+ "wasip2",
954+ "wasm-bindgen",
955+]
956+
957+[[package]]
958+name = "getrandom"
959+version = "0.4.3"
960+source = "registry+https://github.com/rust-lang/crates.io-index"
961+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
962+dependencies = [
963+ "cfg-if",
964+ "js-sys",
965+ "libc",
966+ "r-efi 6.0.0",
967+ "rand_core 0.10.1",
968+ "wasm-bindgen",
969+]
970+
971+[[package]]
972+name = "ghash"
973+version = "0.5.1"
974+source = "registry+https://github.com/rust-lang/crates.io-index"
975+checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
976+dependencies = [
977+ "opaque-debug",
978+ "polyval",
979+]
980+
981+[[package]]
982+name = "glob"
983+version = "0.3.4"
984+source = "registry+https://github.com/rust-lang/crates.io-index"
985+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
986+
987+[[package]]
988+name = "hashbrown"
989+version = "0.16.1"
990+source = "registry+https://github.com/rust-lang/crates.io-index"
991+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
992+dependencies = [
993+ "allocator-api2 0.2.21",
994+ "equivalent",
995+ "foldhash",
996+]
997+
998+[[package]]
999+name = "hashbrown"
1000+version = "0.17.1"
1001+source = "registry+https://github.com/rust-lang/crates.io-index"
1002+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
1003+
1004+[[package]]
1005+name = "heck"
1006+version = "0.5.0"
1007+source = "registry+https://github.com/rust-lang/crates.io-index"
1008+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
1009+
1010+[[package]]
1011+name = "hermit-abi"
1012+version = "0.5.3"
1013+source = "registry+https://github.com/rust-lang/crates.io-index"
1014+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
1015+
1016+[[package]]
1017+name = "hex"
1018+version = "0.4.3"
1019+source = "registry+https://github.com/rust-lang/crates.io-index"
1020+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
1021+
1022+[[package]]
1023+name = "home"
1024+version = "0.5.12"
1025+source = "registry+https://github.com/rust-lang/crates.io-index"
1026+checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
1027+dependencies = [
1028+ "windows-sys 0.61.2",
1029+]
1030+
1031+[[package]]
1032+name = "htmlescape"
1033+version = "0.3.1"
1034+source = "registry+https://github.com/rust-lang/crates.io-index"
1035+checksum = "e9025058dae765dee5070ec375f591e2ba14638c63feff74f13805a72e523163"
1036+
1037+[[package]]
1038+name = "http"
1039+version = "1.5.0"
1040+source = "registry+https://github.com/rust-lang/crates.io-index"
1041+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
1042+dependencies = [
1043+ "bytes",
1044+ "itoa",
1045+]
1046+
1047+[[package]]
1048+name = "hybrid-array"
1049+version = "0.4.15"
1050+source = "registry+https://github.com/rust-lang/crates.io-index"
1051+checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
1052+dependencies = [
1053+ "typenum",
1054+]
1055+
1056+[[package]]
1057+name = "iana-time-zone"
1058+version = "0.1.65"
1059+source = "registry+https://github.com/rust-lang/crates.io-index"
1060+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
1061+dependencies = [
1062+ "android_system_properties",
1063+ "core-foundation-sys",
1064+ "iana-time-zone-haiku",
1065+ "js-sys",
1066+ "log",
1067+ "wasm-bindgen",
1068+ "windows-core",
1069+]
1070+
1071+[[package]]
1072+name = "iana-time-zone-haiku"
1073+version = "0.1.2"
1074+source = "registry+https://github.com/rust-lang/crates.io-index"
1075+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
1076+dependencies = [
1077+ "cc",
1078+]
1079+
1080+[[package]]
1081+name = "icu_collator"
1082+version = "2.4.0"
1083+source = "registry+https://github.com/rust-lang/crates.io-index"
1084+checksum = "24cb0205c419b2036da3f9082964905d6849b3f2130dd4a517940c45899a544b"
1085+dependencies = [
1086+ "icu_collator_data",
1087+ "icu_collections",
1088+ "icu_locale_core",
1089+ "icu_locale_fallback",
1090+ "icu_normalizer",
1091+ "icu_properties",
1092+ "icu_provider",
1093+ "smallvec",
1094+ "utf16_iter",
1095+ "utf8_iter",
1096+ "zerovec",
1097+]
1098+
1099+[[package]]
1100+name = "icu_collator_data"
1101+version = "2.4.0"
1102+source = "registry+https://github.com/rust-lang/crates.io-index"
1103+checksum = "183f47e821a327661c1ebe152f61d5b6c2000010d228cadbbf226e0e2b8c2634"
1104+
1105+[[package]]
1106+name = "icu_collections"
1107+version = "2.4.0"
1108+source = "registry+https://github.com/rust-lang/crates.io-index"
1109+checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd"
1110+dependencies = [
1111+ "displaydoc",
1112+ "potential_utf",
1113+ "utf8_iter",
1114+ "yoke",
1115+ "zerofrom",
1116+ "zerovec",
1117+]
1118+
1119+[[package]]
1120+name = "icu_locale"
1121+version = "2.4.0"
1122+source = "registry+https://github.com/rust-lang/crates.io-index"
1123+checksum = "fe8fa57bcddc15cb921582ee5259c5b77da39f946f188ca5213fad24d9241236"
1124+dependencies = [
1125+ "icu_collections",
1126+ "icu_locale_core",
1127+ "icu_locale_data",
1128+ "icu_locale_fallback",
1129+ "icu_provider",
1130+ "tinystr",
1131+ "zerovec",
1132+]
1133+
1134+[[package]]
1135+name = "icu_locale_core"
1136+version = "2.4.0"
1137+source = "registry+https://github.com/rust-lang/crates.io-index"
1138+checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0"
1139+dependencies = [
1140+ "displaydoc",
1141+ "litemap",
1142+ "serde",
1143+ "tinystr",
1144+ "writeable",
1145+ "zerovec",
1146+]
1147+
1148+[[package]]
1149+name = "icu_locale_data"
1150+version = "2.4.0"
1151+source = "registry+https://github.com/rust-lang/crates.io-index"
1152+checksum = "a64014dac577a11d8d2cee48517c73c1984bd72ab11031e934269bd3cefb2ad9"
1153+
1154+[[package]]
1155+name = "icu_locale_fallback"
1156+version = "2.4.0"
1157+source = "registry+https://github.com/rust-lang/crates.io-index"
1158+checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c"
1159+dependencies = [
1160+ "icu_locale_core",
1161+ "icu_locale_fallback_data",
1162+ "icu_provider",
1163+ "potential_utf",
1164+ "tinystr",
1165+ "zerovec",
1166+]
1167+
1168+[[package]]
1169+name = "icu_locale_fallback_data"
1170+version = "2.4.0"
1171+source = "registry+https://github.com/rust-lang/crates.io-index"
1172+checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c"
1173+
1174+[[package]]
1175+name = "icu_normalizer"
1176+version = "2.4.0"
1177+source = "registry+https://github.com/rust-lang/crates.io-index"
1178+checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599"
1179+dependencies = [
1180+ "icu_collections",
1181+ "icu_normalizer_data",
1182+ "icu_properties",
1183+ "icu_provider",
1184+ "smallvec",
1185+ "utf16_iter",
1186+ "utf8_iter",
1187+ "write16",
1188+ "zerovec",
1189+]
1190+
1191+[[package]]
1192+name = "icu_normalizer_data"
1193+version = "2.4.0"
1194+source = "registry+https://github.com/rust-lang/crates.io-index"
1195+checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc"
1196+
1197+[[package]]
1198+name = "icu_properties"
1199+version = "2.4.0"
1200+source = "registry+https://github.com/rust-lang/crates.io-index"
1201+checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f"
1202+dependencies = [
1203+ "displaydoc",
1204+ "icu_collections",
1205+ "icu_locale_core",
1206+ "icu_properties_data",
1207+ "icu_provider",
1208+ "zerotrie",
1209+ "zerovec",
1210+]
1211+
1212+[[package]]
1213+name = "icu_properties_data"
1214+version = "2.4.0"
1215+source = "registry+https://github.com/rust-lang/crates.io-index"
1216+checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf"
1217+
1218+[[package]]
1219+name = "icu_provider"
1220+version = "2.4.0"
1221+source = "registry+https://github.com/rust-lang/crates.io-index"
1222+checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514"
1223+dependencies = [
1224+ "displaydoc",
1225+ "icu_locale_core",
1226+ "serde",
1227+ "stable_deref_trait",
1228+ "writeable",
1229+ "yoke",
1230+ "zerofrom",
1231+ "zerotrie",
1232+ "zerovec",
1233+]
1234+
1235+[[package]]
1236+name = "ident_case"
1237+version = "1.0.1"
1238+source = "registry+https://github.com/rust-lang/crates.io-index"
1239+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
1240+
1241+[[package]]
1242+name = "im-core"
1243+version = "0.1.0"
1244+dependencies = [
1245+ "argon2",
1246+ "base64 0.23.1",
1247+ "chacha20poly1305",
1248+ "ed25519-dalek",
1249+ "hex",
1250+ "ipnet",
1251+ "rand 0.10.3",
1252+ "serde",
1253+ "serde_json",
1254+ "sha2",
1255+ "subtle",
1256+ "tempfile",
1257+ "thiserror",
1258+ "time",
1259+ "tokio",
1260+ "toml",
1261+ "tracing",
1262+ "turso",
1263+ "ulid",
1264+]
1265+
1266+[[package]]
1267+name = "im-web"
1268+version = "0.1.0"
1269+
1270+[[package]]
1271+name = "indexmap"
1272+version = "2.14.2"
1273+source = "registry+https://github.com/rust-lang/crates.io-index"
1274+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
1275+dependencies = [
1276+ "equivalent",
1277+ "hashbrown 0.17.1",
1278+]
1279+
1280+[[package]]
1281+name = "inout"
1282+version = "0.1.4"
1283+source = "registry+https://github.com/rust-lang/crates.io-index"
1284+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
1285+dependencies = [
1286+ "generic-array",
1287+]
1288+
1289+[[package]]
1290+name = "inout"
1291+version = "0.2.5"
1292+source = "registry+https://github.com/rust-lang/crates.io-index"
1293+checksum = "3b5cf4372d022092674a83b8febf5865f7a573cc0c5baec5e49c879b6a20978f"
1294+dependencies = [
1295+ "hybrid-array",
1296+]
1297+
1298+[[package]]
1299+name = "intrusive-collections"
1300+version = "0.9.7"
1301+source = "registry+https://github.com/rust-lang/crates.io-index"
1302+checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86"
1303+dependencies = [
1304+ "memoffset",
1305+]
1306+
1307+[[package]]
1308+name = "inventory"
1309+version = "0.3.25"
1310+source = "registry+https://github.com/rust-lang/crates.io-index"
1311+checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c"
1312+dependencies = [
1313+ "rustversion",
1314+]
1315+
1316+[[package]]
1317+name = "io-uring"
1318+version = "0.7.15"
1319+source = "registry+https://github.com/rust-lang/crates.io-index"
1320+checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb"
1321+dependencies = [
1322+ "bitflags",
1323+ "cfg-if",
1324+ "libc",
1325+]
1326+
1327+[[package]]
1328+name = "ipnet"
1329+version = "2.12.2"
1330+source = "registry+https://github.com/rust-lang/crates.io-index"
1331+checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
1332+
1333+[[package]]
1334+name = "itertools"
1335+version = "0.12.1"
1336+source = "registry+https://github.com/rust-lang/crates.io-index"
1337+checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"
1338+dependencies = [
1339+ "either",
1340+]
1341+
1342+[[package]]
1343+name = "itertools"
1344+version = "0.14.0"
1345+source = "registry+https://github.com/rust-lang/crates.io-index"
1346+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
1347+dependencies = [
1348+ "either",
1349+]
1350+
1351+[[package]]
1352+name = "itoa"
1353+version = "1.0.18"
1354+source = "registry+https://github.com/rust-lang/crates.io-index"
1355+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
1356+
1357+[[package]]
1358+name = "jobserver"
1359+version = "0.1.35"
1360+source = "registry+https://github.com/rust-lang/crates.io-index"
1361+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
1362+dependencies = [
1363+ "getrandom 0.4.3",
1364+ "libc",
1365+]
1366+
1367+[[package]]
1368+name = "js-sys"
1369+version = "0.3.106"
1370+source = "registry+https://github.com/rust-lang/crates.io-index"
1371+checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
1372+dependencies = [
1373+ "cfg-if",
1374+ "futures-util",
1375+ "wasm-bindgen",
1376+]
1377+
1378+[[package]]
1379+name = "lazy_static"
1380+version = "1.5.1"
1381+source = "registry+https://github.com/rust-lang/crates.io-index"
1382+checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
1383+
1384+[[package]]
1385+name = "lazycell"
1386+version = "1.3.0"
1387+source = "registry+https://github.com/rust-lang/crates.io-index"
1388+checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55"
1389+
1390+[[package]]
1391+name = "levenshtein_automata"
1392+version = "0.2.1"
1393+source = "registry+https://github.com/rust-lang/crates.io-index"
1394+checksum = "0c2cdeb66e45e9f36bfad5bbdb4d2384e70936afbee843c6f6543f0c551ebb25"
1395+
1396+[[package]]
1397+name = "libc"
1398+version = "0.2.191"
1399+source = "registry+https://github.com/rust-lang/crates.io-index"
1400+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
1401+
1402+[[package]]
1403+name = "libloading"
1404+version = "0.8.9"
1405+source = "registry+https://github.com/rust-lang/crates.io-index"
1406+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
1407+dependencies = [
1408+ "cfg-if",
1409+ "windows-link",
1410+]
1411+
1412+[[package]]
1413+name = "libm"
1414+version = "0.2.16"
1415+source = "registry+https://github.com/rust-lang/crates.io-index"
1416+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
1417+
1418+[[package]]
1419+name = "libmimalloc-sys"
1420+version = "0.1.49"
1421+source = "registry+https://github.com/rust-lang/crates.io-index"
1422+checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9"
1423+dependencies = [
1424+ "cc",
1425+]
1426+
1427+[[package]]
1428+name = "linkme"
1429+version = "0.3.37"
1430+source = "registry+https://github.com/rust-lang/crates.io-index"
1431+checksum = "3045e122bd98aef8ec3ad58ce84f0791f64e70163d1a02710af4aa11a4d54cc5"
1432+dependencies = [
1433+ "linkme-impl",
1434+]
1435+
1436+[[package]]
1437+name = "linkme-impl"
1438+version = "0.3.37"
1439+source = "registry+https://github.com/rust-lang/crates.io-index"
1440+checksum = "77060ebe535362c3da75682cd17b0431017b6e7c5661e714fc69a7ad017d1301"
1441+dependencies = [
1442+ "proc-macro2",
1443+ "quote",
1444+ "syn 3.0.9",
1445+]
1446+
1447+[[package]]
1448+name = "linux-raw-sys"
1449+version = "0.4.15"
1450+source = "registry+https://github.com/rust-lang/crates.io-index"
1451+checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
1452+
1453+[[package]]
1454+name = "linux-raw-sys"
1455+version = "0.12.1"
1456+source = "registry+https://github.com/rust-lang/crates.io-index"
1457+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
1458+
1459+[[package]]
1460+name = "litemap"
1461+version = "0.8.3"
1462+source = "registry+https://github.com/rust-lang/crates.io-index"
1463+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
1464+
1465+[[package]]
1466+name = "lock_api"
1467+version = "0.4.14"
1468+source = "registry+https://github.com/rust-lang/crates.io-index"
1469+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
1470+dependencies = [
1471+ "scopeguard",
1472+]
1473+
1474+[[package]]
1475+name = "log"
1476+version = "0.4.34"
1477+source = "registry+https://github.com/rust-lang/crates.io-index"
1478+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
1479+
1480+[[package]]
1481+name = "loom"
1482+version = "0.7.2"
1483+source = "registry+https://github.com/rust-lang/crates.io-index"
1484+checksum = "419e0dc8046cb947daa77eb95ae174acfbddb7673b4151f56d1eed8e93fbfaca"
1485+dependencies = [
1486+ "cfg-if",
1487+ "generator",
1488+ "scoped-tls",
1489+ "tracing",
1490+ "tracing-subscriber",
1491+]
1492+
1493+[[package]]
1494+name = "lru"
1495+version = "0.16.4"
1496+source = "registry+https://github.com/rust-lang/crates.io-index"
1497+checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39"
1498+dependencies = [
1499+ "hashbrown 0.16.1",
1500+]
1501+
1502+[[package]]
1503+name = "lz4_flex"
1504+version = "0.13.1"
1505+source = "registry+https://github.com/rust-lang/crates.io-index"
1506+checksum = "7ef0d4ed8669f8f8826eb00dc878084aa8f253506c4fd5e8f58f5bce72ddb97e"
1507+
1508+[[package]]
1509+name = "matchers"
1510+version = "0.2.0"
1511+source = "registry+https://github.com/rust-lang/crates.io-index"
1512+checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
1513+dependencies = [
1514+ "regex-automata",
1515+]
1516+
1517+[[package]]
1518+name = "measure_time"
1519+version = "0.9.0"
1520+source = "registry+https://github.com/rust-lang/crates.io-index"
1521+checksum = "51c55d61e72fc3ab704396c5fa16f4c184db37978ae4e94ca8959693a235fc0e"
1522+dependencies = [
1523+ "log",
1524+]
1525+
1526+[[package]]
1527+name = "memchr"
1528+version = "2.8.3"
1529+source = "registry+https://github.com/rust-lang/crates.io-index"
1530+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
1531+
1532+[[package]]
1533+name = "memmap2"
1534+version = "0.9.12"
1535+source = "registry+https://github.com/rust-lang/crates.io-index"
1536+checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157"
1537+dependencies = [
1538+ "libc",
1539+]
1540+
1541+[[package]]
1542+name = "memoffset"
1543+version = "0.9.1"
1544+source = "registry+https://github.com/rust-lang/crates.io-index"
1545+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
1546+dependencies = [
1547+ "autocfg",
1548+]
1549+
1550+[[package]]
1551+name = "miette"
1552+version = "7.6.0"
1553+source = "registry+https://github.com/rust-lang/crates.io-index"
1554+checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7"
1555+dependencies = [
1556+ "cfg-if",
1557+ "miette-derive",
1558+ "unicode-width",
1559+]
1560+
1561+[[package]]
1562+name = "miette-derive"
1563+version = "7.6.0"
1564+source = "registry+https://github.com/rust-lang/crates.io-index"
1565+checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b"
1566+dependencies = [
1567+ "proc-macro2",
1568+ "quote",
1569+ "syn 2.0.119",
1570+]
1571+
1572+[[package]]
1573+name = "mimalloc"
1574+version = "0.1.52"
1575+source = "registry+https://github.com/rust-lang/crates.io-index"
1576+checksum = "2d4139bb28d14ad1facf21d5eb8825051b326e172d216b39f6d31df53cc97862"
1577+dependencies = [
1578+ "libmimalloc-sys",
1579+]
1580+
1581+[[package]]
1582+name = "minimal-lexical"
1583+version = "0.2.1"
1584+source = "registry+https://github.com/rust-lang/crates.io-index"
1585+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
1586+
1587+[[package]]
1588+name = "murmurhash32"
1589+version = "0.3.1"
1590+source = "registry+https://github.com/rust-lang/crates.io-index"
1591+checksum = "2195bf6aa996a481483b29d62a7663eed3fe39600c460e323f8ff41e90bdd89b"
1592+
1593+[[package]]
1594+name = "nom"
1595+version = "7.1.3"
1596+source = "registry+https://github.com/rust-lang/crates.io-index"
1597+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
1598+dependencies = [
1599+ "memchr",
1600+ "minimal-lexical",
1601+]
1602+
1603+[[package]]
1604+name = "nu-ansi-term"
1605+version = "0.50.3"
1606+source = "registry+https://github.com/rust-lang/crates.io-index"
1607+checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
1608+dependencies = [
1609+ "windows-sys 0.61.2",
1610+]
1611+
1612+[[package]]
1613+name = "num-bigint"
1614+version = "0.4.8"
1615+source = "registry+https://github.com/rust-lang/crates.io-index"
1616+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
1617+dependencies = [
1618+ "num-integer",
1619+ "num-traits",
1620+]
1621+
1622+[[package]]
1623+name = "num-conv"
1624+version = "0.2.2"
1625+source = "registry+https://github.com/rust-lang/crates.io-index"
1626+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
1627+
1628+[[package]]
1629+name = "num-integer"
1630+version = "0.1.47"
1631+source = "registry+https://github.com/rust-lang/crates.io-index"
1632+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
1633+dependencies = [
1634+ "num-traits",
1635+]
1636+
1637+[[package]]
1638+name = "num-traits"
1639+version = "0.2.19"
1640+source = "registry+https://github.com/rust-lang/crates.io-index"
1641+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
1642+dependencies = [
1643+ "autocfg",
1644+]
1645+
1646+[[package]]
1647+name = "once_cell"
1648+version = "1.21.4"
1649+source = "registry+https://github.com/rust-lang/crates.io-index"
1650+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
1651+
1652+[[package]]
1653+name = "oneshot"
1654+version = "0.1.13"
1655+source = "registry+https://github.com/rust-lang/crates.io-index"
1656+checksum = "269bca4c2591a28585d6bf10d9ed0332b7d76900a1b02bec41bdc3a2cdcda107"
1657+
1658+[[package]]
1659+name = "opaque-debug"
1660+version = "0.3.1"
1661+source = "registry+https://github.com/rust-lang/crates.io-index"
1662+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
1663+
1664+[[package]]
1665+name = "ordered-float"
1666+version = "5.5.1"
1667+source = "registry+https://github.com/rust-lang/crates.io-index"
1668+checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab"
1669+dependencies = [
1670+ "num-traits",
1671+]
1672+
1673+[[package]]
1674+name = "ownedbytes"
1675+version = "0.9.0"
1676+source = "registry+https://github.com/rust-lang/crates.io-index"
1677+checksum = "2fbd56f7631767e61784dc43f8580f403f4475bd4aaa4da003e6295e1bab4a7e"
1678+dependencies = [
1679+ "stable_deref_trait",
1680+]
1681+
1682+[[package]]
1683+name = "owo-colors"
1684+version = "3.5.0"
1685+source = "registry+https://github.com/rust-lang/crates.io-index"
1686+checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f"
1687+
1688+[[package]]
1689+name = "pack1"
1690+version = "1.1.0"
1691+source = "registry+https://github.com/rust-lang/crates.io-index"
1692+checksum = "e3b7bb0ecf2e447b1f20ee94ee79ef6eed1e9d4b3c36ce1903b9dea3bf205523"
1693+dependencies = [
1694+ "bytemuck",
1695+]
1696+
1697+[[package]]
1698+name = "parking_lot"
1699+version = "0.12.5"
1700+source = "registry+https://github.com/rust-lang/crates.io-index"
1701+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
1702+dependencies = [
1703+ "lock_api",
1704+ "parking_lot_core",
1705+]
1706+
1707+[[package]]
1708+name = "parking_lot_core"
1709+version = "0.9.12"
1710+source = "registry+https://github.com/rust-lang/crates.io-index"
1711+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
1712+dependencies = [
1713+ "cfg-if",
1714+ "libc",
1715+ "redox_syscall",
1716+ "smallvec",
1717+ "windows-link",
1718+]
1719+
1720+[[package]]
1721+name = "password-hash"
1722+version = "0.6.1"
1723+source = "registry+https://github.com/rust-lang/crates.io-index"
1724+checksum = "aab41826031698d6ffcd9cff78ef56ef998e39dc7e5067cdfebe373842d4723b"
1725+dependencies = [
1726+ "getrandom 0.4.3",
1727+ "phc",
1728+]
1729+
1730+[[package]]
1731+name = "pastey"
1732+version = "0.2.3"
1733+source = "registry+https://github.com/rust-lang/crates.io-index"
1734+checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
1735+
1736+[[package]]
1737+name = "phc"
1738+version = "0.6.1"
1739+source = "registry+https://github.com/rust-lang/crates.io-index"
1740+checksum = "44dc769b75f93afdddd8c7fa12d685292ddeff1e66f7f0f3a234cf1818afe892"
1741+dependencies = [
1742+ "base64ct",
1743+ "ctutils",
1744+ "getrandom 0.4.3",
1745+]
1746+
1747+[[package]]
1748+name = "pin-project-lite"
1749+version = "0.2.17"
1750+source = "registry+https://github.com/rust-lang/crates.io-index"
1751+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
1752+
1753+[[package]]
1754+name = "pkg-config"
1755+version = "0.3.34"
1756+source = "registry+https://github.com/rust-lang/crates.io-index"
1757+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
1758+
1759+[[package]]
1760+name = "polling"
1761+version = "3.11.0"
1762+source = "registry+https://github.com/rust-lang/crates.io-index"
1763+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
1764+dependencies = [
1765+ "cfg-if",
1766+ "concurrent-queue",
1767+ "hermit-abi",
1768+ "pin-project-lite",
1769+ "rustix 1.1.6",
1770+ "windows-sys 0.61.2",
1771+]
1772+
1773+[[package]]
1774+name = "poly1305"
1775+version = "0.9.1"
1776+source = "registry+https://github.com/rust-lang/crates.io-index"
1777+checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"
1778+dependencies = [
1779+ "cpufeatures 0.3.1",
1780+ "universal-hash 0.6.1",
1781+]
1782+
1783+[[package]]
1784+name = "polyval"
1785+version = "0.6.2"
1786+source = "registry+https://github.com/rust-lang/crates.io-index"
1787+checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"
1788+dependencies = [
1789+ "cfg-if",
1790+ "cpufeatures 0.2.17",
1791+ "opaque-debug",
1792+ "universal-hash 0.5.1",
1793+]
1794+
1795+[[package]]
1796+name = "potential_utf"
1797+version = "0.1.6"
1798+source = "registry+https://github.com/rust-lang/crates.io-index"
1799+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
1800+dependencies = [
1801+ "serde_core",
1802+ "writeable",
1803+ "zerovec",
1804+]
1805+
1806+[[package]]
1807+name = "powerfmt"
1808+version = "0.2.1"
1809+source = "registry+https://github.com/rust-lang/crates.io-index"
1810+checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
1811+
1812+[[package]]
1813+name = "ppv-lite86"
1814+version = "0.2.21"
1815+source = "registry+https://github.com/rust-lang/crates.io-index"
1816+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
1817+dependencies = [
1818+ "zerocopy",
1819+]
1820+
1821+[[package]]
1822+name = "prettyplease"
1823+version = "0.2.37"
1824+source = "registry+https://github.com/rust-lang/crates.io-index"
1825+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
1826+dependencies = [
1827+ "proc-macro2",
1828+ "syn 2.0.119",
1829+]
1830+
1831+[[package]]
1832+name = "prettyplease"
1833+version = "0.3.0"
1834+source = "registry+https://github.com/rust-lang/crates.io-index"
1835+checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0"
1836+dependencies = [
1837+ "proc-macro2",
1838+ "syn 3.0.9",
1839+]
1840+
1841+[[package]]
1842+name = "proc-macro2"
1843+version = "1.0.107"
1844+source = "registry+https://github.com/rust-lang/crates.io-index"
1845+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
1846+dependencies = [
1847+ "unicode-ident",
1848+]
1849+
1850+[[package]]
1851+name = "prost"
1852+version = "0.14.4"
1853+source = "registry+https://github.com/rust-lang/crates.io-index"
1854+checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"
1855+dependencies = [
1856+ "bytes",
1857+ "prost-derive",
1858+]
1859+
1860+[[package]]
1861+name = "prost-derive"
1862+version = "0.14.4"
1863+source = "registry+https://github.com/rust-lang/crates.io-index"
1864+checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"
1865+dependencies = [
1866+ "anyhow",
1867+ "itertools 0.14.0",
1868+ "proc-macro2",
1869+ "quote",
1870+ "syn 2.0.119",
1871+]
1872+
1873+[[package]]
1874+name = "quote"
1875+version = "1.0.47"
1876+source = "registry+https://github.com/rust-lang/crates.io-index"
1877+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
1878+dependencies = [
1879+ "proc-macro2",
1880+]
1881+
1882+[[package]]
1883+name = "r-efi"
1884+version = "5.3.0"
1885+source = "registry+https://github.com/rust-lang/crates.io-index"
1886+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
1887+
1888+[[package]]
1889+name = "r-efi"
1890+version = "6.0.0"
1891+source = "registry+https://github.com/rust-lang/crates.io-index"
1892+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
1893+
1894+[[package]]
1895+name = "radium"
1896+version = "0.7.0"
1897+source = "registry+https://github.com/rust-lang/crates.io-index"
1898+checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"
1899+
1900+[[package]]
1901+name = "rand"
1902+version = "0.8.8"
1903+source = "registry+https://github.com/rust-lang/crates.io-index"
1904+checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
1905+dependencies = [
1906+ "libc",
1907+ "rand_chacha 0.3.1",
1908+ "rand_core 0.6.4",
1909+]
1910+
1911+[[package]]
1912+name = "rand"
1913+version = "0.9.5"
1914+source = "registry+https://github.com/rust-lang/crates.io-index"
1915+checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
1916+dependencies = [
1917+ "rand_chacha 0.9.0",
1918+ "rand_core 0.9.5",
1919+]
1920+
1921+[[package]]
1922+name = "rand"
1923+version = "0.10.3"
1924+source = "registry+https://github.com/rust-lang/crates.io-index"
1925+checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
1926+dependencies = [
1927+ "chacha20",
1928+ "getrandom 0.4.3",
1929+ "rand_core 0.10.1",
1930+]
1931+
1932+[[package]]
1933+name = "rand_chacha"
1934+version = "0.3.1"
1935+source = "registry+https://github.com/rust-lang/crates.io-index"
1936+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
1937+dependencies = [
1938+ "ppv-lite86",
1939+ "rand_core 0.6.4",
1940+]
1941+
1942+[[package]]
1943+name = "rand_chacha"
1944+version = "0.9.0"
1945+source = "registry+https://github.com/rust-lang/crates.io-index"
1946+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
1947+dependencies = [
1948+ "ppv-lite86",
1949+ "rand_core 0.9.5",
1950+]
1951+
1952+[[package]]
1953+name = "rand_core"
1954+version = "0.6.4"
1955+source = "registry+https://github.com/rust-lang/crates.io-index"
1956+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
1957+dependencies = [
1958+ "getrandom 0.2.17",
1959+]
1960+
1961+[[package]]
1962+name = "rand_core"
1963+version = "0.9.5"
1964+source = "registry+https://github.com/rust-lang/crates.io-index"
1965+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
1966+dependencies = [
1967+ "getrandom 0.3.4",
1968+]
1969+
1970+[[package]]
1971+name = "rand_core"
1972+version = "0.10.1"
1973+source = "registry+https://github.com/rust-lang/crates.io-index"
1974+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
1975+
1976+[[package]]
1977+name = "rand_pcg"
1978+version = "0.3.1"
1979+source = "registry+https://github.com/rust-lang/crates.io-index"
1980+checksum = "59cad018caf63deb318e5a4586d99a24424a364f40f1e5778c29aca23f4fc73e"
1981+dependencies = [
1982+ "rand_core 0.6.4",
1983+]
1984+
1985+[[package]]
1986+name = "rapidhash"
1987+version = "4.5.1"
1988+source = "registry+https://github.com/rust-lang/crates.io-index"
1989+checksum = "5da7e78a036ce858e8d55b7e7dc8ba3a88b78350fd2155d3591bbd966b58589e"
1990+dependencies = [
1991+ "rustversion",
1992+]
1993+
1994+[[package]]
1995+name = "rayon"
1996+version = "1.12.0"
1997+source = "registry+https://github.com/rust-lang/crates.io-index"
1998+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
1999+dependencies = [
2000+ "either",
Cargo.tomladded+57 -0
@@ -0,0 +1,57 @@
1+[workspace]
2+resolver = "3"
3+members = [
4+ "crates/im-core",
5+ "crates/im-web",
6+]
7+
8+[workspace.package]
9+version = "0.1.0"
10+edition = "2024"
11+license = "AGPL-3.0-or-later"
12+
13+[workspace.dependencies]
14+argon2 = "0.6.0"
15+base64 = "0.23.1"
16+chacha20poly1305 = "0.11.0"
17+ed25519-dalek = { version = "3.0.0", features = ["rand_core"] }
18+hex = "0.4.3"
19+ipnet = "2.12.2"
20+rand = "0.10.3"
21+serde = { version = "1.0.229", features = ["derive"] }
22+serde_json = "1.0.154"
23+sha2 = "0.11.1"
24+subtle = "2.6.1"
25+thiserror = "2.0.21"
26+time = { version = "0.3.55", features = ["formatting", "parsing", "macros"] }
27+tokio = { version = "1.54.1", features = ["sync", "rt", "rt-multi-thread", "macros"] }
28+toml = "1.1.8"
29+tracing = "0.1.44"
30+turso = "0.8.3"
31+ulid = "3.0.0"
32+tempfile = "3.27.0"
33+# internal crates
34+im-core = { path = "crates/im-core" }
35+
36+[workspace.lints.rust]
37+unsafe_code = "forbid"
38+
39+[profile.dev]
40+# Line tables keep file:line in backtraces but drop variable info; binaries and links are much smaller.
41+debug = "line-tables-only"
42+
43+[profile.dev.package.argon2]
44+# Password hashing (argon2id) takes hundreds of ms per call when unoptimized; release is unaffected.
45+opt-level = 3
46+
47+[profile.dev.package.sha2]
48+# Hashing session and token digests on every request is too slow unoptimized.
49+opt-level = 3
50+
51+[profile.dev.package.turso]
52+# The embedded database engine is too slow unoptimized to run the store tests quickly.
53+opt-level = 3
54+
55+[profile.release]
56+lto = true
57+codegen-units = 1
config/im.example.tomladded+33 -0
@@ -0,0 +1,33 @@
1+# im configuration. This file is committed as the example. The live file is config/im.toml (gitignored),
2+# and it is created from this one on first run when it is missing. Secrets never go in this file: enter
3+# them in the admin UI, where they are sealed in the database.
4+
5+# SQLite-format database. Relative paths are relative to the working directory.
6+database = "data/im.db"
7+
8+# Holds the instance key (im.key), photos and backups. Created with mode 0700 when missing.
9+data_dir = "data"
10+
11+# Address the HTTP server binds to. Put a TLS-terminating reverse proxy in front of it in production.
12+listen = "127.0.0.1:8080"
13+
14+# Public origin, with no trailing slash. This is the OpenID issuer and the origin of links in mail.
15+base_url = "http://localhost:8080"
16+
17+# Proxies whose X-Forwarded-For header is believed, as addresses or CIDR networks. Empty means the
18+# TCP peer is always the client address.
19+trusted_proxies = []
20+
21+[mail]
22+# Development only: write mail to data/mail-log/ instead of sending it.
23+log_only = true
24+
25+[backup]
26+# Directory for scheduled backups. Empty turns them off.
27+dir = ""
28+# Hours between two scheduled backups. At least 1.
29+interval_hours = 24
30+# Snapshot sets kept. At least 1.
31+keep = 7
32+# Dead-man URL pinged after each run. Empty for none.
33+healthcheck_url = ""
crates/im-core/Cargo.tomladded+32 -0
@@ -0,0 +1,32 @@
1+[package]
2+name = "im-core"
3+version.workspace = true
4+edition.workspace = true
5+license.workspace = true
6+publish = false
7+
8+[lints]
9+workspace = true
10+
11+[dependencies]
12+argon2.workspace = true
13+base64.workspace = true
14+chacha20poly1305.workspace = true
15+ed25519-dalek.workspace = true
16+hex.workspace = true
17+ipnet.workspace = true
18+rand.workspace = true
19+serde.workspace = true
20+serde_json.workspace = true
21+sha2.workspace = true
22+subtle.workspace = true
23+thiserror.workspace = true
24+time.workspace = true
25+tokio.workspace = true
26+toml.workspace = true
27+tracing.workspace = true
28+turso.workspace = true
29+ulid.workspace = true
30+
31+[dev-dependencies]
32+tempfile.workspace = true
crates/im-core/migrations/0001_init.sqladded+237 -0
@@ -0,0 +1,237 @@
1+-- 0001: the whole initial schema of im. Every table, its constraints and its lookup indexes.
2+-- Ids are ULID text; timestamps are fixed-width UTC RFC 3339 text; booleans are INTEGER 0/1.
3+-- Never edit this file once it has been applied anywhere; add 0002_... instead.
4+
5+CREATE TABLE users (
6+ id TEXT PRIMARY KEY,
7+ email TEXT NOT NULL,
8+ email_folded TEXT NOT NULL UNIQUE,
9+ name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 100),
10+ password_hash TEXT NOT NULL,
11+ is_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_admin IN (0, 1)),
12+ disabled_at TEXT,
13+ -- Sealed TOTP secret. Held while enrolling (totp_enabled_at NULL) and kept after enabling.
14+ totp_secret_sealed TEXT,
15+ totp_enabled_at TEXT,
16+ totp_last_step INTEGER,
17+ locale TEXT NOT NULL DEFAULT 'en' CHECK (locale IN ('en', 'tr')),
18+ zoneinfo TEXT NOT NULL DEFAULT 'Europe/Istanbul',
19+ theme TEXT NOT NULL DEFAULT 'system' CHECK (theme IN ('system', 'light', 'dark')),
20+ photo_mime TEXT,
21+ picture_version INTEGER NOT NULL DEFAULT 0,
22+ created_at TEXT NOT NULL,
23+ updated_at TEXT NOT NULL
24+);
25+
26+-- Ten codes per set, shown once. Only their hashes are stored; used_at marks a consumed code.
27+CREATE TABLE recovery_codes (
28+ user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
29+ code_hash TEXT NOT NULL,
30+ used_at TEXT,
31+ PRIMARY KEY (user_id, code_hash)
32+);
33+
34+-- Browser sessions. The id is the OIDC `sid`. Ended sessions are deleted, after their
35+-- back-channel logout jobs are queued.
36+CREATE TABLE sessions (
37+ id TEXT PRIMARY KEY,
38+ user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
39+ token_hash TEXT NOT NULL UNIQUE,
40+ csrf_token TEXT NOT NULL,
41+ created_at TEXT NOT NULL,
42+ expires_at TEXT NOT NULL,
43+ last_seen_at TEXT NOT NULL,
44+ ip TEXT,
45+ user_agent TEXT,
46+ auth_time TEXT NOT NULL,
47+ amr TEXT NOT NULL CHECK (amr IN ('pwd', 'pwd otp', 'pwd rc'))
48+);
49+CREATE INDEX sessions_user ON sessions (user_id);
50+CREATE INDEX sessions_expires ON sessions (expires_at);
51+
52+-- OIDC clients. secret_hash is the hash of the client secret; the secret itself is shown once.
53+CREATE TABLE clients (
54+ id TEXT PRIMARY KEY,
55+ name TEXT NOT NULL,
56+ secret_hash TEXT NOT NULL,
57+ secret_rotated_at TEXT NOT NULL,
58+ redirect_uris TEXT NOT NULL DEFAULT '[]' CHECK (json_valid (redirect_uris)),
59+ post_logout_redirect_uris TEXT NOT NULL DEFAULT '[]' CHECK (json_valid (post_logout_redirect_uris)),
60+ backchannel_logout_uri TEXT,
61+ allowed_scopes TEXT NOT NULL,
62+ service_key TEXT UNIQUE,
63+ created_at TEXT NOT NULL,
64+ disabled_at TEXT
65+);
66+
67+-- The switcher list. im's own row (key 'im') is maintained at boot from base_url.
68+CREATE TABLE services (
69+ key TEXT PRIMARY KEY CHECK (
70+ length(key) BETWEEN 1 AND 32
71+ AND key GLOB '[a-z]*'
72+ AND key NOT GLOB '*[^a-z0-9-]*'
73+ ),
74+ name TEXT NOT NULL,
75+ url TEXT NOT NULL,
76+ position INTEGER NOT NULL DEFAULT 0,
77+ client_id TEXT REFERENCES clients (id) ON DELETE SET NULL,
78+ healthy INTEGER CHECK (healthy IS NULL OR healthy IN (0, 1)),
79+ checked_at TEXT,
80+ check_ms INTEGER,
81+ check_error TEXT
82+);
83+
84+-- One-time authorization codes. A second use of a used code revokes the refresh tokens issued
85+-- from it (refresh_tokens.code_hash).
86+CREATE TABLE auth_codes (
87+ code_hash TEXT PRIMARY KEY,
88+ client_id TEXT NOT NULL REFERENCES clients (id) ON DELETE CASCADE,
89+ user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
90+ session_id TEXT NOT NULL REFERENCES sessions (id) ON DELETE CASCADE,
91+ redirect_uri TEXT NOT NULL,
92+ scope TEXT NOT NULL,
93+ nonce TEXT,
94+ -- PKCE S256 is mandatory for every client (contracts.md 2.3).
95+ code_challenge TEXT NOT NULL,
96+ expires_at TEXT NOT NULL,
97+ used_at TEXT
98+);
99+CREATE INDEX auth_codes_expires ON auth_codes (expires_at);
100+
101+-- Refresh tokens, rotated on every use. Presenting a used token revokes its whole family.
102+CREATE TABLE refresh_tokens (
103+ id TEXT PRIMARY KEY,
104+ token_hash TEXT NOT NULL UNIQUE,
105+ family_id TEXT NOT NULL,
106+ client_id TEXT NOT NULL REFERENCES clients (id) ON DELETE CASCADE,
107+ user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
108+ session_id TEXT NOT NULL REFERENCES sessions (id) ON DELETE CASCADE,
109+ -- Plain text, not a foreign key: authorization codes are swept while their tokens live on.
110+ code_hash TEXT,
111+ scope TEXT NOT NULL,
112+ created_at TEXT NOT NULL,
113+ expires_at TEXT NOT NULL,
114+ used_at TEXT,
115+ revoked_at TEXT
116+);
117+CREATE INDEX refresh_tokens_family ON refresh_tokens (family_id);
118+CREATE INDEX refresh_tokens_session ON refresh_tokens (session_id);
119+
120+-- Which clients a browser session has signed in to. Drives back-channel logout and the
121+-- "connected apps" list.
122+CREATE TABLE client_sessions (
123+ session_id TEXT NOT NULL REFERENCES sessions (id) ON DELETE CASCADE,
124+ client_id TEXT NOT NULL REFERENCES clients (id) ON DELETE CASCADE,
125+ first_at TEXT NOT NULL,
126+ last_at TEXT NOT NULL,
127+ PRIMARY KEY (session_id, client_id)
128+);
129+CREATE INDEX client_sessions_client ON client_sessions (client_id);
130+
131+-- Token-signing keys. kid is the first 16 hex characters of the SHA-256 of the public key. The
132+-- current key is the newest one that is active and not retired.
133+CREATE TABLE signing_keys (
134+ kid TEXT PRIMARY KEY,
135+ private_sealed TEXT NOT NULL,
136+ public_raw BLOB NOT NULL,
137+ created_at TEXT NOT NULL,
138+ activates_at TEXT NOT NULL,
139+ retires_at TEXT
140+);
141+CREATE INDEX signing_keys_current ON signing_keys (activates_at) WHERE retires_at IS NULL;
142+
143+-- Invitations. The token is stored as its hash. A new invite for an address deletes its older
144+-- pending invites.
145+CREATE TABLE invites (
146+ token_hash TEXT PRIMARY KEY,
147+ email_folded TEXT NOT NULL,
148+ is_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_admin IN (0, 1)),
149+ invited_by TEXT REFERENCES users (id) ON DELETE SET NULL,
150+ created_at TEXT NOT NULL,
151+ expires_at TEXT NOT NULL,
152+ accepted_at TEXT
153+);
154+CREATE INDEX invites_email ON invites (email_folded);
155+
156+-- Single-use links for password reset and both halves of an email change. The two halves of one
157+-- email change share pair_id.
158+CREATE TABLE account_links (
159+ token_hash TEXT PRIMARY KEY,
160+ kind TEXT NOT NULL CHECK (kind IN ('reset', 'email_old', 'email_new')),
161+ user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
162+ pair_id TEXT,
163+ new_email TEXT,
164+ created_at TEXT NOT NULL,
165+ expires_at TEXT NOT NULL,
166+ used_at TEXT
167+);
168+CREATE INDEX account_links_user ON account_links (user_id);
169+CREATE INDEX account_links_pair ON account_links (pair_id);
170+
171+-- Outgoing mail, sent by the mail worker with retries. Links in bodies are never logged.
172+CREATE TABLE mail_outbox (
173+ id TEXT PRIMARY KEY,
174+ kind TEXT NOT NULL CHECK (kind IN (
175+ 'invite', 'reset', 'email_old', 'email_new', 'email_done', 'notice', 'test', 'security'
176+ )),
177+ to_addr TEXT NOT NULL,
178+ subject TEXT NOT NULL,
179+ body_text TEXT NOT NULL,
180+ state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')),
181+ attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),
182+ next_attempt_at TEXT NOT NULL,
183+ last_error TEXT,
184+ created_at TEXT NOT NULL,
185+ sent_at TEXT
186+);
187+CREATE INDEX mail_outbox_due ON mail_outbox (state, next_attempt_at);
188+
189+-- Back-channel logout deliveries to clients, sent by the back-channel worker.
190+CREATE TABLE backchannel_outbox (
191+ id TEXT PRIMARY KEY,
192+ client_id TEXT NOT NULL REFERENCES clients (id) ON DELETE CASCADE,
193+ sid TEXT,
194+ sub TEXT NOT NULL,
195+ reason TEXT NOT NULL,
196+ state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')),
197+ attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),
198+ next_attempt_at TEXT NOT NULL,
199+ last_error TEXT,
200+ created_at TEXT NOT NULL,
201+ done_at TEXT
202+);
203+CREATE INDEX backchannel_outbox_due ON backchannel_outbox (state, next_attempt_at);
204+
205+-- The change feed for machine clients. seq is the cursor. Rows older than 30 days are pruned.
206+CREATE TABLE directory_changes (
207+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
208+ sub TEXT NOT NULL,
209+ kind TEXT NOT NULL CHECK (kind IN ('member', 'deleted')),
210+ at TEXT NOT NULL
211+);
212+CREATE INDEX directory_changes_at ON directory_changes (at);
213+
214+-- Append-only record of changes. actor_id and target_id are not foreign keys, so the trail
215+-- survives the deletion of the user it names. data never holds secrets.
216+CREATE TABLE audit_log (
217+ id TEXT PRIMARY KEY,
218+ at TEXT NOT NULL,
219+ actor_id TEXT,
220+ actor_kind TEXT NOT NULL CHECK (actor_kind IN ('user', 'client', 'cli', 'system', 'anonymous')),
221+ action TEXT NOT NULL,
222+ target_kind TEXT,
223+ target_id TEXT,
224+ ip TEXT,
225+ data TEXT CHECK (data IS NULL OR json_valid (data))
226+);
227+CREATE INDEX audit_log_at ON audit_log (at);
228+CREATE INDEX audit_log_actor ON audit_log (actor_id, at);
229+CREATE INDEX audit_log_target ON audit_log (target_kind, target_id, at);
230+
231+-- Runtime setting overrides (admin UI values and the sealed SMTP password). Precedence is
232+-- override, then config file, then built-in default.
233+CREATE TABLE settings (
234+ key TEXT PRIMARY KEY,
235+ value TEXT NOT NULL,
236+ updated_at TEXT NOT NULL
237+);
crates/im-core/src/config.rsadded+181 -0
@@ -0,0 +1,181 @@
1+//! The instance configuration, read from TOML.
2+//!
3+//! Only non-secret, deployment-level settings live here. Secrets are never in this file: they are
4+//! entered in the admin UI and sealed in the database, or kept in a separate file that only the
5+//! service user can read. Every struct rejects unknown keys, so a typo fails at boot instead of
6+//! silently doing nothing.
7+
8+use std::net::SocketAddr;
9+use std::path::{Path, PathBuf};
10+
11+use ipnet::IpNet;
12+use serde::{Deserialize, Deserializer};
13+
14+use crate::error::{Error, Result};
15+
16+/// The example file. It is written to the config path on first run when that path is missing.
17+const EXAMPLE: &str = include_str!("../../../config/im.example.toml");
18+
19+/// Parses each entry as a CIDR network, or as a single address (a /32 or /128).
20+fn deserialize_trusted_proxies<'de, D: Deserializer<'de>>(
21+ deserializer: D,
22+) -> std::result::Result<Vec<IpNet>, D::Error> {
23+ let entries = Vec::<String>::deserialize(deserializer)?;
24+ entries
25+ .iter()
26+ .map(|entry| {
27+ entry
28+ .parse::<IpNet>()
29+ .or_else(|_| entry.parse::<std::net::IpAddr>().map(IpNet::from))
30+ .map_err(|_| serde::de::Error::custom(format!("invalid trusted proxy `{entry}`")))
31+ })
32+ .collect()
33+}
34+
35+/// Outbound mail settings that do not involve a secret.
36+#[derive(Debug, Clone, Default, Deserialize)]
37+#[serde(deny_unknown_fields, default)]
38+pub struct MailConfig {
39+ /// When true, mail is written to `data_dir/mail-log/` instead of being sent. For development
40+ /// only; a production instance sends mail through the SMTP sender set in the admin UI.
41+ pub log_only: bool,
42+}
43+
44+/// Scheduled backups. Off while `dir` is empty.
45+#[derive(Debug, Clone, Deserialize)]
46+#[serde(deny_unknown_fields, default)]
47+pub struct BackupConfig {
48+ /// Directory that receives one snapshot set per run. Empty turns backups off.
49+ pub dir: PathBuf,
50+ /// Hours between two scheduled backups. Must be at least 1 when backups are on.
51+ pub interval_hours: u64,
52+ /// Number of snapshot sets kept; older sets are deleted after a successful run. At least 1.
53+ pub keep: u32,
54+ /// Dead-man URL pinged after each run (`/start`, then success or `/fail`). Empty for none.
55+ pub healthcheck_url: String,
56+}
57+
58+impl Default for BackupConfig {
59+ fn default() -> Self {
60+ Self {
61+ dir: PathBuf::new(),
62+ interval_hours: 24,
63+ keep: 7,
64+ healthcheck_url: String::new(),
65+ }
66+ }
67+}
68+
69+impl BackupConfig {
70+ /// True when a backup directory is set.
71+ pub fn enabled(&self) -> bool {
72+ !self.dir.as_os_str().is_empty()
73+ }
74+}
75+
76+/// The whole file. Field names are the TOML keys.
77+#[derive(Debug, Clone, Deserialize)]
78+#[serde(deny_unknown_fields)]
79+pub struct Config {
80+ /// Path of the SQLite-format database file.
81+ pub database: PathBuf,
82+ /// Directory for the instance key, photos, backups and other files beside the database.
83+ pub data_dir: PathBuf,
84+ /// Address the HTTP server binds to.
85+ pub listen: SocketAddr,
86+ /// Public origin of this instance, such as `https://id.example.com`. No trailing slash. Used
87+ /// for links in mail and for the OpenID issuer.
88+ pub base_url: String,
89+ /// Peers whose `X-Forwarded-For` header is believed. Entries are addresses or CIDR networks.
90+ /// Empty by default, so the TCP peer is always the client.
91+ #[serde(default, deserialize_with = "deserialize_trusted_proxies")]
92+ pub trusted_proxies: Vec<IpNet>,
93+ /// Mail settings without secrets.
94+ #[serde(default)]
95+ pub mail: MailConfig,
96+ /// Scheduled backups.
97+ #[serde(default)]
98+ pub backup: BackupConfig,
99+}
100+
101+impl Config {
102+ /// Reads and validates the file at `path`.
103+ ///
104+ /// When the file does not exist, the example file is written there first (creating its parent
105+ /// directory), so a fresh checkout runs with development defaults.
106+ pub fn load(path: &Path) -> Result<Config> {
107+ let text = match std::fs::read_to_string(path) {
108+ Ok(text) => text,
109+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
110+ if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
111+ std::fs::create_dir_all(parent)?;
112+ }
113+ std::fs::write(path, EXAMPLE)?;
114+ EXAMPLE.to_owned()
115+ }
116+ Err(e) => return Err(e.into()),
117+ };
118+ Self::parse(&text).map_err(|e| Error::Config(format!("{}: {e}", path.display())))
119+ }
120+
121+ /// Parses and validates TOML text. Used by [`Config::load`] and by tests.
122+ pub fn parse(text: &str) -> Result<Config> {
123+ let config: Config = toml::from_str(text).map_err(|e| Error::Config(format!("{e}")))?;
124+ config.validate()?;
125+ Ok(config)
126+ }
127+
128+ /// The cross-field rules that cannot be expressed per field. Run after parsing.
129+ pub fn validate(&self) -> Result<()> {
130+ if self.database.as_os_str().is_empty() {
131+ return Err(Error::Config("database must not be empty".into()));
132+ }
133+ if self.data_dir.as_os_str().is_empty() {
134+ return Err(Error::Config("data_dir must not be empty".into()));
135+ }
136+ validate_base_url(&self.base_url)?;
137+ if self.backup.enabled() {
138+ if self.backup.interval_hours == 0 {
139+ return Err(Error::Config(
140+ "[backup] interval_hours must be at least 1".into(),
141+ ));
142+ }
143+ if self.backup.keep == 0 {
144+ return Err(Error::Config("[backup] keep must be at least 1".into()));
145+ }
146+ }
147+ let hc = &self.backup.healthcheck_url;
148+ if !hc.is_empty() && !(hc.starts_with("https://") || hc.starts_with("http://")) {
149+ return Err(Error::Config(
150+ "[backup] healthcheck_url must be an http or https URL".into(),
151+ ));
152+ }
153+ Ok(())
154+ }
155+}
156+
157+/// Checks that `base_url` is an http(s) origin with a path of at most `/`.
158+fn validate_base_url(url: &str) -> Result<()> {
159+ let rest = url
160+ .strip_prefix("https://")
161+ .or_else(|| url.strip_prefix("http://"))
162+ .ok_or_else(|| Error::Config("base_url must start with http:// or https://".into()))?;
163+ if rest.is_empty() || rest.ends_with('/') || url.chars().any(char::is_whitespace) {
164+ return Err(Error::Config(
165+ "base_url must be an origin with no trailing slash or spaces".into(),
166+ ));
167+ }
168+ Ok(())
169+}
170+
171+#[cfg(test)]
172+mod tests {
173+ use super::*;
174+
175+ #[test]
176+ fn example_file_parses_and_rejects_unknown_keys() {
177+ Config::parse(EXAMPLE).expect("the example must be valid");
178+ let typo = format!("{EXAMPLE}\nlisen = \"0.0.0.0:1\"\n");
179+ assert!(Config::parse(&typo).is_err());
180+ }
181+}
crates/im-core/src/error.rsadded+39 -0
@@ -0,0 +1,39 @@
1+//! The error type shared by every `im-core` module.
2+//!
3+//! `Invalid` and `Conflict` carry text that is safe to show the user. Every other variant is a
4+//! server-side failure: the web layer answers with a generic page and logs the cause.
5+
6+/// Everything `im-core` can fail with.
7+#[derive(Debug, thiserror::Error)]
8+pub enum Error {
9+ /// A filesystem operation failed.
10+ #[error("io error: {0}")]
11+ Io(#[from] std::io::Error),
12+ /// The database rejected a statement or could not be opened.
13+ #[error("database error: {0}")]
14+ Database(String),
15+ /// A migration could not be recorded or applied.
16+ #[error("migration error: {0}")]
17+ Migration(String),
18+ /// The configuration file is unreadable or breaks a cross-field rule.
19+ #[error("config error: {0}")]
20+ Config(String),
21+ /// Sealing, opening, hashing or the instance key failed.
22+ #[error("crypto error: {0}")]
23+ Crypto(String),
24+ /// The row asked for does not exist, or the caller may not know that it does.
25+ #[error("not found")]
26+ NotFound,
27+ /// The request clashes with existing state, such as a taken email address. Shown to the user.
28+ #[error("conflict: {0}")]
29+ Conflict(String),
30+ /// The caller may not do this. Shown to the user.
31+ #[error("forbidden: {0}")]
32+ Forbidden(String),
33+ /// The input is malformed or breaks a policy. Shown to the user.
34+ #[error("invalid value: {0}")]
35+ Invalid(String),
36+}
37+
38+/// `Result` with the crate error.
39+pub type Result<T> = std::result::Result<T, Error>;
crates/im-core/src/lib.rsadded+14 -0
@@ -0,0 +1,14 @@
1+//! Domain core of `im`: errors, time, secrets, tokens, passwords, configuration and the store.
2+//!
3+//! This crate has no HTTP code. It holds the pieces every other part of `im` depends on, so that
4+//! the web binary cannot get a security primitive or a database rule wrong by re-implementing it.
5+
6+pub mod config;
7+pub mod error;
8+pub mod password;
9+pub mod secret;
10+pub mod store;
11+pub mod time;
12+pub mod token;
13+
14+pub use error::{Error, Result};
crates/im-core/src/password.rsadded+125 -0
@@ -0,0 +1,125 @@
1+//! Password hashing with argon2id, and the password policy.
2+//!
3+//! Hashes are PHC strings with a random salt. Hashing and verifying take hundreds of milliseconds
4+//! by design, so the async wrappers move that work onto the blocking thread pool; a request task
5+//! must never run argon2 inline.
6+
7+use argon2::Argon2;
8+use argon2::password_hash::phc::PasswordHash;
9+use argon2::password_hash::{PasswordHasher, PasswordVerifier};
10+
11+use crate::error::{Error, Result};
12+
13+/// Shortest accepted password, in characters. Length is the main defence against guessing, so it
14+/// is set well above what people choose by habit.
15+pub const MIN_PASSWORD_CHARS: usize = 10;
16+
17+/// Longest accepted password, in characters. Bounds the work an attacker can force argon2 to do
18+/// per request.
19+pub const MAX_PASSWORD_CHARS: usize = 256;
20+
21+/// Shortest word of the name or email local part that a password may not contain, in characters.
22+/// Shorter words are too common to forbid: a two-letter word would reject many good passwords.
23+pub const MIN_FORBIDDEN_WORD_CHARS: usize = 4;
24+
25+/// Hashes `pw` with argon2id (default parameters) and a fresh random salt. Returns a PHC string.
26+pub fn hash_password(pw: &str) -> Result<String> {
27+ Argon2::default()
28+ .hash_password(pw.as_bytes())
29+ .map(|h| h.to_string())
30+ .map_err(|e| Error::Crypto(format!("argon2: {e}")))
31+}
32+
33+/// Returns true only if `pw` matches the PHC string `hash`. A malformed hash gives false, never
34+/// a panic.
35+pub fn verify_password(pw: &str, hash: &str) -> bool {
36+ let Ok(parsed) = PasswordHash::new(hash) else {
37+ return false;
38+ };
39+ Argon2::default()
40+ .verify_password(pw.as_bytes(), &parsed)
41+ .is_ok()
42+}
43+
44+/// [`hash_password`] on the blocking thread pool.
45+pub async fn hash_password_async(pw: String) -> Result<String> {
46+ tokio::task::spawn_blocking(move || hash_password(&pw))
47+ .await
48+ .map_err(|e| Error::Crypto(format!("hashing task failed: {e}")))?
49+}
50+
51+/// [`verify_password`] on the blocking thread pool.
52+pub async fn verify_password_async(pw: String, hash: String) -> Result<bool> {
53+ tokio::task::spawn_blocking(move || verify_password(&pw, &hash))
54+ .await
55+ .map_err(|e| Error::Crypto(format!("verify task failed: {e}")))
56+}
57+
58+/// Checks a new password against the policy.
59+///
60+/// Rules: 10 to 256 characters; it must not contain the email local part (when that is at least
61+/// [`MIN_FORBIDDEN_WORD_CHARS`] long) or any word of the name that is at least that long, compared
62+/// case-insensitively. The rule that the password differs from the current one needs the stored
63+/// hash and is checked by the caller.
64+///
65+/// Returns `Error::Invalid` with a message that is safe to show the user.
66+pub fn check_policy(password: &str, email: &str, name: &str) -> Result<()> {
67+ let chars = password.chars().count();
68+ if chars < MIN_PASSWORD_CHARS {
69+ return Err(Error::Invalid(format!(
70+ "password must be at least {MIN_PASSWORD_CHARS} characters"
71+ )));
72+ }
73+ if chars > MAX_PASSWORD_CHARS {
74+ return Err(Error::Invalid(format!(
75+ "password must be at most {MAX_PASSWORD_CHARS} characters"
76+ )));
77+ }
78+
79+ let lowered = password.to_lowercase();
80+ let local_part = email.split('@').next().unwrap_or_default();
81+ let forbidden = std::iter::once(local_part)
82+ .chain(name.split(|c: char| !c.is_alphanumeric()))
83+ .map(str::to_lowercase)
84+ .filter(|word| word.chars().count() >= MIN_FORBIDDEN_WORD_CHARS);
85+ for word in forbidden {
86+ if lowered.contains(&word) {
87+ return Err(Error::Invalid(
88+ "password must not contain your email address or name".into(),
89+ ));
90+ }
91+ }
92+ Ok(())
93+}
94+
95+#[cfg(test)]
96+mod tests {
97+ use super::*;
98+
99+ #[test]
100+ fn hash_then_verify_accepts_only_the_same_password() {
101+ let hash = hash_password("correct horse").unwrap();
102+ assert!(hash.starts_with("$argon2id$"));
103+ assert!(verify_password("correct horse", &hash));
104+ assert!(!verify_password("wrong", &hash));
105+ assert!(!verify_password("pw", "not a phc string"));
106+ }
107+
108+ #[test]
109+ fn policy_enforces_length_bounds() {
110+ assert!(check_policy("short", "a@example.com", "Ada").is_err());
111+ assert!(check_policy("nine-char", "a@example.com", "Ada").is_err());
112+ assert!(check_policy("ten-chars!", "a@example.com", "Ada").is_ok());
113+ let long = "x".repeat(MAX_PASSWORD_CHARS + 1);
114+ assert!(check_policy(&long, "a@example.com", "Ada").is_err());
115+ }
116+
117+ #[test]
118+ fn policy_rejects_email_local_part_and_name_words_case_insensitively() {
119+ let email = "tahinli@example.com";
120+ assert!(check_policy("My-TAHINLI-pass", email, "Ada").is_err());
121+ assert!(check_policy("correct Lovelace horse", email, "Ada Lovelace").is_err());
122+ // Words under four characters do not count, so "Ada" alone does not block a password.
123+ assert!(check_policy("my ada horse 1", email, "Ada").is_ok());
124+ }
125+}
crates/im-core/src/secret.rsadded+137 -0
@@ -0,0 +1,137 @@
1+//! The instance key and XChaCha20-Poly1305 sealing of secrets at rest.
2+//!
3+//! A sealed value is `v1:` followed by base64(nonce || ciphertext). The nonce is random for every
4+//! seal, so sealing the same plaintext twice gives different text. The key never goes in the
5+//! database; it lives in a 0600 file beside the data.
6+
7+use std::path::Path;
8+
9+use base64::prelude::{BASE64_STANDARD, Engine as _};
10+use chacha20poly1305::aead::Aead;
11+use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce};
12+
13+use crate::error::{Error, Result};
14+
15+const PREFIX: &str = "v1:";
16+const NONCE_LEN: usize = 24;
17+
18+/// Loads the 32-byte instance key at `path`, creating it if it is missing.
19+///
20+/// A new key is written with mode 0600 and `O_EXCL`, so two starts cannot both create it. An
21+/// existing key with any group or world permission is refused, because a leaked key defeats every
22+/// sealed secret.
23+pub fn load_or_create_key(path: &Path) -> Result<[u8; 32]> {
24+ if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
25+ std::fs::create_dir_all(parent)?;
26+ }
27+ match create_key(path) {
28+ Ok(key) => Ok(key),
29+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => read_key(path),
30+ Err(e) => Err(e.into()),
31+ }
32+}
33+
34+fn create_key(path: &Path) -> std::io::Result<[u8; 32]> {
35+ use std::io::Write;
36+
37+ use rand::TryRng;
38+
39+ let mut key = [0u8; 32];
40+ rand::rngs::SysRng
41+ .try_fill_bytes(&mut key)
42+ .map_err(std::io::Error::other)?;
43+
44+ let mut options = std::fs::OpenOptions::new();
45+ options.write(true).create_new(true);
46+ #[cfg(unix)]
47+ {
48+ use std::os::unix::fs::OpenOptionsExt;
49+ options.mode(0o600);
50+ }
51+ let mut file = options.open(path)?;
52+ let written = file.write_all(&key).and_then(|()| file.sync_all());
53+ if let Err(e) = written {
54+ // A truncated key would be rejected at the next start, so remove it now.
55+ drop(file);
56+ let _ = std::fs::remove_file(path);
57+ return Err(e);
58+ }
59+ Ok(key)
60+}
61+
62+fn read_key(path: &Path) -> Result<[u8; 32]> {
63+ #[cfg(unix)]
64+ {
65+ use std::os::unix::fs::PermissionsExt;
66+ let mode = std::fs::metadata(path)?.permissions().mode();
67+ if mode & 0o077 != 0 {
68+ return Err(Error::Crypto(format!(
69+ "instance key {} is group/world accessible (mode {:o}); expected 0600",
70+ path.display(),
71+ mode & 0o777
72+ )));
73+ }
74+ }
75+ let bytes = std::fs::read(path)?;
76+ <[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| {
77+ Error::Crypto(format!(
78+ "instance key {} has length {}, expected 32",
79+ path.display(),
80+ bytes.len()
81+ ))
82+ })
83+}
84+
85+/// Seals `plaintext` under `key`. Output: `"v1:" + base64(nonce || ciphertext)`.
86+///
87+/// Errors if the cipher rejects the input. The caller must then refuse to store the value, never
88+/// store it in clear.
89+pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result<String> {
90+ let mut nonce = [0u8; NONCE_LEN];
91+ rand::fill(&mut nonce);
92+ let cipher = XChaCha20Poly1305::new(key.into());
93+ let ciphertext = cipher
94+ .encrypt(&XNonce::from(nonce), plaintext)
95+ .map_err(|_| Error::Crypto("sealing failed".into()))?;
96+ let mut blob = Vec::with_capacity(NONCE_LEN + ciphertext.len());
97+ blob.extend_from_slice(&nonce);
98+ blob.extend_from_slice(&ciphertext);
99+ Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob)))
100+}
101+
102+/// Opens a value produced by [`seal`] under the same key.
103+///
104+/// Any failure (bad prefix, bad base64, short input, wrong key, tampering) is an error. The
105+/// messages are fixed strings, so nothing about the plaintext or the key can leak through them.
106+pub fn open(key: &[u8; 32], sealed: &str) -> Result<Vec<u8>> {
107+ let encoded = sealed
108+ .strip_prefix(PREFIX)
109+ .ok_or_else(|| Error::Crypto("sealed value has no v1 prefix".into()))?;
110+ let blob = BASE64_STANDARD
111+ .decode(encoded)
112+ .map_err(|_| Error::Crypto("sealed value is not valid base64".into()))?;
113+ if blob.len() < NONCE_LEN {
114+ return Err(Error::Crypto("sealed value is too short".into()));
115+ }
116+ let (nonce, ciphertext) = blob.split_at(NONCE_LEN);
117+ let nonce = <[u8; NONCE_LEN]>::try_from(nonce)
118+ .map_err(|_| Error::Crypto("sealed value has a bad nonce".into()))?;
119+ let cipher = XChaCha20Poly1305::new(key.into());
120+ cipher
121+ .decrypt(&XNonce::from(nonce), ciphertext)
122+ .map_err(|_| Error::Crypto("sealed value failed authentication".into()))
123+}
124+
125+#[cfg(test)]
126+mod tests {
127+ use super::*;
128+
129+ #[test]
130+ fn seal_then_open_returns_the_plaintext_and_rejects_another_key() {
131+ let key = [7u8; 32];
132+ let sealed = seal(&key, b"hello secret").unwrap();
133+ assert!(sealed.starts_with("v1:"));
134+ assert_eq!(open(&key, &sealed).unwrap(), b"hello secret");
135+ assert!(open(&[8u8; 32], &sealed).is_err());
136+ }
137+}
crates/im-core/src/store/migrate.rsadded+64 -0
@@ -0,0 +1,64 @@
1+//! Migration runner. Applied versions are recorded in `schema_migrations`.
2+//!
3+//! A migration file is never edited once applied; a change is a new numbered file. Each migration
4+//! runs in its own transaction together with its `schema_migrations` row, so a failure leaves
5+//! nothing half-applied.
6+
7+use turso::Connection;
8+
9+use crate::error::{Error, Result};
10+use crate::time::now_stamp;
11+
12+/// `(version, sql)` in ascending order, with no gaps. Add each new file here.
13+pub const MIGRATIONS: &[(u32, &str)] = &[(1, include_str!("../../migrations/0001_init.sql"))];
14+
15+fn migration_err(e: turso::Error) -> Error {
16+ Error::Migration(e.to_string())
17+}
18+
19+/// Applies every migration whose version is not yet recorded. Running it again is a no-op.
20+pub async fn migrate(conn: &Connection) -> Result<()> {
21+ conn.execute_batch(
22+ "CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)",
23+ )
24+ .await
25+ .map_err(migration_err)?;
26+
27+ let applied = applied_versions(conn).await?;
28+ for &(version, sql) in MIGRATIONS {
29+ let version = i64::from(version);
30+ if applied.contains(&version) {
31+ continue;
32+ }
33+ let tx = conn.unchecked_transaction().await.map_err(migration_err)?;
34+ tx.execute_batch(sql).await.map_err(migration_err)?;
35+ tx.execute(
36+ "INSERT INTO schema_migrations (version, applied_at) VALUES (?1, ?2)",
37+ (version, now_stamp()),
38+ )
39+ .await
40+ .map_err(migration_err)?;
41+ tx.commit().await.map_err(migration_err)?;
42+ tracing::info!(version, "applied database migration");
43+ }
44+ Ok(())
45+}
46+
47+async fn applied_versions(conn: &Connection) -> Result<Vec<i64>> {
48+ let mut rows = conn
49+ .query("SELECT version FROM schema_migrations ORDER BY version", ())
50+ .await
51+ .map_err(migration_err)?;
52+ let mut versions = Vec::new();
53+ while let Some(row) = rows.next().await.map_err(migration_err)? {
54+ match row.get_value(0).map_err(migration_err)? {
55+ turso::Value::Integer(v) => versions.push(v),
56+ _ => {
57+ return Err(Error::Migration(
58+ "schema_migrations.version is not an integer".into(),
59+ ));
60+ }
61+ }
62+ }
63+ Ok(versions)
64+}
crates/im-core/src/store/mod.rsadded+290 -0
@@ -0,0 +1,290 @@
1+//! Turso-backed storage. All persistent state lives in this database; the key file and photos sit
2+//! beside it in `data_dir`.
3+//!
4+//! Connections: one writer behind a tokio mutex, and a pool of read-only connections. Writes,
5+//! transactions and read-then-write sequences use the writer; a pure SELECT may use a reader. Every
6+//! connection gets WAL, `synchronous = FULL`, `foreign_keys = ON` and a busy timeout, and the values
7+//! in effect are logged at boot.
8+
9+pub mod migrate;
10+pub mod snapshot;
11+
12+use std::path::Path;
13+use std::sync::Arc;
14+use std::sync::atomic::{AtomicUsize, Ordering};
15+use std::time::Duration;
16+
17+use tokio::sync::{Mutex, MutexGuard};
18+use turso::transaction::Transaction;
19+use turso::{Builder, Connection, Database, IntoParams, Row, Value};
20+
21+use crate::error::{Error, Result};
22+use crate::time::now_stamp;
23+
24+/// How long a statement waits for a lock held by another connection before it fails.
25+const BUSY_TIMEOUT: Duration = Duration::from_millis(5000);
26+
27+/// Number of read-only connections in the pool.
28+const READER_COUNT: usize = 4;
29+
30+/// Handle to the database. Cheap to clone; every clone shares the same connections.
31+///
32+/// Rule for [`Store::read_conn`]: use it only for a function that is a pure SELECT and does not
33+/// need to see a write made in the same call. Anything in a transaction, any write, and any
34+/// read-then-write sequence goes through the writer.
35+#[derive(Clone)]
36+pub struct Store {
37+ inner: Arc<Inner>,
38+}
39+
40+struct Inner {
41+ /// Kept alive for as long as the connections are in use.
42+ _db: Database,
43+ /// The single writer.
44+ conn: Mutex<Connection>,
45+ /// Read-only connections, each with `PRAGMA query_only = 1`.
46+ readers: Vec<Mutex<Connection>>,
47+ /// Round-robin start index for `read_conn`.
48+ next_reader: AtomicUsize,
49+}
50+
51+impl Store {
52+ /// Opens (creating if needed) the database at `path`, applies the connection pragmas and runs
53+ /// any pending migrations. Readers are opened after migrations so their schema view is current.
54+ pub async fn open(path: &Path) -> Result<Store> {
55+ let path_str = path.to_str().ok_or_else(|| {
56+ Error::Config(format!("database path is not UTF-8: {}", path.display()))
57+ })?;
58+ let db = Builder::new_local(path_str).build().await.map_err(db_err)?;
59+ let conn = db.connect().map_err(db_err)?;
60+ apply_pragmas(&conn).await;
61+ migrate::migrate(&conn).await?;
62+
63+ let mut readers = Vec::with_capacity(READER_COUNT);
64+ for _ in 0..READER_COUNT {
65+ let reader = db.connect().map_err(db_err)?;
66+ apply_pragmas(&reader).await;
67+ apply_query_only(&reader).await?;
68+ readers.push(Mutex::new(reader));
69+ }
70+ Ok(Store {
71+ inner: Arc::new(Inner {
72+ _db: db,
73+ conn: Mutex::new(conn),
74+ readers,
75+ next_reader: AtomicUsize::new(0),
76+ }),
77+ })
78+ }
79+
80+ /// Returns a read-only pooled connection. It tries each reader without waiting, starting at the
81+ /// round-robin index, and falls back to waiting on the start reader when all are busy.
82+ pub async fn read_conn(&self) -> MutexGuard<'_, Connection> {
83+ let len = self.inner.readers.len();
84+ let start = self.inner.next_reader.fetch_add(1, Ordering::Relaxed) % len;
85+ for offset in 0..len {
86+ let idx = (start + offset) % len;
87+ if let Some(guard) = self.inner.readers.get(idx).and_then(|m| m.try_lock().ok()) {
88+ return guard;
89+ }
90+ }
91+ self.inner.readers[start].lock().await
92+ }
93+
94+ /// Number of user rows. Used to decide whether first-run setup is still open.
95+ pub async fn user_count(&self) -> Result<u64> {
96+ let conn = self.read_conn().await;
97+ let row = fetch_opt(&conn, "SELECT COUNT(*) FROM users", (), |row| {
98+ col_int(row, 0)
99+ })
100+ .await?
101+ .ok_or_else(missing_row)?;
102+ u64::try_from(row).map_err(|_| Error::Database("negative count".into()))
103+ }
104+
105+ /// The stored value of a runtime setting, or `None` when it has no override.
106+ pub async fn setting(&self, key: &str) -> Result<Option<String>> {
107+ let conn = self.read_conn().await;
108+ fetch_opt(
109+ &conn,
110+ "SELECT value FROM settings WHERE key = ?1",
111+ (key.to_string(),),
112+ |row| col_text(row, 0),
113+ )
114+ .await
115+ }
116+
117+ /// Stores (or replaces) a runtime setting. Writes through the writer connection.
118+ pub async fn set_setting(&self, key: &str, value: &str) -> Result<()> {
119+ let conn = self.inner.conn.lock().await;
120+ conn.execute(
121+ "INSERT INTO settings (key, value, updated_at) VALUES (?1, ?2, ?3) \
122+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
123+ (key.to_string(), value.to_string(), now_stamp()),
124+ )
125+ .await
126+ .map_err(db_err)?;
127+ Ok(())
128+ }
129+}
130+
131+/// Ends a transaction: commits when `outcome` is `Ok`, rolls back otherwise, and returns the
132+/// outcome. Every multi-statement write ends with this, so no path leaves a transaction open.
133+pub async fn finish<T>(tx: Transaction<'_>, outcome: Result<T>) -> Result<T> {
134+ match outcome {
135+ Ok(value) => {
136+ tx.commit().await.map_err(db_err)?;
137+ Ok(value)
138+ }
139+ Err(e) => {
140+ let _ = tx.rollback().await;
141+ Err(e)
142+ }
143+ }
144+}
145+
146+/// Converts a Turso error to the crate error.
147+pub(crate) fn db_err(e: turso::Error) -> Error {
148+ Error::Database(e.to_string())
149+}
150+
151+fn missing_row() -> Error {
152+ Error::Database("expected a row that is not there".into())
153+}
154+
155+/// Makes a connection refuse writes. Turso takes `1`, not `ON`. Failure is fatal: a reader that
156+/// could write would break the pool's rule.
157+async fn apply_query_only(conn: &Connection) -> Result<()> {
158+ let mut rows = conn
159+ .query("PRAGMA query_only = 1", ())
160+ .await
161+ .map_err(db_err)?;
162+ while rows.next().await.map_err(db_err)?.is_some() {}
163+ Ok(())
164+}
165+
166+/// Applies the connection pragmas. A pragma that is not supported is logged and skipped, never
167+/// fatal. The values actually in effect are logged afterwards.
168+async fn apply_pragmas(conn: &Connection) {
169+ for sql in [
170+ "PRAGMA journal_mode = WAL",
171+ "PRAGMA synchronous = FULL",
172+ "PRAGMA foreign_keys = ON",
173+ ] {
174+ let applied = async {
175+ let mut rows = conn.query(sql, ()).await?;
176+ while rows.next().await?.is_some() {}
177+ Ok::<(), turso::Error>(())
178+ }
179+ .await;
180+ if let Err(e) = applied {
181+ tracing::warn!(pragma = sql, error = %e, "database pragma not applied");
182+ }
183+ }
184+ if let Err(e) = conn.busy_timeout(BUSY_TIMEOUT) {
185+ tracing::warn!(error = %e, "busy_timeout not applied");
186+ }
187+ for name in ["journal_mode", "synchronous", "foreign_keys"] {
188+ match fetch_opt(conn, &format!("PRAGMA {name}"), (), |row| {
189+ col_to_string(row, 0)
190+ })
191+ .await
192+ {
193+ Ok(value) => tracing::info!(pragma = name, value = ?value, "database pragma in effect"),
194+ Err(e) => tracing::warn!(pragma = name, error = %e, "could not read database pragma"),
195+ }
196+ }
197+}
198+
199+/// Runs a query and maps every row. Returns an empty vector for no rows.
200+pub(crate) async fn fetch_all<T, P>(
201+ conn: &Connection,
202+ sql: &str,
203+ params: P,
204+ map: impl Fn(&Row) -> Result<T>,
205+) -> Result<Vec<T>>
206+where
207+ P: IntoParams,
208+{
209+ let mut rows = conn.query(sql, params).await.map_err(db_err)?;
210+ let mut out = Vec::new();
211+ while let Some(row) = rows.next().await.map_err(db_err)? {
212+ out.push(map(&row)?);
213+ }
214+ Ok(out)
215+}
216+
217+/// Runs a query and maps its first row, or returns `None` when there is none.
218+pub(crate) async fn fetch_opt<T, P>(
219+ conn: &Connection,
220+ sql: &str,
221+ params: P,
222+ map: impl Fn(&Row) -> Result<T>,
223+) -> Result<Option<T>>
224+where
225+ P: IntoParams,
226+{
227+ let mut rows = conn.query(sql, params).await.map_err(db_err)?;
228+ match rows.next().await.map_err(db_err)? {
229+ Some(row) => Ok(Some(map(&row)?)),
230+ None => Ok(None),
231+ }
232+}
233+
234+/// Reads a text column. Any other type is a database error.
235+pub(crate) fn col_text(row: &Row, i: usize) -> Result<String> {
236+ match row.get_value(i).map_err(db_err)? {
237+ Value::Text(s) => Ok(s),
238+ _ => Err(Error::Database(format!("column {i} is not text"))),
239+ }
240+}
241+
242+/// Reads an integer column. Any other type is a database error.
243+pub(crate) fn col_int(row: &Row, i: usize) -> Result<i64> {
244+ match row.get_value(i).map_err(db_err)? {
245+ Value::Integer(n) => Ok(n),
246+ _ => Err(Error::Database(format!("column {i} is not an integer"))),
247+ }
248+}
249+
250+/// Reads a column as text, accepting integers too. Used for PRAGMA results, which are text for
251+/// some pragmas and integers for others.
252+pub(crate) fn col_to_string(row: &Row, i: usize) -> Result<String> {
253+ match row.get_value(i).map_err(db_err)? {
254+ Value::Text(s) => Ok(s),
255+ Value::Integer(n) => Ok(n.to_string()),
256+ _ => Err(Error::Database(format!(
257+ "column {i} is not text or integer"
258+ ))),
259+ }
260+}
261+
262+#[cfg(test)]
263+mod tests {
264+ use super::*;
265+
266+ #[tokio::test]
267+ async fn open_twice_applies_migrations_once_and_keeps_data() {
268+ let dir = tempfile::tempdir().unwrap();
269+ let path = dir.path().join("im.db");
270+ {
271+ let store = Store::open(&path).await.unwrap();
272+ store.set_setting("invite_days", "7").await.unwrap();
273+ }
274+ let store = Store::open(&path).await.unwrap();
275+ assert_eq!(store.user_count().await.unwrap(), 0);
276+ assert_eq!(
277+ store.setting("invite_days").await.unwrap().as_deref(),
278+ Some("7")
279+ );
280+ assert_eq!(store.setting("missing").await.unwrap(), None);
281+
282+ let conn = store.read_conn().await;
283+ let applied = fetch_all(&conn, "SELECT version FROM schema_migrations", (), |row| {
284+ col_int(row, 0)
285+ })
286+ .await
287+ .unwrap();
288+ assert_eq!(applied, vec![1]);
289+ }
290+}
crates/im-core/src/store/snapshot.rsadded+116 -0
@@ -0,0 +1,116 @@
1+//! Consistent, self-contained copies of the database for backups.
2+//!
3+//! Method: `VACUUM INTO` on the writer connection, which holds its lock for the whole copy so no
4+//! other statement can interleave. The copy is then checkpointed so that the main file alone holds
5+//! every row, and fsynced. A live database file is never copied byte for byte.
6+
7+use std::path::Path;
8+
9+use turso::Builder;
10+
11+use super::{col_int, db_err, fetch_all};
12+use crate::error::{Error, Result};
13+use crate::store::Store;
14+
15+impl Store {
16+ /// Writes a consistent copy of the database to `dest`. `dest` must not exist yet.
17+ pub async fn snapshot_to(&self, dest: &Path) -> Result<()> {
18+ if std::fs::symlink_metadata(dest).is_ok() {
19+ return Err(Error::Conflict(format!(
20+ "snapshot target already exists: {}",
21+ dest.display()
22+ )));
23+ }
24+ let text = path_text(dest)?;
25+ let sql = format!("VACUUM INTO {}", sql_string_literal(text)?);
26+ {
27+ let conn = self.inner.conn.lock().await;
28+ conn.execute(&sql, ()).await.map_err(db_err)?;
29+ }
30+ make_self_contained(dest).await?;
31+ std::fs::File::open(dest)?.sync_all()?;
32+ Ok(())
33+ }
34+}
35+
36+fn path_text(path: &Path) -> Result<&str> {
37+ path.to_str()
38+ .ok_or_else(|| Error::Config(format!("snapshot path is not UTF-8: {}", path.display())))
39+}
40+
41+/// Quotes `text` as an SQL string literal, refusing NUL bytes.
42+fn sql_string_literal(text: &str) -> Result<String> {
43+ if text.contains('\0') {
44+ return Err(Error::Invalid("path contains NUL".into()));
45+ }
46+ Ok(format!("'{}'", text.replace('\'', "''")))
47+}
48+
49+/// `VACUUM INTO` writes a WAL-mode file, so its rows may still sit in a `-wal` sidecar. This
50+/// checkpoints the copy until every frame is in the main file, then removes sidecars that are
51+/// empty. A sidecar that still holds bytes is an error, so the main file alone is the database.
52+async fn make_self_contained(dest: &Path) -> Result<()> {
53+ let db = Builder::new_local(path_text(dest)?)
54+ .build()
55+ .await
56+ .map_err(db_err)?;
57+ let conn = db.connect().map_err(db_err)?;
58+ // Columns of the checkpoint result: busy flag, frames in the log, frames checkpointed.
59+ let status = fetch_all(&conn, "PRAGMA wal_checkpoint(TRUNCATE)", (), |row| {
60+ Ok((col_int(row, 0)?, col_int(row, 1)?, col_int(row, 2)?))
61+ })
62+ .await?;
63+ drop(conn);
64+ drop(db);
65+ match status.as_slice() {
66+ [(0, log, done)] if log == done => {}
67+ other => {
68+ return Err(Error::Database(format!(
69+ "checkpoint of the snapshot did not complete: {other:?}"
70+ )));
71+ }
72+ }
73+ for suffix in ["-wal", "-shm"] {
74+ let mut sidecar = dest.as_os_str().to_owned();
75+ sidecar.push(suffix);
76+ let sidecar = Path::new(&sidecar);
77+ match std::fs::metadata(sidecar) {
78+ Err(_) => {}
79+ Ok(meta) if meta.len() == 0 => std::fs::remove_file(sidecar)?,
80+ Ok(meta) => {
81+ return Err(Error::Database(format!(
82+ "snapshot still has {} bytes in {}",
83+ meta.len(),
84+ sidecar.display()
85+ )));
86+ }
87+ }
88+ }
89+ Ok(())
90+}
91+
92+#[cfg(test)]
93+mod tests {
94+ use super::*;
95+
96+ #[tokio::test]
97+ async fn snapshot_opens_with_its_data_and_refuses_an_existing_target() {
98+ let dir = tempfile::tempdir().unwrap();
99+ let store = Store::open(&dir.path().join("im.db")).await.unwrap();
100+ store
101+ .set_setting("base_url", "https://id.example")
102+ .await
103+ .unwrap();
104+
105+ let snap = dir.path().join("snap").join("im.db");
106+ std::fs::create_dir_all(snap.parent().unwrap()).unwrap();
107+ store.snapshot_to(&snap).await.unwrap();
108+ assert!(store.snapshot_to(&snap).await.is_err());
109+
110+ let copy = Store::open(&snap).await.unwrap();
111+ assert_eq!(
112+ copy.setting("base_url").await.unwrap().as_deref(),
113+ Some("https://id.example")
114+ );
115+ }
116+}
crates/im-core/src/time.rsadded+54 -0
@@ -0,0 +1,54 @@
1+//! UTC timestamps as stored in the database.
2+//!
3+//! The format is RFC 3339 with 9 fractional digits and a `Z` suffix. It has a fixed width, so
4+//! comparing two stamps as text gives the same order as comparing the times.
5+
6+use std::time::Duration;
7+
8+use time::{
9+ OffsetDateTime, SignedDuration, format_description::FormatItem, macros::format_description,
10+};
11+
12+const FORMAT: &[FormatItem<'static>] =
13+ format_description!("[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:9]Z");
14+
15+fn format_stamp(at: OffsetDateTime) -> String {
16+ // The format description only uses fields that always format, so this cannot fail.
17+ at.format(FORMAT).unwrap_or_default()
18+}
19+
20+/// Converts a `std` duration to the signed form `time` uses, saturating on overflow.
21+fn signed(d: Duration) -> SignedDuration {
22+ SignedDuration::try_from(d).unwrap_or(SignedDuration::MAX)
23+}
24+
25+/// The current time as a stamp.
26+pub fn now_stamp() -> String {
27+ format_stamp(OffsetDateTime::now_utc())
28+}
29+
30+/// The stamp for `now + after`. Saturates at the maximum representable time instead of panicking.
31+pub fn stamp_after(after: Duration) -> String {
32+ format_stamp(OffsetDateTime::now_utc().saturating_add(signed(after)))
33+}
34+
35+/// The stamp for `now - before`. Saturates at the minimum representable time instead of panicking.
36+pub fn stamp_before(before: Duration) -> String {
37+ format_stamp(OffsetDateTime::now_utc().saturating_sub(signed(before)))
38+}
39+
40+#[cfg(test)]
41+mod tests {
42+ use super::*;
43+
44+ #[test]
45+ fn stamps_have_fixed_width_and_sort_in_time_order() {
46+ let now = now_stamp();
47+ let later = stamp_after(Duration::from_secs(3600));
48+ let much_later = stamp_after(Duration::from_secs(7200));
49+ assert_eq!(now.len(), 30, "bad stamp: {now}");
50+ assert!(now.ends_with('Z'));
51+ assert!(now < later && later < much_later);
52+ assert!(stamp_before(Duration::from_secs(3600)) < now);
53+ }
54+}
crates/im-core/src/token.rsadded+62 -0
@@ -0,0 +1,62 @@
1+//! Random tokens, codes, and the hashing and comparison rules that go with them.
2+//!
3+//! A token is 32 random bytes in base64url. Only its SHA-256 (hex) is stored, so a database leak
4+//! does not reveal live tokens. Codes typed by people use a readable alphabet with no look-alike
5+//! characters.
6+
7+use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
8+use sha2::{Digest, Sha256};
9+use subtle::ConstantTimeEq;
10+
11+/// Alphabet for codes typed by people: lowercase letters and the digits 2 to 9, without `l`, `o`,
12+/// `0` and `1`, which are easy to confuse. It has exactly 32 symbols, so the low five bits of a
13+/// random byte pick one uniformly, with no modulo bias.
14+pub const READABLE_ALPHABET: &[u8; 32] = b"abcdefghijkmnpqrstuvwxyz23456789";
15+
16+/// A fresh token: 32 random bytes, base64url without padding (43 characters).
17+pub fn generate_token() -> String {
18+ BASE64_URL_SAFE_NO_PAD.encode(random_32())
19+}
20+
21+/// `len` random characters from [`READABLE_ALPHABET`].
22+pub fn random_readable(len: usize) -> String {
23+ let mut buf = vec![0u8; len];
24+ rand::fill(buf.as_mut_slice());
25+ buf.iter()
26+ .map(|b| char::from(READABLE_ALPHABET[usize::from(b & 31)]))
27+ .collect()
28+}
29+
30+/// The hex SHA-256 of `token`. This is what the database stores in place of the token.
31+pub fn hash_token(token: &str) -> String {
32+ hex::encode(Sha256::digest(token.as_bytes()))
33+}
34+
35+/// Compares two byte strings in time that does not depend on where they first differ.
36+///
37+/// Different lengths return false at once; the length of a secret is not itself secret here,
38+/// because every token of a kind has the same length.
39+pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
40+ a.ct_eq(b).into()
41+}
42+
43+/// 32 random bytes from the thread RNG, which is seeded from the operating system. It cannot fail,
44+/// so callers need no error path.
45+pub(crate) fn random_32() -> [u8; 32] {
46+ let mut buf = [0u8; 32];
47+ rand::fill(&mut buf);
48+ buf
49+}
50+
51+#[cfg(test)]
52+mod tests {
53+ use super::*;
54+
55+ #[test]
56+ fn constant_time_eq_matches_plain_equality() {
57+ assert!(constant_time_eq(b"same", b"same"));
58+ assert!(!constant_time_eq(b"same", b"diff"));
59+ assert!(!constant_time_eq(b"short", b"longer"));
60+ assert!(constant_time_eq(b"", b""));
61+ }
62+}
crates/im-web/Cargo.tomladded+13 -0
@@ -0,0 +1,13 @@
1+[package]
2+name = "im-web"
3+version.workspace = true
4+edition.workspace = true
5+license.workspace = true
6+publish = false
7+
8+[lints]
9+workspace = true
10+
11+[[bin]]
12+name = "im"
13+path = "src/main.rs"
crates/im-web/src/main.rsadded+5 -0
@@ -0,0 +1,5 @@
1+//! The `im` binary. Placeholder until the server, CLI and UI land; it only prints its name.
2+
3+fn main() {
4+ println!("im");
5+}
docs/architecture.mdadded+295 -0
@@ -0,0 +1,295 @@
1+# im architecture
2+
3+`im` is the family's account service: an OpenID Connect provider, the people directory, and the service
4+registry. It is the root of the family: `in` and `iz` depend on it, it depends on nothing. Read
5+`docs/contracts.md` (the cross-app API) and `docs/conventions.md` (how code is written) first.
6+
7+Status: design for the rebuild. The previous implementation (`~/Documents/Code/Rust/old_im`) is a feature
8+reference only; its known defects are listed in section 11 so they are not carried over.
9+
10+---
11+
12+## 1. Goals
13+
14+- **Boring and safe.** im guards every other app. It changes rarely and carefully.
15+- **Feature parity** with old im: password + TOTP sign-in, invites, password reset, two-sided email change,
16+ profile photo, preferences, sessions, connected apps, admin panel (users, services/clients, SMTP, policy,
17+ message, audit log, health), backups, CLI.
18+- **Better than old im:** CSRF on every form, recovery codes, admin 2FA reset, key rotation, refresh-token reuse
19+ detection, back-channel logout, client-credentials machine tokens, no per-request introspection by apps,
20+ security headers and a strict CSP, every page translated.
21+
22+Not goals now (listed in `docs/backlog.md`): passkeys, social sign-in, SCIM, multiple organisations, consent
23+screens (every family client is first-party and trusted).
24+
25+---
26+
27+## 2. Crates and modules
28+
29+```
30+im/
31+ Cargo.toml config/im.example.toml deploy/im.service style/*.scss docs/
32+ crates/
33+ im-core/ domain, store, migrations, config, secret, password, token, time, totp, jwt, authz, audit types, i18n-free
34+ im-web/ binary `im`: pages, OIDC endpoints, machine APIs, live, mail worker, back-channel worker, CLI
35+```
36+
37+**im-core**
38+- `error.rs`, `time.rs`, `config.rs` (+ `settings.rs` for UI overrides), `secret.rs` (instance key, seal/open)
39+- `password.rs` (argon2id, policy check), `token.rs` (random tokens, hashing, constant-time compare, readable codes)
40+- `totp.rs` (RFC 6238, SHA-1, 6 digits, 30 s, ±1 step, replay guard by last step)
41+- `jwt.rs` (EdDSA sign/verify, header/claims structs; ed25519-dalek; no generic JWT library needed)
42+- `names.rs` (email normalisation: trim, lowercase domain and local part, basic shape check)
43+- `authz.rs` (actor kinds and actions, section 6)
44+- `model.rs` (User, Session, Client, Service, Invite, ...)
45+- `store/` (`mod.rs` + one file per area: `users.rs`, `sessions.rs`, `oidc.rs`, `clients.rs`, `invites.rs`,
46+ `links.rs` (reset/email-change), `mail.rs` (outbox), `backchannel.rs`, `directory.rs` (change feed),
47+ `audit.rs`, `settings.rs`, `snapshot.rs`, `migrate.rs`)
48+
49+**im-web**
50+- `main.rs`, `boot.rs`, `state.rs`, `admin_cli.rs`
51+- `auth.rs` (session cookie, `current_user`, `require_user`, `require_admin`, `require_csrf`, pre-CSRF, `safe_next`,
52+ pending-2FA sealed cookie), `throttle.rs`, `client_ip.rs`
53+- `oidc/` (`discovery.rs`, `authorize.rs`, `token.rs`, `userinfo.rs`, `logout.rs`, `revoke.rs`, `introspect.rs`,
54+ `jwks.rs`, `keys.rs` (rotation worker))
55+- `api/` machine routes (`directory.rs`, `family.rs`, `photo.rs`, `machine_auth.rs` = verify our own
56+ client-credentials JWTs)
57+- `pages/` (one file per page or area)
58+- `views/` (`shell`, components), `i18n/` (key enums per area)
59+- `live.rs`, `mail/` (SMTP transport via `lettre`, outbox worker, templates), `backchannel.rs` (outbox worker),
60+ `health.rs` (service probe worker), `audit.rs` (writer), `assets.rs`
61+- `assets/nav.js`, `assets/pages.js` (small page behaviours: dropdown search, copy button, QR toggle, photo
62+ upload progress), `assets/offline.html`, `assets/sw.js`
63+
64+---
65+
66+## 3. Data model
67+
68+Conventions from `docs/conventions.md` section 4. Every table below is in `0001_init.sql` unless noted.
69+
70+**users**
71+- `id` TEXT PK (ULID; this is the OIDC `sub`, never reused)
72+- `email` TEXT NOT NULL, `email_folded` TEXT NOT NULL UNIQUE (normalised)
73+- `name` TEXT NOT NULL (1–100 chars)
74+- `password_hash` TEXT NOT NULL (argon2id PHC)
75+- `is_admin` INTEGER NOT NULL DEFAULT 0, `disabled_at` TEXT NULL
76+- `totp_secret_sealed` TEXT NULL, `totp_enabled_at` TEXT NULL, `totp_last_step` INTEGER NULL
77+- `locale` TEXT NOT NULL DEFAULT 'en' CHECK (locale IN ('en','tr'))
78+- `zoneinfo` TEXT NOT NULL DEFAULT 'Europe/Istanbul' (IANA name, validated against the `jiff` tz database)
79+- `theme` TEXT NOT NULL DEFAULT 'system' CHECK IN ('system','light','dark')
80+- `photo_mime` TEXT NULL, `picture_version` INTEGER NOT NULL DEFAULT 0
81+- `created_at`, `updated_at` TEXT NOT NULL
82+
83+**recovery_codes**: `user_id` FK CASCADE, `code_hash` TEXT, `used_at` TEXT NULL; PK (user_id, code_hash).
84+Ten codes, `xxxx-xxxx` from the readable alphabet, shown once, regenerated as a set.
85+
86+**sessions** (browser sessions at im)
87+- `id` TEXT PK (ULID; this is the OIDC `sid`), `user_id` FK CASCADE, `token_hash` TEXT UNIQUE, `csrf_token` TEXT
88+- `created_at`, `expires_at`, `last_seen_at` TEXT; `ip` TEXT, `user_agent` TEXT
89+- `auth_time` TEXT, `amr` TEXT ('pwd' or 'pwd otp' or 'pwd rc')
90+- Ended sessions are deleted (their back-channel jobs are queued first).
91+
92+**clients** (OIDC clients; one per family app, plus any extra)
93+- `id` TEXT PK (the `client_id`, ULID), `name` TEXT, `secret_hash` TEXT, `secret_rotated_at` TEXT
94+- `redirect_uris` TEXT (JSON array), `post_logout_redirect_uris` TEXT (JSON array), `backchannel_logout_uri` TEXT NULL
95+- `allowed_scopes` TEXT (space-separated; `openid profile email` plus machine scopes)
96+- `service_key` TEXT NULL UNIQUE (family key such as `in`; NULL for a client that is not a family service)
97+- `created_at`, `disabled_at` NULL
98+
99+**services** (the switcher list)
100+- `key` TEXT PK (`^[a-z][a-z0-9-]{0,31}$`), `name` TEXT, `url` TEXT (origin), `position` INTEGER,
101+ `client_id` TEXT NULL REFERENCES clients ON DELETE SET NULL
102+- `healthy` INTEGER NULL, `checked_at` TEXT NULL, `check_ms` INTEGER NULL, `check_error` TEXT NULL
103+- im's own row (`key = 'im'`) is maintained at boot from `base_url` and cannot be removed.
104+
105+**auth_codes**: `code_hash` PK, `client_id`, `user_id`, `session_id`, `redirect_uri`, `scope`, `nonce`,
106+`code_challenge`, `expires_at`, `used_at` NULL. A second use of a used code revokes the refresh tokens issued
107+from it (`refresh_tokens.code_hash`).
108+
109+**refresh_tokens**: `id` PK, `token_hash` UNIQUE, `family_id` (first token of the chain), `client_id`,
110+`user_id`, `session_id` FK sessions CASCADE, `code_hash`, `scope`, `created_at`, `expires_at` (30 days),
111+`used_at` NULL, `revoked_at` NULL. Rotation on every use; presenting a used token revokes the whole family.
112+
113+**client_sessions**: (`session_id`, `client_id`) PK, `first_at`, `last_at`. Which apps a browser session has
114+signed in to: drives back-channel logout and the "connected apps" list.
115+
116+**signing_keys**: `kid` PK (first 16 hex of SHA-256 of the public key), `private_sealed`, `public_raw` BLOB,
117+`created_at`, `activates_at`, `retires_at` NULL. Exactly one key is "current": the newest with
118+`activates_at <= now` and no `retires_at`.
119+
120+**invites**: `token_hash` PK, `email_folded`, `is_admin`, `invited_by` NULL FK SET NULL, `created_at`,
121+`expires_at`, `accepted_at` NULL. Creating a new invite for an address deletes its older pending invites.
122+
123+**account_links** (password reset and email change)
124+- `token_hash` PK, `kind` CHECK IN ('reset','email_old','email_new'), `user_id` FK CASCADE, `pair_id` NULL
125+ (both email-change halves share it), `new_email` NULL, `created_at`, `expires_at`, `used_at` NULL.
126+
127+**mail_outbox**: `id` PK, `kind` (invite|reset|email_old|email_new|email_done|notice|test|security),
128+`to_addr`, `subject`, `body_text`, `state` CHECK IN ('pending','sent','failed','abandoned'), `attempts`,
129+`next_attempt_at`, `last_error`, `created_at`, `sent_at`. Links in bodies are never logged.
130+
131+**backchannel_outbox**: `id` PK, `client_id`, `sid` NULL, `sub`, `reason`, `state`, `attempts`,
132+`next_attempt_at`, `last_error`, `created_at`, `done_at`.
133+
134+**directory_changes**: `seq` INTEGER PK AUTOINCREMENT, `sub`, `kind` CHECK IN ('member','deleted'), `at`.
135+The cursor of the directory stream is `seq`. Rows older than 30 days are pruned; a cursor older than the oldest
136+row gets `resync`.
137+
138+**audit_log**: per conventions section 10.
139+
140+**settings**: `key` PK, `value`, `updated_at` (UI overrides and sealed SMTP password).
141+
142+Files beside the DB in `data_dir`: `im.key`, `photos/<user_id>` (0600, written by temp file + fsync + rename).
143+
144+---
145+
146+## 4. Routes
147+
148+### 4.1 Browser pages
149+
150+| Path | Who | What |
151+|---|---|---|
152+| `GET/POST /setup` | only while no user exists | create the first admin |
153+| `GET/POST /login` | anonymous | email + password; then `/login/2fa` when TOTP is on |
154+| `GET/POST /login/2fa` | pending cookie | TOTP code or recovery code |
155+| `POST /logout` | user | end this session (back-channel to its apps) |
156+| `GET/POST /logout` (OIDC end-session) | any | section 4.2 |
157+| `GET/POST /forgot`, `GET/POST /reset/{token}` | anonymous | password reset by mail |
158+| `GET/POST /invite/{token}` | anonymous | accept an invite: name + password |
159+| `GET/POST /email/{token}` | anonymous | confirm one side of an email change; GET never mutates |
160+| `GET /` | user | account home: profile card, connected apps, switcher |
161+| `GET /account/profile` + POSTs | user | name, photo upload/remove, email change request |
162+| `GET /account/security` + POSTs | user | password change, TOTP enroll/disable, recovery codes |
163+| `GET /account/sessions` + POST revoke | user | own browser sessions; revoke one or all others |
164+| `GET /account/apps` + POST revoke | user | apps signed in to; sign out of one app |
165+| `GET /account/preferences` + POST | user | language, time zone, theme |
166+| `GET /people/{id}` | user | public profile card |
167+| `GET /admin/users` (+ `/{id}`) and POSTs | admin | list, invite, disable/enable, delete, revoke sessions, rescue email, reset 2FA, promote/demote (not self, not the last admin) |
168+| `GET /admin/services` and POSTs | admin | services + their clients: add (key, name, origin → client with derived URIs, secret shown once), rename, reorder, rotate secret, edit scopes, remove |
169+| `GET /admin/clients` and POSTs | admin | non-family OIDC clients |
170+| `GET /admin/mail` and POSTs | admin | SMTP sender (password write-only, sealed), check connection, send test, outbox with retry |
171+| `GET /admin/message` + POST | admin | notice mail to everyone or one person (queued) |
172+| `GET /admin/settings` + POST | admin | policy (section 7), base URL, trusted proxies; UI > file > default |
173+| `GET /admin/keys` + POST rotate | admin | signing keys and their state |
174+| `GET /admin/audit` | admin | filters (action, actor, target, date range), keyset paging |
175+| `GET /admin/health` | admin | services health, outboxes, disk, DB size, last backup |
176+| `GET /photo/{id}` | user | photo bytes or initials SVG |
177+| `GET /-/alive`, `GET /.../events` | per page | live streams |
178+| `GET /healthz`, `GET /assets/*` | anyone | |
179+
180+### 4.2 OIDC and machine endpoints
181+
182+As in `docs/contracts.md` sections 2–4: `/.well-known/openid-configuration`, `/jwks.json`, `/authorize`,
183+`/token` (authorization_code, refresh_token, client_credentials), `/userinfo`, `/logout` (RP-initiated),
184+`/revoke` (RFC 7009), `/introspect` (RFC 7662; for debugging and third-party clients; family apps do not use
185+it), `/api/v1/directory`, `/api/v1/directory/stream`, `/api/v1/people/{sub}/photo`, `/api/v1/family`.
186+
187+`/authorize` without a session redirects to `/login?next=<the authorize URL>`. After sign-in the user returns
188+there and is redirected to the client. Invalid `client_id` or `redirect_uri` renders an error page (never
189+redirects). Other errors redirect to the client with `error=` and `state`.
190+
191+---
192+
193+## 5. Sign-in, sessions, 2FA
194+
195+- Login order (forge): pre-CSRF → throttle (account key and IP key) → lookup (unknown → dummy verify) → password
196+ → disabled check (revealed only after a correct password) → 2FA step or session.
197+- Pending 2FA: sealed cookie `__Host-im_pending` (`user_id|expires|next|amr`), SameSite=Strict, 5 minutes.
198+- Second factor: 6 digits → TOTP with replay guard; `xxxx-xxxx` → recovery code (consumed). Throttled per user.
199+- Session: 30 days idle-extended up to `session_max_days` (policy), cookie `__Host-im_session`. At most
200+ `max_sessions` per user: the oldest is ended (with back-channel) when exceeded.
201+- Password change ends every other session; reset ends all. Disable and delete end all and queue
202+ back-channel logout by `sub`.
203+- TOTP enroll: secret generated and held sealed in a pending state until a valid code confirms it; enrolling
204+ again while enabled requires the current code (old defect: re-visiting enroll reset it). Disabling TOTP
205+ requires the password and a code. Admin "reset 2FA" clears TOTP and recovery codes and is audited and mailed
206+ to the user.
207+- Password policy: 10–256 chars, not containing the email local part or name words of ≥4 chars, not equal to
208+ the current one.
209+
210+---
211+
212+## 6. Authorization
213+
214+`authz::authorize(actor, action) -> Result<(), Denied>` where `actor` is `Anonymous`, `User { id, is_admin }`
215+or `Client { id, scopes, service_key }`, and `action` is an enum (`ViewOwnAccount`, `EditOwnAccount`,
216+`ViewPerson`, `Administer`, `ReadDirectory`, `ReadFamily`, ...). Admin pages answer 404 to non-admins.
217+Rules that are not role checks (last admin cannot be demoted or disabled, an admin cannot disable themself) live
218+in the store as single conditional statements so they cannot race.
219+
220+---
221+
222+## 7. Policy settings (admin, UI > file > default)
223+
224+| Key | Default | Kind |
225+|---|---|---|
226+| `registration` | `invite` (`invite` only; open sign-up is in the backlog) | ReadOnly |
227+| `invite_days` | 7 | Live |
228+| `reset_minutes` | 60 | Live |
229+| `email_change_hours` | 24 | Live |
230+| `session_max_days` | 30 | Live |
231+| `max_sessions` | 10 | Live |
232+| `require_2fa_for_admins` | true | Live (an admin without TOTP is sent to enroll after sign-in) |
233+| `base_url`, `trusted_proxies` | from file | Restart |
234+| `listen`, `database`, `data_dir` | from file | ReadOnly |
235+
236+---
237+
238+## 8. Workers (spawned at boot, stop with the stop flag)
239+
240+- **mail**: sends `mail_outbox` rows (5 attempts, backoff 1/5/15/60 min, then `abandoned`); SMTP via `lettre`,
241+ 465 implicit TLS, otherwise STARTTLS required. With no sender configured, rows wait without spending an
242+ attempt. Dev mode (`[mail] log_only = true`) writes mails to `data_dir/mail-log/` instead.
243+- **backchannel**: delivers `backchannel_outbox` rows per contracts.md 2.5.
244+- **keys**: daily; creates the next key 24 h before rotation, retires old keys after 7 days.
245+- **health**: probes services every 60 s (2 s timeout), updates `services`, bumps the admin health topic.
246+- **sweeper**: hourly; deletes expired codes, links, sessions (queuing back-channel), old directory changes,
247+ sent mail older than 30 days.
248+- **backup** (optional, `[backup] dir`): `VACUUM INTO` snapshot + photos + manifest on an interval, keeps N,
249+ pings a dead-man URL (`/start`, success, `/fail`).
250+
251+---
252+
253+## 9. Live
254+
255+Topics: `Account(user_id)` (sessions, apps, profile, security changes; drives `/-/alive` `account` events, so a
256+revoked session leaves at once), `AdminUsers`, `AdminServices`, `AdminMail`, `AdminAudit`, `AdminHealth`,
257+`Person(user_id)`. The directory stream for machines is separate (contracts.md 3.2) and reads
258+`directory_changes`.
259+
260+---
261+
262+## 10. CLI
263+
264+`im admin create-admin <email>` (prompts for name and password; `IM_PASSWORD` for scripts),
265+`im admin reset-2fa <email>`, `im admin disable <email>`, `im admin create-client <key> <name> <origin>`
266+(prints the secret once), `im admin rotate-key`, `im admin backup --out DIR`, `im admin backup-verify SET`,
267+`im admin restore --from SET --data-dir NEW`, `im admin audit-purge --older-than-days N`.
268+The CLI opens the database directly; it refuses to run while the server holds it unless `--online` is given,
269+in which case it talks to the running server over a unix socket in `data_dir/run/` with a per-boot token
270+(forge `admin_client.rs` pattern).
271+
272+---
273+
274+## 11. Old defects not to repeat
275+
276+From the inventory of old im: no CSRF tokens; signing key never rotated; refresh reuse not detected; access
277+token scope hard-coded; email-change links leaked in a redirect query when mail failed; any client could claim
278+unowned service rows; `/directory`, `/photo` and `/family` open to any client; live profile frames broadcast to
279+everyone; revisiting enroll reset a confirmed TOTP; no way to disable TOTP or reset it for a locked-out user;
280+login pages English-only; deleted users left reset links, email changes and photos behind; SMTP password left
281+behind when the sender was cleared; cookie lifetime and DB lifetime disagreed; pack archives held the plaintext
282+key; Google Fonts loaded from a third party; generated CSS committed.
283+
284+---
285+
286+## 12. Build order
287+
288+1. Scaffold: workspace, core basics (error, time, secret, token, password, config, store + migrate + 0001),
289+ boot, `/healthz`, assets pipeline, shell, `nav.js`, i18n skeleton, security headers, 404 page.
290+2. Accounts: setup, login, 2FA, sessions, logout, throttle, account pages, preferences, photo.
291+3. Mail outbox + SMTP; invites, password reset, email change.
292+4. OIDC: keys, discovery, JWKS, authorize, token (all grants), userinfo, logout, revoke, introspect, back-channel.
293+5. Machine APIs: directory + stream, photo, family.
294+6. Admin: users, services/clients, mail, message, settings, keys, audit, health.
295+7. Live topics, backups, CLI, deploy unit, README.
docs/contracts.mdadded+241 -0
@@ -0,0 +1,241 @@
1+# Family contracts, v1
2+
3+Status: normative. This file is copied byte for byte into `im/docs/contracts.md`, `in/docs/contracts.md` and
4+`iz/docs/contracts.md`. A change is made in all three repos in the same sitting, and the version line below is
5+bumped. The apps share no code. They share only the HTTP contracts written here.
6+
7+Contract version: **1**
8+
9+---
10+
11+## 1. The family
12+
13+| Key | App | Role | Default listen |
14+|---|---|---|---|
15+| `im` | Account | OpenID Connect provider, people directory, service registry. Depends on nothing. | `127.0.0.1:7650` |
16+| `in` | Files | Personal drive. Blob store for the other apps. Depends on `im`. | `127.0.0.1:7655` |
17+| `iz` | Board | Task board. Depends on `im`, optionally on `in`. | `127.0.0.1:7654` |
18+
19+Production origins are `https://<key>.<domain>` behind a TLS-terminating reverse proxy (Ferron). Apps bind
20+`127.0.0.1` only.
21+
22+### 1.1 Design rules
23+
24+1. **No app is down because another is down.** A signed-in user keeps working in `in` and `iz` while `im` is
25+ unreachable. Only new sign-ins need `im`. Nothing calls `im` on the request path of an ordinary page.
26+2. **Standards first.** Where a standard exists (OIDC Core, OIDC Discovery, OIDC RP-Initiated Logout, OIDC
27+ Back-Channel Logout, OAuth 2.0 client credentials, RFC 7009 revocation, RFC 7662 introspection), it is used
28+ as written. Extensions are named and listed here.
29+3. **Machine calls carry a short-lived JWT** issued by `im` through the client credentials grant, with an
30+ audience and scopes. Static shared bearer keys are not used.
31+4. **Every machine API is versioned** under `/api/v1/`. A consumer accepts unknown JSON fields. A provider keeps
32+ v1 working for at least one release after v2 ships.
33+5. **Errors are JSON with a real HTTP status** (section 7).
34+
35+---
36+
37+## 2. Identity (OIDC)
38+
39+`im` is the issuer. Its issuer URL is its public origin with no trailing slash, for example
40+`https://im.example.com`.
41+
42+### 2.1 Discovery
43+
44+`GET /.well-known/openid-configuration` returns standard metadata, including:
45+
46+- `issuer`, `authorization_endpoint` (`/authorize`), `token_endpoint` (`/token`), `userinfo_endpoint`
47+ (`/userinfo`), `jwks_uri` (`/jwks.json`), `end_session_endpoint` (`/logout`), `revocation_endpoint`
48+ (`/revoke`), `introspection_endpoint` (`/introspect`)
49+- `response_types_supported: ["code"]`, `grant_types_supported: ["authorization_code", "refresh_token", "client_credentials"]`
50+- `code_challenge_methods_supported: ["S256"]`, `id_token_signing_alg_values_supported: ["EdDSA"]`
51+- `token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"]`
52+- `backchannel_logout_supported: true`, `backchannel_logout_session_supported: true`
53+- `scopes_supported: ["openid", "profile", "email", "directory.read", "files.service"]`
54+
55+Clients fetch discovery once at boot and cache it. They may hard-code the paths above as a fallback.
56+
57+### 2.2 Keys
58+
59+- Signing algorithm: **EdDSA (Ed25519)**. `jwks.json` publishes every key that is active or retired within
60+ the last 7 days, as `{"kty":"OKP","crv":"Ed25519","x":...,"kid":...,"use":"sig","alg":"EdDSA"}`.
61+- `im` rotates the signing key every 90 days and on admin demand. A new key is published 24 hours before it
62+ signs anything.
63+- Clients cache the JWKS for 1 hour, and refetch at most once a minute when a token names an unknown `kid`.
64+
65+### 2.3 Sign-in (authorization code + PKCE)
66+
67+1. App redirects the browser to `/authorize` with `response_type=code`, `client_id`, `redirect_uri` (exact match
68+ with a registered URI), `scope` containing `openid` (and `profile email`), `state` (≥128 bits),
69+ `nonce` (≥128 bits), `code_challenge`, `code_challenge_method=S256`. PKCE is mandatory.
70+2. `im` signs the user in (password, then TOTP or a recovery code if enrolled) and redirects back with
71+ `code` and `state`. Codes live 60 seconds and are single use. A reused code revokes every token issued from it.
72+3. App posts to `/token` (`grant_type=authorization_code`, `code`, `redirect_uri`, `code_verifier`), client auth
73+ by `client_secret_basic` or `client_secret_post`. Response: `access_token` (JWT, 10 min), `id_token`,
74+ `refresh_token`, `token_type: "Bearer"`, `expires_in`.
75+4. App validates the `id_token`: signature against JWKS, `iss` exact, `aud` equals its `client_id`, `exp` in the
76+ future, `iat` not more than 5 minutes in the future, `nonce` equal to the one it sent.
77+
78+**ID token claims:** `iss`, `sub` (the user's ULID, stable forever), `aud`, `exp`, `iat`, `auth_time`, `nonce`,
79+`sid` (the `im` browser session id), `email`, `email_verified` (always true: `im` only stores confirmed
80+addresses), `name`, and the `im` extensions `admin` (bool), `locale` (`en`|`tr`), `zoneinfo` (IANA name, for
81+example `Europe/Istanbul`), `picture_version` (integer, bumps when the photo changes).
82+
83+### 2.4 App sessions
84+
85+After step 4 the app creates **its own local session** (its own table, its own `__Host-` cookie, its own CSRF
86+token), keyed by `sub`, and stores `sid` beside it. The app does not call `im` again for this session.
87+
88+- Local session lifetime: at most 12 hours of absolute age. After that the app sends the browser through
89+ `/authorize` again. While the `im` session is alive this is an invisible redirect.
90+- The app may keep the `refresh_token` only if it needs to call `/userinfo` later. Apps in this family do not.
91+ They discard it.
92+
93+### 2.5 Sign-out and revocation
94+
95+- **App-initiated sign-out:** the app deletes its local session, then redirects to
96+ `/logout?id_token_hint=...&post_logout_redirect_uri=<registered>&state=...` (OIDC RP-Initiated Logout). `im`
97+ ends the `im` session and every app session tied to it (back-channel, below).
98+- **Back-Channel Logout** (OIDC Back-Channel Logout 1.0): each client registers a `backchannel_logout_uri`
99+ (`<origin>/auth/backchannel-logout`). When an `im` session ends (sign-out, admin revoke, password change or
100+ reset, user disabled or deleted, session expired by policy), `im` POSTs `logout_token=<JWT>` (form-encoded)
101+ to every client that was used in that session. The token carries `iss`, `aud`, `iat`, `exp` (2 min), `jti`,
102+ `events: {"http://schemas.openid.net/event/backchannel-logout": {}}`, and `sid` (and `sub`). For "disable" and
103+ "delete" it carries only `sub`, which means "every session of this user".
104+- The app validates it like an ID token (no `nonce`; it must carry `events` and must not carry `nonce`),
105+ rejects a reused `jti` for 10 minutes, deletes the matching local sessions, and answers `200` with an empty
106+ body. Any other answer is a failure.
107+- `im` delivers through a durable outbox: retries with backoff (10 s, 30 s, 1 min, 5 min, then every 15 min)
108+ for 24 hours. Combined with the 12-hour local session cap (2.4), a missed delivery cannot keep a revoked
109+ user signed in for longer than 12 hours, even if the app was down.
110+- The directory stream (section 3) also carries `disabled: true` and `deleted` events. An app that sees one
111+ deletes the user's local sessions as well. Two independent paths; either one is enough.
112+
113+### 2.6 Machine-to-machine tokens
114+
115+- A client that calls another app's API asks `im` for a token: `POST /token`
116+ `grant_type=client_credentials&scope=<scopes>&audience=<target key>` with its client auth. (`audience` is the
117+ RFC 8707-style extension parameter; its value is a family key such as `in`.)
118+- `im` checks the scopes against the client's allowed scopes (set by the admin) and returns an
119+ `access_token` JWT: `iss`, `sub` = `client:<client_id>`, `azp` = `client_id`, `aud` = target key, `scope`
120+ (space separated), `iat`, `exp` (10 min), `jti`, plus `svc` = the caller's family key.
121+- The receiving app verifies signature, `iss`, `aud` equals its own key, `exp`, and the scope it needs. It
122+ treats `svc` as the caller's identity. Callers cache the token until 60 s before `exp`.
123+
124+| Scope | Granted by default to | Lets the caller |
125+|---|---|---|
126+| `directory.read` | every family client | read the people directory and photos at `im` (section 3) |
127+| `files.service` | `iz` | store and read its own objects in `in` (section 5) |
128+
129+---
130+
131+## 3. People directory (im)
132+
133+All routes need a client-credentials token with `aud = "im"` and scope `directory.read`.
134+
135+### 3.1 Member record
136+
137+```json
138+{
139+ "sub": "01J...",
140+ "email": "a@example.com",
141+ "name": "Ayşe Yılmaz",
142+ "admin": false,
143+ "disabled": false,
144+ "locale": "tr",
145+ "zoneinfo": "Europe/Istanbul",
146+ "picture_version": 3,
147+ "updated_at": "2026-10-28T09:00:00.000000000Z"
148+}
149+```
150+
151+### 3.2 Routes
152+
153+- `GET /api/v1/directory` → `{"members":[<member>...], "cursor":"<opaque>"}`. Every account, disabled ones
154+ included (`disabled: true`). Deleted accounts are absent.
155+- `GET /api/v1/directory/stream` → `text/event-stream`. Optional `Last-Event-ID` (or `?cursor=`) resumes from a
156+ cursor. Events:
157+ - `event: member`, `data: <member>`: a member was created or changed (including disabled/enabled).
158+ - `event: deleted`, `data: {"sub":"..."}`: the account is gone.
159+ - `event: resync`, `data: {}`: the cursor is too old; fetch `GET /api/v1/directory` again.
160+ - Each event has an `id:` that is a cursor. Keep-alive comments every 30 s. `im` closes the stream after
161+ 50 minutes; the client reconnects with its last cursor.
162+- `GET /api/v1/people/{sub}/photo` → image bytes with the stored `Content-Type`, or `404` when there is no photo.
163+ `ETag: "p<picture_version>"`. With `?v=<picture_version>` matching, `Cache-Control: private, max-age=31536000,
164+ immutable`; otherwise `private, no-cache`. Honors `If-None-Match` with `304`.
165+
166+Apps mirror the directory into a local `members` table (full fetch, then the stream), so pages never call `im`
167+to show a name or an avatar. Apps proxy photos through their own origin and cache them on disk keyed by
168+`(sub, picture_version)`; a browser never talks to `im` for a photo.
169+
170+---
171+
172+## 4. Service registry and switcher (im)
173+
174+- `GET /api/v1/family` (token with `aud = "im"`, scope `directory.read`) →
175+ `{"services":[{"key":"in","name":"Files","url":"https://in.example.com","healthy":true,"checked_at":"..."}]}`
176+ in the admin's order. `im` is included as `{"key":"im","name":"Account",...}`.
177+- The list is owned by `im`'s admin. A service row is created with its OIDC client (the admin gives a key,
178+ a name and the origin; the redirect and back-channel URIs are derived from the origin). Apps do not register
179+ themselves.
180+- `im` probes each row's `GET /healthz` every 60 s (2 s timeout) and reports `healthy`. Apps fetch the list
181+ every 5 minutes and render the switcher from their copy; a stale copy is fine.
182+
183+### 4.1 Health
184+
185+Every app serves `GET /healthz` without auth: `200`, body `ok <build sha>`, `Content-Type: text/plain`.
186+It checks that the process answers and that a `SELECT 1` on its database succeeds within 1 s; otherwise
187+`503` with `fail <reason>`.
188+
189+---
190+
191+## 5. Object store (in)
192+
193+`in` stores bytes for other apps in a per-service namespace with its own quota. All routes need a
194+client-credentials token with `aud = "in"` and scope `files.service`. The namespace is the token's `svc`.
195+An object is named by the caller's `external_id` (1–128 chars of `[A-Za-z0-9._-]`).
196+
197+| Method and path | Request | Success |
198+|---|---|---|
199+| `PUT /api/v1/objects/{external_id}` | Raw body; `Content-Type` (stored as given, re-sniffed for display); optional `X-Object-Name` (UTF-8, percent-encoded, ≤255 bytes); optional `If-None-Match: *` | `201` (created) or `200` (replaced), JSON `{"external_id","size","sha256","content_type","created_at"}` |
200+| `GET /api/v1/objects/{external_id}` | Optional `Range: bytes=a-b` (one range) | `200` or `206`, the bytes, `ETag: "<sha256>"`, `Content-Length`, `Accept-Ranges: bytes` |
201+| `HEAD /api/v1/objects/{external_id}` | — | Headers as GET |
202+| `DELETE /api/v1/objects/{external_id}` | — | `204`; also `204` when already absent (idempotent) |
203+| `GET /api/v1/usage` | — | `{"quota_bytes": n, "used_bytes": n, "objects": n}` |
204+
205+- Uploads stream to disk; the body is never held in memory. A body larger than the remaining quota is refused
206+ with `413` and error code `quota_exceeded` before or while it is read.
207+- `PUT` is atomic: the new bytes are visible only after they are fully written and fsynced.
208+- Service objects never appear in a person's drive and do not count against any person's quota.
209+- The quota per service is set in `in`'s admin page (default 10 GiB).
210+
211+---
212+
213+## 6. Users across apps
214+
215+- The user id everywhere is `im`'s `sub` (a ULID). Apps never invent their own user ids for people.
216+- An app learns a user when they first sign in or when the directory names them. A member that the directory
217+ lists but who never signed in still exists in the app (so they can be assigned, mentioned, mailed).
218+- App-level roles (for example `iz` Admin, Member, Viewer) belong to the app. `im`'s `admin` flag means
219+ "instance administrator" and every app treats it as its own top role.
220+
221+---
222+
223+## 7. Errors
224+
225+Machine routes answer errors as:
226+
227+```json
228+{"error": "quota_exceeded", "message": "The service quota of 10 GiB is used up."}
229+```
230+
231+with the matching status: `400 invalid_request`, `401 invalid_token` (with `WWW-Authenticate: Bearer
232+error="invalid_token"`), `403 insufficient_scope`, `404 not_found`, `409 conflict`, `413 quota_exceeded` or
233+`too_large`, `429 rate_limited` (with `Retry-After`), `500 internal`, `503 unavailable`. `error` is a stable
234+machine word; `message` is English for logs and may change. OAuth endpoints (`/token`, `/revoke`,
235+`/introspect`) use the OAuth error format from their RFCs instead.
236+
237+---
238+
239+## 8. Change log
240+
241+- **v1** (2026-10-28): first version.
docs/conventions.mdadded+169 -0
@@ -0,0 +1,169 @@
1+# Code conventions
2+
3+These rules are the same in `im`, `in` and `iz` (the file is copied into each repo). They are taken from
4+`forge` (`~/Documents/Code/Rust/forge`, see its `docs/architecture.md`), which is the reference
5+implementation: when a rule here is unclear, read how forge does it and do the same.
6+
7+## 1. Workspace
8+
9+- Edition 2024, resolver 3, `unsafe_code = "forbid"` in `[workspace.lints.rust]`, every member ends with
10+ `[lints] workspace = true` and `publish = false`.
11+- Every dependency version lives in the root `[workspace.dependencies]`, added with `cargo add` at its latest
12+ release (never copied from another project). Members write `foo.workspace = true`.
13+- Topcoat 0.11 with `default-features = false` and an explicit feature list. Turso (latest stable) for the
14+ database.
15+- Two crates per app: `<app>-core` (domain types, store, migrations, config, secrets, auth primitives, pure
16+ logic; no HTTP) and `<app>-web` (the binary named `<app>`: Topcoat UI, HTTP APIs, background workers, CLI).
17+ Add a crate only for a real boundary.
18+- Dev profile: `debug = "line-tables-only"`; `opt-level = 3` for `argon2`, `sha2` and the turso crates, each with
19+ a one-line reason. Release: `lto = true`, `codegen-units = 1`.
20+
21+## 2. Boot
22+
23+`main.rs` dispatches on positional words: no word or `serve` runs the server, `admin <cmd>` runs the CLI.
24+Config path: `--config <path>`, then `<APP>_CONFIG`, then `config/<app>.toml`. Exit 2 on usage errors, 1 on
25+failure.
26+
27+`serve` order: load and validate config → create `data_dir` (0700) → load or create `<app>.key` (32 bytes, 0600,
28+`O_EXCL`) → open the store (pragmas, migrations) → layer stored UI overrides on the file config → spawn
29+workers → build the router → bind → serve until SIGTERM/Ctrl-C, with one stop flag shared by every listener and
30+worker.
31+
32+Logging: `tracing` + `tracing-subscriber` (`env-filter`), stderr, default `info`, structured fields. Never log
33+tokens, passwords, cookies, or secrets.
34+
35+## 3. Config
36+
37+- `config/<app>.example.toml` is committed. `config/<app>.toml` is gitignored. A missing file is created from
38+ the example (dev defaults) on first run.
39+- `#[serde(deny_unknown_fields)]` on every struct. One `Config::validate()` for cross-field rules, used at load
40+ and when a UI override is saved.
41+- Secrets never live in the TOML. They are entered in the admin UI (sealed in the DB) or in a separate file
42+ readable only by the service user.
43+- Runtime settings: a `settings` key/value table with precedence **UI override → file → built-in default**, and
44+ each field marked `Live`, `Restart` or `ReadOnly` (forge `server_settings.rs`).
45+
46+## 4. Store
47+
48+- One writer connection behind a tokio `Mutex`, plus a pool of 4 `PRAGMA query_only` readers. Pure reads use a
49+ reader; writes, transactions and read-then-write sequences use the writer.
50+- Pragmas on every connection: `journal_mode=WAL`, `synchronous=FULL`, `foreign_keys=ON`, busy timeout 5 s.
51+ Read them back and log them at boot.
52+- Migrations: `crates/<app>-core/migrations/NNNN_snake_name.sql`, each starting with a comment that says what
53+ it does; listed in `store/migrate.rs` as `(version, include_str!(...))`; each applied in its own transaction
54+ with a `schema_migrations` row. Never edit an applied migration.
55+- Ids are ULID text. Timestamps are UTC RFC 3339 with 9 fractional digits and `Z` (fixed width, so text order is
56+ time order) from `time.rs` (`now_stamp()`, `stamp_after(d)`). Booleans are `INTEGER` 0/1 with a `CHECK`.
57+- Column lists are constants (`USER_COLS`) next to their `map_user(row)`; SQL uses `?1, ?2`; ownership goes in
58+ the `WHERE` (`... WHERE id = ?1 AND owner_id = ?2`).
59+- Multi-statement writes: `unchecked_transaction()` + an async block returning `Result` + one `finish(tx,
60+ outcome)` helper that commits or rolls back.
61+- Constraints live in the schema (`NOT NULL`, `CHECK`, `UNIQUE`, `REFERENCES ... ON DELETE ...`), not only in Rust.
62+- Backups: `snapshot_to(path)` with `VACUUM INTO` on the writer, then checkpoint the copy so it is one
63+ self-contained file, then fsync. `admin backup --out DIR` writes the snapshot, the blob tree (where the app
64+ has one) and a `manifest.json` with a sha256 per file. `admin backup-verify SET` checks hashes,
65+ `integrity_check` and contiguous migrations. Never copy a live DB file.
66+
67+## 5. HTTP and pages
68+
69+- Routes with `#[route(...)]` / `#[page(...)]` and `.discover()`. Anything that must not be public is
70+ registered explicitly on a separate router.
71+- Handler shape: (1) authenticate, (2) load and authorize, (3) build the view, (4) return it.
72+- Forms: every field `#[serde(default)]`; every state-changing POST carries a `csrf` field checked in constant
73+ time **before** any side effect (`require_csrf`). Pre-session forms use the `__Host-<app>_precsrf` cookie
74+ (SameSite=Strict). Post/Redirect/Get with notices in the query string (`?notice=...`), not cookies.
75+- Session cookie: `__Host-<app>_session`, random 32 bytes base64url; the DB stores only its SHA-256.
76+ HttpOnly, Secure, SameSite=Lax, Path=/.
77+- `safe_next()` for every return path: one leading `/`, not `//` or `/\`, no control characters, ≤2048 bytes.
78+- One security-headers layer on `/`: `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`,
79+ `Referrer-Policy: same-origin`, `Strict-Transport-Security` when the base URL is https, and
80+ `Content-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self';
81+ form-action 'self'; frame-ancestors 'none'; base-uri 'none'`. **No inline scripts or styles anywhere**; all JS
82+ is in `assets/*.js`.
83+- Styled 404 page for `Accept: text/html`; 404 for "missing" and for "exists but you may not see it".
84+- Request bodies are capped per route (`BodyLimit`); upload routes stream.
85+- Assets (CSS compiled from `style/*.scss` with `grass` in `build.rs`, JS, fonts) are embedded with
86+ `include_str!`/`include_bytes!`, served by routes with `Cache-Control: public, max-age=31536000, immutable`,
87+ and linked with a content-hash query (`/assets/main.css?v=<12 hex>`). Fonts are self-hosted. Nothing is
88+ loaded from a third-party origin.
89+
90+## 6. Auth primitives
91+
92+- Passwords: argon2id (`Argon2::default()`), PHC strings, always on `spawn_blocking`. Unknown accounts verify
93+ against a fixed dummy hash so timing does not reveal them.
94+- Tokens: 32 random bytes, base64url; stored as hex SHA-256; compared with `subtle`; shown once.
95+- Throttle (in memory, sliding window, bounded key count): failed logins per account and per IP, failed second
96+ factors per user; checked before any lookup; `429` with `Retry-After`.
97+- Secrets at rest: `seal`/`open` with XChaCha20-Poly1305 under the instance key, `v1:` + base64(nonce ||
98+ ciphertext).
99+- Client IP: the TCP peer unless it is in `trusted_proxies`; then `X-Forwarded-For` right to left.
100+
101+## 7. Authorization
102+
103+One pure function per app, `authz::authorize(actor, resource, role, action) -> Result<(), Denied>`, with
104+`Denied::{NotFound, Forbidden}`. Every page, form handler, API route and live stream goes through it. It is
105+unit-tested as a truth table.
106+
107+## 8. Live pages
108+
109+- `LiveHub` of `watch::Sender<u64>` per `Topic` (an enum keyed by what a page is about). Writes call
110+ `live.bump(&topic)` after commit.
111+- A page that updates live renders `data-live="<stream url>"`. The stream route authenticates and authorizes
112+ first, then `stream_changes(cx, hub, topics, fingerprint)`: subscribe, read a fingerprint, and send a
113+ data-less `event: changed` only when the fingerprint changes. `retry: 1000`, keep-alive every 30 s,
114+ `X-Accel-Buffering: no`.
115+- `GET /-/alive` is held by every page (anonymous-safe). It drives the "server restarting" bar and carries
116+ `account` events (sign-out, preference change) for the viewer.
117+- `assets/nav.js` (one file, progressive enhancement): soft navigation for same-origin links and forms
118+ (`data-hard` opts out), keeps focus/scroll/typed input across swaps, opens one EventSource per distinct
119+ `data-live` URL, re-fetches the page on `changed`, reconnects after 1/2/3 s, never re-sends a POST.
120+ Pages work without JS.
121+
122+## 9. Errors
123+
124+- One `thiserror` enum per crate: `Io`, `Database`, `Migration`, `Config`, `Crypto`, `NotFound`,
125+ `Conflict(String)`, `Forbidden(String)`, `Invalid(String)`.
126+- `Invalid` and `Conflict` text is for the user (shown as an alert). Everything else is a 500 with a generic
127+ page and a logged cause.
128+- Security-sensitive answers are identical for "unknown" and "wrong".
129+
130+## 10. Audit
131+
132+Append-only `audit_log` (id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data JSON). Written
133+after the change commits; a failed audit write is logged and never fails the request. Never store secrets in
134+`data`. Admin page with filters and keyset paging. Purge only through `admin audit-purge --older-than-days N`.
135+
136+## 11. i18n
137+
138+English and Turkish. `Lang::{En, Tr}`; resolution: the user's stored language, else `Accept-Language`, else
139+English. Keys are enums per area with an exhaustive `match` on `(key, lang)`, so a missing translation does not
140+compile. **Every** page, including sign-in, error and mail text, is translated. Sentences with values use small
141+format helpers, not concatenation in views.
142+
143+## 12. Comments and naming
144+
145+- `//!` on every module: what it is, what it is not, the invariant it keeps. `///` on every public item and on
146+ every policy constant (with its unit and reason). Inline comments explain why, in full sentences.
147+- No commented-out code. No `TODO` without a line in `docs/backlog.md`.
148+
149+## 13. Tests
150+
151+Few and meaningful. Unit tests for pure logic that is easy to get wrong (authz truth table, token and CSRF
152+compare, `safe_next`, parsers, time math, quota math), store tests on a real temp database (`tempfile`) for
153+tricky queries and constraints, and one or two in-process router tests per security rule (CSRF refused,
154+hidden resource is 404, admin page refuses members). No snapshot tests, no browser tests, no mocks of the
155+database. Tests never write outside their temp dir.
156+
157+## 14. Deploy
158+
159+`deploy/<app>.service`: dedicated user, `ProtectSystem=strict`, `ReadWritePaths=` the data dir only,
160+`ProtectHome=yes`, `PrivateTmp=yes`, `PrivateDevices=yes`, `NoNewPrivileges=yes`, `CapabilityBoundingSet=`,
161+`RestrictNamespaces=yes`, `RestrictSUIDSGID=yes`, `LockPersonality=yes`, `MemoryDenyWriteExecute=yes`,
162+`SystemCallArchitectures=native`, `SystemCallFilter=@system-service`, `UMask=0077`, `Restart=on-failure`.
163+`/healthz` per contracts.md 4.1.
164+
165+## 15. Git
166+
167+Commit messages follow forge's style: gitmoji + type + description, for example
168+`✨ feat: sign-in with TOTP and recovery codes`, `🐛 fix: ...`, `♻️ refactor: ...`, `📝 docs: ...`.
169+No co-author or "generated with" lines.
docs/reference/old-inventory.mdadded+311 -0
@@ -0,0 +1,311 @@
1+# im: feature inventory (rebuild reference)
2+
3+Source: /home/tahinli/Documents/Code/Rust/old_im (read-only survey). Workspace crates: im-core (domain + storage, feature `server`), im-web (topcoat web app, binary `im-web`), im-client (app-side SDK).
4+
5+## 1. Purpose summary
6+
7+1. im is a self-hosted OpenID Connect identity provider (OIDC, RS256, PKCE S256) and account portal for a small family of sibling apps.
8+2. Users sign in with email + Argon2id password, optional TOTP 2FA; they manage sessions, profile photo, preferences, password, and email change.
9+3. Admins manage users (invite, disable, delete, sign-out-everywhere), OIDC clients, the sibling service registry, SMTP, policy settings, a filterable audit log, and service health.
10+4. Sibling apps ("in" = Files, "iz" = Board) integrate via OIDC, mirror the member directory over HTTP + SSE, read profile photos, introspect app sessions, and register themselves in the family registry.
11+5. Single binary, Turso (SQLite-compatible) storage, files beside the DB; backup/restore via `pack`/`unpack`; systemd user unit with GitHub Actions deploy.
12+
13+## 2. User-facing features
14+
15+Routes are method + path as registered in `crates/im-web/src`. Pages return HTML; POST handlers redirect (303) with `?ok=` or `?error=` codes.
16+
17+### 2.1 Landing and profile (`pages.rs`)
18+- `GET /` signed out: login card. Signed in: landing with sections via `?section=` = `profile` | `sessions` | `apps` | `preferences` | `password`.
19+- Profile card: photo or initial avatar, 2FA chip, admin chip, email, member since, link to public profile, "activate 2FA" link when off, admin panel link when admin.
20+- Stats card (`stats.rs`): sign_ins (all sessions ever), active_sessions (not revoked, not expired), connected_apps (distinct clients with live app sessions).
21+- Sessions section: list of sessions as `<details>` items; device label parsed from User-Agent (Edge, Firefox, Chromium, Chrome, Safari; iPhone, iPad, Android, Windows, macOS, ChromeOS, Linux); shows address, created, last seen; `POST /sessions/revoke` (`session`=token hash) revokes one owned session (cascades to refresh_tokens and app_sessions of that session).
22+- Apps section: connected apps (`list_connected_apps`) with revoke.
23+- Preferences: `POST /preferences`: theme `light|dark`; ui `instrument|ledger`; language `en|tr`; timezone from zone_options UTC-12..UTC+14 plus UTC (default `UTC+03:00`). Redirect `/?section=preferences`.
24+- Password: `POST /password` (current, password, password_confirm). Rules below. Revokes all other sessions, keeps current. Redirect `/?section=password&ok=password`.
25+
26+### 2.2 Login and 2FA (`auth.rs`, `pages.rs`)
27+- `GET /login` (optional `back`, `error`, `ok`). `POST /login` (email, password, back).
28+ - Rate limited per account (key = trimmed email); over limit → `/login?error=rate_limited`.
29+ - Bad credentials (also unknown email, disabled user, same message) → `/login?error=bad_login&back=...`.
30+ - Account with confirmed TOTP → sealed pending cookie `im_pending` (JSON {user, purpose "login", back, exp}, TTL 10 min or policy `pending_minutes`) → redirect `/login/totp`.
31+ - Account without 2FA → session issued immediately (2FA is optional).
32+ - `safe_back`: only local paths (or same-origin family URLs) accepted.
33+- `GET /login/totp`, `POST /login/totp` (code). Rate limit key `totp:{user}`. Bad → `/login/totp?error=bad_code`. Success → `im_session` cookie and redirect to back. Replay protection via `users.totp_last_step`.
34+- `POST /logout`: signs out everywhere (central session revoked; cookie cleared) → `/`.
35+- `GET /logout?back=`: RP-initiated logout; `back` must be local path or same origin as a family service; clears central session.
36+- `GET /api/me`: 204 when signed in, 401 otherwise (used by client JS).
37+
38+### 2.3 2FA enrollment (`pages.rs`, `totp.rs`)
39+- `GET /enroll`: generates a 20-byte secret (stored sealed, `totp_confirmed = 0`), shows base32 secret grouped by 4, `otpauth://totp/im:{email}?secret=...&issuer=im`, QR as SVG (`qrcode` crate). Page strings are English-only.
40+- `POST /enroll` (code). Bad → `/enroll?error=bad_code`; good → `totp_confirmed = 1`, redirect `/?ok=enrolled`.
41+- No UI or route to disable TOTP once enrolled. Re-visiting `/enroll` after confirmation regenerates the secret (`set_totp` resets confirmed flag) — see oddities.
42+- Verification: HMAC-SHA1, 6 digits, 30 s step, +/-1 step drift. Secret 160-bit.
43+
44+### 2.4 Invitations and account creation
45+- Invite creation: admin only (see 2.8). Invite token = 32 random bytes, base64url, stored as SHA-256 hex (`invites.token`). Expiry = policy `invite_days` (default 7).
46+- `GET /invite/{token}`: form with name, password, password_confirm; invalid/expired/accepted token shows error.
47+- `POST /invite` (token, name, password, password_confirm): creates user (transactional, marks invite accepted), auto-signs-in, redirect `/`. TOTP not forced.
48+- Invite refused if email already has an account. Multiple pending invites for one email are allowed.
49+- Mail: invite email in English only (`invite_mail`), link `{issuer}/invite/{token}`, mentions INVITE_DAYS. If no SMTP configured, dev mode prints the link to stdout; admin UI shows the link once.
50+
51+### 2.5 Password reset (`pages.rs`, `accounts.rs`)
52+- `GET /forgot`; `POST /forgot` (email): always redirects `/forgot?ok=sent` (no enumeration). Rate limit key `forgot:{email}`. If account exists, creates reset link (retires previous unused links; expiry policy `reset_minutes`, default 60) and mails `{issuer}/reset/{token}` in the account's language.
53+- `GET /reset/{token}`; `POST /reset` (token, password, password_confirm): success → `/login?ok=reset`; errors → `/reset/{token}?error=...`. On success marks link used, sets hash, revokes all sessions, clears login failures.
54+
55+### 2.6 Email change (two-sided confirmation) (`pages.rs`, `auth.rs`, `accounts.rs`)
56+- `POST /email_change` (email): validates address (trim, lowercase, contains @ and dotted domain; taken → error). Creates a pair of tokens (old-address token, new-address token) in `email_changes`, expiry ~ policy-driven. Mails both: "leaving" link to old address, "gaining" link to new address (`{issuer}/email/{token}`).
57+- If mail send fails, both confirmation links are returned in the redirect query `links=` (see security oddities).
58+- `GET /email/{token}` shows confirmation page (GET never mutates). `POST /email` (token) confirms that side. Results: `/login?ok=email_changed` when both sides confirmed; `/login?ok=email_half_confirmed` otherwise; errors. At completion the new address is re-checked for being taken.
59+- Pending state shown on profile via `pending_email_change`.
60+
61+### 2.7 Profile photo (`photo.rs`)
62+- `POST /api/profile_photo` (multipart, field file): limit 5 MiB (`PHOTO_LIMIT_BYTES`); BodyLimit set to limit + 4096. Sniffs magic bytes: PNG, JPEG, GIF, WEBP, AVIF. Errors `/?error=no_file|photo_too_big|not_an_image|unavailable`; success `/?ok=photo_saved`. Stores file at `<storage>/photos/<user_id>`, row increments `photo_version`.
63+- `POST /api/delete_profile_photo` → `/?ok=photo_removed`.
64+- `GET /photo/{user_id}`: auth by session cookie OR HTTP Basic app credentials; otherwise 404. Unknown user or no photo → SVG initial tile. Headers: ETag `"p{version}"`; with `?v=` matching version: `private, max-age=31536000, immutable`; otherwise `private, no-cache`; 304 on If-None-Match.
65+
66+### 2.8 Public profile (`people.rs`)
67+- `GET /people/{user_id}`: requires signed-in viewer; unknown id or signed out → router not-found. Shows name, email, member since, 2FA/admin chips, stats. Edit link only for self.
68+
69+### 2.9 Admin panel (`admin.rs`)
70+- `GET /admin` (admin only; non-admin → 303 `/`). Sections via `?section=`: `users` (default), `services` (alias `clients`), `message`, `settings`, `logs`, `health`. A `mail` section exists but is only reached by redirects; the nav has no Mail tab (oddity).
71+- Admin role cannot be granted from the panel. Only CLI `promote`/`demote` or an invite with role admin.
72+- Users section: table with per-user session rows (device, address, created, last seen, revoke button), disable/enable, delete, sign out everywhere, per-user email edit fold.
73+ - `POST /admin/invite` (email, role `member|admin`): mails invite or shows link once via `invited=`; logs `invite_created`.
74+ - `POST /admin/uninvite` (invite=hash): removes pending invite; logs `invite_revoked`.
75+ - `POST /admin/user_email` (user, email): direct rescue edit, no confirmation; logs `email_changed`.
76+ - `POST /admin/delete` (user): deletes user (see 4 for what survives); logs `user_deleted`.
77+ - `POST /admin/revoke` (user): sign out everywhere; logs `sessions_revoked`.
78+ - `POST /admin/session_revoke` (user, session): one session; logs.
79+ - `POST /admin/disable` and `POST /admin/enable` (user): disable revokes all sessions; `notify_profile` broadcast; logs `user_disabled`/`user_enabled`.
80+- Services section: `POST /admin/services_add` (key, name, url); `POST /admin/services_edit` (key, name, url, limit_amount, limit_unit `MiB|GiB`); `POST /admin/services_remove` (key; refuses owned rows; closes gap); `POST /admin/services_move` (key, dir `up|down`; swaps with neighbor). Keys: lowercase letters, digits, dashes. Name non-empty. URL http(s), no spaces. Edit: only name and storage limit may change for existing rows; URL change refused.
81+- Clients section (OIDC clients): `POST /admin/clients_add` (name, redirect_uris split by whitespace or comma); client secret shown once via show-once shelf (10 min one-time ticket in `shown=`). `POST /admin/clients_rotate` (client): new secret, shown once. `POST /admin/clients_revoke` (client): deletes client, its refresh tokens and app sessions (not central sessions).
82+- Settings section: `POST /admin/settings` (invite_days, session_days, max_sessions, pending_minutes, reset_minutes, login_attempts_per_hour). Values < 1 clamped to default.
83+- SMTP: `POST /admin/smtp` (host, port u16 default 587, username, password optional (blank keeps old), from_name, from); saves and re-probes in background. `POST /admin/smtp_test` sends test mail to admin's email. `POST /admin/smtp_check` runs connection probe (15 s timeout). Standing shown as NotConfigured / Unchecked / Connected / Refused, with recorded check time, latency, error.
84+- Message section: `POST /admin/message` (to = `everyone` (excludes admin) or user id; subject; body). Sends sequentially; aborts on first failure.
85+- Logs section: audit events table. Filters: kind, actor, from/to dates, dir (`newest|oldest`), q (substring). Default 50 rows per page (cookie `im_rows_logs`, clamp 5 to 200, fit-to-viewport script). Cursor paging `before` / `after` as `rfc3339~id`; position note `X-Y / Z`.
86+- Health section: table of services with `/healthz` result and latency.
87+
88+### 2.10 Logout of sibling apps
89+- Apps call `GET /logout?back=` (see 2.2) to end the central session.
90+
91+### 2.11 Family registry (cross-app, see 3.8/3.9)
92+- Services are listed in the admin panel and in the family flyout (signed-in chrome) with health dots. im's own row is excluded from the flyout.
93+
94+## 3. Machine and API endpoints (cross-app contract)
95+
96+Base: `issuer` (config, default `http://127.0.0.1:7650`). Auth schemes: "Basic" = HTTP Basic `client_id:client_secret` checked against `oidc_clients` (secret stored as hash). "Bearer" = RS256 JWT from /token.
97+
98+### 3.1 OIDC discovery and keys
99+- `GET /.well-known/openid-configuration` (no auth). JSON: `issuer`, `authorization_endpoint` `{issuer}/authorize`, `token_endpoint` `/token`, `userinfo_endpoint` `/userinfo`, `jwks_uri` `/jwks.json`, `response_types_supported` ["code"], `grant_types_supported` ["authorization_code","refresh_token"], `subject_types_supported` ["public"], `id_token_signing_alg_values_supported` ["RS256"], `scopes_supported` ["openid","profile","email"], `claims_supported` iss, sub, aud, exp, iat, nonce, email, name, `code_challenge_methods_supported` ["S256"]. No introspection_endpoint or end_session_endpoint listed.
100+- `GET /jwks.json` (no auth). `{"keys":[{"kty":"RSA","alg":"RS256","use":"sig","kid":...,"n":...,"e":...}]}`. kid = first 16 hex of SHA-256 of public DER.
101+
102+### 3.2 Authorization code flow
103+- `GET /authorize` (no auth; needs central session). Query: `client_id`, `redirect_uri` (must exactly match a registered URI), `response_type=code`, `scope` (must include `openid`; only openid/profile/email), `code_challenge` (required), `code_challenge_method=S256`, `state`, `nonce`.
104+ - No central session → 303 `/login?back=/authorize?...`.
105+ - Bad client or redirect_uri → bare 400 "invalid request" (no redirect).
106+ - Other errors → 302 to redirect_uri with `?error=` (`unsupported_response_type`, `invalid_scope`, `invalid_request`) and `state`.
107+ - Success → 303 `redirect_uri?code=...&state=...`. Code: 32 random bytes, stored as hash, TTL 60 s, single use (peek then consume in immediate transaction).
108+- `POST /token` (form-encoded). Client auth: `client_secret_post` only (client_id and client_secret in body).
109+ - `grant_type=authorization_code`: `code`, `redirect_uri`, `client_id`, `client_secret`, `code_verifier` (PKCE S256 check). Response JSON:
110+ - `access_token`: RS256 JWT, claims iss, sub, aud=client_id, exp (now+900), iat, scope "openid profile email" (hardcoded).
111+ - `id_token`: RS256 JWT, claims iss, sub, aud=client_id, exp, iat, email, name, nonce.
112+ - `refresh_token`: opaque, 30 days (`REFRESH_DAYS`), stored hash; bound to central session_hash.
113+ - `expires_in`: 900; `token_type`: "Bearer"; `app_session`: opaque app session token (30 days, non-OIDC, used by `/introspect`).
114+ - `grant_type=refresh_token`: `refresh_token`, `client_id`, `client_secret`. Rotates: old revoked, new issued. No reuse detection (reuse does not revoke the chain).
115+ - Errors: JSON `{"error": "invalid_request" | "invalid_client" | "invalid_grant" | "unsupported_grant_type"}` with 400 (401 for invalid_client).
116+- `GET /userinfo`: `Authorization: Bearer <JWT>`. Verifies signature, requires aud to be a registered client. Returns `{"sub","email","name"}`. Failure: 401 `invalid_token` with `WWW-Authenticate: Bearer`.
117+
118+### 3.3 Introspection
119+- `POST /introspect` (form: `token`, `client_id`, `client_secret`). Token is an app_session (opaque). Response JSON: `{"active": true, "sub", "email", "name", "admin", "photo_version", "timezone", "exp"}` or `{"active": false}`. Active requires: client_id match, central session alive, user not disabled, app session not expired/revoked. Invalid client → 401 `{"error":"invalid_client"}`.
120+
121+### 3.4 Directory (member mirror)
122+- `GET /directory` (Basic). JSON array of non-disabled members: `sub`, `email`, `name`, `admin`, `photo_version`, `timezone`, `disabled` (false). Invalid client → 401 `{"error":"invalid_client"}`.
123+- `GET /directory/live` (Basic). SSE. First frame: comment "directory live" and `retry: 5000`. Events:
124+ - `event: profile`, data = member JSON (may carry `disabled: true`, although the full list excludes disabled members).
125+ - `event: revoked`, data `{"sub": "<user id>"}`.
126+ - Ticks are silent. Keep-alive comments. Stream window 50 minutes (`WINDOW`), then closes; client reconnects.
127+
128+### 3.5 Profile photo
129+- `GET /photo/{user_id}` with Basic credentials (see 2.7). Used by sibling apps to show avatars.
130+
131+### 3.6 Live SSE for browsers
132+- `GET /live` (session cookie; signed-in users). SSE, 50-min window, per-connection resolved session.
133+ - `event: profile` data `{"kind":"profile","sub":"<user id>"}` for any member change (not filtered to the viewer).
134+ - `event: revoked` (empty data) sent to matching user + session hash, or all sessions of a user.
135+ - Tick → default message with data `{}`.
136+- Client JS (`live_script`): EventSource `/live`; on `revoked` navigates home; on error probes `/api/me`, on 401 navigates home.
137+
138+### 3.7 Health
139+- `GET /healthz` (no auth): body `ok {IM_BUILD_SHA}` (build SHA from env, default `dev`).
140+- im itself probes each service's `{url}/healthz`: 2 s timeout, success status and body starting "ok". Shared reqwest client, 30 s cache (`CACHE_TTL`).
141+
142+### 3.8 Family registry
143+- `GET /family` (Basic). JSON array ordered by position: `key`, `name`, `url`, `limit_bytes`. (`owner` and `client_id` are not serialized.)
144+- `POST /family/register` (Basic). JSON body `{key, name, url}`. Owner and client_id = authenticated client id.
145+ - Success: returns the service JSON (200).
146+ - 409 `{"error":"owned"}` if another client owns the key.
147+ - 400 `{"error":"invalid","reason":...}` on validation failure.
148+ - Claims unowned rows; refreshing own row updates url/owner/client_id; name stays admin's.
149+
150+### 3.9 Local-process hints
151+- `IM_BUILD_SHA` env used in /healthz; `IM_*` env vars used by the im-client example only.
152+
153+## 4. Data model
154+
155+Storage: Turso (single writer, one connection behind `tokio::sync::Mutex`, `BEGIN IMMEDIATE` transactions). Schema: SCHEMA const in `crates/im-core/src/store.rs`, plus guarded ALTERs in `Store::migrate`. No `migrations/` directory exists. Files beside DB: `storage/photos/<user_id>`, `im.key` (32-byte at-rest key, mode 0600).
156+
157+Tables:
158+- `users`: id (ULID PK), email (UNIQUE COLLATE NOCASE), name, password_hash (Argon2id PHC), totp_secret (BLOB, sealed), totp_confirmed (bool), totp_last_step (replay guard), admin (bool), disabled (bool), created_at, photo_mime, photo_version (int, cache key), theme (default `light`), language (default `en`), ui (default `instrument`), timezone (default `UTC+03:00`).
159+- `invites`: token (hash PK), email, invited_by (user id, nulled on inviter delete), admin (bool, role), created_at, expires_at, accepted_at.
160+- `sessions`: token_hash PK, user_id FK, created_at, expires_at, revoked_at, ip, agent (User-Agent), seen_at (throttled to 5 min).
161+- `oidc_clients`: client_id PK, name, secret_hash, redirect_uris (JSON text), created_at.
162+- `auth_codes`: code_hash PK, client_id, user_id, redirect_uri, nonce, code_challenge, session_hash, expires_at (60 s), consumed_at.
163+- `refresh_tokens`: token_hash PK, user_id, client_id, session_hash FK sessions, expires_at, revoked_at.
164+- `signing_keys`: kid PK, private_der_enc (PKCS#8, sealed), public_der, created_at, active (default 1; never set to 0 in code).
165+- `app_sessions`: token_hash PK, user_id, client_id, session_hash, created_at, expires_at, revoked_at.
166+- `events`: id (ULID PK), at, kind, actor, detail (audit log).
167+- `reset_links`: token (hash PK), user_id, created_at, expires_at, used_at.
168+- `email_changes`: old_token_hash PK, new_token_hash UNIQUE, user_id, old_email, new_email, created_at, expires_at, confirmed_old_at, confirmed_new_at, used_at.
169+- `login_attempts`: key, at; index on key+at (rolling 1 h window).
170+- `settings`: key PK, value. Policy keys (invite_days, session_days, max_sessions, pending_minutes, reset_minutes, login_attempts_per_hour), smtp_* keys (host, port, username, from, from_name, password sealed as `smtp_password`), smtp_check_at, smtp_check_ms, smtp_check_error.
171+- `services`: key PK, name, url, position, owner (client id; null if unowned), client_id, storage_limit_bytes.
172+
173+Migration ALTERs (`migrate`): users.photo_mime, photo_version, theme, language, ui, timezone, totp_last_step; services.client_id, storage_limit_bytes; sessions.ip, agent, seen_at. Services seed from config only when table is empty.
174+
175+Sealed values use the `v1:` envelope (see 6).
176+
177+## 5. Config keys
178+
179+File: `config/im.toml` (also written with DEFAULTS by `Config::load()` if missing). Path resolution beside the binary's working dir (`%h/im` in deploy).
180+
181+| Key | Default | Notes |
182+|---|---|---|
183+| `database` | `im.db` | Turso DB path; key file and storage dir live beside it |
184+| `listen` | `127.0.0.1:7650` | bind address |
185+| `issuer` | `http://127.0.0.1:7650` | must be http(s); trailing slash trimmed; https makes cookies Secure |
186+| `[[services]]` | in/Files/`http://127.0.0.1:7655`, im/Account/`http://127.0.0.1:7650`, iz/Board/`http://127.0.0.1:7654` | first-boot seed only; key in/im/iz; url http(s) |
187+| `[smtp]` | commented example | host, port (587 default), username, from, from_name, password (password stored sealed in DB, not in TOML) |
188+
189+Policy defaults (admin-editable in `settings`; values < 1 clamp to default):
190+- `invite_days` 7
191+- `session_days` 30 (DB expiry; the cookie MaxAge is a constant 30 days, see oddities)
192+- `max_sessions` 5 (oldest revoked when exceeded)
193+- `pending_minutes` 10
194+- `reset_minutes` 60
195+- `login_attempts_per_hour` 10
196+
197+Constants: `MIN_PASSWORD_CHARS` 10; `SESSION_DAYS` 30; `CODE_SECONDS` 60; `TOKEN_SECONDS` 900; `REFRESH_DAYS` 30; `APP_SESSION_DAYS` 30; `PHOTO_LIMIT_BYTES` 5 MiB; live `WINDOW` 50 min; `CACHE_TTL` 30 s (health); health timeout 2 s; SMTP probe timeout 15 s; probe timeout for SMTP check; `DEFAULT_TIMEZONE` "UTC+03:00"; Argon2 m=19456 KiB, t=2, p=1; show-once secret TTL 10 min; photo max-age 31536000.
198+
199+Env: `IM_BUILD_SHA` (build-time, default `dev`); im-client example reads `IM_ISSUER`, `IM_CLIENT_ID`, `IM_CLIENT_SECRET`.
200+
201+CLI (`im-web` binary; no subcommand = serve):
202+- `invite <email> [--admin]`; `revoke <email>`; `promote <email>`; `demote <email>`
203+- `create-client <name> <redirect_uri...>`; `rotate-client <client_id>`; `revoke-client <client_id>`
204+- `pack [--root DIR] [--out FILE]`; `unpack FILE [--root DIR] [--force]`
205+
206+Serve startup: seed services when empty; `register_self` (im's own row claimed with owner "im" from issuer on each boot); sweep orphan photo files (deletes unknown files and `*.incoming-*` / `*.tmp`; reports rows missing files); create signing key if none; BodyLimit on `/api/profile_photo`; cookies; assets bundle; trusted proxies `nearest(1)`; graceful shutdown on SIGTERM/Ctrl+C.
207+
208+## 6. Security mechanisms
209+
210+- Passwords: Argon2id (m=19456 KiB, t=2, p=1, v0x13), PHC strings. `dummy_verify` for unknown emails to equalize timing. Rules: min 10 chars; reject if it contains the email, local part, or name words (>= 3 chars, substring); change must differ from current; wrong current rejected.
211+- Tokens: 32 random bytes, base64url no pad; stored as SHA-256 hex. Compared with `subtle` (constant time) where applicable.
212+- Cookies: `im_session` (raw random token; HttpOnly, SameSite=Lax, Secure iff issuer is https, Path=/, Max-Age 30 days constant); `im_pending` (sealed JSON; 10 min). App cookie in im-client: sealed JSON, MaxAge 30 days.
213+- Sealing: XChaCha20-Poly1305, `v1:` envelope (base64 of 24-byte nonce || ciphertext), key = 32-byte `im.key` (mode 0600, created on first boot).
214+- Sealed at rest: TOTP secrets, signing private key (PKCS#8), SMTP password, pending cookie.
215+- JWT: RS256 (PKCS#1 v1.5 + SHA-256), hand-rolled `sign_jwt`; RSA-2048 key generated on first boot; no rotation mechanism.
216+- PKCE: S256 required on /authorize; verified at /token.
217+- Auth codes: single use, 60 s TTL, peek then consume in immediate transaction.
218+- Refresh: rotation on each use; old revoked; no reuse-detection chain revocation.
219+- Login rate limit: per-key rolling 1 h window, `login_attempts_per_hour` (default 10); keys: email (login), `totp:{user}`, `forgot:{email}`. Limits successful-login lockout by design (DoS possible).
220+- Session policy: `max_sessions` cap (oldest revoked); sessions revoked on disable, delete, password reset, password change (others), sign-out-everywhere; `seen_at` throttled to 5 min.
221+- Disabled users: refused at login, at session resolve, at introspection.
222+- Open redirects: `safe_back` allows local paths and same-origin family URLs only; redirect_uri exact match.
223+- Email confirmation: email change requires both old and new addresses to confirm; GET confirmation pages do not mutate.
224+- Forgot password: always same response (no enumeration).
225+- Show-once secrets: client secrets and invite links shown once via in-memory shelf (`SHOWN_SECRETS`, 10-minute TTL, one-time ticket).
226+- Basic auth for cross-app endpoints checks client_id:secret against `oidc_clients`.
227+- Trusted proxy: client label from `nearest(1)` proxy (X-Forwarded-For).
228+- Photo upload: magic-byte sniffing; 5 MiB limit; BodyLimit.
229+- Audit: events logged for admin and account actions; introspection deliberately not logged; `log` never fails the caller.
230+- Pack archives: 0600 mode; unpack refuses unsafe paths; manifest version must be 1; tightens .toml, .keys, .key to 0600. Pack archive contains plaintext `<key>.key` (not encrypted).
231+- Not present: CSP, HSTS, X-Frame-Options, CSRF tokens (relies on SameSite=Lax + same-origin forms).
232+
233+## 7. im-client crate public API
234+
235+Crate: `crates/im-client` (features: `oidc` default on). Directory mirror always available.
236+
237+OIDC (`oidc` feature):
238+- `Config { issuer, client_id, client_secret, redirect_uri, cookie_name, cookie_key: [u8; 32] }`.
239+- `mount(builder, config)`: adds routes:
240+ - `GET /auth/login?next=`: sets PKCE pair cookie `{cookie_name}_pkce` (10 min); redirects to `/authorize` (scope openid profile email).
241+ - `GET /auth/callback`: state check; code exchange; id_token validation (JWKS cached 1 h, refetch on unknown kid; nonce check); introspection of app_session; sets app cookie. Errors redirect to `/?auth_error=...`.
242+ - `GET /auth/logout`: clears app cookie only (does not end the central session).
243+- `current_user(cx) -> Option<User>` where `User { sub, email, name, admin, photo_version }`; introspects per request.
244+- App session cookie: sealed JSON `{app_session, exp}`, MaxAge 30 days.
245+- Refresh tokens are ignored by the client (app session lasts 30 days).
246+- `Error` enum: `Http`, `Refused`, `Token`.
247+
248+Directory mirror (`directory` module):
249+- `DirectoryClient::new(issuer, client_id, client_secret)`; methods `directory()` (full list), `photo(sub)` (bytes), `open_stream()` returning `DirectoryStream` with `next()` yielding `DirectoryEvent`.
250+- `DirectoryMember { sub, email, name, admin, photo_version, timezone (default "UTC+03:00"), disabled }`.
251+- `DirectoryEvent { Profile(DirectoryMember), Revoked { sub } }`.
252+- `spawn_sync(client, on_member, on_resync)`: full pass, then stream; backoff 1 s doubling to 30 s cap; `on_resync` after reconnect.
253+- Oddity: module doc comment has a truncated sentence about `open_stream` and events.
254+
255+Example: `crates/im-client/examples/demo.rs`: smoke-test app at redirect `http://127.0.0.1:7656/auth/callback`, env IM_ISSUER / IM_CLIENT_ID / IM_CLIENT_SECRET, fixed DEV_COOKIE_KEY [42; 32]; routes `/` and `/me`.
256+
257+## 8. UI pages and style
258+
259+Pages (all server-rendered via topcoat `view!`):
260+- Signed out: `/` (login card), `/login`, `/login/totp`, `/invite/{token}`, `/forgot`, `/reset/{token}`, `/email/{token}`, `/enroll` (hardcoded English for these pages).
261+- Signed in: `/` landing (sections profile, sessions, apps, preferences, password), `/enroll`, `/people/{user_id}`, `/admin` (users, services, message, settings, logs, health; mail reached only via redirect).
262+- Errors shown via `error_text` and OK messages via `ok_text`; mapping in i18n.rs. Landing uses the user's language; `lang_of` returns English when signed out.
263+- Shell (`layout.rs` `shell`): `lang` attribute; `data-theme="dark"` only when user theme is dark; `data-ui` = instrument (default) or ledger. Google Fonts link loads IBM Plex Mono only (Newsreader used by ledger is not loaded; falls back to Georgia).
264+- Signed-in chrome: "im" mark with family flyout (sibling marks, health dots; CSS hover/focus).
265+- Avatar: photo or initial span; avatar viewer JS and XHR upload-progress JS (`avatar_script`).
266+- Soft navigation JS (`soft_nav_script`): fetch + DOM swap; `data-hard` opts out.
267+- Themed dropdown (`dropdown.rs`): replaces `select.auth-input`; search box when > 7 options or `data-search`; keyboard support; panel appended to body; only on signed-in pages.
268+- Logs fit-to-viewport script (`LOG_FIT_SCRIPT`), cookie `im_rows_logs`, clamp 5 to 200 rows, default 50.
269+- Session list: `<details>` modal cards; admin popovers use top-layer dialogs.
270+- Styles: `style/main.scss` and `style/_ledger.scss` compiled by `build.rs` (grass) to `crates/im-web/assets/main.css` (generated, 1304 lines, not in .gitignore). Tokens: --ink #1a1b1d, --accent #46557b, --font-sans system-ui, --font-mono IBM Plex Mono. Two data-ui languages (instrument: default; ledger: warm paper, serif display) plus dark variants. Responsive breakpoint at 720px.
271+- Assets served through topcoat `asset!("assets/main.css")` bundle.
272+
273+## 9. Oddities, bugs, half-finished items
274+
275+Security:
276+- `/email_change` leaks both confirmation links in the redirect query (`links=`) when mail sending fails.
277+- Any registered OIDC client can call `/family/register` for an unowned key and URL; im then GETs `{url}/healthz` from signed-in pages (SSRF-like probe).
278+- Any valid client can claim unowned service rows.
279+- `/photo`, `/directory`, `/family` are accessible to any registered client (no per-client scoping).
280+- Live `profile` frames are broadcast to all signed-in users (not filtered per viewer).
281+- No CSP, HSTS, X-Frame-Options; no CSRF tokens (SameSite=Lax + same-origin forms only).
282+- Signing key never rotated (`active` never set to 0).
283+- Refresh token reuse does not revoke the chain.
284+- Access token `scope` hardcoded to "openid profile email".
285+- Login rate limit can lock out a legitimate user (per-account DoS).
286+- Admin user email edit (`/admin/user_email`) bypasses two-sided confirmation (intentional rescue but unguarded).
287+- Admin cannot disable TOTP for locked-out users; no UI to remove 2FA.
288+- `login` allows sign-in without 2FA (2FA is optional for everyone).
289+- `verify_login` receives untrimmed email while rate-limit key is trimmed (inconsistent).
290+
291+Functional / consistency:
292+- `SESSION_DAYS` const (30) vs policy `session_days`: cookie Max-Age is the constant while DB expiry uses policy.
293+- `delete_user` does not delete `reset_links`, `email_changes`, `auth_codes`, `events`, or the photo file (orphans).
294+- Duplicate pending invites for the same email are allowed.
295+- `set_smtp` with empty host removes smtp keys but NOT `smtp_password`.
296+- `NavMail` i18n key is unused; the admin mail section is unreachable from the nav.
297+- `connected_chip` TR and EN branches are identical (trivial).
298+- Unused `let _ = issuer;` in the enroll page (dead code).
299+- `/enroll` revisit regenerates the TOTP secret for already-confirmed users (`set_totp` resets `totp_confirmed = 0`), which could lock out a user who has not yet re-scanned.
300+- Login, TOTP, invite, enroll, forgot, reset, and email-confirm pages are English-only even for Turkish users.
301+- `invite_mail` English only.
302+- im-client module doc has a truncated sentence.
303+- `store.rs` `migrate` comment for services.client_id sits under the timezone ALTER (comment placement mismatch).
304+- `migrations/` directory absent; schema is in `store.rs`.
305+- Pack archive holds plaintext `*.key` (unencrypted at-rest key).
306+- `connected_chip` and some i18n keys duplicated; `kind_word` lacks labels for several audit kinds (forgot_limited, user_demoted, services_updated, email_changed, email_change_asked); raw kind strings shown instead.
307+- `main.css` is a generated artifact and is not git-ignored.
308+- Discovery document omits introspection and end-session endpoints even though they exist.
309+- Deploy: GitHub Actions `.github/workflows/main.yml` runs `cargo test --workspace`, bundles assets, deploys over SSH to `$HOME/im` with `current` / `current.new` / `current.previous` swap; systemd unit `deploy/im.service` (`ExecStart=%h/im/current/im-web`, Restart=on-failure, WantedBy=default.target); health-check and rollback loop; served-stylesheet hash check.
310+- Release profile: fat LTO, codegen-units=1; `dist` profile: thin LTO, codegen-units=16.
311+- Coverage gaps in this survey: admin logs/health markup and test modules were surveyed, not read line-by-line; i18n full key list not enumerated; `main.css` not read in detail.