forge
Explore
Log in

Don't you dare go Hollow

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

Browse files at this commit

c997f70d1c6d78b61dc02098fe6f58b450ff4a74Ahmet Kaan GümüşRoot commit (no parents)
.gitignoreadded+7 -0
@@ -0,0 +1,7 @@
1+target/
2+config/in.toml
3+data/
4+*.db
5+*.db-wal
6+*.db-shm
7+*.key
Cargo.lockadded+3464 -0

Diff too large; view file

@@ -0,0 +1,3464 @@
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 = "darling"
604+version = "0.24.1"
605+source = "registry+https://github.com/rust-lang/crates.io-index"
606+checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
607+dependencies = [
608+ "darling_core",
609+ "darling_macro",
610+]
611+
612+[[package]]
613+name = "darling_core"
614+version = "0.24.1"
615+source = "registry+https://github.com/rust-lang/crates.io-index"
616+checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
617+dependencies = [
618+ "ident_case",
619+ "proc-macro2",
620+ "quote",
621+ "strsim",
622+ "syn 3.0.9",
623+]
624+
625+[[package]]
626+name = "darling_macro"
627+version = "0.24.1"
628+source = "registry+https://github.com/rust-lang/crates.io-index"
629+checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
630+dependencies = [
631+ "darling_core",
632+ "quote",
633+ "syn 3.0.9",
634+]
635+
636+[[package]]
637+name = "datasketches"
638+version = "0.2.0"
639+source = "registry+https://github.com/rust-lang/crates.io-index"
640+checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745"
641+
642+[[package]]
643+name = "deranged"
644+version = "0.5.9"
645+source = "registry+https://github.com/rust-lang/crates.io-index"
646+checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
647+dependencies = [
648+ "serde_core",
649+]
650+
651+[[package]]
652+name = "digest"
653+version = "0.11.3"
654+source = "registry+https://github.com/rust-lang/crates.io-index"
655+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
656+dependencies = [
657+ "block-buffer",
658+ "const-oid",
659+ "crypto-common 0.2.2",
660+ "ctutils",
661+]
662+
663+[[package]]
664+name = "displaydoc"
665+version = "0.2.7"
666+source = "registry+https://github.com/rust-lang/crates.io-index"
667+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
668+dependencies = [
669+ "proc-macro2",
670+ "quote",
671+ "syn 3.0.9",
672+]
673+
674+[[package]]
675+name = "downcast-rs"
676+version = "2.0.2"
677+source = "registry+https://github.com/rust-lang/crates.io-index"
678+checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc"
679+
680+[[package]]
681+name = "either"
682+version = "1.19.0"
683+source = "registry+https://github.com/rust-lang/crates.io-index"
684+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
685+
686+[[package]]
687+name = "env_filter"
688+version = "2.0.0"
689+source = "registry+https://github.com/rust-lang/crates.io-index"
690+checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217"
691+dependencies = [
692+ "log",
693+ "regex",
694+]
695+
696+[[package]]
697+name = "env_logger"
698+version = "0.11.11"
699+source = "registry+https://github.com/rust-lang/crates.io-index"
700+checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6"
701+dependencies = [
702+ "env_filter",
703+ "log",
704+]
705+
706+[[package]]
707+name = "equivalent"
708+version = "1.0.3"
709+source = "registry+https://github.com/rust-lang/crates.io-index"
710+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
711+
712+[[package]]
713+name = "erased-serde"
714+version = "0.4.11"
715+source = "registry+https://github.com/rust-lang/crates.io-index"
716+checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66"
717+dependencies = [
718+ "serde",
719+ "serde_core",
720+ "typeid",
721+]
722+
723+[[package]]
724+name = "errno"
725+version = "0.3.14"
726+source = "registry+https://github.com/rust-lang/crates.io-index"
727+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
728+dependencies = [
729+ "libc",
730+ "windows-sys 0.61.2",
731+]
732+
733+[[package]]
734+name = "fallible-iterator"
735+version = "0.3.0"
736+source = "registry+https://github.com/rust-lang/crates.io-index"
737+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
738+
739+[[package]]
740+name = "fastbloom"
741+version = "0.14.1"
742+source = "registry+https://github.com/rust-lang/crates.io-index"
743+checksum = "4e7f34442dbe69c60fe8eaf58a8cafff81a1f278816d8ab4db255b3bef4ac3c4"
744+dependencies = [
745+ "getrandom 0.3.4",
746+ "libm",
747+ "siphasher",
748+]
749+
750+[[package]]
751+name = "fastdivide"
752+version = "0.4.2"
753+source = "registry+https://github.com/rust-lang/crates.io-index"
754+checksum = "9afc2bd4d5a73106dd53d10d73d3401c2f32730ba2c0b93ddb888a8983680471"
755+
756+[[package]]
757+name = "fastrand"
758+version = "2.5.0"
759+source = "registry+https://github.com/rust-lang/crates.io-index"
760+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
761+
762+[[package]]
763+name = "find-msvc-tools"
764+version = "0.1.15"
765+source = "registry+https://github.com/rust-lang/crates.io-index"
766+checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
767+
768+[[package]]
769+name = "fnv"
770+version = "1.0.7"
771+source = "registry+https://github.com/rust-lang/crates.io-index"
772+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
773+
774+[[package]]
775+name = "foldhash"
776+version = "0.2.0"
777+source = "registry+https://github.com/rust-lang/crates.io-index"
778+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
779+
780+[[package]]
781+name = "fs4"
782+version = "0.13.1"
783+source = "registry+https://github.com/rust-lang/crates.io-index"
784+checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4"
785+dependencies = [
786+ "rustix 1.1.6",
787+ "windows-sys 0.59.0",
788+]
789+
790+[[package]]
791+name = "funty"
792+version = "2.0.0"
793+source = "registry+https://github.com/rust-lang/crates.io-index"
794+checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
795+
796+[[package]]
797+name = "futures-core"
798+version = "0.3.34"
799+source = "registry+https://github.com/rust-lang/crates.io-index"
800+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
801+
802+[[package]]
803+name = "futures-macro"
804+version = "0.3.34"
805+source = "registry+https://github.com/rust-lang/crates.io-index"
806+checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
807+dependencies = [
808+ "proc-macro2",
809+ "quote",
810+ "syn 3.0.9",
811+]
812+
813+[[package]]
814+name = "futures-task"
815+version = "0.3.34"
816+source = "registry+https://github.com/rust-lang/crates.io-index"
817+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
818+
819+[[package]]
820+name = "futures-util"
821+version = "0.3.34"
822+source = "registry+https://github.com/rust-lang/crates.io-index"
823+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
824+dependencies = [
825+ "futures-core",
826+ "futures-macro",
827+ "futures-task",
828+ "pin-project-lite",
829+ "slab",
830+]
831+
832+[[package]]
833+name = "genawaiter"
834+version = "0.99.1"
835+source = "registry+https://github.com/rust-lang/crates.io-index"
836+checksum = "c86bd0361bcbde39b13475e6e36cb24c329964aa2611be285289d1e4b751c1a0"
837+dependencies = [
838+ "genawaiter-macro",
839+]
840+
841+[[package]]
842+name = "genawaiter-macro"
843+version = "0.99.1"
844+source = "registry+https://github.com/rust-lang/crates.io-index"
845+checksum = "0b32dfe1fdfc0bbde1f22a5da25355514b5e450c33a6af6770884c8750aedfbc"
846+
847+[[package]]
848+name = "generator"
849+version = "0.8.11"
850+source = "registry+https://github.com/rust-lang/crates.io-index"
851+checksum = "1be81b31c9ce4caf7f3178eeb90662bb1864d3ad363ec6bdada3201adff19c37"
852+dependencies = [
853+ "cc",
854+ "cfg-if",
855+ "libc",
856+ "log",
857+ "rustversion",
858+ "windows-link",
859+ "windows-result",
860+]
861+
862+[[package]]
863+name = "generic-array"
864+version = "0.14.7"
865+source = "registry+https://github.com/rust-lang/crates.io-index"
866+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
867+dependencies = [
868+ "typenum",
869+ "version_check",
870+]
871+
872+[[package]]
873+name = "getrandom"
874+version = "0.2.17"
875+source = "registry+https://github.com/rust-lang/crates.io-index"
876+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
877+dependencies = [
878+ "cfg-if",
879+ "js-sys",
880+ "libc",
881+ "wasi",
882+ "wasm-bindgen",
883+]
884+
885+[[package]]
886+name = "getrandom"
887+version = "0.3.4"
888+source = "registry+https://github.com/rust-lang/crates.io-index"
889+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
890+dependencies = [
891+ "cfg-if",
892+ "js-sys",
893+ "libc",
894+ "r-efi 5.3.0",
895+ "wasip2",
896+ "wasm-bindgen",
897+]
898+
899+[[package]]
900+name = "getrandom"
901+version = "0.4.3"
902+source = "registry+https://github.com/rust-lang/crates.io-index"
903+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
904+dependencies = [
905+ "cfg-if",
906+ "js-sys",
907+ "libc",
908+ "r-efi 6.0.0",
909+ "rand_core 0.10.1",
910+ "wasm-bindgen",
911+]
912+
913+[[package]]
914+name = "ghash"
915+version = "0.5.1"
916+source = "registry+https://github.com/rust-lang/crates.io-index"
917+checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
918+dependencies = [
919+ "opaque-debug",
920+ "polyval",
921+]
922+
923+[[package]]
924+name = "glob"
925+version = "0.3.4"
926+source = "registry+https://github.com/rust-lang/crates.io-index"
927+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
928+
929+[[package]]
930+name = "hashbrown"
931+version = "0.16.1"
932+source = "registry+https://github.com/rust-lang/crates.io-index"
933+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
934+dependencies = [
935+ "allocator-api2 0.2.21",
936+ "equivalent",
937+ "foldhash",
938+]
939+
940+[[package]]
941+name = "hashbrown"
942+version = "0.17.1"
943+source = "registry+https://github.com/rust-lang/crates.io-index"
944+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
945+
946+[[package]]
947+name = "heck"
948+version = "0.5.0"
949+source = "registry+https://github.com/rust-lang/crates.io-index"
950+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
951+
952+[[package]]
953+name = "hermit-abi"
954+version = "0.5.3"
955+source = "registry+https://github.com/rust-lang/crates.io-index"
956+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
957+
958+[[package]]
959+name = "hex"
960+version = "0.4.3"
961+source = "registry+https://github.com/rust-lang/crates.io-index"
962+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
963+
964+[[package]]
965+name = "hmac"
966+version = "0.13.0"
967+source = "registry+https://github.com/rust-lang/crates.io-index"
968+checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
969+dependencies = [
970+ "digest",
971+]
972+
973+[[package]]
974+name = "home"
975+version = "0.5.12"
976+source = "registry+https://github.com/rust-lang/crates.io-index"
977+checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
978+dependencies = [
979+ "windows-sys 0.61.2",
980+]
981+
982+[[package]]
983+name = "htmlescape"
984+version = "0.3.1"
985+source = "registry+https://github.com/rust-lang/crates.io-index"
986+checksum = "e9025058dae765dee5070ec375f591e2ba14638c63feff74f13805a72e523163"
987+
988+[[package]]
989+name = "http"
990+version = "1.5.0"
991+source = "registry+https://github.com/rust-lang/crates.io-index"
992+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
993+dependencies = [
994+ "bytes",
995+ "itoa",
996+]
997+
998+[[package]]
999+name = "hybrid-array"
1000+version = "0.4.15"
1001+source = "registry+https://github.com/rust-lang/crates.io-index"
1002+checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
1003+dependencies = [
1004+ "typenum",
1005+]
1006+
1007+[[package]]
1008+name = "iana-time-zone"
1009+version = "0.1.65"
1010+source = "registry+https://github.com/rust-lang/crates.io-index"
1011+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
1012+dependencies = [
1013+ "android_system_properties",
1014+ "core-foundation-sys",
1015+ "iana-time-zone-haiku",
1016+ "js-sys",
1017+ "log",
1018+ "wasm-bindgen",
1019+ "windows-core",
1020+]
1021+
1022+[[package]]
1023+name = "iana-time-zone-haiku"
1024+version = "0.1.2"
1025+source = "registry+https://github.com/rust-lang/crates.io-index"
1026+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
1027+dependencies = [
1028+ "cc",
1029+]
1030+
1031+[[package]]
1032+name = "icu_collator"
1033+version = "2.4.0"
1034+source = "registry+https://github.com/rust-lang/crates.io-index"
1035+checksum = "24cb0205c419b2036da3f9082964905d6849b3f2130dd4a517940c45899a544b"
1036+dependencies = [
1037+ "icu_collator_data",
1038+ "icu_collections",
1039+ "icu_locale_core",
1040+ "icu_locale_fallback",
1041+ "icu_normalizer",
1042+ "icu_properties",
1043+ "icu_provider",
1044+ "smallvec",
1045+ "utf16_iter",
1046+ "utf8_iter",
1047+ "zerovec",
1048+]
1049+
1050+[[package]]
1051+name = "icu_collator_data"
1052+version = "2.4.0"
1053+source = "registry+https://github.com/rust-lang/crates.io-index"
1054+checksum = "183f47e821a327661c1ebe152f61d5b6c2000010d228cadbbf226e0e2b8c2634"
1055+
1056+[[package]]
1057+name = "icu_collections"
1058+version = "2.4.0"
1059+source = "registry+https://github.com/rust-lang/crates.io-index"
1060+checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd"
1061+dependencies = [
1062+ "displaydoc",
1063+ "potential_utf",
1064+ "utf8_iter",
1065+ "yoke",
1066+ "zerofrom",
1067+ "zerovec",
1068+]
1069+
1070+[[package]]
1071+name = "icu_locale"
1072+version = "2.4.0"
1073+source = "registry+https://github.com/rust-lang/crates.io-index"
1074+checksum = "fe8fa57bcddc15cb921582ee5259c5b77da39f946f188ca5213fad24d9241236"
1075+dependencies = [
1076+ "icu_collections",
1077+ "icu_locale_core",
1078+ "icu_locale_data",
1079+ "icu_locale_fallback",
1080+ "icu_provider",
1081+ "tinystr",
1082+ "zerovec",
1083+]
1084+
1085+[[package]]
1086+name = "icu_locale_core"
1087+version = "2.4.0"
1088+source = "registry+https://github.com/rust-lang/crates.io-index"
1089+checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0"
1090+dependencies = [
1091+ "displaydoc",
1092+ "litemap",
1093+ "serde",
1094+ "tinystr",
1095+ "writeable",
1096+ "zerovec",
1097+]
1098+
1099+[[package]]
1100+name = "icu_locale_data"
1101+version = "2.4.0"
1102+source = "registry+https://github.com/rust-lang/crates.io-index"
1103+checksum = "a64014dac577a11d8d2cee48517c73c1984bd72ab11031e934269bd3cefb2ad9"
1104+
1105+[[package]]
1106+name = "icu_locale_fallback"
1107+version = "2.4.0"
1108+source = "registry+https://github.com/rust-lang/crates.io-index"
1109+checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c"
1110+dependencies = [
1111+ "icu_locale_core",
1112+ "icu_locale_fallback_data",
1113+ "icu_provider",
1114+ "potential_utf",
1115+ "tinystr",
1116+ "zerovec",
1117+]
1118+
1119+[[package]]
1120+name = "icu_locale_fallback_data"
1121+version = "2.4.0"
1122+source = "registry+https://github.com/rust-lang/crates.io-index"
1123+checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c"
1124+
1125+[[package]]
1126+name = "icu_normalizer"
1127+version = "2.4.0"
1128+source = "registry+https://github.com/rust-lang/crates.io-index"
1129+checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599"
1130+dependencies = [
1131+ "icu_collections",
1132+ "icu_normalizer_data",
1133+ "icu_properties",
1134+ "icu_provider",
1135+ "smallvec",
1136+ "utf16_iter",
1137+ "utf8_iter",
1138+ "write16",
1139+ "zerovec",
1140+]
1141+
1142+[[package]]
1143+name = "icu_normalizer_data"
1144+version = "2.4.0"
1145+source = "registry+https://github.com/rust-lang/crates.io-index"
1146+checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc"
1147+
1148+[[package]]
1149+name = "icu_properties"
1150+version = "2.4.0"
1151+source = "registry+https://github.com/rust-lang/crates.io-index"
1152+checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f"
1153+dependencies = [
1154+ "displaydoc",
1155+ "icu_collections",
1156+ "icu_locale_core",
1157+ "icu_properties_data",
1158+ "icu_provider",
1159+ "zerotrie",
1160+ "zerovec",
1161+]
1162+
1163+[[package]]
1164+name = "icu_properties_data"
1165+version = "2.4.0"
1166+source = "registry+https://github.com/rust-lang/crates.io-index"
1167+checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf"
1168+
1169+[[package]]
1170+name = "icu_provider"
1171+version = "2.4.0"
1172+source = "registry+https://github.com/rust-lang/crates.io-index"
1173+checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514"
1174+dependencies = [
1175+ "displaydoc",
1176+ "icu_locale_core",
1177+ "serde",
1178+ "stable_deref_trait",
1179+ "writeable",
1180+ "yoke",
1181+ "zerofrom",
1182+ "zerotrie",
1183+ "zerovec",
1184+]
1185+
1186+[[package]]
1187+name = "ident_case"
1188+version = "1.0.1"
1189+source = "registry+https://github.com/rust-lang/crates.io-index"
1190+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
1191+
1192+[[package]]
1193+name = "in-core"
1194+version = "0.1.0"
1195+dependencies = [
1196+ "argon2",
1197+ "base64 0.23.1",
1198+ "chacha20poly1305",
1199+ "hex",
1200+ "hmac",
1201+ "ipnet",
1202+ "rand 0.10.3",
1203+ "serde",
1204+ "serde_json",
1205+ "sha2",
1206+ "subtle",
1207+ "tempfile",
1208+ "thiserror",
1209+ "time",
1210+ "tokio",
1211+ "toml",
1212+ "tracing",
1213+ "turso",
1214+ "ulid",
1215+]
1216+
1217+[[package]]
1218+name = "in-web"
1219+version = "0.1.0"
1220+
1221+[[package]]
1222+name = "indexmap"
1223+version = "2.14.2"
1224+source = "registry+https://github.com/rust-lang/crates.io-index"
1225+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
1226+dependencies = [
1227+ "equivalent",
1228+ "hashbrown 0.17.1",
1229+]
1230+
1231+[[package]]
1232+name = "inout"
1233+version = "0.1.4"
1234+source = "registry+https://github.com/rust-lang/crates.io-index"
1235+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
1236+dependencies = [
1237+ "generic-array",
1238+]
1239+
1240+[[package]]
1241+name = "inout"
1242+version = "0.2.5"
1243+source = "registry+https://github.com/rust-lang/crates.io-index"
1244+checksum = "3b5cf4372d022092674a83b8febf5865f7a573cc0c5baec5e49c879b6a20978f"
1245+dependencies = [
1246+ "hybrid-array",
1247+]
1248+
1249+[[package]]
1250+name = "intrusive-collections"
1251+version = "0.9.7"
1252+source = "registry+https://github.com/rust-lang/crates.io-index"
1253+checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86"
1254+dependencies = [
1255+ "memoffset",
1256+]
1257+
1258+[[package]]
1259+name = "inventory"
1260+version = "0.3.25"
1261+source = "registry+https://github.com/rust-lang/crates.io-index"
1262+checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c"
1263+dependencies = [
1264+ "rustversion",
1265+]
1266+
1267+[[package]]
1268+name = "io-uring"
1269+version = "0.7.15"
1270+source = "registry+https://github.com/rust-lang/crates.io-index"
1271+checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb"
1272+dependencies = [
1273+ "bitflags",
1274+ "cfg-if",
1275+ "libc",
1276+]
1277+
1278+[[package]]
1279+name = "ipnet"
1280+version = "2.12.2"
1281+source = "registry+https://github.com/rust-lang/crates.io-index"
1282+checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
1283+
1284+[[package]]
1285+name = "itertools"
1286+version = "0.12.1"
1287+source = "registry+https://github.com/rust-lang/crates.io-index"
1288+checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"
1289+dependencies = [
1290+ "either",
1291+]
1292+
1293+[[package]]
1294+name = "itertools"
1295+version = "0.14.0"
1296+source = "registry+https://github.com/rust-lang/crates.io-index"
1297+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
1298+dependencies = [
1299+ "either",
1300+]
1301+
1302+[[package]]
1303+name = "itoa"
1304+version = "1.0.18"
1305+source = "registry+https://github.com/rust-lang/crates.io-index"
1306+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
1307+
1308+[[package]]
1309+name = "jobserver"
1310+version = "0.1.35"
1311+source = "registry+https://github.com/rust-lang/crates.io-index"
1312+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
1313+dependencies = [
1314+ "getrandom 0.4.3",
1315+ "libc",
1316+]
1317+
1318+[[package]]
1319+name = "js-sys"
1320+version = "0.3.106"
1321+source = "registry+https://github.com/rust-lang/crates.io-index"
1322+checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
1323+dependencies = [
1324+ "cfg-if",
1325+ "futures-util",
1326+ "wasm-bindgen",
1327+]
1328+
1329+[[package]]
1330+name = "lazy_static"
1331+version = "1.5.1"
1332+source = "registry+https://github.com/rust-lang/crates.io-index"
1333+checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
1334+
1335+[[package]]
1336+name = "lazycell"
1337+version = "1.3.0"
1338+source = "registry+https://github.com/rust-lang/crates.io-index"
1339+checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55"
1340+
1341+[[package]]
1342+name = "levenshtein_automata"
1343+version = "0.2.1"
1344+source = "registry+https://github.com/rust-lang/crates.io-index"
1345+checksum = "0c2cdeb66e45e9f36bfad5bbdb4d2384e70936afbee843c6f6543f0c551ebb25"
1346+
1347+[[package]]
1348+name = "libc"
1349+version = "0.2.191"
1350+source = "registry+https://github.com/rust-lang/crates.io-index"
1351+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
1352+
1353+[[package]]
1354+name = "libloading"
1355+version = "0.8.9"
1356+source = "registry+https://github.com/rust-lang/crates.io-index"
1357+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
1358+dependencies = [
1359+ "cfg-if",
1360+ "windows-link",
1361+]
1362+
1363+[[package]]
1364+name = "libm"
1365+version = "0.2.16"
1366+source = "registry+https://github.com/rust-lang/crates.io-index"
1367+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
1368+
1369+[[package]]
1370+name = "libmimalloc-sys"
1371+version = "0.1.49"
1372+source = "registry+https://github.com/rust-lang/crates.io-index"
1373+checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9"
1374+dependencies = [
1375+ "cc",
1376+]
1377+
1378+[[package]]
1379+name = "linkme"
1380+version = "0.3.37"
1381+source = "registry+https://github.com/rust-lang/crates.io-index"
1382+checksum = "3045e122bd98aef8ec3ad58ce84f0791f64e70163d1a02710af4aa11a4d54cc5"
1383+dependencies = [
1384+ "linkme-impl",
1385+]
1386+
1387+[[package]]
1388+name = "linkme-impl"
1389+version = "0.3.37"
1390+source = "registry+https://github.com/rust-lang/crates.io-index"
1391+checksum = "77060ebe535362c3da75682cd17b0431017b6e7c5661e714fc69a7ad017d1301"
1392+dependencies = [
1393+ "proc-macro2",
1394+ "quote",
1395+ "syn 3.0.9",
1396+]
1397+
1398+[[package]]
1399+name = "linux-raw-sys"
1400+version = "0.4.15"
1401+source = "registry+https://github.com/rust-lang/crates.io-index"
1402+checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
1403+
1404+[[package]]
1405+name = "linux-raw-sys"
1406+version = "0.12.1"
1407+source = "registry+https://github.com/rust-lang/crates.io-index"
1408+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
1409+
1410+[[package]]
1411+name = "litemap"
1412+version = "0.8.3"
1413+source = "registry+https://github.com/rust-lang/crates.io-index"
1414+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
1415+
1416+[[package]]
1417+name = "lock_api"
1418+version = "0.4.14"
1419+source = "registry+https://github.com/rust-lang/crates.io-index"
1420+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
1421+dependencies = [
1422+ "scopeguard",
1423+]
1424+
1425+[[package]]
1426+name = "log"
1427+version = "0.4.34"
1428+source = "registry+https://github.com/rust-lang/crates.io-index"
1429+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
1430+
1431+[[package]]
1432+name = "loom"
1433+version = "0.7.2"
1434+source = "registry+https://github.com/rust-lang/crates.io-index"
1435+checksum = "419e0dc8046cb947daa77eb95ae174acfbddb7673b4151f56d1eed8e93fbfaca"
1436+dependencies = [
1437+ "cfg-if",
1438+ "generator",
1439+ "scoped-tls",
1440+ "tracing",
1441+ "tracing-subscriber",
1442+]
1443+
1444+[[package]]
1445+name = "lru"
1446+version = "0.16.4"
1447+source = "registry+https://github.com/rust-lang/crates.io-index"
1448+checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39"
1449+dependencies = [
1450+ "hashbrown 0.16.1",
1451+]
1452+
1453+[[package]]
1454+name = "lz4_flex"
1455+version = "0.13.1"
1456+source = "registry+https://github.com/rust-lang/crates.io-index"
1457+checksum = "7ef0d4ed8669f8f8826eb00dc878084aa8f253506c4fd5e8f58f5bce72ddb97e"
1458+
1459+[[package]]
1460+name = "matchers"
1461+version = "0.2.0"
1462+source = "registry+https://github.com/rust-lang/crates.io-index"
1463+checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
1464+dependencies = [
1465+ "regex-automata",
1466+]
1467+
1468+[[package]]
1469+name = "measure_time"
1470+version = "0.9.0"
1471+source = "registry+https://github.com/rust-lang/crates.io-index"
1472+checksum = "51c55d61e72fc3ab704396c5fa16f4c184db37978ae4e94ca8959693a235fc0e"
1473+dependencies = [
1474+ "log",
1475+]
1476+
1477+[[package]]
1478+name = "memchr"
1479+version = "2.8.3"
1480+source = "registry+https://github.com/rust-lang/crates.io-index"
1481+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
1482+
1483+[[package]]
1484+name = "memmap2"
1485+version = "0.9.12"
1486+source = "registry+https://github.com/rust-lang/crates.io-index"
1487+checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157"
1488+dependencies = [
1489+ "libc",
1490+]
1491+
1492+[[package]]
1493+name = "memoffset"
1494+version = "0.9.1"
1495+source = "registry+https://github.com/rust-lang/crates.io-index"
1496+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
1497+dependencies = [
1498+ "autocfg",
1499+]
1500+
1501+[[package]]
1502+name = "miette"
1503+version = "7.6.0"
1504+source = "registry+https://github.com/rust-lang/crates.io-index"
1505+checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7"
1506+dependencies = [
1507+ "cfg-if",
1508+ "miette-derive",
1509+ "unicode-width",
1510+]
1511+
1512+[[package]]
1513+name = "miette-derive"
1514+version = "7.6.0"
1515+source = "registry+https://github.com/rust-lang/crates.io-index"
1516+checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b"
1517+dependencies = [
1518+ "proc-macro2",
1519+ "quote",
1520+ "syn 2.0.119",
1521+]
1522+
1523+[[package]]
1524+name = "mimalloc"
1525+version = "0.1.52"
1526+source = "registry+https://github.com/rust-lang/crates.io-index"
1527+checksum = "2d4139bb28d14ad1facf21d5eb8825051b326e172d216b39f6d31df53cc97862"
1528+dependencies = [
1529+ "libmimalloc-sys",
1530+]
1531+
1532+[[package]]
1533+name = "minimal-lexical"
1534+version = "0.2.1"
1535+source = "registry+https://github.com/rust-lang/crates.io-index"
1536+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
1537+
1538+[[package]]
1539+name = "murmurhash32"
1540+version = "0.3.1"
1541+source = "registry+https://github.com/rust-lang/crates.io-index"
1542+checksum = "2195bf6aa996a481483b29d62a7663eed3fe39600c460e323f8ff41e90bdd89b"
1543+
1544+[[package]]
1545+name = "nom"
1546+version = "7.1.3"
1547+source = "registry+https://github.com/rust-lang/crates.io-index"
1548+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
1549+dependencies = [
1550+ "memchr",
1551+ "minimal-lexical",
1552+]
1553+
1554+[[package]]
1555+name = "nu-ansi-term"
1556+version = "0.50.3"
1557+source = "registry+https://github.com/rust-lang/crates.io-index"
1558+checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
1559+dependencies = [
1560+ "windows-sys 0.61.2",
1561+]
1562+
1563+[[package]]
1564+name = "num-bigint"
1565+version = "0.4.8"
1566+source = "registry+https://github.com/rust-lang/crates.io-index"
1567+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
1568+dependencies = [
1569+ "num-integer",
1570+ "num-traits",
1571+]
1572+
1573+[[package]]
1574+name = "num-conv"
1575+version = "0.2.2"
1576+source = "registry+https://github.com/rust-lang/crates.io-index"
1577+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
1578+
1579+[[package]]
1580+name = "num-integer"
1581+version = "0.1.47"
1582+source = "registry+https://github.com/rust-lang/crates.io-index"
1583+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
1584+dependencies = [
1585+ "num-traits",
1586+]
1587+
1588+[[package]]
1589+name = "num-traits"
1590+version = "0.2.19"
1591+source = "registry+https://github.com/rust-lang/crates.io-index"
1592+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
1593+dependencies = [
1594+ "autocfg",
1595+]
1596+
1597+[[package]]
1598+name = "once_cell"
1599+version = "1.21.4"
1600+source = "registry+https://github.com/rust-lang/crates.io-index"
1601+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
1602+
1603+[[package]]
1604+name = "oneshot"
1605+version = "0.1.13"
1606+source = "registry+https://github.com/rust-lang/crates.io-index"
1607+checksum = "269bca4c2591a28585d6bf10d9ed0332b7d76900a1b02bec41bdc3a2cdcda107"
1608+
1609+[[package]]
1610+name = "opaque-debug"
1611+version = "0.3.1"
1612+source = "registry+https://github.com/rust-lang/crates.io-index"
1613+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
1614+
1615+[[package]]
1616+name = "ordered-float"
1617+version = "5.5.1"
1618+source = "registry+https://github.com/rust-lang/crates.io-index"
1619+checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab"
1620+dependencies = [
1621+ "num-traits",
1622+]
1623+
1624+[[package]]
1625+name = "ownedbytes"
1626+version = "0.9.0"
1627+source = "registry+https://github.com/rust-lang/crates.io-index"
1628+checksum = "2fbd56f7631767e61784dc43f8580f403f4475bd4aaa4da003e6295e1bab4a7e"
1629+dependencies = [
1630+ "stable_deref_trait",
1631+]
1632+
1633+[[package]]
1634+name = "owo-colors"
1635+version = "3.5.0"
1636+source = "registry+https://github.com/rust-lang/crates.io-index"
1637+checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f"
1638+
1639+[[package]]
1640+name = "pack1"
1641+version = "1.1.0"
1642+source = "registry+https://github.com/rust-lang/crates.io-index"
1643+checksum = "e3b7bb0ecf2e447b1f20ee94ee79ef6eed1e9d4b3c36ce1903b9dea3bf205523"
1644+dependencies = [
1645+ "bytemuck",
1646+]
1647+
1648+[[package]]
1649+name = "parking_lot"
1650+version = "0.12.5"
1651+source = "registry+https://github.com/rust-lang/crates.io-index"
1652+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
1653+dependencies = [
1654+ "lock_api",
1655+ "parking_lot_core",
1656+]
1657+
1658+[[package]]
1659+name = "parking_lot_core"
1660+version = "0.9.12"
1661+source = "registry+https://github.com/rust-lang/crates.io-index"
1662+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
1663+dependencies = [
1664+ "cfg-if",
1665+ "libc",
1666+ "redox_syscall",
1667+ "smallvec",
1668+ "windows-link",
1669+]
1670+
1671+[[package]]
1672+name = "password-hash"
1673+version = "0.6.1"
1674+source = "registry+https://github.com/rust-lang/crates.io-index"
1675+checksum = "aab41826031698d6ffcd9cff78ef56ef998e39dc7e5067cdfebe373842d4723b"
1676+dependencies = [
1677+ "getrandom 0.4.3",
1678+ "phc",
1679+]
1680+
1681+[[package]]
1682+name = "pastey"
1683+version = "0.2.3"
1684+source = "registry+https://github.com/rust-lang/crates.io-index"
1685+checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
1686+
1687+[[package]]
1688+name = "phc"
1689+version = "0.6.1"
1690+source = "registry+https://github.com/rust-lang/crates.io-index"
1691+checksum = "44dc769b75f93afdddd8c7fa12d685292ddeff1e66f7f0f3a234cf1818afe892"
1692+dependencies = [
1693+ "base64ct",
1694+ "ctutils",
1695+ "getrandom 0.4.3",
1696+]
1697+
1698+[[package]]
1699+name = "pin-project-lite"
1700+version = "0.2.17"
1701+source = "registry+https://github.com/rust-lang/crates.io-index"
1702+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
1703+
1704+[[package]]
1705+name = "pkg-config"
1706+version = "0.3.34"
1707+source = "registry+https://github.com/rust-lang/crates.io-index"
1708+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
1709+
1710+[[package]]
1711+name = "polling"
1712+version = "3.11.0"
1713+source = "registry+https://github.com/rust-lang/crates.io-index"
1714+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
1715+dependencies = [
1716+ "cfg-if",
1717+ "concurrent-queue",
1718+ "hermit-abi",
1719+ "pin-project-lite",
1720+ "rustix 1.1.6",
1721+ "windows-sys 0.61.2",
1722+]
1723+
1724+[[package]]
1725+name = "poly1305"
1726+version = "0.9.1"
1727+source = "registry+https://github.com/rust-lang/crates.io-index"
1728+checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"
1729+dependencies = [
1730+ "cpufeatures 0.3.1",
1731+ "universal-hash 0.6.1",
1732+]
1733+
1734+[[package]]
1735+name = "polyval"
1736+version = "0.6.2"
1737+source = "registry+https://github.com/rust-lang/crates.io-index"
1738+checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"
1739+dependencies = [
1740+ "cfg-if",
1741+ "cpufeatures 0.2.17",
1742+ "opaque-debug",
1743+ "universal-hash 0.5.1",
1744+]
1745+
1746+[[package]]
1747+name = "potential_utf"
1748+version = "0.1.6"
1749+source = "registry+https://github.com/rust-lang/crates.io-index"
1750+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
1751+dependencies = [
1752+ "serde_core",
1753+ "writeable",
1754+ "zerovec",
1755+]
1756+
1757+[[package]]
1758+name = "powerfmt"
1759+version = "0.2.1"
1760+source = "registry+https://github.com/rust-lang/crates.io-index"
1761+checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
1762+
1763+[[package]]
1764+name = "ppv-lite86"
1765+version = "0.2.21"
1766+source = "registry+https://github.com/rust-lang/crates.io-index"
1767+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
1768+dependencies = [
1769+ "zerocopy",
1770+]
1771+
1772+[[package]]
1773+name = "prettyplease"
1774+version = "0.2.37"
1775+source = "registry+https://github.com/rust-lang/crates.io-index"
1776+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
1777+dependencies = [
1778+ "proc-macro2",
1779+ "syn 2.0.119",
1780+]
1781+
1782+[[package]]
1783+name = "prettyplease"
1784+version = "0.3.0"
1785+source = "registry+https://github.com/rust-lang/crates.io-index"
1786+checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0"
1787+dependencies = [
1788+ "proc-macro2",
1789+ "syn 3.0.9",
1790+]
1791+
1792+[[package]]
1793+name = "proc-macro2"
1794+version = "1.0.107"
1795+source = "registry+https://github.com/rust-lang/crates.io-index"
1796+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
1797+dependencies = [
1798+ "unicode-ident",
1799+]
1800+
1801+[[package]]
1802+name = "prost"
1803+version = "0.14.4"
1804+source = "registry+https://github.com/rust-lang/crates.io-index"
1805+checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"
1806+dependencies = [
1807+ "bytes",
1808+ "prost-derive",
1809+]
1810+
1811+[[package]]
1812+name = "prost-derive"
1813+version = "0.14.4"
1814+source = "registry+https://github.com/rust-lang/crates.io-index"
1815+checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"
1816+dependencies = [
1817+ "anyhow",
1818+ "itertools 0.14.0",
1819+ "proc-macro2",
1820+ "quote",
1821+ "syn 2.0.119",
1822+]
1823+
1824+[[package]]
1825+name = "quote"
1826+version = "1.0.47"
1827+source = "registry+https://github.com/rust-lang/crates.io-index"
1828+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
1829+dependencies = [
1830+ "proc-macro2",
1831+]
1832+
1833+[[package]]
1834+name = "r-efi"
1835+version = "5.3.0"
1836+source = "registry+https://github.com/rust-lang/crates.io-index"
1837+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
1838+
1839+[[package]]
1840+name = "r-efi"
1841+version = "6.0.0"
1842+source = "registry+https://github.com/rust-lang/crates.io-index"
1843+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
1844+
1845+[[package]]
1846+name = "radium"
1847+version = "0.7.0"
1848+source = "registry+https://github.com/rust-lang/crates.io-index"
1849+checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"
1850+
1851+[[package]]
1852+name = "rand"
1853+version = "0.8.8"
1854+source = "registry+https://github.com/rust-lang/crates.io-index"
1855+checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
1856+dependencies = [
1857+ "libc",
1858+ "rand_chacha 0.3.1",
1859+ "rand_core 0.6.4",
1860+]
1861+
1862+[[package]]
1863+name = "rand"
1864+version = "0.9.5"
1865+source = "registry+https://github.com/rust-lang/crates.io-index"
1866+checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
1867+dependencies = [
1868+ "rand_chacha 0.9.0",
1869+ "rand_core 0.9.5",
1870+]
1871+
1872+[[package]]
1873+name = "rand"
1874+version = "0.10.3"
1875+source = "registry+https://github.com/rust-lang/crates.io-index"
1876+checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
1877+dependencies = [
1878+ "chacha20",
1879+ "getrandom 0.4.3",
1880+ "rand_core 0.10.1",
1881+]
1882+
1883+[[package]]
1884+name = "rand_chacha"
1885+version = "0.3.1"
1886+source = "registry+https://github.com/rust-lang/crates.io-index"
1887+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
1888+dependencies = [
1889+ "ppv-lite86",
1890+ "rand_core 0.6.4",
1891+]
1892+
1893+[[package]]
1894+name = "rand_chacha"
1895+version = "0.9.0"
1896+source = "registry+https://github.com/rust-lang/crates.io-index"
1897+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
1898+dependencies = [
1899+ "ppv-lite86",
1900+ "rand_core 0.9.5",
1901+]
1902+
1903+[[package]]
1904+name = "rand_core"
1905+version = "0.6.4"
1906+source = "registry+https://github.com/rust-lang/crates.io-index"
1907+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
1908+dependencies = [
1909+ "getrandom 0.2.17",
1910+]
1911+
1912+[[package]]
1913+name = "rand_core"
1914+version = "0.9.5"
1915+source = "registry+https://github.com/rust-lang/crates.io-index"
1916+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
1917+dependencies = [
1918+ "getrandom 0.3.4",
1919+]
1920+
1921+[[package]]
1922+name = "rand_core"
1923+version = "0.10.1"
1924+source = "registry+https://github.com/rust-lang/crates.io-index"
1925+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
1926+
1927+[[package]]
1928+name = "rand_pcg"
1929+version = "0.3.1"
1930+source = "registry+https://github.com/rust-lang/crates.io-index"
1931+checksum = "59cad018caf63deb318e5a4586d99a24424a364f40f1e5778c29aca23f4fc73e"
1932+dependencies = [
1933+ "rand_core 0.6.4",
1934+]
1935+
1936+[[package]]
1937+name = "rapidhash"
1938+version = "4.5.1"
1939+source = "registry+https://github.com/rust-lang/crates.io-index"
1940+checksum = "5da7e78a036ce858e8d55b7e7dc8ba3a88b78350fd2155d3591bbd966b58589e"
1941+dependencies = [
1942+ "rustversion",
1943+]
1944+
1945+[[package]]
1946+name = "rayon"
1947+version = "1.12.0"
1948+source = "registry+https://github.com/rust-lang/crates.io-index"
1949+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
1950+dependencies = [
1951+ "either",
1952+ "rayon-core",
1953+]
1954+
1955+[[package]]
1956+name = "rayon-core"
1957+version = "1.13.0"
1958+source = "registry+https://github.com/rust-lang/crates.io-index"
1959+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
1960+dependencies = [
1961+ "crossbeam-deque",
1962+ "crossbeam-utils",
1963+]
1964+
1965+[[package]]
1966+name = "redox_syscall"
1967+version = "0.5.18"
1968+source = "registry+https://github.com/rust-lang/crates.io-index"
1969+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
1970+dependencies = [
1971+ "bitflags",
1972+]
1973+
1974+[[package]]
1975+name = "regex"
1976+version = "1.13.1"
1977+source = "registry+https://github.com/rust-lang/crates.io-index"
1978+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
1979+dependencies = [
1980+ "aho-corasick",
1981+ "memchr",
1982+ "regex-automata",
1983+ "regex-syntax",
1984+]
1985+
1986+[[package]]
1987+name = "regex-automata"
1988+version = "0.4.18"
1989+source = "registry+https://github.com/rust-lang/crates.io-index"
1990+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
1991+dependencies = [
1992+ "aho-corasick",
1993+ "memchr",
1994+ "regex-syntax",
1995+]
1996+
1997+[[package]]
1998+name = "regex-syntax"
1999+version = "0.8.11"
2000+source = "registry+https://github.com/rust-lang/crates.io-index"
Cargo.tomladded+62 -0
@@ -0,0 +1,62 @@
1+[workspace]
2+resolver = "3"
3+members = [
4+ "crates/in-core",
5+ "crates/in-web",
6+]
7+
8+[workspace.package]
9+version = "0.1.0"
10+edition = "2024"
11+license = "AGPL-3.0-or-later"
12+
13+[workspace.lints.rust]
14+unsafe_code = "forbid"
15+
16+# Development builds keep file:line in backtraces but drop variable info.
17+[profile.dev]
18+debug = "line-tables-only"
19+
20+# Hashing and sealing run on every request path that touches secrets. Unoptimized they are slow, and
21+# release builds are unaffected.
22+[profile.dev.package.argon2]
23+opt-level = 3
24+
25+[profile.dev.package.sha2]
26+opt-level = 3
27+
28+[profile.dev.package.chacha20poly1305]
29+opt-level = 3
30+
31+# The store runs migrations through the Turso engine on every fresh database; unoptimized it is slow.
32+[profile.dev.package.turso_core]
33+opt-level = 3
34+
35+[profile.dev.package.turso_parser]
36+opt-level = 3
37+
38+[profile.release]
39+lto = true
40+codegen-units = 1
41+
42+[workspace.dependencies]
43+argon2 = "0.6.0"
44+base64 = "0.23.1"
45+chacha20poly1305 = "0.11.0"
46+hex = "0.4.3"
47+hmac = "0.13.0"
48+ipnet = "2.12.2"
49+rand = "0.10.3"
50+serde = "1.0.229"
51+serde_json = "1.0.154"
52+sha2 = "0.11.1"
53+subtle = "2.6.1"
54+tempfile = "3.27.0"
55+thiserror = "2.0.21"
56+time = "0.3.55"
57+tokio = "1.54.1"
58+toml = "1.1.8"
59+tracing = "0.1.44"
60+turso = "0.8.3"
61+ulid = "3.0.0"
62+
config/in.example.tomladded+37 -0
@@ -0,0 +1,37 @@
1+# in: file configuration. Copy this to config/in.toml, or let `in` create it on first run.
2+# Secrets are never written here. The OIDC client secret and the S3 keys are read from files or
3+# entered in the admin UI.
4+
5+# Database file (Turso). Relative paths are relative to the working directory.
6+database = "data/in.db"
7+# Directory for blobs, staging files, the instance key (in.key) and caches. Created with mode 0700.
8+data_dir = "data"
9+# Address the HTTP server binds to. Put a TLS reverse proxy in front of it for public use.
10+listen = "127.0.0.1:7655"
11+# Public URL of this instance, with no trailing slash. An https URL turns on Secure cookies and HSTS.
12+base_url = "http://127.0.0.1:7655"
13+# Proxies whose X-Forwarded-For header is believed for client addresses. CIDR ranges or bare addresses.
14+trusted_proxies = []
15+
16+# Sign-in through im. Placeholder for development: point issuer at the im instance you run.
17+[oidc]
18+issuer = "http://127.0.0.1:7600"
19+client_id = "in"
20+
21+[storage]
22+backend = "local"
23+
24+# To store blobs in an S3-compatible bucket instead, use backend = "s3" and this table:
25+# [storage.s3]
26+# endpoint = "https://<account>.r2.cloudflarestorage.com" # omit for AWS
27+# region = "auto"
28+# bucket = "in-blobs"
29+# access_key_id_file = "/etc/in/s3_access_key_id"
30+# secret_access_key_file = "/etc/in/s3_secret_access_key"
31+
32+# Optional scheduled backups (a snapshot plus a blob manifest). Omit this table to disable them.
33+# [backup]
34+# dir = "data/backups"
35+# interval_hours = 24
36+# keep = 7
37+# healthcheck_url = "https://hc-ping.example/uuid"
crates/in-core/Cargo.tomladded+33 -0
@@ -0,0 +1,33 @@
1+[package]
2+name = "in-core"
3+description = "Domain types, store, migrations, config and security primitives for in"
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+publish = false
8+
9+[dependencies]
10+argon2.workspace = true
11+base64.workspace = true
12+chacha20poly1305.workspace = true
13+hex.workspace = true
14+hmac.workspace = true
15+ipnet.workspace = true
16+rand.workspace = true
17+serde = { workspace = true, features = ["derive"] }
18+serde_json.workspace = true
19+sha2.workspace = true
20+subtle.workspace = true
21+thiserror.workspace = true
22+time = { workspace = true, features = ["formatting", "parsing", "macros"] }
23+tokio = { workspace = true, features = ["sync", "rt", "macros", "fs", "io-util", "time"] }
24+toml.workspace = true
25+tracing.workspace = true
26+turso.workspace = true
27+ulid.workspace = true
28+
29+[dev-dependencies]
30+tempfile.workspace = true
31+
32+[lints]
33+workspace = true
crates/in-core/migrations/0001_init.sqladded+180 -0
@@ -0,0 +1,180 @@
1+-- 0001: the first schema of `in`. Creates every table in docs/architecture.md section 3, with its
2+-- constraints and indexes. Timestamps are fixed-width UTC text (see time.rs); booleans are INTEGER 0/1.
3+
4+CREATE TABLE settings (
5+ key TEXT PRIMARY KEY NOT NULL,
6+ value TEXT NOT NULL,
7+ updated_at TEXT NOT NULL
8+);
9+
10+-- Mirror of the people in `im`. `sub` is the OIDC subject and never changes for a person.
11+CREATE TABLE members (
12+ sub TEXT PRIMARY KEY NOT NULL,
13+ email TEXT NOT NULL,
14+ name TEXT NOT NULL,
15+ is_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_admin IN (0, 1)),
16+ disabled INTEGER NOT NULL DEFAULT 0 CHECK (disabled IN (0, 1)),
17+ locale TEXT NOT NULL DEFAULT 'en',
18+ zoneinfo TEXT NOT NULL DEFAULT 'UTC',
19+ picture_version INTEGER NOT NULL DEFAULT 0 CHECK (picture_version >= 0),
20+ im_updated_at TEXT NOT NULL,
21+ first_seen_at TEXT NOT NULL,
22+ last_sign_in_at TEXT,
23+ theme TEXT NOT NULL DEFAULT 'system' CHECK (theme IN ('system', 'light', 'dark')),
24+ locale_override TEXT,
25+ quota_bytes INTEGER NOT NULL CHECK (quota_bytes >= 0),
26+ used_bytes INTEGER NOT NULL DEFAULT 0 CHECK (used_bytes >= 0)
27+);
28+
29+-- Local sessions. Only the SHA-256 of the cookie token is stored.
30+CREATE TABLE sessions (
31+ id TEXT PRIMARY KEY NOT NULL,
32+ sub TEXT NOT NULL REFERENCES members (sub) ON DELETE CASCADE,
33+ token_hash TEXT NOT NULL UNIQUE,
34+ csrf_token TEXT NOT NULL,
35+ im_sid TEXT NOT NULL,
36+ created_at TEXT NOT NULL,
37+ expires_at TEXT NOT NULL,
38+ last_seen_at TEXT NOT NULL,
39+ ip TEXT,
40+ user_agent TEXT
41+);
42+CREATE INDEX sessions_im_sid ON sessions (im_sid);
43+CREATE INDEX sessions_sub ON sessions (sub);
44+
45+-- Back-channel logout token ids already used. Kept until the token would have expired anyway.
46+CREATE TABLE seen_logout_jti (
47+ jti TEXT PRIMARY KEY NOT NULL,
48+ expires_at TEXT NOT NULL
49+);
50+
51+-- Folders. Live names are unique per owner and parent. A NULL parent is written as '' so that the
52+-- root level is covered too.
53+CREATE TABLE folders (
54+ id TEXT PRIMARY KEY NOT NULL,
55+ owner TEXT NOT NULL REFERENCES members (sub) ON DELETE RESTRICT,
56+ parent_id TEXT REFERENCES folders (id) ON DELETE RESTRICT,
57+ name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 255),
58+ created_at TEXT NOT NULL,
59+ updated_at TEXT NOT NULL,
60+ trashed_at TEXT,
61+ trash_root TEXT REFERENCES folders (id) ON DELETE SET NULL,
62+ CHECK (parent_id IS NULL OR parent_id <> id)
63+);
64+CREATE UNIQUE INDEX folders_live_name
65+ ON folders (owner, COALESCE(parent_id, ''), name)
66+ WHERE trashed_at IS NULL;
67+CREATE INDEX folders_parent ON folders (parent_id);
68+CREATE INDEX folders_trash_root ON folders (trash_root);
69+
70+-- Files. `sha256` is the hex digest of the content; `blob_key` names the bytes in the blob store.
71+CREATE TABLE files (
72+ id TEXT PRIMARY KEY NOT NULL,
73+ owner TEXT NOT NULL REFERENCES members (sub) ON DELETE RESTRICT,
74+ folder_id TEXT REFERENCES folders (id) ON DELETE RESTRICT,
75+ name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 255),
76+ mime TEXT NOT NULL,
77+ size INTEGER NOT NULL CHECK (size >= 0),
78+ sha256 TEXT NOT NULL CHECK (length(sha256) = 64),
79+ blob_key TEXT NOT NULL UNIQUE,
80+ thumb_state TEXT NOT NULL DEFAULT 'none'
81+ CHECK (thumb_state IN ('none', 'pending', 'ready', 'failed', 'skip')),
82+ download_count INTEGER NOT NULL DEFAULT 0 CHECK (download_count >= 0),
83+ created_at TEXT NOT NULL,
84+ updated_at TEXT NOT NULL,
85+ trashed_at TEXT,
86+ trash_root TEXT REFERENCES folders (id) ON DELETE SET NULL
87+);
88+CREATE UNIQUE INDEX files_live_name
89+ ON files (owner, COALESCE(folder_id, ''), name)
90+ WHERE trashed_at IS NULL;
91+CREATE INDEX files_folder ON files (folder_id);
92+CREATE INDEX files_trash_root ON files (trash_root);
93+CREATE INDEX files_thumb_pending ON files (thumb_state) WHERE thumb_state = 'pending';
94+
95+-- Per-person shares. `target_id` names a file or folder; it cannot be a foreign key because it points
96+-- at either table, so the application removes grants when their target is purged.
97+CREATE TABLE grants (
98+ id TEXT PRIMARY KEY NOT NULL,
99+ target_kind TEXT NOT NULL CHECK (target_kind IN ('file', 'folder')),
100+ target_id TEXT NOT NULL,
101+ owner TEXT NOT NULL REFERENCES members (sub) ON DELETE RESTRICT,
102+ grantee TEXT NOT NULL REFERENCES members (sub) ON DELETE CASCADE,
103+ can_download INTEGER NOT NULL DEFAULT 0 CHECK (can_download IN (0, 1)),
104+ created_at TEXT NOT NULL,
105+ UNIQUE (target_kind, target_id, grantee)
106+);
107+CREATE INDEX grants_grantee ON grants (grantee);
108+
109+-- Public share links. The token itself is never stored: `token_hash` is looked up, and `token_sealed`
110+-- lets the owner see the URL again.
111+CREATE TABLE links (
112+ id TEXT PRIMARY KEY NOT NULL,
113+ token_hash TEXT NOT NULL UNIQUE,
114+ token_sealed TEXT NOT NULL,
115+ target_kind TEXT NOT NULL CHECK (target_kind IN ('file', 'folder')),
116+ target_id TEXT NOT NULL,
117+ owner TEXT NOT NULL REFERENCES members (sub) ON DELETE RESTRICT,
118+ can_download INTEGER NOT NULL DEFAULT 0 CHECK (can_download IN (0, 1)),
119+ password_hash TEXT,
120+ expires_at TEXT,
121+ revoked_at TEXT,
122+ created_at TEXT NOT NULL,
123+ last_used_at TEXT,
124+ use_count INTEGER NOT NULL DEFAULT 0 CHECK (use_count >= 0)
125+);
126+CREATE INDEX links_target ON links (target_kind, target_id);
127+CREATE INDEX links_owner ON links (owner);
128+
129+-- Resumable uploads in progress. Chunks are staged on disk until `finish` turns them into a file.
130+CREATE TABLE uploads (
131+ id TEXT PRIMARY KEY NOT NULL,
132+ owner TEXT NOT NULL REFERENCES members (sub) ON DELETE RESTRICT,
133+ folder_id TEXT REFERENCES folders (id) ON DELETE RESTRICT,
134+ name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 255),
135+ size INTEGER NOT NULL CHECK (size >= 0),
136+ chunk_size INTEGER NOT NULL CHECK (chunk_size > 0),
137+ state TEXT NOT NULL DEFAULT 'active' CHECK (state IN ('active', 'done', 'aborted')),
138+ file_id TEXT REFERENCES files (id) ON DELETE SET NULL,
139+ created_at TEXT NOT NULL,
140+ expires_at TEXT NOT NULL
141+);
142+CREATE INDEX uploads_owner ON uploads (owner);
143+CREATE INDEX uploads_expires ON uploads (expires_at);
144+
145+-- Namespaces for machine callers (other family apps). The key is the token's `svc` claim.
146+CREATE TABLE services (
147+ key TEXT PRIMARY KEY NOT NULL,
148+ quota_bytes INTEGER NOT NULL CHECK (quota_bytes >= 0),
149+ used_bytes INTEGER NOT NULL DEFAULT 0 CHECK (used_bytes >= 0),
150+ created_at TEXT NOT NULL
151+);
152+
153+-- Objects stored by services. The primary key is the service's own id for the object.
154+CREATE TABLE objects (
155+ service TEXT NOT NULL REFERENCES services (key) ON DELETE RESTRICT,
156+ external_id TEXT NOT NULL,
157+ size INTEGER NOT NULL CHECK (size >= 0),
158+ sha256 TEXT NOT NULL CHECK (length(sha256) = 64),
159+ content_type TEXT NOT NULL,
160+ name TEXT,
161+ blob_key TEXT NOT NULL UNIQUE,
162+ created_at TEXT NOT NULL,
163+ updated_at TEXT NOT NULL,
164+ PRIMARY KEY (service, external_id)
165+);
166+
167+-- Append-only record of changes. `data` is JSON and never holds secrets.
168+CREATE TABLE audit_log (
169+ id TEXT PRIMARY KEY NOT NULL,
170+ at TEXT NOT NULL,
171+ actor_id TEXT,
172+ actor_kind TEXT NOT NULL CHECK (actor_kind IN ('member', 'service', 'link', 'system')),
173+ action TEXT NOT NULL,
174+ target_kind TEXT NOT NULL,
175+ target_id TEXT,
176+ ip TEXT,
177+ data TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(data))
178+);
179+CREATE INDEX audit_log_at ON audit_log (at);
180+CREATE INDEX audit_log_target ON audit_log (target_kind, target_id);
crates/in-core/src/config.rsadded+289 -0
@@ -0,0 +1,289 @@
1+//! File configuration (`config/in.toml`). Secrets never live here: the OIDC client secret and the
2+//! S3 keys are read from files or entered in the admin UI. Every struct rejects unknown keys, so a
3+//! typo fails at boot instead of being silently ignored.
4+
5+use std::net::{IpAddr, SocketAddr};
6+use std::path::{Path, PathBuf};
7+use std::str::FromStr;
8+
9+use ipnet::IpNet;
10+use serde::{Deserialize, Deserializer};
11+
12+use crate::error::{Error, Result};
13+
14+/// The example file. It is committed, and it is written to `config/in.toml` when that file is missing.
15+pub const EXAMPLE: &str = include_str!("../../../config/in.example.toml");
16+
17+/// The whole file configuration.
18+#[derive(Debug, Clone, PartialEq, Deserialize)]
19+#[serde(deny_unknown_fields, default)]
20+pub struct Config {
21+ /// Path of the database file. Relative paths are relative to the working directory.
22+ pub database: PathBuf,
23+ /// Directory for blobs, staging files, the instance key and caches. Created at boot with mode 0700.
24+ pub data_dir: PathBuf,
25+ /// Address the HTTP server binds to.
26+ pub listen: SocketAddr,
27+ /// Public URL of the instance, with scheme and no trailing slash. Decides cookie `Secure` and HSTS.
28+ pub base_url: String,
29+ /// Proxies whose `X-Forwarded-For` is believed. Each entry is a CIDR range or a bare address.
30+ #[serde(deserialize_with = "deserialize_trusted_proxies")]
31+ pub trusted_proxies: Vec<IpNet>,
32+ /// Sign-in through `im`. Without it the instance cannot sign anyone in.
33+ pub oidc: Option<Oidc>,
34+ /// Where blobs are kept.
35+ pub storage: Storage,
36+ /// Scheduled backups. Absent means no scheduled backups.
37+ pub backup: Option<Backup>,
38+}
39+
40+impl Default for Config {
41+ fn default() -> Self {
42+ Self {
43+ database: PathBuf::from("data/in.db"),
44+ data_dir: PathBuf::from("data"),
45+ listen: SocketAddr::from(([127, 0, 0, 1], 7655)),
46+ base_url: "http://127.0.0.1:7655".into(),
47+ trusted_proxies: Vec::new(),
48+ oidc: None,
49+ storage: Storage::default(),
50+ backup: None,
51+ }
52+ }
53+}
54+
55+/// The `[oidc]` table: where `im` lives and which client id `in` uses. The secret is not here.
56+#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
57+#[serde(deny_unknown_fields)]
58+pub struct Oidc {
59+ /// Issuer URL of `im`, as published in its discovery document.
60+ pub issuer: String,
61+ /// The OAuth client id registered for `in` in `im`.
62+ pub client_id: String,
63+}
64+
65+/// The `[storage]` table.
66+#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)]
67+#[serde(deny_unknown_fields, default)]
68+pub struct Storage {
69+ /// Which blob backend to use.
70+ pub backend: Backend,
71+ /// S3 settings. Required when `backend` is `s3`, and an error when `backend` is `local`.
72+ pub s3: Option<S3>,
73+}
74+
75+/// Blob backends.
76+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
77+#[serde(rename_all = "lowercase")]
78+pub enum Backend {
79+ /// Files in `data_dir/blobs`.
80+ #[default]
81+ Local,
82+ /// An S3-compatible bucket (AWS, R2, Hetzner Object Storage, ...).
83+ S3,
84+}
85+
86+/// The `[storage.s3]` table. Credentials are files readable only by the service user.
87+#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
88+#[serde(deny_unknown_fields)]
89+pub struct S3 {
90+ /// Endpoint URL for a non-AWS service. Absent means AWS.
91+ #[serde(default)]
92+ pub endpoint: Option<String>,
93+ /// Region name the service expects (`auto` for R2).
94+ pub region: String,
95+ /// Bucket that holds the blob tree.
96+ pub bucket: String,
97+ /// File holding the access key id.
98+ pub access_key_id_file: PathBuf,
99+ /// File holding the secret access key.
100+ pub secret_access_key_file: PathBuf,
101+}
102+
103+/// The `[backup]` table.
104+#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
105+#[serde(deny_unknown_fields)]
106+pub struct Backup {
107+ /// Directory that receives one snapshot set per run.
108+ pub dir: PathBuf,
109+ /// Hours between backup runs. Must be at least 1.
110+ #[serde(default = "default_interval_hours")]
111+ pub interval_hours: u32,
112+ /// Snapshot sets kept; older ones are removed after a successful run. Must be at least 1.
113+ #[serde(default = "default_keep")]
114+ pub keep: u32,
115+ /// Dead-man URL pinged after each successful run. Absent means no pings.
116+ #[serde(default)]
117+ pub healthcheck_url: Option<String>,
118+}
119+
120+fn default_interval_hours() -> u32 {
121+ 24
122+}
123+
124+fn default_keep() -> u32 {
125+ 7
126+}
127+
128+impl Config {
129+ /// Reads and validates the file at `path`. A missing file is first created from [`EXAMPLE`], so a
130+ /// first run starts with working development defaults.
131+ pub fn load(path: &Path) -> Result<Config> {
132+ let text = match std::fs::read_to_string(path) {
133+ Ok(text) => text,
134+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
135+ if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
136+ std::fs::create_dir_all(parent)?;
137+ }
138+ std::fs::write(path, EXAMPLE)?;
139+ EXAMPLE.to_owned()
140+ }
141+ Err(e) => return Err(e.into()),
142+ };
143+ let config: Config =
144+ toml::from_str(&text).map_err(|e| Error::Config(format!("{}: {e}", path.display())))?;
145+ config.validate()?;
146+ Ok(config)
147+ }
148+
149+ /// Checks the rules that span fields. Called by [`Config::load`] and again whenever a setting
150+ /// is changed from the admin UI.
151+ pub fn validate(&self) -> Result<()> {
152+ if self.data_dir.as_os_str().is_empty() {
153+ return Err(config_err("data_dir must not be empty"));
154+ }
155+ if self.database.as_os_str().is_empty() {
156+ return Err(config_err("database must not be empty"));
157+ }
158+ validate_base_url("base_url", &self.base_url)?;
159+ if let Some(oidc) = &self.oidc {
160+ validate_base_url("oidc.issuer", &oidc.issuer)?;
161+ if oidc.client_id.trim().is_empty() || oidc.client_id.chars().any(char::is_control) {
162+ return Err(config_err(
163+ "oidc.client_id must be a non-empty plain string",
164+ ));
165+ }
166+ }
167+ self.storage.validate()?;
168+ if let Some(backup) = &self.backup {
169+ backup.validate()?;
170+ }
171+ Ok(())
172+ }
173+}
174+
175+impl Storage {
176+ fn validate(&self) -> Result<()> {
177+ match (self.backend, &self.s3) {
178+ (Backend::Local, Some(_)) => Err(config_err(
179+ "storage.s3 is set but storage.backend is \"local\"",
180+ )),
181+ (Backend::Local, None) => Ok(()),
182+ (Backend::S3, None) => Err(config_err(
183+ "storage.backend is \"s3\" but [storage.s3] is missing",
184+ )),
185+ (Backend::S3, Some(s3)) => s3.validate(),
186+ }
187+ }
188+}
189+
190+impl S3 {
191+ fn validate(&self) -> Result<()> {
192+ if let Some(endpoint) = &self.endpoint {
193+ validate_base_url("storage.s3.endpoint", endpoint)?;
194+ }
195+ if self.region.trim().is_empty() {
196+ return Err(config_err("storage.s3.region must not be empty"));
197+ }
198+ if self.bucket.trim().is_empty() {
199+ return Err(config_err("storage.s3.bucket must not be empty"));
200+ }
201+ if self.access_key_id_file.as_os_str().is_empty()
202+ || self.secret_access_key_file.as_os_str().is_empty()
203+ {
204+ return Err(config_err(
205+ "storage.s3 credential file paths must not be empty",
206+ ));
207+ }
208+ Ok(())
209+ }
210+}
211+
212+impl Backup {
213+ fn validate(&self) -> Result<()> {
214+ if self.dir.as_os_str().is_empty() {
215+ return Err(config_err("backup.dir must not be empty"));
216+ }
217+ if self.interval_hours == 0 {
218+ return Err(config_err("backup.interval_hours must be at least 1"));
219+ }
220+ if self.keep == 0 {
221+ return Err(config_err("backup.keep must be at least 1"));
222+ }
223+ if let Some(url) = &self.healthcheck_url {
224+ validate_base_url("backup.healthcheck_url", url)?;
225+ }
226+ Ok(())
227+ }
228+}
229+
230+fn config_err(message: &str) -> Error {
231+ Error::Config(message.to_string())
232+}
233+
234+/// An http or https URL with no trailing slash. Scheme checks only: the rest is left to the
235+/// component that uses the URL, which reports its own error.
236+fn validate_base_url(field: &str, url: &str) -> Result<()> {
237+ if !(url.starts_with("https://") || url.starts_with("http://")) {
238+ return Err(config_err(&format!(
239+ "{field} must start with http:// or https://"
240+ )));
241+ }
242+ if url.ends_with('/') || url.chars().any(char::is_whitespace) {
243+ return Err(config_err(&format!(
244+ "{field} must have no trailing slash and no whitespace"
245+ )));
246+ }
247+ Ok(())
248+}
249+
250+/// Accepts `10.0.0.1`, `fd00::1` (a single address, which becomes a host range) or a CIDR range.
251+fn deserialize_trusted_proxies<'de, D>(deserializer: D) -> std::result::Result<Vec<IpNet>, D::Error>
252+where
253+ D: Deserializer<'de>,
254+{
255+ let items = Vec::<String>::deserialize(deserializer)?;
256+ items
257+ .iter()
258+ .map(|item| parse_proxy(item).map_err(serde::de::Error::custom))
259+ .collect()
260+}
261+
262+/// Parses one trusted-proxy entry. A bare address becomes a single-host range.
263+pub fn parse_proxy(text: &str) -> std::result::Result<IpNet, String> {
264+ let text = text.trim();
265+ if text.contains('/') {
266+ return IpNet::from_str(text).map_err(|e| format!("trusted proxy {text:?}: {e}"));
267+ }
268+ let ip = IpAddr::from_str(text).map_err(|e| format!("trusted proxy {text:?}: {e}"))?;
269+ let host_len = if ip.is_ipv4() { 32 } else { 128 };
270+ IpNet::new(ip, host_len).map_err(|e| format!("trusted proxy {text:?}: {e}"))
271+}
272+
273+#[cfg(test)]
274+mod tests {
275+ use super::*;
276+
277+ #[test]
278+ fn example_is_valid_and_bare_proxy_addresses_are_accepted() {
279+ let config: Config = toml::from_str(EXAMPLE).unwrap();
280+ config.validate().unwrap();
281+
282+ let text = "trusted_proxies = [\"10.0.0.1\", \"fd00::/8\"]";
283+ let config: Config = toml::from_str(text).unwrap();
284+ assert_eq!(config.trusted_proxies.len(), 2);
285+ assert_eq!(config.trusted_proxies[0].prefix_len(), 32);
286+
287+ assert!(toml::from_str::<Config>("databse = \"typo.db\"").is_err());
288+ }
289+}
crates/in-core/src/error.rsadded+37 -0
@@ -0,0 +1,37 @@
1+//! The error type for `in-core`. `Invalid` and `Conflict` carry text meant for the user; every other
2+//! variant becomes a generic 500 page with the cause logged.
3+
4+/// Every failure `in-core` reports.
5+#[derive(Debug, thiserror::Error)]
6+pub enum Error {
7+ /// A filesystem operation failed.
8+ #[error("io error: {0}")]
9+ Io(#[from] std::io::Error),
10+ /// The database rejected or failed a statement.
11+ #[error("database error: {0}")]
12+ Database(String),
13+ /// A schema migration could not be applied.
14+ #[error("migration error: {0}")]
15+ Migration(String),
16+ /// The configuration file is unreadable, malformed or fails validation.
17+ #[error("config error: {0}")]
18+ Config(String),
19+ /// Sealing, opening, hashing or the instance key failed.
20+ #[error("crypto error: {0}")]
21+ Crypto(String),
22+ /// The requested row does not exist, or the viewer may not know that it exists.
23+ #[error("not found")]
24+ NotFound,
25+ /// The write clashes with existing state, such as a name that is already taken.
26+ #[error("conflict: {0}")]
27+ Conflict(String),
28+ /// The actor is known but may not do this.
29+ #[error("forbidden: {0}")]
30+ Forbidden(String),
31+ /// The input is malformed or breaks a rule.
32+ #[error("invalid value: {0}")]
33+ Invalid(String),
34+}
35+
36+/// Shorthand for results carrying [`Error`].
37+pub type Result<T> = std::result::Result<T, Error>;
crates/in-core/src/lib.rsadded+11 -0
@@ -0,0 +1,11 @@
1+//! Core of `in`: errors, time stamps, secrets, tokens, passwords, display-name rules, configuration
2+//! and the Turso-backed store. Nothing here serves HTTP; `in-web` builds on it.
3+
4+pub mod config;
5+pub mod error;
6+pub mod names;
7+pub mod password;
8+pub mod secret;
9+pub mod store;
10+pub mod time;
11+pub mod token;
crates/in-core/src/names.rsadded+117 -0
@@ -0,0 +1,117 @@
1+//! Display-name rules for files and folders. A name is shown as typed, but it never carries folders,
2+//! control characters or more than 255 characters. Names are compared exactly; the database enforces
3+//! uniqueness among live items in one folder.
4+
5+/// Longest name in characters (not bytes).
6+pub const MAX_NAME_CHARS: usize = 255;
7+/// Name given to an item whose input has no usable characters left.
8+pub const UNTITLED: &str = "Untitled";
9+
10+/// Makes a safe display name from user input. Only the last path component survives, so `a/b/c.txt`
11+/// becomes `c.txt`. Control characters are dropped, surrounding spaces are trimmed, and input with
12+/// nothing left (or `.` / `..`) becomes [`UNTITLED`]. The result is cut to [`MAX_NAME_CHARS`].
13+pub fn display_name(input: &str) -> String {
14+ // Path separators come from both Unix and Windows clients, so split on both.
15+ let leaf = input
16+ .rsplit(['/', '\\'])
17+ .find(|part| !part.trim().is_empty())
18+ .unwrap_or("");
19+ let cleaned: String = leaf.chars().filter(|c| !c.is_control()).collect();
20+ let trimmed = cleaned.trim();
21+ if trimmed.is_empty() || trimmed == "." || trimmed == ".." {
22+ return UNTITLED.to_string();
23+ }
24+ truncate_chars(trimmed, MAX_NAME_CHARS)
25+}
26+
27+/// The name to try after a clash: `report.txt` with `n = 2` gives `report (2).txt`. A folder gets the
28+/// suffix at the end (`root (2)`), and so does a file with no extension (`note (2)`). A name starting
29+/// with a dot has no extension, so `.bashrc` gives `.bashrc (2)`. The stem is cut so the whole result
30+/// stays within [`MAX_NAME_CHARS`]; the extension and the suffix are always kept.
31+///
32+/// `name` is passed through [`display_name`] first, so the result is always a valid display name.
33+pub fn postfix(name: &str, n: u32, is_file: bool) -> String {
34+ let base = display_name(name);
35+ let suffix = format!(" ({n})");
36+ let (stem, ext) = if is_file {
37+ split_extension(&base)
38+ } else {
39+ (base.as_str(), "")
40+ };
41+ // An extension so long that no stem would fit beside it is dropped, so the suffix still fits.
42+ let (stem, ext) = if suffix.chars().count() + ext.chars().count() < MAX_NAME_CHARS {
43+ (stem, ext)
44+ } else {
45+ (base.as_str(), "")
46+ };
47+ let budget = MAX_NAME_CHARS - suffix.chars().count() - ext.chars().count();
48+ format!("{}{suffix}{ext}", truncate_chars(stem, budget))
49+}
50+
51+/// Splits `name` at its last dot, which must not be the first character. The dot stays with the
52+/// extension, so `archive.tar.gz` splits into `archive.tar` and `.gz`.
53+fn split_extension(name: &str) -> (&str, &str) {
54+ match name.rfind('.') {
55+ // A dot is one byte, so the cut is always on a character boundary.
56+ Some(i) if i > 0 => (&name[..i], &name[i..]),
57+ _ => (name, ""),
58+ }
59+}
60+
61+/// The first `max` characters of `s`.
62+fn truncate_chars(s: &str, max: usize) -> String {
63+ s.chars().take(max).collect()
64+}
65+
66+#[cfg(test)]
67+mod tests {
68+ use super::*;
69+
70+ #[test]
71+ fn display_name_keeps_only_the_leaf_and_drops_control_characters() {
72+ assert_eq!(display_name("../a/b/report.txt"), "report.txt");
73+ assert_eq!(display_name("docs\\notes\\todo.md"), "todo.md");
74+ assert_eq!(display_name("bad\u{7}name\n"), "badname");
75+ assert_eq!(display_name(" spaced "), "spaced");
76+ assert_eq!(display_name("trailing/"), "trailing");
77+ }
78+
79+ #[test]
80+ fn display_name_falls_back_to_untitled() {
81+ for input in ["", " ", "/", "..", ".", "\u{1}\u{2}"] {
82+ assert_eq!(display_name(input), UNTITLED, "input {input:?}");
83+ }
84+ }
85+
86+ #[test]
87+ fn display_name_cuts_long_names_by_characters() {
88+ let long = "é".repeat(300);
89+ let shown = display_name(&long);
90+ assert_eq!(shown.chars().count(), MAX_NAME_CHARS);
91+ assert!(shown.chars().all(|c| c == 'é'));
92+ }
93+
94+ #[test]
95+ fn postfix_puts_the_number_before_the_extension() {
96+ assert_eq!(postfix("report.txt", 2, true), "report (2).txt");
97+ assert_eq!(postfix("note", 2, true), "note (2)");
98+ assert_eq!(postfix(".bashrc", 2, true), ".bashrc (2)");
99+ assert_eq!(postfix("archive.tar.gz", 3, true), "archive.tar (3).gz");
100+ }
101+
102+ #[test]
103+ fn postfix_appends_for_folders_even_when_they_contain_dots() {
104+ assert_eq!(postfix("root", 2, false), "root (2)");
105+ assert_eq!(postfix("v1.2", 2, false), "v1.2 (2)");
106+ }
107+
108+ #[test]
109+ fn postfix_truncates_the_stem_so_the_result_fits() {
110+ // 250 characters of stem plus ".pdf" is already 254, so the suffix needs room taken from the stem.
111+ let name = format!("{}.pdf", "é".repeat(250));
112+ let out = postfix(&name, 2, true);
113+ assert_eq!(out.chars().count(), MAX_NAME_CHARS);
114+ assert!(out.ends_with(" (2).pdf"));
115+ assert!(out.starts_with('é'));
116+ }
117+}
crates/in-core/src/password.rsadded+43 -0
@@ -0,0 +1,43 @@
1+//! Password hashing with argon2id. Used for account passwords and for share-link passwords. The
2+//! blocking versions are slow by design, so async callers use the `_async` functions, which run them
3+//! on tokio's blocking pool.
4+
5+use argon2::Argon2;
6+use argon2::password_hash::phc::PasswordHash;
7+use argon2::password_hash::{PasswordHasher, PasswordVerifier};
8+
9+use crate::error::{Error, Result};
10+
11+/// Hashes `pw` with argon2id (default parameters) and a random salt. Returns a PHC string.
12+pub fn hash_password(pw: &str) -> Result<String> {
13+ // The trait method draws a fresh salt from the OS RNG.
14+ Argon2::default()
15+ .hash_password(pw.as_bytes())
16+ .map(|h| h.to_string())
17+ .map_err(|e| Error::Crypto(format!("argon2: {e}")))
18+}
19+
20+/// Returns true only if `pw` matches the PHC string `hash`. A malformed hash also gives false, so
21+/// callers never have to tell "bad hash" apart from "wrong password".
22+pub fn verify_password(pw: &str, hash: &str) -> bool {
23+ let Ok(parsed) = PasswordHash::new(hash) else {
24+ return false;
25+ };
26+ Argon2::default()
27+ .verify_password(pw.as_bytes(), &parsed)
28+ .is_ok()
29+}
30+
31+/// [`hash_password`] on the blocking pool, so the async runtime is not held for the hashing time.
32+pub async fn hash_password_async(pw: String) -> Result<String> {
33+ tokio::task::spawn_blocking(move || hash_password(&pw))
34+ .await
35+ .map_err(|e| Error::Crypto(format!("hashing task failed: {e}")))?
36+}
37+
38+/// [`verify_password`] on the blocking pool.
39+pub async fn verify_password_async(pw: String, hash: String) -> Result<bool> {
40+ tokio::task::spawn_blocking(move || verify_password(&pw, &hash))
41+ .await
42+ .map_err(|e| Error::Crypto(format!("verify task failed: {e}")))
43+}
crates/in-core/src/secret.rsadded+137 -0
@@ -0,0 +1,137 @@
1+//! The instance key and XChaCha20-Poly1305 sealing of secrets at rest. A sealed value is safe to
2+//! store in the database; the key lives in a file readable only by the service user.
3+
4+use std::path::Path;
5+
6+use base64::prelude::{BASE64_STANDARD, Engine as _};
7+use chacha20poly1305::aead::Aead;
8+use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce};
9+
10+use crate::error::{Error, Result};
11+
12+/// Prefix of every sealed value. It names the format so a later format can coexist.
13+const PREFIX: &str = "v1:";
14+/// XChaCha20 nonce length. Long enough that a random nonce per seal never repeats in practice.
15+const NONCE_LEN: usize = 24;
16+
17+/// Loads the 32-byte instance key at `path`, creating it when missing. A new key is created with
18+/// mode 0600 and `O_EXCL`, so an existing key is never overwritten. An existing key with group or
19+/// world access is refused.
20+pub fn load_or_create_key(path: &Path) -> Result<[u8; 32]> {
21+ if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
22+ std::fs::create_dir_all(parent)?;
23+ }
24+ match create_key(path) {
25+ Ok(key) => Ok(key),
26+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => read_key(path),
27+ Err(e) => Err(e.into()),
28+ }
29+}
30+
31+fn create_key(path: &Path) -> std::io::Result<[u8; 32]> {
32+ use std::io::Write;
33+
34+ use rand::TryRng;
35+
36+ let mut key = [0u8; 32];
37+ rand::rngs::SysRng
38+ .try_fill_bytes(&mut key)
39+ .map_err(std::io::Error::other)?;
40+
41+ let mut options = std::fs::OpenOptions::new();
42+ options.write(true).create_new(true);
43+ #[cfg(unix)]
44+ {
45+ use std::os::unix::fs::OpenOptionsExt;
46+ options.mode(0o600);
47+ }
48+ let mut file = options.open(path)?;
49+ let written = file.write_all(&key).and_then(|()| file.sync_all());
50+ if let Err(e) = written {
51+ // A truncated key would be rejected at every later start, so remove it now.
52+ drop(file);
53+ let _ = std::fs::remove_file(path);
54+ return Err(e);
55+ }
56+ Ok(key)
57+}
58+
59+fn read_key(path: &Path) -> Result<[u8; 32]> {
60+ #[cfg(unix)]
61+ {
62+ use std::os::unix::fs::PermissionsExt;
63+ let mode = std::fs::metadata(path)?.permissions().mode();
64+ if mode & 0o077 != 0 {
65+ return Err(Error::Crypto(format!(
66+ "instance key {} is group/world accessible (mode {:o}); expected 0600",
67+ path.display(),
68+ mode & 0o777
69+ )));
70+ }
71+ }
72+ let bytes = std::fs::read(path)?;
73+ <[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| {
74+ Error::Crypto(format!(
75+ "instance key {} has length {}, expected 32",
76+ path.display(),
77+ bytes.len()
78+ ))
79+ })
80+}
81+
82+/// Seals `plaintext` under `key`. The output is `"v1:" + base64(nonce || ciphertext)` with a fresh
83+/// random nonce each time. The caller must not store the plaintext when this fails.
84+pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result<String> {
85+ let mut nonce = [0u8; NONCE_LEN];
86+ rand::fill(&mut nonce);
87+ let cipher = XChaCha20Poly1305::new(key.into());
88+ let ciphertext = cipher
89+ .encrypt(&XNonce::from(nonce), plaintext)
90+ .map_err(|_| Error::Crypto("sealing failed".into()))?;
91+ let mut blob = Vec::with_capacity(NONCE_LEN + ciphertext.len());
92+ blob.extend_from_slice(&nonce);
93+ blob.extend_from_slice(&ciphertext);
94+ Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob)))
95+}
96+
97+/// Opens a value produced by [`seal`]. A wrong key, a changed byte or a malformed value is an error.
98+pub fn open(key: &[u8; 32], sealed: &str) -> Result<Vec<u8>> {
99+ let encoded = sealed
100+ .strip_prefix(PREFIX)
101+ .ok_or_else(|| Error::Crypto("sealed value has no v1 prefix".into()))?;
102+ let blob = BASE64_STANDARD
103+ .decode(encoded)
104+ .map_err(|_| Error::Crypto("sealed value is not valid base64".into()))?;
105+ if blob.len() < NONCE_LEN {
106+ return Err(Error::Crypto("sealed value is too short".into()));
107+ }
108+ let (nonce, ciphertext) = blob.split_at(NONCE_LEN);
109+ let nonce = <[u8; NONCE_LEN]>::try_from(nonce)
110+ .map_err(|_| Error::Crypto("sealed value has a bad nonce".into()))?;
111+ let cipher = XChaCha20Poly1305::new(key.into());
112+ cipher
113+ .decrypt(&XNonce::from(nonce), ciphertext)
114+ .map_err(|_| Error::Crypto("sealed value failed authentication".into()))
115+}
116+
117+#[cfg(test)]
118+mod tests {
119+ use super::*;
120+
121+ #[test]
122+ fn seal_and_open_round_trip_and_reject_wrong_key_or_tampering() {
123+ let key = [7u8; 32];
124+ let sealed = seal(&key, b"hello secret").unwrap();
125+ assert!(sealed.starts_with("v1:"));
126+ assert_eq!(open(&key, &sealed).unwrap(), b"hello secret");
127+ // A fresh nonce means the same plaintext never seals to the same text twice.
128+ assert_ne!(sealed, seal(&key, b"hello secret").unwrap());
129+
130+ assert!(open(&[8u8; 32], &sealed).is_err(), "wrong key must fail");
131+ let mut tampered = sealed.clone();
132+ let last = tampered.pop().unwrap();
133+ tampered.push(if last == 'A' { 'B' } else { 'A' });
134+ assert!(open(&key, &tampered).is_err(), "tampered value must fail");
135+ assert!(open(&key, "data").is_err(), "missing prefix must fail");
136+ }
137+}
crates/in-core/src/store/migrate.rsadded+50 -0
@@ -0,0 +1,50 @@
1+//! The schema migration runner. Migrations are SQL files compiled into the binary and applied in
2+//! order. Each one runs in its own transaction with its `schema_migrations` row, so a failure leaves
3+//! the database as it was.
4+
5+use turso::Connection;
6+
7+use crate::error::{Error, Result};
8+use crate::store::fetch_all;
9+use crate::time::now_stamp;
10+
11+/// `(version, sql)` in ascending order. Never edit a migration that has been applied; add a new one.
12+pub const MIGRATIONS: &[(u32, &str)] = &[(1, include_str!("../../migrations/0001_init.sql"))];
13+
14+fn migration_err(e: turso::Error) -> Error {
15+ Error::Migration(e.to_string())
16+}
17+
18+/// Applies every migration whose version is not yet recorded.
19+pub async fn migrate(conn: &Connection) -> Result<()> {
20+ conn.execute_batch(
21+ "CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)",
22+ )
23+ .await
24+ .map_err(migration_err)?;
25+
26+ let applied = fetch_all(
27+ conn,
28+ "SELECT version FROM schema_migrations ORDER BY version",
29+ (),
30+ |row| crate::store::col_int(row, 0),
31+ )
32+ .await?;
33+ for &(version, sql) in MIGRATIONS {
34+ let version = i64::from(version);
35+ if applied.contains(&version) {
36+ continue;
37+ }
38+ let tx = conn.unchecked_transaction().await.map_err(migration_err)?;
39+ tx.execute_batch(sql).await.map_err(migration_err)?;
40+ tx.execute(
41+ "INSERT INTO schema_migrations (version, applied_at) VALUES (?1, ?2)",
42+ (version, now_stamp()),
43+ )
44+ .await
45+ .map_err(migration_err)?;
46+ tx.commit().await.map_err(migration_err)?;
47+ tracing::info!(version, "applied database migration");
48+ }
49+ Ok(())
50+}
crates/in-core/src/store/mod.rsadded+257 -0
@@ -0,0 +1,257 @@
1+//! The Turso-backed store. One writer connection serialises writes and transactions. A small pool of
2+//! read-only connections serves pure reads, so readers do not queue behind the writer.
3+//!
4+//! Every connection gets the same pragmas (WAL, `synchronous = FULL`, foreign keys, a 5 s busy
5+//! timeout). The helpers at the bottom of this file are shared by every table module.
6+
7+pub mod migrate;
8+pub mod settings;
9+pub mod snapshot;
10+
11+use std::path::Path;
12+use std::sync::Arc;
13+use std::sync::atomic::{AtomicUsize, Ordering};
14+use std::time::Duration;
15+
16+use tokio::sync::{Mutex, MutexGuard};
17+use turso::{Builder, Connection, Database, IntoParams, Row, Value};
18+
19+use crate::error::{Error, Result};
20+
21+/// How long a connection waits for a lock before it gives up.
22+const BUSY_TIMEOUT: Duration = Duration::from_millis(5000);
23+/// Read-only connections in the pool.
24+const READER_COUNT: usize = 4;
25+
26+/// Handle to the database. It is cheap to clone, and every clone shares the same connections.
27+///
28+/// Rule for [`Store::read_conn`]: use it only for a function that is a pure `SELECT` and does not need
29+/// to see a write made in the same call. Anything that writes, opens a transaction, or reads and then
30+/// writes uses the writer.
31+#[derive(Clone)]
32+pub struct Store {
33+ inner: Arc<Inner>,
34+}
35+
36+struct Inner {
37+ /// Keeps the database open for as long as any connection exists.
38+ _db: Database,
39+ /// The single writer. Holding its lock serialises writes and transactions.
40+ conn: Mutex<Connection>,
41+ /// Read-only connections, each with `PRAGMA query_only = 1`.
42+ readers: Vec<Mutex<Connection>>,
43+ /// Round-robin start index for [`Store::read_conn`].
44+ next_reader: AtomicUsize,
45+}
46+
47+impl Store {
48+ /// Opens (or creates) the database at `path`, applies the pragmas and runs pending migrations.
49+ /// Opening an up-to-date database again changes nothing.
50+ pub async fn open(path: &Path) -> Result<Store> {
51+ let path_str = path.to_str().ok_or_else(|| {
52+ Error::Config(format!("database path is not UTF-8: {}", path.display()))
53+ })?;
54+ let db = Builder::new_local(path_str).build().await.map_err(db_err)?;
55+ let conn = db.connect().map_err(db_err)?;
56+ apply_pragmas(&conn).await;
57+ migrate::migrate(&conn).await?;
58+ // Readers open after the migrations so that their view of the schema is current.
59+ let mut readers = Vec::with_capacity(READER_COUNT);
60+ for _ in 0..READER_COUNT {
61+ let reader = db.connect().map_err(db_err)?;
62+ apply_pragmas(&reader).await;
63+ apply_query_only(&reader).await?;
64+ readers.push(Mutex::new(reader));
65+ }
66+ Ok(Store {
67+ inner: Arc::new(Inner {
68+ _db: db,
69+ conn: Mutex::new(conn),
70+ readers,
71+ next_reader: AtomicUsize::new(0),
72+ }),
73+ })
74+ }
75+
76+ /// Returns a read-only pooled connection. It tries each reader without waiting, starting at the
77+ /// round-robin position, and waits on that position only when every reader is busy.
78+ pub async fn read_conn(&self) -> MutexGuard<'_, Connection> {
79+ let len = self.inner.readers.len();
80+ let start = self.inner.next_reader.fetch_add(1, Ordering::Relaxed) % len;
81+ for offset in 0..len {
82+ let idx = (start + offset) % len;
83+ if let Some(guard) = self.inner.readers.get(idx).and_then(|m| m.try_lock().ok()) {
84+ return guard;
85+ }
86+ }
87+ self.inner.readers[start].lock().await
88+ }
89+}
90+
91+/// Sets the pragmas every connection needs. A pragma that fails is logged, not fatal, and the values
92+/// in effect are read back and logged so a silent failure is visible at boot.
93+async fn apply_pragmas(conn: &Connection) {
94+ for sql in [
95+ "PRAGMA journal_mode = WAL",
96+ "PRAGMA synchronous = FULL",
97+ "PRAGMA foreign_keys = ON",
98+ ] {
99+ let applied = async {
100+ let mut rows = conn.query(sql, ()).await?;
101+ while rows.next().await?.is_some() {}
102+ Ok::<(), turso::Error>(())
103+ }
104+ .await;
105+ if let Err(e) = applied {
106+ tracing::warn!(pragma = sql, error = %e, "database pragma not applied");
107+ }
108+ }
109+ if let Err(e) = conn.busy_timeout(BUSY_TIMEOUT) {
110+ tracing::warn!(error = %e, "busy timeout not applied");
111+ }
112+ for name in ["journal_mode", "synchronous", "foreign_keys"] {
113+ match fetch_opt(conn, &format!("PRAGMA {name}"), (), |row| {
114+ col_to_string(row, 0)
115+ })
116+ .await
117+ {
118+ Ok(value) => tracing::info!(pragma = name, value = ?value, "database pragma in effect"),
119+ Err(e) => tracing::warn!(pragma = name, error = %e, "could not read database pragma"),
120+ }
121+ }
122+}
123+
124+/// Marks a connection read-only, so a mistaken write through the reader pool fails.
125+async fn apply_query_only(conn: &Connection) -> Result<()> {
126+ let mut rows = conn
127+ .query("PRAGMA query_only = 1", ())
128+ .await
129+ .map_err(db_err)?;
130+ while rows.next().await.map_err(db_err)?.is_some() {}
131+ Ok(())
132+}
133+
134+/// Ends a transaction: commits when `outcome` is `Ok`, rolls back and returns the error otherwise.
135+/// Every multi-statement write goes through this, so no path leaves a transaction open.
136+pub async fn finish<T>(tx: turso::transaction::Transaction<'_>, outcome: Result<T>) -> Result<T> {
137+ match outcome {
138+ Ok(value) => {
139+ tx.commit().await.map_err(db_err)?;
140+ Ok(value)
141+ }
142+ Err(e) => {
143+ let _ = tx.rollback().await;
144+ Err(e)
145+ }
146+ }
147+}
148+
149+/// Runs a query and maps every row. Used for lists.
150+pub async fn fetch_all<T, P>(
151+ conn: &Connection,
152+ sql: &str,
153+ params: P,
154+ map: impl Fn(&Row) -> Result<T>,
155+) -> Result<Vec<T>>
156+where
157+ P: IntoParams,
158+{
159+ let mut rows = conn.query(sql, params).await.map_err(db_err)?;
160+ let mut out = Vec::new();
161+ while let Some(row) = rows.next().await.map_err(db_err)? {
162+ out.push(map(&row)?);
163+ }
164+ Ok(out)
165+}
166+
167+/// Runs a query and maps its first row, if there is one.
168+pub async fn fetch_opt<T, P>(
169+ conn: &Connection,
170+ sql: &str,
171+ params: P,
172+ map: impl Fn(&Row) -> Result<T>,
173+) -> Result<Option<T>>
174+where
175+ P: IntoParams,
176+{
177+ let mut rows = conn.query(sql, params).await.map_err(db_err)?;
178+ match rows.next().await.map_err(db_err)? {
179+ Some(row) => Ok(Some(map(&row)?)),
180+ None => Ok(None),
181+ }
182+}
183+
184+/// Wraps a database error with its text. Constraint violations are handled by the caller, which knows
185+/// what the user should be told (see [`insert_err`]).
186+pub fn db_err(e: turso::Error) -> Error {
187+ Error::Database(e.to_string())
188+}
189+
190+/// Maps a `UNIQUE` violation to a conflict with `conflict_msg`, and any other error to `Database`.
191+pub fn insert_err(e: turso::Error, conflict_msg: &str) -> Error {
192+ match e {
193+ turso::Error::Constraint(ref msg) if msg.to_ascii_uppercase().contains("UNIQUE") => {
194+ Error::Conflict(conflict_msg.to_string())
195+ }
196+ other => db_err(other),
197+ }
198+}
199+
200+/// The error for a query that must return a row and did not.
201+pub fn missing_row() -> Error {
202+ Error::Database("expected a row that is not there".into())
203+}
204+
205+/// Reads column `i` as text. A value of another type is a database error.
206+pub fn col_text(row: &Row, i: usize) -> Result<String> {
207+ match row.get_value(i).map_err(db_err)? {
208+ Value::Text(s) => Ok(s),
209+ _ => Err(Error::Database(format!("column {i} is not text"))),
210+ }
211+}
212+
213+/// Reads column `i` as an integer. A value of another type is a database error.
214+pub fn col_int(row: &Row, i: usize) -> Result<i64> {
215+ match row.get_value(i).map_err(db_err)? {
216+ Value::Integer(n) => Ok(n),
217+ _ => Err(Error::Database(format!("column {i} is not an integer"))),
218+ }
219+}
220+
221+/// Reads column `i` as a string whatever its type, for diagnostics and pragmas.
222+pub fn col_to_string(row: &Row, i: usize) -> Result<String> {
223+ match row.get_value(i).map_err(db_err)? {
224+ Value::Text(s) => Ok(s),
225+ Value::Integer(n) => Ok(n.to_string()),
226+ Value::Real(f) => Ok(f.to_string()),
227+ Value::Null => Ok("NULL".into()),
228+ Value::Blob(_) => Ok("<blob>".into()),
229+ }
230+}
231+
232+#[cfg(test)]
233+mod tests {
234+ use super::*;
235+
236+ #[tokio::test]
237+ async fn opening_twice_is_idempotent_and_settings_persist() {
238+ let dir = tempfile::tempdir().unwrap();
239+ let path = dir.path().join("in.db");
240+
241+ let store = Store::open(&path).await.unwrap();
242+ store.set_setting("probe", "one").await.unwrap();
243+ drop(store);
244+
245+ // The second open runs the same migrations again; they must do nothing.
246+ let store = Store::open(&path).await.unwrap();
247+ assert_eq!(
248+ store.get_setting("probe").await.unwrap().as_deref(),
249+ Some("one")
250+ );
251+ store.set_setting("probe", "two").await.unwrap();
252+ assert_eq!(
253+ store.get_setting("probe").await.unwrap().as_deref(),
254+ Some("two")
255+ );
256+ }
257+}
crates/in-core/src/store/settings.rsadded+34 -0
@@ -0,0 +1,34 @@
1+//! The `settings` key/value table: runtime overrides that the admin UI writes. Precedence is UI
2+//! override, then the config file, then the built-in default; this module only stores and reads the
3+//! UI layer.
4+
5+use crate::error::Result;
6+use crate::store::{Store, col_text, db_err, fetch_opt};
7+use crate::time::now_stamp;
8+
9+impl Store {
10+ /// The stored value for `key`, or `None` when no override is set.
11+ pub async fn get_setting(&self, key: &str) -> Result<Option<String>> {
12+ let conn = self.read_conn().await;
13+ fetch_opt(
14+ &conn,
15+ "SELECT value FROM settings WHERE key = ?1",
16+ (key.to_string(),),
17+ |row| col_text(row, 0),
18+ )
19+ .await
20+ }
21+
22+ /// Stores `value` for `key`, replacing any earlier value.
23+ pub async fn set_setting(&self, key: &str, value: &str) -> Result<()> {
24+ let conn = self.inner.conn.lock().await;
25+ conn.execute(
26+ "INSERT INTO settings (key, value, updated_at) VALUES (?1, ?2, ?3) \
27+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
28+ (key.to_string(), value.to_string(), now_stamp()),
29+ )
30+ .await
31+ .map_err(db_err)?;
32+ Ok(())
33+ }
34+}
crates/in-core/src/store/snapshot.rsadded+114 -0
@@ -0,0 +1,114 @@
1+//! Consistent copies of the database for backups. The copy is made with `VACUUM INTO` on the writer,
2+//! so no write can interleave with it. A WAL-mode copy keeps its rows in a sidecar file, so the copy is
3+//! then checkpointed until it is one self-contained file.
4+
5+use std::path::Path;
6+
7+use turso::Builder;
8+
9+use crate::error::{Error, Result};
10+use crate::store::{Store, col_int, db_err, fetch_all};
11+
12+impl Store {
13+ /// Writes a consistent copy of the database to `dest`, then fsyncs it. `dest` must not exist.
14+ pub async fn snapshot_to(&self, dest: &Path) -> Result<()> {
15+ if std::fs::symlink_metadata(dest).is_ok() {
16+ return Err(Error::Conflict(format!(
17+ "snapshot target already exists: {}",
18+ dest.display()
19+ )));
20+ }
21+ let text = dest.to_str().ok_or_else(|| {
22+ Error::Config(format!("snapshot path is not UTF-8: {}", dest.display()))
23+ })?;
24+ let sql = format!("VACUUM INTO {}", sql_string_literal(text)?);
25+ {
26+ let conn = self.inner.conn.lock().await;
27+ conn.execute(&sql, ()).await.map_err(db_err)?;
28+ }
29+ make_self_contained(dest).await?;
30+ std::fs::File::open(dest)?.sync_all()?;
31+ Ok(())
32+ }
33+}
34+
35+/// A SQL string literal for `text`, with single quotes doubled. Paths are the only input, and they come
36+/// from the operator, but a NUL byte is still refused.
37+fn sql_string_literal(text: &str) -> Result<String> {
38+ if text.contains('\0') {
39+ return Err(Error::Invalid("path contains NUL".into()));
40+ }
41+ Ok(format!("'{}'", text.replace('\'', "''")))
42+}
43+
44+/// Checkpoints the copy so every frame is in the main file, then removes the WAL and shared-memory
45+/// sidecars when they are empty. A sidecar that still holds bytes is an error: the main file alone
46+/// would then not be the whole database.
47+async fn make_self_contained(dest: &Path) -> Result<()> {
48+ let text = dest
49+ .to_str()
50+ .ok_or_else(|| Error::Config(format!("snapshot path is not UTF-8: {}", dest.display())))?;
51+ let db = Builder::new_local(text).build().await.map_err(db_err)?;
52+ let conn = db.connect().map_err(db_err)?;
53+ // Columns: busy flag, frames in the log, frames checkpointed.
54+ let status = fetch_all(&conn, "PRAGMA wal_checkpoint(TRUNCATE)", (), |row| {
55+ Ok((col_int(row, 0)?, col_int(row, 1)?, col_int(row, 2)?))
56+ })
57+ .await?;
58+ drop(conn);
59+ drop(db);
60+ match status.as_slice() {
61+ [(0, log, done)] if log == done => {}
62+ other => {
63+ return Err(Error::Database(format!(
64+ "checkpoint of the snapshot did not complete: {other:?}"
65+ )));
66+ }
67+ }
68+ for suffix in ["-wal", "-shm"] {
69+ let mut sidecar = dest.as_os_str().to_owned();
70+ sidecar.push(suffix);
71+ let sidecar = Path::new(&sidecar);
72+ match std::fs::metadata(sidecar) {
73+ Err(_) => {}
74+ Ok(meta) if meta.len() == 0 => std::fs::remove_file(sidecar)?,
75+ Ok(meta) => {
76+ return Err(Error::Database(format!(
77+ "snapshot still has {} bytes in {}",
78+ meta.len(),
79+ sidecar.display()
80+ )));
81+ }
82+ }
83+ }
84+ Ok(())
85+}
86+
87+#[cfg(test)]
88+mod tests {
89+ use super::*;
90+ use crate::error::Error;
91+
92+ #[tokio::test]
93+ async fn snapshot_is_a_single_file_that_opens_with_the_same_data() {
94+ let dir = tempfile::tempdir().unwrap();
95+ let store = Store::open(&dir.path().join("in.db")).await.unwrap();
96+ store.set_setting("probe", "snap").await.unwrap();
97+
98+ let dest = dir.path().join("snap.db");
99+ store.snapshot_to(&dest).await.unwrap();
100+ assert!(!dir.path().join("snap.db-wal").exists());
101+
102+ let copy = Store::open(&dest).await.unwrap();
103+ assert_eq!(
104+ copy.get_setting("probe").await.unwrap().as_deref(),
105+ Some("snap")
106+ );
107+
108+ // A second snapshot to the same path must not overwrite the first.
109+ assert!(matches!(
110+ store.snapshot_to(&dest).await,
111+ Err(Error::Conflict(_))
112+ ));
113+ }
114+}
crates/in-core/src/time.rsadded+61 -0
@@ -0,0 +1,61 @@
1+//! UTC time stamps stored as text. The format is RFC 3339 with nine fractional digits and a `Z`
2+//! suffix. Its width is fixed, so comparing stamps as text gives time order.
3+
4+use std::time::Duration;
5+
6+use time::{
7+ OffsetDateTime, SignedDuration, format_description::FormatItem, macros::format_description,
8+};
9+
10+const FORMAT: &[FormatItem<'static>] =
11+ format_description!("[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:9]Z");
12+
13+fn format_stamp(at: OffsetDateTime) -> String {
14+ // The format description only uses fields that always format, so this cannot fail.
15+ at.format(FORMAT).unwrap_or_default()
16+}
17+
18+/// The current time as a stamp.
19+pub fn now_stamp() -> String {
20+ format_stamp(OffsetDateTime::now_utc())
21+}
22+
23+/// The stamp for `now + after`. Saturates at the largest representable time instead of panicking.
24+pub fn stamp_after(after: Duration) -> String {
25+ let delta = SignedDuration::try_from(after).unwrap_or(SignedDuration::MAX);
26+ format_stamp(OffsetDateTime::now_utc().saturating_add(delta))
27+}
28+
29+/// The stamp for `now - before`. Saturates at the smallest representable time instead of panicking.
30+pub fn stamp_before(before: Duration) -> String {
31+ let delta = SignedDuration::try_from(before).unwrap_or(SignedDuration::MAX);
32+ format_stamp(OffsetDateTime::now_utc().saturating_sub(delta))
33+}
34+
35+#[cfg(test)]
36+mod tests {
37+ use super::*;
38+
39+ fn is_valid_stamp(s: &str) -> bool {
40+ let b = s.as_bytes();
41+ b.len() == 30
42+ && b[4] == b'-'
43+ && b[7] == b'-'
44+ && b[10] == b'T'
45+ && b[13] == b':'
46+ && b[16] == b':'
47+ && b[19] == b'.'
48+ && b[29] == b'Z'
49+ && b[20..29].iter().all(u8::is_ascii_digit)
50+ }
51+
52+ #[test]
53+ fn stamps_have_fixed_width_and_sort_in_time_order() {
54+ let now = now_stamp();
55+ let later = stamp_after(Duration::from_secs(3600));
56+ assert!(is_valid_stamp(&now), "bad stamp: {now}");
57+ assert!(is_valid_stamp(&later), "bad stamp: {later}");
58+ assert!(now < later);
59+ assert!(stamp_before(Duration::from_secs(3600)) < now);
60+ }
61+}
crates/in-core/src/token.rsadded+56 -0
@@ -0,0 +1,56 @@
1+//! Random tokens, readable codes and constant-time comparison. Tokens are shown to the user once and
2+//! stored only as their SHA-256 hash, so a leaked database does not reveal a usable token.
3+
4+use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _};
5+use sha2::{Digest, Sha256};
6+use subtle::ConstantTimeEq;
7+
8+/// Alphabet for codes that people type: lowercase letters and the digits 2 to 9, without look-alikes
9+/// such as `l`, `o`, `0` and `1`. It has exactly 32 symbols, so the low five bits of a random byte
10+/// pick one with no bias.
11+pub const READABLE_ALPHABET: &[u8; 32] = b"abcdefghijkmnpqrstuvwxyz23456789";
12+
13+/// A session or share token: 32 random bytes, base64url without padding (43 characters).
14+pub fn generate_token() -> String {
15+ let mut buf = [0u8; 32];
16+ rand::fill(&mut buf);
17+ BASE64_URL_SAFE_NO_PAD.encode(buf)
18+}
19+
20+/// `len` random characters from [`READABLE_ALPHABET`].
21+pub fn random_readable(len: usize) -> String {
22+ let mut buf = vec![0u8; len];
23+ rand::fill(buf.as_mut_slice());
24+ buf.iter()
25+ .map(|b| char::from(READABLE_ALPHABET[usize::from(b & 31)]))
26+ .collect()
27+}
28+
29+/// Lowercase hex SHA-256 of `token`. This is what the database stores.
30+pub fn hash_token(token: &str) -> String {
31+ hex::encode(Sha256::digest(token.as_bytes()))
32+}
33+
34+/// Compares two byte strings in time that does not depend on where they first differ. Different
35+/// lengths are unequal; the length itself is not hidden.
36+pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
37+ a.ct_eq(b).into()
38+}
39+
40+#[cfg(test)]
41+mod tests {
42+ use super::*;
43+
44+ #[test]
45+ fn constant_time_eq_matches_ordinary_equality() {
46+ assert!(constant_time_eq(b"same", b"same"));
47+ assert!(!constant_time_eq(b"same", b"diff"));
48+ assert!(!constant_time_eq(b"short", b"longer"));
49+ assert!(constant_time_eq(b"", b""));
50+ // Known vector: SHA-256 of "abc".
51+ assert_eq!(
52+ hash_token("abc"),
53+ "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
54+ );
55+ }
56+}
crates/in-web/Cargo.tomladded+10 -0
@@ -0,0 +1,10 @@
1+[package]
2+name = "in-web"
3+description = "The `in` binary: pages, HTTP APIs, workers and the CLI"
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+publish = false
8+
9+[lints]
10+workspace = true
crates/in-web/src/main.rsadded+6 -0
@@ -0,0 +1,6 @@
1+//! Entry point of the `in` binary. This is a placeholder until the boot sequence exists; it only
2+//! proves that the workspace builds.
3+
4+fn main() {
5+ println!("in");
6+}
docs/architecture.mdadded+252 -0
@@ -0,0 +1,252 @@
1+# in architecture
2+
3+`in` is the family's file drive: folders, uploads (resumable), previews and thumbnails, trash, sharing with
4+people and by link, quotas, and an object store that other family apps use through a machine API. Read
5+`docs/contracts.md` (cross-app API) and `docs/conventions.md` (how code is written) first.
6+
7+Status: design for the rebuild. `~/Documents/Code/Rust/old_in` is a feature reference only;
8+`docs/reference/old-inventory.md` lists its features (the parity checklist) and its defects (section 12 there),
9+which must not be carried over.
10+
11+---
12+
13+## 1. Goals
14+
15+- **Your files outlive the app.** The blob tree is plain files named by id, and `admin export` writes a
16+ normal directory tree (real folder and file names) that needs no `in` to read.
17+- **Feature parity** with old in (inventory sections 2–3).
18+- **Better than old in:** CSRF everywhere, local sessions (no per-request call to `im`), back-channel logout,
19+ machine API with `im` JWTs instead of minted bearer keys (contracts.md 5), streaming uploads everywhere (no
20+ whole-file buffering), fsync on every blob write, security headers, rate-limited share passwords, every page
21+ translated, real `/healthz`.
22+
23+Not goals now (`docs/backlog.md`): file versioning, WebDAV, end-to-end encryption, desktop sync client,
24+office document editing.
25+
26+---
27+
28+## 2. Crates and modules
29+
30+```
31+in/
32+ crates/
33+ in-core/ domain, store, migrations, config, secret, token, time, names, sniff, authz, quota math, blob trait + backends, thumbs
34+ in-web/ binary `in`: pages, OIDC client, directory mirror, machine API, upload API, share pages, live, workers, CLI
35+```
36+
37+**in-core**
38+- `error.rs`, `time.rs`, `config.rs`, `settings.rs`, `secret.rs`, `token.rs`, `password.rs` (share passwords)
39+- `names.rs`: display-name rules (inventory 2.2 "Name rules": strip path components and control characters,
40+ empty → "Untitled", ≤255 chars by `char`, collision postfix " (2)" before the extension for files, appended for
41+ folders; files and folders are separate namespaces; comparison is exact)
42+- `sniff.rs`: magic-number sniffing (inventory 5.6, plus SVG detection so SVG is never inline), never trusts
43+ the client's type
44+- `authz.rs`: section 6
45+- `blob/`: `mod.rs` (`BlobStore` trait: `put_stream`, `adopt_file`, `open_range`, `size`, `delete`, `list`),
46+ `local.rs` (temp file + fsync + rename + dir fsync), `s3.rs` (`object_store` S3 client for R2, Hetzner Object
47+ Storage or any S3 endpoint; multipart for large objects)
48+- `thumbs.rs`: images with the `image` crate (decode limits: 64 MiB source, 40 megapixels, 10 s on
49+ `spawn_blocking`), video through `ffmpeg` when present (10 s kill, temp file in `data_dir/tmp` mode 0600),
50+ WebP output, max edge 512
51+- `store/`: `users.rs` (local mirror of members), `sessions.rs`, `folders.rs`, `files.rs`, `trash.rs`,
52+ `shares.rs`, `links.rs`, `uploads.rs`, `services.rs` (service namespaces and objects), `audit.rs`,
53+ `settings.rs`, `snapshot.rs`, `migrate.rs`
54+
55+**in-web**
56+- `main.rs`, `boot.rs`, `state.rs`, `admin_cli.rs`, `auth.rs`, `throttle.rs`, `client_ip.rs`
57+- `oidc/` (client: discovery cache, JWKS cache, login, callback, logout, back-channel endpoint, client-credentials
58+ token cache), `directory.rs` (mirror worker), `family.rs` (switcher list worker)
59+- `api/objects.rs` + `api/machine_auth.rs` (contracts.md 5), `api/upload.rs` (chunked upload JSON API)
60+- `pages/` (`drive.rs`, `view.rs`, `trash.rs`, `shared.rs`, `share_dialog.rs`, `links.rs`, `settings.rs`,
61+ `admin.rs`, `public_share.rs`, `files.rs` (byte serving), `thumbs.rs`, `avatar.rs`, `not_found.rs`)
62+- `serve_bytes.rs`: one function that serves a blob with Range, ETag, disposition and the byte-response headers
63+ (section 7) for every byte route
64+- `views/`, `i18n/`, `live.rs`, `audit.rs`, `assets.rs`, workers (`sweeper.rs`, `thumbs_worker.rs`, `backup.rs`)
65+- `assets/nav.js`, `assets/drive.js` (upload queue: chunking, resume, retry, progress, drop zone; context
66+ menus; dropdowns), `assets/player.js` (media player), `assets/offline.html`, `assets/sw.js`
67+
68+---
69+
70+## 3. Data model
71+
72+**members** (mirror of `im`'s directory, contracts.md 3; one row per person)
73+- `sub` TEXT PK, `email`, `name`, `is_admin`, `disabled`, `locale`, `zoneinfo`, `picture_version`,
74+ `im_updated_at`, `first_seen_at`, `last_sign_in_at` NULL
75+- `theme` TEXT NOT NULL DEFAULT 'system' CHECK IN ('system','light','dark'), `locale_override` NULL
76+- `quota_bytes` INTEGER NOT NULL, `used_bytes` INTEGER NOT NULL DEFAULT 0 CHECK (used_bytes >= 0)
77+
78+**sessions**: `id` PK, `sub` FK members CASCADE, `token_hash` UNIQUE, `csrf_token`, `im_sid`, `created_at`,
79+`expires_at` (≤12 h, contracts.md 2.4), `last_seen_at`, `ip`, `user_agent`. Index on `im_sid` and `sub`.
80+
81+**oidc_flights**: none in the DB; the login flight (verifier, state, nonce, next) is a sealed
82+`__Host-in_flight` cookie, 10 minutes, SameSite=Lax (it must survive the redirect back from `im`).
83+
84+**seen_logout_jti**: `jti` PK, `expires_at` (replay guard for back-channel logout tokens).
85+
86+**folders**: `id` PK, `owner` FK members, `parent_id` NULL FK folders, `name`, `created_at`, `updated_at`,
87+`trashed_at` NULL, `trash_root` NULL (id of the folder whose trashing trashed this one; restore restores exactly
88+that set). Partial unique index `(owner, parent_id, name) WHERE trashed_at IS NULL` (parent NULL handled with
89+`COALESCE(parent_id, '')`), so postfixing is checked by the database.
90+
91+**files**: `id` PK, `owner` FK members, `folder_id` NULL FK folders, `name`, `mime` (sniffed), `size`,
92+`sha256`, `blob_key` (`files/<id[0..2]>/<id>`), `thumb_state` CHECK IN ('none','pending','ready','failed','skip'),
93+`download_count`, `created_at`, `updated_at`, `trashed_at` NULL, `trash_root` NULL. Same partial unique index on
94+live names per folder.
95+
96+**grants** (per-person shares): `id` PK, `target_kind` CHECK IN ('file','folder'), `target_id`, `owner`,
97+`grantee` FK members CASCADE, `can_download` 0/1, `created_at`; UNIQUE (target_kind, target_id, grantee);
98+index on `grantee`.
99+
100+**links** (public share links): `id` PK, `token_hash` UNIQUE, `token_sealed` (so the owner can see the URL
101+again), `target_kind`, `target_id`, `owner`, `can_download`, `password_hash` NULL, `expires_at` NULL,
102+`revoked_at` NULL, `created_at`, `last_used_at` NULL, `use_count`.
103+
104+**uploads**: `id` PK, `owner`, `folder_id` NULL, `name`, `size`, `chunk_size`, `state` CHECK IN
105+('active','done','aborted'), `file_id` NULL, `created_at`, `expires_at` (24 h).
106+
107+**services** (namespaces for machine callers): `key` PK (the token's `svc`), `quota_bytes`, `used_bytes`,
108+`created_at`. Created on first authorised call with the default quota from settings.
109+
110+**objects**: `service` FK services, `external_id`, `size`, `sha256`, `content_type`, `name` NULL, `blob_key`
111+(`objects/<service>/<sha256-of-external_id>`), `created_at`, `updated_at`; PK (service, external_id).
112+
113+**audit_log**, **settings**: per conventions.
114+
115+Quota rule (one place, `quota.rs`): `used_bytes` = sum of `size` of the person's files, live and trashed, kept
116+up to date inside the same transaction as every insert, replace, purge; headroom for a new upload = quota −
117+used − sizes declared by the person's other active uploads. A nightly check recomputes and logs any drift.
118+
119+Blob tree (`[storage] backend = "local"`, root `data_dir/blobs`): `files/<2 hex>/<id>`, `thumbs/<2 hex>/<id>.webp`,
120+`objects/<service>/<sha>`, staging `data_dir/uploads/<upload id>/<index>` (always local). Ordering contract: bytes
121+are durable at their key before the row that names them commits; bytes are deleted only after the row is gone.
122+The sweeper removes unreferenced blobs older than 24 h.
123+
124+---
125+
126+## 4. Routes
127+
128+### 4.1 Pages (session required unless noted)
129+
130+| Path | What |
131+|---|---|
132+| `GET /` | signed out: sign-in card; signed in: redirect to `/drive` |
133+| `GET /drive`, `GET /drive/{folder_id}` | folder listing (inventory 2.2): sort, kind filter, search (`?q=`), breadcrumbs, row menus, rename in place, new folder, upload, drop zone, move dialog, share dialog |
134+| `POST /folders`, `/folders/{id}/rename`, `/folders/{id}/move`, `/folders/{id}/trash` | folder writes |
135+| `POST /files` (multipart, streamed), `/files/{id}/rename`, `/files/{id}/move`, `/files/{id}/trash` | file writes |
136+| `GET /view/{id}` | viewer page (image, video, audio, PDF, text; inventory 2.4) |
137+| `GET /file/{id}` (`?dl=1`), `GET /thumb/{id}` | bytes (section 7) |
138+| `GET /trash`, `POST /trash/restore`, `/trash/purge`, `/trash/empty` | trash |
139+| `GET /shared` | items shared with me |
140+| `POST /grants`, `/grants/{id}/update`, `/grants/{id}/remove` | per-person shares (grantee chosen from the members mirror) |
141+| `GET /links`, `POST /links`, `/links/{id}/revoke`, `/links/{id}/remint` | my share links |
142+| `GET/POST /s/{token}` (anonymous) | public share page, folder browsing, password gate, download, media, thumbs |
143+| `GET /settings` + POST | preferences (theme; language follows `im` unless overridden), storage usage |
144+| `GET /admin` + POSTs (instance admin) | people with quotas (set quota), services with quotas, default quotas, storage backend status, base URL, audit log, health |
145+| `GET /avatar/{sub}` | photo proxy with disk cache (contracts.md 3.2) |
146+| `GET /auth/login`, `/auth/callback`, `POST /auth/logout`, `POST /auth/backchannel-logout` | OIDC client |
147+| `GET /-/alive`, live streams, `/healthz`, `/assets/*` | |
148+
149+### 4.2 JSON APIs
150+
151+- Upload (session + CSRF header `X-CSRF-Token`): `POST /api/uploads` `{folder_id?, name, size}` →
152+ `{id, chunk_size}`; `GET /api/uploads/{id}` → state with received chunk indexes; `PUT /api/uploads/{id}/{index}`
153+ (raw body, ≤ chunk size); `POST /api/uploads/{id}/finish` → `{file_id}`; `DELETE /api/uploads/{id}`.
154+ Chunk size 8 MiB; files under 8 MiB may use `POST /files`.
155+- Objects for services: contracts.md 5.
156+
157+---
158+
159+## 5. Sign-in
160+
161+Per contracts.md 2: `/auth/login?next=` builds the flight cookie and redirects to `im`; `/auth/callback`
162+validates state, exchanges the code (client_secret_basic), validates the ID token, upserts the member from its
163+claims (so a person can use `in` before the directory stream catches up), creates a local session (12 h), and
164+redirects to `next`. The client secret is read from `data_dir/oidc_client_secret` (0600) or the
165+`IN_OIDC_CLIENT_SECRET` environment variable, never from the TOML. A member with `disabled` set cannot sign in
166+and has no sessions.
167+
168+---
169+
170+## 6. Authorization
171+
172+`authz::authorize(actor, target, grant, action)`:
173+- `actor`: `Anonymous`, `Member { sub, is_admin }`, `Link { link }` (a validated share-link visit),
174+ `Service { key, scopes }`.
175+- `target`: a file or folder with owner and trashed state, plus the effective grant (the most permissive grant
176+ on the item or any live ancestor folder) and, for links, whether the item is inside the linked folder.
177+- `action`: `List`, `View` (see name, preview inline), `Download`, `Write` (rename, move, upload into, trash),
178+ `Share`, `Purge`, `Administer`.
179+- Rules: owner may do everything on their items (trashed items: only `View`, `Download`, restore, `Purge`);
180+ grantee: `List` and `View`, `Download` when `can_download`, never on trashed items; link visitor: the same as
181+ a grantee within the link's subtree; admin: `Administer` only (an admin does **not** read other people's
182+ files); anything else is `NotFound`.
183+
184+---
185+
186+## 7. Byte serving (one function for every byte route)
187+
188+- Single `Range` (`a-b`, `a-`, `-n`), 206 / 416; `ETag` = `"<sha256>"`; `If-None-Match` → 304.
189+- `Content-Disposition`: `inline` only for image/* (not SVG, not HEIC), video/*, audio/*, application/pdf,
190+ text/plain, and only when the action allows `View` and `dl` is not set; otherwise `attachment`. Always both
191+ `filename="<ascii fallback>"` and `filename*=UTF-8''<percent-encoded>`.
192+- Every byte response: `X-Content-Type-Options: nosniff`,
193+ `Content-Security-Policy: default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; sandbox`,
194+ `Cross-Origin-Resource-Policy: same-origin`, `Cache-Control: private, max-age=31536000, immutable` for
195+ content addressed by id and hash, `private, no-cache` for share-link bytes.
196+- Streams from the blob store in 64 KiB frames; never buffers a whole file.
197+- The download counter counts a forced download that starts at byte 0, once per request.
198+
199+---
200+
201+## 8. Share links
202+
203+- Token: 32 random bytes; DB stores the SHA-256 and a sealed copy for the owner to re-display.
204+- Options: can download, password (argon2id), expiry (1 hour to 1 year, or none).
205+- Password gate: POST checks the password (throttled per link and per IP: 10 failures / 15 min) and sets a cookie
206+ `__Host-in_link_<id>` = HMAC-SHA256(instance key, "link-unlock:" || link id || password_hash), 12 h, so
207+ changing the password or remint invalidates old unlocks.
208+- Dead links (revoked, expired, target trashed or purged) answer one identical "link no longer works" page.
209+- Remint creates the new link and revokes the old one in one transaction.
210+
211+---
212+
213+## 9. Workers
214+
215+- **directory**: full fetch, then stream (contracts.md 3), resync on gap; applies member changes; on
216+ `disabled` or `deleted` ends the person's sessions. Backoff 1 s → 30 s.
217+- **family**: fetches the switcher list every 5 minutes.
218+- **thumbs**: picks `pending` files, generates thumbnails with bounded concurrency (2), marks ready/failed.
219+- **sweeper** (hourly): expired sessions, expired uploads (staging removed), seen JTIs, trash past
220+ `purge_after_days`, unreferenced blobs older than 24 h, quota drift check (nightly).
221+- **backup** (optional): snapshot + blob tree manifest, keep N, dead-man pings.
222+
223+---
224+
225+## 10. Settings (UI > file > default)
226+
227+`default_quota_bytes` (10 GiB), `default_service_quota_bytes` (10 GiB), `purge_after_days` (30),
228+`max_upload_bytes` (50 GiB), `link_max_days` (365), `base_url`, `trusted_proxies`; storage backend and its
229+credentials (S3 secret sealed) are Restart settings.
230+
231+---
232+
233+## 11. CLI
234+
235+`in admin backup --out DIR`, `in admin backup-verify SET`, `in admin restore --from SET --data-dir NEW`,
236+`in admin export --user <sub|email> --out DIR` (plain tree with real names), `in admin fsck` (every row has
237+its blob, every blob has a row, sizes and hashes match; `--repair-thumbs`), `in admin audit-purge
238+--older-than-days N`.
239+
240+---
241+
242+## 12. Build order
243+
244+1. Scaffold (workspace, core basics, store + 0001, boot, healthz, assets, shell, nav.js, i18n, headers, 404).
245+2. OIDC client, local sessions, back-channel logout, members mirror, avatar proxy, switcher.
246+3. Blob stores (local, S3) and `serve_bytes`.
247+4. Drive: folders, files, small uploads, rename, move, trash, restore, purge, search, sort, quota.
248+5. Chunked upload API and `drive.js`.
249+6. Viewer, thumbnails worker, media player.
250+7. Grants, shared page, links, public share pages.
251+8. Machine object API.
252+9. Settings, admin, audit, live topics, sweeper, backup, export, fsck, 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+549 -0
@@ -0,0 +1,549 @@
1+# "in" (old_in) - complete feature inventory for a from-scratch rebuild
2+
3+Source tree: /home/tahinli/Documents/Code/Rust/old_in (read-only inventory; nothing modified).
4+Crates: crates/in-core (store, config, thumbs, live), crates/in-client (OIDC client to im), crates/in-web (HTTP app on topcoat 0.9.0).
5+Method: every source file was read by a dedicated pass (turso_store.rs and tests were split), then cross-checked by grep. Items marked "(unverified)" were not confirmed against source.
6+
7+---
8+
9+## 1. Purpose
10+
11+1. "in" is a personal file drive: folders, file upload (small and chunked/resumable), download, preview, thumbnails, trash, share links, per-person shares, quotas.
12+2. Sign-in is delegated to sibling app "im" (OIDC, PKCE, RS256 id_token, introspection per request). im also provides the user directory (full pass + live stream) and avatars.
13+3. Storage is local disk (default) or Cloudflare R2 (S3 API) for final blobs; upload staging is always local.
14+4. A machine "service API" (bearer keys) lets other family apps push, fetch and delete blobs against a per-service account and quota.
15+5. Single binary, server-rendered HTML with small inline JS, SSE for live updates, SQLite-compatible Turso database.
16+
17+---
18+
19+## 2. User-facing features
20+
21+Conventions: "owner" = the signed-in user who owns a row. Cross-owner access always answers 404 (never 403) on purpose. Mutations are HTML form POSTs that answer 303 back to the page with `?refusal=<code>&on=<call>` on failure. JSON "API" routes answer HTTP 200 with `{"ok": ...}` or `{"err": "<Name>"}`. Unauthenticated page GETs redirect 303 to `/`.
22+
23+### 2.1 Sign-in and session
24+- GET `/` : signed-in browser gets 303 to `/drive`; signed-out gets the sign-in card (link to `/auth/login`). Store error renders a scaffold note.
25+- GET `/auth/login` : OIDC start. Sets flight cookie `in_session_pkce` (sealed JSON {verifier, state, nonce, next, exp}, Max-Age 600). 303 to `{issuer}/authorize` (response_type=code, scope "openid profile email", PKCE S256, 32-byte verifier, 16-byte state and nonce). `next` accepted only as a local absolute path.
26+- GET `/auth/callback` : `?error=X` -> `/?auth_error=X`; missing code/state or flight cookie -> `invalid_request`; expired flight or state mismatch -> `invalid_state`; exchange failure -> `exchange_failed`. Success sets session cookie and redirects to `next`.
27+- GET `/auth/logout` : clears `in_session`, 303 to `{issuer}/logout?back=<origin>/`. (State-changing GET; logout CSRF possible, see oddities.)
28+- Per request: `current_user` opens the session cookie, checks local exp, then introspects with im every request. Only explicit `active:false` clears the cookie; transport errors read as signed out but keep the cookie. A disabled local account reads as signed out. First provisioned user becomes admin.
29+- GET `/api/me` : session probe. 204 signed in, 401 signed out (empty body), 500 on store failure.
30+- GET `/whoami` : appears in one place as a route; probably test-only (unverified).
31+
32+### 2.2 Drive (browse, folders)
33+- GET `/drive` (`?folder=<id>`, `?q=`, `?sort=key:dir`, `?kind=all|folders|files`, `?edit=<id>`, `?share=kind:id`, `?move=kind:id`, `?created=<token>`, `?refusal=&on=`).
34+ - Owner view of a folder: `current_folder` requires owned, live folder with no trashed ancestor; otherwise 404 (store errors also 404). If that fails, `granted_folder` tries a grant; grantee gets the read-only `drive_shared` view. Otherwise 404.
35+ - Listing: subfolders first, then files, from `list_children`. Row: chip, name, "Shared" chip (from `shared_target_ids`, silent on error), size (files), created date, download count (files). Folder rows link `/drive?folder=`, file rows `/view/<id>`.
36+ - Row Options menu (details element): Rename (`?edit=`), Share (`?share=`), Move (`?move=`), Delete (POST), Download (files, `/file/<id>?dl=1`).
37+ - Breadcrumb trail root-first, hidden in search and at root; errors silently truncate it.
38+ - Sorting keys: name (default asc), uploaded (created_at), size, downloads. Bare key defaults: name asc, others desc. Unknown key = standing order. Folders sort by name for size/downloads. Ties broken by id. Sorting done in page layer.
39+ - Kind filter `all|folders|files` (unknown = all), applied after sort.
40+ - Filter bar: search box (`q`), sort select and kind select (autosubmit), "+" menu (New folder; upload input `#drive-upload-input`).
41+ - Search mode (`q` trimmed, non-empty): `store.search(user, q, 50)` library-wide, folders and files separately, ignores current folder; caption "Search results"; NoResults empty state; no row options.
42+ - Empty states: `EmptyFolder` (note a kind filter that hides everything also shows this), `NoResults`, `SharedFolderEmpty` for grantees.
43+ - Rename-in-place when `?edit=<id>`: inline form posting to `/api/folder/rename` or `/api/file/rename`, input maxlength 255, required.
44+ - Created-link panel `?created=<token>`: one-time share URL `{origin}/s/{token}` with "copy once" note.
45+ - Refusal banner from `?refusal=` for names create, rename, move, delete, upload (not share).
46+- GET `/search` : 303 to `/drive?q=<raw q>` (blank -> `/drive`). Only `q` forwarded.
47+- Move picker `?move=kind:id`: modal listing "Drive" root plus all owned live folders (depth-first, one list_children per folder, N+1). Folder target excludes its own subtree (display-path prefix match, a folder name containing " / " can confuse it). Each row is a POST form (`/api/file/move` with folder_id, or `/api/folder/move` with parent_id; blank = root).
48+- Share modal `?share=kind:id` rendered by `share.rs` (see 2.7).
49+- Grantee view `drive_shared`: granted folder title, "Shared with you" + access chip (View only / May download), listing with sort and kind only (q/edit/share/move ignored), trail stops at granted root, no write affordances.
50+
51+Folder mutations (all owner-only, POST, 303 back via `back_to`, refusal via redirect):
52+- POST `/api/folder/create` (`parent_id`, `name`). Parent must be owned and live. Blank name -> quick-create "New folder" (postfixed by store) and redirect to `/drive?folder=<parent>&edit=<newid>` (sort/kind dropped). Name not trimmed when stored.
53+- POST `/api/folder/rename` (`id`, `name`). Owned+live folder. No server-side trim, emptiness or length check in this layer (HTML maxlength only); the store enforces names.
54+- POST `/api/folder/move` (`id`, `parent_id`). Owned+live folder and parent. Cycles/self-nesting -> store `Cycle` -> refusal `Forbidden`.
55+- POST `/api/folder/delete` (`id`). Soft-trashes the subtree (store). Cross-owner / missing -> NotFound refusal.
56+- store error mapping: QuotaExceeded -> QuotaExceeded; NotFound/CrossOwner -> NotFound; Cycle -> Forbidden; other -> Unavailable.
57+
58+Name rules (store): labels only, path components stripped (`../../etc` stored as `etc`), control chars removed, empty -> "Untitled", max 255 chars (postfixed names truncate the stem so the total fits; the extension itself is not truncated). Collisions among live siblings get " (2)", " (3)"... inserted before the extension for files (`report.txt` -> `report (2).txt`; extension-less `note` -> `note (2)`), appended for folders (`root (2)`). Files and folders are separate namespaces. Name match is exact and case-sensitive (BINARY collation; "Zeta" sorts before "alpha").
59+
60+### 2.3 Upload
61+Two paths, both owner-only.
62+
63+A. Single-shot multipart (`POST /files`): fields `folder_id` (must precede file parts) and one or more `file` parts. Each part fully buffered in memory, then `insert_file`. Empty list = redirect with no refusal. Folder must be owned and live (else NotFound, redirect `/drive`). Stops at the first refusal; files already inserted stay; only that refusal is reported. Redirect `303 /drive?folder=<id>` (+ `&refusal=&on=upload`). Body limit 2 GiB (main.rs). Parse errors return Unavailable before any insert. Blob puts happen inside the store's write transaction.
64+
65+B. Chunked, resumable (JS in the drive page; threshold 8 MiB in JS `LIMIT = 8388608`; smaller files use A). Chunk size fixed at 8 MiB (`CHUNK_SIZE = 8388608`, server-fixed, returned by start). Chunk body limit 32 MiB (main.rs `/api/upload`).
66+- POST `/api/upload/start` body `{folder_id?, name, size_bytes}` -> `{id, chunk_size}`. Folder must be owned, live. Quota pre-check against user quota minus other active sessions' declared sizes (`staged_claim`). Creates session row `state=active`, `expires_at = now + 24h` (`UPLOAD_TTL_HOURS = 24`), and staging dir.
67+- GET `/api/upload/{id}` -> `{id, chunk_size, size_bytes, name, folder_id, uploaded: [indexes]}`. Works on expired sessions; lets the client skip staged chunks. Other owner / unknown -> `{"err":"NotFound"}`.
68+- PUT `/api/upload/{id}/{index}` raw body -> `{received_bytes, size_bytes}`. Index must be < chunk_count; byte length must equal the expected length (last chunk may be short) else `BadChunk`; expired or not-active -> `UploadExpired`. Written atomically to `uploads/<id>/<index>`. `received_bytes` is measured from disk, not incremented.
69+- POST `/api/upload/{id}/finish` -> `{ok: "<new file id>"}`. Requires all chunks; assembles them in order to a temp file, checks total size; MIME sniffed from first 1 MiB (never the uploader's claim); thumbnail computed outside the transaction; then in one IMMEDIATE transaction: re-checks session active and unexpired, parent live, quota (excluding this session's own claim), name collision (postfix, never refused); adopts the temp to `files/<id>`, puts thumb, inserts row, marks session `done`, refreshes usage; staging dir removed after commit. Chunks kept on refusal so the client can retry. Refusals: UploadExpired, NotFound, BadChunk, QuotaExceeded.
70+- POST `/api/upload/{id}/abort` -> `{ok: null}`. Marks active session aborted and removes staging dir. Idempotent (unknown id answers `{err:"not_found"}` in one path, per upload.rs).
71+- Client behaviour (JS in drive page): 3 attempts per chunk, backoff 1000*attempt ms; one session restart on UploadExpired; resume key in localStorage `in-upload:<folder>:<name>:<size>`.
72+- Expired sessions: boot sweep marks active sessions past `expires_at` as aborted and deletes staging dirs (`prune_expired_uploads`); rows are kept as aborted.
73+
74+Quota: `used_bytes` counts all live and trashed file bytes; checked at start, at finish and for service pushes. Staged sessions' declared sizes count against new uploads' headroom.
75+
76+### 2.4 Download, preview, viewer
77+- GET `/file/{id}` (`?dl=1` forces attachment; presence of the key counts, even `dl=0`).
78+ - Unauthenticated -> 303 `/`. Not visible (not owner and no grant, or trashed and not owner) -> 404.
79+ - Forced download needs `may_download` (owner, or grant with can_download; trashed files are not downloadable). Otherwise 404.
80+ - Inline only if not forced and mime in: image/* (except image/heic), video/*, audio/*, application/pdf, text/plain; never image/svg+xml or text/html (forced to attachment).
81+ - Content-Disposition: `inline|attachment; filename="<ascii-sanitised>"; filename*=UTF-8''<pct>`; ASCII fallback maps non-[A-Za-z0-9._-] to `_`.
82+ - Content-Type = stored mime (not re-sniffed). `Accept-Ranges: bytes`. `Cache-Control: private, max-age=31536000, immutable`.
83+ - Range: single `bytes=a-b`, `a-`, `-N` only; multi-range, malformed, start>end, `-0` ignored (full 200). Start past end -> 416 with `Content-Range: bytes */total`. Valid -> 206 with `Content-Range`.
84+ - Streams via `file_stream` (64 KiB frames per doc).
85+ - Download counter `download_count` incremented only when forced, successful, and either no Range or range starts at 0.
86+- GET `/thumb/{id}` : webp thumbnail (`image/webp`), visible to the same audience as `/file` (trashed owner can still fetch). Not visible -> plain 404. ETag = quoted FNV-1a hex of bytes; `If-None-Match` exact match -> 304; `Cache-Control: private, max-age=31536000, immutable`.
87+- GET `/view/{id}` : viewer page. Not visible -> framework 404. Shows entry chip, name, meta "mime · size", uploaded date, download count, details panel (size, uploaded, downloads). Back link: trashed -> `/trash`; `?from=shared` -> `/shared`; else `/drive`. Download button only when may_download; "View only" note for non-owner without download.
88+ - Viewer kinds (`viewer_kind`): Image (`<img>`, all viewers), Video and Audio (house media player, all viewers), PDF (`<object>`) and Text (`<iframe sandbox="">`) only with download grant, otherwise "preview unavailable"; everything else "preview unavailable". image/heic is download-only.
89+ - Media player: play, seek, volume, mute, speed 0.5-2, fullscreen (video); dead after media error or 5 s with readyState 0 and networkState 2.
90+ - Context menu blocked over the viewer stage (viewer_guard_script).
91+
92+### 2.5 Trash
93+- GET `/trash` (`?kind=all|folders|files`, `?q=` case-insensitive substring on name, `?sort=key:dir` with keys name, deleted (default, desc), uploaded, size; folders sort as size 0). Lists owner's trashed folders and files, each with a `...` menu: Restore and Delete forever. Trashed file rows link to `/view/<id>` (owner preview); trashed file chips use mime-class glyph (no thumbnail). Unauthenticated -> 200 message page (not a redirect). Empty-trash button shown only if the unfiltered list is non-empty.
94+- Soft delete: files via POST `/api/file/delete` (trash only, bytes kept, still count toward quota); folders via POST `/api/folder/delete` (subtree trashed with one shared timestamp).
95+- POST `/api/trash/restore` (`kind` file|folder, `id`): row must be owner's and trashed. File restore: refused if an ancestor folder is trashed; name collision postfixed; no quota check (trashed bytes already counted). Folder restore cascades to descendants stamped with the same timestamp; individually trashed rows keep their earlier stamp; top folder name postfixed; refused if parent chain trashed. Refusals mapped via `refusal_of` (AncestorTrashed -> refusal `restore`/`on`). Redirect to `/trash`.
96+- POST `/api/trash/purge` (`kind`, `id`): permanent. File: removes rows (share_link and share_user rows for the file too) then best-effort blob deletes (`files/<id>`, `thumbs/<id>`). Folder: deepest-first row deletion of the trashed subtree, files and blobs. Sessions whose folder is purged get folder_id NULL (finish into root). Unknown or live rows: refused (NotFound for files on the route side; purge_file returns Ok(false) on live rows, purge_folder returns NotFound).
97+- POST `/api/trash/empty`: purges everything the owner trashed (store `empty_trash`, guard re-checked under the write lock).
98+- Auto purge: `purge_expired(now - purge_after_days)` runs once at boot in the background (default 30 days). `open` itself never purges trash.
99+
100+### 2.6 Search
101+- Drive search (see 2.2) and `/search` redirect. Store `search(owner, q, limit)`: LIKE with escaped `%`, `_`, `\` (ESCAPE '\\'), ASCII case-insensitive under SQLite defaults (unverified on Turso), limit clamped 1..=100 per list, no pagination. Owner scoped; trashed hidden.
102+
103+### 2.7 Sharing
104+Per-person grants (`share_user`):
105+- Only the owner of a live target can add or list grants; only owner can remove (trashed targets allowed for removal).
106+- Grant has one flag: `can_download` (view-only = false). Re-sharing upserts and can flip the flag.
107+- Grantee by lowercased email from the im directory mirror; unknown address -> NotFound. Sharing with yourself is a silent Ok.
108+- POST `/api/share/user/add` (form: kind, target_id, email list). Multi-address is not atomic: loop returns early on the first unknown address (earlier grants persist).
109+- POST `/api/share/user/remove` (kind, target_id, email). Removing a non-existent grant is not an error.
110+- Share modal (rendered inside the drive page via `?share=`, not a route): people picker from im directory (`provision_user` per directory member on each render, so the GET path writes), grants list with name, email, access chip and Remove form. Shows only the first live link and hides the create form while one exists (the API allows several).
111+- GET `/shared`: grants made to the reader (folders and files; dead or trashed targets silently dropped). Signed-out visitor gets a 200 message page.
112+- Grantee access: `can_see` (any live ancestor folder grant counts, most permissive wins) and `can_download`.
113+
114+Public share links (`share_link`):
115+- POST `/api/share/link/create` (form: kind file|folder, target_id, can_download (absent = false; "", 0, false, no, off = false), expires_in_days (absent/blank = none; else positive integer, else Forbidden; no maximum; checked_mul by 86400), password (trimmed; blank = none)). Owner-only (CrossOwner/NotFound). 303 to `/settings?section=links` with `created=<token>` on success.
116+ - Token: 32 random bytes, base64url no padding (43 chars). Only SHA-256 (unsalted, base64url) is stored in `token_hash` (unique). Plaintext also sealed (XChaCha20-Poly1305, app key) into setting `share_token:{link_id}` so the owner can redisplay the URL; links created before sealing (or after key loss) show a masked value and a Remint action.
117+ - Origin: `base_url` setting if set, else config `public_origin()` (listen address). Share URL `{origin}/s/{token}`.
118+- POST `/api/share/link/revoke` (form id): sets `revoked_at = COALESCE(revoked_at, now)`; owner only; idempotent. Deletes the sealed token setting.
119+- POST `/api/share/link/remint` (form id): creates a fresh link with the same kind/target/flags (carries expiry only if still in the future; an elapsed expiry becomes no expiry), revokes the old one. Known issues: remint does not check revoked/expired on the source; creates before revoking.
120+- Expired links are not deleted; they stop resolving. Revoked/expired -> dead.
121+- Public page GET `/s/{token}` (no session; the token is the credential). Priority: `dl` > `media` > `thumb` > card.
122+ - Dead or unknown token: 200 HTML "no longer works" card (never 404; same status and body for dead and view-only-download).
123+ - Card: file card (name, mime, size; download only when can_download), or folder listing (folders then files by lowercase name; each file with thumbnail where ready). Folder browsing with `?folder=` and `?file=`; each folder ancestor must be live and owned by link owner.
124+ - `?dl=1`: download bytes (attachment) only if can_download; else dead card. Counts toward the file's download_count (same counter as owner downloads; not per link; counts before serving).
125+ - `?media=1`: inline video or audio regardless of can_download (range supported, `Content-Disposition: inline`, `Cache-Control: private, no-cache`).
126+ - `?thumb=1`: webp thumbnail regardless of can_download (`Cache-Control: private, max-age=31536000, immutable`, FNV ETag).
127+ - Password-protected link: without the proof cookie, GET shows a password gate (no file name). POST `/s/{token}` (form password) verifies with Argon2; success sets cookie `in_link_<link_id>` (value = base64url(SHA-256("token:phc")), Path=/s, HttpOnly, SameSite=Lax, Secure only if OIDC issuer is https, session cookie no Max-Age) and 303 to `/s/{token}`; failure 303 to `/s/{token}?wrong=1` with "Wrong password." The gate covers card, bytes, media and thumbs.
128+ - Downloads from links: `Content-Disposition: attachment; filename="<safe>"` (quotes, backslashes, control chars removed; raw UTF-8, no filename*), `Cache-Control: private, no-cache`.
129+ - No view counter, no use limit, no lockout or rate limit on password guesses.
130+
131+### 2.8 Quota
132+- Per-user `quota_bytes` (default from config `default_quota_bytes`, 10 GiB) and `used_bytes` (sum of all file sizes owned, live and trashed; recomputed on each mutation).
133+- Enforced on: folder create (none, folders are 0 bytes), upload start (pre-check), upload finish, file insert, service push. Restore and rename/move skip checks.
134+- Admin can set quota (see 2.9); lowering below usage is allowed and not enforced retroactively. Quota 0 accepted.
135+- Profile shows "used / quota" and a bar (`quota_percent`, capped at 100; quota 0 shows 100).
136+
137+### 2.9 Settings (`GET /settings`, `?section=profile|links|everyone|server|service`, `?saved=`, `?created=`, `?shown=`)
138+Rail: Profile and Links for everyone; Everyone, Server and Service for admins (non-admin requests for admin sections fall back to Profile). Reached from the user menu, not the topbar.
139+- Profile (all): display name and email (read-only, no profile edit route here), storage used bar, Connection card (OIDC issuer and client id, stream connected or reconnecting, age of last roster event and last full pass; secret never shown), preferences form.
140+ - POST `/api/settings/preferences`: `ui` in {instrument, ledger} (default instrument for new users; the migration default is ledger, see oddities), `theme` in {light, dark} (new users default dark), `language` in {en, tr} (default en). Unknown values refused (BadUi, BadTheme, BadLanguage). Success -> `/settings?section=profile&saved=preferences`.
141+- Links (all): lists the user's live links (skips revoked): target name, expiry (`Expires <RFC3339>` or Never), May download / View only, copy-once URL (`?created=`), revoke form, remint for legacy links.
142+- Everyone (admin): table of all users (name, admin and disabled chips, email, used/quota, forms).
143+ - POST `/api/settings/quota` (user_id, quota decimal, quota_unit MiB|GiB; 1 MiB = 1048576, 1 GiB = 1073741824). Refused for service accounts (ServiceQuota), BadLimit for negative/non-finite or unknown unit. Zero accepted. Amount rounded to 2 decimals (silent rounding on re-save).
144+ - POST `/api/settings/disable` (user_id, disabled). Missing `disabled` field means DISABLE (dangerous default). `""`, `0`, `false`, `no`, `off` (case-insensitive) mean enable; anything else disables. Self-disable refused (Forbidden). Admins can disable other admins. Disabling and enabling both announce Revoked to that user's open tabs.
145+- Server (admin): effective origin display; POST `/api/settings/base_url` (base_url): empty = fall back; non-empty must start http:// or https:// and must not end with `/` (Config::validate_base_url), else BadBaseUrl; stored in setting `base_url`.
146+- Service (admin): see section 3. POST `/api/settings/service_add` (service from mintable list, name), `/api/settings/service_rotate` (service), `/api/settings/service_revoke` (service). Minted key shown once via `?shown=<ticket>` (ticket exchanged once, in-memory shelf, 10 min TTL, lost on restart). Rotate and revoke are one-click after expanding a details element (no confirm).
147+
148+### 2.10 Admin-only controls outside settings
149+- Admin status comes from im's directory `admin` flag (mirrored), or the first user at provisioning.
150+- Disabled accounts are signed out on their next request.
151+- Family flyout (topbar app switcher) lists sibling services from im's family list with health dots (probes `{url}/healthz`, 2 s timeout, 30 s cache).
152+
153+### 2.11 Avatars
154+- GET `/avatar/{user_id}` (session required; no session -> 401 empty body). Unknown id or store error -> 404 with `Cache-Control: private, max-age=300`.
155+- ETag `"p{photo_version}"` (version from local row). `?v=<photo_version>` gives `private, max-age=31536000, immutable`; other requests `private, no-cache`. Exact `If-None-Match` -> 304 without contacting im.
156+- Otherwise fetches photo bytes from im (`directory.photo(oidc_sub)`), serves with im's content type (fallback octet-stream). No size limit, no server cache.
157+- Topbar avatar: initials in one of five tones (hash of id mod 5) with the photo image overlaid; broken image hidden by JS.
158+
159+### 2.12 Live updates
160+- GET `/api/live` : Server-Sent Events, unnamed events (`message`), JSON data. Requires session (401 empty otherwise). One stream per tab; window `live_seconds` = 300 then the server closes and the browser reconnects. Keepalive interval is topcoat's default (unverified). Graceful shutdown ends streams immediately.
161+- Frame: `{"topic":"<kind>","id":"<user id>","seq":N}` where kind is library, trash, shares, profile, revoked, admin. `seq` is a process-global counter starting at 1 on each boot (not per user).
162+- `{"topic":"resync"}` on broadcast lag (stream stays open).
163+- `{"topic":"revoked"}` when the signed-in user's own account is revoked, then the stream ends.
164+- Filter: own id always heard; Profile heard by everyone; Admin heard by admins only; Revoked only by the target; other users' Library/Trash/Shares dropped.
165+- Topics fired: Library(owner) on folder/file create, rename, move, delete, restore, purge, upload finish, record_download, service push/delete; Trash(owner) on trash, restore, purge, empty; Shares(owner) on share link and grant changes; Profile on preferences change and provisioning updates; Admin on quota, disable, provisioning; Revoked on disable/enable.
166+- Browser (JS `live_script`): one EventSource per tab; resync and profile refresh everywhere; `admin` only on Settings; `shares` only on Shared; `trash` only on Trash; `library` elsewhere; `revoked` hard-redirects to `/`; on error probes `/api/me` and leaves on 401; morph refresh debounced 200 ms; 60 s tick refresh where `[data-tick]` exists.
167+
168+### 2.13 Chrome, navigation, UI behaviour
169+- Topbar: monogram/wordmark "in", family app switcher, nav tabs Drive, Shared, Trash, user menu (name, email, admin badge, Profile link to `{issuer}/people/{sub}`, Settings, Sign out).
170+- Soft navigation: same-origin links and forms swap the body via fetch with field and focus restoration; multipart uploads via XHR with progress and cancel; `in:wire` event after swaps; build-skew triggers one reload per build.
171+- Live search on drive search box (200 ms debounce).
172+- Custom dropdown replaces native selects (keyboard arrows, Enter, type-to-filter, search when >7 options).
173+- Notices: persistent toast stack (never auto-dismisses; dismiss button), mirrored in `window.__inNotices`.
174+- Escape key manager (priorities: dropdown 95, viewer and delete confirm 90, user menu 40 (dead), datepicker 20 (absent), row context menu 10 (absent)).
175+- Theme/skin: `data-theme="dark"` and `data-ui` (instrument default or ledger) from user prefs. No light/dark toggle outside settings.
176+- Language: `<html lang>` from i18n.
177+- Overlays: viewer scrim, modal scrim (share, move, delete confirm via details), query keys scrubbed on close.
178+- Errors: 404 page inside the shell (catch-all `/{*path}` and NotFound). No styled 403 or 500 page.
179+- Health: GET `/healthz` returns `ok <IN_BUILD_SHA>` (sha from git at build time or `dev`), no DB check.
180+
181+---
182+
183+## 3. Machine service API (crates/in-web/src/service.rs)
184+
185+Auth for all four routes: header `Authorization: Bearer <token>` (case-sensitive prefix, trimmed, non-empty). The token is hashed (SHA-256, base64url, unsalted) and looked up in `service_key.token_hash`. The cookie is never read. There is no config key or env var for service keys: admins mint them in Settings > Service (`POST /api/settings/service_add`, `_rotate`, `_revoke`). Token: 32 random bytes, base64url (43 chars), shown once. Disabled account counts as no key (note: `service_account_by_token` does not check `disabled`; the caller in server.rs does; unverified in the route path).
186+
187+Missing or wrong key -> HTTP 401, body `{"err":"Unauthorized"}` on JSON routes, empty body on byte routes.
188+
189+JSON routes answer HTTP 200 for both success and refusal.
190+
191+| Method and path | Request | Success | Errors |
192+|---|---|---|---|
193+| POST `/api/service/files` | multipart/form-data: `external_id` (text, non-empty), `name` (text, non-empty), `file` (bytes). Unknown fields ignored. Body limit 512 MiB. | `200 {"ok":"<file id>"}` | 401; missing or empty field: `200 {"err":"BadRequest"}`; multipart read error: `{"err":"Unavailable"}`; quota: `{"err":"QuotaExceeded"}`; other store error: `{"err":"Unavailable"}` |
194+| GET `/api/service/file/{external_id}` | none | `200` raw bytes; `Content-Disposition: attachment; filename="<name with non [A-Za-z0-9._-] -> _>"`; `Content-Type` = stored mime (if parseable); `Cache-Control: private, max-age=31536000, immutable` | 401 empty body; unknown handle or any store error: 404 empty body |
195+| DELETE `/api/service/file/{external_id}` | none | `200 {"ok":true}` (unknown handle also `{"ok":true}`) | 401; store error: `{"err":"Unavailable"}` |
196+| GET `/api/service/status` | none | `200 {"ok":true,"quota_bytes":N,"used_bytes":N}` (u64) | 401; store error: `{"err":"Unavailable"}` |
197+
198+Service pushes: writes replace in place when `external_id` already exists for that owner (same row id, new bytes, new name and mime, size charged as the difference); a re-push does not create a second row. Pushed files are hard-deleted (no trash) and get no thumbnail. Service pushes count toward user quota like any file.
199+
200+Service accounts: one user row per service family, `oidc_sub = "service:<service>"`, admin false, quota from family limit or `default_quota_bytes`. One key per service (unique index on `service_key.service`); minting a second key for a service that already has one fails with a Backend error (rotate instead). Re-mint after revoke reuses the account.
201+
202+Family limits: `apply_family_limits` sets each service account quota from im's family list `limit_bytes` (house default when null). Abort on first store error (later accounts not updated) (see oddities).
203+
204+### 3.1 Authentication with im
205+
206+Config `[oidc]` (in config/in.toml): issuer, client_id, client_secret, optional redirect_uri (default `http://<listen host>/auth/callback`; unspecified bind maps to 127.0.0.1; port 80 omitted). Cookie name hard-coded `in_session`. Session cookie key = 32 bytes in `in.key` (created beside the DB, mode 0600), also used to seal share-token plaintext.
207+
208+Login flow (in-client crate, mounted with `in_client::mount`):
209+1. `/auth/login` -> `{issuer}/authorize` with PKCE S256 (verifier 32 bytes), state and nonce (16 bytes each), scope `openid profile email`. Client id, state and nonce are not percent-encoded in the URL (safe in practice).
210+2. `/auth/callback` -> POST `{issuer}/token` with form: `grant_type=authorization_code`, `code`, `redirect_uri`, `client_id`, `client_secret`, `code_verifier`. Response must carry `id_token` and im's `app_session` (opaque token).
211+3. id_token validated: compact JWT, header alg RS256, kid required; JWKS from `GET {issuer}/jwks.json` cached 3600 s and refetched on unknown kid; RSA PKCS#1 v1.5 SHA-256; `iss` = issuer; `aud` (string) = client_id; `exp` in the future; `nonce` = flight nonce. The id_token identity is then ignored: the app_session is introspected and must return active:true or login is refused.
212+4. Session cookie `in_session`: base64url(24-byte nonce || XChaCha20-Poly1305(JSON `{"app_session":"...","exp":<unix>}`)). Attributes: HttpOnly, SameSite=Lax, Path=/, Max-Age 30 days, Secure only if the issuer scheme is https.
213+5. Per request: `POST {issuer}/introspect` (form: token, client_id, client_secret). Missing or non-bool `active`, transport failure or missing sub/email/name/exp reads as signed out but keeps the cookie. Optional `photo_version` (default 0).
214+6. Logout: `/auth/logout` clears the cookie and redirects to `{issuer}/logout?back=<origin>/`.
215+
216+### 3.2 Family registration (heartbeat)
217+- Every 300 s (first pass at boot), if `base_url` is set: `POST {issuer}/family/register` with HTTP Basic (client_id:client_secret), JSON `{"key":"in","name":"Files","url":"<base_url, trailing slash trimmed>","limit_bytes":null}`. Any 2xx is success; otherwise logs `im refused with <status>: <error>: <reason>`. If base_url is empty it logs and skips registration.
218+- Then `GET {issuer}/family` (Basic auth) -> list of `{key, name, url, limit_bytes?}`; on non-2xx or bad body the last stored list is kept. Success: apply limits to service accounts, store the list JSON in setting `family` (read by topbar flyout and mintable dropdown).
219+
220+### 3.3 Directory usage
221+- Client: `im_client::directory::DirectoryClient::new(issuer, client_id, client_secret)` (Basic auth in the test fake). The im client crate is a git dependency (DizeyLab/im, pinned rev), not in this tree, so its endpoint paths below come from the test fake and are not verified against source.
222+- Full pass: `GET {issuer}/directory`; each member mirrored with `provision_user(sub, email, name, admin, photo_version, default_quota)` and `set_user_disabled` if disabled differs.
223+- Stream: `GET {issuer}/directory/live` (events `Profile(member)` or `Revoked{sub}`); Revoked announces the local account so its tabs morph to sign-in. Each event updates the health atomics.
224+- On stream end, a full pass runs again. Failures back off 1 s doubling to 30 s cap.
225+- Photos: `directory.photo(oidc_sub)` via avatar route.
226+- Local cache: sub, email, name, admin, disabled, photo_version, quota stored in the user table; not fetched per request.
227+
228+### 3.4 mint example
229+`crates/in-client/examples/mint.rs` (feature `test-seam`): `mint <in.key path> <app-session-token> [cookie-name=in_session]` prints a sealed `in_session` cookie value valid against that key, expiring in 1 day. Dev helper for smoke runs against a fake im. A missing token argument panics instead of printing usage.
230+
231+---
232+
233+## 4. Data model
234+
235+Database: Turso 0.8.0-pre.10 (SQLite-compatible), file `database` (config), WAL, `PRAGMA foreign_keys = ON`, busy timeout 5000 ms. Migrations `0001`-`0007` in `crates/in-core/migrations/`, concatenated as `schema::schema_sql()`. Fingerprint of sqlite_master compared at boot; mismatch triggers an automatic rebuild (see section 5.4).
236+
237+Timestamps: RFC 3339 text (ISO-like). Ordering relies on lexicographic text comparison; `stamp()` does not normalise to UTC (caller-supplied expires_at could break ordering).
238+
239+**user**
240+- id TEXT PK (ULID); oidc_sub TEXT NOT NULL, unique index (user_oidc_sub); email TEXT NOT NULL (lowercased); display_name TEXT NOT NULL
241+- admin INT NOT NULL DEFAULT 0; disabled INT NOT NULL DEFAULT 0
242+- quota_bytes INT NOT NULL; used_bytes INT NOT NULL DEFAULT 0 (recomputed from file sizes)
243+- created_at TEXT NOT NULL; last_seen_at TEXT
244+- 0002: ui TEXT NOT NULL DEFAULT 'ledger' (instrument or ledger skin)
245+- 0003: theme TEXT NOT NULL DEFAULT 'light' (light or dark); language TEXT NOT NULL DEFAULT 'en' (en or tr)
246+- 0006: photo_version INT NOT NULL DEFAULT 0 (avatar cache stamp)
247+
248+**folder**
249+- id TEXT PK; owner_id TEXT NOT NULL FK user; parent_id TEXT FK folder (NULL = root); name TEXT NOT NULL (label only); created_at NOT NULL; deleted_at TEXT (trash stamp, NULL = live)
250+- index folder_by_parent(owner_id, parent_id). No DB uniqueness for live sibling names (application-level postfixing only).
251+
252+**file**
253+- id TEXT PK; owner_id FK user; folder_id FK folder (NULL = root); name NOT NULL; mime NOT NULL (sniffed server-side); size_bytes INT NOT NULL
254+- thumb_state TEXT NOT NULL DEFAULT 'none' (none, pending, ready, failed); created_at NOT NULL; updated_at NOT NULL; deleted_at TEXT (trash)
255+- index file_by_folder(owner_id, folder_id)
256+- 0004: download_count INT NOT NULL DEFAULT 0
257+- 0007: external_id TEXT (service handle), partial unique index file_external_by_owner(owner_id, external_id) WHERE external_id IS NOT NULL
258+
259+**share_link**
260+- id TEXT PK; token_hash TEXT NOT NULL, unique (share_link_token); kind TEXT NOT NULL ('file' or 'folder', no CHECK); target_id NOT NULL; created_by FK user; can_download INT NOT NULL DEFAULT 1; created_at NOT NULL; expires_at TEXT; revoked_at TEXT
261+- 0005: password_hash TEXT (Argon2id PHC string, NULL = no password)
262+
263+**share_user** (per-person grants)
264+- kind TEXT; target_id TEXT; user_id TEXT FK user; can_download INT NOT NULL DEFAULT 1; created_at NOT NULL; PK(kind, target_id, user_id). No index on user_id (grantee lookups scan).
265+
266+**upload_session**
267+- id TEXT PK; owner_id FK user; folder_id FK folder (nullable); name NOT NULL; size_bytes NOT NULL; chunk_size NOT NULL; received_bytes INT NOT NULL DEFAULT 0; state TEXT NOT NULL DEFAULT 'active' ('active', 'done', 'aborted'; no CHECK); created_at NOT NULL; expires_at NOT NULL
268+
269+**setting** (0004)
270+- key TEXT PK; value TEXT NOT NULL. Instance key/value: base_url, family (JSON), share_token:<link id> (sealed plaintext token), others.
271+
272+**service_key** (0007)
273+- token_hash TEXT PK (SHA-256 of bearer token); name NOT NULL; service NOT NULL; user_id FK user; created_at NOT NULL; unique index service_key_service(service) (one key per service)
274+
275+Mismatches and notes:
276+- 0001_init.sql's CREATE TABLEs predate later ALTERs (they lack user.ui/theme/language/photo_version, file.download_count/external_id, share_link.password_hash) and omit setting and service_key. Its header claims all changes land in three places; this is not kept. The authoritative schema is the migrations applied in order.
277+- Reconcile backfill defaults disagree with migrations for old databases: map uses ui 'instrument' and theme 'dark' while 0002/0003 default ui 'ledger' and theme 'light'. Rebuilt and migrated DBs can differ in preferences.
278+- No CHECK constraints on enum-like columns; validation lives in parse functions.
279+- Trait-level types: `ThumbState` (none/pending/ready/failed), `UploadState` (active/done/aborted), `ShareKind` (file/folder).
280+
281+---
282+
283+## 5. Blob storage design
284+
285+### 5.1 Local tree (default)
286+Storage root = config `storage` path, default `<database parent>/storage`. Created at boot with mode 0700 (`files/`, `thumbs/`, `uploads/`). Boot also removes a legacy `storage/previews` directory unconditionally.
287+- `files/<file-id>`: bytes, keyed by row id only (name never in path).
288+- `thumbs/<file-id>`: WebP thumbnail.
289+- `uploads/<session-id>/<index>`: staged chunks (decimal index); always local, even with R2.
290+- Temp files: `put` writes `<key>.<ulid>.tmp` in the same directory, then renames (no fsync). Crash debris is reclaimed by the sweep.
291+- `adopt(key, staged, expected_len)`: length check then rename into place (same filesystem required).
292+- `get` returns None on NotFound; `span(key, start, len)` clamps to real length and streams 64 KiB frames; `delete` idempotent; `list_with_times(dir)` lists files with mtime.
293+
294+### 5.2 R2 (optional, config `[storage.r2]`)
295+- Presence of the table selects R2. Required: account_id, bucket, key_file. Endpoint `https://<account_id>.r2.cloudflarestorage.com`, region "auto", via `object_store` AmazonS3. Plain HTTP is test-only.
296+- Credentials: key_file is a plaintext two-line file (access key id, then secret). Read at boot by in-web main.rs; empty values refused. The app does not create it or enforce its mode.
297+- Keys identical to local: `files/<id>` and `thumbs/<id>`. Uploads are never in the bucket.
298+- `put`: single PUT of the whole buffer (thumbnails, small inserts).
299+- `adopt`: streams the staged file as multipart upload with 8 MiB parts; only the last part may be short; a zero-byte file is one empty PUT; on error it aborts the multipart upload and keeps staging; on success unlinks staging.
300+- `span`: HEAD for size, clamp, then ranged GET (honest length from response). NotFound between HEAD and GET -> None.
301+- `list_with_times("files"|"thumbs")`: prefix list, mtime as unix seconds (used by the sweep).
302+- Ordering contract (stated in both blob modules): bytes land at their key before the row commits; bytes are deleted only after the row is gone or can never name them. Exception: finish_upload adopts the file before committing; a failed commit leaves an orphan that the boot sweep reclaims once it is older than the watermark.
303+
304+### 5.3 Upload staging
305+Chunks written atomically (temp + rename) to `uploads/<session>/<n>`. `received_bytes` is recomputed from disk. Finish assembles into `files/<id>.<ulid>.tmp` and adopts it. Session dirs are removed after commit, on abort, and on expiry by the sweep. Declared sizes of active sessions count against quota for new uploads (`staged_claim`).
306+
307+### 5.4 Reconcile and rebuild (crates/in-core/src/store/reconcile.rs)
308+- CLI: `in reconcile [--dry-run] [--yes]` (in-web main.rs; exits after running).
309+- Boot: `repair_if_stale` runs before any long-lived handle opens the database. If the file exists, is non-empty and its sqlite_master fingerprint (normalised, comments and IF NOT EXISTS stripped) differs from the declared schema, reconcile runs with auto: true, then reopens and re-fingerprints; a mismatch refuses to start.
310+- Rebuild steps: write `<db>.rebuilt`, create declared schema, copy each table with explicit column maps (foreign keys off during copy), verify (FK check, integrity_check == ok, row counts per table; note `service_key` is omitted from the count list), checkpoint WAL, rename original to `<db>.backup-<UTC timestamp>` (with -wal/-shm), rename rebuilt into place. Originals are never deleted. Blobs untouched.
311+- Known hazards: swap window with no lock; manual reconcile against a running server copies without locking.
312+
313+### 5.5 Boot sweep (turso_store.rs `boot_sweeps`, background after the port opens)
314+1. `prune_expired_uploads(now)`: active sessions past expires_at -> aborted; staging dirs removed.
315+2. `sweep_orphan_files`: under one IMMEDIATE transaction (write lock held for the whole pass):
316+ - id sets: all file ids; file ids with thumb_state='ready'; active upload_session ids.
317+ - watermark = newest timestamp among file.created_at, file.updated_at, upload_session.created_at.
318+ - For `files/` and `thumbs/`: unknown objects with mtime <= watermark are deleted; newer ones are kept and logged; known ids missing on disk are logged only. Empty DB = nothing deleted.
319+ - For `uploads/`: any directory not matching an active session is removed under the same watermark rule.
320+3. `purge_expired(now - purge_after_days)`: trash older than the cutoff is purged (same background task, not in `open`).
321+
322+### 5.6 Content sniffing (crates/in-core/src/store/sniff.rs)
323+Pure function over bytes; result written to `file.mime` and drives thumbnail eligibility and serve disposition. The uploader's claim is never used.
324+- Magic numbers: PNG, JPEG, GIF, PDF, zip (PK\x03\x04), OLE2 (D0 CF 11 E0 ...), gzip, Matroska/EBML (1A 45 DF A3), WebP, WAV, FLAC, Ogg, MP3 (ID3, FF FB/F3/F2), ISO-BMFF ftyp brands: avif, heic/heix/hevc/heif/mif1/msf1, qt, generic mp4.
325+- Zip: substring scan picks xlsx (`xl/workbook.xml`), ods (`opendocument.spreadsheet`), pptx (`ppt/presentation.xml`), else application/zip.
326+- OLE2: "Workbook" in UTF-16 gives application/vnd.ms-excel, else application/x-ole-storage.
327+- Matroska: track walk; video/webm only when all tracks are VP8/VP9/AV1 or Vorbis/Opus; otherwise video/x-matroska; unparseable keeps video/webm.
328+- Fallback: valid UTF-8 (including empty) is text/plain; otherwise application/octet-stream.
329+- Sniff runs on insert, service insert and finish (first 1 MiB for finish).
330+
331+### 5.7 Thumbnails (crates/in-core/src/thumbs.rs)
332+- Eligible (`thumbnailed(mime)`): any image/* (including SVG and HEIC, which cannot decode; they fail), plus video/mp4, video/webm, video/quicktime, video/x-matroska.
333+- Max edge 512 px, output WebP. Images: `image` crate `thumbnail(512,512)` then WebP encode, in-process. Source cap 64 MiB (`THUMB_SOURCE_CAP`); larger files get failed without decoding. No pixel cap or explicit decode timeout in thumbs.rs.
334+- Video: external `ffmpeg` on PATH (checked once, cached). Seek 1 s (first frame for short clips), `scale=512:512:force_original_aspect_ratio=decrease`, `-c:v libwebp`, 10 s kill timeout per attempt, two attempts (worst case ~20 s). Output validated as RIFF....WEBP. Video bytes for the in-memory path are spilled to `std::env::temp_dir()` as `in-thumb-<pid>-<counter>.bin` with default permissions and removed afterwards (plaintext spill; leaks on crash).
335+- States: none (not attempted), pending, ready (blob at thumbs/<id>), failed. Failures never retried.
336+- Serving: `thumb_bytes` only if state ready.
337+
338+---
339+
340+## 6. Configuration
341+
342+Loading: `Config::load()` reads `./config/in.toml` relative to the process working directory (fixed path; no env overrides; no CLI flag; no upward search). If absent, the file is written from development defaults and the process stops with "missing oidc.issuer" (first-run behaviour). A successful boot rewrites the file to append missing optional top-level keys (`complete()`), which can modify the file under a deployment. Parse errors exit 2. Relative paths resolve against the directory containing `config/`. Unknown keys are collected and logged.
343+
344+| Key | Type | Code default | config/in.toml value | Rules |
345+|---|---|---|---|---|
346+| `database` | string | required | `"in.db"` | empty -> Missing |
347+| `storage` | string path or [storage] table | `<db parent>/storage` | `"/home/tahinli/Documents/Code/Rust/in/storage"` (absolute, points into a sibling tree `Rust/in`, not `Rust/old_in`) | empty -> default |
348+| `listen` | SocketAddr | `127.0.0.1:7655` | `127.0.0.1:7655` | hostnames rejected (Invalid) |
349+| `live_seconds` | u64 | 300 | 300 | 0 invalid |
350+| `purge_after_days` | u32 | 30 | 30 | no range check |
351+| `default_quota_bytes` | u64 | 10 GiB (10737418240) | 10737418240 | no range check; 0 accepted |
352+| `base_url` | string | none (use listen) | `""` | empty = None; must start http:// or https:// and not end with `/` |
353+| `[oidc] issuer` | string | required | `"http://127.0.0.1:7650"` | empty -> Missing; scheme not enforced |
354+| `[oidc] client_id` | string | required | `"01M21CE4Y692M537BJ7AAYE5RT"` | empty -> Missing |
355+| `[oidc] client_secret` | string | required | `"dev-drive-secret-2026"` (a live-looking secret committed to the repo) | empty -> Missing |
356+| `[oidc] redirect_uri` | string | `http://<listen host>[:port]/auth/callback` | commented out | not validated |
357+| `[storage.r2] account_id` | string | optional table | commented example | required if table present |
358+| `[storage.r2] bucket` | string | optional | commented example | required |
359+| `[storage.r2] key_file` | path | optional | commented example | required; 2-line plaintext key file |
360+
361+Other fixed values: cookie name `in_session`; flight cookie `in_session_pkce`; link cookie `in_link_<id>`; session key file `in.key` beside the database (32 raw bytes, 0600 intended); family registration key `in`, name `Files`; `FAMILY_SECONDS = 300`; `UPLOAD_TTL_HOURS = 24`; `CHUNK_SIZE = 8 MiB`; `THUMB_SOURCE_CAP = 64 MiB`; broadcast channel capacity 256; busy timeout 5000 ms. Body limits: `/api/upload` 32 MiB, `/api/service/files` 512 MiB, `/files` 2 GiB (main.rs).
362+
363+Secrets: `oidc.client_secret` is plaintext in config; R2 credentials are plaintext in key_file; the link sealing key is `in.key`. `Config` and `OidcConfig` derive Debug and contain the plaintext client_secret (leak risk through debug output).
364+
365+Cargo: workspace resolver 3, edition 2024, GPL-3.0-or-later. Profiles: release (fat LTO, 1 codegen unit), dist (thin LTO, 16 units; used by deploy). Pins: turso =0.8.0-pre.10, im-client git rev, rsa 0.10.0-rc.18.
366+
367+---
368+
369+## 7. Security mechanisms
370+
371+- Authentication: OIDC authorization code with PKCE S256, state and nonce checks, RS256 id_token signature check against JWKS, then app_session introspection with im on every request.
372+- Session cookie: XChaCha20-Poly1305 sealed with `in.key`; HttpOnly; SameSite=Lax; Path=/; 30-day Max-Age; Secure only when the issuer is https (not the app's own scheme).
373+- CSRF: no CSRF token anywhere in the codebase. The only mitigations are SameSite=Lax on cookies and a middleware that rewrites redirect Locations using the Referer (`back_to`, `carrying`, `same_origin`) for form posts. Origin header is not examined. Logout is a GET.
374+- Cross-owner: answered as 404 by design, never 403. Grantees: explicit `can_see`/`can_download` checks; trashed targets excluded.
375+- Share tokens: 256-bit random, stored only as unsalted SHA-256; plaintext sealed separately for redisplay.
376+- Share passwords: Argon2id v0x13, m=19 MiB, t=2, p=1, random salt, PHC strings; verified in spawn_blocking; malformed hash verifies false. Unlock proof cookie: SHA-256("token:phc"), unkeyed, no expiry, no rotation. No rate limiting or lockout. Password trimmed at creation, not at unlock.
377+- Content-type handling: mime from sniffing (never uploader claim); inline disposition only for an allow-list; SVG and HTML forced to attachment; `text/plain` inline allowed; PDF inline; viewer iframe sandbox="" for text.
378+- Headers: `Cache-Control` set per response class (private, immutable for content keyed by id, no-cache for mutable, no-cache on HTML via global middleware `cache_directives`). No CSP, no HSTS, no X-Content-Type-Options, no Referrer-Policy, no X-Robots-Tag anywhere in the code (framework defaults unverified).
379+- Content-Disposition: attachment filenames sanitised (ASCII fallback plus filename* for normal downloads; quote/backslash/control stripped for share downloads).
380+- Size limits: body limits per route as above; per-user quota; per-file thumbnail cap 64 MiB; chunk size fixed at 8 MiB and validated per chunk; no per-file upload cap beyond quota and body limits.
381+- Service keys: bearer tokens, SHA-256 hashed at rest, one key per service, shown once via in-memory shelf (10 min TTL, lost on restart).
382+- Secrets at rest: client_secret and R2 key file in plaintext; key files created then restricted (brief default-permission window in some paths).
383+- Process: no tracing crate; logging is println/eprintln.
384+
385+---
386+
387+## 8. UI pages
388+
389+- `/` : sign-in card (wordmark, Sign in button, auth notes) for signed-out; redirects to drive for signed-in users. Title bug (see oddities).
390+- `/drive` : folder list with topbar, filter bar (search, sort, kind, "+" menu), column header, rows (folders then files), row options, breadcrumb trail, upload control and drop overlay, empty states, rename-in-place, created-link panel, move picker modal, share modal, refusal banner. Grantee variant: read-only shared folder.
391+- `/search` : redirect only.
392+- `/view/{id}` : file viewer with preview (image, video, audio, PDF, text as allowed), details panel, download button, back link.
393+- `/trash` : trashed folders and files with filter, search, sort, per-row restore and purge menu, empty-trash button, countdown text.
394+- `/shared` : grants made to you (folders and files), Shared topbar tab, message page when signed out.
395+- `/settings` : sections Profile (identity, quota bar, preferences, connection card), Links (share links with copy-once URL, revoke, remint), Everyone (admin user table with quota and disable), Server (admin base URL), Service (admin keys: mint, rotate, revoke with one-time key display).
396+- `/s/{token}` : public share page: file card, folder listing with thumbnails, password gate, media player (`?media=1`), dead-link card, download only where allowed.
397+- 404 page within the shell (catch-all). No 403 or 500 page.
398+- Overlays and dialogs: viewer scrim, modal scrim (share, move, delete confirm), notice toast stack, custom dropdown panels.
399+- Themes: instrument (default, dense) and ledger (serif, warm paper) skins; light and dark tokens. Styling sources: style/main.scss (5538 lines), style/_instrument.scss, style/_ledger.scss; compiled at build by grass into the stylesheet with fingerprint checked at boot.
400+- Many stylesheet blocks are dead (board, task detail, mail rules, profile, logs, datepicker families). See oddities.
401+
402+---
403+
404+## 9. Localization
405+
406+- Two locales, inline in code: `Lang::En`, `Lang::Tr` (crates/in-web/src/i18n.rs). `Key` enum with 185 variants; both matches exhaustive with no fallback arm, so a missing translation is a compile error. No runtime fallback path, no interpolation, no plural rules.
407+- Selection: signed-in user's stored `language` (anything other than "tr" is English); signed-out or user lookup error: first tag of `Accept-Language` (q-values ignored; primary subtag only); else English. No cookie, no query parameter.
408+- Hard-coded labels not keyed: "English" and "Türkçe" in the language select; "MiB" and "GiB" in the quota unit select.
409+- `<html lang>` from the code.
410+
411+---
412+
413+## 10. Health and operations
414+
415+- GET `/healthz`: 200, body `ok <IN_BUILD_SHA>`; checks only that the HTTP server answers. Unauthenticated; publishes build commit.
416+- Family health probes: `{url}/healthz` with 2 s timeout, accepts 2xx and body starting with "ok", body truncated to 64 chars, cached 30 s (for the topbar family flyout dots).
417+- Directory health: atomics for stream connected, last event age, last full-pass age (shown on Settings Connection card).
418+- CLI: `in reconcile [--dry-run] [--yes]`.
419+- Startup order (main.rs): CLI check; config load and completion; asset bundle load and stylesheet fingerprint check (exit 2 on mismatch); storage tree creation; optional R2 client; store open (migrations, repair_if_stale; panics on failure); boot sweeps and trash purge in background; in.key load or create; OIDC client mount; directory sync task; family sync task; listener bind (panics on failure); graceful shutdown on SIGINT/SIGTERM (ends SSE streams).
420+- Deploy: GitHub Actions on push to main (see section 11).
421+
422+---
423+
424+## 11. Build, test and deploy
425+
426+Build:
427+- `crates/in-web/build.rs` compiles style/main.scss with grass into `crates/in-web/assets/main.css`; emits `IN_STYLE_FINGERPRINT` (sha256 of css) and `IN_BUILD_SHA` (env, default "dev"). rerun-if-changed covers only the three scss files.
428+- Asset bundling in CI: `topcoat asset bundle --package in-web --profile dist --out stage/assets` (topcoat-cli 0.9.0).
429+- No i18n build step (i18n is hand-written Rust).
430+
431+Deploy (`.github/workflows/main.yml`):
432+- Trigger: push to main only. Single job `deploy`, runner ubuntu-24.04, concurrency group `deploy` (no cancel). Target `x86_64-unknown-linux-gnu`, profile `dist`.
433+- Steps: checkout; rustup stable (unpinned); rust-cache; cache topcoat-cli; write `.cargo/config.toml` target line (appended, not committed); asset bundle; copy and strip binary; install SSH key from secrets; ssh-keyscan (no host pinning); upload tarball to `~/in/current.new` (subdir validated); swap `current` and `current.previous`; clean `config/*.bak*` and `*.pre-*`; chmod config 0600; install `deploy/in.service` to `~/.config/systemd/user/`; daemon-reload, enable, restart; poll `/healthz` 30 times requiring `ok <sha>`; rollback on failure; verify served stylesheet sha256 matches the staged asset; `rm -rf ~/.ssh` (no if: always()).
434+- Secrets used by name: SSH_PRIVATE_KEY, SSH_HOST, SSH_USER. Nothing else.
435+- No cargo test, clippy or fmt step in CI.
436+
437+Systemd unit `deploy/in.service`: systemd user unit, WorkingDirectory=%h/in, ExecStart=%h/in/current/in-web, Restart=on-failure, After=network-online.target, WantedBy=default.target. No Environment, no hardening, no RestartSec. Requires `loginctl enable-linger` once.
438+
439+Tests (not run in CI):
440+- crates/in-web/tests/http.rs (about 6555 lines, roughly 100 #[test] attributes): fake im, real router and store. Covers drive CRUD, uploads (small, chunked, resume, abort, quota, postfix), downloads and ranges, thumbnails, previews, share links (create, public view, password, expiry, revoke, remint, legacy), per-person sharing, search, trash, settings guards, avatars, service API, live channel, me probe. Needs a prebuilt asset bundle at target/debug/assets.
441+- crates/in-core/tests/store.rs (about 2390 lines, 71 tests): schema and users, change feed, names and postfixing, files and thumbnails, trash and purge races, sharing, uploads, boot sweep, R2 via local s3s server (access key test-key), service accounts.
442+- Video tests skip when ffmpeg is absent.
443+
444+Workspace: members in-core, in-client, in-web. `.gitignore` excludes target, dist, style/main.css, *.db, storage, .env, in.key, CLAUDE.md, assets, backups.
445+
446+---
447+
448+## 12. Oddities, bugs, half-finished work
449+
450+Security:
451+1. `config/in.toml` contains a literal client_secret ("dev-drive-secret-2026") while its comment says the committed copy stays empty. Treat as exposed.
452+2. `Config` and `OidcConfig` derive Debug with the plaintext secret.
453+3. No CSRF tokens; logout is a GET (logout CSRF); cross-site top-level navigation can sign the user out.
454+4. Callback error reflection: `format!("/?auth_error={error}")` after percent-decoding; decoded `&` or `#` can inject query parameters into the local redirect.
455+5. `settings` disable: a POST with no `disabled` field disables the account; an empty string enables it. Admins can disable admins; only self-disable refused.
456+6. Quota form: service-account guard uses `unwrap_or(false)`, so a store error lets the quota write proceed against a service account. No check that user_id exists.
457+7. Share link password: unkeyed SHA-256 unlock proof with no expiry; no lockout; trim mismatch (create trims, unlock does not). Remint does not check revoked or expired on the source link and can turn an expired link into a permanent one; it also creates the new link before revoking the old, so a failed revoke leaves two live links with the new token never shown.
458+8. Copy-once share URL travels in the `?created=` query string (browser history, logs, Referer), unlike the shown= ticket design for service keys.
459+9. Share links: dead answers are all 200, so clients cannot tell dead from live by status. Thumbnails cached for a year even after revoke.
460+10. Token in the URL path leaks via logs and Referer; no Referrer-Policy.
461+11. Live stream and Revoked: set_user_disabled announces Revoked on enable as well as disable, so re-enabling kills open tabs.
462+12. Cookie Secure flag follows issuer scheme, not the app's public origin.
463+13. Family limits loop aborts on first store error; accounts left unchanged; a service dropping out of im's family silently falls back to default quota.
464+14. `mint` example prints a usable session cookie to stdout.
465+15. Unverified: whether in-client module doc (promising refresh tokens and silent rotation) matches code. Code has no refresh token; `current_user` introspects every request.
466+16. Logout and callback: id_token identity ignored (only nonce checked).
467+17. JWKS refetch: `?` on RsaPublicKey::new aborts the whole refresh on one bad key.
468+18. `/api/service/file` download: store errors collapse to 404.
469+19. Service pushes buffer the whole file in memory (512 MiB body limit).
470+20. Service delete of an unknown handle returns `{"ok":true}`.
471+21. `service_file_bytes` is unused in routes.
472+22. `insert_service_file` replace path writes new bytes before commit; if the commit fails the row keeps the old size and name while bytes are replaced (data loss of the previous version).
473+23. `service_file` and insert ignore `deleted_at` (service pushes can silently refill trashed rows).
474+24. `service_account_by_token` does not check `disabled` (caller responsibility).
475+25. `apply_service_limit` can set quota below used_bytes.
476+26. Service key re-mint for an existing service fails with a generic Backend error.
477+
478+Data integrity and storage:
479+27. finish_upload and insert_file: blobs written inside the IMMEDIATE write transaction (I/O under the write lock); if a later step fails, the blobs are orphaned until the boot sweep.
480+28. record_chunk and abort_upload race: a chunk write can recreate the staging dir after abort; prune_expired_uploads lacks an `AND state='active'` guard.
481+29. create_upload_session quota check and insert are not in one transaction; directory create after commit can leave an active session with no dir.
482+30. Share create and grant add are vet-then-write without a transaction; a concurrent trash can leave a dangling grant.
483+31. delete_file does its UPDATE and refresh_usage as separate autocommit statements (used_bytes can drift on crash).
484+32. ancestor_trashed, depth_in and move_folder cycle walk have no cycle guard beyond the self-parent check.
485+33. select_expired and select_trash load all candidates with no LIMIT.
486+34. delete_folder_rows nulls folder_id on all upload sessions, including finished ones.
487+35. Name uniqueness is application-level only (no DB unique index); concurrent creates can collide. Name matching is case-sensitive.
488+36. Reconcile: backfill defaults for ui and theme disagree with migrations; verify omits service_key; swap window has no lock; manual run against a live server copies without locking and compares counts only.
489+37. Sweep holds the DB write lock across R2 listing and deletes (slow bucket stalls all writers).
490+38. Local blob operations use blocking std::fs inside async functions.
491+39. R2 adopt comment claims one part buffer resident; the code keeps about two.
492+40. LocalBlobs tmp naming uses with_extension (wrong for keys containing dots; harmless today).
493+41. Thumbnails: image/* includes SVG and HEIC which cannot decode (wasted attempts); no pixel cap in thumbs.rs; video temp spill to system temp dir as plaintext.
494+42. Sniff substring markers can misclassify plain zips containing those bytes; unrecognised formats (AVI, BMP, TIFF, 7z, rar, tar) fall to octet-stream or text.
495+43. Sniff doc links to a non-existent GENERIC_MIME_TYPES; fingerprint filter treats `_` in LIKE as wildcard.
496+44. `pending` thumbnail state is never reset on boot after a crash (unverified).
497+45. Keys and config files are created with default permissions before being restricted (brief exposure).
498+46. Config boot rewrites `config/in.toml`; `complete()` can be suppressed by a same-named key in another table.
499+47. `purge_file` on a live file returns Ok(false); `purge_folder` on a live folder returns NotFound.
500+48. Trash purge deletes share rows for the purged file/folder (defensive, correct) but purge does not remove sealed token settings for those links (unverified).
501+49. Files restore and move/rename skip quota (correct under the model) but folder rename and move call refresh_usage needlessly.
502+50. Module docs in store and turso_store refer to a `crates/in-core/migrations` apply step and "0001_init.sql as the declared schema" (stale).
503+51. Dead store method: default `Blobs::list` is unused outside tests.
504+52. share_user has no index on user_id.
505+
506+Web and UI:
507+53. Title bug: `title_key_of("/")` always returns SignIn even when `/` serves the drive to a signed-in browser.
508+54. `escape_script` (user menu Escape) is defined but never emitted; the user-menu Escape resolver is dead.
509+55. `topcoat::dev::script()` emitted unconditionally in `<head>` (verify whether dev-only).
510+56. Google Fonts loaded from a third-party CDN without SRI.
511+57. `--font-serif` referenced in the ledger skin but never defined; titles fall back to Georgia.
512+58. Large stylesheet dead-code: board, task detail, mail rules, profile, logs, datepicker, tag and auth families have no Rust counterpart (roughly 287 class names with no literal match; some may be format-built). Light and dark token blocks duplicated.
513+59. Drive search mode: "+" menu and upload still target the current folder, which is not the visible context.
514+60. Drive kind filter can show "empty folder" when content exists but is hidden by the filter.
515+61. Drive row Shared chip and folder-picker subtree filter by display path (names containing " / " can confuse it).
516+62. Redirect `/search` forwards raw q without decoding; `here` link drops q.
517+63. Folder/file breadcrumbs and picker swallow store errors silently.
518+64. Grantee drive page runs a wasted `search` before the grantee branch.
519+65. Share modal writes (provision_user per directory member) during a GET render.
520+66. Share modal and settings: one live link per target shown, though the API allows several.
521+67. `/` route: `search` link does not exist in the topbar (intentional per tests).
522+68. Upload progress and abort via XHR; refusal parsing relies on responseURL.
523+69. Stylistic: many mis-indented view! blocks and rustfmt drift in files.rs parse_range; garbled comments (e.g. "in never kept bytes" in reconcile header); doc comments glued together in layout.rs.
524+70. Layout catch-all `/{*path}` raises NotFound inside the shell (intended).
525+71. Unused or stale: `/whoami` route probably test-only; `public/` directory contains only .gitkeep; `config/im.toml` is an im-side config (database im.db, listen 7650) not read by in-web and with none of in's keys.
526+72. Duplicate rules and dead CSS as described; `!important` once.
527+
528+Test and CI gaps:
529+73. CI does not run tests, clippy or fmt; deploy only builds and health checks.
530+74. Video tests silently skip without ffmpeg.
531+75. Rollback on first deploy: `rm -rf current` then `mv current.previous current` fails under set -e when no previous release exists.
532+76. `find config -name '*.bak*' -delete` runs on every deploy (deletes operator backups).
533+77. `ssh-keyscan` without pinning; `~/.ssh` cleanup not in `if: always()`.
534+78. Deploy writes `.cargo/config.toml` with `>>` (accumulates on non-fresh checkout).
535+79. Systemd unit has no hardening and no RestartSec.
536+80. Dependencies pinned to pre-release versions (turso, rsa).
537+
538+---
539+
540+## 13. Rebuild checklist (what a faithful clone must cover)
541+
542+- All routes in sections 2 and 3, with the exact status, redirect and JSON shapes above.
543+- Store semantics: owner scoping, trash cascade with shared timestamp, postfix naming, quota arithmetic, staged-claim accounting, deepest-first purge, sealed token storage, Argon2 PHC, SHA-256 token hashes, service key hashing.
544+- Blob layout `files/<id>`, `thumbs/<id>`, `uploads/<session>/<n>`, same keys on R2, plus the boot sweep and watermark rule.
545+- OIDC login with PKCE and id_token validation, per-request introspection, family heartbeat, directory mirror and stream, avatar proxy.
546+- SSE channel with the topic filter rules and the resync and revoked control frames.
547+- Config keys and defaults as in section 6; `/healthz` body format.
548+- The sniffing allow-lists for inline disposition and the sniffed mime model.
549+- Decide explicitly whether to keep the oddities listed in section 12 (most are bugs, not features).