forge
Explore
Log in

Don't you dare go Hollow

Drive storage with im OIDC login, sharing, quota, trash, thumbnails

Browse files at this commit

41180433aa3013b63b32d4ebeab414e90ad6715bAhmet Kaan GümüşParent: dba55fc
  • feat
    • drive storage with im OIDC login, sharing, quota, trash, thumbnails
Show full message
feat: drive storage with im OIDC login, sharing, quota, trash, thumbnails

Initial build of in, sibling of iz and im on the same stack (topcoat
0.6.2 server-rendered UI, turso metadata store, file bytes on the
filesystem).

- in-core: folder tree, files, share links + per-user grants
  (transitive, most-permissive-wins), per-user quota, trash with
  purge horizon, chunked upload sessions, image + ffmpeg-gated video
  thumbnails, search, reconcile/migrations discipline from iz
- in-client: vendored im OIDC relying party (authorization code +
  PKCE, introspection per request), strict next validation, cookie
  kept on transient introspect failure
- in-web: drive browser, small + chunked upload with progress,
  Range-capable downloads, public /s/{token} share pages with
  previews, trash/search/settings surfaces, SSE live updates,
  En/Tr i18n, iz house style
- deploy workflow adapted from iz (dist profile, asset bundle guard,
  /healthz build-sha check)
.github/workflows/main.ymladded+228 -0
@@ -0,0 +1,228 @@
1+on:
2+ push:
3+ branches:
4+ - main
5+
6+# The deploy swaps a release directory and restarts one service; two of them
7+# racing would leave the binary and the running process from different builds.
8+concurrency:
9+ group: deploy
10+ cancel-in-progress: false
11+
12+env:
13+ # A gnu binary links against the runner's glibc, so the runner is pinned
14+ # (see runs-on below) to the same 24.04 the server runs; the day either
15+ # side moves, the pin is what forces a conscious decision rather than a
16+ # broken deploy. In exchange: no cross-toolchain, and the linker is
17+ # rustc's default bundled lld.
18+ TARGET: x86_64-unknown-linux-gnu
19+ # The systemd user unit that owns the process. See in.service.
20+ SERVICE: in
21+ # `release` keeps fat LTO in one codegen unit for when the last few percent
22+ # are worth five minutes. `dist` is that profile with thin LTO and the cores
23+ # actually used: measured on a 12-core machine, the relink every deploy pays
24+ # for goes from 2m27s to 25s, for a binary this server will never be
25+ # CPU-bound on. See the profile in Cargo.toml.
26+ PROFILE: dist
27+ TOPCOAT: 0.6.2
28+ # The deploy lives in this subdirectory of the SSH user's home. The home
29+ # itself is resolved on the server ($HOME), so switching the deploy user
30+ # moves the path with it — a baked-in absolute path once kept pointing at
31+ # the previous user's home and failed the deploy on permissions.
32+ DEPLOY_SUBDIR: in
33+ # Baked into the binary by build.rs and asserted against after the
34+ # deploy restart: a /healthz answered by a stale process from an old
35+ # deploy now fails and rolls back instead of reporting green (observed
36+ # on the initial in deploy).
37+ IN_BUILD_SHA: ${{ github.sha }}
38+
39+jobs:
40+ deploy:
41+ name: Deploy
42+ # Pinned, not `latest`: ubuntu-latest floating to the next LTS would
43+ # one day ship a glibc newer than the server's, and the gnu binary
44+ # would stop running there. See the TARGET comment above.
45+ runs-on: ubuntu-24.04
46+ steps:
47+ - name: Checkout repository
48+ uses: actions/checkout@v4
49+
50+ - name: Set up Rust
51+ run: rustup toolchain install stable --profile minimal
52+
53+ - name: Cache cargo
54+ uses: Swatinem/rust-cache@v2
55+ with:
56+ cache-all-crates: true
57+ # Bump when the target, the profile or any rustflags change: the
58+ # key does not otherwise see those, and a run that restores the
59+ # old key reports it up-to-date at save time — discarding the
60+ # recompiled dependencies and silently recompiling them on every
61+ # later run (observed when the musl→gnu move landed on this key).
62+ prefix-key: v1-rust-gnu
63+
64+ # Compiling the CLI from source costs minutes and it changes only when
65+ # the pinned version does, so it is cached on that version alone.
66+ - name: Cache the topcoat CLI
67+ id: topcoat-cache
68+ uses: actions/cache@v4
69+ with:
70+ path: ~/.cargo/bin/topcoat
71+ key: topcoat-cli-${{ env.TOPCOAT }}-${{ runner.os }}
72+
73+ - name: Install the topcoat CLI
74+ # Installed before the cargo config below exists, so the CLI itself
75+ # is built for the host and not for the deploy target.
76+ if: steps.topcoat-cache.outputs.cache-hit != 'true'
77+ run: cargo install topcoat-cli@${{ env.TOPCOAT }} --locked
78+
79+ - name: Point cargo at the deploy target
80+ run: |
81+ set -euo pipefail
82+ # `topcoat asset bundle` runs its own `cargo build` and strips every
83+ # CARGO_* variable from it, so the target cannot be passed by
84+ # environment; it goes into the cargo config that inner build
85+ # reads. This file is written in CI only; it is not committed.
86+ #
87+ # With the gnu target the linker is rustc's default — the bundled
88+ # rust-lld — and it matters: a warm relink of this binary measured
89+ # 142s under the BFD that an explicit `linker = "gcc"` would pick,
90+ # against 23s under lld. That link is the largest single chunk of
91+ # the deploy build, so the default is deliberately left alone.
92+ mkdir -p .cargo
93+ printf '[build]\ntarget = "%s"\n' "$TARGET" >> .cargo/config.toml
94+
95+ - name: Build the binary and bundle its assets
96+ run: |
97+ set -euo pipefail
98+ # One compile: this builds in-web and writes out the asset bundle
99+ # embedded in the binary it produced.
100+ topcoat asset bundle --package in-web --profile "$PROFILE" --out stage/assets
101+ cp "target/$TARGET/$PROFILE/in-web" stage/in-web
102+ strip stage/in-web
103+ ls -l stage stage/assets
104+
105+ - name: Install SSH keys
106+ run: |
107+ mkdir -p ~/.ssh
108+ echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa && chmod 600 ~/.ssh/id_rsa
109+ ssh-keyscan -H ${{ secrets.SSH_HOST }} > ~/.ssh/known_hosts
110+
111+ - name: Upload the release
112+ run: |
113+ set -euo pipefail
114+ ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}"
115+
116+ # The server's login shell is not bash, and ssh would hand this
117+ # script to it; `bash -s` takes it on stdin instead, so the login
118+ # shell only ever parses one plain command.
119+ #
120+ # The deploy path is $DEPLOY_SUBDIR under the SSH user's home,
121+ # resolved on the server as $HOME: there is no path secret to go
122+ # stale, and switching the deploy user moves the deploy with it.
123+ ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" <<'REMOTE'
124+ set -euo pipefail
125+ case "$1" in
126+ ''|/*|*..*)
127+ echo "Refusing a broad deploy subdirectory: '$1'" >&2
128+ exit 1
129+ ;;
130+ esac
131+ deploy_path=$HOME/$1
132+ # The deploy path is the service's working directory: config/,
133+ # in.db and in.key live there and are never touched from here.
134+ # Only 'current' is replaced.
135+ mkdir -p -- "$deploy_path"
136+ rm -rf -- "$deploy_path/current.new"
137+ mkdir -p -- "$deploy_path/current.new"
138+ REMOTE
139+ # stdin carries the tarball, so the script cannot; the extraction
140+ # still goes through bash -c because the login shell is fish and
141+ # would not expand $HOME.
142+ tar -C stage -czf - . | ssh "$ssh_target" "bash -c 'exec tar -xzf - -C \"\$HOME/\$1/current.new\"' -- '$DEPLOY_SUBDIR'"
143+
144+ - name: Swap and restart
145+ run: |
146+ set -euo pipefail
147+ ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}"
148+
149+ # bash -s for the same reason as above: the login shell is not
150+ # bash and must never see this script.
151+ ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$GITHUB_SHA'" <<'REMOTE'
152+ set -euo pipefail
153+ deploy_path=$HOME/$1
154+ service=$2
155+ expected="ok $3"
156+ export XDG_RUNTIME_DIR=/run/user/$(id -u)
157+ # Read before anything moves: a config the health check cannot
158+ # read is a failure to stop on, not one to roll back from.
159+ listen=$(sed -n 's/^listen[[:space:]]*=[[:space:]]*"\(.*\)"/\1/p' "$deploy_path/config/in.toml")
160+ if [ -z "$listen" ]; then
161+ echo "no listen address in $deploy_path/config/in.toml" >&2
162+ exit 1
163+ fi
164+ chmod +x -- "$deploy_path/current.new/in-web"
165+ rm -rf -- "$deploy_path/current.previous"
166+ if [ -e "$deploy_path/current" ]; then
167+ mv -- "$deploy_path/current" "$deploy_path/current.previous"
168+ fi
169+ mv -- "$deploy_path/current.new" "$deploy_path/current"
170+ systemctl --user restart "$service"
171+ # The unit is Type=simple, so a restart returns before the new
172+ # process has bound its port — and before an old one has let go
173+ # of it. Wait for the health route rather than a clock, and
174+ # check the answer names this commit: a stale process can still
175+ # answer, and did once (the initial in deploy deployed green over
176+ # a stale server).
177+ rollback() {
178+ rm -rf -- "$deploy_path/current"
179+ mv -- "$deploy_path/current.previous" "$deploy_path/current"
180+ systemctl --user restart "$service"
181+ }
182+ for _ in $(seq 1 30); do
183+ served=$(curl -fsS "http://$listen/healthz" 2>/dev/null) || { sleep 1; continue; }
184+ if [ "$served" != "$expected" ]; then
185+ echo "/healthz answered '$served', wanted '$expected'; rolling back" >&2
186+ rollback
187+ exit 1
188+ fi
189+ echo 'in is up'
190+ rm -rf -- "$deploy_path/current.previous"
191+ exit 0
192+ done
193+ echo 'in did not answer /healthz; rolling back' >&2
194+ rollback
195+ exit 1
196+ REMOTE
197+
198+ # The boot-time fingerprint guard refuses a foreign bundle, so a
199+ # mixed generation cannot get this far unnoticed — this is the
200+ # independent after-the-fact check: the page's stylesheet URL must
201+ # answer with bytes byte-identical to the bundle this deploy staged.
202+ - name: Verify the served stylesheet is this deploy's
203+ run: |
204+ set -euo pipefail
205+ ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}"
206+ # One remote script: mixing runner-side and server-side variables in
207+ # nested ssh quoting once shipped a check that failed on a healthy
208+ # deploy. Everything server-side happens inside the heredoc; only the
209+ # stylesheet bytes come back on stdout.
210+ ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" > served-stylesheet.css <<'REMOTE'
211+ set -euo pipefail
212+ deploy_path=$HOME/$1
213+ listen=$(sed -n 's/^listen[[:space:]]*=[[:space:]]*"\(.*\)"/\1/p' "$deploy_path/config/in.toml")
214+ url=$(curl -fsS "http://${listen}/" | grep -oE '/_topcoat/assets/main-[a-f0-9]+\.css' | head -n1)
215+ if [ -z "$url" ]; then
216+ echo 'the served page references no stylesheet' >&2
217+ exit 1
218+ fi
219+ echo "served stylesheet url: $url" >&2
220+ curl -fsS "http://${listen}${url}"
221+ REMOTE
222+ staged=$(sha256sum stage/assets/main-*.css | cut -d' ' -f1)
223+ served=$(sha256sum served-stylesheet.css | cut -d' ' -f1)
224+ echo "staged sha256:$staged, served sha256:$served"
225+ test "$staged" = "$served"
226+
227+ - name: Cleaning
228+ run: rm -rf ~/.ssh
.gitignoreadded+12 -0
@@ -0,0 +1,12 @@
1+/target
2+/dist
3+/style/main.css
4+*.db
5+*.db-*
6+/storage
7+.env
8+in.key
9+/config/in.toml
10+CLAUDE.md
11+/crates/in-web/assets
12+*.db.backup-*
Cargo.lockadded+5387 -0

Diff too large; view file

@@ -0,0 +1,5387 @@
1+# This file is automatically @generated by Cargo.
2+# It is not intended for manual editing.
3+version = 4
4+
5+[[package]]
6+name = "adler2"
7+version = "2.0.1"
8+source = "registry+https://github.com/rust-lang/crates.io-index"
9+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
10+
11+[[package]]
12+name = "aead"
13+version = "0.5.2"
14+source = "registry+https://github.com/rust-lang/crates.io-index"
15+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"
16+dependencies = [
17+ "crypto-common 0.1.7",
18+ "generic-array",
19+]
20+
21+[[package]]
22+name = "aegis"
23+version = "0.9.15"
24+source = "registry+https://github.com/rust-lang/crates.io-index"
25+checksum = "58541132f980da31e9aa99f7bdee69bc84bf1e168b9b91ef2dbe8abb7b4ce5dd"
26+dependencies = [
27+ "cc",
28+ "softaes",
29+]
30+
31+[[package]]
32+name = "aes"
33+version = "0.8.4"
34+source = "registry+https://github.com/rust-lang/crates.io-index"
35+checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
36+dependencies = [
37+ "cfg-if",
38+ "cipher",
39+ "cpufeatures 0.2.17",
40+]
41+
42+[[package]]
43+name = "aes-gcm"
44+version = "0.10.3"
45+source = "registry+https://github.com/rust-lang/crates.io-index"
46+checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
47+dependencies = [
48+ "aead",
49+ "aes",
50+ "cipher",
51+ "ctr",
52+ "ghash",
53+ "subtle",
54+]
55+
56+[[package]]
57+name = "ahash"
58+version = "0.8.12"
59+source = "registry+https://github.com/rust-lang/crates.io-index"
60+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
61+dependencies = [
62+ "cfg-if",
63+ "once_cell",
64+ "version_check",
65+ "zerocopy",
66+]
67+
68+[[package]]
69+name = "aho-corasick"
70+version = "1.1.5"
71+source = "registry+https://github.com/rust-lang/crates.io-index"
72+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
73+dependencies = [
74+ "memchr",
75+]
76+
77+[[package]]
78+name = "alloc-no-stdlib"
79+version = "2.0.4"
80+source = "registry+https://github.com/rust-lang/crates.io-index"
81+checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
82+
83+[[package]]
84+name = "alloc-stdlib"
85+version = "0.2.4"
86+source = "registry+https://github.com/rust-lang/crates.io-index"
87+checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
88+dependencies = [
89+ "alloc-no-stdlib",
90+]
91+
92+[[package]]
93+name = "allocator-api2"
94+version = "0.2.21"
95+source = "registry+https://github.com/rust-lang/crates.io-index"
96+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
97+
98+[[package]]
99+name = "allocator-api2"
100+version = "0.4.0"
101+source = "registry+https://github.com/rust-lang/crates.io-index"
102+checksum = "c880a97d28a3681c0267bd29cff89621202715b065127cd445fa0f0fe0aa2880"
103+
104+[[package]]
105+name = "android_system_properties"
106+version = "0.1.6"
107+source = "registry+https://github.com/rust-lang/crates.io-index"
108+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
109+dependencies = [
110+ "libc",
111+]
112+
113+[[package]]
114+name = "anstream"
115+version = "1.0.0"
116+source = "registry+https://github.com/rust-lang/crates.io-index"
117+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
118+dependencies = [
119+ "anstyle",
120+ "anstyle-parse",
121+ "anstyle-query",
122+ "anstyle-wincon",
123+ "colorchoice",
124+ "is_terminal_polyfill",
125+ "utf8parse",
126+]
127+
128+[[package]]
129+name = "anstyle"
130+version = "1.0.14"
131+source = "registry+https://github.com/rust-lang/crates.io-index"
132+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
133+
134+[[package]]
135+name = "anstyle-parse"
136+version = "1.0.0"
137+source = "registry+https://github.com/rust-lang/crates.io-index"
138+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
139+dependencies = [
140+ "utf8parse",
141+]
142+
143+[[package]]
144+name = "anstyle-query"
145+version = "1.1.5"
146+source = "registry+https://github.com/rust-lang/crates.io-index"
147+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
148+dependencies = [
149+ "windows-sys 0.61.2",
150+]
151+
152+[[package]]
153+name = "anstyle-wincon"
154+version = "3.0.11"
155+source = "registry+https://github.com/rust-lang/crates.io-index"
156+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
157+dependencies = [
158+ "anstyle",
159+ "once_cell_polyfill",
160+ "windows-sys 0.61.2",
161+]
162+
163+[[package]]
164+name = "antithesis_sdk"
165+version = "0.3.0"
166+source = "registry+https://github.com/rust-lang/crates.io-index"
167+checksum = "a8ed6751597568a284314fd9e2db420665898600109dedc7d8d9b588f00ae9c4"
168+dependencies = [
169+ "libc",
170+ "libloading",
171+ "linkme",
172+ "once_cell",
173+ "rand 0.8.8",
174+ "rustc_version_runtime",
175+ "serde",
176+ "serde_json",
177+]
178+
179+[[package]]
180+name = "anyhow"
181+version = "1.0.104"
182+source = "registry+https://github.com/rust-lang/crates.io-index"
183+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
184+
185+[[package]]
186+name = "anymap3"
187+version = "1.1.0"
188+source = "registry+https://github.com/rust-lang/crates.io-index"
189+checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9"
190+
191+[[package]]
192+name = "arc-swap"
193+version = "1.9.2"
194+source = "registry+https://github.com/rust-lang/crates.io-index"
195+checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b"
196+dependencies = [
197+ "rustversion",
198+]
199+
200+[[package]]
201+name = "aristo"
202+version = "0.4.1"
203+source = "registry+https://github.com/rust-lang/crates.io-index"
204+checksum = "fcdeefa800110050103e2459a2f8dbdbd560ad046e30f1f87e24ce19c2cb8bde"
205+dependencies = [
206+ "aristo-macros",
207+]
208+
209+[[package]]
210+name = "aristo-macros"
211+version = "0.4.1"
212+source = "registry+https://github.com/rust-lang/crates.io-index"
213+checksum = "d64a66d21a80182b35b1741997a6d2456911f54b7eb1918aa4e2382fc205268d"
214+dependencies = [
215+ "proc-macro2",
216+ "quote",
217+ "syn 2.0.119",
218+]
219+
220+[[package]]
221+name = "assoc"
222+version = "0.1.3"
223+source = "registry+https://github.com/rust-lang/crates.io-index"
224+checksum = "bfdc70193dadb9d7287fa4b633f15f90c876915b31f6af17da307fc59c9859a8"
225+
226+[[package]]
227+name = "async-compression"
228+version = "0.4.44"
229+source = "registry+https://github.com/rust-lang/crates.io-index"
230+checksum = "515a1f282e33d55983c499d7e9e87082e81cbc32974825bf9032f928392d5844"
231+dependencies = [
232+ "compression-codecs",
233+ "compression-core",
234+ "pin-project-lite",
235+ "tokio",
236+]
237+
238+[[package]]
239+name = "async-trait"
240+version = "0.1.92"
241+source = "registry+https://github.com/rust-lang/crates.io-index"
242+checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
243+dependencies = [
244+ "proc-macro2",
245+ "quote",
246+ "syn 3.0.4",
247+]
248+
249+[[package]]
250+name = "atomic-waker"
251+version = "1.1.2"
252+source = "registry+https://github.com/rust-lang/crates.io-index"
253+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
254+
255+[[package]]
256+name = "autocfg"
257+version = "1.5.1"
258+source = "registry+https://github.com/rust-lang/crates.io-index"
259+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
260+
261+[[package]]
262+name = "aws-lc-rs"
263+version = "1.18.1"
264+source = "registry+https://github.com/rust-lang/crates.io-index"
265+checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e"
266+dependencies = [
267+ "aws-lc-sys",
268+ "zeroize",
269+]
270+
271+[[package]]
272+name = "aws-lc-sys"
273+version = "0.45.0"
274+source = "registry+https://github.com/rust-lang/crates.io-index"
275+checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27"
276+dependencies = [
277+ "cc",
278+ "cmake",
279+ "dunce",
280+ "fs_extra",
281+ "pkg-config",
282+]
283+
284+[[package]]
285+name = "base64"
286+version = "0.22.1"
287+source = "registry+https://github.com/rust-lang/crates.io-index"
288+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
289+
290+[[package]]
291+name = "base64"
292+version = "0.23.1"
293+source = "registry+https://github.com/rust-lang/crates.io-index"
294+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
295+
296+[[package]]
297+name = "base64ct"
298+version = "1.8.3"
299+source = "registry+https://github.com/rust-lang/crates.io-index"
300+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
301+
302+[[package]]
303+name = "bigdecimal"
304+version = "0.4.10"
305+source = "registry+https://github.com/rust-lang/crates.io-index"
306+checksum = "4d6867f1565b3aad85681f1015055b087fcfd840d6aeee6eee7f2da317603695"
307+dependencies = [
308+ "autocfg",
309+ "libm",
310+ "num-bigint",
311+ "num-integer",
312+ "num-traits",
313+]
314+
315+[[package]]
316+name = "bindgen"
317+version = "0.69.5"
318+source = "registry+https://github.com/rust-lang/crates.io-index"
319+checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088"
320+dependencies = [
321+ "bitflags",
322+ "cexpr",
323+ "clang-sys",
324+ "itertools 0.12.1",
325+ "lazy_static",
326+ "lazycell",
327+ "log",
328+ "prettyplease 0.2.37",
329+ "proc-macro2",
330+ "quote",
331+ "regex",
332+ "rustc-hash 1.1.0",
333+ "shlex 1.3.0",
334+ "syn 2.0.119",
335+ "which",
336+]
337+
338+[[package]]
339+name = "bitflags"
340+version = "2.13.1"
341+source = "registry+https://github.com/rust-lang/crates.io-index"
342+checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
343+
344+[[package]]
345+name = "bitpacking"
346+version = "0.9.3"
347+source = "registry+https://github.com/rust-lang/crates.io-index"
348+checksum = "96a7139abd3d9cebf8cd6f920a389cf3dc9576172e32f4563f188cae3c3eb019"
349+dependencies = [
350+ "crunchy",
351+]
352+
353+[[package]]
354+name = "bitvec"
355+version = "1.1.1"
356+source = "registry+https://github.com/rust-lang/crates.io-index"
357+checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837"
358+dependencies = [
359+ "funty",
360+ "radium",
361+ "tap",
362+ "wyz",
363+]
364+
365+[[package]]
366+name = "block-buffer"
367+version = "0.10.4"
368+source = "registry+https://github.com/rust-lang/crates.io-index"
369+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
370+dependencies = [
371+ "generic-array",
372+]
373+
374+[[package]]
375+name = "block-buffer"
376+version = "0.12.1"
377+source = "registry+https://github.com/rust-lang/crates.io-index"
378+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
379+dependencies = [
380+ "hybrid-array",
381+]
382+
383+[[package]]
384+name = "bon"
385+version = "3.10.0"
386+source = "registry+https://github.com/rust-lang/crates.io-index"
387+checksum = "9e3fac94a66da67200398458a25412bcc3f9b6443b5119a6cad9cf3ccfcd8cc6"
388+dependencies = [
389+ "bon-macros",
390+]
391+
392+[[package]]
393+name = "bon-macros"
394+version = "3.10.0"
395+source = "registry+https://github.com/rust-lang/crates.io-index"
396+checksum = "d4654961ad0494e4774c5c60b4cb4cd0ae9b9d92d039d901638b1dba97ebebf5"
397+dependencies = [
398+ "darling",
399+ "ident_case",
400+ "prettyplease 0.3.0",
401+ "proc-macro2",
402+ "quote",
403+ "syn 3.0.4",
404+]
405+
406+[[package]]
407+name = "branches"
408+version = "0.4.6"
409+source = "registry+https://github.com/rust-lang/crates.io-index"
410+checksum = "7436b21fd6195415058eb41c9090e156b556bc7e0377bb57c5c026a421521525"
411+dependencies = [
412+ "rustc_version",
413+]
414+
415+[[package]]
416+name = "brotli"
417+version = "8.0.4"
418+source = "registry+https://github.com/rust-lang/crates.io-index"
419+checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
420+dependencies = [
421+ "alloc-no-stdlib",
422+ "alloc-stdlib",
423+ "brotli-decompressor",
424+]
425+
426+[[package]]
427+name = "brotli-decompressor"
428+version = "5.0.3"
429+source = "registry+https://github.com/rust-lang/crates.io-index"
430+checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
431+dependencies = [
432+ "alloc-no-stdlib",
433+ "alloc-stdlib",
434+]
435+
436+[[package]]
437+name = "bumpalo"
438+version = "3.20.3"
439+source = "registry+https://github.com/rust-lang/crates.io-index"
440+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
441+
442+[[package]]
443+name = "bytemuck"
444+version = "1.25.2"
445+source = "registry+https://github.com/rust-lang/crates.io-index"
446+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
447+dependencies = [
448+ "bytemuck_derive",
449+]
450+
451+[[package]]
452+name = "bytemuck_derive"
453+version = "1.12.0"
454+source = "registry+https://github.com/rust-lang/crates.io-index"
455+checksum = "fc0e56a716f1e132ff6bf4bdac1c944a3fcdc1cae65f70a4a2a1ac3b401d2d1f"
456+dependencies = [
457+ "proc-macro2",
458+ "quote",
459+ "syn 3.0.4",
460+]
461+
462+[[package]]
463+name = "byteorder"
464+version = "1.5.0"
465+source = "registry+https://github.com/rust-lang/crates.io-index"
466+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
467+
468+[[package]]
469+name = "byteorder-lite"
470+version = "0.1.0"
471+source = "registry+https://github.com/rust-lang/crates.io-index"
472+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
473+
474+[[package]]
475+name = "bytes"
476+version = "1.12.1"
477+source = "registry+https://github.com/rust-lang/crates.io-index"
478+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
479+
480+[[package]]
481+name = "cc"
482+version = "1.4.5"
483+source = "registry+https://github.com/rust-lang/crates.io-index"
484+checksum = "005ec2760ca554fae18df7a11195552ec576cd665632a881bc011d5bb2fd4d80"
485+dependencies = [
486+ "find-msvc-tools",
487+ "jobserver",
488+ "libc",
489+ "shlex 2.0.1",
490+]
491+
492+[[package]]
493+name = "census"
494+version = "0.4.2"
495+source = "registry+https://github.com/rust-lang/crates.io-index"
496+checksum = "4f4c707c6a209cbe82d10abd08e1ea8995e9ea937d2550646e02798948992be0"
497+
498+[[package]]
499+name = "cexpr"
500+version = "0.6.0"
501+source = "registry+https://github.com/rust-lang/crates.io-index"
502+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
503+dependencies = [
504+ "nom 7.1.3",
505+]
506+
507+[[package]]
508+name = "cfg-if"
509+version = "1.0.4"
510+source = "registry+https://github.com/rust-lang/crates.io-index"
511+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
512+
513+[[package]]
514+name = "cfg_aliases"
515+version = "0.2.2"
516+source = "registry+https://github.com/rust-lang/crates.io-index"
517+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
518+
519+[[package]]
520+name = "cfg_block"
521+version = "0.1.1"
522+source = "registry+https://github.com/rust-lang/crates.io-index"
523+checksum = "18758054972164c3264f7c8386f5fc6da6114cb46b619fd365d4e3b2dc3ae487"
524+
525+[[package]]
526+name = "chacha20"
527+version = "0.9.1"
528+source = "registry+https://github.com/rust-lang/crates.io-index"
529+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
530+dependencies = [
531+ "cfg-if",
532+ "cipher",
533+ "cpufeatures 0.2.17",
534+]
535+
536+[[package]]
537+name = "chacha20"
538+version = "0.10.2"
539+source = "registry+https://github.com/rust-lang/crates.io-index"
540+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
541+dependencies = [
542+ "cfg-if",
543+ "cpufeatures 0.3.1",
544+ "rand_core 0.10.1",
545+]
546+
547+[[package]]
548+name = "chacha20poly1305"
549+version = "0.10.1"
550+source = "registry+https://github.com/rust-lang/crates.io-index"
551+checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
552+dependencies = [
553+ "aead",
554+ "chacha20 0.9.1",
555+ "cipher",
556+ "poly1305",
557+ "zeroize",
558+]
559+
560+[[package]]
561+name = "chrono"
562+version = "0.4.45"
563+source = "registry+https://github.com/rust-lang/crates.io-index"
564+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
565+dependencies = [
566+ "iana-time-zone",
567+ "js-sys",
568+ "num-traits",
569+ "wasm-bindgen",
570+ "windows-link",
571+]
572+
573+[[package]]
574+name = "cipher"
575+version = "0.4.4"
576+source = "registry+https://github.com/rust-lang/crates.io-index"
577+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
578+dependencies = [
579+ "crypto-common 0.1.7",
580+ "inout",
581+ "zeroize",
582+]
583+
584+[[package]]
585+name = "clang-sys"
586+version = "1.9.1"
587+source = "registry+https://github.com/rust-lang/crates.io-index"
588+checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
589+dependencies = [
590+ "glob",
591+ "libc",
592+ "libloading",
593+]
594+
595+[[package]]
596+name = "clap"
597+version = "4.6.6"
598+source = "registry+https://github.com/rust-lang/crates.io-index"
599+checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca"
600+dependencies = [
601+ "clap_builder",
602+]
603+
604+[[package]]
605+name = "clap_builder"
606+version = "4.6.6"
607+source = "registry+https://github.com/rust-lang/crates.io-index"
608+checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889"
609+dependencies = [
610+ "anstream",
611+ "anstyle",
612+ "clap_lex",
613+ "strsim",
614+]
615+
616+[[package]]
617+name = "clap_lex"
618+version = "1.1.0"
619+source = "registry+https://github.com/rust-lang/crates.io-index"
620+checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
621+
622+[[package]]
623+name = "cmake"
624+version = "0.1.58"
625+source = "registry+https://github.com/rust-lang/crates.io-index"
626+checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"
627+dependencies = [
628+ "cc",
629+]
630+
631+[[package]]
632+name = "codemap"
633+version = "0.1.3"
634+source = "registry+https://github.com/rust-lang/crates.io-index"
635+checksum = "b9e769b5c8c8283982a987c6e948e540254f1058d5a74b8794914d4ef5fc2a24"
636+
637+[[package]]
638+name = "color_quant"
639+version = "1.1.0"
640+source = "registry+https://github.com/rust-lang/crates.io-index"
641+checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
642+
643+[[package]]
644+name = "colorchoice"
645+version = "1.0.5"
646+source = "registry+https://github.com/rust-lang/crates.io-index"
647+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
648+
649+[[package]]
650+name = "combine"
651+version = "4.6.8"
652+source = "registry+https://github.com/rust-lang/crates.io-index"
653+checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e"
654+dependencies = [
655+ "bytes",
656+ "memchr",
657+]
658+
659+[[package]]
660+name = "compression-codecs"
661+version = "0.4.39"
662+source = "registry+https://github.com/rust-lang/crates.io-index"
663+checksum = "2fe67f2944eef52fc7b106b8c9450d243a88701a0c065f7f57235e76abaed7df"
664+dependencies = [
665+ "brotli",
666+ "compression-core",
667+ "flate2",
668+ "memchr",
669+]
670+
671+[[package]]
672+name = "compression-core"
673+version = "0.4.33"
674+source = "registry+https://github.com/rust-lang/crates.io-index"
675+checksum = "6e8ccc4ea9f6acc32d102c0f6d471d11d913ad15f20c04de743374861fa1d414"
676+
677+[[package]]
678+name = "concurrent-queue"
679+version = "2.5.0"
680+source = "registry+https://github.com/rust-lang/crates.io-index"
681+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
682+dependencies = [
683+ "crossbeam-utils",
684+]
685+
686+[[package]]
687+name = "const-oid"
688+version = "0.9.6"
689+source = "registry+https://github.com/rust-lang/crates.io-index"
690+checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
691+
692+[[package]]
693+name = "const-oid"
694+version = "0.10.2"
695+source = "registry+https://github.com/rust-lang/crates.io-index"
696+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
697+
698+[[package]]
699+name = "cookie"
700+version = "0.18.2"
701+source = "registry+https://github.com/rust-lang/crates.io-index"
702+checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"
703+dependencies = [
704+ "aes-gcm",
705+ "base64 0.22.1",
706+ "hkdf",
707+ "hmac",
708+ "percent-encoding",
709+ "rand 0.8.8",
710+ "sha2 0.10.9",
711+ "subtle",
712+ "time",
713+ "version_check",
714+]
715+
716+[[package]]
717+name = "core-foundation"
718+version = "0.10.1"
719+source = "registry+https://github.com/rust-lang/crates.io-index"
720+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
721+dependencies = [
722+ "core-foundation-sys",
723+ "libc",
724+]
725+
726+[[package]]
727+name = "core-foundation-sys"
728+version = "0.8.7"
729+source = "registry+https://github.com/rust-lang/crates.io-index"
730+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
731+
732+[[package]]
733+name = "cpufeatures"
734+version = "0.2.17"
735+source = "registry+https://github.com/rust-lang/crates.io-index"
736+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
737+dependencies = [
738+ "libc",
739+]
740+
741+[[package]]
742+name = "cpufeatures"
743+version = "0.3.1"
744+source = "registry+https://github.com/rust-lang/crates.io-index"
745+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
746+dependencies = [
747+ "libc",
748+]
749+
750+[[package]]
751+name = "crc32c"
752+version = "0.6.8"
753+source = "registry+https://github.com/rust-lang/crates.io-index"
754+checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47"
755+dependencies = [
756+ "rustc_version",
757+]
758+
759+[[package]]
760+name = "crc32fast"
761+version = "1.5.1"
762+source = "registry+https://github.com/rust-lang/crates.io-index"
763+checksum = "8498c871161e1742aaa9d52551b2d6ebdd4c3d45a3be423e3728f33b955be550"
764+dependencies = [
765+ "cfg-if",
766+]
767+
768+[[package]]
769+name = "crossbeam-channel"
770+version = "0.5.16"
771+source = "registry+https://github.com/rust-lang/crates.io-index"
772+checksum = "d85363c37faeca707aef026efa9f3b34d077bce547e48f770770625c6013679e"
773+dependencies = [
774+ "crossbeam-utils",
775+]
776+
777+[[package]]
778+name = "crossbeam-deque"
779+version = "0.8.7"
780+source = "registry+https://github.com/rust-lang/crates.io-index"
781+checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"
782+dependencies = [
783+ "crossbeam-epoch",
784+ "crossbeam-utils",
785+]
786+
787+[[package]]
788+name = "crossbeam-epoch"
789+version = "0.9.20"
790+source = "registry+https://github.com/rust-lang/crates.io-index"
791+checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"
792+dependencies = [
793+ "crossbeam-utils",
794+]
795+
796+[[package]]
797+name = "crossbeam-utils"
798+version = "0.8.22"
799+source = "registry+https://github.com/rust-lang/crates.io-index"
800+checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
801+
802+[[package]]
803+name = "crunchy"
804+version = "0.2.4"
805+source = "registry+https://github.com/rust-lang/crates.io-index"
806+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
807+
808+[[package]]
809+name = "crypto-common"
810+version = "0.1.7"
811+source = "registry+https://github.com/rust-lang/crates.io-index"
812+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
813+dependencies = [
814+ "generic-array",
815+ "rand_core 0.6.4",
816+ "typenum",
817+]
818+
819+[[package]]
820+name = "crypto-common"
821+version = "0.2.2"
822+source = "registry+https://github.com/rust-lang/crates.io-index"
823+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
824+dependencies = [
825+ "hybrid-array",
826+]
827+
828+[[package]]
829+name = "ctr"
830+version = "0.9.2"
831+source = "registry+https://github.com/rust-lang/crates.io-index"
832+checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
833+dependencies = [
834+ "cipher",
835+]
836+
837+[[package]]
838+name = "darling"
839+version = "0.24.1"
840+source = "registry+https://github.com/rust-lang/crates.io-index"
841+checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
842+dependencies = [
843+ "darling_core",
844+ "darling_macro",
845+]
846+
847+[[package]]
848+name = "darling_core"
849+version = "0.24.1"
850+source = "registry+https://github.com/rust-lang/crates.io-index"
851+checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
852+dependencies = [
853+ "ident_case",
854+ "proc-macro2",
855+ "quote",
856+ "strsim",
857+ "syn 3.0.4",
858+]
859+
860+[[package]]
861+name = "darling_macro"
862+version = "0.24.1"
863+source = "registry+https://github.com/rust-lang/crates.io-index"
864+checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
865+dependencies = [
866+ "darling_core",
867+ "quote",
868+ "syn 3.0.4",
869+]
870+
871+[[package]]
872+name = "data-encoding"
873+version = "2.11.1"
874+source = "registry+https://github.com/rust-lang/crates.io-index"
875+checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
876+
877+[[package]]
878+name = "datasketches"
879+version = "0.2.0"
880+source = "registry+https://github.com/rust-lang/crates.io-index"
881+checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745"
882+
883+[[package]]
884+name = "der"
885+version = "0.7.10"
886+source = "registry+https://github.com/rust-lang/crates.io-index"
887+checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
888+dependencies = [
889+ "const-oid 0.9.6",
890+ "pem-rfc7468",
891+ "zeroize",
892+]
893+
894+[[package]]
895+name = "deranged"
896+version = "0.5.8"
897+source = "registry+https://github.com/rust-lang/crates.io-index"
898+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
899+dependencies = [
900+ "serde_core",
901+]
902+
903+[[package]]
904+name = "digest"
905+version = "0.10.7"
906+source = "registry+https://github.com/rust-lang/crates.io-index"
907+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
908+dependencies = [
909+ "block-buffer 0.10.4",
910+ "const-oid 0.9.6",
911+ "crypto-common 0.1.7",
912+ "subtle",
913+]
914+
915+[[package]]
916+name = "digest"
917+version = "0.11.3"
918+source = "registry+https://github.com/rust-lang/crates.io-index"
919+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
920+dependencies = [
921+ "block-buffer 0.12.1",
922+ "const-oid 0.10.2",
923+ "crypto-common 0.2.2",
924+]
925+
926+[[package]]
927+name = "displaydoc"
928+version = "0.2.7"
929+source = "registry+https://github.com/rust-lang/crates.io-index"
930+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
931+dependencies = [
932+ "proc-macro2",
933+ "quote",
934+ "syn 3.0.4",
935+]
936+
937+[[package]]
938+name = "downcast-rs"
939+version = "2.0.2"
940+source = "registry+https://github.com/rust-lang/crates.io-index"
941+checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc"
942+
943+[[package]]
944+name = "dunce"
945+version = "1.0.5"
946+source = "registry+https://github.com/rust-lang/crates.io-index"
947+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
948+
949+[[package]]
950+name = "either"
951+version = "1.18.0"
952+source = "registry+https://github.com/rust-lang/crates.io-index"
953+checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
954+
955+[[package]]
956+name = "elsa"
957+version = "1.11.2"
958+source = "registry+https://github.com/rust-lang/crates.io-index"
959+checksum = "9abf33c656a7256451ebb7d0082c5a471820c31269e49d807c538c252352186e"
960+dependencies = [
961+ "stable_deref_trait",
962+]
963+
964+[[package]]
965+name = "email-encoding"
966+version = "0.4.2"
967+source = "registry+https://github.com/rust-lang/crates.io-index"
968+checksum = "420b9da095f052ea597503e39073b5b3c522f7db933fbac202d91d24492693fd"
969+dependencies = [
970+ "base64 0.23.1",
971+ "memchr",
972+]
973+
974+[[package]]
975+name = "email_address"
976+version = "0.2.9"
977+source = "registry+https://github.com/rust-lang/crates.io-index"
978+checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449"
979+
980+[[package]]
981+name = "encoding_rs"
982+version = "0.8.35"
983+source = "registry+https://github.com/rust-lang/crates.io-index"
984+checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"
985+dependencies = [
986+ "cfg-if",
987+]
988+
989+[[package]]
990+name = "env_filter"
991+version = "2.0.0"
992+source = "registry+https://github.com/rust-lang/crates.io-index"
993+checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217"
994+dependencies = [
995+ "log",
996+ "regex",
997+]
998+
999+[[package]]
1000+name = "env_logger"
1001+version = "0.11.11"
1002+source = "registry+https://github.com/rust-lang/crates.io-index"
1003+checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6"
1004+dependencies = [
1005+ "env_filter",
1006+ "log",
1007+]
1008+
1009+[[package]]
1010+name = "equivalent"
1011+version = "1.0.2"
1012+source = "registry+https://github.com/rust-lang/crates.io-index"
1013+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
1014+
1015+[[package]]
1016+name = "erased-serde"
1017+version = "0.4.10"
1018+source = "registry+https://github.com/rust-lang/crates.io-index"
1019+checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
1020+dependencies = [
1021+ "serde",
1022+ "serde_core",
1023+ "typeid",
1024+]
1025+
1026+[[package]]
1027+name = "errno"
1028+version = "0.3.14"
1029+source = "registry+https://github.com/rust-lang/crates.io-index"
1030+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
1031+dependencies = [
1032+ "libc",
1033+ "windows-sys 0.61.2",
1034+]
1035+
1036+[[package]]
1037+name = "fallible-iterator"
1038+version = "0.3.0"
1039+source = "registry+https://github.com/rust-lang/crates.io-index"
1040+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
1041+
1042+[[package]]
1043+name = "fastbloom"
1044+version = "0.14.1"
1045+source = "registry+https://github.com/rust-lang/crates.io-index"
1046+checksum = "4e7f34442dbe69c60fe8eaf58a8cafff81a1f278816d8ab4db255b3bef4ac3c4"
1047+dependencies = [
1048+ "getrandom 0.3.4",
1049+ "libm",
1050+ "siphasher",
1051+]
1052+
1053+[[package]]
1054+name = "fastdivide"
1055+version = "0.4.2"
1056+source = "registry+https://github.com/rust-lang/crates.io-index"
1057+checksum = "9afc2bd4d5a73106dd53d10d73d3401c2f32730ba2c0b93ddb888a8983680471"
1058+
1059+[[package]]
1060+name = "fastrand"
1061+version = "2.5.0"
1062+source = "registry+https://github.com/rust-lang/crates.io-index"
1063+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
1064+
1065+[[package]]
1066+name = "fdeflate"
1067+version = "0.3.7"
1068+source = "registry+https://github.com/rust-lang/crates.io-index"
1069+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
1070+dependencies = [
1071+ "simd-adler32",
1072+]
1073+
1074+[[package]]
1075+name = "find-msvc-tools"
1076+version = "0.1.12"
1077+source = "registry+https://github.com/rust-lang/crates.io-index"
1078+checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d"
1079+
1080+[[package]]
1081+name = "flate2"
1082+version = "1.1.10"
1083+source = "registry+https://github.com/rust-lang/crates.io-index"
1084+checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
1085+dependencies = [
1086+ "crc32fast",
1087+ "miniz_oxide 0.9.1",
1088+ "zlib-rs",
1089+]
1090+
1091+[[package]]
1092+name = "fnv"
1093+version = "1.0.7"
1094+source = "registry+https://github.com/rust-lang/crates.io-index"
1095+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
1096+
1097+[[package]]
1098+name = "foldhash"
1099+version = "0.2.0"
1100+source = "registry+https://github.com/rust-lang/crates.io-index"
1101+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
1102+
1103+[[package]]
1104+name = "form_urlencoded"
1105+version = "1.2.2"
1106+source = "registry+https://github.com/rust-lang/crates.io-index"
1107+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
1108+dependencies = [
1109+ "percent-encoding",
1110+]
1111+
1112+[[package]]
1113+name = "fs4"
1114+version = "0.13.1"
1115+source = "registry+https://github.com/rust-lang/crates.io-index"
1116+checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4"
1117+dependencies = [
1118+ "rustix 1.1.4",
1119+ "windows-sys 0.59.0",
1120+]
1121+
1122+[[package]]
1123+name = "fs_extra"
1124+version = "1.3.0"
1125+source = "registry+https://github.com/rust-lang/crates.io-index"
1126+checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
1127+
1128+[[package]]
1129+name = "funty"
1130+version = "2.0.0"
1131+source = "registry+https://github.com/rust-lang/crates.io-index"
1132+checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
1133+
1134+[[package]]
1135+name = "futures-channel"
1136+version = "0.3.34"
1137+source = "registry+https://github.com/rust-lang/crates.io-index"
1138+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
1139+dependencies = [
1140+ "futures-core",
1141+]
1142+
1143+[[package]]
1144+name = "futures-core"
1145+version = "0.3.34"
1146+source = "registry+https://github.com/rust-lang/crates.io-index"
1147+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
1148+
1149+[[package]]
1150+name = "futures-macro"
1151+version = "0.3.34"
1152+source = "registry+https://github.com/rust-lang/crates.io-index"
1153+checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
1154+dependencies = [
1155+ "proc-macro2",
1156+ "quote",
1157+ "syn 3.0.4",
1158+]
1159+
1160+[[package]]
1161+name = "futures-sink"
1162+version = "0.3.34"
1163+source = "registry+https://github.com/rust-lang/crates.io-index"
1164+checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"
1165+
1166+[[package]]
1167+name = "futures-task"
1168+version = "0.3.34"
1169+source = "registry+https://github.com/rust-lang/crates.io-index"
1170+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
1171+
1172+[[package]]
1173+name = "futures-util"
1174+version = "0.3.34"
1175+source = "registry+https://github.com/rust-lang/crates.io-index"
1176+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
1177+dependencies = [
1178+ "futures-core",
1179+ "futures-macro",
1180+ "futures-sink",
1181+ "futures-task",
1182+ "pin-project-lite",
1183+ "slab",
1184+]
1185+
1186+[[package]]
1187+name = "genawaiter"
1188+version = "0.99.1"
1189+source = "registry+https://github.com/rust-lang/crates.io-index"
1190+checksum = "c86bd0361bcbde39b13475e6e36cb24c329964aa2611be285289d1e4b751c1a0"
1191+dependencies = [
1192+ "genawaiter-macro",
1193+]
1194+
1195+[[package]]
1196+name = "genawaiter-macro"
1197+version = "0.99.1"
1198+source = "registry+https://github.com/rust-lang/crates.io-index"
1199+checksum = "0b32dfe1fdfc0bbde1f22a5da25355514b5e450c33a6af6770884c8750aedfbc"
1200+
1201+[[package]]
1202+name = "generator"
1203+version = "0.8.9"
1204+source = "registry+https://github.com/rust-lang/crates.io-index"
1205+checksum = "b3b854b0e584ead1a33f18b2fcad7cf7be18b3875c78816b753639aa501513ae"
1206+dependencies = [
1207+ "cc",
1208+ "cfg-if",
1209+ "libc",
1210+ "log",
1211+ "rustversion",
1212+ "windows-link",
1213+ "windows-result",
1214+]
1215+
1216+[[package]]
1217+name = "generic-array"
1218+version = "0.14.7"
1219+source = "registry+https://github.com/rust-lang/crates.io-index"
1220+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
1221+dependencies = [
1222+ "typenum",
1223+ "version_check",
1224+]
1225+
1226+[[package]]
1227+name = "getrandom"
1228+version = "0.2.17"
1229+source = "registry+https://github.com/rust-lang/crates.io-index"
1230+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
1231+dependencies = [
1232+ "cfg-if",
1233+ "js-sys",
1234+ "libc",
1235+ "wasi",
1236+ "wasm-bindgen",
1237+]
1238+
1239+[[package]]
1240+name = "getrandom"
1241+version = "0.3.4"
1242+source = "registry+https://github.com/rust-lang/crates.io-index"
1243+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
1244+dependencies = [
1245+ "cfg-if",
1246+ "js-sys",
1247+ "libc",
1248+ "r-efi 5.3.0",
1249+ "wasip2",
1250+ "wasm-bindgen",
1251+]
1252+
1253+[[package]]
1254+name = "getrandom"
1255+version = "0.4.3"
1256+source = "registry+https://github.com/rust-lang/crates.io-index"
1257+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
1258+dependencies = [
1259+ "cfg-if",
1260+ "js-sys",
1261+ "libc",
1262+ "r-efi 6.0.0",
1263+ "rand_core 0.10.1",
1264+ "wasm-bindgen",
1265+]
1266+
1267+[[package]]
1268+name = "ghash"
1269+version = "0.5.1"
1270+source = "registry+https://github.com/rust-lang/crates.io-index"
1271+checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
1272+dependencies = [
1273+ "opaque-debug",
1274+ "polyval",
1275+]
1276+
1277+[[package]]
1278+name = "gif"
1279+version = "0.14.2"
1280+source = "registry+https://github.com/rust-lang/crates.io-index"
1281+checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"
1282+dependencies = [
1283+ "color_quant",
1284+ "weezl",
1285+]
1286+
1287+[[package]]
1288+name = "glob"
1289+version = "0.3.4"
1290+source = "registry+https://github.com/rust-lang/crates.io-index"
1291+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
1292+
1293+[[package]]
1294+name = "grass"
1295+version = "0.13.4"
1296+source = "registry+https://github.com/rust-lang/crates.io-index"
1297+checksum = "f7a68216437ef68f0738e48d6c7bb9e6e6a92237e001b03d838314b068f33c94"
1298+dependencies = [
1299+ "clap",
1300+ "getrandom 0.2.17",
1301+ "grass_compiler",
1302+]
1303+
1304+[[package]]
1305+name = "grass_compiler"
1306+version = "0.13.4"
1307+source = "registry+https://github.com/rust-lang/crates.io-index"
1308+checksum = "2d9e3df7f0222ce5184154973d247c591d9aadc28ce7a73c6cd31100c9facff6"
1309+dependencies = [
1310+ "codemap",
1311+ "indexmap",
1312+ "lasso",
1313+ "once_cell",
1314+ "phf",
1315+ "rand 0.8.8",
1316+]
1317+
1318+[[package]]
1319+name = "h2"
1320+version = "0.4.19"
1321+source = "registry+https://github.com/rust-lang/crates.io-index"
1322+checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16"
1323+dependencies = [
1324+ "atomic-waker",
1325+ "bytes",
1326+ "fnv",
1327+ "futures-core",
1328+ "futures-sink",
1329+ "http",
1330+ "indexmap",
1331+ "slab",
1332+ "tokio",
1333+ "tokio-util",
1334+ "tracing",
1335+]
1336+
1337+[[package]]
1338+name = "hashbrown"
1339+version = "0.14.5"
1340+source = "registry+https://github.com/rust-lang/crates.io-index"
1341+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
1342+dependencies = [
1343+ "ahash",
1344+ "allocator-api2 0.2.21",
1345+]
1346+
1347+[[package]]
1348+name = "hashbrown"
1349+version = "0.16.1"
1350+source = "registry+https://github.com/rust-lang/crates.io-index"
1351+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
1352+dependencies = [
1353+ "allocator-api2 0.2.21",
1354+ "equivalent",
1355+ "foldhash",
1356+]
1357+
1358+[[package]]
1359+name = "hashbrown"
1360+version = "0.17.1"
1361+source = "registry+https://github.com/rust-lang/crates.io-index"
1362+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
1363+
1364+[[package]]
1365+name = "heck"
1366+version = "0.5.0"
1367+source = "registry+https://github.com/rust-lang/crates.io-index"
1368+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
1369+
1370+[[package]]
1371+name = "hermit-abi"
1372+version = "0.5.3"
1373+source = "registry+https://github.com/rust-lang/crates.io-index"
1374+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
1375+
1376+[[package]]
1377+name = "hex"
1378+version = "0.4.3"
1379+source = "registry+https://github.com/rust-lang/crates.io-index"
1380+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
1381+
1382+[[package]]
1383+name = "hkdf"
1384+version = "0.12.4"
1385+source = "registry+https://github.com/rust-lang/crates.io-index"
1386+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
1387+dependencies = [
1388+ "hmac",
1389+]
1390+
1391+[[package]]
1392+name = "hmac"
1393+version = "0.12.1"
1394+source = "registry+https://github.com/rust-lang/crates.io-index"
1395+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
1396+dependencies = [
1397+ "digest 0.10.7",
1398+]
1399+
1400+[[package]]
1401+name = "home"
1402+version = "0.5.12"
1403+source = "registry+https://github.com/rust-lang/crates.io-index"
1404+checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
1405+dependencies = [
1406+ "windows-sys 0.61.2",
1407+]
1408+
1409+[[package]]
1410+name = "hostname"
1411+version = "0.4.2"
1412+source = "registry+https://github.com/rust-lang/crates.io-index"
1413+checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd"
1414+dependencies = [
1415+ "cfg-if",
1416+ "libc",
1417+ "windows-link",
1418+]
1419+
1420+[[package]]
1421+name = "htmlescape"
1422+version = "0.3.1"
1423+source = "registry+https://github.com/rust-lang/crates.io-index"
1424+checksum = "e9025058dae765dee5070ec375f591e2ba14638c63feff74f13805a72e523163"
1425+
1426+[[package]]
1427+name = "http"
1428+version = "1.5.0"
1429+source = "registry+https://github.com/rust-lang/crates.io-index"
1430+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
1431+dependencies = [
1432+ "bytes",
1433+ "itoa",
1434+]
1435+
1436+[[package]]
1437+name = "http-body"
1438+version = "1.1.0"
1439+source = "registry+https://github.com/rust-lang/crates.io-index"
1440+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
1441+dependencies = [
1442+ "bytes",
1443+ "http",
1444+]
1445+
1446+[[package]]
1447+name = "http-body-util"
1448+version = "0.1.5"
1449+source = "registry+https://github.com/rust-lang/crates.io-index"
1450+checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
1451+dependencies = [
1452+ "bytes",
1453+ "futures-core",
1454+ "http",
1455+ "http-body",
1456+ "pin-project-lite",
1457+]
1458+
1459+[[package]]
1460+name = "httparse"
1461+version = "1.10.1"
1462+source = "registry+https://github.com/rust-lang/crates.io-index"
1463+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
1464+
1465+[[package]]
1466+name = "httpdate"
1467+version = "1.0.3"
1468+source = "registry+https://github.com/rust-lang/crates.io-index"
1469+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
1470+
1471+[[package]]
1472+name = "hybrid-array"
1473+version = "0.4.14"
1474+source = "registry+https://github.com/rust-lang/crates.io-index"
1475+checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b"
1476+dependencies = [
1477+ "typenum",
1478+]
1479+
1480+[[package]]
1481+name = "hyper"
1482+version = "1.11.1"
1483+source = "registry+https://github.com/rust-lang/crates.io-index"
1484+checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43"
1485+dependencies = [
1486+ "atomic-waker",
1487+ "bytes",
1488+ "futures-channel",
1489+ "futures-core",
1490+ "h2",
1491+ "http",
1492+ "http-body",
1493+ "httparse",
1494+ "httpdate",
1495+ "itoa",
1496+ "pin-project-lite",
1497+ "smallvec",
1498+ "tokio",
1499+ "want",
1500+]
1501+
1502+[[package]]
1503+name = "hyper-rustls"
1504+version = "0.27.9"
1505+source = "registry+https://github.com/rust-lang/crates.io-index"
1506+checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"
1507+dependencies = [
1508+ "http",
1509+ "hyper",
1510+ "hyper-util",
1511+ "rustls",
1512+ "tokio",
1513+ "tokio-rustls",
1514+ "tower-service",
1515+]
1516+
1517+[[package]]
1518+name = "hyper-util"
1519+version = "0.1.20"
1520+source = "registry+https://github.com/rust-lang/crates.io-index"
1521+checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
1522+dependencies = [
1523+ "base64 0.22.1",
1524+ "bytes",
1525+ "futures-channel",
1526+ "futures-util",
1527+ "http",
1528+ "http-body",
1529+ "hyper",
1530+ "ipnet",
1531+ "libc",
1532+ "percent-encoding",
1533+ "pin-project-lite",
1534+ "socket2",
1535+ "tokio",
1536+ "tower-service",
1537+ "tracing",
1538+]
1539+
1540+[[package]]
1541+name = "iana-time-zone"
1542+version = "0.1.65"
1543+source = "registry+https://github.com/rust-lang/crates.io-index"
1544+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
1545+dependencies = [
1546+ "android_system_properties",
1547+ "core-foundation-sys",
1548+ "iana-time-zone-haiku",
1549+ "js-sys",
1550+ "log",
1551+ "wasm-bindgen",
1552+ "windows-core",
1553+]
1554+
1555+[[package]]
1556+name = "iana-time-zone-haiku"
1557+version = "0.1.2"
1558+source = "registry+https://github.com/rust-lang/crates.io-index"
1559+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
1560+dependencies = [
1561+ "cc",
1562+]
1563+
1564+[[package]]
1565+name = "icu_collator"
1566+version = "2.3.1"
1567+source = "registry+https://github.com/rust-lang/crates.io-index"
1568+checksum = "08984ed58ac439ebf3e13d2cf26b0c46a60afcd21721c1d14087c0b240344dda"
1569+dependencies = [
1570+ "icu_collator_data",
1571+ "icu_collections",
1572+ "icu_locale_core",
1573+ "icu_locale_fallback",
1574+ "icu_normalizer",
1575+ "icu_properties",
1576+ "icu_provider",
1577+ "smallvec",
1578+ "utf16_iter",
1579+ "utf8_iter",
1580+ "zerovec",
1581+]
1582+
1583+[[package]]
1584+name = "icu_collator_data"
1585+version = "2.3.0"
1586+source = "registry+https://github.com/rust-lang/crates.io-index"
1587+checksum = "f7d7e54efdddeb1208c08dd5d32b53a879ac00d2d3d051b2255fd26821d16368"
1588+
1589+[[package]]
1590+name = "icu_collections"
1591+version = "2.3.0"
1592+source = "registry+https://github.com/rust-lang/crates.io-index"
1593+checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
1594+dependencies = [
1595+ "displaydoc",
1596+ "potential_utf",
1597+ "utf8_iter",
1598+ "yoke",
1599+ "zerofrom",
1600+ "zerovec",
1601+]
1602+
1603+[[package]]
1604+name = "icu_locale"
1605+version = "2.3.1"
1606+source = "registry+https://github.com/rust-lang/crates.io-index"
1607+checksum = "785f595c61ef57169a467eeed7b4b6936a66f6cacbb116a96ee86da983251bf4"
1608+dependencies = [
1609+ "icu_collections",
1610+ "icu_locale_core",
1611+ "icu_locale_data",
1612+ "icu_locale_fallback",
1613+ "icu_provider",
1614+ "tinystr",
1615+ "zerovec",
1616+]
1617+
1618+[[package]]
1619+name = "icu_locale_core"
1620+version = "2.3.0"
1621+source = "registry+https://github.com/rust-lang/crates.io-index"
1622+checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
1623+dependencies = [
1624+ "displaydoc",
1625+ "litemap",
1626+ "serde",
1627+ "tinystr",
1628+ "writeable",
1629+ "zerovec",
1630+]
1631+
1632+[[package]]
1633+name = "icu_locale_data"
1634+version = "2.3.0"
1635+source = "registry+https://github.com/rust-lang/crates.io-index"
1636+checksum = "d37d91460e362a5cf58907cd7ce871411775ee6294e49a5cc8e6cec16dfa75ea"
1637+
1638+[[package]]
1639+name = "icu_locale_fallback"
1640+version = "2.3.0"
1641+source = "registry+https://github.com/rust-lang/crates.io-index"
1642+checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9"
1643+dependencies = [
1644+ "icu_locale_core",
1645+ "icu_locale_fallback_data",
1646+ "icu_provider",
1647+ "potential_utf",
1648+ "tinystr",
1649+ "zerovec",
1650+]
1651+
1652+[[package]]
1653+name = "icu_locale_fallback_data"
1654+version = "2.3.0"
1655+source = "registry+https://github.com/rust-lang/crates.io-index"
1656+checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8"
1657+
1658+[[package]]
1659+name = "icu_normalizer"
1660+version = "2.3.0"
1661+source = "registry+https://github.com/rust-lang/crates.io-index"
1662+checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"
1663+dependencies = [
1664+ "icu_collections",
1665+ "icu_normalizer_data",
1666+ "icu_properties",
1667+ "icu_provider",
1668+ "smallvec",
1669+ "utf16_iter",
1670+ "utf8_iter",
1671+ "write16",
1672+ "zerovec",
1673+]
1674+
1675+[[package]]
1676+name = "icu_normalizer_data"
1677+version = "2.3.0"
1678+source = "registry+https://github.com/rust-lang/crates.io-index"
1679+checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
1680+
1681+[[package]]
1682+name = "icu_properties"
1683+version = "2.3.0"
1684+source = "registry+https://github.com/rust-lang/crates.io-index"
1685+checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"
1686+dependencies = [
1687+ "displaydoc",
1688+ "icu_collections",
1689+ "icu_locale_core",
1690+ "icu_properties_data",
1691+ "icu_provider",
1692+ "zerotrie",
1693+ "zerovec",
1694+]
1695+
1696+[[package]]
1697+name = "icu_properties_data"
1698+version = "2.3.0"
1699+source = "registry+https://github.com/rust-lang/crates.io-index"
1700+checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"
1701+
1702+[[package]]
1703+name = "icu_provider"
1704+version = "2.3.1"
1705+source = "registry+https://github.com/rust-lang/crates.io-index"
1706+checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
1707+dependencies = [
1708+ "displaydoc",
1709+ "icu_locale_core",
1710+ "serde",
1711+ "stable_deref_trait",
1712+ "writeable",
1713+ "yoke",
1714+ "zerofrom",
1715+ "zerotrie",
1716+ "zerovec",
1717+]
1718+
1719+[[package]]
1720+name = "ident_case"
1721+version = "1.0.1"
1722+source = "registry+https://github.com/rust-lang/crates.io-index"
1723+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
1724+
1725+[[package]]
1726+name = "idna"
1727+version = "1.1.0"
1728+source = "registry+https://github.com/rust-lang/crates.io-index"
1729+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
1730+dependencies = [
1731+ "idna_adapter",
1732+ "smallvec",
1733+ "utf8_iter",
1734+]
1735+
1736+[[package]]
1737+name = "idna_adapter"
1738+version = "1.2.2"
1739+source = "registry+https://github.com/rust-lang/crates.io-index"
1740+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
1741+dependencies = [
1742+ "icu_normalizer",
1743+ "icu_properties",
1744+]
1745+
1746+[[package]]
1747+name = "image"
1748+version = "0.25.10"
1749+source = "registry+https://github.com/rust-lang/crates.io-index"
1750+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
1751+dependencies = [
1752+ "bytemuck",
1753+ "byteorder-lite",
1754+ "color_quant",
1755+ "gif",
1756+ "image-webp",
1757+ "moxcms",
1758+ "num-traits",
1759+ "png",
1760+ "zune-core",
1761+ "zune-jpeg",
1762+]
1763+
1764+[[package]]
1765+name = "image-webp"
1766+version = "0.2.4"
1767+source = "registry+https://github.com/rust-lang/crates.io-index"
1768+checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
1769+dependencies = [
1770+ "byteorder-lite",
1771+ "quick-error",
1772+]
1773+
1774+[[package]]
1775+name = "in-client"
1776+version = "0.1.0"
1777+dependencies = [
1778+ "base64 0.22.1",
1779+ "chacha20poly1305",
1780+ "http",
1781+ "rand 0.10.2",
1782+ "rand_core 0.6.4",
1783+ "reqwest",
1784+ "rsa",
1785+ "serde",
1786+ "serde_json",
1787+ "sha2 0.10.9",
1788+ "sha2 0.11.0",
1789+ "subtle",
1790+ "thiserror",
1791+ "time",
1792+ "tokio",
1793+ "topcoat",
1794+]
1795+
1796+[[package]]
1797+name = "in-core"
1798+version = "0.1.0"
1799+dependencies = [
1800+ "async-trait",
1801+ "base64 0.22.1",
1802+ "chacha20poly1305",
1803+ "image",
1804+ "rand 0.10.2",
1805+ "serde",
1806+ "serde_json",
1807+ "sha2 0.11.0",
1808+ "subtle",
1809+ "tempfile",
1810+ "thiserror",
1811+ "time",
1812+ "tokio",
1813+ "toml",
1814+ "turso",
1815+ "ulid",
1816+ "zip",
1817+]
1818+
1819+[[package]]
1820+name = "in-web"
1821+version = "0.1.0"
1822+dependencies = [
1823+ "async-trait",
1824+ "futures-util",
1825+ "grass",
1826+ "http",
1827+ "http-body-util",
1828+ "in-client",
1829+ "in-core",
1830+ "serde",
1831+ "serde_json",
1832+ "sha2 0.10.9",
1833+ "thiserror",
1834+ "time",
1835+ "tokio",
1836+ "topcoat",
1837+ "ulid",
1838+]
1839+
1840+[[package]]
1841+name = "indexmap"
1842+version = "2.14.1"
1843+source = "registry+https://github.com/rust-lang/crates.io-index"
1844+checksum = "07aa2048142242915a31d35844fb311e0e53fcca590c3a0a40dcf1b841fa09eb"
1845+dependencies = [
1846+ "equivalent",
1847+ "hashbrown 0.17.1",
1848+]
1849+
1850+[[package]]
1851+name = "inout"
1852+version = "0.1.4"
1853+source = "registry+https://github.com/rust-lang/crates.io-index"
1854+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
1855+dependencies = [
1856+ "generic-array",
1857+]
1858+
1859+[[package]]
1860+name = "intrusive-collections"
1861+version = "0.9.7"
1862+source = "registry+https://github.com/rust-lang/crates.io-index"
1863+checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86"
1864+dependencies = [
1865+ "memoffset",
1866+]
1867+
1868+[[package]]
1869+name = "inventory"
1870+version = "0.3.24"
1871+source = "registry+https://github.com/rust-lang/crates.io-index"
1872+checksum = "a4f0c30c76f2f4ccee3fe55a2435f691ca00c0e4bd87abe4f4a851b1d4dac39b"
1873+dependencies = [
1874+ "rustversion",
1875+]
1876+
1877+[[package]]
1878+name = "io-uring"
1879+version = "0.7.14"
1880+source = "registry+https://github.com/rust-lang/crates.io-index"
1881+checksum = "d64d8ca234d152948ceaede1f419b6a83983a5ecccaac05fb337a809c96d3aa6"
1882+dependencies = [
1883+ "bitflags",
1884+ "cfg-if",
1885+ "libc",
1886+]
1887+
1888+[[package]]
1889+name = "ipnet"
1890+version = "2.12.1"
1891+source = "registry+https://github.com/rust-lang/crates.io-index"
1892+checksum = "6a756c3fac73139e83f14c2d742155dd2b78d3ee56597b419a0579b7bdd6dd78"
1893+
1894+[[package]]
1895+name = "is_terminal_polyfill"
1896+version = "1.70.2"
1897+source = "registry+https://github.com/rust-lang/crates.io-index"
1898+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
1899+
1900+[[package]]
1901+name = "itertools"
1902+version = "0.12.1"
1903+source = "registry+https://github.com/rust-lang/crates.io-index"
1904+checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"
1905+dependencies = [
1906+ "either",
1907+]
1908+
1909+[[package]]
1910+name = "itertools"
1911+version = "0.14.0"
1912+source = "registry+https://github.com/rust-lang/crates.io-index"
1913+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
1914+dependencies = [
1915+ "either",
1916+]
1917+
1918+[[package]]
1919+name = "itoa"
1920+version = "1.0.18"
1921+source = "registry+https://github.com/rust-lang/crates.io-index"
1922+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
1923+
1924+[[package]]
1925+name = "jni"
1926+version = "0.22.4"
1927+source = "registry+https://github.com/rust-lang/crates.io-index"
1928+checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
1929+dependencies = [
1930+ "cfg-if",
1931+ "combine",
1932+ "jni-macros",
1933+ "jni-sys",
1934+ "log",
1935+ "simd_cesu8",
1936+ "thiserror",
1937+ "walkdir",
1938+ "windows-link",
1939+]
1940+
1941+[[package]]
1942+name = "jni-macros"
1943+version = "0.22.4"
1944+source = "registry+https://github.com/rust-lang/crates.io-index"
1945+checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
1946+dependencies = [
1947+ "proc-macro2",
1948+ "quote",
1949+ "rustc_version",
1950+ "simd_cesu8",
1951+ "syn 2.0.119",
1952+]
1953+
1954+[[package]]
1955+name = "jni-sys"
1956+version = "0.4.1"
1957+source = "registry+https://github.com/rust-lang/crates.io-index"
1958+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
1959+dependencies = [
1960+ "jni-sys-macros",
1961+]
1962+
1963+[[package]]
1964+name = "jni-sys-macros"
1965+version = "0.4.1"
1966+source = "registry+https://github.com/rust-lang/crates.io-index"
1967+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
1968+dependencies = [
1969+ "quote",
1970+ "syn 2.0.119",
1971+]
1972+
1973+[[package]]
1974+name = "jobserver"
1975+version = "0.1.35"
1976+source = "registry+https://github.com/rust-lang/crates.io-index"
1977+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
1978+dependencies = [
1979+ "getrandom 0.4.3",
1980+ "libc",
1981+]
1982+
1983+[[package]]
1984+name = "js-sys"
1985+version = "0.3.104"
1986+source = "registry+https://github.com/rust-lang/crates.io-index"
1987+checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a"
1988+dependencies = [
1989+ "cfg-if",
1990+ "futures-util",
1991+ "wasm-bindgen",
1992+]
1993+
1994+[[package]]
1995+name = "lasso"
1996+version = "0.7.3"
1997+source = "registry+https://github.com/rust-lang/crates.io-index"
1998+checksum = "6e14eda50a3494b3bf7b9ce51c52434a761e383d7238ce1dd5dcec2fbc13e9fb"
1999+dependencies = [
2000+ "hashbrown 0.14.5",
Cargo.tomladded+47 -0
@@ -0,0 +1,47 @@
1+[workspace]
2+resolver = "3"
3+members = ["crates/in-core", "crates/in-client", "crates/in-web"]
4+
5+[workspace.package]
6+version = "0.1.0"
7+edition = "2024"
8+license = "GPL-3.0-or-later"
9+repository = "https://github.com/DizeyLab/in"
10+
11+[workspace.dependencies]
12+in-core = { path = "crates/in-core", default-features = false }
13+in-client = { path = "crates/in-client" }
14+serde = { version = "1.0.229", features = ["derive"] }
15+serde_json = "1.0.145"
16+thiserror = "2.0.20"
17+ulid = "1"
18+time = { version = "0.3.55", features = ["serde", "formatting", "parsing", "macros"] }
19+tokio = { version = "1.53.1", features = ["full"] }
20+turso = "=0.8.0-pre.8"
21+rand = "0.10.2"
22+sha2 = "0.11.0"
23+subtle = "2.6.1"
24+chacha20poly1305 = "0.10.1"
25+base64 = "0.22.1"
26+toml = "1"
27+async-trait = "0.1.92"
28+image = { version = "0.25", default-features = false, features = [
29+ "jpeg",
30+ "png",
31+ "gif",
32+ "webp",
33+] }
34+
35+[profile.release]
36+codegen-units = 1
37+lto = true
38+
39+# What the deploy builds. Fat LTO and one codegen unit buy the last few
40+# percent by optimizing the whole program in a single non-parallel pass —
41+# worth it for something CPU-bound, not for a server whose time goes to
42+# SQLite, TLS and the network. Thin LTO still optimizes across crates, in
43+# parallel, so `release` stays available for when the trade is worth making.
44+[profile.dist]
45+inherits = "release"
46+lto = "thin"
47+codegen-units = 16
crates/in-client/Cargo.tomladded+49 -0
@@ -0,0 +1,49 @@
1+[package]
2+name = "in-client"
3+version.workspace = true
4+edition.workspace = true
5+license.workspace = true
6+repository.workspace = true
7+description = "Drop-in OIDC client for topcoat apps authenticating against im"
8+
9+[dependencies]
10+topcoat = { version = "0.6.2", default-features = false, features = [
11+ "router",
12+ "cookie",
13+] }
14+serde.workspace = true
15+serde_json.workspace = true
16+thiserror.workspace = true
17+time.workspace = true
18+tokio.workspace = true
19+base64.workspace = true
20+rand.workspace = true
21+sha2.workspace = true
22+subtle.workspace = true
23+chacha20poly1305.workspace = true
24+# rsa 0.9 verifies through the digest 0.10 traits, so its hasher comes from
25+# the sha2 0.10 line; the workspace sha2 0.11 stays for PKCE.
26+sha2-for-rsa = { package = "sha2", version = "0.10", features = ["oid"] }
27+rsa = "0.9.10"
28+reqwest = { version = "0.13.4", default-features = false, features = [
29+ "rustls",
30+ "json",
31+ "form",
32+] }
33+
34+
35+[features]
36+test-seam = []
37+
38+[dev-dependencies]
39+topcoat = { version = "0.6.2", default-features = false, features = [
40+ "router",
41+ "cookie",
42+ "view",
43+ "serve",
44+ "discover",
45+] }
46+http = "1.5"
47+# Tests generate their own RSA keys, and rsa 0.9's RNG is the rand_core 0.6
48+# line.
49+rand_core06 = { package = "rand_core", version = "0.6.4", features = ["getrandom"] }
crates/in-client/src/lib.rsadded+1310 -0
@@ -0,0 +1,1310 @@
1+//! in-client: drop-in OIDC client for topcoat apps authenticating against im.
2+//!
3+//! An app adds three things: `in_client::mount(builder, config)` when it
4+//! builds its router, `.discover()` as usual (the `/auth/login`,
5+//! `/auth/callback`, `/auth/logout` routes register themselves), and
6+//! `in_client::current_user(cx)` wherever it needs the person.
7+//!
8+//! The model: im holds the central session; this crate holds the app's side
9+//! of it — an encrypted cookie with the identity claims and the refresh
10+//! token. When the access token ages out, `current_user` silently rotates it
11+//! against im; when im has revoked the central session, the rotation is
12+//! refused and the app sees a signed-out user.
13+
14+use base64::Engine;
15+use base64::engine::general_purpose::URL_SAFE_NO_PAD as b64url;
16+use chacha20poly1305::aead::Aead;
17+use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce};
18+use rand::Rng;
19+use serde::{Deserialize, Serialize};
20+use sha2::{Digest, Sha256};
21+use subtle::ConstantTimeEq;
22+use time::OffsetDateTime;
23+use topcoat::context::{Cx, try_app_context};
24+use topcoat::cookie::{Cookie, Cookies, cookie, cookies};
25+use topcoat::router::response::{IntoResponse, Response};
26+use topcoat::router::{HeaderValue, RouterBuilder, StatusCode, header, route};
27+
28+// ---------------------------------------------------------------------------
29+// Configuration and state
30+// ---------------------------------------------------------------------------
31+
32+/// Everything the app knows about its im registration. `client_secret` and
33+/// `cookie_key` are secrets: the first authenticates the app to im, the
34+/// second seals the browser cookies this crate writes.
35+#[derive(Clone)]
36+pub struct Config {
37+ /// im's base URL, e.g. `http://127.0.0.1:7650` or `https://auth.example.com`.
38+ pub issuer: String,
39+ pub client_id: String,
40+ pub client_secret: String,
41+ /// Must exactly match one of the URIs registered with im.
42+ pub redirect_uri: String,
43+ /// The app's session cookie name, e.g. `in_session`.
44+ pub cookie_name: String,
45+ /// 32 bytes, generated once per app and kept out of the repository.
46+ pub cookie_key: [u8; 32],
47+}
48+
49+/// The registered state: the config, one HTTP client, and the JWKS cache.
50+pub struct InClient {
51+ config: Config,
52+ http: reqwest::Client,
53+ jwks: tokio::sync::RwLock<Option<JwksCache>>,
54+}
55+
56+struct JwksCache {
57+ fetched_at: OffsetDateTime,
58+ /// kid -> public key
59+ keys: Vec<(String, rsa::RsaPublicKey)>,
60+}
61+
62+#[derive(Debug, thiserror::Error)]
63+pub enum Error {
64+ #[error("http: {0}")]
65+ Http(String),
66+ #[error("im refused: {0}")]
67+ Refused(String),
68+ #[error("bad token: {0}")]
69+ Token(String),
70+}
71+
72+pub type Result<T, E = Error> = std::result::Result<T, E>;
73+
74+impl InClient {
75+ pub fn new(config: Config) -> Self {
76+ InClient {
77+ config,
78+ http: reqwest::Client::new(),
79+ jwks: tokio::sync::RwLock::new(None),
80+ }
81+ }
82+}
83+
84+/// Registers the client state on the router. The routes themselves register
85+/// through `discover()` — call it as usual.
86+pub fn mount(builder: RouterBuilder, config: Config) -> RouterBuilder {
87+ builder.app_context(InClient::new(config))
88+}
89+
90+fn client(cx: &Cx) -> &InClient {
91+ try_app_context::<InClient>(cx).expect("in_client::mount was called on the router")
92+}
93+
94+/// The authenticated person, if this browser has one. Every call asks im:
95+/// the cookie holds an opaque session token, introspected per request, so an
96+/// admin revoking the person signs them out of this app immediately — there
97+/// is no token-validity window in which a ghost lives.
98+pub async fn current_user(cx: &Cx) -> Option<User> {
99+ let state = client(cx);
100+ let sealed = cookies(cx).get(&state.config.cookie_name)?;
101+ let session: Session = open_json(&state.config.cookie_key, sealed.value())?;
102+ if session.exp <= OffsetDateTime::now_utc().unix_timestamp() {
103+ clear_cookie(cx, &state.config.cookie_name);
104+ return None;
105+ }
106+ match introspect(state, &session.app_session).await {
107+ Introspected::Active(user, _exp) => Some(user),
108+ Introspected::Revoked => {
109+ clear_cookie(cx, &state.config.cookie_name);
110+ None
111+ }
112+ // The question went unanswered — a blackholed route, a dropped
113+ // connection, a body that is not the JSON im speaks. Nothing was
114+ // learned about the session, so this request reads as signed-out
115+ // while the cookie stays for the next request to try again.
116+ Introspected::Unanswered => None,
117+ }
118+}
119+
120+/// Path of im's RFC 7662 introspection endpoint, relative to the issuer.
121+const INTROSPECT_PATH: &str = "/introspect";
122+
123+/// What one introspection round-trip settled.
124+enum Introspected {
125+ /// im answered `"active": true` with usable claims.
126+ Active(User, i64),
127+ /// im answered `"active": false`: the central session is gone and the
128+ /// app cookie goes with it.
129+ Revoked,
130+ /// The question itself went unanswered — the transport failed, the body
131+ /// was not JSON, or the claims were missing their fields. Nothing about
132+ /// the session was learned, so the cookie must stay.
133+ Unanswered,
134+}
135+
136+async fn introspect(state: &InClient, token: &str) -> Introspected {
137+ let Ok(reply) = state
138+ .http
139+ .post(format!("{}{}", state.config.issuer, INTROSPECT_PATH))
140+ .form(&[
141+ ("token", token),
142+ ("client_id", &state.config.client_id),
143+ ("client_secret", &state.config.client_secret),
144+ ])
145+ .send()
146+ .await
147+ else {
148+ return Introspected::Unanswered;
149+ };
150+ let Ok(answer): Result<serde_json::Value, _> = reply.json().await else {
151+ return Introspected::Unanswered;
152+ };
153+ // Only an explicit `"active": false` revokes. A missing or non-boolean
154+ // `active` is a malformed answer, not a revocation.
155+ match answer.get("active") {
156+ Some(serde_json::Value::Bool(true)) => {}
157+ Some(serde_json::Value::Bool(false)) => return Introspected::Revoked,
158+ _ => return Introspected::Unanswered,
159+ }
160+ let (Some(sub), Some(email), Some(name), Some(exp)) = (
161+ answer["sub"].as_str(),
162+ answer["email"].as_str(),
163+ answer["name"].as_str(),
164+ answer["exp"].as_i64(),
165+ ) else {
166+ return Introspected::Unanswered;
167+ };
168+ Introspected::Active(
169+ User {
170+ sub: sub.to_string(),
171+ email: email.to_string(),
172+ name: name.to_string(),
173+ },
174+ exp,
175+ )
176+}
177+
178+/// Who this browser is, from the claims.
179+#[derive(Debug, Clone, Serialize, Deserialize)]
180+pub struct User {
181+ pub sub: String,
182+ pub email: String,
183+ pub name: String,
184+}
185+
186+// ---------------------------------------------------------------------------
187+// The app session cookie
188+// ---------------------------------------------------------------------------
189+
190+#[derive(Serialize, Deserialize)]
191+struct Session {
192+ /// The opaque token im issued at the code exchange; introspected per
193+ /// request, never trusted on its own.
194+ app_session: String,
195+ exp: i64,
196+}
197+
198+/// Test seam for integration tests: seals a session cookie exactly like the
199+/// `/auth/callback` handler does, without a live im. Returns the cookie
200+/// VALUE only; tests set the `Cookie` header themselves.
201+#[cfg(feature = "test-seam")]
202+pub fn mint_session_cookie(
203+ config: &Config,
204+ app_session: &str,
205+ exp: time::OffsetDateTime,
206+) -> String {
207+ seal_json(
208+ &config.cookie_key,
209+ &Session {
210+ app_session: app_session.to_string(),
211+ exp: exp.unix_timestamp(),
212+ },
213+ )
214+}
215+
216+/// The introspection path `current_user` POSTs to, so a fake-im test server
217+/// can mount the right route.
218+#[cfg(feature = "test-seam")]
219+pub fn introspect_path() -> &'static str {
220+ INTROSPECT_PATH
221+}
222+
223+/// The in-flight login: PKCE verifier, state, nonce, and where to land after.
224+#[derive(Serialize, Deserialize)]
225+struct InFlight {
226+ verifier: String,
227+ state: String,
228+ nonce: String,
229+ next: String,
230+ exp: i64,
231+}
232+
233+const IN_FLIGHT_MINUTES: i64 = 10;
234+
235+fn seal(key: &[u8; 32], plaintext: &[u8]) -> String {
236+ let cipher = XChaCha20Poly1305::new(key.into());
237+ let mut nonce_bytes = [0u8; 24];
238+ rand::rng().fill_bytes(&mut nonce_bytes);
239+ let ciphertext = cipher
240+ .encrypt(XNonce::from_slice(&nonce_bytes), plaintext)
241+ .expect("XChaCha20-Poly1305 cannot fail on a payload this small");
242+ let mut payload = nonce_bytes.to_vec();
243+ payload.extend_from_slice(&ciphertext);
244+ b64url.encode(payload)
245+}
246+
247+fn open(key: &[u8; 32], sealed: &str) -> Option<Vec<u8>> {
248+ let payload = b64url.decode(sealed).ok()?;
249+ if payload.len() < 24 {
250+ return None;
251+ }
252+ let (nonce_bytes, ciphertext) = payload.split_at(24);
253+ let cipher = XChaCha20Poly1305::new(key.into());
254+ cipher
255+ .decrypt(XNonce::from_slice(nonce_bytes), ciphertext)
256+ .ok()
257+}
258+
259+fn seal_json<T: Serialize>(key: &[u8; 32], value: &T) -> String {
260+ seal(key, &serde_json::to_vec(value).expect("plain data"))
261+}
262+
263+fn open_json<T: for<'de> Deserialize<'de>>(key: &[u8; 32], sealed: &str) -> Option<T> {
264+ serde_json::from_slice(&open(key, sealed)?).ok()
265+}
266+
267+fn app_cookies(cx: &Cx) -> impl Cookies {
268+ cookies(cx)
269+ .default_secure(client(cx).config.issuer.starts_with("https://"))
270+ .default_http_only(true)
271+ .default_same_site(topcoat::cookie::SameSite::Lax)
272+ .default_path("/")
273+}
274+
275+fn set_session_cookie(cx: &Cx, state: &InClient, session: &Session) {
276+ let name = state.config.cookie_name.clone();
277+ app_cookies(cx).add(cookie! {
278+ name = seal_json(&state.config.cookie_key, session);
279+ Path = "/";
280+ HttpOnly;
281+ SameSite = Lax;
282+ MaxAge = time::Duration::days(30)
283+ });
284+}
285+
286+fn clear_cookie(cx: &Cx, name: &str) {
287+ app_cookies(cx).remove(Cookie::build((name.to_string(), "")).path("/").build());
288+}
289+
290+// ---------------------------------------------------------------------------
291+// Routes
292+// ---------------------------------------------------------------------------
293+
294+fn see(cx: &Cx, location: &str) -> Result<Response, topcoat::Error> {
295+ (
296+ StatusCode::SEE_OTHER,
297+ [(header::LOCATION, location_value(location))],
298+ )
299+ .into_response(cx)
300+}
301+
302+/// A `Location` value that cannot panic its handler: anything `HeaderValue`
303+/// still refuses (a hostile `next` sealed before the strict validation, a
304+/// query echo) lands on `/` instead of killing the request.
305+fn location_value(location: &str) -> HeaderValue {
306+ HeaderValue::from_str(location).unwrap_or_else(|_| HeaderValue::from_static("/"))
307+}
308+
309+/// A `next` worth honoring: a local absolute path, never `//elsewhere`,
310+/// never carrying control bytes, never touching a backslash. The query
311+/// arrives percent-decoded, so `%0D%0A` is a real CR LF by the time it is
312+/// checked — and a sealed `next` is rendered into a `Location` header, so
313+/// anything `HeaderValue` would choke on must die here. Backslashes die
314+/// here too: browsers normalize `\` to `/` in `Location`, turning
315+/// `/\evil` into a cross-origin hop.
316+fn safe_next(raw: &str) -> &str {
317+ if raw.starts_with('/')
318+ && !raw.starts_with("//")
319+ && !raw.contains('\\')
320+ && !raw.chars().any(|c| c.is_control())
321+ {
322+ raw
323+ } else {
324+ "/"
325+ }
326+}
327+
328+/// A JWKS older than this is refreshed before the next validation.
329+const JWKS_TTL_SECONDS: i64 = 3600;
330+
331+async fn jwks_stale(state: &InClient) -> bool {
332+ match state.jwks.read().await.as_ref() {
333+ None => true,
334+ Some(cache) => {
335+ cache.fetched_at < OffsetDateTime::now_utc() - time::Duration::seconds(JWKS_TTL_SECONDS)
336+ }
337+ }
338+}
339+
340+fn query_value(query: &str, key: &str) -> Option<String> {
341+ query.split('&').find_map(|pair| {
342+ let (k, v) = pair.split_once('=')?;
343+ (k == key).then(|| urldecode(v))
344+ })
345+}
346+
347+/// Percent-decodes a query value (`+` is a space, form-style).
348+fn urldecode(raw: &str) -> String {
349+ let bytes = raw.as_bytes();
350+ let mut out = Vec::with_capacity(bytes.len());
351+ let mut i = 0;
352+ while i < bytes.len() {
353+ match bytes[i] {
354+ b'+' => {
355+ out.push(b' ');
356+ i += 1;
357+ }
358+ b'%' if i + 2 < bytes.len() => {
359+ let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or("");
360+ match u8::from_str_radix(hex, 16) {
361+ Ok(byte) => {
362+ out.push(byte);
363+ i += 3;
364+ }
365+ Err(_) => {
366+ out.push(b'%');
367+ i += 1;
368+ }
369+ }
370+ }
371+ byte => {
372+ out.push(byte);
373+ i += 1;
374+ }
375+ }
376+ }
377+ String::from_utf8_lossy(&out).into_owned()
378+}
379+
380+fn random_b64(bytes: usize) -> String {
381+ let mut buf = vec![0u8; bytes];
382+ rand::rng().fill_bytes(&mut buf);
383+ b64url.encode(buf)
384+}
385+
386+/// Sends the browser to im's `/authorize` with a fresh PKCE pair.
387+#[route(GET "/auth/login")]
388+async fn in_login(cx: &Cx) -> Result<Response, topcoat::Error> {
389+ let state = client(cx);
390+ let query = topcoat::router::request::uri(cx)
391+ .query()
392+ .unwrap_or("")
393+ .to_string();
394+ let next = safe_next(query_value(&query, "next").as_deref().unwrap_or("/")).to_string();
395+
396+ let flight = InFlight {
397+ verifier: random_b64(32),
398+ state: random_b64(16),
399+ nonce: random_b64(16),
400+ next,
401+ exp: OffsetDateTime::now_utc().unix_timestamp() + IN_FLIGHT_MINUTES * 60,
402+ };
403+ let challenge = b64url.encode(Sha256::digest(flight.verifier.as_bytes()));
404+ let cookie_name = format!("{}_pkce", state.config.cookie_name);
405+ app_cookies(cx).add(cookie! {
406+ cookie_name = seal_json(&state.config.cookie_key, &flight);
407+ Path = "/";
408+ HttpOnly;
409+ SameSite = Lax;
410+ MaxAge = time::Duration::minutes(IN_FLIGHT_MINUTES)
411+ });
412+
413+ let url = format!(
414+ "{}/authorize?response_type=code&client_id={}&redirect_uri={}&scope=openid%20profile%20email&state={}&nonce={}&code_challenge={}&code_challenge_method=S256",
415+ state.config.issuer,
416+ state.config.client_id,
417+ urlencoded(&state.config.redirect_uri),
418+ flight.state,
419+ flight.nonce,
420+ challenge,
421+ );
422+ see(cx, &url)
423+}
424+
425+/// im's answer lands here: exchange the code, validate the id_token, mint
426+/// the app session.
427+#[route(GET "/auth/callback")]
428+async fn in_callback(cx: &Cx) -> Result<Response, topcoat::Error> {
429+ let state = client(cx);
430+ let query = topcoat::router::request::uri(cx)
431+ .query()
432+ .unwrap_or("")
433+ .to_string();
434+ if let Some(error) = query_value(&query, "error") {
435+ return see(cx, &format!("/?auth_error={error}"));
436+ }
437+ let (Some(code), Some(presented_state)) =
438+ (query_value(&query, "code"), query_value(&query, "state"))
439+ else {
440+ return see(cx, "/?auth_error=invalid_request");
441+ };
442+ let cookie_name = format!("{}_pkce", state.config.cookie_name);
443+ let flight: Option<InFlight> = cookies(cx)
444+ .get(&cookie_name)
445+ .and_then(|c| open_json(&state.config.cookie_key, c.value()));
446+ let Some(flight) = flight else {
447+ return see(cx, "/?auth_error=invalid_request");
448+ };
449+ clear_cookie(cx, &cookie_name);
450+ if flight.exp <= OffsetDateTime::now_utc().unix_timestamp()
451+ || flight
452+ .state
453+ .as_bytes()
454+ .ct_eq(presented_state.as_bytes())
455+ .unwrap_u8()
456+ != 1
457+ {
458+ return see(cx, "/?auth_error=invalid_state");
459+ }
460+
461+ match exchange_code(state, &code, &flight).await {
462+ Ok(session) => {
463+ set_session_cookie(cx, state, &session);
464+ // Re-validated, not trusted: the flight cookie may predate the
465+ // strict `next` rules, and its bytes land in a header.
466+ see(cx, safe_next(&flight.next))
467+ }
468+ Err(_) => see(cx, "/?auth_error=exchange_failed"),
469+ }
470+}
471+
472+/// Signs out of the app only. To end the central session too, post to im's
473+/// `/logout` — a link there is a silent re-login, by design.
474+#[route(GET "/auth/logout")]
475+async fn in_logout(cx: &Cx) -> Result<Response, topcoat::Error> {
476+ clear_cookie(cx, &client(cx).config.cookie_name);
477+ see(cx, "/")
478+}
479+
480+fn urlencoded(raw: &str) -> String {
481+ let mut out = String::with_capacity(raw.len());
482+ for byte in raw.bytes() {
483+ match byte {
484+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
485+ out.push(byte as char)
486+ }
487+ _ => out.push_str(&format!("%{byte:02X}")),
488+ }
489+ }
490+ out
491+}
492+
493+// ---------------------------------------------------------------------------
494+// Token exchange, refresh, validation
495+// ---------------------------------------------------------------------------
496+
497+#[derive(Deserialize)]
498+struct TokenAnswer {
499+ /// Validated for its nonce and signature; the identity the app serves
500+ /// comes from introspection, not from these claims.
501+ id_token: String,
502+ /// Not OIDC — im's own: the opaque session this crate introspects per
503+ /// request. Absent means the issuer is not a current im.
504+ app_session: Option<String>,
505+}
506+
507+async fn exchange_code(state: &InClient, code: &str, flight: &InFlight) -> Result<Session> {
508+ let answer: TokenAnswer = state
509+ .http
510+ .post(format!("{}/token", state.config.issuer))
511+ .form(&[
512+ ("grant_type", "authorization_code"),
513+ ("code", code),
514+ ("redirect_uri", &state.config.redirect_uri),
515+ ("client_id", &state.config.client_id),
516+ ("client_secret", &state.config.client_secret),
517+ ("code_verifier", &flight.verifier),
518+ ])
519+ .send()
520+ .await
521+ .map_err(|e| Error::Http(e.to_string()))?
522+ .error_for_status()
523+ .map_err(|e| Error::Refused(e.to_string()))?
524+ .json()
525+ .await
526+ .map_err(|e| Error::Http(e.to_string()))?;
527+ let claims = validate_id_token(state, &answer.id_token).await?;
528+ if claims["nonce"].as_str() != Some(flight.nonce.as_str()) {
529+ return Err(Error::Token("nonce mismatch".into()));
530+ }
531+ let app_session = answer
532+ .app_session
533+ .ok_or_else(|| Error::Token("issuer gave no app session".into()))?;
534+ // The session's expiry and identity come from a live introspection, not
535+ // from the token answer — the same check every later request will make.
536+ // Any non-answer (revoked or unanswered alike) means there is no fresh
537+ // session to mint.
538+ let (_user, exp) = match introspect(state, &app_session).await {
539+ Introspected::Active(user, exp) => (user, exp),
540+ Introspected::Revoked | Introspected::Unanswered => {
541+ return Err(Error::Refused("fresh app session does not introspect".into()));
542+ }
543+ };
544+ Ok(Session { app_session, exp })
545+}
546+
547+/// Validates an id_token: RS256 against im's JWKS, issuer, audience, expiry.
548+/// The nonce is the caller's to check (only the callback holds one).
549+async fn validate_id_token(state: &InClient, token: &str) -> Result<serde_json::Value> {
550+ let parts: Vec<&str> = token.split('.').collect();
551+ if parts.len() != 3 {
552+ return Err(Error::Token("not a compact JWT".into()));
553+ }
554+ let header: serde_json::Value = serde_json::from_slice(
555+ &b64url
556+ .decode(parts[0])
557+ .map_err(|e| Error::Token(e.to_string()))?,
558+ )
559+ .map_err(|e| Error::Token(e.to_string()))?;
560+ if header["alg"] != "RS256" {
561+ return Err(Error::Token("unexpected alg".into()));
562+ }
563+ let kid = header["kid"]
564+ .as_str()
565+ .ok_or_else(|| Error::Token("no kid".into()))?
566+ .to_string();
567+
568+ if jwks_stale(state).await {
569+ refetch_jwks(state).await?;
570+ }
571+ let key = match cached_key(state, &kid).await {
572+ Some(key) => key,
573+ None => {
574+ refetch_jwks(state).await?;
575+ cached_key(state, &kid)
576+ .await
577+ .ok_or_else(|| Error::Token("unknown kid after refetch".into()))?
578+ }
579+ };
580+
581+ verify_claims(&parts, &key, &state.config.issuer, &state.config.client_id)
582+}
583+
584+/// The pure half of [`validate_id_token`]: signature, issuer, audience,
585+/// expiry. Split out so the test suite signs its own tokens without standing
586+/// a server up.
587+fn verify_claims(
588+ parts: &[&str],
589+ key: &rsa::RsaPublicKey,
590+ issuer: &str,
591+ client_id: &str,
592+) -> Result<serde_json::Value> {
593+ use rsa::signature::Verifier;
594+ let signature_bytes = b64url
595+ .decode(parts[2])
596+ .map_err(|e| Error::Token(e.to_string()))?;
597+ let signature = rsa::pkcs1v15::Signature::try_from(signature_bytes.as_slice())
598+ .map_err(|e| Error::Token(e.to_string()))?;
599+ let verifying = rsa::pkcs1v15::VerifyingKey::<sha2_for_rsa::Sha256>::new(key.clone());
600+ verifying
601+ .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature)
602+ .map_err(|_| Error::Token("bad signature".into()))?;
603+
604+ let claims: serde_json::Value = serde_json::from_slice(
605+ &b64url
606+ .decode(parts[1])
607+ .map_err(|e| Error::Token(e.to_string()))?,
608+ )
609+ .map_err(|e| Error::Token(e.to_string()))?;
610+ if claims["iss"].as_str() != Some(issuer) {
611+ return Err(Error::Token("wrong issuer".into()));
612+ }
613+ if claims["aud"].as_str() != Some(client_id) {
614+ return Err(Error::Token("wrong audience".into()));
615+ }
616+ match claims["exp"].as_i64() {
617+ Some(exp) if exp > OffsetDateTime::now_utc().unix_timestamp() => {}
618+ _ => return Err(Error::Token("expired".into())),
619+ }
620+ Ok(claims)
621+}
622+
623+async fn cached_key(state: &InClient, kid: &str) -> Option<rsa::RsaPublicKey> {
624+ state
625+ .jwks
626+ .read()
627+ .await
628+ .as_ref()?
629+ .keys
630+ .iter()
631+ .find(|(k, _)| k == kid)
632+ .map(|(_, key)| key.clone())
633+}
634+
635+/// Fetches and caches im's JWKS. Cached for an hour at most; an unknown kid
636+/// forces an immediate refetch above.
637+async fn refetch_jwks(state: &InClient) -> Result<()> {
638+ let doc: serde_json::Value = state
639+ .http
640+ .get(format!("{}/jwks.json", state.config.issuer))
641+ .send()
642+ .await
643+ .map_err(|e| Error::Http(e.to_string()))?
644+ .error_for_status()
645+ .map_err(|e| Error::Refused(e.to_string()))?
646+ .json()
647+ .await
648+ .map_err(|e| Error::Http(e.to_string()))?;
649+ let mut keys = Vec::new();
650+ for jwk in doc["keys"].as_array().into_iter().flatten() {
651+ let (Some(kid), Some(n), Some(e)) =
652+ (jwk["kid"].as_str(), jwk["n"].as_str(), jwk["e"].as_str())
653+ else {
654+ continue;
655+ };
656+ let (Ok(n), Ok(e)) = (b64url.decode(n), b64url.decode(e)) else {
657+ continue;
658+ };
659+ let key = rsa::RsaPublicKey::new(
660+ rsa::BigUint::from_bytes_be(&n),
661+ rsa::BigUint::from_bytes_be(&e),
662+ )
663+ .map_err(|err| Error::Token(format!("bad jwk {kid}: {err}")))?;
664+ keys.push((kid.to_string(), key));
665+ }
666+ *state.jwks.write().await = Some(JwksCache {
667+ fetched_at: OffsetDateTime::now_utc(),
668+ keys,
669+ });
670+ Ok(())
671+}
672+#[cfg(test)]
673+mod tests {
674+ use super::*;
675+ use rsa::signature::{SignatureEncoding, Signer};
676+ use rsa::traits::PublicKeyParts;
677+ use topcoat::cookie::RouterBuilderCookieExt;
678+ use topcoat::router::{Body, Router, to_bytes};
679+ use std::sync::{Arc, OnceLock};
680+
681+ fn keypair() -> (rsa::RsaPrivateKey, rsa::RsaPublicKey) {
682+ // 2048-bit generation is slow for a unit test; 1024 is the smallest
683+ // rsa 0.9 accepts and the signature math under test is identical.
684+ let private = rsa::RsaPrivateKey::new(&mut rand_core06::OsRng, 1024).unwrap();
685+ let public = private.to_public_key();
686+ (private, public)
687+ }
688+
689+ fn sign(claims: serde_json::Value, key: &rsa::RsaPrivateKey) -> String {
690+ let header = serde_json::json!({"alg": "RS256", "typ": "JWT", "kid": "test"});
691+ let mut out = b64url.encode(header.to_string());
692+ out.push('.');
693+ out.push_str(&b64url.encode(claims.to_string()));
694+ let signing = rsa::pkcs1v15::SigningKey::<sha2_for_rsa::Sha256>::new(key.clone());
695+ let signature = signing.sign(out.as_bytes());
696+ format!("{}.{}", out, b64url.encode(signature.to_bytes()))
697+ }
698+
699+ fn good_claims() -> serde_json::Value {
700+ serde_json::json!({
701+ "iss": "http://im.test",
702+ "sub": "user-1",
703+ "aud": "client-1",
704+ "exp": OffsetDateTime::now_utc().unix_timestamp() + 600,
705+ "iat": OffsetDateTime::now_utc().unix_timestamp(),
706+ "email": "ann@example.com",
707+ "name": "Ann",
708+ })
709+ }
710+
711+ #[test]
712+ fn valid_token_validates() {
713+ let (private, public) = keypair();
714+ let token = sign(good_claims(), &private);
715+ let parts: Vec<&str> = token.split('.').collect();
716+ let claims = verify_claims(&parts, &public, "http://im.test", "client-1").unwrap();
717+ assert_eq!(claims["sub"], "user-1");
718+ }
719+
720+ #[test]
721+ fn tampered_payload_rejected() {
722+ let (private, public) = keypair();
723+ let token = sign(good_claims(), &private);
724+ let parts: Vec<&str> = token.split('.').collect();
725+ let forged_payload = b64url.encode(r#"{"sub":"mallory"}"#);
726+ let forged = vec![parts[0], forged_payload.as_str(), parts[2]];
727+ assert!(verify_claims(&forged, &public, "http://im.test", "client-1").is_err());
728+ }
729+
730+ #[test]
731+ fn wrong_key_rejected() {
732+ let (private, _) = keypair();
733+ let (_, other_public) = keypair();
734+ let token = sign(good_claims(), &private);
735+ let parts: Vec<&str> = token.split('.').collect();
736+ assert!(verify_claims(&parts, &other_public, "http://im.test", "client-1").is_err());
737+ }
738+
739+ #[test]
740+ fn wrong_audience_rejected() {
741+ let (private, public) = keypair();
742+ let token = sign(good_claims(), &private);
743+ let parts: Vec<&str> = token.split('.').collect();
744+ assert!(verify_claims(&parts, &public, "http://im.test", "another-app").is_err());
745+ }
746+
747+ #[test]
748+ fn wrong_issuer_rejected() {
749+ let (private, public) = keypair();
750+ let token = sign(good_claims(), &private);
751+ let parts: Vec<&str> = token.split('.').collect();
752+ assert!(verify_claims(&parts, &public, "https://elsewhere.example", "client-1").is_err());
753+ }
754+
755+ #[test]
756+ fn expired_rejected() {
757+ let (private, public) = keypair();
758+ let mut claims = good_claims();
759+ claims["exp"] = (OffsetDateTime::now_utc().unix_timestamp() - 10).into();
760+ let token = sign(claims, &private);
761+ let parts: Vec<&str> = token.split('.').collect();
762+ assert!(verify_claims(&parts, &public, "http://im.test", "client-1").is_err());
763+ }
764+
765+ #[test]
766+ fn pkce_rfc7636_vector() {
767+ // RFC 7636 Appendix B.
768+ let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
769+ let challenge = b64url.encode(Sha256::digest(verifier.as_bytes()));
770+ assert_eq!(challenge, "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM");
771+ }
772+
773+ #[test]
774+ fn cookie_seal_roundtrip() {
775+ let key = [7u8; 32];
776+ let session = Session {
777+ app_session: "opaque-token".into(),
778+ exp: 1,
779+ };
780+ let sealed = seal_json(&key, &session);
781+ let back: Session = open_json(&key, &sealed).unwrap();
782+ assert_eq!(back.app_session, "opaque-token");
783+ assert!(open_json::<Session>(&[8u8; 32], &sealed).is_none());
784+ assert!(open_json::<Session>(&key, "garbage").is_none());
785+ }
786+
787+ #[cfg(feature = "test-seam")]
788+ #[test]
789+ fn seam_cookie_reads_back() {
790+ let config = Config {
791+ issuer: "http://im.test".into(),
792+ client_id: "client-1".into(),
793+ client_secret: "secret".into(),
794+ redirect_uri: "http://app.test/auth/callback".into(),
795+ cookie_name: "in_session".into(),
796+ cookie_key: [7u8; 32],
797+ };
798+ assert_eq!(introspect_path(), "/introspect");
799+ let exp = OffsetDateTime::now_utc() + time::Duration::hours(1);
800+ let sealed = mint_session_cookie(&config, "opaque-token", exp);
801+ let back: Session = open_json(&config.cookie_key, &sealed).unwrap();
802+ assert_eq!(back.app_session, "opaque-token");
803+ assert_eq!(back.exp, exp.unix_timestamp());
804+ }
805+ // -- review regressions -------------------------------------------------
806+ //
807+ // Strict `next` (CRLF injection + backslash), a `Location` that cannot
808+ // panic, and a `current_user` that only clears the cookie on an explicit
809+ // `active:false`.
810+
811+ #[test]
812+ fn next_allows_plain_local_paths() {
813+ assert_eq!(safe_next("/"), "/");
814+ assert_eq!(safe_next("/drive/folder/a"), "/drive/folder/a");
815+ assert_eq!(safe_next("/?auth_error=exchange_failed"), "/?auth_error=exchange_failed");
816+ }
817+
818+ #[test]
819+ fn login_next_with_crlf_injection_is_neutralized() {
820+ // The login half of the repro: the query arrives percent-encoded,
821+ // `query_value` decodes it, `safe_next` judges the decoded bytes.
822+ let decoded = query_value("next=/%0d%0aX-evil:1", "next").unwrap();
823+ assert_eq!(decoded, "/\r\nX-evil:1");
824+ assert_eq!(safe_next(&decoded), "/");
825+ assert_eq!(safe_next("/\r\nX-evil:1"), "/");
826+ assert_eq!(safe_next("/ok\r/evil"), "/");
827+ assert_eq!(safe_next("/tab\there"), "/");
828+ }
829+
830+ #[test]
831+ fn next_rejects_backslash_paths() {
832+ // Browsers normalize `\` to `/` in `Location`, so a backslash-led
833+ // path is an open redirect wearing a local costume.
834+ assert_eq!(safe_next("/\\evil"), "/");
835+ assert_eq!(safe_next("/drive/\\evil"), "/");
836+ assert_eq!(safe_next("\\evil"), "/");
837+ assert_eq!(safe_next("//evil.example"), "/");
838+ assert_eq!(safe_next("https://evil.example/"), "/");
839+ assert_eq!(safe_next(""), "/");
840+ }
841+
842+ #[test]
843+ fn location_value_falls_back_to_root() {
844+ // `HeaderValue` refuses the injected bytes; the redirect must land
845+ // on `/` rather than panic its handler.
846+ assert!(HeaderValue::from_str("/\r\nX-evil:1").is_err());
847+ assert_eq!(location_value("/\r\nX-evil:1"), HeaderValue::from_static("/"));
848+ assert_eq!(
849+ location_value("/drive"),
850+ HeaderValue::from_str("/drive").unwrap()
851+ );
852+ }
853+
854+ #[route(GET "/whoami")]
855+ async fn whoami(cx: &Cx) -> Result<Response, topcoat::Error> {
856+ match current_user(cx).await {
857+ Some(user) => user.email.into_response(cx),
858+ None => "anon".into_response(cx),
859+ }
860+ }
861+
862+ fn test_config(issuer: String) -> Config {
863+ Config {
864+ issuer,
865+ client_id: "client-1".into(),
866+ client_secret: "s3cr3t".into(),
867+ redirect_uri: "http://app.test/auth/callback".into(),
868+ cookie_name: "in_session".into(),
869+ cookie_key: [7u8; 32],
870+ }
871+ }
872+
873+ fn test_router(config: Config) -> Router {
874+ mount(Router::builder(), config)
875+ .discover_routes()
876+ .cookies()
877+ .build()
878+ }
879+
880+ fn get(uri: &str, cookie: Option<&str>) -> http::Request<Body> {
881+ let mut builder = http::Request::builder().method("GET").uri(uri);
882+ if let Some(cookie) = cookie {
883+ builder = builder.header(http::header::COOKIE, cookie);
884+ }
885+ builder.body(Body::empty()).unwrap()
886+ }
887+
888+ struct TestResponse {
889+ status: http::StatusCode,
890+ location: Option<String>,
891+ set_cookies: Vec<String>,
892+ body: Vec<u8>,
893+ }
894+
895+ impl TestResponse {
896+ async fn of(response: Response) -> Self {
897+ let status = response.status();
898+ let headers = response.headers().clone();
899+ let location = headers
900+ .get(http::header::LOCATION)
901+ .and_then(|v| v.to_str().ok())
902+ .map(str::to_string);
903+ let set_cookies = headers
904+ .get_all(http::header::SET_COOKIE)
905+ .iter()
906+ .filter_map(|v| v.to_str().ok().map(str::to_string))
907+ .collect();
908+ let body = to_bytes(response.into_body(), usize::MAX)
909+ .await
910+ .unwrap()
911+ .to_vec();
912+ Self {
913+ status,
914+ location,
915+ set_cookies,
916+ body,
917+ }
918+ }
919+
920+ fn text(&self) -> &str {
921+ std::str::from_utf8(&self.body).unwrap()
922+ }
923+
924+ /// The session cookie was cleared iff a `Set-Cookie` names it —
925+ /// the test routes set no cookies of their own.
926+ fn clears_session(&self) -> bool {
927+ self.set_cookies
928+ .iter()
929+ .any(|c| c.starts_with("in_session="))
930+ }
931+ }
932+
933+ fn session_cookie(token: &str) -> String {
934+ let session = Session {
935+ app_session: token.into(),
936+ exp: OffsetDateTime::now_utc().unix_timestamp() + 3600,
937+ };
938+ format!("in_session={}", seal_json(&[7u8; 32], &session))
939+ }
940+
941+ /// Canned bodies served per path over plain HTTP/1.1 with keep-alive,
942+ /// behind locks so the test learns the URL first and fills them after.
943+ /// Raw strings, so a test can answer garbage on purpose.
944+ #[derive(Clone, Default)]
945+ struct CannedIm {
946+ token: Arc<OnceLock<String>>,
947+ jwks: Arc<OnceLock<String>>,
948+ introspect: Arc<OnceLock<String>>,
949+ }
950+
951+ struct FakeIm {
952+ addr: std::net::SocketAddr,
953+ }
954+
955+ impl FakeIm {
956+ async fn spawn(canned: CannedIm) -> Self {
957+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
958+ let addr = listener.local_addr().unwrap();
959+ tokio::spawn(async move {
960+ loop {
961+ let Ok((socket, _)) = listener.accept().await else {
962+ return;
963+ };
964+ let canned = canned.clone();
965+ tokio::spawn(async move {
966+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
967+ let mut socket = socket;
968+ let mut buf = vec![0u8; 8192];
969+ let mut req = Vec::new();
970+ loop {
971+ let body_start = loop {
972+ let Ok(n) = socket.read(&mut buf).await else {
973+ return;
974+ };
975+ if n == 0 {
976+ return;
977+ }
978+ req.extend_from_slice(&buf[..n]);
979+ if let Some(end) = headers_end(&req) {
980+ let head =
981+ String::from_utf8_lossy(&req[..end]).to_string();
982+ let len = content_length(&head);
983+ if req.len() >= end + len {
984+ break end;
985+ }
986+ }
987+ if req.len() > 1_000_000 {
988+ return;
989+ }
990+ };
991+ let head =
992+ String::from_utf8_lossy(&req[..body_start]).to_string();
993+ let first = head.lines().next().unwrap_or("").to_string();
994+ let len = content_length(&head);
995+ req.drain(..body_start + len);
996+ let payload = if first.starts_with("POST /token ") {
997+ canned.token.get().cloned().unwrap_or_default()
998+ } else if first.starts_with("GET /jwks.json ") {
999+ canned.jwks.get().cloned().unwrap_or_default()
1000+ } else {
1001+ canned.introspect.get().cloned().unwrap_or_default()
1002+ };
1003+ let response = format!(
1004+ "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: keep-alive\r\n\r\n",
1005+ payload.len()
1006+ );
1007+ if socket.write_all(response.as_bytes()).await.is_err() {
1008+ return;
1009+ }
1010+ if socket.write_all(payload.as_bytes()).await.is_err() {
1011+ return;
1012+ }
1013+ }
1014+ });
1015+ }
1016+ });
1017+ Self { addr }
1018+ }
1019+
1020+ fn url(&self) -> String {
1021+ format!("http://{}", self.addr)
1022+ }
1023+ }
1024+
1025+ fn headers_end(req: &[u8]) -> Option<usize> {
1026+ req.windows(4)
1027+ .position(|w| w == b"\r\n\r\n")
1028+ .map(|pos| pos + 4)
1029+ }
1030+
1031+ fn content_length(head: &str) -> usize {
1032+ head.lines()
1033+ .find_map(|line| {
1034+ let (name, value) = line.split_once(':')?;
1035+ name.trim()
1036+ .eq_ignore_ascii_case("content-length")
1037+ .then(|| value.trim().parse().unwrap_or(0))
1038+ })
1039+ .unwrap_or(0)
1040+ }
1041+
1042+ fn jwk_of(public: &rsa::RsaPublicKey, kid: &str) -> serde_json::Value {
1043+ serde_json::json!({
1044+ "kty": "RSA",
1045+ "kid": kid,
1046+ "n": b64url.encode(public.n().to_bytes_be()),
1047+ "e": b64url.encode(public.e().to_bytes_be()),
1048+ })
1049+ }
1050+
1051+ /// The named repro end to end: `GET /auth/login?next=/%0d%0aX-evil:1`,
1052+ /// then a completed callback. Pre-fix the sealed `next` carried the CR
1053+ /// LF into `see()` and the callback died (500 via the panic boundary);
1054+ /// now the browser lands on `/`.
1055+ #[tokio::test]
1056+ async fn login_then_callback_with_injected_next_lands_on_root() {
1057+ let (private, public) = keypair();
1058+ // Login touches no im endpoint, so any issuer will do; the flight
1059+ // cookie below is opened with the test-known key.
1060+ let login_router = test_router(test_config("http://im.test".into()));
1061+ let login = TestResponse::of(
1062+ login_router
1063+ .handle(get("/auth/login?next=/%0d%0aX-evil:1", None))
1064+ .await,
1065+ )
1066+ .await;
1067+ assert_eq!(login.status, http::StatusCode::SEE_OTHER);
1068+ let sealed = login
1069+ .set_cookies
1070+ .iter()
1071+ .find(|c| c.starts_with("in_session_pkce="))
1072+ .expect("login sets the flight cookie");
1073+ let sealed = sealed["in_session_pkce=".len()..]
1074+ .split(';')
1075+ .next()
1076+ .unwrap();
1077+ let flight: InFlight = open_json(&[7u8; 32], sealed).unwrap();
1078+ // Neutralized at login: the hostile bytes never reach the seal.
1079+ assert_eq!(flight.next, "/");
1080+
1081+ // Now complete the dance against a fake im.
1082+ let canned = CannedIm::default();
1083+ let fake = FakeIm::spawn(canned.clone()).await;
1084+ let now = OffsetDateTime::now_utc().unix_timestamp();
1085+ let id_token = sign(
1086+ serde_json::json!({
1087+ "iss": fake.url(),
1088+ "sub": "user-1",
1089+ "aud": "client-1",
1090+ "exp": now + 600,
1091+ "iat": now,
1092+ "nonce": flight.nonce,
1093+ }),
1094+ &private,
1095+ );
1096+ let _ = canned
1097+ .jwks
1098+ .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string());
1099+ let _ = canned
1100+ .token
1101+ .set(serde_json::json!({
1102+ "id_token": id_token,
1103+ "app_session": "tok-1",
1104+ })
1105+ .to_string());
1106+ let _ = canned
1107+ .introspect
1108+ .set(serde_json::json!({
1109+ "active": true,
1110+ "sub": "user-1",
1111+ "email": "ann@example.com",
1112+ "name": "Ann",
1113+ "exp": now + 3600,
1114+ })
1115+ .to_string());
1116+
1117+ let router = test_router(test_config(fake.url()));
1118+ let callback = TestResponse::of(
1119+ router
1120+ .handle(get(
1121+ &format!("/auth/callback?code=code-1&state={}", flight.state),
1122+ Some(&format!("in_session_pkce={sealed}")),
1123+ ))
1124+ .await,
1125+ )
1126+ .await;
1127+ assert_eq!(callback.status, http::StatusCode::SEE_OTHER);
1128+ assert_eq!(callback.location.as_deref(), Some("/"));
1129+ }
1130+
1131+ /// A flight cookie sealed before the strict rules (hand-sealed hostile
1132+ /// here): the callback re-validates before rendering the header, so
1133+ /// even this lands on `/` instead of panicking.
1134+ #[tokio::test]
1135+ async fn callback_with_hostile_stored_next_lands_on_root() {
1136+ let (private, public) = keypair();
1137+ let canned = CannedIm::default();
1138+ let fake = FakeIm::spawn(canned.clone()).await;
1139+ let now = OffsetDateTime::now_utc().unix_timestamp();
1140+ let flight = InFlight {
1141+ verifier: "verifier".into(),
1142+ state: "state-1".into(),
1143+ nonce: "nonce-1".into(),
1144+ next: "/\r\nX-evil:1".into(),
1145+ exp: now + 600,
1146+ };
1147+ let sealed = seal_json(&[7u8; 32], &flight);
1148+ let id_token = sign(
1149+ serde_json::json!({
1150+ "iss": fake.url(),
1151+ "sub": "user-1",
1152+ "aud": "client-1",
1153+ "exp": now + 600,
1154+ "iat": now,
1155+ "nonce": "nonce-1",
1156+ }),
1157+ &private,
1158+ );
1159+ let _ = canned
1160+ .jwks
1161+ .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string());
1162+ let _ = canned
1163+ .token
1164+ .set(serde_json::json!({
1165+ "id_token": id_token,
1166+ "app_session": "tok-1",
1167+ })
1168+ .to_string());
1169+ let _ = canned
1170+ .introspect
1171+ .set(serde_json::json!({
1172+ "active": true,
1173+ "sub": "user-1",
1174+ "email": "ann@example.com",
1175+ "name": "Ann",
1176+ "exp": now + 3600,
1177+ })
1178+ .to_string());
1179+
1180+ let router = test_router(test_config(fake.url()));
1181+ let callback = TestResponse::of(
1182+ router
1183+ .handle(get(
1184+ "/auth/callback?code=code-1&state=state-1",
1185+ Some(&format!("in_session_pkce={sealed}")),
1186+ ))
1187+ .await,
1188+ )
1189+ .await;
1190+ assert_eq!(callback.status, http::StatusCode::SEE_OTHER);
1191+ assert_eq!(callback.location.as_deref(), Some("/"));
1192+ }
1193+
1194+ #[tokio::test]
1195+ async fn current_user_keeps_cookie_when_im_is_blackholed() {
1196+ // Nothing listens: the POST fails, the request reads as signed-out,
1197+ // and the cookie survives for the next try.
1198+ let probe = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1199+ let port = probe.local_addr().unwrap().port();
1200+ drop(probe);
1201+ let router = test_router(test_config(format!("http://127.0.0.1:{port}")));
1202+ let res = TestResponse::of(
1203+ router
1204+ .handle(get("/whoami", Some(&session_cookie("tok-1"))))
1205+ .await,
1206+ )
1207+ .await;
1208+ assert_eq!(res.text(), "anon");
1209+ assert!(
1210+ !res.clears_session(),
1211+ "a blackholed introspection must not clear the cookie: {:?}",
1212+ res.set_cookies
1213+ );
1214+ }
1215+
1216+ #[tokio::test]
1217+ async fn current_user_keeps_cookie_on_unparseable_introspection() {
1218+ let canned = CannedIm::default();
1219+ let _ = canned.introspect.set("not-json{{{".into());
1220+ let fake = FakeIm::spawn(canned).await;
1221+ let router = test_router(test_config(fake.url()));
1222+ let res = TestResponse::of(
1223+ router
1224+ .handle(get("/whoami", Some(&session_cookie("tok-1"))))
1225+ .await,
1226+ )
1227+ .await;
1228+ assert_eq!(res.text(), "anon");
1229+ assert!(
1230+ !res.clears_session(),
1231+ "an unparseable introspection must not clear the cookie: {:?}",
1232+ res.set_cookies
1233+ );
1234+ }
1235+
1236+ #[tokio::test]
1237+ async fn current_user_keeps_cookie_when_active_is_missing() {
1238+ // A malformed answer is not a revocation.
1239+ let canned = CannedIm::default();
1240+ let _ = canned
1241+ .introspect
1242+ .set(serde_json::json!({"sub": "user-1"}).to_string());
1243+ let fake = FakeIm::spawn(canned).await;
1244+ let router = test_router(test_config(fake.url()));
1245+ let res = TestResponse::of(
1246+ router
1247+ .handle(get("/whoami", Some(&session_cookie("tok-1"))))
1248+ .await,
1249+ )
1250+ .await;
1251+ assert_eq!(res.text(), "anon");
1252+ assert!(
1253+ !res.clears_session(),
1254+ "an answer without `active` must not clear the cookie: {:?}",
1255+ res.set_cookies
1256+ );
1257+ }
1258+
1259+ #[tokio::test]
1260+ async fn current_user_clears_cookie_when_session_revoked() {
1261+ let canned = CannedIm::default();
1262+ let _ = canned
1263+ .introspect
1264+ .set(serde_json::json!({"active": false}).to_string());
1265+ let fake = FakeIm::spawn(canned).await;
1266+ let router = test_router(test_config(fake.url()));
1267+ let res = TestResponse::of(
1268+ router
1269+ .handle(get("/whoami", Some(&session_cookie("tok-1"))))
1270+ .await,
1271+ )
1272+ .await;
1273+ assert_eq!(res.text(), "anon");
1274+ assert!(
1275+ res.clears_session(),
1276+ "an `active:false` answer must clear the cookie: {:?}",
1277+ res.set_cookies
1278+ );
1279+ }
1280+
1281+ #[tokio::test]
1282+ async fn current_user_serves_the_introspected_user() {
1283+ let now = OffsetDateTime::now_utc().unix_timestamp();
1284+ let canned = CannedIm::default();
1285+ let _ = canned
1286+ .introspect
1287+ .set(serde_json::json!({
1288+ "active": true,
1289+ "sub": "user-1",
1290+ "email": "ann@example.com",
1291+ "name": "Ann",
1292+ "exp": now + 3600,
1293+ })
1294+ .to_string());
1295+ let fake = FakeIm::spawn(canned).await;
1296+ let router = test_router(test_config(fake.url()));
1297+ let res = TestResponse::of(
1298+ router
1299+ .handle(get("/whoami", Some(&session_cookie("tok-1"))))
1300+ .await,
1301+ )
1302+ .await;
1303+ assert_eq!(res.text(), "ann@example.com");
1304+ assert!(
1305+ !res.clears_session(),
1306+ "a live session must not clear the cookie: {:?}",
1307+ res.set_cookies
1308+ );
1309+ }
1310+}
crates/in-core/Cargo.tomladded+49 -0
@@ -0,0 +1,49 @@
1+[package]
2+name = "in-core"
3+version.workspace = true
4+edition.workspace = true
5+license.workspace = true
6+repository.workspace = true
7+description = "Domain model and storage for In"
8+
9+[features]
10+# The domain vocabulary (record shapes) compiles anywhere, including the wasm
11+# bundle. Everything that touches a database, a secret or a CSPRNG lives
12+# behind `server` so none of it is shipped to the browser.
13+default = ["server"]
14+server = [
15+ "dep:async-trait",
16+ "dep:base64",
17+ "dep:chacha20poly1305",
18+ "dep:image",
19+ "dep:rand",
20+ "dep:sha2",
21+ "dep:subtle",
22+ "dep:tokio",
23+ "dep:turso",
24+ "dep:ulid",
25+]
26+
27+[dependencies]
28+async-trait = { version = "0.1.92", optional = true }
29+base64 = { workspace = true, optional = true }
30+chacha20poly1305 = { workspace = true, optional = true }
31+image = { workspace = true, optional = true }
32+rand = { workspace = true, optional = true }
33+sha2 = { workspace = true, optional = true }
34+subtle = { workspace = true, optional = true }
35+serde.workspace = true
36+serde_json.workspace = true
37+thiserror.workspace = true
38+time.workspace = true
39+toml.workspace = true
40+tokio = { workspace = true, optional = true }
41+turso = { workspace = true, optional = true }
42+ulid = { workspace = true, optional = true }
43+
44+[dev-dependencies]
45+async-trait = "0.1.92"
46+serde_json.workspace = true
47+tokio = { workspace = true }
48+tempfile = "3"
49+zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
crates/in-core/migrations/0001_init.sqladded+135 -0
@@ -0,0 +1,135 @@
1+-- In's schema, whole, in one file.
2+--
3+-- One plain SQL file, applied at boot to an empty database: Turso has no
4+-- migration runner of its own, and keeping the schema as SQL is what makes
5+-- the store trait swappable.
6+-- Timestamps are RFC 3339 text in UTC. Ids are ULIDs as text — sortable by
7+-- creation.
8+--
9+-- This file is the first migration, not the whole schema any more. Everything
10+-- after it is a numbered `0002_*.sql` beside it, and an empty database is
11+-- built by applying them in order. A live database is brought up by
12+-- `in reconcile`, not by re-running the files, so a change to a table lands
13+-- in three places — the newest migration, this file's table, and that tool's
14+-- copy map.
15+
16+-- An account. There is no password column on purpose: sign-in is the OIDC
17+-- provider's business, and this database never sees a secret worth stealing.
18+-- `oidc_sub` is the provider's stable subject for the person; the row is
19+-- created on first sight of a sub (JIT provisioning) and refreshed on every
20+-- sight after. The first row ever provisioned is the admin.
21+--
22+-- `quota_bytes` is the person's ceiling, `used_bytes` the running total of
23+-- every live AND trashed byte they hold — trash counts, because a file that
24+-- can be restored is a file that still costs. `used_bytes` is recomputed
25+-- from the rows after every mutation, never blindly incremented, so a crash
26+-- between two writes cannot drift it from the truth.
27+CREATE TABLE user (
28+ id TEXT PRIMARY KEY,
29+ oidc_sub TEXT NOT NULL,
30+ email TEXT NOT NULL,
31+ display_name TEXT NOT NULL,
32+ admin INTEGER NOT NULL DEFAULT 0,
33+ disabled INTEGER NOT NULL DEFAULT 0,
34+ quota_bytes INTEGER NOT NULL,
35+ used_bytes INTEGER NOT NULL DEFAULT 0,
36+ created_at TEXT NOT NULL,
37+ last_seen_at TEXT
38+);
39+CREATE UNIQUE INDEX user_oidc_sub ON user(oidc_sub);
40+
41+-- A folder. `parent_id` NULL is the person's root: everything an account
42+-- holds hangs, directly or not, under nothing. Names are unique among live
43+-- siblings — two folders called the same thing in one place is one folder
44+-- spelled twice — and trashed rows do not count, so deleting a name frees it.
45+--
46+-- Trash is `deleted_at`: a folder trash stamps the folder, every descendant
47+-- folder and every file under them with the same timestamp, in one
48+-- transaction. The bytes stay on disk until a purge takes the rows.
49+CREATE TABLE folder (
50+ id TEXT PRIMARY KEY,
51+ owner_id TEXT NOT NULL REFERENCES user(id),
52+ parent_id TEXT REFERENCES folder(id),
53+ name TEXT NOT NULL,
54+ created_at TEXT NOT NULL,
55+ deleted_at TEXT
56+);
57+CREATE INDEX folder_by_parent ON folder(owner_id, parent_id);
58+
59+-- A file. The bytes are deliberately not on this type: they sit at
60+-- `<storage>/files/<id>`, named by the row's own id, and a thumbnail — when
61+-- the bytes are an image — at `<storage>/thumbs/<id>`. The directory is state
62+-- the same way the database file is — back the two up together, and boot
63+-- deletes any file no row names. And a name is still exactly where an
64+-- uploaded file name must never end up: `../../etc` is a valid file name and
65+-- a terrible path, so `name` remains a label printed on a row; the file a row
66+-- names is found by its id alone, never resolved from anything the row was
67+-- given.
68+--
69+-- `mime` is what the server decided the bytes are, never what the upload
70+-- claimed. `thumb_state` is `none` for bytes no thumbnail is attempted for,
71+-- `pending` while one is being made, and `ready` or `failed` once it is.
72+CREATE TABLE file (
73+ id TEXT PRIMARY KEY,
74+ owner_id TEXT NOT NULL REFERENCES user(id),
75+ folder_id TEXT REFERENCES folder(id),
76+ name TEXT NOT NULL,
77+ mime TEXT NOT NULL,
78+ size_bytes INTEGER NOT NULL,
79+ thumb_state TEXT NOT NULL DEFAULT 'none',
80+ created_at TEXT NOT NULL,
81+ updated_at TEXT NOT NULL,
82+ deleted_at TEXT
83+);
84+CREATE INDEX file_by_folder ON file(owner_id, folder_id);
85+
86+-- A public share link. Only the hash is stored: the plaintext token is shown
87+-- once when the link is created, and anyone who holds it reads through it.
88+-- `kind` names which table `target_id` points at — `file` or `folder` — and
89+-- `expires_at` / `revoked_at` end the link without deleting the row, so a
90+-- dead link stays distinguishable from a wrong token.
91+CREATE TABLE share_link (
92+ id TEXT PRIMARY KEY,
93+ token_hash TEXT NOT NULL,
94+ kind TEXT NOT NULL,
95+ target_id TEXT NOT NULL,
96+ created_by TEXT NOT NULL REFERENCES user(id),
97+ can_download INTEGER NOT NULL DEFAULT 1,
98+ created_at TEXT NOT NULL,
99+ expires_at TEXT,
100+ revoked_at TEXT
101+);
102+CREATE UNIQUE INDEX share_link_token ON share_link(token_hash);
103+
104+-- A per-person share: `user_id` may see one file or folder of somebody
105+-- else's. `kind` names which table `target_id` points at, as on `share_link`.
106+-- The row is the whole of the permission — no role, no hierarchy — so
107+-- removing it unshares completely.
108+CREATE TABLE share_user (
109+ kind TEXT NOT NULL,
110+ target_id TEXT NOT NULL,
111+ user_id TEXT NOT NULL REFERENCES user(id),
112+ can_download INTEGER NOT NULL DEFAULT 1,
113+ created_at TEXT NOT NULL,
114+ PRIMARY KEY (kind, target_id, user_id)
115+);
116+
117+-- A chunked upload on its way in. Chunks land at
118+-- `<storage>/uploads/<id>/<n>`, staged until the finish assembles them in
119+-- order, sniffs what they are, and moves the result to its file row. A
120+-- session whose `expires_at` passes is aborted and its chunks deleted — by
121+-- the boot sweep, and by anyone who asks — so an abandoned upload cannot pin
122+-- disk forever. `state` is `active`, `done` or `aborted`: a finished or
123+-- aborted session keeps its row as the record of what happened.
124+CREATE TABLE upload_session (
125+ id TEXT PRIMARY KEY,
126+ owner_id TEXT NOT NULL REFERENCES user(id),
127+ folder_id TEXT REFERENCES folder(id),
128+ name TEXT NOT NULL,
129+ size_bytes INTEGER NOT NULL,
130+ chunk_size INTEGER NOT NULL,
131+ received_bytes INTEGER NOT NULL DEFAULT 0,
132+ state TEXT NOT NULL DEFAULT 'active',
133+ created_at TEXT NOT NULL,
134+ expires_at TEXT NOT NULL
135+);
crates/in-core/src/config.rsadded+746 -0
@@ -0,0 +1,746 @@
1+//! Everything In reads from `config/in.toml`, in one place.
2+//!
3+//! Nothing here has a silent default once the file exists. A key that is
4+//! missing, empty or unusable stops the boot and says which key and which
5+//! file, because the alternative is worse than not starting: a wrong
6+//! `database` does not mean "no data", it means a second In quietly
7+//! writing a different file while everyone believes they are looking at the
8+//! same drive — and Turso is single-writer, so the two are not even
9+//! reconcilable afterwards.
10+//!
11+//! Development still needs to be one command, so the *absence* of
12+//! `config/in.toml` is the opt-in that takes the development defaults: the
13+//! app writes the file itself, with those defaults in it and comments saying
14+//! what each key does, and then stops — the `[oidc]` keys have no default
15+//! worth guessing, so the first boot writes the file and says which keys to
16+//! fill in rather than starting half-authenticated. That is opt-in on purpose
17+//! too — it only ever happens once, because the second boot finds the file
18+//! it wrote the first time and reads it like any other. A real deployment is
19+//! handed the same file and edits it; it never writes itself over a
20+//! deployment's choices, because it only writes when the file is not there
21+//! at all.
22+//!
23+//! Whatever is finally resolved is printed once at startup — the database
24+//! path absolute, the address bound, the issuer sign-ins go to — so "which
25+//! file are we on" is answered by the log rather than by someone's memory.
26+//!
27+//! The file is kept complete: a top-level key it does not mention is added,
28+//! with its comment and the default already in effect, so reading the file
29+//! is the way to learn what can be changed. `redirect_uri` is the one
30+//! exception: it defaults from `listen` on every boot, and freezing the
31+//! derived value into the file would desync it the day `listen` moves. A key
32+//! nobody here knows is named in the startup report rather than obeyed or
33+//! refused — a typo should be visible without being a boot failure, and a key
34+//! this file has stopped honouring must never half-configure anything.
35+
36+use serde::Deserialize;
37+use std::fmt;
38+use std::net::SocketAddr;
39+use std::path::{Path, PathBuf};
40+
41+/// The path, relative to the working directory, of the file `Config::load`
42+/// reads and, failing that, writes.
43+const FILE_NAME: &str = "config/in.toml";
44+
45+/// What a freshly written `config/in.toml` says, comments included.
46+/// Development defaults, except for `[oidc]`: no issuer, id or secret has a
47+/// default worth guessing, so the file is written with blanks and the boot
48+/// stops until they are filled in.
49+const DEVELOPMENT_DEFAULTS: &str = r#"# Where the one database file lives. One process holds it.
50+database = "in.db"
51+# The address the server listens on. Environment variables are ignored —
52+# this is the only thing that decides where In binds.
53+listen = "127.0.0.1:7655"
54+# How long a live-update connection is held before the browser is asked to
55+# reconnect, in seconds. The reconnect is what re-checks the session, so a
56+# revoked sign-in stops receiving within this long.
57+live_seconds = 300
58+# How many days a trashed file or folder waits before the boot sweep purges
59+# it for good. Trash counts toward quota until then.
60+purge_after_days = 30
61+# The quota a newly provisioned account starts on, in bytes. 10 GiB.
62+default_quota_bytes = 10737418240
63+# Where drive files, thumbnails and staged upload chunks live as files,
64+# created on boot. Not written here: it defaults to beside the database file,
65+# and the boot completes this file with the value it resolved.
66+[oidc]
67+# The provider that signs people in. Required: no default is guessed.
68+issuer = ""
69+# The client id In presents to the provider. Required.
70+client_id = ""
71+# The client secret In presents to the provider. Required. The file holds a
72+# live credential once this is filled in, so it is created mode 0600.
73+client_secret = ""
74+# Where the provider sends the browser back after sign-in. Not written here:
75+# it defaults from `listen` on every boot, so moving the address never leaves
76+# a stale callback behind. Set it only when the public address differs from
77+# the bind address (a proxy in front, for instance).
78+# redirect_uri = "http://127.0.0.1:7655/auth/callback"
79+"#;
80+
81+/// The default `listen` when the file is silent about it. A file missing this
82+/// key is completed with it on the next boot, so the silence lasts one run.
83+///
84+/// 7655 rather than a round number: 3000, 4000, 5000, 8000 and 8080 are what
85+/// every other thing on a developer's machine already took, and a first run
86+/// that dies on "address already in use" is a first run that teaches nothing.
87+const DEFAULT_LISTEN: &str = "127.0.0.1:7655";
88+
89+/// How long one live-update connection lasts before the server ends it and the
90+/// browser opens another. Five minutes is a compromise: a stream is
91+/// authenticated once, when it opens, so a session revoked mid-stream keeps
92+/// hearing until the next reconnect — and a reconnect costs one request, so
93+/// doing it every few seconds to shorten that window would be worse than the
94+/// window. Long enough to be cheap, short enough that a revoked session goes
95+/// quiet while the person who revoked it is still watching.
96+const DEFAULT_LIVE_SECONDS: u64 = 300;
97+
98+/// How many days trash waits before the boot sweep purges it for good.
99+const DEFAULT_PURGE_AFTER_DAYS: u32 = 30;
100+
101+/// The quota a newly provisioned account starts on: 10 GiB.
102+const DEFAULT_QUOTA_BYTES: u64 = 10 * 1024 * 1024 * 1024;
103+
104+/// Every completable top-level key, with the comment and default a file
105+/// missing it is completed with. `database` is not here: it has no default
106+/// worth guessing, so its absence stops the boot instead. `storage` is
107+/// neither: its default is derived from `database`, so its completed line is
108+/// built per-file rather than printed from a constant. `redirect_uri` is not
109+/// here either: it derives from `listen` on every boot (see the module docs).
110+const OPTIONAL_KEYS: &[(&str, &str)] = &[
111+ (
112+ "listen",
113+ concat!(
114+ "# The address the server listens on. Environment variables are ignored —\n",
115+ "# this is the only thing that decides where In binds.\n",
116+ "listen = \"127.0.0.1:7655\"\n"
117+ ),
118+ ),
119+ (
120+ "live_seconds",
121+ concat!(
122+ "# How long a live-update connection is held before the browser is asked to\n",
123+ "# reconnect, in seconds. The reconnect is what re-checks the session, so a\n",
124+ "# revoked sign-in stops receiving within this long.\n",
125+ "live_seconds = 300\n"
126+ ),
127+ ),
128+ (
129+ "purge_after_days",
130+ concat!(
131+ "# How many days a trashed file or folder waits before the boot sweep purges\n",
132+ "# it for good. Trash counts toward quota until then.\n",
133+ "purge_after_days = 30\n"
134+ ),
135+ ),
136+ (
137+ "default_quota_bytes",
138+ concat!(
139+ "# The quota a newly provisioned account starts on, in bytes. 10 GiB.\n",
140+ "default_quota_bytes = 10737418240\n"
141+ ),
142+ ),
143+];
144+
145+/// The `[oidc]` table of `config/in.toml`, before the values are checked.
146+/// Anything else the section says lands in `other`, which is read for its key
147+/// names only.
148+#[derive(Deserialize)]
149+struct OidcToml {
150+ issuer: Option<String>,
151+ client_id: Option<String>,
152+ client_secret: Option<String>,
153+ redirect_uri: Option<String>,
154+ #[serde(flatten, default)]
155+ other: std::collections::BTreeMap<String, toml::Value>,
156+}
157+
158+/// The shape of `config/in.toml`, before the values are checked. Anything
159+/// else the file says lands in `other`, which is read for its key names only
160+/// — enough for the report to say a key was seen and not obeyed.
161+#[derive(Deserialize)]
162+struct Toml {
163+ database: Option<String>,
164+ storage: Option<String>,
165+ listen: Option<String>,
166+ live_seconds: Option<u64>,
167+ purge_after_days: Option<u32>,
168+ default_quota_bytes: Option<u64>,
169+ oidc: Option<OidcToml>,
170+ #[serde(flatten)]
171+ other: std::collections::BTreeMap<String, toml::Value>,
172+}
173+
174+/// The OIDC provider In trusts, and how In presents itself to it.
175+#[derive(Clone, Debug, PartialEq, Eq)]
176+pub struct OidcConfig {
177+ /// The provider's issuer URL. Sign-ins from anywhere else are refused.
178+ pub issuer: String,
179+ /// The client id In presents to the provider.
180+ pub client_id: String,
181+ /// The client secret In presents to the provider. Never printed.
182+ pub client_secret: String,
183+ /// Where the provider sends the browser after sign-in. Defaults from
184+ /// `listen` when the file is silent about it.
185+ pub redirect_uri: String,
186+}
187+
188+/// What the process needs to know before it opens a socket.
189+#[derive(Clone, Debug, PartialEq, Eq)]
190+pub struct Config {
191+ /// The database file, absolute, as a string — the form
192+ /// [`crate::store::TursoStore::open`] takes.
193+ pub database: String,
194+ /// Where drive files, thumbnails and staged upload chunks live as files,
195+ /// absolute. Bytes never sit in the database: this directory and the
196+ /// database file are backed up together, or not at all.
197+ pub storage: PathBuf,
198+ /// The address the server binds. The only source for this — `HOST` and
199+ /// `PORT` environment variables are never read.
200+ pub listen: SocketAddr,
201+ /// How long one live-update connection is held open before the browser is
202+ /// asked to reconnect. The reconnect re-authenticates, which is how a
203+ /// session revoked mid-stream stops being fed.
204+ pub live_seconds: u64,
205+ /// How many days trash waits before the boot sweep purges it for good.
206+ pub purge_after_days: u32,
207+ /// The quota a newly provisioned account starts on, in bytes.
208+ pub default_quota_bytes: u64,
209+ /// The OIDC provider In trusts.
210+ pub oidc: OidcConfig,
211+ /// Keys the file sets that nothing here reads, in the order the file
212+ /// gives them. Named at startup so a typo is visible.
213+ pub ignored: Vec<String>,
214+ /// Whether `config/in.toml` did not exist and was just written with the
215+ /// development defaults this boot.
216+ pub defaulted: bool,
217+}
218+
219+/// Why the process is not starting.
220+#[derive(Clone, Debug, PartialEq, Eq)]
221+pub enum ConfigError {
222+ /// The file exists but is not valid TOML.
223+ Unparseable { why: String },
224+ /// A key is missing or set to an empty value.
225+ Missing(&'static str),
226+ /// A key is set to something the app cannot use.
227+ Invalid { key: &'static str, why: String },
228+ /// The file could not be read for a reason other than "it is not there"
229+ /// (permissions, for instance), or the default could not be written.
230+ Io(String),
231+}
232+
233+impl fmt::Display for ConfigError {
234+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235+ match self {
236+ ConfigError::Unparseable { why } => {
237+ write!(f, "not starting: {FILE_NAME} is not valid TOML — {why}")
238+ }
239+ ConfigError::Missing(key) => {
240+ write!(
241+ f,
242+ "not starting: {FILE_NAME} has no {key}. Add it, or delete {FILE_NAME} to take the development defaults."
243+ )
244+ }
245+ ConfigError::Invalid { key, why } => {
246+ write!(
247+ f,
248+ "not starting: {FILE_NAME}'s {key} is set to something unusable — {why}"
249+ )
250+ }
251+ ConfigError::Io(why) => write!(f, "not starting: {why}"),
252+ }
253+ }
254+}
255+
256+impl std::error::Error for ConfigError {}
257+
258+impl Config {
259+ /// Reads `config/in.toml` from the current directory, writing it with
260+ /// the development defaults first if it is not there.
261+ pub fn load() -> Result<Config, ConfigError> {
262+ Config::load_from(Path::new("."))
263+ }
264+
265+ /// The same reading, against any directory — which is how it is tested
266+ /// without a test being able to disturb another test's working
267+ /// directory, or another test's `config/in.toml`.
268+ pub fn load_from(dir: &Path) -> Result<Config, ConfigError> {
269+ let path = dir.join(FILE_NAME);
270+ match std::fs::read_to_string(&path) {
271+ Ok(text) => {
272+ let config = Config::parse(&text, dir, false)?;
273+ complete(&path, &text, dir);
274+ Ok(config)
275+ }
276+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
277+ if let Some(parent) = path.parent() {
278+ std::fs::create_dir_all(parent).map_err(|err| {
279+ ConfigError::Io(format!("could not create {}: {err}", parent.display()))
280+ })?;
281+ }
282+ std::fs::write(&path, DEVELOPMENT_DEFAULTS).map_err(|err| {
283+ ConfigError::Io(format!("could not write {}: {err}", path.display()))
284+ })?;
285+ // The file will hold a live client secret once the admin
286+ // fills it in; close it now, before it does.
287+ let _ = crate::store::secret::restrict(&path);
288+ println!(
289+ "in wrote {FILE_NAME} with development defaults — fill in [oidc] for a real deployment"
290+ );
291+ Config::parse(DEVELOPMENT_DEFAULTS, dir, true)
292+ }
293+ Err(err) => Err(ConfigError::Io(format!(
294+ "could not read {}: {err}",
295+ path.display()
296+ ))),
297+ }
298+ }
299+
300+ /// The reading itself, against a string — which is how it is tested
301+ /// without a test being able to disturb another test's filesystem.
302+ pub fn parse(text: &str, dir: &Path, defaulted: bool) -> Result<Config, ConfigError> {
303+ let toml: Toml = toml::from_str(text).map_err(|err| ConfigError::Unparseable {
304+ why: err.to_string(),
305+ })?;
306+
307+ let value = |raw: Option<String>| raw.filter(|value| !value.trim().is_empty());
308+
309+ let database = value(toml.database).ok_or(ConfigError::Missing("database"))?;
310+ let database_path = absolute(dir, Path::new(&database));
311+
312+ let storage = match value(toml.storage) {
313+ Some(raw) => absolute(dir, Path::new(&raw)),
314+ None => default_storage(&database_path),
315+ };
316+
317+ let listen = value(toml.listen).unwrap_or_else(|| DEFAULT_LISTEN.to_string());
318+ let listen: SocketAddr = listen.parse().map_err(|err| ConfigError::Invalid {
319+ key: "listen",
320+ why: format!("{listen:?} is not a host:port address — {err}"),
321+ })?;
322+
323+ // Zero would mean a stream that ends the moment it opens, which is a
324+ // reconnect loop rather than a live feed; the key is refused rather
325+ // than quietly corrected, because a deployment that meant to say
326+ // "never expire" should find out here and not at three in the morning.
327+ let live_seconds = toml.live_seconds.unwrap_or(DEFAULT_LIVE_SECONDS);
328+ if live_seconds == 0 {
329+ return Err(ConfigError::Invalid {
330+ key: "live_seconds",
331+ why: "0 would close every live connection as soon as it opened".to_string(),
332+ });
333+ }
334+
335+ let purge_after_days = toml.purge_after_days.unwrap_or(DEFAULT_PURGE_AFTER_DAYS);
336+ let default_quota_bytes = toml.default_quota_bytes.unwrap_or(DEFAULT_QUOTA_BYTES);
337+
338+ let oidc_toml = toml.oidc.ok_or(ConfigError::Missing("[oidc]"))?;
339+ let issuer = value(oidc_toml.issuer).ok_or(ConfigError::Missing("oidc.issuer"))?;
340+ let client_id = value(oidc_toml.client_id).ok_or(ConfigError::Missing("oidc.client_id"))?;
341+ let client_secret =
342+ value(oidc_toml.client_secret).ok_or(ConfigError::Missing("oidc.client_secret"))?;
343+ // Derived from the address bound, on every boot: a deployment behind
344+ // a proxy sets this key, and everyone else follows `listen` for free.
345+ let redirect_uri = value(oidc_toml.redirect_uri)
346+ .unwrap_or_else(|| format!("{}/auth/callback", listen_url_of(&listen)));
347+
348+ let mut ignored: Vec<String> = toml.other.into_keys().collect();
349+ ignored.extend(oidc_toml.other.into_keys().map(|key| format!("oidc.{key}")));
350+
351+ Ok(Config {
352+ database: database_path.display().to_string(),
353+ storage,
354+ listen,
355+ live_seconds,
356+ purge_after_days,
357+ default_quota_bytes,
358+ oidc: OidcConfig {
359+ issuer,
360+ client_id,
361+ client_secret,
362+ redirect_uri,
363+ },
364+ ignored,
365+ defaulted,
366+ })
367+ }
368+
369+ /// The address the server binds, as a URL.
370+ ///
371+ /// A bind that names no interface — `0.0.0.0`, `::` — answers everywhere
372+ /// and is reachable at none of it by name, so the loopback stands in: a
373+ /// link somebody on the box can click beats a link nobody can. Whoever
374+ /// puts In behind a proxy sets the real address where it is needed (and
375+ /// `redirect_uri` in `[oidc]`), which is the only thing this defers to.
376+ pub fn listen_url(&self) -> String {
377+ listen_url_of(&self.listen)
378+ }
379+
380+ /// The lines to print once at startup. Nothing secret is among them.
381+ pub fn report(&self) -> Vec<String> {
382+ let mut lines = vec![
383+ format!("database {}", self.database),
384+ format!("storage {}", self.storage.display()),
385+ format!("listen {}", self.listen),
386+ format!("oidc {}", self.oidc.issuer),
387+ ];
388+ if !self.ignored.is_empty() {
389+ lines.push(format!(
390+ "ignored {FILE_NAME} sets {}, which nothing reads",
391+ self.ignored.join(", ")
392+ ));
393+ }
394+ if self.defaulted {
395+ lines.push(format!(
396+ "dev {FILE_NAME} did not exist, development defaults written and taken"
397+ ));
398+ }
399+ lines
400+ }
401+}
402+
403+/// The address bound, as a URL — the shape `redirect_uri` defaults from.
404+fn listen_url_of(listen: &SocketAddr) -> String {
405+ let ip = listen.ip();
406+ let host = if ip.is_unspecified() {
407+ "127.0.0.1".to_string()
408+ } else if listen.is_ipv6() {
409+ format!("[{ip}]")
410+ } else {
411+ ip.to_string()
412+ };
413+ match listen.port() {
414+ 80 => format!("http://{host}"),
415+ port => format!("http://{host}:{port}"),
416+ }
417+}
418+
419+/// Adds the top-level keys the file does not mention, each with its own
420+/// comment and the default already in effect. The file is how a reader learns
421+/// what can be changed, so a key that is silently defaulted is a key nobody
422+/// discovers.
423+///
424+/// Only ever adds, never rewrites: whatever else the file says — comments,
425+/// ordering, a value somebody chose — is theirs. The additions go before the
426+/// first `[table]` header when there is one, because a key appended past one
427+/// would belong to that table rather than to the file. A file that cannot be
428+/// written is not a reason not to start; the defaults it is missing are the
429+/// ones already in force, so the run is correct either way and the note says
430+/// what could not be done.
431+fn complete(path: &Path, text: &str, base: &Path) {
432+ let mut missing: Vec<(&str, String)> = OPTIONAL_KEYS
433+ .iter()
434+ .filter(|(key, _)| !mentions(text, key))
435+ .map(|(key, block)| (*key, (*block).to_string()))
436+ .collect();
437+ // `storage` has no fixed default to print: a file silent about it derives
438+ // the directory from where `database` points, so the completed line says
439+ // the value this boot actually resolved rather than a placeholder.
440+ if !mentions(text, "storage") {
441+ // The same base `parse` resolves against, or the completed line would
442+ // point somewhere this boot never looks (config/ vs the directory
443+ // the app runs from).
444+ let database: Option<String> = toml::from_str::<Toml>(text)
445+ .ok()
446+ .and_then(|t| t.database)
447+ .filter(|value| !value.trim().is_empty());
448+ let storage = database
449+ .as_deref()
450+ .map(|db| default_storage(&absolute(base, Path::new(db))))
451+ .unwrap_or_else(|| PathBuf::from("storage"));
452+ missing.push((
453+ "storage",
454+ format!(
455+ "# Where drive files, thumbnails and staged upload chunks live as files, created on boot.\n\
456+ storage = {:?}\n",
457+ storage.display().to_string()
458+ ),
459+ ));
460+ }
461+ if missing.is_empty() {
462+ return;
463+ }
464+ let block = missing
465+ .iter()
466+ .map(|(_, block)| block.as_str())
467+ .collect::<Vec<_>>()
468+ .join("\n");
469+ // Top-level keys must land before any `[table]` header, or TOML would
470+ // read them as that table's. A file with no tables takes them at the end.
471+ let completed = match text.lines().position(|line| {
472+ let trimmed = line.trim_start();
473+ trimmed.starts_with('[') && !trimmed.starts_with("[ ")
474+ }) {
475+ Some(idx) => {
476+ let mut lines: Vec<&str> = text.lines().collect();
477+ // A `[` that is not a header — `[[bin]]` aside, a bracketed value
478+ // cannot start a line in valid TOML outside a header — but only a
479+ // header matters here, and a false positive merely moves the
480+ // insertion up, never into another table.
481+ lines.insert(idx, block.as_str());
482+ let mut out = lines.join("\n");
483+ if text.ends_with('\n') {
484+ out.push('\n');
485+ }
486+ out
487+ }
488+ None => {
489+ let mut completed = text.to_string();
490+ if !completed.is_empty() && !completed.ends_with('\n') {
491+ completed.push('\n');
492+ }
493+ completed.push('\n');
494+ completed.push_str(&block);
495+ completed
496+ }
497+ };
498+ match std::fs::write(path, completed) {
499+ Ok(()) => println!(
500+ "in added {} to {FILE_NAME}, at the default already in use",
501+ missing
502+ .iter()
503+ .map(|(key, _)| *key)
504+ .collect::<Vec<_>>()
505+ .join(", ")
506+ ),
507+ Err(err) => println!("in could not complete {FILE_NAME}: {err}"),
508+ }
509+}
510+
511+/// Whether the file sets this top-level key — a line whose first word it is.
512+/// A key named inside a comment, a value, or an `[oidc]`-style table does not
513+/// count. (An indented `redirect_uri` inside `[oidc]` does count for its own
514+/// name: `trim_start` puts it at the line's start.)
515+fn mentions(text: &str, key: &str) -> bool {
516+ text.lines().any(|line| {
517+ line.trim_start()
518+ .strip_prefix(key)
519+ .is_some_and(|rest| rest.trim_start().starts_with('='))
520+ })
521+}
522+
523+/// Where binary files live when the file is silent about it: beside the
524+/// database file. The two are one backup unit — a backup that takes the
525+/// database but not the files beside it restores a drive whose contents are
526+/// gone — so the default keeps them siblings.
527+fn default_storage(database: &Path) -> PathBuf {
528+ database
529+ .parent()
530+ .map(|parent| parent.join("storage"))
531+ .unwrap_or_else(|| PathBuf::from("storage"))
532+}
533+
534+/// An absolute path for a file that may not exist yet: the directory is
535+/// resolved against `base` (the directory `config/in.toml` was read
536+/// from), the file name is kept as written.
537+fn absolute(base: &Path, path: &Path) -> PathBuf {
538+ if path.is_absolute() {
539+ return path.to_path_buf();
540+ }
541+ let base = base
542+ .canonicalize()
543+ .unwrap_or_else(|_| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
544+ let joined = base.join(path);
545+ match (joined.parent(), joined.file_name()) {
546+ (Some(parent), Some(name)) => match parent.canonicalize() {
547+ Ok(parent) => parent.join(name),
548+ Err(_) => joined.clone(),
549+ },
550+ _ => joined,
551+ }
552+}
553+
554+#[cfg(test)]
555+mod tests {
556+ use super::*;
557+
558+ /// A scratch directory, cleaned up when the test ends, so `load_from` can
559+ /// be driven without touching the working directory.
560+ struct Scratch {
561+ dir: PathBuf,
562+ }
563+
564+ impl Scratch {
565+ fn new() -> Self {
566+ let dir = std::env::temp_dir().join(format!("in-config-test-{}", Ulid::new()));
567+ std::fs::create_dir_all(dir.join("config")).unwrap();
568+ Self { dir }
569+ }
570+
571+ fn write(&self, text: &str) {
572+ std::fs::write(self.dir.join(FILE_NAME), text).unwrap();
573+ }
574+
575+ fn load(&self) -> Result<Config, ConfigError> {
576+ Config::load_from(&self.dir)
577+ }
578+ }
579+
580+ impl Drop for Scratch {
581+ fn drop(&mut self) {
582+ let _ = std::fs::remove_dir_all(&self.dir);
583+ }
584+ }
585+
586+ use ulid::Ulid;
587+
588+ const FULL: &str = r#"database = "in.db"
589+listen = "127.0.0.1:7655"
590+live_seconds = 300
591+purge_after_days = 30
592+default_quota_bytes = 10737418240
593+[oidc]
594+issuer = "https://id.example.com"
595+client_id = "in"
596+client_secret = "s3cret"
597+"#;
598+
599+ #[test]
600+ fn a_missing_file_is_written_with_defaults_and_then_refuses_oidc() {
601+ let scratch = Scratch::new();
602+ // The fresh file has blank [oidc] keys, so the first boot writes and
603+ // then stops on the first of them.
604+ let err = scratch.load().unwrap_err();
605+ assert_eq!(err, ConfigError::Missing("oidc.issuer"));
606+ let written = std::fs::read_to_string(scratch.dir.join(FILE_NAME)).unwrap();
607+ assert!(written.contains("database = \"in.db\""));
608+ assert!(written.contains("client_secret"));
609+ #[cfg(unix)]
610+ {
611+ use std::os::unix::fs::PermissionsExt as _;
612+ let mode = std::fs::metadata(scratch.dir.join(FILE_NAME))
613+ .unwrap()
614+ .permissions()
615+ .mode()
616+ & 0o777;
617+ assert_eq!(mode, 0o600, "the config file holds a live secret one day");
618+ }
619+ }
620+
621+ #[test]
622+ fn a_full_file_loads() {
623+ let scratch = Scratch::new();
624+ scratch.write(FULL);
625+ let config = scratch.load().unwrap();
626+ assert!(config.database.ends_with("in.db"));
627+ assert_eq!(config.listen.port(), 7655);
628+ assert_eq!(config.live_seconds, 300);
629+ assert_eq!(config.purge_after_days, 30);
630+ assert_eq!(config.default_quota_bytes, 10 * 1024 * 1024 * 1024);
631+ assert_eq!(config.oidc.issuer, "https://id.example.com");
632+ assert_eq!(
633+ config.oidc.redirect_uri,
634+ "http://127.0.0.1:7655/auth/callback"
635+ );
636+ assert!(!config.defaulted);
637+ assert!(config.ignored.is_empty());
638+ }
639+
640+ #[test]
641+ fn redirect_uri_defaults_from_listen() {
642+ let scratch = Scratch::new();
643+ scratch.write(&FULL.replace("127.0.0.1:7655", "0.0.0.0:9000"));
644+ let config = scratch.load().unwrap();
645+ // An unspecified bind is not a name anyone can reach; the loopback
646+ // stands in.
647+ assert_eq!(config.oidc.redirect_uri, "http://127.0.0.1:9000/auth/callback");
648+ }
649+ #[test]
650+ fn an_explicit_redirect_uri_wins() {
651+ let scratch = Scratch::new();
652+ scratch.write(
653+ r#"database = "in.db"
654+[oidc]
655+issuer = "https://id.example.com"
656+client_id = "in"
657+client_secret = "s3cret"
658+redirect_uri = "https://files.example.com/auth/callback"
659+"#,
660+ );
661+ let config = scratch.load().unwrap();
662+ assert_eq!(
663+ config.oidc.redirect_uri,
664+ "https://files.example.com/auth/callback"
665+ );
666+ }
667+
668+ #[test]
669+ fn zero_live_seconds_is_refused() {
670+ let scratch = Scratch::new();
671+ scratch.write(&FULL.replace("live_seconds = 300", "live_seconds = 0"));
672+ assert!(matches!(
673+ scratch.load().unwrap_err(),
674+ ConfigError::Invalid { key: "live_seconds", .. }
675+ ));
676+ }
677+
678+ #[test]
679+ fn a_missing_database_is_refused() {
680+ let scratch = Scratch::new();
681+ scratch.write(
682+ r#"[oidc]
683+issuer = "https://id.example.com"
684+client_id = "in"
685+client_secret = "s3cret"
686+"#,
687+ );
688+ assert_eq!(scratch.load().unwrap_err(), ConfigError::Missing("database"));
689+ }
690+
691+ #[test]
692+ fn unknown_keys_are_ignored_and_reported() {
693+ let scratch = Scratch::new();
694+ scratch.write(
695+ r#"database = "in.db"
696+typo_key = 1
697+[oidc]
698+issuer = "https://id.example.com"
699+client_id = "in"
700+client_secret = "s3cret"
701+oidc_typo = 1
702+"#,
703+ );
704+ let config = scratch.load().unwrap();
705+ assert!(config.ignored.contains(&"typo_key".to_string()));
706+ assert!(config.ignored.contains(&"oidc.oidc_typo".to_string()));
707+ assert!(config.report().iter().any(|line| line.contains("typo_key")));
708+ }
709+
710+ #[test]
711+ fn a_silent_file_is_completed_with_top_level_defaults() {
712+ let scratch = Scratch::new();
713+ scratch.write(
714+ r#"database = "in.db"
715+[oidc]
716+issuer = "https://id.example.com"
717+client_id = "in"
718+client_secret = "s3cret"
719+"#,
720+ );
721+ let config = scratch.load().unwrap();
722+ assert_eq!(config.live_seconds, 300);
723+ let completed = std::fs::read_to_string(scratch.dir.join(FILE_NAME)).unwrap();
724+ // Completed top-level keys land before the [oidc] header, never
725+ // inside it.
726+ let oidc_at = completed.find("[oidc]").unwrap();
727+ let listen_at = completed.find("listen = ").unwrap();
728+ assert!(listen_at < oidc_at);
729+ let reparsed: toml::Value = toml::from_str(&completed).unwrap();
730+ assert!(reparsed.get("listen").is_some());
731+ }
732+
733+ #[test]
734+ fn storage_defaults_beside_the_database() {
735+ let scratch = Scratch::new();
736+ scratch.write(FULL);
737+ let config = scratch.load().unwrap();
738+ assert_eq!(
739+ config.storage,
740+ PathBuf::from(&config.database)
741+ .parent()
742+ .unwrap()
743+ .join("storage")
744+ );
745+ }
746+}
crates/in-core/src/lib.rsadded+29 -0
@@ -0,0 +1,29 @@
1+//! Domain model and storage for In.
2+//!
3+//! The vocabulary — the account, folder, file, share and upload shapes —
4+//! compiles everywhere, so the UI and the server speak the same types. The
5+//! `server` feature adds the halves that must never reach the browser: the
6+//! store, the config, the live announcements and the thumbnailing.
7+
8+pub mod store;
9+
10+#[cfg(feature = "server")]
11+pub mod config;
12+#[cfg(feature = "server")]
13+pub mod live;
14+#[cfg(feature = "server")]
15+pub mod thumbs;
16+
17+pub use store::{
18+ CHUNK_SIZE, CreatedLink, File, Folder, Listing, ShareKind, ShareLink, ShareUser, SharedItem,
19+ ThumbState, UPLOAD_TTL_HOURS, UploadSession, UploadState, User,
20+};
21+
22+#[cfg(feature = "server")]
23+pub use config::{Config, ConfigError, OidcConfig};
24+#[cfg(feature = "server")]
25+pub use live::{Change, Topic, next_seq};
26+#[cfg(feature = "server")]
27+pub use store::{
28+ ReconcileOptions, Result, Store, StoreError, TursoStore, hash_share_token, reconcile,
29+};
crates/in-core/src/live.rsadded+68 -0
@@ -0,0 +1,68 @@
1+//! Committed-write announcements.
2+//!
3+//! A write that committed publishes one [`Change`] per surface it touches,
4+//! and the change carries a topic — never data. That is deliberate: a
5+//! channel that carried rows would need a per-message authorisation check,
6+//! and one forgotten filter would leak. A topic cannot leak anything; the
7+//! woken client re-fetches through the ordinary route, and the existing gate
8+//! answers there.
9+//!
10+//! [`Change::seq`] is a process-local counter, so a client that sees 41 and
11+//! then 43 knows it missed one and can resync instead of rendering a mix of
12+//! before and after.
13+
14+use std::sync::atomic::{AtomicU64, Ordering};
15+
16+/// The surface a committed write touched. Every variant carries the user the
17+/// surface belongs to: a change is only ever heard by its own user — or, for
18+/// [`Topic::Admin`], by an admin.
19+#[derive(Debug, Clone, PartialEq, Eq)]
20+pub enum Topic {
21+ /// The person's library: folders, files, uploads, thumbnails.
22+ Library(String),
23+ /// The person's trash: what was trashed, restored, purged or emptied.
24+ Trash(String),
25+ /// Shares: links created or revoked, per-person grants added or removed.
26+ Shares(String),
27+ /// Users, quotas, disablements — the admin's surface.
28+ Admin(String),
29+}
30+
31+impl Topic {
32+ /// The name the wire uses for this topic: the SSE `event:` field, and
33+ /// the key the listener filter decides on.
34+ pub fn kind(&self) -> &'static str {
35+ match self {
36+ Topic::Library(_) => "library",
37+ Topic::Trash(_) => "trash",
38+ Topic::Shares(_) => "shares",
39+ Topic::Admin(_) => "admin",
40+ }
41+ }
42+
43+ /// The user this topic is about. A listener may hear a topic when this
44+ /// is its own id — or, for [`Topic::Admin`], when it is an admin.
45+ pub fn id(&self) -> &str {
46+ match self {
47+ Topic::Library(id) | Topic::Trash(id) | Topic::Shares(id) | Topic::Admin(id) => id,
48+ }
49+ }
50+}
51+
52+/// One committed write: which surface changed, and where this change sits
53+/// in the store's sequence. Everything a client needs to know to refresh —
54+/// and nothing about what changed.
55+#[derive(Debug, Clone, PartialEq, Eq)]
56+pub struct Change {
57+ pub topic: Topic,
58+ pub seq: u64,
59+}
60+
61+static SEQ: AtomicU64 = AtomicU64::new(0);
62+
63+/// The next sequence number, starting at 1. Process-local on purpose: the
64+/// sequence exists to catch a dropped event inside one stream, not to order
65+/// two servers.
66+pub fn next_seq() -> u64 {
67+ SEQ.fetch_add(1, Ordering::Relaxed) + 1
68+}
crates/in-core/src/store/mod.rsadded+607 -0
@@ -0,0 +1,607 @@
1+//! Storage boundary.
2+//!
3+//! Everything the app does to persistent state goes through [`Store`]. The
4+//! only implementation today is Turso (in-process, SQLite-compatible); a
5+//! Postgres swap is a new impl of this trait and nothing else.
6+//!
7+//! The record shapes — [`User`], [`Folder`], [`File`] and the rest — are the
8+//! vocabulary and compile everywhere. Everything that touches a database, a
9+//! secret or a CSPRNG lives behind `server` so none of it is shipped to the
10+//! browser.
11+
12+use serde::{Deserialize, Serialize};
13+use time::OffsetDateTime;
14+
15+#[cfg(feature = "server")]
16+pub mod reconcile;
17+#[cfg(feature = "server")]
18+pub mod schema;
19+#[cfg(feature = "server")]
20+pub mod secret;
21+#[cfg(feature = "server")]
22+pub mod sniff;
23+#[cfg(feature = "server")]
24+pub mod turso_store;
25+
26+#[cfg(feature = "server")]
27+pub use turso_store::{TursoStore, hash_share_token};
28+#[cfg(feature = "server")]
29+pub use reconcile::{ReconcileOptions, reconcile};
30+
31+/// What the store can fail with. A caller that needs to distinguish "no such
32+/// row" from "someone else's row" gets [`StoreError::NotFound`] for the
33+/// first and [`StoreError::CrossOwner`] for the second — and the route layer
34+/// answers 404 to both, because telling a stranger which ids exist is the
35+/// leak the distinction exists to prevent.
36+#[derive(Debug, thiserror::Error)]
37+pub enum StoreError {
38+ /// The name is already taken among the live siblings.
39+ #[error("that name is already taken here")]
40+ NameTaken,
41+ /// The database refused the write or could not be read.
42+ #[error("database: {0}")]
43+ Backend(String),
44+ /// No such row.
45+ #[error("not found")]
46+ NotFound,
47+ /// The row belongs to another owner. Answered as 404, never 403.
48+ #[error("not found")]
49+ CrossOwner,
50+ /// The owner's quota has no room for these bytes.
51+ #[error("quota exceeded")]
52+ QuotaExceeded,
53+ /// The upload session is past `expires_at`, or is no longer active.
54+ #[error("upload expired")]
55+ UploadExpired,
56+ /// A chunk that does not fit the session: wrong size, wrong index, or
57+ /// bytes past the declared total.
58+ #[error("bad chunk")]
59+ BadChunk,
60+ /// The restore is refused: an ancestor is still trashed, and restoring
61+ /// under it would resurrect the row into a trash it never left.
62+ #[error("an ancestor is still trashed")]
63+ AncestorTrashed,
64+ /// The folder move would put a folder inside its own descendant.
65+ #[error("that move would make a circle")]
66+ Cycle,
67+ /// A stored value is not valid — a timestamp that does not parse, a state
68+ /// the code does not know.
69+ #[error("stored value is not valid: {0}")]
70+ Corrupt(String),
71+}
72+
73+pub type Result<T> = std::result::Result<T, StoreError>;
74+
75+/// An account. There is no password here on purpose: sign-in is the OIDC
76+/// provider's business, and this record is what handlers load and what pages
77+/// serialise, so a secret with a field here is a secret one careless response
78+/// away from the wire.
79+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80+pub struct User {
81+ pub id: String,
82+ /// The provider's stable subject. The row is created on first sight of a
83+ /// sub and refreshed on every sight after.
84+ pub oidc_sub: String,
85+ pub email: String,
86+ pub display_name: String,
87+ pub admin: bool,
88+ pub disabled: bool,
89+ /// The person's ceiling, in bytes. Set at provisioning, changed by an
90+ /// admin afterwards.
91+ pub quota_bytes: u64,
92+ /// Every live AND trashed byte the person holds. Trash counts, because a
93+ /// file that can be restored still costs. Recomputed from the rows after
94+ /// every mutation, never blindly incremented.
95+ pub used_bytes: u64,
96+ pub created_at: OffsetDateTime,
97+ pub last_seen_at: Option<OffsetDateTime>,
98+}
99+
100+/// A folder. `parent_id` NULL is the person's root. `deleted_at` is the
101+/// trash: `Some` while trashed, with the same timestamp its whole trashed
102+/// subtree wears.
103+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
104+pub struct Folder {
105+ pub id: String,
106+ pub owner_id: String,
107+ pub parent_id: Option<String>,
108+ /// What the person called it. A label, never a path.
109+ pub name: String,
110+ pub created_at: OffsetDateTime,
111+ pub deleted_at: Option<OffsetDateTime>,
112+}
113+
114+/// A file, as a screen lists it: a name, a type, a size and where it sits.
115+/// The bytes are deliberately not on this type — it is what handlers load and
116+/// pages serialise, and a file's contents have no business travelling with a
117+/// list of file names.
118+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
119+pub struct File {
120+ pub id: String,
121+ pub owner_id: String,
122+ pub folder_id: Option<String>,
123+ /// What the person called it. A label, never a path.
124+ pub name: String,
125+ /// What the server decided the bytes are, never what the upload claimed.
126+ pub mime: String,
127+ pub size_bytes: u64,
128+ pub thumb_state: ThumbState,
129+ pub created_at: OffsetDateTime,
130+ pub updated_at: OffsetDateTime,
131+ pub deleted_at: Option<OffsetDateTime>,
132+}
133+
134+/// Whether a file's thumbnail exists. `None` for bytes no thumbnail is
135+/// attempted for; `Pending` while one is being made; `Ready` or `Failed`
136+/// once the attempt settled.
137+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
138+#[serde(rename_all = "lowercase")]
139+pub enum ThumbState {
140+ None,
141+ Pending,
142+ Ready,
143+ Failed,
144+}
145+
146+impl ThumbState {
147+ pub fn as_str(self) -> &'static str {
148+ match self {
149+ ThumbState::None => "none",
150+ ThumbState::Pending => "pending",
151+ ThumbState::Ready => "ready",
152+ ThumbState::Failed => "failed",
153+ }
154+ }
155+
156+ pub fn parse(raw: &str) -> Result<Self> {
157+ match raw {
158+ "none" => Ok(ThumbState::None),
159+ "pending" => Ok(ThumbState::Pending),
160+ "ready" => Ok(ThumbState::Ready),
161+ "failed" => Ok(ThumbState::Failed),
162+ _ => Err(StoreError::Corrupt(format!("thumb state {raw:?}"))),
163+ }
164+ }
165+}
166+
167+/// Which table a share points at — one file, or one folder and everything
168+/// under it.
169+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
170+#[serde(rename_all = "lowercase")]
171+pub enum ShareKind {
172+ File,
173+ Folder,
174+}
175+
176+impl ShareKind {
177+ pub fn as_str(self) -> &'static str {
178+ match self {
179+ ShareKind::File => "file",
180+ ShareKind::Folder => "folder",
181+ }
182+ }
183+
184+ pub fn parse(raw: &str) -> Result<Self> {
185+ match raw {
186+ "file" => Ok(ShareKind::File),
187+ "folder" => Ok(ShareKind::Folder),
188+ _ => Err(StoreError::Corrupt(format!("share kind {raw:?}"))),
189+ }
190+ }
191+}
192+
193+/// A public share link. The row holds only the token's hash; the plaintext
194+/// is shown once at creation and never again.
195+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196+pub struct ShareLink {
197+ pub id: String,
198+ pub token_hash: String,
199+ pub kind: ShareKind,
200+ pub target_id: String,
201+ pub created_by: String,
202+ pub can_download: bool,
203+ pub created_at: OffsetDateTime,
204+ pub expires_at: Option<OffsetDateTime>,
205+ pub revoked_at: Option<OffsetDateTime>,
206+}
207+
208+impl ShareLink {
209+ /// Whether the link opens today: unrevoked and unexpired.
210+ pub fn is_live(&self, now: OffsetDateTime) -> bool {
211+ self.revoked_at.is_none() && self.expires_at.is_none_or(|at| at > now)
212+ }
213+}
214+
215+/// A freshly created link, with the one thing the row does not keep: the
216+/// plaintext token, shown once and then forgotten.
217+#[derive(Debug, Clone, PartialEq, Eq)]
218+pub struct CreatedLink {
219+ pub link: ShareLink,
220+ pub token: String,
221+}
222+
223+/// One file or folder shared with one person. The row is the whole of the
224+/// permission — removing it unshares completely.
225+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
226+pub struct ShareUser {
227+ pub kind: ShareKind,
228+ pub target_id: String,
229+ pub user_id: String,
230+ pub can_download: bool,
231+ pub created_at: OffsetDateTime,
232+}
233+
234+/// A target shared with the reader, with the name the listing prints. What a
235+/// "shared with me" screen reads; the owner's own library never appears here.
236+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237+pub struct SharedItem {
238+ pub kind: ShareKind,
239+ pub target_id: String,
240+ pub name: String,
241+ /// The file's mime, when the target is one.
242+ pub mime: Option<String>,
243+ pub owner_id: String,
244+ pub can_download: bool,
245+ pub created_at: OffsetDateTime,
246+}
247+
248+/// A chunked upload on its way in. `state` is `active` while chunks are
249+/// still arriving, `done` once the finish assembled them, `aborted` once
250+/// anyone gave up on it.
251+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
252+pub struct UploadSession {
253+ pub id: String,
254+ pub owner_id: String,
255+ pub folder_id: Option<String>,
256+ /// What the person called the coming file. A label, never a path.
257+ pub name: String,
258+ /// The total the finish must add up to, in bytes.
259+ pub size_bytes: u64,
260+ /// The server-fixed chunk size every non-final chunk must match.
261+ pub chunk_size: u64,
262+ /// The bytes staged so far.
263+ pub received_bytes: u64,
264+ pub state: UploadState,
265+ pub created_at: OffsetDateTime,
266+ pub expires_at: OffsetDateTime,
267+}
268+
269+/// What an upload session is doing: arriving, arrived, or given up on.
270+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
271+#[serde(rename_all = "lowercase")]
272+pub enum UploadState {
273+ Active,
274+ Done,
275+ Aborted,
276+}
277+
278+impl UploadState {
279+ pub fn as_str(self) -> &'static str {
280+ match self {
281+ UploadState::Active => "active",
282+ UploadState::Done => "done",
283+ UploadState::Aborted => "aborted",
284+ }
285+ }
286+
287+ pub fn parse(raw: &str) -> Result<Self> {
288+ match raw {
289+ "active" => Ok(UploadState::Active),
290+ "done" => Ok(UploadState::Done),
291+ "aborted" => Ok(UploadState::Aborted),
292+ _ => Err(StoreError::Corrupt(format!("upload state {raw:?}"))),
293+ }
294+ }
295+}
296+
297+/// One directory's live contents — or one search's live hits. Trashed rows
298+/// never appear here; the trash has its own listing.
299+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
300+pub struct Listing {
301+ pub folders: Vec<Folder>,
302+ pub files: Vec<File>,
303+}
304+
305+/// The chunk size the server fixes for every upload session: 8 MiB. The
306+/// upload route caps bodies above it, and the UI sends single-POST below it.
307+pub const CHUNK_SIZE: u64 = 8 * 1024 * 1024;
308+
309+/// How long an upload session gets before it expires: a day is long enough
310+/// for a browser left open overnight and short enough that an abandoned
311+/// upload cannot pin disk for a season.
312+pub const UPLOAD_TTL_HOURS: u32 = 24;
313+
314+#[cfg(feature = "server")]
315+#[async_trait::async_trait]
316+pub trait Store: 'static + Send + Sync {
317+ /// A receiver of committed-write announcements. One [`Change`](crate::live::Change)
318+ /// per write that committed, carrying the topic to re-fetch and no data:
319+ /// the channel cannot say more than the reader may hear, because it says
320+ /// nothing — the woken client re-fetches through the ordinary gated
321+ /// route. Sending to zero subscribers is normal and silent, and a slow
322+ /// subscriber's overflow is the client's cue to resync.
323+ fn subscribe(&self) -> tokio::sync::broadcast::Receiver<crate::live::Change>;
324+
325+ // -- users -------------------------------------------------------------
326+
327+ /// The account holding `sub`, if it has ever signed in.
328+ async fn user_by_oidc_sub(&self, sub: &str) -> Result<Option<User>>;
329+
330+ /// Lookup by address, folded to lowercase before comparing — the provider
331+ /// may capitalise what the row stored plainly, and the two must still
332+ /// meet. What the share UI uses to turn a typed address into a grantee.
333+ async fn user_by_email(&self, email: &str) -> Result<Option<User>>;
334+
335+ /// One account, by id.
336+ async fn user(&self, id: &str) -> Result<Option<User>>;
337+
338+ /// Every account, oldest first — the admin's settings screen.
339+ async fn users(&self) -> Result<Vec<User>>;
340+
341+ /// JIT upsert on OIDC login: unknown sub inserts (first user ever gets
342+ /// admin=1, quota = default_quota_bytes), known sub refreshes
343+ /// email/display_name and stamps last_seen_at. Returns the row.
344+ async fn provision_user(
345+ &self,
346+ sub: &str,
347+ email: &str,
348+ display_name: &str,
349+ default_quota_bytes: u64,
350+ ) -> Result<User>;
351+
352+ /// Writes an account's ceiling. The bytes it already holds are untouched
353+ /// — a quota lowered under current usage refuses new uploads until the
354+ /// person frees space, rather than deleting anything.
355+ async fn set_user_quota(&self, user_id: &str, quota_bytes: u64) -> Result<()>;
356+
357+ /// Disables an account. A disabled account signs in to nothing: the auth
358+ /// layer reads this and treats the person as signed out.
359+ async fn set_user_disabled(&self, user_id: &str, disabled: bool) -> Result<()>;
360+
361+ // -- folders -----------------------------------------------------------
362+
363+ /// Creates a folder. A parent of another owner is [`StoreError::CrossOwner`],
364+ /// not a refusal — the asker named a thing that is not theirs.
365+ async fn create_folder(
366+ &self,
367+ owner_id: &str,
368+ parent_id: Option<&str>,
369+ name: &str,
370+ ) -> Result<Folder>;
371+
372+ /// One folder, by id, trashed or not. The caller decides what trashed
373+ /// means for its screen.
374+ async fn folder(&self, id: &str) -> Result<Option<Folder>>;
375+
376+ /// Renames a folder. A name a live sibling wears is [`StoreError::NameTaken`].
377+ async fn rename_folder(&self, id: &str, name: &str) -> Result<()>;
378+
379+ /// Moves a folder. Into its own descendant is [`StoreError::Cycle`];
380+ /// across owners is [`StoreError::CrossOwner`].
381+ async fn move_folder(&self, id: &str, parent_id: Option<&str>) -> Result<()>;
382+
383+ /// Trashes a folder: the folder, every descendant folder and every file
384+ /// under them wear the same `deleted_at`, in one transaction. The bytes
385+ /// stay on disk until a purge takes the rows.
386+ async fn delete_folder(&self, id: &str) -> Result<()>;
387+
388+ /// One directory's live contents: the folders and files whose parent is
389+ /// `parent_id` (`None` is the root) and whose trash timestamp is empty.
390+ async fn list_children(
391+ &self,
392+ owner_id: &str,
393+ parent_id: Option<&str>,
394+ ) -> Result<Listing>;
395+
396+ // -- files -------------------------------------------------------------
397+
398+ /// Stores small bytes straight through: sanitises the name, checks the
399+ /// quota, sniffs the mime (never trusting the uploader), writes the
400+ /// file, attempts a thumbnail for images and video, and recomputes usage. The
401+ /// chunked upload's finish is the same pipeline over assembled chunks.
402+ async fn insert_file(
403+ &self,
404+ owner_id: &str,
405+ folder_id: Option<&str>,
406+ name: &str,
407+ bytes: &[u8],
408+ ) -> Result<File>;
409+
410+ /// One file's row, still without its bytes.
411+ async fn file(&self, id: &str) -> Result<Option<File>>;
412+
413+ /// Renames a file. A name a live sibling wears is [`StoreError::NameTaken`].
414+ async fn rename_file(&self, id: &str, name: &str) -> Result<()>;
415+
416+ /// Moves a file. Across owners is [`StoreError::CrossOwner`].
417+ async fn move_file(&self, id: &str, folder_id: Option<&str>) -> Result<()>;
418+
419+ /// Trashes a file. The bytes stay on disk — and counting toward quota —
420+ /// until a purge takes the row.
421+ async fn delete_file(&self, id: &str) -> Result<()>;
422+
423+ /// The bytes themselves, for the one handler that serves them. `None`
424+ /// when there is no such row, or its file went missing.
425+ async fn file_bytes(&self, id: &str) -> Result<Option<Vec<u8>>>;
426+
427+ /// The thumbnail's bytes, for the one handler that serves them. `None`
428+ /// when no thumbnail was made, or its file went missing.
429+ async fn thumb_bytes(&self, id: &str) -> Result<Option<Vec<u8>>>;
430+
431+ // -- trash -------------------------------------------------------------
432+
433+ /// Everything the person trashed and has not purged: folders and files
434+ /// wearing a `deleted_at`, newest trash first.
435+ async fn list_trash(&self, owner_id: &str) -> Result<Listing>;
436+
437+ /// Restores a trashed file. Refused with [`StoreError::AncestorTrashed`]
438+ /// while any ancestor folder is still trashed, and with
439+ /// [`StoreError::NameTaken`] while a live sibling wears its name.
440+ async fn restore_file(&self, id: &str) -> Result<()>;
441+
442+ /// Restores a trashed folder and everything under it that it took with
443+ /// it — descendants wearing the folder's own trash timestamp. Anything
444+ /// trashed individually before the folder keeps its earlier moment and
445+ /// stays trashed. Same refusals as [`Store::restore_file`].
446+ async fn restore_folder(&self, id: &str) -> Result<()>;
447+
448+ /// Purges one trashed file for good: the row goes and the bytes and
449+ /// thumbnail follow. `false` when there was no such row. A live file is
450+ /// never purged — trash it first.
451+ async fn purge_file(&self, id: &str) -> Result<bool>;
452+
453+ /// Purges one trashed folder for good: the folder row, every trashed
454+ /// descendant folder and every trashed file under them, deepest rows
455+ /// first. Links and grants naming the purged rows go with them; bytes
456+ /// and thumbnails follow the commit. Returns how many rows went. A
457+ /// folder that is not trashed is refused with [`StoreError::NotFound`] —
458+ /// trash it first.
459+ async fn purge_folder(&self, id: &str) -> Result<u64>;
460+
461+ /// Purges every file and folder trashed before `before`, deepest folders
462+ /// first, and returns how many rows went. The boot sweep calls this with
463+ /// "purge_after_days ago".
464+ async fn purge_expired(&self, before: OffsetDateTime) -> Result<u64>;
465+
466+ /// Purges everything the person trashed, files before folders, and
467+ /// returns how many rows went.
468+ async fn empty_trash(&self, owner_id: &str) -> Result<u64>;
469+
470+ // -- share links -------------------------------------------------------
471+
472+ /// Creates a public link onto one file or folder. Returns the row and the
473+ /// plaintext token — the only moment the token exists outside its hash.
474+ /// A target of another owner is [`StoreError::CrossOwner`].
475+ async fn create_share_link(
476+ &self,
477+ created_by: &str,
478+ kind: ShareKind,
479+ target_id: &str,
480+ can_download: bool,
481+ expires_at: Option<OffsetDateTime>,
482+ ) -> Result<CreatedLink>;
483+
484+ /// Revokes a link. The row stays, so a dead link reads as revoked rather
485+ /// than wrong. Revoking twice is not an error.
486+ async fn revoke_share_link(&self, id: &str) -> Result<()>;
487+
488+ /// Every link the person created, newest first — the shares screen.
489+ async fn share_links(&self, owner_id: &str) -> Result<Vec<ShareLink>>;
490+
491+ /// Resolves a token hash to its link, if the link is live: unrevoked and
492+ /// unexpired at `now`. A dead link and a wrong token both answer `None`,
493+ /// because telling a stranger which tokens exist is the leak the
494+ /// distinction would be.
495+ async fn resolve_share_link(
496+ &self,
497+ token_hash: &str,
498+ now: OffsetDateTime,
499+ ) -> Result<Option<ShareLink>>;
500+
501+ // -- per-person shares -------------------------------------------------
502+
503+ /// Shares one file or folder with one person. The caller must own the
504+ /// live target — another owner's target is [`StoreError::CrossOwner`],
505+ /// a missing or trashed one [`StoreError::NotFound`], the same rule as
506+ /// [`Store::create_share_link`]. Sharing with the owner, or
507+ /// re-sharing what is already shared, is not an error — the second write
508+ /// only refreshes `can_download`.
509+ async fn add_share_user(
510+ &self,
511+ caller_id: &str,
512+ kind: ShareKind,
513+ target_id: &str,
514+ user_id: &str,
515+ can_download: bool,
516+ ) -> Result<()>;
517+
518+ /// Unshares. Removing what was never shared is not an error.
519+ async fn remove_share_user(
520+ &self,
521+ kind: ShareKind,
522+ target_id: &str,
523+ user_id: &str,
524+ ) -> Result<()>;
525+
526+ /// Everything shared with the person that is still live: untrashed
527+ /// targets, newest grant first. The person's own library never appears
528+ /// here.
529+ async fn shares_for_user(&self, user_id: &str) -> Result<Vec<SharedItem>>;
530+
531+ /// Whether `user_id` may see the target: its owner may, and anyone
532+ /// holding a live grant onto the target — or onto any live folder above
533+ /// it — may. A grant on a folder covers everything under it. Nobody else
534+ /// may — and the answer never says which of "no such target" and "not
535+ /// shared" it was.
536+ async fn can_see(&self, kind: ShareKind, target_id: &str, user_id: &str)
537+ -> Result<bool>;
538+
539+ /// Whether `user_id` may download the target: its owner always may, and
540+ /// anyone may who sees it through a grant whose `can_download` is set —
541+ /// on the target itself or on any live folder above it. The most
542+ /// permissive grant on the chain wins: a download grant above the target
543+ /// opens the bytes even under a view-only grant on the target itself.
544+ /// A view-only grant alone opens the page but not the bytes.
545+ async fn can_download(
546+ &self,
547+ kind: ShareKind,
548+ target_id: &str,
549+ user_id: &str,
550+ ) -> Result<bool>;
551+
552+ // -- chunked uploads ---------------------------------------------------
553+
554+ /// Opens an upload session: checks the quota against the declared total,
555+ /// and answers [`StoreError::QuotaExceeded`] while there is still nothing
556+ /// on disk to clean up. A folder of another owner is
557+ /// [`StoreError::CrossOwner`].
558+ async fn create_upload_session(
559+ &self,
560+ owner_id: &str,
561+ folder_id: Option<&str>,
562+ name: &str,
563+ size_bytes: u64,
564+ ) -> Result<UploadSession>;
565+
566+ /// One session, whatever its state.
567+ async fn upload_session(&self, id: &str) -> Result<Option<UploadSession>>;
568+
569+ /// Stages one chunk: `bytes` land at `uploads/<id>/<index>`, and the
570+ /// session's received count follows the files on disk, not the calls —
571+ /// re-sending an index replaces its bytes rather than counting them
572+ /// twice. Anything past the declared total, or on a session that is not
573+ /// active and unexpired, is refused.
574+ async fn record_chunk(
575+ &self,
576+ id: &str,
577+ index: u64,
578+ bytes: &[u8],
579+ ) -> Result<UploadSession>;
580+
581+ /// Assembles a session's chunks in order, rechecks the quota, sniffs the
582+ /// mime (never trusting anything the uploader said), writes the file,
583+ /// attempts a thumbnail for images and video, inserts the row and marks the session
584+ /// done — and returns the file. A session whose chunks do not add up, or
585+ /// whose owner filled their quota while it was arriving, is refused with
586+ /// the chunks still staged for another attempt.
587+ async fn finish_upload(&self, id: &str) -> Result<File>;
588+
589+ /// Aborts a session: the row says `aborted` and the staged chunks are
590+ /// deleted. Aborting twice is not an error.
591+ async fn abort_upload(&self, id: &str) -> Result<()>;
592+
593+ /// Aborts every active session past `expires_at` and deletes its chunks.
594+ /// The boot sweep calls this with now; a janitor may call it any time.
595+ async fn prune_expired_uploads(&self, now: OffsetDateTime) -> Result<u64>;
596+
597+ // -- search ------------------------------------------------------------
598+
599+ /// Owner-scoped substring search over live file and folder names, files
600+ /// and folders in their own lists. At most `limit` of each.
601+ async fn search(
602+ &self,
603+ owner_id: &str,
604+ query: &str,
605+ limit: u32,
606+ ) -> Result<Listing>;
607+}
crates/in-core/src/store/reconcile.rsadded+580 -0
@@ -0,0 +1,580 @@
1+//! Reconcile a live Turso database with the declared whole schema.
2+//!
3+//! The live file is never altered in place. Instead a new file is built from
4+//! `migrations/0001_init.sql`, the data is copied with an explicit per-table
5+//! column map, the copy is verified, and only then the files are swapped. The
6+//! original file is kept as a timestamped backup and is never deleted.
7+//!
8+//! Binary is the one thing that needs no extraction here: In never kept
9+//! bytes in its tables — files, thumbnails and chunks live under the storage
10+//! directory from the first schema, keyed by row id — so the copy moves rows
11+//! only, and the tree beside the database is untouched throughout.
12+
13+use super::schema::{declared_fingerprint, diff_report, fingerprint, schema_sql};
14+use super::{Result, StoreError};
15+
16+use turso::{Builder, Connection};
17+pub struct ReconcileOptions {
18+ /// Print the diff and plan, then stop without touching anything.
19+ pub dry_run: bool,
20+ /// Skip the interactive confirmation.
21+ pub yes: bool,
22+ /// Boot path: do not prompt, log what happened and proceed.
23+ pub auto: bool,
24+}
25+
26+/// Rebuilds the database at `path` to match the declared schema.
27+///
28+/// - Empty or already-current databases are a no-op.
29+/// - A differing database is backed up, rebuilt, verified and swapped into
30+/// place.
31+/// - `storage` is accepted for the call shape the boot path shares with
32+/// databases that once kept binary in their tables; In never did, so the
33+/// tree beside the database is left exactly as it was.
34+/// - A rebuild that fails verification deletes the `.rebuilt` file and leaves
35+/// the original untouched.
36+pub async fn reconcile(
37+ path: &str,
38+ storage: Option<&std::path::Path>,
39+ opts: ReconcileOptions,
40+) -> Result<()> {
41+ let _ = storage;
42+ if path == ":memory:" {
43+ return Err(StoreError::Backend(
44+ "reconcile is not meaningful on an in-memory database".into(),
45+ ));
46+ }
47+ let db_path = std::path::Path::new(path);
48+ if !db_path.exists() {
49+ return Err(StoreError::Backend(format!("database not found: {}", path)));
50+ }
51+
52+ // Open the live database read-only to inspect its fingerprint.
53+ let old_db = Builder::new_local(path)
54+ .build()
55+ .await
56+ .map_err(|e| StoreError::Backend(e.to_string()))?;
57+ let old_conn = old_db
58+ .connect()
59+ .map_err(|e| StoreError::Backend(e.to_string()))?;
60+
61+ let old_fp = fingerprint(&old_conn).await?;
62+ let new_fp = declared_fingerprint().await?;
63+
64+ if old_fp == new_fp {
65+ if !opts.auto {
66+ println!("database already matches the declared schema");
67+ }
68+ return Ok(());
69+ }
70+
71+ let diff = diff_report(&old_fp, &new_fp);
72+
73+ if opts.dry_run {
74+ println!("schema difference:\n{}", diff);
75+ println!("dry run: would rebuild {}", path);
76+ return Ok(());
77+ }
78+
79+ if opts.auto {
80+ eprintln!("database schema differs from declared schema; rebuilding automatically");
81+ eprintln!("difference:\n{}", diff);
82+ } else {
83+ println!("schema difference:\n{}", diff);
84+ if !opts.yes {
85+ print!("rebuild {}? [y/N] ", path);
86+ let _ = std::io::Write::flush(&mut std::io::stdout());
87+ let mut answer = String::new();
88+ match std::io::stdin().read_line(&mut answer) {
89+ Ok(_) if answer.trim().eq_ignore_ascii_case("y") => {}
90+ _ => {
91+ println!("rebuild cancelled");
92+ return Ok(());
93+ }
94+ }
95+ }
96+ }
97+
98+ let rebuilt_path = format!("{}.rebuilt", path);
99+ cleanup_rebuilt(&rebuilt_path);
100+
101+ let result = rebuild(path, &rebuilt_path, &old_conn).await;
102+
103+ // Close the read-only connection before any file moves; this also
104+ // releases the WAL locks on the original file.
105+ drop(old_conn);
106+ drop(old_db);
107+
108+ if let Err(e) = result {
109+ cleanup_rebuilt(&rebuilt_path);
110+ return Err(e);
111+ }
112+
113+ let backup_path = backup_name(path)?;
114+ std::fs::rename(path, &backup_path).map_err(|e| {
115+ StoreError::Backend(format!(
116+ "failed to move original database to backup {}: {}",
117+ backup_path, e
118+ ))
119+ })?;
120+ // SQLite WAL/SHM siblings belong to the main file; the backup must be a
121+ // complete database on its own, and the rebuilt file starts with none.
122+ rename_sibling(path, &backup_path, "-wal");
123+ rename_sibling(path, &backup_path, "-shm");
124+ if let Err(e) = std::fs::rename(&rebuilt_path, path) {
125+ // Best-effort undo so the live file is not gone. If this also fails,
126+ // the caller has both the backup and the rebuilt file to recover from.
127+ let _ = std::fs::rename(&backup_path, path);
128+ let _ = rename_sibling(&backup_path, path, "-wal");
129+ let _ = rename_sibling(&backup_path, path, "-shm");
130+ return Err(StoreError::Backend(format!(
131+ "failed to move rebuilt database into place {}: {}",
132+ rebuilt_path, e
133+ )));
134+ }
135+ // The rebuilt file was checkpointed before the swap, so its own sidecars
136+ // hold nothing — but a `.rebuilt-wal` left lying about would be adopted by
137+ // the NEXT rebuild's fresh `.rebuilt` file, which is how a stale WAL
138+ // corrupts a database that was otherwise fine.
139+ let _ = std::fs::remove_file(format!("{}-wal", rebuilt_path));
140+ let _ = std::fs::remove_file(format!("{}-shm", rebuilt_path));
141+
142+ if opts.auto {
143+ eprintln!(
144+ "database rebuilt and verified; original backed up to {}",
145+ backup_path
146+ );
147+ eprintln!("rebuilt database now at {}", path);
148+ } else {
149+ println!("database rebuilt and verified");
150+ println!("original backed up to {}", backup_path);
151+ println!("rebuilt database now at {}", path);
152+ }
153+
154+ Ok(())
155+}
156+
157+/// Does the actual rebuild: creates `.rebuilt`, copies the data, and verifies
158+/// the result. On success the rebuilt file is complete and checkpointed; on
159+/// failure the caller deletes it.
160+async fn rebuild(path: &str, rebuilt_path: &str, old_conn: &Connection) -> Result<()> {
161+ // The copy runs as `INSERT ... SELECT FROM old.<table>`, which needs
162+ // ATTACH — still gated in this engine, and switched on only here, for the
163+ // one connection that does the rebuild. The verification afterwards is
164+ // what protects the data, not the copy's mechanism.
165+ let new_db = Builder::new_local(rebuilt_path)
166+ .experimental_attach(true)
167+ .build()
168+ .await
169+ .map_err(|e| StoreError::Backend(e.to_string()))?;
170+ let new_conn = new_db
171+ .connect()
172+ .map_err(|e| StoreError::Backend(e.to_string()))?;
173+
174+ new_conn
175+ .execute_batch(&schema_sql())
176+ .await
177+ .map_err(|e| StoreError::Backend(e.to_string()))?;
178+
179+ copy_data(old_conn, &new_conn, path).await?;
180+ verify(old_conn, &new_conn).await?;
181+
182+ // A checkpoint PRAGMA answers with a row, so it is a query: `execute`
183+ // treats a row as a failure ("unexpected row during execution").
184+ let mut checkpoint = new_conn
185+ .query("PRAGMA wal_checkpoint(TRUNCATE)", ())
186+ .await
187+ .map_err(|e| StoreError::Backend(format!("checkpoint: {e}")))?;
188+ while checkpoint
189+ .next()
190+ .await
191+ .map_err(|e| StoreError::Backend(format!("checkpoint: {e}")))?
192+ .is_some()
193+ {}
194+
195+ Ok(())
196+}
197+
198+/// A per-table column map. Every destination column must appear exactly once;
199+/// `copy_data` validates this against the declared schema before inserting.
200+struct TableMap {
201+ name: &'static str,
202+ columns: Vec<(&'static str, String)>,
203+}
204+
205+/// Builds the explicit column map. Every table maps every column to its old
206+/// self: In's first schema is the declared one, so a database old enough to
207+/// be reconciled carries the same columns, and the map is the receipt that
208+/// says nothing was dropped, renamed or defaulted on the way across.
209+fn build_maps() -> Vec<TableMap> {
210+ vec![
211+ TableMap {
212+ name: "user",
213+ columns: old_cols(&[
214+ "id",
215+ "oidc_sub",
216+ "email",
217+ "display_name",
218+ "admin",
219+ "disabled",
220+ "quota_bytes",
221+ "used_bytes",
222+ "created_at",
223+ "last_seen_at",
224+ ]),
225+ },
226+ TableMap {
227+ name: "folder",
228+ columns: old_cols(&[
229+ "id",
230+ "owner_id",
231+ "parent_id",
232+ "name",
233+ "created_at",
234+ "deleted_at",
235+ ]),
236+ },
237+ TableMap {
238+ name: "file",
239+ columns: old_cols(&[
240+ "id",
241+ "owner_id",
242+ "folder_id",
243+ "name",
244+ "mime",
245+ "size_bytes",
246+ "thumb_state",
247+ "created_at",
248+ "updated_at",
249+ "deleted_at",
250+ ]),
251+ },
252+ TableMap {
253+ name: "share_link",
254+ columns: old_cols(&[
255+ "id",
256+ "token_hash",
257+ "kind",
258+ "target_id",
259+ "created_by",
260+ "can_download",
261+ "created_at",
262+ "expires_at",
263+ "revoked_at",
264+ ]),
265+ },
266+ TableMap {
267+ name: "share_user",
268+ columns: old_cols(&["kind", "target_id", "user_id", "can_download", "created_at"]),
269+ },
270+ TableMap {
271+ name: "upload_session",
272+ columns: old_cols(&[
273+ "id",
274+ "owner_id",
275+ "folder_id",
276+ "name",
277+ "size_bytes",
278+ "chunk_size",
279+ "received_bytes",
280+ "state",
281+ "created_at",
282+ "expires_at",
283+ ]),
284+ },
285+ ]
286+}
287+
288+fn old_cols(cols: &[&'static str]) -> Vec<(&'static str, String)> {
289+ cols.iter().map(|c| (*c, format!("old.{}", c))).collect()
290+}
291+
292+/// Validates that every destination column is covered and that no map
293+/// references a column that does not exist. A missing column is a startup
294+/// error, never a silent NULL.
295+async fn validate_maps(conn: &Connection, maps: &[TableMap]) -> Result<()> {
296+ use std::collections::HashSet;
297+
298+ for map in maps {
299+ let sql = format!("PRAGMA table_info({})", map.name);
300+ let mut rows = conn
301+ .query(&sql, ())
302+ .await
303+ .map_err(|e| StoreError::Backend(e.to_string()))?;
304+ let mut actual = HashSet::new();
305+ while let Some(row) = rows
306+ .next()
307+ .await
308+ .map_err(|e| StoreError::Backend(e.to_string()))?
309+ {
310+ let name: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?;
311+ actual.insert(name);
312+ }
313+
314+ for (col, _) in &map.columns {
315+ if !actual.contains(*col) {
316+ return Err(StoreError::Backend(format!(
317+ "reconcile map for {} references missing column {}",
318+ map.name, col
319+ )));
320+ }
321+ }
322+ for col in actual {
323+ if !map.columns.iter().any(|(c, _)| c == &col) {
324+ return Err(StoreError::Backend(format!(
325+ "reconcile map for {} is missing column {} (would become NULL)",
326+ map.name, col
327+ )));
328+ }
329+ }
330+ }
331+
332+ // Every table the declared schema creates must have a map: a declared
333+ // table without one is a table the rebuild would create empty while the
334+ // copy ran. Engine bookkeeping (`sqlite_*`) is not user data. A table the
335+ // old database carries but the declared schema does not is dropped on
336+ // purpose; it is the declared side that may never go unmapped.
337+ let mut rows = conn
338+ .query("SELECT name FROM sqlite_master WHERE type = 'table'", ())
339+ .await
340+ .map_err(|e| StoreError::Backend(e.to_string()))?;
341+ let mut declared = Vec::new();
342+ while let Some(row) = rows
343+ .next()
344+ .await
345+ .map_err(|e| StoreError::Backend(e.to_string()))?
346+ {
347+ let name: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?;
348+ if !name.starts_with("sqlite_") {
349+ declared.push(name);
350+ }
351+ }
352+ for table in declared {
353+ if !maps.iter().any(|m| m.name == table) {
354+ return Err(StoreError::Backend(format!(
355+ "reconcile has no map for declared table {table} (its rows would be dropped)"
356+ )));
357+ }
358+ }
359+ Ok(())
360+}
361+
362+/// Copies every mapped table from the attached old database into the new
363+/// main schema, in foreign-key-safe order: owners before folders, folders
364+/// before the files and sessions that name them, everything before the
365+/// shares that name all of it.
366+async fn copy_data(_old_conn: &Connection, new_conn: &Connection, path: &str) -> Result<()> {
367+ let escaped = path.replace('\'', "''");
368+ new_conn
369+ .execute(&format!("ATTACH DATABASE '{}' AS old", escaped), ())
370+ .await
371+ .map_err(|e| StoreError::Backend(e.to_string()))?;
372+
373+ let maps = build_maps();
374+ validate_maps(new_conn, &maps).await?;
375+
376+ // Foreign keys stay off during the copy and are checked by `verify`
377+ // instead: folder rows copy in rowid order, which is not a topological
378+ // order for the self-referencing parent link, and a child copied ahead of
379+ // its parent is a good row in a bad moment rather than a bad row.
380+ new_conn
381+ .execute("PRAGMA foreign_keys = OFF", ())
382+ .await
383+ .map_err(|e| StoreError::Backend(e.to_string()))?;
384+ for map in maps {
385+ let cols = map
386+ .columns
387+ .iter()
388+ .map(|(c, _)| *c)
389+ .collect::<Vec<_>>()
390+ .join(", ");
391+ // `old` is the attached SCHEMA, not a table, so `old.id` in a select
392+ // list reads as "table old, column id". The source table is aliased
393+ // and the maps' `old.` prefix rewritten onto that alias.
394+ let exprs = map
395+ .columns
396+ .iter()
397+ .map(|(_, e)| e.replace("old.", "src."))
398+ .collect::<Vec<_>>()
399+ .join(", ");
400+ let sql = format!(
401+ "INSERT INTO main.{} ({}) SELECT {} FROM old.{} AS src",
402+ map.name, cols, exprs, map.name
403+ );
404+ new_conn.execute(&sql, ()).await.map_err(|e| {
405+ StoreError::Backend(format!("{} while copying {}: {}", e, map.name, sql))
406+ })?;
407+ }
408+ new_conn
409+ .execute("PRAGMA foreign_keys = ON", ())
410+ .await
411+ .map_err(|e| StoreError::Backend(e.to_string()))?;
412+
413+ new_conn
414+ .execute("DETACH DATABASE old", ())
415+ .await
416+ .map_err(|e| StoreError::Backend(e.to_string()))?;
417+
418+ Ok(())
419+}
420+
421+/// Verifies the rebuilt database before the swap: foreign keys, integrity,
422+/// and row counts table by table. Anything lost or invented fails here
423+/// instead of shipping.
424+async fn verify(old_conn: &Connection, new_conn: &Connection) -> Result<()> {
425+ let mut rows = new_conn
426+ .query("PRAGMA foreign_key_check", ())
427+ .await
428+ .map_err(|e| StoreError::Backend(e.to_string()))?;
429+ let mut fk_errors = Vec::new();
430+ while let Some(row) = rows
431+ .next()
432+ .await
433+ .map_err(|e| StoreError::Backend(e.to_string()))?
434+ {
435+ let table: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?;
436+ let rowid: i64 = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?;
437+ let parent: String = row.get(2).map_err(|e| StoreError::Backend(e.to_string()))?;
438+ let fkid: i64 = row.get(3).map_err(|e| StoreError::Backend(e.to_string()))?;
439+ fk_errors.push(format!(
440+ "{} rowid {} references {} (foreign key {})",
441+ table, rowid, parent, fkid
442+ ));
443+ }
444+ if !fk_errors.is_empty() {
445+ return Err(StoreError::Backend(format!(
446+ "foreign key check failed:\n{}",
447+ fk_errors.join("\n")
448+ )));
449+ }
450+
451+ let mut rows = new_conn
452+ .query("PRAGMA integrity_check", ())
453+ .await
454+ .map_err(|e| StoreError::Backend(e.to_string()))?;
455+ let mut integrity = Vec::new();
456+ while let Some(row) = rows
457+ .next()
458+ .await
459+ .map_err(|e| StoreError::Backend(e.to_string()))?
460+ {
461+ let msg: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?;
462+ integrity.push(msg);
463+ }
464+ if integrity.len() != 1 || integrity[0] != "ok" {
465+ return Err(StoreError::Backend(format!(
466+ "integrity check failed: {:?}",
467+ integrity
468+ )));
469+ }
470+
471+ let tables = [
472+ "user",
473+ "folder",
474+ "file",
475+ "share_link",
476+ "share_user",
477+ "upload_session",
478+ ];
479+ for table in tables {
480+ let old_count = count_rows(old_conn, table).await?;
481+ let new_count = count_rows(new_conn, table).await?;
482+ if old_count != new_count {
483+ return Err(StoreError::Backend(format!(
484+ "row count mismatch for {}: old {} new {}",
485+ table, old_count, new_count
486+ )));
487+ }
488+ }
489+
490+ Ok(())
491+}
492+
493+async fn count_rows(conn: &Connection, table: &str) -> Result<i64> {
494+ let sql = format!("SELECT COUNT(*) FROM {}", table);
495+ let mut rows = conn
496+ .query(&sql, ())
497+ .await
498+ .map_err(|e| StoreError::Backend(e.to_string()))?;
499+ let Some(row) = rows
500+ .next()
501+ .await
502+ .map_err(|e| StoreError::Backend(e.to_string()))?
503+ else {
504+ return Err(StoreError::Backend(format!(
505+ "could not count rows in {}",
506+ table
507+ )));
508+ };
509+ row.get::<i64>(0)
510+ .map_err(|e| StoreError::Backend(e.to_string()))
511+}
512+
513+fn cleanup_rebuilt(rebuilt_path: &str) {
514+ let _ = std::fs::remove_file(rebuilt_path);
515+ let _ = std::fs::remove_file(format!("{}-wal", rebuilt_path));
516+ let _ = std::fs::remove_file(format!("{}-shm", rebuilt_path));
517+}
518+
519+/// Move a SQLite sidecar file (`-wal` or `-shm`) if it exists. A missing
520+/// sibling is fine: WAL mode may not have created one, and the backup is
521+/// still consistent without it.
522+fn rename_sibling(from: &str, to: &str, suffix: &str) {
523+ let from_path = format!("{}{}", from, suffix);
524+ let to_path = format!("{}{}", to, suffix);
525+ if std::path::Path::new(&from_path).exists() {
526+ let _ = std::fs::rename(&from_path, &to_path);
527+ }
528+}
529+
530+fn backup_name(path: &str) -> Result<String> {
531+ let format = time::format_description::parse_borrowed::<2>(
532+ "[year]-[month]-[day]T[hour][minute][second]Z",
533+ )
534+ .map_err(|e| StoreError::Backend(format!("invalid time format: {}", e)))?;
535+ let stamp = time::OffsetDateTime::now_utc()
536+ .format(&format)
537+ .map_err(|e| StoreError::Backend(format!("time format failed: {}", e)))?;
538+
539+ let candidate = format!("{}.backup-{}", path, stamp);
540+ if !std::path::Path::new(&candidate).exists() {
541+ return Ok(candidate);
542+ }
543+ let mut n = 1;
544+ loop {
545+ let candidate = format!("{}.backup-{}-{}", path, stamp, n);
546+ if !std::path::Path::new(&candidate).exists() {
547+ return Ok(candidate);
548+ }
549+ n += 1;
550+ if n > 1000 {
551+ return Err(StoreError::Backend(
552+ "could not find an unused backup name".into(),
553+ ));
554+ }
555+ }
556+}
557+
558+/// A probe the copy plan can ask: whether the old database already carries
559+/// `column` on `table`. Unused while the declared schema is the first one —
560+/// every database old enough to be reconciled predates every column it
561+/// would probe — and kept because the second migration will need exactly
562+/// this question on its first day.
563+#[allow(dead_code)]
564+async fn old_has_column(conn: &Connection, table: &str, column: &str) -> Result<bool> {
565+ let mut rows = conn
566+ .query(&format!("PRAGMA table_info({table})"), ())
567+ .await
568+ .map_err(|e| StoreError::Backend(e.to_string()))?;
569+ while let Some(row) = rows
570+ .next()
571+ .await
572+ .map_err(|e| StoreError::Backend(e.to_string()))?
573+ {
574+ let name: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?;
575+ if name == column {
576+ return Ok(true);
577+ }
578+ }
579+ Ok(false)
580+}
crates/in-core/src/store/schema.rsadded+373 -0
@@ -0,0 +1,373 @@
1+//! Schema fingerprinting: compare the database SQLite actually has with the
2+//! declared whole schema in `migrations/0001_init.sql`.
3+//!
4+//! SQLite stores `CREATE` statements as written, comments and all, so two
5+//! databases built from the same logical schema but different comments or
6+//! whitespace would otherwise look different. The normaliser here strips the
7+//! cosmetic differences that do not change what the schema means.
8+
9+use super::{Result, StoreError};
10+use turso::Connection;
11+
12+/// The declared migrations, in order. An empty database is built by applying
13+/// them one after another; each one applies cleanly to what the ones before
14+/// it built, so their concatenation is itself a valid whole-schema script.
15+pub(crate) const MIGRATIONS: &[&str] = &[include_str!("../../migrations/0001_init.sql")];
16+
17+/// The whole declared schema — every migration applied in order — as one
18+/// batch of SQL.
19+pub(crate) fn schema_sql() -> String {
20+ let mut sql = String::new();
21+ for migration in MIGRATIONS {
22+ sql.push_str(migration);
23+ sql.push('\n');
24+ }
25+ sql
26+}
27+
28+/// Reads and normalises the schema of the connected database.
29+///
30+/// The fingerprint is a deterministic text built from `sqlite_master`:
31+/// `type|name|normalised_sql` for every non-sqlite object, ordered by type
32+/// and name. Two schemas that mean the same thing produce the same string;
33+/// two schemas that differ in tables, indexes, columns or constraints do not.
34+pub async fn fingerprint(conn: &Connection) -> Result<String> {
35+ let mut rows = conn
36+ .query(
37+ "SELECT type, name, sql FROM sqlite_master \
38+ WHERE name NOT LIKE 'sqlite_%' \
39+ ORDER BY type, name",
40+ (),
41+ )
42+ .await
43+ .map_err(|e| StoreError::Backend(e.to_string()))?;
44+
45+ let mut out = String::new();
46+ while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? {
47+ let t: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?;
48+ let name: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?;
49+ let sql: Option<String> =
50+ row.get(2).map_err(|e| StoreError::Backend(e.to_string()))?;
51+ out.push_str(&t);
52+ out.push('|');
53+ out.push_str(&name);
54+ out.push('|');
55+ if let Some(sql) = sql {
56+ out.push_str(&normalize_schema(&sql));
57+ }
58+ out.push('\n');
59+ }
60+ Ok(out)
61+}
62+
63+/// Builds an in-memory database from the declared schema and fingerprints it.
64+pub async fn declared_fingerprint() -> Result<String> {
65+ let db = turso::Builder::new_local(":memory:")
66+ .build()
67+ .await
68+ .map_err(|e| StoreError::Backend(e.to_string()))?;
69+ let conn = db.connect().map_err(|e| StoreError::Backend(e.to_string()))?;
70+ conn.execute_batch(&schema_sql())
71+ .await
72+ .map_err(|e| StoreError::Backend(e.to_string()))?;
73+ fingerprint(&conn).await
74+}
75+
76+/// A single schema object for diff reporting.
77+#[derive(Debug, Clone)]
78+pub(crate) struct SchemaObject {
79+ pub(crate) kind: String,
80+ pub(crate) name: String,
81+ pub(crate) sql: String,
82+}
83+
84+/// Parses the normalised schema into objects keyed by (kind, name).
85+pub(crate) fn parse_objects(fingerprint: &str) -> Vec<SchemaObject> {
86+ fingerprint
87+ .lines()
88+ .filter(|line| !line.is_empty())
89+ .filter_map(|line| {
90+ let mut parts = line.splitn(3, '|');
91+ let kind = parts.next()?.to_string();
92+ let name = parts.next()?.to_string();
93+ let sql = parts.next().unwrap_or("").to_string();
94+ Some(SchemaObject { kind, name, sql })
95+ })
96+ .collect()
97+}
98+
99+/// Human-readable description of how two fingerprints differ.
100+pub(crate) fn diff_report(old: &str, new: &str) -> String {
101+ let old_objs = parse_objects(old);
102+ let new_objs = parse_objects(new);
103+
104+ let mut missing = Vec::new();
105+ let mut extra = Vec::new();
106+ let mut changed = Vec::new();
107+
108+ for old_obj in &old_objs {
109+ match new_objs.iter().find(|n| n.kind == old_obj.kind && n.name == old_obj.name) {
110+ Some(new_obj) if new_obj.sql != old_obj.sql => changed.push((old_obj, new_obj)),
111+ Some(_) => {}
112+ None => missing.push(old_obj),
113+ }
114+ }
115+ for new_obj in &new_objs {
116+ if !old_objs.iter().any(|o| o.kind == new_obj.kind && o.name == new_obj.name) {
117+ extra.push(new_obj);
118+ }
119+ }
120+
121+ let mut lines = Vec::new();
122+ for obj in missing {
123+ lines.push(format!("- {} {} (removed)", obj.kind, obj.name));
124+ }
125+ for obj in extra {
126+ lines.push(format!("+ {} {} (added)", obj.kind, obj.name));
127+ }
128+ for (old_obj, new_obj) in changed {
129+ lines.push(format!("~ {} {} (changed)", old_obj.kind, old_obj.name));
130+ if old_obj.kind == "table" {
131+ let old_cols = extract_column_names(&old_obj.sql);
132+ let new_cols = extract_column_names(&new_obj.sql);
133+ let added: Vec<&str> = new_cols
134+ .iter()
135+ .filter(|c| !old_cols.contains(c))
136+ .map(String::as_str)
137+ .collect();
138+ let removed: Vec<&str> = old_cols
139+ .iter()
140+ .filter(|c| !new_cols.contains(c))
141+ .map(String::as_str)
142+ .collect();
143+ if !added.is_empty() {
144+ lines.push(format!(" added columns: {}", added.join(", ")));
145+ }
146+ if !removed.is_empty() {
147+ lines.push(format!(" removed columns: {}", removed.join(", ")));
148+ }
149+ }
150+ }
151+
152+ if lines.is_empty() {
153+ "schemas differ (cosmetic normalisation only)".to_string()
154+ } else {
155+ lines.join("\n")
156+ }
157+}
158+
159+/// Extracts the column names from a normalised CREATE TABLE statement.
160+/// Constraints at the table level are ignored; only top-level definitions
161+/// that start with an identifier are collected.
162+fn extract_column_names(sql: &str) -> Vec<String> {
163+ let body = match sql.strip_prefix("CREATE TABLE ") {
164+ Some(rest) => rest,
165+ None => return Vec::new(),
166+ };
167+ let body = remove_if_not_exists(body);
168+ let Some(start) = body.find('(') else {
169+ return Vec::new();
170+ };
171+ let Some(end) = body.rfind(')') else {
172+ return Vec::new();
173+ };
174+ let body = &body[start + 1..end];
175+
176+ let mut cols = Vec::new();
177+ let mut depth = 0i32;
178+ let mut current = String::new();
179+ for ch in body.chars() {
180+ match ch {
181+ '(' => {
182+ depth += 1;
183+ current.push(ch);
184+ }
185+ ')' => {
186+ depth -= 1;
187+ current.push(ch);
188+ }
189+ ',' if depth == 0 => {
190+ if let Some(col) = first_identifier(&current) {
191+ cols.push(col);
192+ }
193+ current.clear();
194+ }
195+ _ => current.push(ch),
196+ }
197+ }
198+ if !current.is_empty() {
199+ if let Some(col) = first_identifier(&current) {
200+ cols.push(col);
201+ }
202+ }
203+ cols
204+}
205+
206+fn first_identifier(item: &str) -> Option<String> {
207+ let item = item.trim();
208+ if item.is_empty() {
209+ return None;
210+ }
211+ let first = item.split_whitespace().next()?;
212+ let first = first.to_lowercase();
213+ if first == "constraint"
214+ || first == "primary"
215+ || first == "unique"
216+ || first == "check"
217+ || first == "foreign"
218+ {
219+ return None;
220+ }
221+ Some(first)
222+}
223+
224+/// Normalises SQL text so that cosmetic differences disappear.
225+///
226+/// Differences deliberately ignored:
227+/// - whitespace runs collapse to a single space;
228+/// - SQL comments (`--` to end of line, `/* ... */`) are removed;
229+/// - `IF NOT EXISTS` is removed (case-insensitive, whole tokens only).
230+///
231+/// Differences deliberately preserved:
232+/// - identifier case and spelling;
233+/// - string literal contents, including any whitespace or comment-like text
234+/// inside them;
235+/// - numeric literals, keyword order and constraint text.
236+fn normalize_schema(sql: &str) -> String {
237+ let mut out = String::with_capacity(sql.len());
238+ let mut chars = sql.chars().peekable();
239+ let mut in_string = false;
240+ let mut prev_ws = false;
241+
242+ while let Some(ch) = chars.next() {
243+ if in_string {
244+ out.push(ch);
245+ if ch == '\'' {
246+ if chars.peek() == Some(&'\'') {
247+ out.push(chars.next().unwrap());
248+ } else {
249+ in_string = false;
250+ }
251+ }
252+ continue;
253+ }
254+
255+ if ch == '-' && chars.peek() == Some(&'-') {
256+ chars.next();
257+ while let Some(c) = chars.next() {
258+ if c == '\n' {
259+ break;
260+ }
261+ }
262+ prev_ws = true;
263+ continue;
264+ }
265+
266+ if ch == '/' && chars.peek() == Some(&'*') {
267+ chars.next();
268+ while let Some(c) = chars.next() {
269+ if c == '*' && chars.peek() == Some(&'/') {
270+ chars.next();
271+ break;
272+ }
273+ }
274+ prev_ws = true;
275+ continue;
276+ }
277+
278+ if ch == '\'' {
279+ in_string = true;
280+ out.push(ch);
281+ prev_ws = false;
282+ continue;
283+ }
284+
285+ if ch.is_whitespace() {
286+ prev_ws = true;
287+ continue;
288+ }
289+
290+ if prev_ws && !out.is_empty() {
291+ out.push(' ');
292+ }
293+ out.push(ch);
294+ prev_ws = false;
295+ }
296+
297+ remove_if_not_exists(&out)
298+}
299+
300+/// Strips a normalised `IF NOT EXISTS` token sequence, preserving whitespace
301+/// around it. Because `normalize_schema` has already collapsed whitespace, the
302+/// sequence appears as separate tokens separated by single spaces.
303+fn remove_if_not_exists(sql: &str) -> String {
304+ let tokens: Vec<&str> = sql.split(' ').collect();
305+ let mut out = Vec::with_capacity(tokens.len());
306+ let mut i = 0;
307+ while i < tokens.len() {
308+ if i + 2 < tokens.len()
309+ && tokens[i].eq_ignore_ascii_case("IF")
310+ && tokens[i + 1].eq_ignore_ascii_case("NOT")
311+ && tokens[i + 2].eq_ignore_ascii_case("EXISTS")
312+ {
313+ i += 3;
314+ } else {
315+ out.push(tokens[i]);
316+ i += 1;
317+ }
318+ }
319+ out.join(" ")
320+}
321+
322+#[cfg(test)]
323+mod tests {
324+ use super::{normalize_schema, parse_objects};
325+
326+ #[test]
327+ fn comments_and_whitespace_do_not_change_meaning() {
328+ let a = "CREATE TABLE foo (\n id INTEGER, -- the key\n name TEXT /* a comment */\n);";
329+ let b = "CREATE TABLE foo ( id INTEGER, name TEXT );";
330+ assert_eq!(normalize_schema(a), normalize_schema(b));
331+ }
332+
333+ #[test]
334+ fn if_not_exists_is_ignored() {
335+ let a = "CREATE TABLE IF NOT EXISTS foo (id INTEGER);";
336+ let b = "CREATE TABLE foo (id INTEGER);";
337+ assert_eq!(normalize_schema(a), normalize_schema(b));
338+ }
339+
340+ #[test]
341+ fn string_literals_are_preserved() {
342+ let a = "CREATE TABLE foo (name TEXT DEFAULT 'a -- b /* c */');";
343+ let b = "CREATE TABLE foo (name TEXT DEFAULT 'a -- b /* c */');";
344+ assert_eq!(normalize_schema(a), normalize_schema(b));
345+ }
346+
347+ #[test]
348+ fn real_differences_still_differ() {
349+ let a = "CREATE TABLE foo (id INTEGER);";
350+ let b = "CREATE TABLE foo (id TEXT);";
351+ assert_ne!(normalize_schema(a), normalize_schema(b));
352+ }
353+
354+ #[test]
355+ fn if_not_exists_does_not_corrupt_identifiers() {
356+ // The stripper looks for whole tokens; words that merely appear
357+ // inside identifiers or string literals must stay put.
358+ let a = "CREATE TABLE IF NOT EXISTS notification (if_not_exists TEXT DEFAULT 'IF NOT EXISTS');";
359+ let b = "CREATE TABLE notification (if_not_exists TEXT DEFAULT 'IF NOT EXISTS');";
360+ assert_eq!(normalize_schema(a), normalize_schema(b));
361+ }
362+
363+ #[test]
364+ fn partial_index_where_clause_is_parsed_safely() {
365+ // Partial-index SQL contains a WHERE clause; diff_report must not
366+ // try to extract column names from it, and parsing must not panic.
367+ let fp = "index|tag_one_default|CREATE UNIQUE INDEX tag_one_default ON tag(board_id) WHERE is_default = 1\n";
368+ let objs = parse_objects(fp);
369+ assert_eq!(objs.len(), 1);
370+ assert_eq!(objs[0].kind, "index");
371+ assert_eq!(objs[0].name, "tag_one_default");
372+ }
373+}
crates/in-core/src/store/secret.rsadded+199 -0
@@ -0,0 +1,199 @@
1+//! The SMTP password's second lock.
2+//!
3+//! File permissions on the database (see [`TursoStore::open`]) stop a casual
4+//! `ls` on the server from reading the password, but a copy of the database
5+//! file — a backup, a snapshot, an `scp` by someone who should not have had
6+//! it — carries the plaintext right along with it. This module is the fix:
7+//! the column holds ciphertext, and the key that opens it lives in a second
8+//! file (`in.key`, beside the database) that a database backup does not
9+//! automatically include.
10+//!
11+//! The envelope is `v1:` followed by base64 of a 24-byte XChaCha20-Poly1305
12+//! nonce and the sealed bytes it protects. The prefix is what lets
13+//! [`TursoStore::open`] tell a value we sealed apart from a plaintext
14+//! password left behind by a deployment from before this module existed —
15+//! see the migration note there. There is deliberately no `v2` yet; add one
16+//! the day the algorithm changes, and keep `open` accepting both prefixes for
17+//! as long as ciphertext under the old one might still be sitting in a row.
18+//!
19+//! Losing the key file — a backup restored without its sibling, most likely —
20+//! is not a crash. [`open`] returns `None` on anything it cannot make sense
21+//! of: wrong key, damaged ciphertext, a value that never was one of ours.
22+//! The caller in [`TursoStore::smtp_password`] turns that into "no password
23+//! set", which is the same screen an admin sees on a workspace that never had
24+//! a sender configured, and the same fix: type the password in again.
25+
26+use std::io;
27+use std::path::Path;
28+
29+use base64::Engine;
30+use base64::engine::general_purpose::STANDARD as base64;
31+use chacha20poly1305::aead::Aead;
32+use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce};
33+use rand::Rng;
34+
35+/// A key is 32 raw bytes; nothing here derives it from a password, because
36+/// there is no password to derive it from — it is the thing that protects
37+/// one.
38+pub const KEY_BYTES: usize = 32;
39+pub type Key = [u8; KEY_BYTES];
40+
41+const PREFIX: &str = "v1:";
42+const NONCE_BYTES: usize = 24;
43+
44+/// True for a value already in our envelope — the test the migration-at-open
45+/// logic uses to skip a row it has already sealed.
46+pub fn is_sealed(value: &str) -> bool {
47+ value.starts_with(PREFIX)
48+}
49+
50+/// Encrypts `plaintext` under `key`, returning the envelope ready to store.
51+///
52+/// A fresh random nonce is drawn every call, so sealing the same password
53+/// twice gives two different strings. XChaCha20-Poly1305's 24-byte nonce is
54+/// wide enough that "draw at random and never track reuse" is safe for the
55+/// volume of writes a settings panel produces in a workspace's lifetime.
56+pub fn seal(key: &Key, plaintext: &str) -> String {
57+ let cipher = XChaCha20Poly1305::new(key.into());
58+ let mut nonce_bytes = [0u8; NONCE_BYTES];
59+ rand::rng().fill_bytes(&mut nonce_bytes);
60+ let nonce = XNonce::from_slice(&nonce_bytes);
61+ let ciphertext = cipher
62+ .encrypt(nonce, plaintext.as_bytes())
63+ .expect("XChaCha20-Poly1305 cannot fail to encrypt a plaintext this small");
64+ let mut payload = Vec::with_capacity(NONCE_BYTES + ciphertext.len());
65+ payload.extend_from_slice(&nonce_bytes);
66+ payload.extend_from_slice(&ciphertext);
67+ format!("{PREFIX}{}", base64.encode(payload))
68+}
69+
70+/// Reverses [`seal`]. `None` covers every way this can fail to come back —
71+/// not our prefix, not valid base64, too short to hold a nonce, wrong key,
72+/// or a tampered/truncated ciphertext that fails the Poly1305 tag check —
73+/// and every one of those is meant to degrade to "no password", never panic
74+/// or bubble an error past the mailer.
75+pub fn open(key: &Key, sealed: &str) -> Option<String> {
76+ let body = sealed.strip_prefix(PREFIX)?;
77+ let payload = base64.decode(body).ok()?;
78+ if payload.len() < NONCE_BYTES {
79+ return None;
80+ }
81+ let (nonce_bytes, ciphertext) = payload.split_at(NONCE_BYTES);
82+ let cipher = XChaCha20Poly1305::new(key.into());
83+ let nonce = XNonce::from_slice(nonce_bytes);
84+ let plaintext = cipher.decrypt(nonce, ciphertext).ok()?;
85+ String::from_utf8(plaintext).ok()
86+}
87+
88+/// Reads the key at `path`, generating and writing a fresh one (mode 0600,
89+/// where the platform has modes) if the file is not there yet.
90+///
91+/// Called once, at [`TursoStore::open`] — the key is loaded, not re-read per
92+/// query, so a corrupted key file is a boot-time failure, not a per-send one.
93+pub fn load_or_create_key(path: &Path) -> io::Result<Key> {
94+ match std::fs::read(path) {
95+ Ok(bytes) => {
96+ let key: Key = bytes.try_into().map_err(|bytes: Vec<u8>| {
97+ io::Error::new(
98+ io::ErrorKind::InvalidData,
99+ format!(
100+ "{} holds {} bytes, not the {KEY_BYTES} of a key",
101+ path.display(),
102+ bytes.len()
103+ ),
104+ )
105+ })?;
106+ Ok(key)
107+ }
108+ Err(e) if e.kind() == io::ErrorKind::NotFound => {
109+ let mut key = [0u8; KEY_BYTES];
110+ rand::rng().fill_bytes(&mut key);
111+ std::fs::write(path, key)?;
112+ restrict(path)?;
113+ Ok(key)
114+ }
115+ Err(e) => Err(e),
116+ }
117+}
118+
119+/// 0600 on a freshly written file holding key material or a live credential.
120+#[cfg(unix)]
121+pub fn restrict(path: &Path) -> io::Result<()> {
122+ use std::os::unix::fs::PermissionsExt;
123+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
124+}
125+
126+#[cfg(not(unix))]
127+pub fn restrict(_path: &Path) -> io::Result<()> {
128+ Ok(())
129+}
130+
131+#[cfg(test)]
132+mod tests {
133+ use super::*;
134+
135+ fn key() -> Key {
136+ let mut k = [0u8; KEY_BYTES];
137+ rand::rng().fill_bytes(&mut k);
138+ k
139+ }
140+
141+ #[test]
142+ fn roundtrip() {
143+ let k = key();
144+ let sealed = seal(&k, "hunter2");
145+ assert!(is_sealed(&sealed));
146+ assert_eq!(open(&k, &sealed).as_deref(), Some("hunter2"));
147+ }
148+
149+ #[test]
150+ fn tamper_fails() {
151+ let k = key();
152+ let mut sealed = seal(&k, "hunter2").into_bytes();
153+ let last = sealed.len() - 1;
154+ sealed[last] ^= 0x01;
155+ let sealed = String::from_utf8(sealed).unwrap();
156+ assert_eq!(open(&k, &sealed), None);
157+ }
158+
159+ #[test]
160+ fn wrong_key_fails() {
161+ let sealed = seal(&key(), "hunter2");
162+ assert_eq!(open(&key(), &sealed), None);
163+ }
164+
165+ #[test]
166+ fn non_envelope_fails() {
167+ let k = key();
168+ assert_eq!(open(&k, "hunter2"), None);
169+ assert_eq!(open(&k, ""), None);
170+ assert_eq!(open(&k, "v1:not-base64!!"), None);
171+ }
172+
173+ #[test]
174+ fn load_or_create_key_persists_and_restricts() {
175+ let dir = std::env::temp_dir().join(format!("in-key-test-{}", unique_suffix()));
176+ std::fs::create_dir_all(&dir).unwrap();
177+ let path = dir.join("in.key");
178+ let first = load_or_create_key(&path).unwrap();
179+ let second = load_or_create_key(&path).unwrap();
180+ assert_eq!(first, second, "a second open reuses the same key");
181+ #[cfg(unix)]
182+ {
183+ use std::os::unix::fs::PermissionsExt;
184+ let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
185+ assert_eq!(mode, 0o600);
186+ }
187+ let _ = std::fs::remove_dir_all(&dir);
188+ }
189+
190+ // A tiny stand-in so this module does not reach for the `ulid` crate just
191+ // to name a scratch directory.
192+ fn unique_suffix() -> u64 {
193+ use std::time::{SystemTime, UNIX_EPOCH};
194+ SystemTime::now()
195+ .duration_since(UNIX_EPOCH)
196+ .unwrap()
197+ .as_nanos() as u64
198+ }
199+}
crates/in-core/src/store/sniff.rsadded+366 -0
@@ -0,0 +1,366 @@
1+//! What uploaded bytes are, decided from the bytes themselves — never from a
2+//! part's `content_type()`, which is whatever the browser felt like sending.
3+//!
4+//! Pure `bytes -> mime`, with no I/O and nothing browser-shaped in it, living
5+//! behind the same `server` gate as the store it serves. The upload path
6+//! sniffs a file once when it arrives; [`TursoStore::open`] additionally runs
7+//! [`refine`] over rows whose stored type is one of the [`GENERIC_MIME_TYPES`]
8+//! buckets, so attachments written before the sniffer could name OOXML files
9+//! come out of the next restart carrying their real type. One definition
10+//! serves both callers: the store cannot reach the web crate, and a second
11+//! sniffer would drift.
12+
13+/// The mime types the upload path can store that name nothing: a zip that is
14+/// not an office document, bytes no magic matched, and an OLE container with
15+/// no stream name to narrow it. The boot pass reads only rows wearing one of
16+/// these; `text/plain` is deliberately absent — no window of a text file can
17+/// ever refine it, so sweeping it would read every text blob on every boot
18+/// for a guaranteed no-op.
19+pub const GENERIC_MIME_TYPES: &[&str] = &[
20+ "application/zip",
21+ "application/octet-stream",
22+ "application/x-ole-storage",
23+];
24+
25+/// Head bytes read per generic row: every prefix-magic format this sniffer
26+/// knows decides from the first bytes, an OpenDocument file's `mimetype`
27+/// entry is required to be the first thing in the file, and an OLE
28+/// container's directory sectors precede its stream data.
29+pub const HEAD_WINDOW: i64 = 64 * 1024;
30+/// Tail bytes read per generic row. A zip ends with its end-of-central-
31+/// directory record, which — comment included — can sit at most
32+/// 22 + 65535 bytes from the end of the file, so a tail this wide can never
33+/// miss it, and it usually holds much of the central directory besides.
34+pub const TAIL_WINDOW: i64 = 128 * 1024;
35+/// A central directory larger than this — tens of thousands of entries — is
36+/// left unread and the row left exactly as stored.
37+pub const DIRECTORY_CAP: i64 = 4 * 1024 * 1024;
38+
39+pub fn sniff(bytes: &[u8]) -> &'static str {
40+ if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
41+ "image/png"
42+ } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
43+ "image/jpeg"
44+ } else if bytes.starts_with(b"GIF8") {
45+ "image/gif"
46+ } else if bytes.starts_with(b"%PDF-") {
47+ "application/pdf"
48+ } else if bytes.starts_with(b"PK\x03\x04") {
49+ // Every OOXML and OpenDocument file is a zip; what kind it is lives in
50+ // the entry names, which a zip stores uncompressed. `xl/workbook.xml`
51+ // is the one part an xlsx cannot be without, an ods declares its
52+ // type in the `mimetype` entry the format requires be stored first,
53+ // and `ppt/presentation.xml` is the one part a pptx cannot be
54+ // without.
55+ zip_mime(bytes)
56+ } else if bytes.starts_with(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]) {
57+ // The pre-2007 OLE compound file .xls, .doc and .ppt all share. Its
58+ // directory holds stream names in UTF-16, and only a workbook carries
59+ // one called `Workbook` — a .doc or .ppt stays an unnamed container.
60+ if contains(bytes, b"W\0o\0r\0k\0b\0o\0o\0k\0") {
61+ "application/vnd.ms-excel"
62+ } else {
63+ "application/x-ole-storage"
64+ }
65+ } else if bytes.starts_with(&[0x1F, 0x8B]) {
66+ "application/gzip"
67+ } else if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" && &bytes[8..12] == b"avif" {
68+ "image/avif"
69+ } else if bytes.len() >= 12
70+ && &bytes[4..8] == b"ftyp"
71+ && matches!(
72+ &bytes[8..12],
73+ b"heic" | b"heix" | b"hevc" | b"heif" | b"mif1" | b"msf1"
74+ )
75+ {
76+ // Apple's HEIC container reuses the ISO-BMFF `ftyp` box video shares;
77+ // the brand at bytes 8..12 is what tells a photo from a video apart.
78+ "image/heic"
79+ } else if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" && &bytes[8..12] == b"qt " {
80+ "video/quicktime"
81+ } else if bytes.len() >= 8 && &bytes[4..8] == b"ftyp" {
82+ "video/mp4"
83+ } else if bytes.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) {
84+ "video/webm"
85+ } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP" {
86+ "image/webp"
87+ } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WAVE" {
88+ "audio/wav"
89+ } else if bytes.starts_with(b"fLaC") {
90+ "audio/flac"
91+ } else if bytes.starts_with(b"OggS") {
92+ "audio/ogg"
93+ } else if bytes.starts_with(b"ID3")
94+ || bytes.starts_with(&[0xFF, 0xFB])
95+ || bytes.starts_with(&[0xFF, 0xF3])
96+ || bytes.starts_with(&[0xFF, 0xF2])
97+ {
98+ "audio/mpeg"
99+ } else if std::str::from_utf8(bytes).is_ok() {
100+ "text/plain"
101+ } else {
102+ "application/octet-stream"
103+ }
104+}
105+
106+/// Which office document a zip's bytes declare, decided the way every reader
107+/// of the format does: by the entry names a zip stores uncompressed. Ends in
108+/// [`GENERIC_MIME_TYPES`]' zip bucket when the names name nothing.
109+fn zip_mime(bytes: &[u8]) -> &'static str {
110+ if contains(bytes, b"xl/workbook.xml") {
111+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
112+ } else if contains(bytes, b"opendocument.spreadsheet") {
113+ "application/vnd.oasis.opendocument.spreadsheet"
114+ } else if contains(bytes, b"ppt/presentation.xml") {
115+ "application/vnd.openxmlformats-officedocument.presentationml.presentation"
116+ } else {
117+ "application/zip"
118+ }
119+}
120+
121+/// Whether `haystack` holds `needle` anywhere in it. Used on zip bytes, where
122+/// the entry names sit in the clear even when the entries themselves do not.
123+fn contains(haystack: &[u8], needle: &[u8]) -> bool {
124+ haystack
125+ .windows(needle.len())
126+ .any(|window| window == needle)
127+}
128+
129+/// The office mime declared by the zip entry names in `bytes` — the central
130+/// directory's vocabulary, where every entry a file holds is listed. An
131+/// OpenDocument file is deliberately absent: its marker is the *content* of
132+/// the `mimetype` entry the format requires be stored first, not an entry
133+/// name, so it is decided from the head window and could never be found here.
134+pub(crate) fn office_entry_mime(bytes: &[u8]) -> Option<&'static str> {
135+ if contains(bytes, b"xl/workbook.xml") {
136+ Some("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
137+ } else if contains(bytes, b"ppt/presentation.xml") {
138+ Some("application/vnd.openxmlformats-officedocument.presentationml.presentation")
139+ } else {
140+ None
141+ }
142+}
143+
144+/// What one generic row's byte windows decided.
145+#[derive(Debug)]
146+pub(crate) enum Verdict {
147+ /// Nothing left to read. `Some` is a candidate more specific than the
148+ /// stored bucket (subject to [`refinement`]), `None` means the windows
149+ /// could not improve on what is stored — and, for a zip, never will:
150+ /// whatever the central directory says, the search already covered it.
151+ Settle(Option<&'static str>),
152+ /// A zip whose windows name no office part. `offset`/`size` locate the
153+ /// central directory as the end record states them; reading it is the
154+ /// last word, because every entry name the file has is listed there.
155+ ReadDirectory { offset: u64, size: u64 },
156+}
157+
158+/// Decides a generic row from its head and tail windows alone. When the
159+/// windows themselves hold a verdict it settles; only a zip with no office
160+/// marker in either window asks for the central directory.
161+pub(crate) fn refine(stored: &str, head: &[u8], tail: &[u8]) -> Verdict {
162+ let mut windows = Vec::with_capacity(head.len() + tail.len());
163+ windows.extend_from_slice(head);
164+ windows.extend_from_slice(tail);
165+ match sniff(&windows) {
166+ "application/zip" => match end_of_central_directory(tail) {
167+ Some((offset, size)) => Verdict::ReadDirectory { offset, size },
168+ None => Verdict::Settle(None),
169+ },
170+ candidate => Verdict::Settle(refinement(stored, Some(candidate))),
171+ }
172+}
173+
174+/// Whether `candidate` may replace `stored`: something specific, something
175+/// other than what is stored, and never `text/plain` — a window cannot prove
176+/// a whole blob is UTF-8, so a text verdict out of windows is unverifiable,
177+/// and a text row would gain nothing from the sweep anyway. Everything else
178+/// the sniffer names is either a prefix-magic fact (true of the whole blob
179+/// when true of its head) or an office marker, both safe to act on.
180+pub(crate) fn refinement(stored: &str, candidate: Option<&'static str>) -> Option<&'static str> {
181+ let candidate = candidate?;
182+ if candidate == stored
183+ || candidate == "text/plain"
184+ || GENERIC_MIME_TYPES.contains(&candidate)
185+ {
186+ return None;
187+ }
188+ Some(candidate)
189+}
190+
191+/// The end-of-central-directory record every zip ends with: `PK\x05\x06`,
192+/// then the directory's size (12..16) and offset (16..20), then a comment
193+/// whose declared length must land exactly at the end of the bytes. Scanning
194+/// from the end, the first signature satisfying that anchor is the record.
195+/// `None` when there is none to trust: no record at all, or a zip64 one —
196+/// the `u32::MAX` sentinels say the real numbers live in a zip64 locator
197+/// this pass declines to parse, and a row it declines stays as stored.
198+pub(crate) fn end_of_central_directory(tail: &[u8]) -> Option<(u64, u64)> {
199+ if tail.len() < 22 {
200+ return None;
201+ }
202+ for i in (0..=tail.len() - 22).rev() {
203+ if &tail[i..i + 4] != b"PK\x05\x06" {
204+ continue;
205+ }
206+ let comment = u16::from_le_bytes([tail[i + 20], tail[i + 21]]) as usize;
207+ if i + 22 + comment != tail.len() {
208+ continue;
209+ }
210+ let size = u32::from_le_bytes(tail[i + 12..i + 16].try_into().ok()?) as u64;
211+ let offset = u32::from_le_bytes(tail[i + 16..i + 20].try_into().ok()?) as u64;
212+ if offset == u32::MAX as u64 || size == u32::MAX as u64 {
213+ return None;
214+ }
215+ return Some((offset, size));
216+ }
217+ None
218+}
219+
220+#[cfg(test)]
221+mod tests {
222+ use super::*;
223+
224+ #[test]
225+ fn sniffs_the_magic_numbers() {
226+ assert_eq!(sniff(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A]), "image/png");
227+ assert_eq!(sniff(&[0xFF, 0xD8, 0xFF, 0xE0]), "image/jpeg");
228+ assert_eq!(sniff(b"hello, this is plainly text"), "text/plain");
229+ assert_eq!(
230+ sniff(&[0x00, 0x01, 0xFE, 0xFF, 0x02]),
231+ "application/octet-stream"
232+ );
233+ }
234+
235+ #[test]
236+ fn sniffs_the_media_types() {
237+ assert_eq!(
238+ sniff(b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00"),
239+ "video/mp4"
240+ );
241+ assert_eq!(
242+ sniff(b"\x00\x00\x00\x18ftypavif\x00\x00\x00\x00"),
243+ "image/avif"
244+ );
245+ assert_eq!(
246+ sniff(b"\x00\x00\x00\x18ftypheic\x00\x00\x00\x00"),
247+ "image/heic"
248+ );
249+ assert_eq!(
250+ sniff(b"\x00\x00\x00\x18ftypmif1\x00\x00\x00\x00"),
251+ "image/heic"
252+ );
253+ assert_eq!(
254+ sniff(b"\x00\x00\x00\x14ftypqt \x00\x00\x00\x00"),
255+ "video/quicktime"
256+ );
257+ assert_eq!(sniff(&[0x1A, 0x45, 0xDF, 0xA3, 0x00, 0x00]), "video/webm");
258+ assert_eq!(sniff(b"RIFF\x00\x00\x00\x00WEBPVP8 "), "image/webp");
259+ assert_eq!(sniff(b"RIFF\x00\x00\x00\x00WAVEfmt "), "audio/wav");
260+ assert_eq!(sniff(b"fLaC\x00\x00\x00\x00"), "audio/flac");
261+ assert_eq!(sniff(b"OggS\x00\x00\x00\x00"), "audio/ogg");
262+ assert_eq!(sniff(b"ID3\x03\x00\x00\x00"), "audio/mpeg");
263+ assert_eq!(sniff(&[0xFF, 0xFB, 0x90, 0x00]), "audio/mpeg");
264+ }
265+
266+ /// A zip of the named entries, bytes inside irrelevant: the sniff reads
267+ /// the entry names a zip stores uncompressed.
268+ fn zip_with(names: &[&str]) -> Vec<u8> {
269+ use std::io::Write as _;
270+ let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
271+ for name in names {
272+ zip.start_file(*name, zip::write::SimpleFileOptions::default())
273+ .unwrap();
274+ zip.write_all(b"<xml/>").unwrap();
275+ }
276+ zip.finish().unwrap().into_inner()
277+ }
278+
279+ #[test]
280+ fn a_presentation_sniffs_its_presentation_mime_and_a_plain_zip_stays_a_zip() {
281+ let pptx = zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]);
282+ assert_eq!(
283+ sniff(&pptx),
284+ "application/vnd.openxmlformats-officedocument.presentationml.presentation"
285+ );
286+ assert_eq!(sniff(&zip_with(&["notes.txt"])), "application/zip");
287+ }
288+
289+ #[test]
290+ fn a_workbook_declared_only_in_its_central_directory_is_found_by_the_directory_search() {
291+ let bytes = zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]);
292+ let head = &bytes[..bytes.len() / 2];
293+ // Both windows of a cut in half hold the marker, so the windows alone
294+ // settle a small file.
295+ assert!(contains(head, b"ppt/presentation.xml"));
296+ match refine("application/zip", head, &bytes[bytes.len() / 2..]) {
297+ Verdict::Settle(Some(
298+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
299+ )) => {}
300+ other => panic!("expected a settled presentation, got {other:?}"),
301+ }
302+ // The real end record survives its move into the synthetic tail.
303+ let (offset, size) = end_of_central_directory(&bytes).expect("a real zip has an EOCD");
304+ let directory = &bytes[offset as usize..(offset + size) as usize];
305+ assert_eq!(
306+ office_entry_mime(directory),
307+ Some("application/vnd.openxmlformats-officedocument.presentationml.presentation")
308+ );
309+ }
310+
311+ #[test]
312+ fn an_eocd_is_found_by_its_anchor_and_declined_when_zip64_or_absent() {
313+ // A hand-built record: signature, the two disk fields, two entry
314+ // counts, size, offset, a one-byte comment.
315+ let mut tail = Vec::new();
316+ tail.extend_from_slice(b"PK\x05\x06");
317+ tail.extend_from_slice(&[0, 0, 0, 0]); // disk numbers
318+ tail.extend_from_slice(&[1, 0, 1, 0]); // entry counts
319+ tail.extend_from_slice(&0x1122_3344u32.to_le_bytes()); // size
320+ tail.extend_from_slice(&0x5566_7788u32.to_le_bytes()); // offset
321+ tail.extend_from_slice(&1u16.to_le_bytes()); // comment length
322+ tail.push(b'!');
323+ assert_eq!(
324+ end_of_central_directory(&tail),
325+ Some((0x5566_7788, 0x1122_3344))
326+ );
327+ // A lie about the comment length leaves the record unanchored.
328+ let mut drifting = tail.clone();
329+ *drifting.last_mut().unwrap() = b'?';
330+ drifting.push(b'!');
331+ assert_eq!(end_of_central_directory(&drifting), None);
332+ // zip64 sentinels are declined rather than mis-read.
333+ let mut zip64 = tail.clone();
334+ zip64[16..20].copy_from_slice(&u32::MAX.to_le_bytes());
335+ assert_eq!(end_of_central_directory(&zip64), None);
336+ // No record, no verdict.
337+ assert_eq!(end_of_central_directory(b"PK\x03\x04 not a tail"), None);
338+ assert_eq!(end_of_central_directory(&[]), None);
339+ }
340+
341+ #[test]
342+ fn a_refinement_must_be_specific_different_and_never_text() {
343+ assert_eq!(refinement("application/zip", Some("image/png")), Some("image/png"));
344+ assert_eq!(refinement("image/png", Some("image/png")), None, "no rewrite of the same value");
345+ assert_eq!(refinement("application/zip", Some("text/plain")), None, "windows cannot prove text");
346+ assert_eq!(refinement("application/zip", Some("application/zip")), None, "never narrowed");
347+ assert_eq!(refinement("application/zip", Some("application/octet-stream")), None);
348+ assert_eq!(refinement("application/zip", None), None);
349+ }
350+
351+ #[test]
352+ fn an_opendocument_file_is_decided_from_the_head_window_alone() {
353+ // The format requires the `mimetype` entry first, stored
354+ // uncompressed: its marker is the first thing in the file.
355+ let head = b"PK\x03\x04\x08\x00\x00\x00mimetypeapplication/vnd.oasis.opendocument.spreadsheet";
356+ match refine("application/zip", head, b"") {
357+ Verdict::Settle(Some(
358+ "application/vnd.oasis.opendocument.spreadsheet",
359+ )) => {}
360+ other => panic!("expected a settled spreadsheet, got {other:?}"),
361+ }
362+ // And the directory search, which reads entry names only, never
363+ // claims one — the marker is entry content, not an entry name.
364+ assert_eq!(office_entry_mime(head), None);
365+ }
366+}
crates/in-core/src/store/turso_store.rsadded+2888 -0

Diff too large; view file

@@ -0,0 +1,2888 @@
1+//! Turso implementation of [`Store`].
2+//!
3+//! Turso is in-process and SQLite-compatible, so the schema is plain SQL and
4+//! there is no server to run alongside the binary. It ships no migration
5+//! runner of its own; [`TursoStore::open`] applies the numbered files in
6+//! `crates/in-core/migrations` at boot and verifies the result.
7+
8+use async_trait::async_trait;
9+use rand::Rng;
10+use time::format_description::well_known::Rfc3339;
11+use time::OffsetDateTime;
12+use turso::transaction::{Transaction, TransactionBehavior};
13+use turso::{Builder, Connection, Row, params};
14+use ulid::Ulid;
15+
16+use super::secret;
17+use super::{
18+ CHUNK_SIZE, CreatedLink, File, Folder, Listing, Result, ShareKind, ShareLink, SharedItem,
19+ Store, StoreError, ThumbState, UPLOAD_TTL_HOURS, UploadSession, UploadState, User,
20+};
21+use super::{ReconcileOptions, reconcile, schema, sniff};
22+use crate::live::{Change, Topic};
23+use crate::thumbs;
24+
25+/// Where one file's bytes live: `<storage>/files/<id>`, named by the row's
26+/// own id. What an upload carried never decides a path here — the name is
27+/// always store-made, so `name` stays a label.
28+const FILES_DIR: &str = "files";
29+/// Where thumbnails live: `<storage>/thumbs/<id>`, webp, longest edge 512.
30+const THUMBS_DIR: &str = "thumbs";
31+/// Where upload chunks stage: `<storage>/uploads/<session-id>/<n>`.
32+const UPLOADS_DIR: &str = "uploads";
33+
34+/// Thumbnails are attempted only below this source size: 64 MiB. Past it the
35+/// row wears `failed` rather than pinning memory the size of the file.
36+const THUMB_SOURCE_CAP: u64 = 64 * 1024 * 1024;
37+
38+const USER_COLUMNS: &str =
39+ "id, oidc_sub, email, display_name, admin, disabled, quota_bytes, used_bytes, created_at, last_seen_at";
40+const FOLDER_COLUMNS: &str = "id, owner_id, parent_id, name, created_at, deleted_at";
41+const FILE_COLUMNS: &str =
42+ "id, owner_id, folder_id, name, mime, size_bytes, thumb_state, created_at, updated_at, deleted_at";
43+const LINK_COLUMNS: &str =
44+ "id, token_hash, kind, target_id, created_by, can_download, created_at, expires_at, revoked_at";
45+const SESSION_COLUMNS: &str =
46+ "id, owner_id, folder_id, name, size_bytes, chunk_size, received_bytes, state, created_at, expires_at";
47+
48+pub struct TursoStore {
49+ /// Shared by every single-statement call. Turso serialises statements on a
50+ /// connection, so this is safe; transactions are the exception and take a
51+ /// connection of their own.
52+ conn: tokio::sync::Mutex<Connection>,
53+ db: turso::Database,
54+ /// Where committed writes are announced. Held as the sender so the store
55+ /// can hand out a receiver per subscriber; nothing is ever read from here
56+ /// by the store itself.
57+ live: tokio::sync::broadcast::Sender<Change>,
58+ /// Root of the file tree the binary payloads live under: `files/` for
59+ /// file bytes, `thumbs/` for thumbnails, `uploads/` for staged chunks —
60+ /// one raw file per row, named by the row's own id. The database keeps
61+ /// the facts and this tree keeps the bytes; a boot sweep deletes
62+ /// whichever half outlives the other.
63+ storage: std::path::PathBuf,
64+}
65+
66+impl TursoStore {
67+ /// Announces a committed write. Called only once the write is durable —
68+ /// after commit for a transaction, and never on a path that returned an
69+ /// error — because a subscriber's whole job is to re-read, and waking it
70+ /// before the row lands makes it read the past.
71+ ///
72+ /// A send with no subscribers returns `Err`, which is the ordinary state
73+ /// of a server nobody is looking at. It is dropped on purpose: an
74+ /// announcement nobody is waiting for is not a problem, and logging it
75+ /// would fill the log with the sound of an idle app.
76+ fn announce(&self, topics: impl IntoIterator<Item = Topic>) {
77+ for topic in topics {
78+ let _ = self.live.send(Change {
79+ topic,
80+ seq: crate::live::next_seq(),
81+ });
82+ }
83+ }
84+
85+ /// Opens (creating if needed) the database at `path` and brings it up to
86+ /// date. `storage` is the root of the file tree the binary payloads live
87+ /// under — created here if missing, derived to sit beside the database
88+ /// when `None`.
89+ ///
90+ /// The boot, in order: create the storage tree, rebuild a stale database
91+ /// before any long-lived handle opens it, migrate an empty one, abort
92+ /// upload sessions past their expiry, and sweep files no row names.
93+ /// Trash is never purged here — see the note on the sweep below.
94+ pub async fn open(database: &str, storage: Option<&std::path::Path>) -> Result<Self> {
95+ let storage_buf;
96+ let storage: &std::path::Path = match storage {
97+ Some(dir) => dir,
98+ None => {
99+ // Beside the database: the two are one backup unit, so the
100+ // default keeps them siblings.
101+ storage_buf = default_storage(database);
102+ &storage_buf
103+ }
104+ };
105+ // Before anything else, including the reconcile below that may need
106+ // this tree: a fresh storage path is a normal first boot, and every
107+ // writer past this point assumes the tree is there.
108+ ensure_storage_dirs(storage)?;
109+ let existed = database != ":memory:" && std::path::Path::new(database).exists();
110+ // Before anything holds this file open: a database of an older shape
111+ // is rebuilt now, while no handle of ours points at the file that the
112+ // rebuild is about to replace.
113+ Self::repair_if_stale(database, storage).await?;
114+ let db = Builder::new_local(database).build().await.map_err(backend)?;
115+ let conn = db.connect().map_err(backend)?;
116+ // Turso is a single-writer engine. Two connections on one Database
117+ // handle serialise by themselves, but a second handle on the same file
118+ // (a second process, or a careless second open) fails outright with
119+ // "database is locked" and silently drops the write unless a busy
120+ // timeout is set. Both pragmas are set on every connection we hand out.
121+ for pragma in ["PRAGMA foreign_keys = ON", "PRAGMA busy_timeout = 5000"] {
122+ conn.execute(pragma, ()).await.map_err(backend)?;
123+ }
124+ // The database file sits beside other local users; 0600 right after
125+ // creation closes the window between "file exists" and "file is ours
126+ // alone" — a WAL file, if this engine leaves one beside the main
127+ // file, gets the same restriction while it's still there to restrict.
128+ if !existed && database != ":memory:" {
129+ restrict_if_present(std::path::Path::new(database))?;
130+ restrict_if_present(&sibling(database, "-wal"))?;
131+ restrict_if_present(&sibling(database, "-shm"))?;
132+ }
133+ // 256 is deep enough that a client which pauses for a moment catches
134+ // up without noticing, and shallow enough that one wedged subscriber
135+ // cannot pin an unbounded backlog. Overflowing it is not a failure:
136+ // the reader is told it lagged and resyncs, which is cheaper than the
137+ // memory a larger buffer would cost to avoid saying so.
138+ let (live, _) = tokio::sync::broadcast::channel(256);
139+ let store = Self {
140+ conn: tokio::sync::Mutex::new(conn),
141+ db,
142+ live,
143+ storage: storage.to_path_buf(),
144+ };
145+ store.migrate(database).await?;
146+ store.prune_expired_uploads(OffsetDateTime::now_utc()).await?;
147+ // Trash is deliberately NOT purged here: the age cutoff is the
148+ // deployment's `purge_after_days`, which this signature never sees.
149+ // The server calls `purge_expired` with its configured cutoff right
150+ // after opening; this boot only aborts expired uploads and sweeps
151+ // files no row names.
152+ store.sweep_orphan_files().await?;
153+ // The file may have been rebuilt from a backup; its permissions and
154+ // any transient WAL/SHM siblings should still be private.
155+ if database != ":memory:" {
156+ restrict_if_present(std::path::Path::new(database))?;
157+ restrict_if_present(&sibling(database, "-wal"))?;
158+ restrict_if_present(&sibling(database, "-shm"))?;
159+ }
160+ Ok(store)
161+ }
162+
163+ /// Sets the storage tree against the database, once per boot. The
164+ /// database and the tree are two halves of one state, and a crash between
165+ /// a row write and its file write — either order — leaves exactly one
166+ /// half behind. A file no row names goes, including a `.tmp` a crash
167+ /// abandoned mid-write and a staged chunk whose session is gone; a row
168+ /// whose file is gone is only said out loud and otherwise kept, because
169+ /// deleting the row would turn a lost file into a lost fact — the row is
170+ /// still what screens list, and a re-upload replaces it cleanly.
171+ async fn sweep_orphan_files(&self) -> Result<()> {
172+ let conn = self.conn.lock().await;
173+ let files = known_ids(&conn, "SELECT id FROM file").await?;
174+ let thumbs = known_ids(
175+ &conn,
176+ "SELECT id FROM file WHERE thumb_state = 'ready'",
177+ )
178+ .await?;
179+ let sessions = known_ids(
180+ &conn,
181+ "SELECT id FROM upload_session WHERE state = 'active'",
182+ )
183+ .await?;
184+ drop(conn);
185+ for (dir, known, kind) in [
186+ (self.storage.join(FILES_DIR), &files, "file"),
187+ (self.storage.join(THUMBS_DIR), &thumbs, "thumbnail"),
188+ ] {
189+ for id in known.iter() {
190+ if !dir.join(id).is_file() {
191+ eprintln!("{kind} {id} names a file that is not there");
192+ }
193+ }
194+ let entries = match std::fs::read_dir(&dir) {
195+ Ok(entries) => entries,
196+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
197+ Err(e) => return Err(backend(e)),
198+ };
199+ for entry in entries {
200+ let entry = entry.map_err(backend)?;
201+ let path = entry.path();
202+ if !path.is_file() {
203+ continue;
204+ }
205+ let named = entry
206+ .file_name()
207+ .to_str()
208+ .is_some_and(|n| known.contains(n));
209+ if !named && let Err(e) = std::fs::remove_file(&path) {
210+ eprintln!(
211+ "could not delete orphaned storage file {}: {e}",
212+ path.display()
213+ );
214+ }
215+ }
216+ }
217+ // A staged-chunk directory outlives its session only through a crash
218+ // between the session write and the first chunk, or a removed session
219+ // row — either way nothing will ever finish it, so it goes.
220+ let uploads = self.storage.join(UPLOADS_DIR);
221+ let entries = match std::fs::read_dir(&uploads) {
222+ Ok(entries) => entries,
223+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
224+ Err(e) => return Err(backend(e)),
225+ };
226+ for entry in entries {
227+ let entry = entry.map_err(backend)?;
228+ let path = entry.path();
229+ if !path.is_dir() {
230+ continue;
231+ }
232+ let named = entry
233+ .file_name()
234+ .to_str()
235+ .is_some_and(|n| sessions.contains(n));
236+ if !named && let Err(e) = std::fs::remove_dir_all(&path) {
237+ eprintln!(
238+ "could not delete orphaned upload directory {}: {e}",
239+ path.display()
240+ );
241+ }
242+ }
243+ Ok(())
244+ }
245+
246+ /// Brings the database to the declared schema.
247+ ///
248+ /// - An empty database is created from the migrations.
249+ /// - A database that already matches the declared schema is left alone.
250+ /// - A stale database is backed up, rebuilt, and re-verified once.
251+ /// If the rebuilt database still does not match, the process stops
252+ /// with the original backed up and untouched.
253+ ///
254+ /// SQLite's DDL is transactional, so a schema that dies halfway leaves
255+ /// nothing behind: a half-created database is a boot that starts over,
256+ /// not a database with a hole in it.
257+ async fn migrate(&self, path: &str) -> Result<()> {
258+ let conn = self.conn.lock().await;
259+ let mut rows = conn
260+ .query(
261+ "SELECT COUNT(*) FROM sqlite_master \
262+ WHERE type = 'table' AND name NOT LIKE 'sqlite_%'",
263+ (),
264+ )
265+ .await
266+ .map_err(backend)?;
267+
268+ let empty = match rows.next().await.map_err(backend)? {
269+ Some(row) => row.get::<i64>(0).map_err(backend)? == 0,
270+ None => true,
271+ };
272+ drop(rows);
273+
274+ if empty {
275+ conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?;
276+ if let Err(e) = conn.execute_batch(&super::schema::schema_sql()).await {
277+ let _ = conn.execute("ROLLBACK", ()).await;
278+ return Err(backend(e));
279+ }
280+ return conn
281+ .execute("COMMIT", ())
282+ .await
283+ .map_err(backend)
284+ .map(|_| ());
285+ }
286+
287+ if path == ":memory:" {
288+ // Tests own an in-memory database; its schema is whatever the
289+ // test created, and the open should not try to reconcile it.
290+ return Ok(());
291+ }
292+
293+ // `repair_if_stale` ran before this handle was ever opened, so by now
294+ // the file on disk matches. Saying so here is cheap and turns a
295+ // reordering mistake into a refusal to start rather than a store
296+ // running against a schema the code does not expect.
297+ let have = schema::fingerprint(&conn).await.map_err(backend)?;
298+ let want = schema::declared_fingerprint().await.map_err(backend)?;
299+ if have != want {
300+ return Err(StoreError::Backend(format!(
301+ "database does not match the declared schema and was not repaired; \
302+ do not restart. diff:\n{}",
303+ schema::diff_report(&have, &want)
304+ )));
305+ }
306+ Ok(())
307+ }
308+
309+ /// Brings a database of an older shape onto the declared schema, BEFORE
310+ /// any long-lived handle is opened on it.
311+ ///
312+ /// The order matters and is the whole reason this is not part of
313+ /// `migrate`: `reconcile` swaps a rebuilt file into place, so a
314+ /// `turso::Database` opened beforehand still refers to the file that is
315+ /// now the backup. Reconnecting such a handle reads the old database and
316+ /// makes a successful rebuild look like a failed one.
317+ async fn repair_if_stale(path: &str, storage: &std::path::Path) -> Result<()> {
318+ if path == ":memory:" || !std::path::Path::new(path).exists() {
319+ return Ok(());
320+ }
321+ let (have, empty) = {
322+ let db = Builder::new_local(path).build().await.map_err(backend)?;
323+ let conn = db.connect().map_err(backend)?;
324+ let mut rows = conn
325+ .query(
326+ "SELECT COUNT(*) FROM sqlite_master \
327+ WHERE type = 'table' AND name NOT LIKE 'sqlite_%'",
328+ (),
329+ )
330+ .await
331+ .map_err(backend)?;
332+ let empty = match rows.next().await.map_err(backend)? {
333+ Some(row) => row.get::<i64>(0).map_err(backend)? == 0,
334+ None => true,
335+ };
336+ drop(rows);
337+ let have = if empty {
338+ String::new()
339+ } else {
340+ schema::fingerprint(&conn).await.map_err(backend)?
341+ };
342+ (have, empty)
343+ };
344+ if empty {
345+ return Ok(());
346+ }
347+ let want = schema::declared_fingerprint().await.map_err(backend)?;
348+ if have == want {
349+ return Ok(());
350+ }
351+
352+ eprintln!(
353+ "database schema differs from the declared schema; rebuilding automatically\n{}",
354+ schema::diff_report(&have, &want)
355+ );
356+ reconcile(
357+ path,
358+ Some(storage),
359+ ReconcileOptions {
360+ dry_run: false,
361+ yes: false,
362+ auto: true,
363+ },
364+ )
365+ .await?;
366+
367+ // Check the result once, on a handle opened after the swap. A
368+ // normalisation bug that rebuilt forever would otherwise write a
369+ // full-size backup on every restart until the disk filled.
370+ let db = Builder::new_local(path).build().await.map_err(backend)?;
371+ let conn = db.connect().map_err(backend)?;
372+ let after = schema::fingerprint(&conn).await.map_err(backend)?;
373+ if after != want {
374+ return Err(StoreError::Backend(format!(
375+ "rebuild did not match the declared schema; the original is backed up beside it \
376+ and this is not retried. diff:\n{}",
377+ schema::diff_report(&after, &want)
378+ )));
379+ }
380+ Ok(())
381+ }
382+
383+ /// A connection of its own, for work that opens a transaction.
384+ /// `Connection::transaction` takes `&mut self`, and a transaction on the
385+ /// shared connection would swallow everyone else's statements.
386+ async fn tx_conn(&self) -> Result<Connection> {
387+ let conn = self.db.connect().map_err(backend)?;
388+ for pragma in ["PRAGMA foreign_keys = ON", "PRAGMA busy_timeout = 5000"] {
389+ conn.execute(pragma, ()).await.map_err(backend)?;
390+ }
391+ Ok(conn)
392+ }
393+
394+ async fn one_row(&self, sql: &str, args: impl turso::IntoParams) -> Result<Option<Row>> {
395+ let conn = self.conn.lock().await;
396+ let mut rows = conn.query(sql, args).await.map_err(backend)?;
397+ rows.next().await.map_err(backend)
398+ }
399+}
400+
401+/// Recomputes one account's usage from the rows: the sum of every file size
402+/// it holds, trashed or not. Runs inside the caller's transaction, so the
403+/// mutation and the total commit as one — usage can never drift from the
404+/// rows, because it is never carried anywhere except from them.
405+async fn refresh_usage(conn: &Connection, owner_id: &str) -> Result<()> {
406+ conn.execute(
407+ "UPDATE user SET used_bytes = \
408+ (SELECT COALESCE(SUM(size_bytes), 0) FROM file WHERE owner_id = ?1) \
409+ WHERE id = ?1",
410+ params![owner_id],
411+ )
412+ .await
413+ .map_err(backend)?;
414+ Ok(())
415+}
416+
417+/// Refuses the write while there is still nothing on disk to clean up: the
418+/// owner's used bytes plus `extra` must fit the ceiling.
419+async fn check_quota(conn: &Connection, owner_id: &str) -> Result<(u64, u64)> {
420+ let mut rows = conn
421+ .query(
422+ "SELECT quota_bytes, used_bytes FROM user WHERE id = ?1",
423+ params![owner_id],
424+ )
425+ .await
426+ .map_err(backend)?;
427+ match rows.next().await.map_err(backend)? {
428+ Some(row) => {
429+ let quota = row.get::<i64>(0).map_err(backend)?.max(0) as u64;
430+ let used = row.get::<i64>(1).map_err(backend)?.max(0) as u64;
431+ Ok((quota, used))
432+ }
433+ None => Err(StoreError::NotFound),
434+ }
435+}
436+
437+fn fit_quota(quota: u64, used: u64, extra: u64) -> Result<()> {
438+ // A zero-byte write costs nothing, so it always fits — even under an
439+ // account whose quota was lowered below current usage, which must still
440+ // be able to trash and rearrange.
441+ if extra > 0 && used.saturating_add(extra) > quota {
442+ return Err(StoreError::QuotaExceeded);
443+ }
444+ Ok(())
445+}
446+
447+/// The label an uploaded or typed name becomes: the last path segment, with
448+/// control characters stripped and surrounding whitespace trimmed. A name
449+/// that is a path (`../../etc`) is a valid file name and a terrible path, so
450+/// only the tail survives; a name that sanitises to nothing becomes
451+/// `Untitled` rather than failing the upload.
452+pub(crate) fn label_of(name: &str) -> String {
453+ let base = name.rsplit(['/', '\\']).next().unwrap_or(name);
454+ let clean: String = base.chars().filter(|c| !c.is_control()).collect();
455+ let trimmed = clean.trim().to_string();
456+ if trimmed.is_empty() {
457+ "Untitled".to_string()
458+ } else {
459+ trimmed
460+ }
461+}
462+
463+/// Addresses match case-insensitively: the provider may capitalise what
464+/// the row stored, so both sides fold before comparing. Provisioning folds
465+/// on the way in, and every lookup folds the question.
466+fn fold_email(email: &str) -> String {
467+ email.trim().to_lowercase()
468+}
469+
470+/// Escapes a substring search for LIKE: backslash first, then the two
471+/// wildcards, so `100%` searches for a percent rather than everything.
472+fn like_pattern(query: &str) -> String {
473+ let mut out = String::with_capacity(query.len() + 2);
474+ out.push('%');
475+ for c in query.chars() {
476+ if matches!(c, '\\' | '%' | '_') {
477+ out.push('\\');
478+ }
479+ out.push(c);
480+ }
481+ out.push('%');
482+ out
483+}
484+
485+/// A fresh public-link token: 32 random bytes, base64url without padding.
486+/// Shown once at creation; only its hash is stored.
487+fn new_token() -> String {
488+ use base64::Engine as _;
489+ let mut bytes = [0u8; 32];
490+ rand::rng().fill_bytes(&mut bytes);
491+ base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)
492+}
493+
494+/// The token's hash, as stored: base64url SHA-256. Constant-length and
495+/// content-hiding — the row answers equality and nothing else.
496+///
497+/// Public because resolving is by hash: the route holding the plaintext token
498+/// hashes it with this and calls [`Store::resolve_share_link`]. The two must
499+/// never disagree about the function, so there is exactly one.
500+pub fn hash_share_token(token: &str) -> String {
501+ use base64::Engine as _;
502+ use sha2::Digest as _;
503+ base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sha2::Sha256::digest(token.as_bytes()))
504+}
505+/// zero-byte upload has no chunks; its finish assembles the empty file.
506+fn chunk_count(size_bytes: u64) -> u64 {
507+ if size_bytes == 0 {
508+ 0
509+ } else {
510+ size_bytes.div_ceil(CHUNK_SIZE)
511+ }
512+}
513+
514+/// The exact bytes chunk `index` must carry: full [`CHUNK_SIZE`] except the
515+/// final one, which carries the remainder.
516+fn expected_chunk_len(size_bytes: u64, index: u64) -> u64 {
517+ let full_before = index.saturating_mul(CHUNK_SIZE);
518+ (size_bytes.saturating_sub(full_before)).min(CHUNK_SIZE)
519+}
520+
521+/// Where file `id`'s bytes live.
522+fn file_path(storage: &std::path::Path, id: &str) -> std::path::PathBuf {
523+ storage.join(FILES_DIR).join(id)
524+}
525+
526+/// Where `id`'s thumbnail lives.
527+fn thumb_path(storage: &std::path::Path, id: &str) -> std::path::PathBuf {
528+ storage.join(THUMBS_DIR).join(id)
529+}
530+
531+/// Where session `id`'s chunks stage.
532+fn session_dir(storage: &std::path::Path, id: &str) -> std::path::PathBuf {
533+ storage.join(UPLOADS_DIR).join(id)
534+}
535+
536+/// Where chunk `index` of session `id` stages.
537+fn chunk_path(
538+ storage: &std::path::Path,
539+ id: &str,
540+ index: u64,
541+) -> std::path::PathBuf {
542+ session_dir(storage, id).join(index.to_string())
543+}
544+
545+/// The staged bytes a session holds, summed from the chunk files on disk —
546+/// never from a counter a re-sent chunk could have double-counted.
547+fn staged_received(storage: &std::path::Path, id: &str) -> u64 {
548+ let mut total = 0u64;
549+ let dir = session_dir(storage, id);
550+ let entries = match std::fs::read_dir(&dir) {
551+ Ok(entries) => entries,
552+ Err(_) => return 0,
553+ };
554+ for entry in entries.flatten() {
555+ if entry.path().is_file() {
556+ total = total.saturating_add(entry.metadata().map(|m| m.len()).unwrap_or(0));
557+ }
558+ }
559+ total
560+}
561+/// Creates the storage tree — the root and one directory per payload kind —
562+/// and locks each to 0700 on unix. Every writer past `open` assumes the tree
563+/// is there.
564+fn ensure_storage_dirs(storage: &std::path::Path) -> Result<()> {
565+ for dir in [
566+ storage.to_path_buf(),
567+ storage.join(FILES_DIR),
568+ storage.join(THUMBS_DIR),
569+ storage.join(UPLOADS_DIR),
570+ ] {
571+ std::fs::create_dir_all(&dir)
572+ .map_err(|e| StoreError::Backend(format!("could not create {}: {e}", dir.display())))?;
573+ restrict_dir(&dir)?;
574+ }
575+ Ok(())
576+}
577+
578+/// 0700 on a directory holding someone's files.
579+#[cfg(unix)]
580+fn restrict_dir(path: &std::path::Path) -> Result<()> {
581+ use std::os::unix::fs::PermissionsExt as _;
582+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).map_err(backend)?;
583+ Ok(())
584+}
585+
586+#[cfg(not(unix))]
587+fn restrict_dir(_path: &std::path::Path) -> Result<()> {
588+ Ok(())
589+}
590+
591+/// Where binary files live when no storage directory is handed in: beside
592+/// the database file. The two are one backup unit — a backup that takes the
593+/// database but not the files beside it restores a drive whose contents are
594+/// gone — so the default keeps them siblings.
595+fn default_storage(database: &str) -> std::path::PathBuf {
596+ std::path::Path::new(database)
597+ .parent()
598+ .map(|parent| parent.join("storage"))
599+ .unwrap_or_else(|| std::path::PathBuf::from("storage"))
600+}
601+
602+/// Writes `bytes` to `path` through a temp name in the same directory and a
603+/// rename, so a reader of the final name never sees a partial file — and a
604+/// crash mid-write leaves a temp name the boot sweep deletes rather than a
605+/// half file wearing a real one. The caller owns what happens next: the row
606+/// goes in after, and a failed row write unlinks this file best-effort.
607+fn write_file_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
608+ use std::io::Write as _;
609+ let tmp = path.with_extension(format!("{}.tmp", Ulid::new()));
610+ let mut file = std::fs::File::create(&tmp)?;
611+ file.write_all(bytes)?;
612+ file.flush()?;
613+ match std::fs::rename(&tmp, path) {
614+ Ok(()) => Ok(()),
615+ Err(err) => {
616+ let _ = std::fs::remove_file(&tmp);
617+ Err(err)
618+ }
619+ }
620+}
621+
622+/// Reads up to `buf.len()` bytes from the start of the file at `path`. What
623+/// the sniffer and the thumbnailer decide from when the whole file is not
624+/// yet — or not affordably — in memory.
625+fn read_up_to(path: &std::path::Path, buf: &mut [u8]) -> std::io::Result<usize> {
626+ use std::io::Read as _;
627+ let mut file = std::fs::File::open(path)?;
628+ let mut filled = 0;
629+ while filled < buf.len() {
630+ match file.read(&mut buf[filled..])? {
631+ 0 => break,
632+ n => filled += n,
633+ }
634+ }
635+ Ok(filled)
636+}
637+
638+/// Every id `sql` hands back — the set of files the sweep must keep.
639+async fn known_ids(conn: &Connection, sql: &str) -> Result<std::collections::HashSet<String>> {
640+ let mut rows = conn.query(sql, ()).await.map_err(backend)?;
641+ let mut out = std::collections::HashSet::new();
642+ while let Some(row) = rows.next().await.map_err(backend)? {
643+ out.insert(row.get::<String>(0).map_err(backend)?);
644+ }
645+ Ok(out)
646+}
647+
648+/// A database sidecar (`in.db-wal`, `in.db-shm`): the file beside the main
649+/// one, wearing the same name plus the suffix.
650+fn sibling(path: &str, suffix: &str) -> std::path::PathBuf {
651+ let base = std::path::Path::new(path);
652+ let mut name = base
653+ .file_name()
654+ .map(|n| n.to_os_string())
655+ .unwrap_or_default();
656+ name.push(suffix);
657+ base.parent()
658+ .map(|parent| parent.join(&name))
659+ .unwrap_or_else(|| std::path::PathBuf::from(name))
660+}
661+
662+/// 0600 on a file holding live state, when it is there to restrict.
663+fn restrict_if_present(path: &std::path::Path) -> Result<()> {
664+ if path.exists() {
665+ secret::restrict(path).map_err(backend)?;
666+ }
667+ Ok(())
668+}
669+
670+fn backend<E: std::fmt::Display>(e: E) -> StoreError {
671+ StoreError::Backend(e.to_string())
672+}
673+
674+/// Whether this engine error is a uniqueness refusal rather than a
675+/// malfunction. The store checks names before writing, so this is only ever
676+/// the backstop for a race two Immediate transactions could not serialise —
677+/// and it answers with the name the check would have used.
678+fn is_constraint_violation(e: &turso::Error) -> bool {
679+ let text = e.to_string().to_lowercase();
680+ text.contains("constraint") || text.contains("unique")
681+}
682+
683+fn now_text() -> Result<String> {
684+ stamp(OffsetDateTime::now_utc())
685+}
686+
687+/// An RFC 3339 UTC timestamp: lexicographically sortable, which is what lets
688+/// expiry and purge comparisons live in SQL string order.
689+fn stamp(at: OffsetDateTime) -> Result<String> {
690+ at.format(&Rfc3339)
691+ .map_err(|e| StoreError::Corrupt(format!("timestamp: {e}")))
692+}
693+
694+fn parse_stamp(raw: &str) -> Result<OffsetDateTime> {
695+ OffsetDateTime::parse(raw, &Rfc3339)
696+ .map_err(|e| StoreError::Corrupt(format!("timestamp {raw:?}: {e}")))
697+}
698+fn opt_stamp(row: &Row, idx: usize) -> Result<Option<OffsetDateTime>> {
699+ match row.get::<Option<String>>(idx).map_err(backend)? {
700+ Some(raw) => Ok(Some(parse_stamp(&raw)?)),
701+ None => Ok(None),
702+ }
703+}
704+
705+/// One user row, in [`USER_COLUMNS`] order.
706+fn user_from(row: &Row) -> Result<User> {
707+ Ok(User {
708+ id: text(row, 0)?,
709+ oidc_sub: text(row, 1)?,
710+ email: text(row, 2)?,
711+ display_name: text(row, 3)?,
712+ admin: row.get::<i64>(4).map_err(backend)? != 0,
713+ disabled: row.get::<i64>(5).map_err(backend)? != 0,
714+ quota_bytes: row.get::<i64>(6).map_err(backend)?.max(0) as u64,
715+ used_bytes: row.get::<i64>(7).map_err(backend)?.max(0) as u64,
716+ created_at: parse_stamp(&text(row, 8)?)?,
717+ last_seen_at: opt_stamp(row, 9)?,
718+ })
719+}
720+
721+/// One folder row, in [`FOLDER_COLUMNS`] order.
722+fn folder_from(row: &Row) -> Result<Folder> {
723+ Ok(Folder {
724+ id: text(row, 0)?,
725+ owner_id: text(row, 1)?,
726+ parent_id: opt_text(row, 2)?,
727+ name: text(row, 3)?,
728+ created_at: parse_stamp(&text(row, 4)?)?,
729+ deleted_at: opt_stamp(row, 5)?,
730+ })
731+}
732+
733+/// One file row, in [`FILE_COLUMNS`] order — still without its bytes, which
734+/// no listing carries.
735+fn file_from(row: &Row) -> Result<File> {
736+ Ok(File {
737+ id: text(row, 0)?,
738+ owner_id: text(row, 1)?,
739+ folder_id: opt_text(row, 2)?,
740+ name: text(row, 3)?,
741+ mime: text(row, 4)?,
742+ size_bytes: row.get::<i64>(5).map_err(backend)?.max(0) as u64,
743+ thumb_state: ThumbState::parse(&text(row, 6)?)?,
744+ created_at: parse_stamp(&text(row, 7)?)?,
745+ updated_at: parse_stamp(&text(row, 8)?)?,
746+ deleted_at: opt_stamp(row, 9)?,
747+ })
748+}
749+
750+/// One share-link row, in [`LINK_COLUMNS`] order.
751+fn link_from(row: &Row) -> Result<ShareLink> {
752+ Ok(ShareLink {
753+ id: text(row, 0)?,
754+ token_hash: text(row, 1)?,
755+ kind: ShareKind::parse(&text(row, 2)?)?,
756+ target_id: text(row, 3)?,
757+ created_by: text(row, 4)?,
758+ can_download: row.get::<i64>(5).map_err(backend)? != 0,
759+ created_at: parse_stamp(&text(row, 6)?)?,
760+ expires_at: opt_stamp(row, 7)?,
761+ revoked_at: opt_stamp(row, 8)?,
762+ })
763+}
764+
765+/// One upload-session row, in [`SESSION_COLUMNS`] order.
766+fn session_from(row: &Row) -> Result<UploadSession> {
767+ Ok(UploadSession {
768+ id: text(row, 0)?,
769+ owner_id: text(row, 1)?,
770+ folder_id: opt_text(row, 2)?,
771+ name: text(row, 3)?,
772+ size_bytes: row.get::<i64>(4).map_err(backend)?.max(0) as u64,
773+ chunk_size: row.get::<i64>(5).map_err(backend)?.max(0) as u64,
774+ received_bytes: row.get::<i64>(6).map_err(backend)?.max(0) as u64,
775+ state: UploadState::parse(&text(row, 7)?)?,
776+ created_at: parse_stamp(&text(row, 8)?)?,
777+ expires_at: parse_stamp(&text(row, 9)?)?,
778+ })
779+}
780+
781+fn text(row: &Row, idx: usize) -> Result<String> {
782+ row.get::<String>(idx).map_err(backend)
783+}
784+
785+fn opt_text(row: &Row, idx: usize) -> Result<Option<String>> {
786+ row.get::<Option<String>>(idx).map_err(backend)
787+}
788+
789+#[async_trait]
790+impl Store for TursoStore {
791+ fn subscribe(&self) -> tokio::sync::broadcast::Receiver<Change> {
792+ self.live.subscribe()
793+ }
794+
795+ async fn user_by_oidc_sub(&self, sub: &str) -> Result<Option<User>> {
796+ let sql = format!("SELECT {USER_COLUMNS} FROM user WHERE oidc_sub = ?1");
797+ match self.one_row(&sql, params![sub]).await? {
798+ Some(row) => Ok(Some(user_from(&row)?)),
799+ None => Ok(None),
800+ }
801+ }
802+
803+ async fn user_by_email(&self, email: &str) -> Result<Option<User>> {
804+ let sql = format!("SELECT {USER_COLUMNS} FROM user WHERE email = ?1");
805+ match self.one_row(&sql, params![fold_email(email)]).await? {
806+ Some(row) => Ok(Some(user_from(&row)?)),
807+ None => Ok(None),
808+ }
809+ }
810+
811+ async fn user(&self, id: &str) -> Result<Option<User>> {
812+ let sql = format!("SELECT {USER_COLUMNS} FROM user WHERE id = ?1");
813+ match self.one_row(&sql, params![id]).await? {
814+ Some(row) => Ok(Some(user_from(&row)?)),
815+ None => Ok(None),
816+ }
817+ }
818+
819+ async fn users(&self) -> Result<Vec<User>> {
820+ let conn = self.conn.lock().await;
821+ let sql = format!("SELECT {USER_COLUMNS} FROM user ORDER BY created_at, id");
822+ let mut rows = conn.query(&sql, ()).await.map_err(backend)?;
823+ let mut out = Vec::new();
824+ while let Some(row) = rows.next().await.map_err(backend)? {
825+ out.push(user_from(&row)?);
826+ }
827+ Ok(out)
828+ }
829+
830+ async fn provision_user(
831+ &self,
832+ sub: &str,
833+ email: &str,
834+ display_name: &str,
835+ default_quota_bytes: u64,
836+ ) -> Result<User> {
837+ let email = fold_email(email);
838+ // IMMEDIATE: "first user ever" is read-then-write. Two concurrent
839+ // first sign-ins each count zero users, each claim admin, and the
840+ // deployment starts with two admins instead of one.
841+ let mut conn = self.tx_conn().await?;
842+ let tx = conn
843+ .transaction_with_behavior(TransactionBehavior::Immediate)
844+ .await
845+ .map_err(backend)?;
846+ let sql = format!("SELECT {USER_COLUMNS} FROM user WHERE oidc_sub = ?1");
847+ let mut rows = tx.query(&sql, params![sub]).await.map_err(backend)?;
848+ if let Some(row) = rows.next().await.map_err(backend)? {
849+ let user = user_from(&row)?;
850+ drop(rows);
851+ // A returning person: the provider may have a new address or a
852+ // new name for them, and the row follows the provider — but the
853+ // admin flag and the quota are ours, and this write touches
854+ // neither.
855+ tx.execute(
856+ "UPDATE user SET email = ?1, display_name = ?2, last_seen_at = ?3 WHERE id = ?4",
857+ params![email, display_name, now_text()?, user.id],
858+ )
859+ .await
860+ .map_err(backend)?;
861+ let mut back = tx.query(&sql, params![sub]).await.map_err(backend)?;
862+ let row = back.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?;
863+ let user = user_from(&row)?;
864+ drop(back);
865+ tx.commit().await.map_err(backend)?;
866+ return Ok(user);
867+ }
868+ drop(rows);
869+ let mut count = tx
870+ .query("SELECT COUNT(*) FROM user", ())
871+ .await
872+ .map_err(backend)?;
873+ let n = match count.next().await.map_err(backend)? {
874+ Some(row) => row.get::<i64>(0).map_err(backend)?,
875+ None => 0,
876+ };
877+ drop(count);
878+ // The first account ever provisioned is the admin: there is no one
879+ // else to make one, and a deployment with no admin is a deployment
880+ // nobody can administer.
881+ let admin = n == 0;
882+ let id = Ulid::new().to_string();
883+ let now = now_text()?;
884+ tx.execute(
885+ "INSERT INTO user (id, oidc_sub, email, display_name, admin, disabled, \
886+ quota_bytes, used_bytes, created_at, last_seen_at) \
887+ VALUES (?1, ?2, ?3, ?4, ?5, 0, ?6, 0, ?7, ?7)",
888+ params![
889+ id.clone(),
890+ sub,
891+ email,
892+ display_name,
893+ if admin { 1 } else { 0 },
894+ default_quota_bytes as i64,
895+ now
896+ ],
897+ )
898+ .await
899+ .map_err(backend)?;
900+ let mut back = tx
901+ .query(
902+ &format!("SELECT {USER_COLUMNS} FROM user WHERE id = ?1"),
903+ params![id],
904+ )
905+ .await
906+ .map_err(backend)?;
907+ let row = back.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?;
908+ let user = user_from(&row)?;
909+ drop(back);
910+ tx.commit().await.map_err(backend)?;
911+ self.announce([Topic::Admin(user.id.clone())]);
912+ Ok(user)
913+ }
914+
915+ async fn set_user_quota(&self, user_id: &str, quota_bytes: u64) -> Result<()> {
916+ let conn = self.conn.lock().await;
917+ let n = conn
918+ .execute(
919+ "UPDATE user SET quota_bytes = ?1 WHERE id = ?2",
920+ params![quota_bytes as i64, user_id],
921+ )
922+ .await
923+ .map_err(backend)?;
924+ if n == 0 {
925+ return Err(StoreError::NotFound);
926+ }
927+ drop(conn);
928+ self.announce([Topic::Admin(user_id.to_string())]);
929+ Ok(())
930+ }
931+
932+ async fn set_user_disabled(&self, user_id: &str, disabled: bool) -> Result<()> {
933+ let conn = self.conn.lock().await;
934+ let n = conn
935+ .execute(
936+ "UPDATE user SET disabled = ?1 WHERE id = ?2",
937+ params![if disabled { 1 } else { 0 }, user_id],
938+ )
939+ .await
940+ .map_err(backend)?;
941+ if n == 0 {
942+ return Err(StoreError::NotFound);
943+ }
944+ drop(conn);
945+ self.announce([Topic::Admin(user_id.to_string())]);
946+ Ok(())
947+ }
948+
949+ async fn create_folder(
950+ &self,
951+ owner_id: &str,
952+ parent_id: Option<&str>,
953+ name: &str,
954+ ) -> Result<Folder> {
955+ let name = label_of(name);
956+ // IMMEDIATE: the name check is read-then-write. Two concurrent
957+ // creates of one name each read no sibling, each pass, and the pair
958+ // leaves two folders with one name.
959+ let mut conn = self.tx_conn().await?;
960+ let tx = conn
961+ .transaction_with_behavior(TransactionBehavior::Immediate)
962+ .await
963+ .map_err(backend)?;
964+ check_live_parent(&tx, owner_id, parent_id).await?;
965+ if folder_name_taken(&tx, owner_id, parent_id, &name, None).await? {
966+ return Err(StoreError::NameTaken);
967+ }
968+ let id = Ulid::new().to_string();
969+ let now = now_text()?;
970+ tx.execute(
971+ "INSERT INTO folder (id, owner_id, parent_id, name, created_at, deleted_at) \
972+ VALUES (?1, ?2, ?3, ?4, ?5, NULL)",
973+ params![id.clone(), owner_id, parent_id, name, now],
974+ )
975+ .await
976+ .map_err(|e| map_constraint(e, StoreError::NameTaken))?;
977+ let mut rows = tx
978+ .query(
979+ &format!("SELECT {FOLDER_COLUMNS} FROM folder WHERE id = ?1"),
980+ params![id],
981+ )
982+ .await
983+ .map_err(backend)?;
984+ let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?;
985+ let folder = folder_from(&row)?;
986+ drop(rows);
987+ tx.commit().await.map_err(backend)?;
988+ self.announce([Topic::Library(owner_id.to_string())]);
989+ Ok(folder)
990+ }
991+
992+ async fn folder(&self, id: &str) -> Result<Option<Folder>> {
993+ let sql = format!("SELECT {FOLDER_COLUMNS} FROM folder WHERE id = ?1");
994+ match self.one_row(&sql, params![id]).await? {
995+ Some(row) => Ok(Some(folder_from(&row)?)),
996+ None => Ok(None),
997+ }
998+ }
999+
1000+ async fn rename_folder(&self, id: &str, name: &str) -> Result<()> {
1001+ let name = label_of(name);
1002+ let mut conn = self.tx_conn().await?;
1003+ let tx = conn
1004+ .transaction_with_behavior(TransactionBehavior::Immediate)
1005+ .await
1006+ .map_err(backend)?;
1007+ let folder = folder_row(&tx, id).await?.ok_or(StoreError::NotFound)?;
1008+ if folder.deleted_at.is_some() {
1009+ return Err(StoreError::NotFound);
1010+ }
1011+ if folder_name_taken(&tx, &folder.owner_id, folder.parent_id.as_deref(), &name, Some(id))
1012+ .await?
1013+ {
1014+ return Err(StoreError::NameTaken);
1015+ }
1016+ tx.execute("UPDATE folder SET name = ?1 WHERE id = ?2", params![name, id])
1017+ .await
1018+ .map_err(|e| map_constraint(e, StoreError::NameTaken))?;
1019+ refresh_usage(&tx, &folder.owner_id).await?;
1020+ tx.commit().await.map_err(backend)?;
1021+ self.announce([Topic::Library(folder.owner_id)]);
1022+ Ok(())
1023+ }
1024+
1025+ async fn move_folder(&self, id: &str, parent_id: Option<&str>) -> Result<()> {
1026+ let mut conn = self.tx_conn().await?;
1027+ let tx = conn
1028+ .transaction_with_behavior(TransactionBehavior::Immediate)
1029+ .await
1030+ .map_err(backend)?;
1031+ let folder = folder_row(&tx, id).await?.ok_or(StoreError::NotFound)?;
1032+ if folder.deleted_at.is_some() {
1033+ return Err(StoreError::NotFound);
1034+ }
1035+ // The destination is vetted before the cycle walk: a stranger's, a
1036+ // missing, or a trashed folder refuses before ancestry is even asked.
1037+ check_live_parent(&tx, &folder.owner_id, parent_id).await?;
1038+ // The cycle walk: the destination's ancestry must not contain the
1039+ // folder being moved. Moving onto itself is the one-step circle.
1040+ let mut cursor = parent_id.map(str::to_string);
1041+ while let Some(current) = cursor {
1042+ if current == id {
1043+ return Err(StoreError::Cycle);
1044+ }
1045+ cursor = parent_of(&tx, &current).await?;
1046+ }
1047+ if folder_name_taken(&tx, &folder.owner_id, parent_id, &folder.name, Some(id)).await? {
1048+ return Err(StoreError::NameTaken);
1049+ }
1050+ tx.execute(
1051+ "UPDATE folder SET parent_id = ?1 WHERE id = ?2",
1052+ params![parent_id, id],
1053+ )
1054+ .await
1055+ .map_err(|e| map_constraint(e, StoreError::NameTaken))?;
1056+ refresh_usage(&tx, &folder.owner_id).await?;
1057+ tx.commit().await.map_err(backend)?;
1058+ self.announce([Topic::Library(folder.owner_id)]);
1059+ Ok(())
1060+ }
1061+
1062+ async fn delete_folder(&self, id: &str) -> Result<()> {
1063+ let owner = {
1064+ let folder = self.folder(id).await?.ok_or(StoreError::NotFound)?;
1065+ if folder.deleted_at.is_some() {
1066+ return Ok(());
1067+ }
1068+ folder.owner_id.clone()
1069+ };
1070+ let now = now_text()?;
1071+ let mut conn = self.tx_conn().await?;
1072+ let tx = conn
1073+ .transaction_with_behavior(TransactionBehavior::Immediate)
1074+ .await
1075+ .map_err(backend)?;
1076+ // One timestamp for the whole subtree: the trash lists one moment,
1077+ // and the purge takes it in one pass. Rows already trashed keep
1078+ // their own earlier moment — a file trashed on its own before the
1079+ // folder must still wear its own timestamp after, so a later
1080+ // restore of the folder can tell the cascade apart from it.
1081+ tx.execute(
1082+ "WITH RECURSIVE sub(id) AS ( \
1083+ SELECT ?1 \
1084+ UNION ALL \
1085+ SELECT f.id FROM folder f JOIN sub s ON f.parent_id = s.id \
1086+ ) \
1087+ UPDATE folder SET deleted_at = ?2 WHERE owner_id = ?3 AND deleted_at IS NULL \
1088+ AND id IN (SELECT id FROM sub)",
1089+ params![id, now.as_str(), owner.as_str()],
1090+ )
1091+ .await
1092+ .map_err(backend)?;
1093+ tx.execute(
1094+ "WITH RECURSIVE sub(id) AS ( \
1095+ SELECT ?1 \
1096+ UNION ALL \
1097+ SELECT f.id FROM folder f JOIN sub s ON f.parent_id = s.id \
1098+ ) \
1099+ UPDATE file SET deleted_at = ?2, updated_at = ?2 \
1100+ WHERE owner_id = ?3 AND deleted_at IS NULL AND folder_id IN (SELECT id FROM sub)",
1101+ params![id, now.as_str(), owner.as_str()],
1102+ )
1103+ .await
1104+ .map_err(backend)?;
1105+ refresh_usage(&tx, &owner).await?;
1106+ tx.commit().await.map_err(backend)?;
1107+ self.announce([Topic::Library(owner.clone()), Topic::Trash(owner)]);
1108+ Ok(())
1109+ }
1110+
1111+ async fn list_children(
1112+ &self,
1113+ owner_id: &str,
1114+ parent_id: Option<&str>,
1115+ ) -> Result<Listing> {
1116+ let conn = self.conn.lock().await;
1117+ let mut folders = Vec::new();
1118+ let mut files = Vec::new();
1119+ match parent_id {
1120+ Some(parent) => {
1121+ let mut rows = conn
1122+ .query(
1123+ &format!(
1124+ "SELECT {FOLDER_COLUMNS} FROM folder \
1125+ WHERE owner_id = ?1 AND parent_id = ?2 AND deleted_at IS NULL \
1126+ ORDER BY name, id"
1127+ ),
1128+ params![owner_id, parent],
1129+ )
1130+ .await
1131+ .map_err(backend)?;
1132+ while let Some(row) = rows.next().await.map_err(backend)? {
1133+ folders.push(folder_from(&row)?);
1134+ }
1135+ let mut rows = conn
1136+ .query(
1137+ &format!(
1138+ "SELECT {FILE_COLUMNS} FROM file \
1139+ WHERE owner_id = ?1 AND folder_id = ?2 AND deleted_at IS NULL \
1140+ ORDER BY name, id"
1141+ ),
1142+ params![owner_id, parent],
1143+ )
1144+ .await
1145+ .map_err(backend)?;
1146+ while let Some(row) = rows.next().await.map_err(backend)? {
1147+ files.push(file_from(&row)?);
1148+ }
1149+ }
1150+ None => {
1151+ let mut rows = conn
1152+ .query(
1153+ &format!(
1154+ "SELECT {FOLDER_COLUMNS} FROM folder \
1155+ WHERE owner_id = ?1 AND parent_id IS NULL AND deleted_at IS NULL \
1156+ ORDER BY name, id"
1157+ ),
1158+ params![owner_id],
1159+ )
1160+ .await
1161+ .map_err(backend)?;
1162+ while let Some(row) = rows.next().await.map_err(backend)? {
1163+ folders.push(folder_from(&row)?);
1164+ }
1165+ let mut rows = conn
1166+ .query(
1167+ &format!(
1168+ "SELECT {FILE_COLUMNS} FROM file \
1169+ WHERE owner_id = ?1 AND folder_id IS NULL AND deleted_at IS NULL \
1170+ ORDER BY name, id"
1171+ ),
1172+ params![owner_id],
1173+ )
1174+ .await
1175+ .map_err(backend)?;
1176+ while let Some(row) = rows.next().await.map_err(backend)? {
1177+ files.push(file_from(&row)?);
1178+ }
1179+ }
1180+ }
1181+ Ok(Listing { folders, files })
1182+ }
1183+ async fn insert_file(
1184+ &self,
1185+ owner_id: &str,
1186+ folder_id: Option<&str>,
1187+ name: &str,
1188+ bytes: &[u8],
1189+ ) -> Result<File> {
1190+ let name = label_of(name);
1191+ let size = bytes.len() as u64;
1192+ // IMMEDIATE: the quota read, the name check and the row write are one
1193+ // write set. Two concurrent uploads each read room for themselves and
1194+ // the pair lands over quota.
1195+ let mut conn = self.tx_conn().await?;
1196+ let tx = conn
1197+ .transaction_with_behavior(TransactionBehavior::Immediate)
1198+ .await
1199+ .map_err(backend)?;
1200+ check_live_parent(&tx, owner_id, folder_id).await?;
1201+ let (quota, used) = check_quota(&tx, owner_id).await?;
1202+ fit_quota(quota, used, size)?;
1203+ if file_name_taken(&tx, owner_id, folder_id, &name, None).await? {
1204+ return Err(StoreError::NameTaken);
1205+ }
1206+ let mime = sniff::sniff(bytes).to_string();
1207+ let (thumb_state, thumb_bytes) = thumb_for(&mime, size, Some(bytes));
1208+ // The bytes land first, temp-plus-rename, then the row says they are
1209+ // there: a crash in between leaves an orphan file the boot sweep
1210+ // deletes, never a row pointing at nothing.
1211+ let id = Ulid::new().to_string();
1212+ let path = file_path(&self.storage, &id);
1213+ write_file_atomic(&path, bytes).map_err(|e| StoreError::Backend(e.to_string()))?;
1214+ if let Some(thumb) = thumb_bytes.as_ref() {
1215+ if write_file_atomic(&thumb_path(&self.storage, &id), thumb).is_err() {
1216+ // A thumbnail that cannot be written is a miss, not a failed
1217+ // upload: the file is what matters, and the row says so.
1218+ let _ = std::fs::remove_file(thumb_path(&self.storage, &id));
1219+ }
1220+ }
1221+ let stored_thumb = if thumb_bytes.is_some()
1222+ && thumb_path(&self.storage, &id).is_file()
1223+ {
1224+ ThumbState::Ready
1225+ } else if thumb_state == ThumbState::Ready {
1226+ ThumbState::Failed
1227+ } else {
1228+ thumb_state
1229+ };
1230+ let now = now_text()?;
1231+ let written = tx
1232+ .execute(
1233+ "INSERT INTO file (id, owner_id, folder_id, name, mime, size_bytes, \
1234+ thumb_state, created_at, updated_at, deleted_at) \
1235+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?8, NULL)",
1236+ params![
1237+ id.clone(),
1238+ owner_id,
1239+ folder_id,
1240+ name,
1241+ mime,
1242+ size as i64,
1243+ stored_thumb.as_str(),
1244+ now
1245+ ],
1246+ )
1247+ .await;
1248+ if let Err(e) = written {
1249+ // The row was never born, so the bytes must not outlive it under
1250+ // a name nothing points at.
1251+ let _ = std::fs::remove_file(&path);
1252+ let _ = std::fs::remove_file(thumb_path(&self.storage, &id));
1253+ return Err(map_constraint(e, StoreError::NameTaken));
1254+ }
1255+ refresh_usage(&tx, owner_id).await?;
1256+ let mut rows = tx
1257+ .query(
1258+ &format!("SELECT {FILE_COLUMNS} FROM file WHERE id = ?1"),
1259+ params![id],
1260+ )
1261+ .await
1262+ .map_err(backend)?;
1263+ let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?;
1264+ let file = file_from(&row)?;
1265+ drop(rows);
1266+ tx.commit().await.map_err(backend)?;
1267+ self.announce([Topic::Library(owner_id.to_string())]);
1268+ Ok(file)
1269+ }
1270+
1271+ async fn file(&self, id: &str) -> Result<Option<File>> {
1272+ let sql = format!("SELECT {FILE_COLUMNS} FROM file WHERE id = ?1");
1273+ match self.one_row(&sql, params![id]).await? {
1274+ Some(row) => Ok(Some(file_from(&row)?)),
1275+ None => Ok(None),
1276+ }
1277+ }
1278+
1279+ async fn rename_file(&self, id: &str, name: &str) -> Result<()> {
1280+ let name = label_of(name);
1281+ let mut conn = self.tx_conn().await?;
1282+ let tx = conn
1283+ .transaction_with_behavior(TransactionBehavior::Immediate)
1284+ .await
1285+ .map_err(backend)?;
1286+ let file = file_row(&tx, id).await?.ok_or(StoreError::NotFound)?;
1287+ if file.deleted_at.is_some() {
1288+ return Err(StoreError::NotFound);
1289+ }
1290+ if file_name_taken(&tx, &file.owner_id, file.folder_id.as_deref(), &name, Some(id)).await?
1291+ {
1292+ return Err(StoreError::NameTaken);
1293+ }
1294+ let now = now_text()?;
1295+ tx.execute(
1296+ "UPDATE file SET name = ?1, updated_at = ?2 WHERE id = ?3",
1297+ params![name, now, id],
1298+ )
1299+ .await
1300+ .map_err(|e| map_constraint(e, StoreError::NameTaken))?;
1301+ refresh_usage(&tx, &file.owner_id).await?;
1302+ tx.commit().await.map_err(backend)?;
1303+ self.announce([Topic::Library(file.owner_id)]);
1304+ Ok(())
1305+ }
1306+
1307+ async fn move_file(&self, id: &str, folder_id: Option<&str>) -> Result<()> {
1308+ let mut conn = self.tx_conn().await?;
1309+ let tx = conn
1310+ .transaction_with_behavior(TransactionBehavior::Immediate)
1311+ .await
1312+ .map_err(backend)?;
1313+ let file = file_row(&tx, id).await?.ok_or(StoreError::NotFound)?;
1314+ if file.deleted_at.is_some() {
1315+ return Err(StoreError::NotFound);
1316+ }
1317+ check_live_parent(&tx, &file.owner_id, folder_id).await?;
1318+ if file_name_taken(&tx, &file.owner_id, folder_id, &file.name, Some(id)).await? {
1319+ return Err(StoreError::NameTaken);
1320+ }
1321+ let now = now_text()?;
1322+ tx.execute(
1323+ "UPDATE file SET folder_id = ?1, updated_at = ?2 WHERE id = ?3",
1324+ params![folder_id, now, id],
1325+ )
1326+ .await
1327+ .map_err(|e| map_constraint(e, StoreError::NameTaken))?;
1328+ refresh_usage(&tx, &file.owner_id).await?;
1329+ tx.commit().await.map_err(backend)?;
1330+ self.announce([Topic::Library(file.owner_id)]);
1331+ Ok(())
1332+ }
1333+
1334+ async fn delete_file(&self, id: &str) -> Result<()> {
1335+ let owner = {
1336+ let file = self.file(id).await?.ok_or(StoreError::NotFound)?;
1337+ if file.deleted_at.is_some() {
1338+ return Ok(());
1339+ }
1340+ file.owner_id.clone()
1341+ };
1342+ let now = now_text()?;
1343+ let conn = self.conn.lock().await;
1344+ conn.execute(
1345+ "UPDATE file SET deleted_at = ?1, updated_at = ?1 WHERE id = ?2",
1346+ params![now, id],
1347+ )
1348+ .await
1349+ .map_err(backend)?;
1350+ refresh_usage(&conn, &owner).await?;
1351+ drop(conn);
1352+ self.announce([Topic::Library(owner.clone()), Topic::Trash(owner)]);
1353+ Ok(())
1354+ }
1355+
1356+ async fn file_bytes(&self, id: &str) -> Result<Option<Vec<u8>>> {
1357+ let conn = self.conn.lock().await;
1358+ let mut rows = conn
1359+ .query("SELECT 1 FROM file WHERE id = ?1", params![id])
1360+ .await
1361+ .map_err(backend)?;
1362+ let known = rows.next().await.map_err(backend)?.is_some();
1363+ drop(conn);
1364+ if !known {
1365+ return Ok(None);
1366+ }
1367+ match std::fs::read(file_path(&self.storage, id)) {
1368+ Ok(bytes) => Ok(Some(bytes)),
1369+ // A row whose file went missing is reported at boot; the read
1370+ // answers "nothing to serve" rather than failing the panel.
1371+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1372+ Err(e) => Err(StoreError::Backend(e.to_string())),
1373+ }
1374+ }
1375+
1376+ async fn thumb_bytes(&self, id: &str) -> Result<Option<Vec<u8>>> {
1377+ let conn = self.conn.lock().await;
1378+ let mut rows = conn
1379+ .query(
1380+ "SELECT thumb_state FROM file WHERE id = ?1",
1381+ params![id],
1382+ )
1383+ .await
1384+ .map_err(backend)?;
1385+ let ready = match rows.next().await.map_err(backend)? {
1386+ Some(row) => text(&row, 0)? == ThumbState::Ready.as_str(),
1387+ None => return Ok(None),
1388+ };
1389+ drop(conn);
1390+ if !ready {
1391+ return Ok(None);
1392+ }
1393+ match std::fs::read(thumb_path(&self.storage, id)) {
1394+ Ok(bytes) => Ok(Some(bytes)),
1395+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1396+ Err(e) => Err(StoreError::Backend(e.to_string())),
1397+ }
1398+ }
1399+ async fn list_trash(&self, owner_id: &str) -> Result<Listing> {
1400+ let conn = self.conn.lock().await;
1401+ let mut folders = Vec::new();
1402+ let mut files = Vec::new();
1403+ let mut rows = conn
1404+ .query(
1405+ &format!(
1406+ "SELECT {FOLDER_COLUMNS} FROM folder \
1407+ WHERE owner_id = ?1 AND deleted_at IS NOT NULL \
1408+ ORDER BY deleted_at DESC, id"
1409+ ),
1410+ params![owner_id],
1411+ )
1412+ .await
1413+ .map_err(backend)?;
1414+ while let Some(row) = rows.next().await.map_err(backend)? {
1415+ folders.push(folder_from(&row)?);
1416+ }
1417+ let mut rows = conn
1418+ .query(
1419+ &format!(
1420+ "SELECT {FILE_COLUMNS} FROM file \
1421+ WHERE owner_id = ?1 AND deleted_at IS NOT NULL \
1422+ ORDER BY deleted_at DESC, id"
1423+ ),
1424+ params![owner_id],
1425+ )
1426+ .await
1427+ .map_err(backend)?;
1428+ while let Some(row) = rows.next().await.map_err(backend)? {
1429+ files.push(file_from(&row)?);
1430+ }
1431+ Ok(Listing { folders, files })
1432+ }
1433+
1434+ async fn restore_file(&self, id: &str) -> Result<()> {
1435+ let mut conn = self.tx_conn().await?;
1436+ let tx = conn
1437+ .transaction_with_behavior(TransactionBehavior::Immediate)
1438+ .await
1439+ .map_err(backend)?;
1440+ let file = file_row(&tx, id).await?.ok_or(StoreError::NotFound)?;
1441+ if file.deleted_at.is_none() {
1442+ return Ok(());
1443+ }
1444+ // A file restored under trash would be trashed the moment it
1445+ // arrives: every ancestor folder must be live first.
1446+ if let Some(folder_id) = file.folder_id.as_deref() {
1447+ ancestor_trashed(&tx, folder_id).await?;
1448+ }
1449+ if file_name_taken(
1450+ &tx,
1451+ &file.owner_id,
1452+ file.folder_id.as_deref(),
1453+ &file.name,
1454+ Some(id),
1455+ )
1456+ .await?
1457+ {
1458+ return Err(StoreError::NameTaken);
1459+ }
1460+ let now = now_text()?;
1461+ tx.execute(
1462+ "UPDATE file SET deleted_at = NULL, updated_at = ?1 WHERE id = ?2",
1463+ params![now, id],
1464+ )
1465+ .await
1466+ .map_err(|e| map_constraint(e, StoreError::NameTaken))?;
1467+ refresh_usage(&tx, &file.owner_id).await?;
1468+ tx.commit().await.map_err(backend)?;
1469+ self.announce([
1470+ Topic::Library(file.owner_id.clone()),
1471+ Topic::Trash(file.owner_id),
1472+ ]);
1473+ Ok(())
1474+ }
1475+
1476+ async fn restore_folder(&self, id: &str) -> Result<()> {
1477+ let mut conn = self.tx_conn().await?;
1478+ let tx = conn
1479+ .transaction_with_behavior(TransactionBehavior::Immediate)
1480+ .await
1481+ .map_err(backend)?;
1482+ let folder = folder_row(&tx, id).await?.ok_or(StoreError::NotFound)?;
1483+ let Some(trashed_at) = folder.deleted_at else {
1484+ return Ok(());
1485+ };
1486+ let trashed_at = stamp(trashed_at)?;
1487+ // Same refusal as the file: no resurrection into a trash that never
1488+ // left. Only the ancestors above the folder are asked — the subtree
1489+ // below comes back with it.
1490+ if let Some(parent_id) = folder.parent_id.as_deref() {
1491+ ancestor_trashed(&tx, parent_id).await?;
1492+ }
1493+ if folder_name_taken(
1494+ &tx,
1495+ &folder.owner_id,
1496+ folder.parent_id.as_deref(),
1497+ &folder.name,
1498+ Some(id),
1499+ )
1500+ .await?
1501+ {
1502+ return Err(StoreError::NameTaken);
1503+ }
1504+ let now = now_text()?;
1505+ // Only the cascade comes back: descendants wear the folder's own
1506+ // trash timestamp when the folder took them with it, while anything
1507+ // trashed individually before keeps its earlier moment and stays
1508+ // trashed.
1509+ tx.execute(
1510+ "WITH RECURSIVE sub(id) AS ( \
1511+ SELECT ?1 \
1512+ UNION ALL \
1513+ SELECT f.id FROM folder f JOIN sub s ON f.parent_id = s.id \
1514+ ) \
1515+ UPDATE folder SET deleted_at = NULL \
1516+ WHERE id IN (SELECT id FROM sub) AND deleted_at = ?2",
1517+ params![id, trashed_at.clone()],
1518+ )
1519+ .await
1520+ .map_err(backend)?;
1521+ tx.execute(
1522+ "WITH RECURSIVE sub(id) AS ( \
1523+ SELECT ?1 \
1524+ UNION ALL \
1525+ SELECT f.id FROM folder f JOIN sub s ON f.parent_id = s.id \
1526+ ) \
1527+ UPDATE file SET deleted_at = NULL, updated_at = ?2 \
1528+ WHERE folder_id IN (SELECT id FROM sub) AND deleted_at = ?3",
1529+ params![id, now, trashed_at],
1530+ )
1531+ .await
1532+ .map_err(backend)?;
1533+ refresh_usage(&tx, &folder.owner_id).await?;
1534+ tx.commit().await.map_err(backend)?;
1535+ self.announce([
1536+ Topic::Library(folder.owner_id.clone()),
1537+ Topic::Trash(folder.owner_id),
1538+ ]);
1539+ Ok(())
1540+ }
1541+
1542+ async fn purge_file(&self, id: &str) -> Result<bool> {
1543+ let owner = {
1544+ let file = self.file(id).await?.ok_or(StoreError::NotFound)?;
1545+ // A live file is never purged — trash it first. This answers
1546+ // `false` rather than failing, because the purge's contract is
1547+ // "take the trash", and a live file is not trash.
1548+ if file.deleted_at.is_none() {
1549+ return Ok(false);
1550+ }
1551+ file.owner_id.clone()
1552+ };
1553+ let mut conn = self.tx_conn().await?;
1554+ let tx = conn
1555+ .transaction_with_behavior(TransactionBehavior::Immediate)
1556+ .await
1557+ .map_err(backend)?;
1558+ delete_file_rows(&tx, &[id.to_string()]).await?;
1559+ refresh_usage(&tx, &owner).await?;
1560+ tx.commit().await.map_err(backend)?;
1561+ // After the delete: the bytes may only follow a delete that
1562+ // committed, or a crash in between would leave a row whose file is
1563+ // gone. Best-effort — a file that survives is orphaned bytes the
1564+ // boot sweep collects.
1565+ let _ = std::fs::remove_file(file_path(&self.storage, id));
1566+ let _ = std::fs::remove_file(thumb_path(&self.storage, id));
1567+ self.announce([Topic::Library(owner.clone()), Topic::Trash(owner)]);
1568+ Ok(true)
1569+ }
1570+
1571+ async fn purge_folder(&self, id: &str) -> Result<u64> {
1572+ let folder = self.folder(id).await?.ok_or(StoreError::NotFound)?;
1573+ // A live folder is never purged — trash it first.
1574+ if folder.deleted_at.is_none() {
1575+ return Err(StoreError::NotFound);
1576+ }
1577+ let owner = folder.owner_id.clone();
1578+ let conn = self.conn.lock().await;
1579+ // The trashed subtree: the folder itself and every trashed folder
1580+ // under it. A live row under trash cannot exist — nothing is created
1581+ // or moved under a trashed folder, and restores cascade — so the
1582+ // trashed set is the whole subtree; the foreign key would say so
1583+ // loudly if that ever stopped being true.
1584+ let mut folder_rows = Vec::new();
1585+ let mut rows = conn
1586+ .query(
1587+ "WITH RECURSIVE sub(id) AS ( \
1588+ SELECT ?1 \
1589+ UNION ALL \
1590+ SELECT f.id FROM folder f JOIN sub s ON f.parent_id = s.id \
1591+ ) \
1592+ SELECT id, parent_id FROM folder WHERE owner_id = ?2 AND id IN (SELECT id FROM sub) AND deleted_at IS NOT NULL",
1593+ params![id, owner.as_str()],
1594+ )
1595+ .await
1596+ .map_err(backend)?;
1597+ while let Some(row) = rows.next().await.map_err(backend)? {
1598+ folder_rows.push((text(&row, 0)?, opt_text(&row, 1)?));
1599+ }
1600+ drop(rows);
1601+ let mut file_ids = Vec::new();
1602+ let mut rows = conn
1603+ .query(
1604+ "WITH RECURSIVE sub(id) AS ( \
1605+ SELECT ?1 \
1606+ UNION ALL \
1607+ SELECT f.id FROM folder f JOIN sub s ON f.parent_id = s.id \
1608+ ) \
1609+ SELECT id FROM file WHERE owner_id = ?2 AND folder_id IN (SELECT id FROM sub) AND deleted_at IS NOT NULL",
1610+ params![id, owner.as_str()],
1611+ )
1612+ .await
1613+ .map_err(backend)?;
1614+ while let Some(row) = rows.next().await.map_err(backend)? {
1615+ file_ids.push(text(&row, 0)?);
1616+ }
1617+ drop(rows);
1618+ drop(conn);
1619+ let folder_ids = order_deepest_first(&folder_rows);
1620+ let mut conn = self.tx_conn().await?;
1621+ let tx = conn
1622+ .transaction_with_behavior(TransactionBehavior::Immediate)
1623+ .await
1624+ .map_err(backend)?;
1625+ delete_file_rows(&tx, &file_ids).await?;
1626+ delete_folder_rows(&tx, &folder_ids).await?;
1627+ refresh_usage(&tx, &owner).await?;
1628+ tx.commit().await.map_err(backend)?;
1629+ // After the delete: bytes may only follow a delete that committed.
1630+ // Best-effort — survivors are orphaned bytes the boot sweep collects.
1631+ for file_id in &file_ids {
1632+ let _ = std::fs::remove_file(file_path(&self.storage, file_id));
1633+ let _ = std::fs::remove_file(thumb_path(&self.storage, file_id));
1634+ }
1635+ let purged = (file_ids.len() + folder_ids.len()) as u64;
1636+ self.announce([Topic::Library(owner.clone()), Topic::Trash(owner)]);
1637+ Ok(purged)
1638+ }
1639+
1640+ async fn purge_expired(&self, before: OffsetDateTime) -> Result<u64> {
1641+ let before = stamp(before)?;
1642+ let conn = self.conn.lock().await;
1643+ let mut file_ids = Vec::new();
1644+ let mut rows = conn
1645+ .query(
1646+ "SELECT id, owner_id FROM file WHERE deleted_at IS NOT NULL AND deleted_at < ?1",
1647+ params![before.as_str()],
1648+ )
1649+ .await
1650+ .map_err(backend)?;
1651+ while let Some(row) = rows.next().await.map_err(backend)? {
1652+ file_ids.push((text(&row, 0)?, text(&row, 1)?));
1653+ }
1654+ let mut folder_rows = Vec::new();
1655+ let mut rows = conn
1656+ .query(
1657+ "SELECT id, owner_id, parent_id FROM folder \
1658+ WHERE deleted_at IS NOT NULL AND deleted_at < ?1",
1659+ params![before],
1660+ )
1661+ .await
1662+ .map_err(backend)?;
1663+ while let Some(row) = rows.next().await.map_err(backend)? {
1664+ folder_rows.push((text(&row, 0)?, text(&row, 1)?, opt_text(&row, 2)?));
1665+ }
1666+ drop(conn);
1667+ if file_ids.is_empty() && folder_rows.is_empty() {
1668+ return Ok(0);
1669+ }
1670+ // Folders deepest first: a parent row cannot go while a child row
1671+ // still names it.
1672+ let folder_ids = order_deepest_first(
1673+ &folder_rows
1674+ .iter()
1675+ .map(|(id, _, parent)| (id.clone(), parent.clone()))
1676+ .collect::<Vec<_>>(),
1677+ );
1678+ let owners = {
1679+ let mut owners: Vec<String> = file_ids.iter().map(|(_, o)| o.clone()).collect();
1680+ owners.extend(folder_rows.iter().map(|(_, o, _)| o.clone()));
1681+ owners.sort();
1682+ owners.dedup();
1683+ owners
1684+ };
1685+ let mut conn = self.tx_conn().await?;
1686+ let tx = conn
1687+ .transaction_with_behavior(TransactionBehavior::Immediate)
1688+ .await
1689+ .map_err(backend)?;
1690+ delete_file_rows(
1691+ &tx,
1692+ &file_ids.iter().map(|(id, _)| id.clone()).collect::<Vec<_>>(),
1693+ )
1694+ .await?;
1695+ delete_folder_rows(&tx, &folder_ids).await?;
1696+ for owner in &owners {
1697+ refresh_usage(&tx, owner).await?;
1698+ }
1699+ tx.commit().await.map_err(backend)?;
1700+ for (id, _) in &file_ids {
1701+ let _ = std::fs::remove_file(file_path(&self.storage, id));
1702+ let _ = std::fs::remove_file(thumb_path(&self.storage, id));
1703+ }
1704+ let purged = (file_ids.len() + folder_ids.len()) as u64;
1705+ for owner in owners {
1706+ self.announce([Topic::Library(owner.clone()), Topic::Trash(owner)]);
1707+ }
1708+ Ok(purged)
1709+ }
1710+
1711+ async fn empty_trash(&self, owner_id: &str) -> Result<u64> {
1712+ let conn = self.conn.lock().await;
1713+ let mut file_ids = Vec::new();
1714+ let mut rows = conn
1715+ .query(
1716+ "SELECT id FROM file WHERE owner_id = ?1 AND deleted_at IS NOT NULL",
1717+ params![owner_id],
1718+ )
1719+ .await
1720+ .map_err(backend)?;
1721+ while let Some(row) = rows.next().await.map_err(backend)? {
1722+ file_ids.push(text(&row, 0)?);
1723+ }
1724+ let mut folder_rows = Vec::new();
1725+ let mut rows = conn
1726+ .query(
1727+ "SELECT id, parent_id FROM folder WHERE owner_id = ?1 AND deleted_at IS NOT NULL",
1728+ params![owner_id],
1729+ )
1730+ .await
1731+ .map_err(backend)?;
1732+ while let Some(row) = rows.next().await.map_err(backend)? {
1733+ folder_rows.push((text(&row, 0)?, opt_text(&row, 1)?));
1734+ }
1735+ drop(conn);
1736+ if file_ids.is_empty() && folder_rows.is_empty() {
1737+ return Ok(0);
1738+ }
1739+ let folder_ids = order_deepest_first(&folder_rows);
1740+ let mut conn = self.tx_conn().await?;
1741+ let tx = conn
1742+ .transaction_with_behavior(TransactionBehavior::Immediate)
1743+ .await
1744+ .map_err(backend)?;
1745+ delete_file_rows(&tx, &file_ids).await?;
1746+ delete_folder_rows(&tx, &folder_ids).await?;
1747+ refresh_usage(&tx, owner_id).await?;
1748+ tx.commit().await.map_err(backend)?;
1749+ for id in &file_ids {
1750+ let _ = std::fs::remove_file(file_path(&self.storage, id));
1751+ let _ = std::fs::remove_file(thumb_path(&self.storage, id));
1752+ }
1753+ let purged = (file_ids.len() + folder_ids.len()) as u64;
1754+ self.announce([
1755+ Topic::Library(owner_id.to_string()),
1756+ Topic::Trash(owner_id.to_string()),
1757+ ]);
1758+ Ok(purged)
1759+ }
1760+ async fn create_share_link(
1761+ &self,
1762+ created_by: &str,
1763+ kind: ShareKind,
1764+ target_id: &str,
1765+ can_download: bool,
1766+ expires_at: Option<OffsetDateTime>,
1767+ ) -> Result<CreatedLink> {
1768+ // The sharer must own a live target: a stranger's, a missing, or a
1769+ // trashed target refuses before any token exists to leak.
1770+ match target_owner(&self.conn, kind, target_id).await? {
1771+ Some(owner) if owner == created_by => {}
1772+ Some(_) => return Err(StoreError::CrossOwner),
1773+ None => return Err(StoreError::NotFound),
1774+ }
1775+ let token = new_token();
1776+ let token_hash = hash_share_token(&token);
1777+ let id = Ulid::new().to_string();
1778+ let now = now_text()?;
1779+ let expires = expires_at.map(stamp).transpose()?;
1780+ let conn = self.conn.lock().await;
1781+ conn.execute(
1782+ "INSERT INTO share_link (id, token_hash, kind, target_id, created_by, \
1783+ can_download, created_at, expires_at, revoked_at) \
1784+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, NULL)",
1785+ params![
1786+ id.clone(),
1787+ token_hash,
1788+ kind.as_str(),
1789+ target_id,
1790+ created_by,
1791+ if can_download { 1 } else { 0 },
1792+ now,
1793+ expires
1794+ ],
1795+ )
1796+ .await
1797+ .map_err(backend)?;
1798+ let mut rows = conn
1799+ .query(
1800+ &format!("SELECT {LINK_COLUMNS} FROM share_link WHERE id = ?1"),
1801+ params![id],
1802+ )
1803+ .await
1804+ .map_err(backend)?;
1805+ let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?;
1806+ let link = link_from(&row)?;
1807+ drop(rows);
1808+ drop(conn);
1809+ self.announce([Topic::Shares(created_by.to_string())]);
1810+ Ok(CreatedLink { link, token })
1811+ }
1812+
1813+ async fn revoke_share_link(&self, id: &str) -> Result<()> {
1814+ let created_by = {
1815+ let row = self
1816+ .one_row(
1817+ &format!("SELECT {LINK_COLUMNS} FROM share_link WHERE id = ?1"),
1818+ params![id],
1819+ )
1820+ .await?;
1821+ match row {
1822+ Some(row) => link_from(&row)?.created_by.clone(),
1823+ None => return Err(StoreError::NotFound),
1824+ }
1825+ };
1826+ let conn = self.conn.lock().await;
1827+ conn.execute(
1828+ "UPDATE share_link SET revoked_at = COALESCE(revoked_at, ?1) WHERE id = ?2",
1829+ params![now_text()?, id],
1830+ )
1831+ .await
1832+ .map_err(backend)?;
1833+ drop(conn);
1834+ self.announce([Topic::Shares(created_by)]);
1835+ Ok(())
1836+ }
1837+
1838+ async fn share_links(&self, owner_id: &str) -> Result<Vec<ShareLink>> {
1839+ let conn = self.conn.lock().await;
1840+ let mut rows = conn
1841+ .query(
1842+ &format!(
1843+ "SELECT {LINK_COLUMNS} FROM share_link \
1844+ WHERE created_by = ?1 ORDER BY created_at DESC, id"
1845+ ),
1846+ params![owner_id],
1847+ )
1848+ .await
1849+ .map_err(backend)?;
1850+ let mut out = Vec::new();
1851+ while let Some(row) = rows.next().await.map_err(backend)? {
1852+ out.push(link_from(&row)?);
1853+ }
1854+ Ok(out)
1855+ }
1856+
1857+ async fn resolve_share_link(
1858+ &self,
1859+ token_hash: &str,
1860+ now: OffsetDateTime,
1861+ ) -> Result<Option<ShareLink>> {
1862+ let sql = format!("SELECT {LINK_COLUMNS} FROM share_link WHERE token_hash = ?1");
1863+ match self.one_row(&sql, params![token_hash]).await? {
1864+ Some(row) => {
1865+ let link = link_from(&row)?;
1866+ // A dead link and a wrong token both answer `None`: telling a
1867+ // stranger which tokens exist is the leak the distinction
1868+ // would be.
1869+ if link.is_live(now) {
1870+ Ok(Some(link))
1871+ } else {
1872+ Ok(None)
1873+ }
1874+ }
1875+ None => Ok(None),
1876+ }
1877+ }
1878+
1879+ async fn add_share_user(
1880+ &self,
1881+ caller_id: &str,
1882+ kind: ShareKind,
1883+ target_id: &str,
1884+ user_id: &str,
1885+ can_download: bool,
1886+ ) -> Result<()> {
1887+ // The caller must own a live target — the same rule as
1888+ // create_share_link: a stranger's, a missing, or a trashed target
1889+ // refuses before any grant names it. The grantee must exist, or the
1890+ // row would point at nobody.
1891+ let owner = match target_owner(&self.conn, kind, target_id).await? {
1892+ Some(owner) if owner == caller_id => owner,
1893+ Some(_) => return Err(StoreError::CrossOwner),
1894+ None => return Err(StoreError::NotFound),
1895+ };
1896+ if self.user(user_id).await?.is_none() {
1897+ return Err(StoreError::NotFound);
1898+ }
1899+ if owner == user_id {
1900+ // Sharing with the owner is a no-op with a success answer: the
1901+ // owner already sees everything.
1902+ return Ok(());
1903+ }
1904+ let conn = self.conn.lock().await;
1905+ conn.execute(
1906+ "INSERT INTO share_user (kind, target_id, user_id, can_download, created_at) \
1907+ VALUES (?1, ?2, ?3, ?4, ?5) \
1908+ ON CONFLICT (kind, target_id, user_id) \
1909+ DO UPDATE SET can_download = excluded.can_download",
1910+ params![
1911+ kind.as_str(),
1912+ target_id,
1913+ user_id,
1914+ if can_download { 1 } else { 0 },
1915+ now_text()?
1916+ ],
1917+ )
1918+ .await
1919+ .map_err(backend)?;
1920+ drop(conn);
1921+ self.announce([
1922+ Topic::Shares(owner),
1923+ Topic::Shares(user_id.to_string()),
1924+ ]);
1925+ Ok(())
1926+ }
1927+
1928+ async fn remove_share_user(
1929+ &self,
1930+ kind: ShareKind,
1931+ target_id: &str,
1932+ user_id: &str,
1933+ ) -> Result<()> {
1934+ // The owner is read before the delete: after it there may be nothing
1935+ // left to announce to. Trash does not stop an unshare — the grant is
1936+ // gone either way, and the owner is still listening.
1937+ let owner = row_owner(&self.conn, kind, target_id)
1938+ .await?
1939+ .ok_or(StoreError::NotFound)?;
1940+ let conn = self.conn.lock().await;
1941+ conn.execute(
1942+ "DELETE FROM share_user WHERE kind = ?1 AND target_id = ?2 AND user_id = ?3",
1943+ params![kind.as_str(), target_id, user_id],
1944+ )
1945+ .await
1946+ .map_err(backend)?;
1947+ drop(conn);
1948+ self.announce([
1949+ Topic::Shares(owner),
1950+ Topic::Shares(user_id.to_string()),
1951+ ]);
1952+ Ok(())
1953+ }
1954+
1955+ async fn shares_for_user(&self, user_id: &str) -> Result<Vec<SharedItem>> {
1956+ let conn = self.conn.lock().await;
1957+ let mut rows = conn
1958+ .query(
1959+ "SELECT kind, target_id, can_download, created_at FROM share_user \
1960+ WHERE user_id = ?1 ORDER BY created_at DESC",
1961+ params![user_id],
1962+ )
1963+ .await
1964+ .map_err(backend)?;
1965+ let mut grants = Vec::new();
1966+ while let Some(row) = rows.next().await.map_err(backend)? {
1967+ grants.push((
1968+ ShareKind::parse(&text(&row, 0)?)?,
1969+ text(&row, 1)?,
1970+ row.get::<i64>(2).map_err(backend)? != 0,
1971+ parse_stamp(&text(&row, 3)?)?,
1972+ ));
1973+ }
1974+ drop(rows);
1975+ // Targets that went missing or were trashed since the grant fall out
1976+ // silently: the grant row stays (the owner may restore the target),
1977+ // but the listing shows only what opens today.
1978+ let mut out = Vec::new();
1979+ for (kind, target_id, can_download, created_at) in grants {
1980+ let (name, mime, owner_id) = match kind {
1981+ ShareKind::File => {
1982+ let mut rows = conn
1983+ .query(
1984+ "SELECT name, mime, owner_id FROM file \
1985+ WHERE id = ?1 AND deleted_at IS NULL",
1986+ params![target_id.as_str()],
1987+ )
1988+ .await
1989+ .map_err(backend)?;
1990+ match rows.next().await.map_err(backend)? {
1991+ Some(row) => (text(&row, 0)?, Some(text(&row, 1)?), text(&row, 2)?),
1992+ None => continue,
1993+ }
1994+ }
1995+ ShareKind::Folder => {
1996+ let mut rows = conn
1997+ .query(
1998+ "SELECT name, owner_id FROM folder \
1999+ WHERE id = ?1 AND deleted_at IS NULL",
2000+ params![target_id.as_str()],
crates/in-core/src/thumbs.rsadded+299 -0
@@ -0,0 +1,299 @@
1+//! Thumbnails: one small webp per image or video file.
2+//!
3+//! Images decode in-process (`bytes -> bytes`, with no I/O and nothing
4+//! store-shaped in it); video needs a decoder the `image` crate does not have,
5+//! so those frames come from `ffmpeg` on `PATH` instead (see
6+//! [`thumbnail_for_video_file`]). The upload path calls into here once per
7+//! finished file, and the store writes whatever comes back to
8+//! `<storage>/thumbs/<id>`. Anything that cannot be made into a thumbnail
9+//! answers `None`, and the row wears `failed` — or `none` when no attempt was
10+//! even possible — so the attempt is never repeated: a thumbnail that cannot
11+//! be made is a fact, not an error.
12+
13+use std::io::Read as _;
14+use std::path::Path;
15+use std::process::{Command, Stdio};
16+use std::sync::OnceLock;
17+use std::sync::atomic::{AtomicU64, Ordering};
18+use std::time::{Duration, Instant};
19+
20+/// The longest edge a thumbnail keeps, in pixels. Big enough to be legible
21+/// on a file card, small enough that a library of them stays cheap.
22+pub const THUMB_MAX_DIM: u32 = 512;
23+
24+/// How long one `ffmpeg` extraction may run before it is killed. A single
25+/// frame out of a local file is milliseconds; ten seconds is already a wedged
26+/// binary, not a slow one.
27+pub const FFMPEG_TIMEOUT: Duration = Duration::from_secs(10);
28+
29+/// Makes the thumbnail for `bytes`: decoded, resized so the longest edge is
30+/// [`THUMB_MAX_DIM`], encoded as webp. `None` for bytes that are not an
31+/// image the decoder knows, or that fail to encode — the caller records the
32+/// miss and moves on.
33+pub fn thumbnail_for_bytes(bytes: &[u8]) -> Option<Vec<u8>> {
34+ let image = image::load_from_memory(bytes).ok()?;
35+ let thumb = image.thumbnail(THUMB_MAX_DIM, THUMB_MAX_DIM);
36+ let mut out = Vec::new();
37+ thumb
38+ .write_to(
39+ &mut std::io::Cursor::new(&mut out),
40+ image::ImageFormat::WebP,
41+ )
42+ .ok()?;
43+ if out.is_empty() { None } else { Some(out) }
44+}
45+
46+/// Whether a thumbnail is even attempted for this mime: images, decoded
47+/// in-process, and the video containers the sniffer names, framed by
48+/// `ffmpeg`. Anything else wears `none` without a decoder ever looking at it.
49+pub fn thumbnailed(mime: &str) -> bool {
50+ mime.starts_with("image/") || is_video_mime(mime)
51+}
52+
53+/// Whether `mime` is a video container this crate frames via `ffmpeg`:
54+/// exactly the video mimes the sniffer can name.
55+pub fn is_video_mime(mime: &str) -> bool {
56+ matches!(mime, "video/mp4" | "video/webm" | "video/quicktime")
57+}
58+
59+/// Whether `ffmpeg` is on `PATH`. The verdict comes from one `ffmpeg
60+/// -version` run and is cached for the process: a missing binary must degrade
61+/// every video to its icon, not fork a failing child per upload.
62+pub fn ffmpeg_available() -> bool {
63+ static HAVE_FFMPEG: OnceLock<bool> = OnceLock::new();
64+ *HAVE_FFMPEG.get_or_init(|| {
65+ Command::new("ffmpeg")
66+ .arg("-version")
67+ .stdin(Stdio::null())
68+ .stdout(Stdio::null())
69+ .stderr(Stdio::null())
70+ .status()
71+ .map(|status| status.success())
72+ .unwrap_or(false)
73+ })
74+}
75+
76+/// Makes the thumbnail for the video at `path`: the frame at one second,
77+/// scaled so the longest edge is [`THUMB_MAX_DIM`], encoded as webp. Clips
78+/// shorter than a second fall back to their first frame. `None` without
79+/// `ffmpeg` on `PATH`, or when the file is not a video `ffmpeg` can read —
80+/// the caller records the miss and moves on, never the upload.
81+pub fn thumbnail_for_video_file(path: &Path) -> Option<Vec<u8>> {
82+ if !ffmpeg_available() {
83+ return None;
84+ }
85+ run_ffmpeg_frame(path, true).or_else(|| run_ffmpeg_frame(path, false))
86+}
87+
88+/// Makes the thumbnail for video `bytes`, spilled to a temp file because
89+/// `ffmpeg` seeks its input and a pipe is not seekable. Same `None` contract
90+/// as [`thumbnail_for_video_file`].
91+pub fn thumbnail_for_video_bytes(bytes: &[u8]) -> Option<Vec<u8>> {
92+ if !ffmpeg_available() || bytes.is_empty() {
93+ return None;
94+ }
95+ static COUNTER: AtomicU64 = AtomicU64::new(0);
96+ let tmp = std::env::temp_dir().join(format!(
97+ "in-thumb-{}-{}.bin",
98+ std::process::id(),
99+ COUNTER.fetch_add(1, Ordering::Relaxed)
100+ ));
101+ std::fs::write(&tmp, bytes).ok()?;
102+ let out = thumbnail_for_video_file(&tmp);
103+ let _ = std::fs::remove_file(&tmp);
104+ out
105+}
106+
107+/// Runs one `ffmpeg` frame extraction: `seek_one_second` takes the frame at
108+/// one second, otherwise the first frame. The webp comes back over the
109+/// stdout pipe; anything else — a nonzero exit, an empty pipe, bytes that are
110+/// not a webp — is `None`. A run past [`FFMPEG_TIMEOUT`] is killed.
111+fn run_ffmpeg_frame(path: &Path, seek_one_second: bool) -> Option<Vec<u8>> {
112+ let scale = format!(
113+ "scale={0}:{0}:force_original_aspect_ratio=decrease",
114+ THUMB_MAX_DIM
115+ );
116+ let mut cmd = Command::new("ffmpeg");
117+ cmd.args(["-v", "error"]);
118+ if seek_one_second {
119+ // Before `-i`: fast input seeking, good enough for a thumbnail.
120+ cmd.args(["-ss", "1"]);
121+ }
122+ cmd.arg("-i")
123+ .arg(path)
124+ .args(["-frames:v", "1", "-vf", &scale])
125+ // `-c:v libwebp` matters: without it this ffmpeg answers `-f webp`
126+ // with its animated encoder, which refuses a single frame.
127+ .args(["-c:v", "libwebp", "-f", "webp", "-"]);
128+ let mut child = cmd
129+ .stdin(Stdio::null())
130+ .stdout(Stdio::piped())
131+ .stderr(Stdio::null())
132+ .spawn()
133+ .ok()?;
134+ // The webp is read on its own thread: the pipe buffer is small, and a
135+ // parent that only `try_wait`s while the child fills the buffer would
136+ // deadlock against it.
137+ let stdout = child.stdout.take();
138+ let (tx, rx) = std::sync::mpsc::channel();
139+ std::thread::spawn(move || {
140+ let mut buf = Vec::new();
141+ if let Some(mut out) = stdout {
142+ let _ = out.read_to_end(&mut buf);
143+ }
144+ let _ = tx.send(buf);
145+ });
146+ let start = Instant::now();
147+ loop {
148+ match child.try_wait() {
149+ Ok(Some(status)) => {
150+ let buf = rx.recv().ok()?;
151+ if !status.success() || buf.len() < 12 {
152+ return None;
153+ }
154+ // Whatever left the pipe must be the webp asked for.
155+ if &buf[0..4] == b"RIFF" && &buf[8..12] == b"WEBP" {
156+ return Some(buf);
157+ }
158+ return None;
159+ }
160+ Ok(None) => {
161+ if start.elapsed() >= FFMPEG_TIMEOUT {
162+ let _ = child.kill();
163+ let _ = child.wait();
164+ return None;
165+ }
166+ std::thread::sleep(Duration::from_millis(20));
167+ }
168+ Err(_) => {
169+ let _ = child.kill();
170+ return None;
171+ }
172+ }
173+ }
174+}
175+
176+#[cfg(test)]
177+mod tests {
178+ use super::*;
179+
180+ /// A 1x1 PNG, hand-built: the smallest thing the decoder must accept.
181+ fn tiny_png() -> Vec<u8> {
182+ let img = image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]));
183+ let mut out = Vec::new();
184+ img.write_to(
185+ &mut std::io::Cursor::new(&mut out),
186+ image::ImageFormat::Png,
187+ )
188+ .unwrap();
189+ out
190+ }
191+
192+ #[test]
193+ fn an_image_makes_a_webp_thumbnail() {
194+ let thumb = thumbnail_for_bytes(&tiny_png()).unwrap();
195+ // A webp RIFF header, not the PNG that went in.
196+ assert_eq!(&thumb[0..4], b"RIFF");
197+ assert_eq!(&thumb[8..12], b"WEBP");
198+ let back = image::load_from_memory(&thumb).unwrap();
199+ assert!(back.width() <= THUMB_MAX_DIM && back.height() <= THUMB_MAX_DIM);
200+ }
201+
202+ #[test]
203+ fn non_images_make_no_thumbnail() {
204+ assert!(thumbnail_for_bytes(b"just some text").is_none());
205+ assert!(thumbnail_for_bytes(&[]).is_none());
206+ }
207+
208+ #[test]
209+ fn images_and_covered_video_are_thumbnailed() {
210+ assert!(thumbnailed("image/png"));
211+ assert!(thumbnailed("image/webp"));
212+ assert!(thumbnailed("video/mp4"));
213+ assert!(thumbnailed("video/webm"));
214+ assert!(thumbnailed("video/quicktime"));
215+ assert!(!thumbnailed("application/pdf"));
216+ assert!(!thumbnailed("text/plain"));
217+ assert!(!thumbnailed("audio/mpeg"));
218+ assert!(!thumbnailed("application/octet-stream"));
219+ }
220+
221+ /// Renders a tiny mp4 with `ffmpeg`'s own test pattern, for the tests
222+ /// that need a real video. `None` when the render itself fails.
223+ fn make_test_mp4(duration_secs: &str) -> Option<Vec<u8>> {
224+ static COUNTER: AtomicU64 = AtomicU64::new(0);
225+ let path = std::env::temp_dir().join(format!(
226+ "in-test-video-{}-{}.mp4",
227+ std::process::id(),
228+ COUNTER.fetch_add(1, Ordering::Relaxed)
229+ ));
230+ let rendered = Command::new("ffmpeg")
231+ .args([
232+ "-v",
233+ "error",
234+ "-f",
235+ "lavfi",
236+ "-i",
237+ &format!("testsrc=duration={duration_secs}:size=64x64:rate=10"),
238+ "-pix_fmt",
239+ "yuv420p",
240+ "-c:v",
241+ "mpeg4",
242+ "-y",
243+ ])
244+ .arg(&path)
245+ .stdin(Stdio::null())
246+ .stdout(Stdio::null())
247+ .stderr(Stdio::null())
248+ .status()
249+ .ok()?;
250+ let bytes = if rendered.success() {
251+ std::fs::read(&path).ok()
252+ } else {
253+ None
254+ };
255+ let _ = std::fs::remove_file(&path);
256+ bytes
257+ }
258+
259+ #[test]
260+ fn a_video_frame_makes_a_webp_thumbnail() {
261+ if !ffmpeg_available() {
262+ // No decoder on PATH, no test: the upload path degrades the same
263+ // way and asserts nothing here.
264+ return;
265+ }
266+ let mp4 = make_test_mp4("2").expect("ffmpeg renders the fixture");
267+ let thumb = thumbnail_for_video_bytes(&mp4).expect("a frame is framed");
268+ assert_eq!(&thumb[0..4], b"RIFF");
269+ assert_eq!(&thumb[8..12], b"WEBP");
270+ let back = image::load_from_memory(&thumb).unwrap();
271+ assert!(back.width() <= THUMB_MAX_DIM && back.height() <= THUMB_MAX_DIM);
272+ }
273+
274+ #[test]
275+ fn a_sub_second_clip_falls_back_to_its_first_frame() {
276+ if !ffmpeg_available() {
277+ return;
278+ }
279+ let mp4 = make_test_mp4("0.3").expect("ffmpeg renders the fixture");
280+ let thumb = thumbnail_for_video_bytes(&mp4).expect("short clips frame too");
281+ assert_eq!(&thumb[0..4], b"RIFF");
282+ assert_eq!(&thumb[8..12], b"WEBP");
283+ }
284+
285+ #[test]
286+ fn garbage_video_makes_no_thumbnail() {
287+ // Bytes `ffmpeg` cannot read — and a path that is not a file at all —
288+ // degrade to `None`, on every machine: with `ffmpeg` the extraction
289+ // fails, without it no attempt runs. Either way nothing panics and
290+ // nothing hangs.
291+ let mut garbage = b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00".to_vec();
292+ garbage.extend_from_slice(&[0xA5u8; 4096]);
293+ assert!(thumbnail_for_video_bytes(&garbage).is_none());
294+ assert!(thumbnail_for_video_bytes(&[]).is_none());
295+ assert!(
296+ thumbnail_for_video_file(Path::new("/nonexistent/in-thumb-probe")).is_none()
297+ );
298+ }
299+}
crates/in-core/tests/store.rsadded+1122 -0
@@ -0,0 +1,1122 @@
1+//! Integration tests for in-core: the storage boundary driven through the
2+//! Turso implementation, and the provisioning and drive flows on top of it.
3+//!
4+//! New integration tests belong in this file rather than a new `tests/*.rs`:
5+//! one test binary links and runs once.
6+
7+use std::path::PathBuf;
8+
9+use in_core::store::{
10+ CHUNK_SIZE, ShareKind, Store, StoreError, ThumbState, TursoStore, UploadState,
11+};
12+use in_core::{File, Folder, User};
13+use time::{Duration, OffsetDateTime};
14+use ulid::Ulid;
15+
16+/// A throwaway database on disk. Turso's in-memory mode is not what production
17+/// runs, so the tests exercise a real file.
18+struct Scratch {
19+ dir: PathBuf,
20+ db: PathBuf,
21+ storage: PathBuf,
22+ store: TursoStore,
23+}
24+
25+impl Scratch {
26+ async fn open() -> Self {
27+ let dir = std::env::temp_dir().join(format!("in-test-{}", Ulid::new()));
28+ std::fs::create_dir_all(&dir).unwrap();
29+ let db = dir.join("in.db");
30+ let storage = dir.join("storage");
31+ let store = TursoStore::open(db.to_str().unwrap(), Some(&storage))
32+ .await
33+ .unwrap();
34+ Self {
35+ dir,
36+ db,
37+ storage,
38+ store,
39+ }
40+ }
41+
42+ /// Reopens the same database file, running the boot path again — the
43+ /// sweep, the prune, the purge — against what the test left behind.
44+ async fn reopen(&mut self) {
45+ drop(std::mem::replace(
46+ &mut self.store,
47+ TursoStore::open(self.db.to_str().unwrap(), Some(&self.storage.clone()))
48+ .await
49+ .unwrap(),
50+ ));
51+ }
52+}
53+
54+/// A second, independent connection to the scratch database, for tests that
55+/// need to write a column the way it actually sits on disk rather than
56+/// through [`Store`]'s API.
57+async fn raw_conn(scratch: &Scratch) -> turso::Connection {
58+ let db = turso::Builder::new_local(scratch.db.to_str().unwrap())
59+ .build()
60+ .await
61+ .unwrap();
62+ db.connect().unwrap()
63+}
64+
65+impl Drop for Scratch {
66+ fn drop(&mut self) {
67+ let _ = std::fs::remove_dir_all(&self.dir);
68+ }
69+}
70+
71+async fn alice(store: &TursoStore) -> User {
72+ store
73+ .provision_user("sub-alice", "alice@example.com", "Alice", 1024 * 1024 * 1024)
74+ .await
75+ .unwrap()
76+}
77+
78+async fn bob(store: &TursoStore) -> User {
79+ store
80+ .provision_user("sub-bob", "bob@example.com", "Bob", 1024 * 1024 * 1024)
81+ .await
82+ .unwrap()
83+}
84+
85+/// A 4x4 red PNG: the smallest thing the thumbnailer must accept.
86+fn png_bytes() -> Vec<u8> {
87+ let img = image::RgbImage::from_pixel(4, 4, image::Rgb([200, 30, 30]));
88+ let mut out = Vec::new();
89+ img.write_to(
90+ &mut std::io::Cursor::new(&mut out),
91+ image::ImageFormat::Png,
92+ )
93+ .unwrap();
94+ out
95+}
96+
97+#[tokio::test]
98+async fn the_schema_is_created_once_and_survives_reopen() {
99+ let dir = std::env::temp_dir().join(format!("in-test-{}", Ulid::new()));
100+ std::fs::create_dir_all(&dir).unwrap();
101+ let path = dir.join("in.db").to_string_lossy().into_owned();
102+
103+ let first = TursoStore::open(&path, None).await.unwrap();
104+ alice(&first).await;
105+ drop(first);
106+
107+ // Re-opening a database that already has tables must not re-run the
108+ // schema (its CREATE TABLE would fail on the first one) and must not
109+ // lose what the first open wrote. `None` storage derives beside the
110+ // database, so the second open finds the same tree.
111+ let second = TursoStore::open(&path, None).await.unwrap();
112+ assert_eq!(
113+ second
114+ .user_by_oidc_sub("sub-alice")
115+ .await
116+ .unwrap()
117+ .unwrap()
118+ .email,
119+ "alice@example.com"
120+ );
121+ assert!(dir.join("storage").join("files").is_dir());
122+ drop(second);
123+ let _ = std::fs::remove_dir_all(&dir);
124+}
125+
126+#[tokio::test]
127+async fn the_first_user_is_admin_and_sign_ins_refresh_the_row() {
128+ let scratch = Scratch::open().await;
129+ let first = alice(&scratch.store).await;
130+ assert!(first.admin);
131+ assert_eq!(first.quota_bytes, 1024 * 1024 * 1024);
132+ assert_eq!(first.used_bytes, 0);
133+ assert!(first.last_seen_at.is_some());
134+
135+ let second = bob(&scratch.store).await;
136+ assert!(!second.admin);
137+
138+ // A returning person keeps their id, admin flag and quota; the provider's
139+ // new address and name win, and the sighting is stamped.
140+ let again = scratch
141+ .store
142+ .provision_user("sub-alice", "alice@new.com", "Alice New", 1)
143+ .await
144+ .unwrap();
145+ assert_eq!(again.id, first.id);
146+ assert!(again.admin);
147+ assert_eq!(again.email, "alice@new.com");
148+ assert_eq!(again.display_name, "Alice New");
149+ assert_eq!(again.quota_bytes, 1024 * 1024 * 1024);
150+}
151+
152+#[tokio::test]
153+async fn quota_and_disablement_round_trip() {
154+ let scratch = Scratch::open().await;
155+ let user = alice(&scratch.store).await;
156+ scratch.store.set_user_quota(&user.id, 42).await.unwrap();
157+ scratch
158+ .store
159+ .set_user_disabled(&user.id, true)
160+ .await
161+ .unwrap();
162+ let back = scratch.store.user(&user.id).await.unwrap().unwrap();
163+ assert_eq!(back.quota_bytes, 42);
164+ assert!(back.disabled);
165+ assert!(matches!(
166+ scratch.store.set_user_quota("no-such-user", 1).await,
167+ Err(StoreError::NotFound)
168+ ));
169+}
170+
171+#[tokio::test]
172+async fn folders_nest_and_names_are_unique_among_live_siblings() {
173+ let scratch = Scratch::open().await;
174+ let user = alice(&scratch.store).await;
175+ let root = scratch
176+ .store
177+ .create_folder(&user.id, None, "root")
178+ .await
179+ .unwrap();
180+ let kid = scratch
181+ .store
182+ .create_folder(&user.id, Some(&root.id), "kid")
183+ .await
184+ .unwrap();
185+ assert_eq!(kid.parent_id.as_deref(), Some(root.id.as_str()));
186+
187+ assert!(matches!(
188+ scratch.store.create_folder(&user.id, None, "root").await,
189+ Err(StoreError::NameTaken)
190+ ));
191+ // Same name in a different directory is a different name.
192+ scratch
193+ .store
194+ .create_folder(&user.id, Some(&root.id), "root")
195+ .await
196+ .unwrap();
197+
198+ let listing = scratch.store.list_children(&user.id, None).await.unwrap();
199+ assert_eq!(listing.folders.len(), 1);
200+ let listing = scratch
201+ .store
202+ .list_children(&user.id, Some(&root.id))
203+ .await
204+ .unwrap();
205+ assert_eq!(listing.folders.len(), 2);
206+}
207+
208+#[tokio::test]
209+async fn a_folder_moved_into_its_descendant_is_refused() {
210+ let scratch = Scratch::open().await;
211+ let user = alice(&scratch.store).await;
212+ let a = scratch.store.create_folder(&user.id, None, "a").await.unwrap();
213+ let b = scratch
214+ .store
215+ .create_folder(&user.id, Some(&a.id), "b")
216+ .await
217+ .unwrap();
218+ let c = scratch
219+ .store
220+ .create_folder(&user.id, Some(&b.id), "c")
221+ .await
222+ .unwrap();
223+
224+ assert!(matches!(
225+ scratch.store.move_folder(&a.id, Some(&c.id)).await,
226+ Err(StoreError::Cycle)
227+ ));
228+ assert!(matches!(
229+ scratch.store.move_folder(&a.id, Some(&a.id)).await,
230+ Err(StoreError::Cycle)
231+ ));
232+ // The refused moves changed nothing.
233+ let back: Folder = scratch.store.folder(&a.id).await.unwrap().unwrap();
234+ assert_eq!(back.parent_id, None);
235+
236+ // A legal move lands.
237+ scratch.store.move_folder(&c.id, None).await.unwrap();
238+ let back: Folder = scratch.store.folder(&c.id).await.unwrap().unwrap();
239+ assert_eq!(back.parent_id, None);
240+}
241+
242+#[tokio::test]
243+async fn strangers_folders_answer_cross_owner() {
244+ let scratch = Scratch::open().await;
245+ let user = alice(&scratch.store).await;
246+ let other = bob(&scratch.store).await;
247+ let folder = scratch
248+ .store
249+ .create_folder(&user.id, None, "mine")
250+ .await
251+ .unwrap();
252+
253+ // The store names the mismatch; the route layer answers 404 to it, never
254+ // 403, so a stranger learns nothing about which ids exist.
255+ assert!(matches!(
256+ scratch
257+ .store
258+ .create_folder(&other.id, Some(&folder.id), "squat")
259+ .await,
260+ Err(StoreError::CrossOwner)
261+ ));
262+ let file = scratch
263+ .store
264+ .insert_file(&user.id, None, "note", b"data")
265+ .await
266+ .unwrap();
267+ let bobs_folder = scratch
268+ .store
269+ .create_folder(&other.id, None, "bobs")
270+ .await
271+ .unwrap();
272+ assert!(matches!(
273+ scratch.store.move_file(&file.id, Some(&bobs_folder.id)).await,
274+ Err(StoreError::CrossOwner)
275+ ));
276+}
277+#[tokio::test]
278+async fn moving_across_owners_is_refused() {
279+ let scratch = Scratch::open().await;
280+ let user = alice(&scratch.store).await;
281+ let other = bob(&scratch.store).await;
282+ let folder = scratch
283+ .store
284+ .create_folder(&user.id, None, "mine")
285+ .await
286+ .unwrap();
287+ let theirs = scratch
288+ .store
289+ .create_folder(&other.id, None, "theirs")
290+ .await
291+ .unwrap();
292+ assert!(matches!(
293+ scratch.store.move_folder(&folder.id, Some(&theirs.id)).await,
294+ Err(StoreError::CrossOwner)
295+ ));
296+}
297+
298+#[tokio::test]
299+async fn names_are_labels_never_paths() {
300+ let scratch = Scratch::open().await;
301+ let user = alice(&scratch.store).await;
302+ let folder = scratch
303+ .store
304+ .create_folder(&user.id, None, "../../etc")
305+ .await
306+ .unwrap();
307+ assert_eq!(folder.name, "etc");
308+ let file = scratch
309+ .store
310+ .insert_file(&user.id, None, "", b"data")
311+ .await
312+ .unwrap();
313+ assert_eq!(file.name, "Untitled");
314+}
315+
316+#[tokio::test]
317+async fn an_inserted_file_round_trips_through_its_row_and_bytes() {
318+ let scratch = Scratch::open().await;
319+ let user = alice(&scratch.store).await;
320+ let mut rx = scratch.store.subscribe();
321+ let bytes = png_bytes();
322+ let file: File = scratch
323+ .store
324+ .insert_file(&user.id, None, "photo.png", &bytes)
325+ .await
326+ .unwrap();
327+ // The mime is sniffed from the bytes, the thumbnail is attempted for an
328+ // image, and the bytes land on disk under the row's id.
329+ assert_eq!(file.mime, "image/png");
330+ assert_eq!(file.thumb_state, ThumbState::Ready);
331+ assert_eq!(file.size_bytes, bytes.len() as u64);
332+ assert_eq!(scratch.store.file_bytes(&file.id).await.unwrap().unwrap(), bytes);
333+ assert!(scratch.storage.join("files").join(&file.id).is_file());
334+ let thumb = scratch.store.thumb_bytes(&file.id).await.unwrap().unwrap();
335+ assert_eq!(&thumb[0..4], b"RIFF");
336+ // The committed write announced the library.
337+ let change = rx.try_recv().unwrap();
338+ assert_eq!(change.topic.kind(), "library");
339+
340+ // What the sniffer cannot name stays generic, and no thumbnail is
341+ // attempted for it.
342+ let text = scratch
343+ .store
344+ .insert_file(&user.id, None, "notes.txt", b"hello")
345+ .await
346+ .unwrap();
347+ assert_eq!(text.mime, "text/plain");
348+ assert_eq!(text.thumb_state, ThumbState::None);
349+ assert!(scratch.store.thumb_bytes(&text.id).await.unwrap().is_none());
350+}
351+
352+/// Renders a tiny mp4 with `ffmpeg`'s own test pattern. `None` when there is
353+/// no `ffmpeg` on `PATH`, or the render itself fails — callers skip silently.
354+fn make_test_mp4() -> Option<Vec<u8>> {
355+ if !in_core::thumbs::ffmpeg_available() {
356+ return None;
357+ }
358+ let path = std::env::temp_dir().join(format!("in-test-upload-{}.mp4", Ulid::new()));
359+ let rendered = std::process::Command::new("ffmpeg")
360+ .args([
361+ "-v",
362+ "error",
363+ "-f",
364+ "lavfi",
365+ "-i",
366+ "testsrc=duration=2:size=64x64:rate=10",
367+ "-pix_fmt",
368+ "yuv420p",
369+ "-c:v",
370+ "mpeg4",
371+ "-y",
372+ ])
373+ .arg(&path)
374+ .stdin(std::process::Stdio::null())
375+ .stdout(std::process::Stdio::null())
376+ .stderr(std::process::Stdio::null())
377+ .status()
378+ .ok()?;
379+ let bytes = if rendered.success() {
380+ std::fs::read(&path).ok()
381+ } else {
382+ None
383+ };
384+ let _ = std::fs::remove_file(&path);
385+ bytes
386+}
387+
388+#[tokio::test]
389+async fn a_broken_video_uploads_fine_without_a_thumbnail() {
390+ let scratch = Scratch::open().await;
391+ let user = alice(&scratch.store).await;
392+ // Wears an mp4's magic but holds garbage: `ffmpeg` — when present —
393+ // cannot frame it, and the upload must not care.
394+ let mut bytes = b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00".to_vec();
395+ bytes.extend_from_slice(&[0xA5u8; 4096]);
396+ let file = scratch
397+ .store
398+ .insert_file(&user.id, None, "clip.mp4", &bytes)
399+ .await
400+ .unwrap();
401+ assert_eq!(file.mime, "video/mp4");
402+ // `Failed` when `ffmpeg` tried and missed, `None` when no attempt was
403+ // possible: never `Ready`, and never an upload error.
404+ assert!(matches!(
405+ file.thumb_state,
406+ ThumbState::Failed | ThumbState::None
407+ ));
408+ assert!(scratch.store.thumb_bytes(&file.id).await.unwrap().is_none());
409+ assert_eq!(scratch.store.file_bytes(&file.id).await.unwrap().unwrap(), bytes);
410+}
411+
412+#[tokio::test]
413+async fn a_real_video_uploads_with_a_thumbnail() {
414+ let Some(bytes) = make_test_mp4() else {
415+ // No decoder on PATH, no test: the upload degrades to its icon.
416+ return;
417+ };
418+ let scratch = Scratch::open().await;
419+ let user = alice(&scratch.store).await;
420+ let file = scratch
421+ .store
422+ .insert_file(&user.id, None, "clip.mp4", &bytes)
423+ .await
424+ .unwrap();
425+ assert_eq!(file.mime, "video/mp4");
426+ assert_eq!(file.thumb_state, ThumbState::Ready);
427+ let thumb = scratch.store.thumb_bytes(&file.id).await.unwrap().unwrap();
428+ assert_eq!(&thumb[0..4], b"RIFF");
429+ assert_eq!(&thumb[8..12], b"WEBP");
430+}
431+
432+#[tokio::test]
433+async fn a_chunked_video_upload_finishes_with_a_thumbnail() {
434+ let Some(bytes) = make_test_mp4() else {
435+ return;
436+ };
437+ let scratch = Scratch::open().await;
438+ let user = alice(&scratch.store).await;
439+ let session = scratch
440+ .store
441+ .create_upload_session(&user.id, None, "clip.mp4", bytes.len() as u64)
442+ .await
443+ .unwrap();
444+ scratch.store.record_chunk(&session.id, 0, &bytes).await.unwrap();
445+ let file = scratch.store.finish_upload(&session.id).await.unwrap();
446+ assert_eq!(file.mime, "video/mp4");
447+ assert_eq!(file.thumb_state, ThumbState::Ready);
448+ let thumb = scratch.store.thumb_bytes(&file.id).await.unwrap().unwrap();
449+ assert_eq!(&thumb[0..4], b"RIFF");
450+ assert_eq!(&thumb[8..12], b"WEBP");
451+}
452+
453+#[tokio::test]
454+async fn a_claimed_mime_is_never_trusted() {
455+ let scratch = Scratch::open().await;
456+ let user = alice(&scratch.store).await;
457+ // Named like an executable, holding a PNG: the row says image, because
458+ // the bytes do.
459+ let file = scratch
460+ .store
461+ .insert_file(&user.id, None, "evil.exe", &png_bytes())
462+ .await
463+ .unwrap();
464+ assert_eq!(file.mime, "image/png");
465+}
466+
467+#[tokio::test]
468+async fn trashing_a_folder_cascades_and_restore_needs_live_ancestors() {
469+ let scratch = Scratch::open().await;
470+ let user = alice(&scratch.store).await;
471+ let root = scratch.store.create_folder(&user.id, None, "root").await.unwrap();
472+ let kid = scratch
473+ .store
474+ .create_folder(&user.id, Some(&root.id), "kid")
475+ .await
476+ .unwrap();
477+ let file = scratch
478+ .store
479+ .insert_file(&user.id, Some(&kid.id), "deep.txt", b"deep")
480+ .await
481+ .unwrap();
482+
483+ scratch.store.delete_folder(&root.id).await.unwrap();
484+ assert!(scratch.store.folder(&root.id).await.unwrap().unwrap().deleted_at.is_some());
485+ assert!(scratch.store.folder(&kid.id).await.unwrap().unwrap().deleted_at.is_some());
486+ assert!(scratch.store.file(&file.id).await.unwrap().unwrap().deleted_at.is_some());
487+ // Trashed rows leave the listing but join the trash.
488+ assert!(scratch.store.list_children(&user.id, None).await.unwrap().folders.is_empty());
489+ let trash = scratch.store.list_trash(&user.id).await.unwrap();
490+ assert_eq!(trash.folders.len(), 2);
491+ assert_eq!(trash.files.len(), 1);
492+
493+ // Restoring from under trash is refused: the ancestor is still down.
494+ assert!(matches!(
495+ scratch.store.restore_folder(&kid.id).await,
496+ Err(StoreError::AncestorTrashed)
497+ ));
498+ assert!(matches!(
499+ scratch.store.restore_file(&file.id).await,
500+ Err(StoreError::AncestorTrashed)
501+ ));
502+
503+ // Restoring the root brings the whole subtree back.
504+ scratch.store.restore_folder(&root.id).await.unwrap();
505+ assert!(scratch.store.folder(&kid.id).await.unwrap().unwrap().deleted_at.is_none());
506+ assert!(scratch.store.file(&file.id).await.unwrap().unwrap().deleted_at.is_none());
507+ assert_eq!(scratch.store.list_children(&user.id, None).await.unwrap().folders.len(), 1);
508+}
509+
510+#[tokio::test]
511+async fn a_trashed_name_is_free_until_restored() {
512+ let scratch = Scratch::open().await;
513+ let user = alice(&scratch.store).await;
514+ let first = scratch.store.create_folder(&user.id, None, "x").await.unwrap();
515+ scratch.store.delete_folder(&first.id).await.unwrap();
516+ // Deleting frees the name; restoring onto a live squatter is refused.
517+ scratch.store.create_folder(&user.id, None, "x").await.unwrap();
518+ assert!(matches!(
519+ scratch.store.restore_folder(&first.id).await,
520+ Err(StoreError::NameTaken)
521+ ));
522+}
523+
524+#[tokio::test]
525+async fn used_bytes_counts_trash_and_purge_frees_it() {
526+ let scratch = Scratch::open().await;
527+ let user = alice(&scratch.store).await;
528+ let a = scratch.store.insert_file(&user.id, None, "a", &[0u8; 10]).await.unwrap();
529+ let b = scratch.store.insert_file(&user.id, None, "b", &[0u8; 20]).await.unwrap();
530+ assert_eq!(scratch.store.user(&user.id).await.unwrap().unwrap().used_bytes, 30);
531+
532+ // Trash counts: the bytes are still on disk, still restorable.
533+ scratch.store.delete_file(&a.id).await.unwrap();
534+ assert_eq!(scratch.store.user(&user.id).await.unwrap().unwrap().used_bytes, 30);
535+ scratch.store.restore_file(&a.id).await.unwrap();
536+ assert_eq!(scratch.store.user(&user.id).await.unwrap().unwrap().used_bytes, 30);
537+
538+ // Purge frees: the row goes and the bytes follow.
539+ scratch.store.delete_file(&a.id).await.unwrap();
540+ assert!(scratch.store.purge_file(&a.id).await.unwrap());
541+ assert_eq!(scratch.store.user(&user.id).await.unwrap().unwrap().used_bytes, 20);
542+ assert!(!scratch.storage.join("files").join(&a.id).exists());
543+
544+ // A live file is never purged, and a missing one is not found.
545+ assert!(!scratch.store.purge_file(&b.id).await.unwrap());
546+ assert!(matches!(
547+ scratch.store.purge_file("no-such-file").await,
548+ Err(StoreError::NotFound)
549+ ));
550+
551+ // Emptying the trash takes the rest.
552+ scratch.store.delete_file(&b.id).await.unwrap();
553+ assert_eq!(scratch.store.empty_trash(&user.id).await.unwrap(), 1);
554+ assert_eq!(scratch.store.user(&user.id).await.unwrap().unwrap().used_bytes, 0);
555+ assert!(scratch.store.list_trash(&user.id).await.unwrap().files.is_empty());
556+}
557+
558+#[tokio::test]
559+async fn quota_is_enforced_at_start_and_at_finish() {
560+ let scratch = Scratch::open().await;
561+ let user = alice(&scratch.store).await;
562+ scratch.store.set_user_quota(&user.id, 100).await.unwrap();
563+
564+ // Over quota at open: refused with nothing on disk to clean up.
565+ assert!(matches!(
566+ scratch.store.create_upload_session(&user.id, None, "big", 101).await,
567+ Err(StoreError::QuotaExceeded)
568+ ));
569+
570+ // Fits at open, over quota by finish: the chunks stay staged for another
571+ // attempt once space is freed.
572+ let session = scratch
573+ .store
574+ .create_upload_session(&user.id, None, "late", 90)
575+ .await
576+ .unwrap();
577+ scratch.store.record_chunk(&session.id, 0, &[7u8; 90]).await.unwrap();
578+ scratch.store.insert_file(&user.id, None, "filler", &[0u8; 20]).await.unwrap();
579+ assert!(matches!(
580+ scratch.store.finish_upload(&session.id).await,
581+ Err(StoreError::QuotaExceeded)
582+ ));
583+ let back = scratch.store.upload_session(&session.id).await.unwrap().unwrap();
584+ assert_eq!(back.state, UploadState::Active);
585+
586+ // Room freed, the same chunks finish.
587+ scratch.store.set_user_quota(&user.id, 200).await.unwrap();
588+ let file = scratch.store.finish_upload(&session.id).await.unwrap();
589+ assert_eq!(file.size_bytes, 90);
590+}
591+
592+#[tokio::test]
593+async fn trash_writes_are_invisible_and_purge_takes_subtrees() {
594+ let scratch = Scratch::open().await;
595+ let user = alice(&scratch.store).await;
596+ let root = scratch.store.create_folder(&user.id, None, "root").await.unwrap();
597+ scratch.store.delete_folder(&root.id).await.unwrap();
598+
599+ // Nothing is created, moved or uploaded under trash.
600+ assert!(matches!(
601+ scratch.store.create_folder(&user.id, Some(&root.id), "kid").await,
602+ Err(StoreError::NotFound)
603+ ));
604+ assert!(matches!(
605+ scratch.store.insert_file(&user.id, Some(&root.id), "f", b"x").await,
606+ Err(StoreError::NotFound)
607+ ));
608+
609+ // Purging the expired takes the folder row itself.
610+ let purged = scratch
611+ .store
612+ .purge_expired(OffsetDateTime::now_utc() + Duration::days(31))
613+ .await
614+ .unwrap();
615+ assert_eq!(purged, 1);
616+ assert!(scratch.store.folder(&root.id).await.unwrap().is_none());
617+ // Too fresh to purge: a cutoff taken before the trash moment matches
618+ // nothing.
619+ let root2 = scratch.store.create_folder(&user.id, None, "root2").await.unwrap();
620+ let cutoff = OffsetDateTime::now_utc();
621+ scratch.store.delete_folder(&root2.id).await.unwrap();
622+ assert_eq!(scratch.store.purge_expired(cutoff).await.unwrap(), 0);
623+}
624+#[tokio::test]
625+async fn share_links_open_until_revoked_or_expired() {
626+ let scratch = Scratch::open().await;
627+ let user = alice(&scratch.store).await;
628+ let file = scratch.store.insert_file(&user.id, None, "f", b"data").await.unwrap();
629+ let now = OffsetDateTime::now_utc();
630+
631+ let created = scratch
632+ .store
633+ .create_share_link(&user.id, ShareKind::File, &file.id, true, None)
634+ .await
635+ .unwrap();
636+ // The token is shown once; the row keeps only the hash.
637+ assert!(!created.token.is_empty());
638+ assert_ne!(created.link.token_hash, created.token);
639+ // The route hashes the plaintext with the store's own function.
640+ assert_eq!(in_core::hash_share_token(&created.token), created.link.token_hash);
641+ let resolved = scratch
642+ .store
643+ .resolve_share_link(&created.link.token_hash, now)
644+ .await
645+ .unwrap()
646+ .unwrap();
647+ assert_eq!(resolved.target_id, file.id);
648+ assert!(resolved.can_download);
649+
650+ // A wrong token and a revoked link both answer None.
651+ assert!(scratch.store.resolve_share_link("wrong", now).await.unwrap().is_none());
652+ scratch.store.revoke_share_link(&created.link.id).await.unwrap();
653+ assert!(scratch.store.resolve_share_link(&created.link.token_hash, now).await.unwrap().is_none());
654+ // Revoking twice is not an error.
655+ scratch.store.revoke_share_link(&created.link.id).await.unwrap();
656+
657+ // An already-expired link never opens.
658+ let past = scratch
659+ .store
660+ .create_share_link(
661+ &user.id,
662+ ShareKind::File,
663+ &file.id,
664+ false,
665+ Some(now - Duration::hours(1)),
666+ )
667+ .await
668+ .unwrap();
669+ assert!(!past.link.is_live(now));
670+ assert!(scratch.store.resolve_share_link(&past.link.token_hash, now).await.unwrap().is_none());
671+ assert_eq!(scratch.store.share_links(&user.id).await.unwrap().len(), 2);
672+}
673+
674+#[tokio::test]
675+async fn per_person_shares_gate_visibility() {
676+ let scratch = Scratch::open().await;
677+ let user = alice(&scratch.store).await;
678+ let friend = bob(&scratch.store).await;
679+ let stranger = scratch
680+ .store
681+ .provision_user("sub-caro", "caro@example.com", "Caro", 1024)
682+ .await
683+ .unwrap();
684+ let file = scratch.store.insert_file(&user.id, None, "shared", b"data").await.unwrap();
685+
686+ assert!(!scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap());
687+ scratch.store.add_share_user(&user.id, ShareKind::File, &file.id, &friend.id, true).await.unwrap();
688+ assert!(scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap());
689+ // The owner always sees; a stranger never does; a missing target is
690+ // simply not seen.
691+ assert!(scratch.store.can_see(ShareKind::File, &file.id, &user.id).await.unwrap());
692+ assert!(!scratch.store.can_see(ShareKind::File, &file.id, &stranger.id).await.unwrap());
693+ assert!(!scratch.store.can_see(ShareKind::File, "missing", &friend.id).await.unwrap());
694+
695+ let shared = scratch.store.shares_for_user(&friend.id).await.unwrap();
696+ assert_eq!(shared.len(), 1);
697+ assert_eq!(shared[0].name, "shared");
698+ assert_eq!(shared[0].mime.as_deref(), Some("text/plain"));
699+
700+ // Trash hides the target from the grantee but not from the owner; purge
701+ // takes the grant with the row.
702+ scratch.store.delete_file(&file.id).await.unwrap();
703+ assert!(scratch.store.shares_for_user(&friend.id).await.unwrap().is_empty());
704+ assert!(!scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap());
705+ assert!(scratch.store.can_see(ShareKind::File, &file.id, &user.id).await.unwrap());
706+
707+ scratch.store.remove_share_user(ShareKind::File, &file.id, &friend.id).await.unwrap();
708+ scratch.store.restore_file(&file.id).await.unwrap();
709+ assert!(!scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap());
710+}
711+
712+#[tokio::test]
713+async fn an_upload_assembles_chunks_in_order_and_sniffs() {
714+ let scratch = Scratch::open().await;
715+ let user = alice(&scratch.store).await;
716+ let bytes = png_bytes();
717+ let session = scratch
718+ .store
719+ .create_upload_session(&user.id, None, "avatar.exe", bytes.len() as u64)
720+ .await
721+ .unwrap();
722+ assert_eq!(session.chunk_size, CHUNK_SIZE);
723+ // A chunk that is not exactly the promised bytes is refused.
724+ assert!(matches!(
725+ scratch.store.record_chunk(&session.id, 0, b"short").await,
726+ Err(StoreError::BadChunk)
727+ ));
728+ assert!(matches!(
729+ scratch.store.record_chunk(&session.id, 1, &bytes).await,
730+ Err(StoreError::BadChunk)
731+ ));
732+ let back = scratch.store.record_chunk(&session.id, 0, &bytes).await.unwrap();
733+ assert_eq!(back.received_bytes, bytes.len() as u64);
734+
735+ let file = scratch.store.finish_upload(&session.id).await.unwrap();
736+ // Named like an executable, holding a PNG: sniffed, thumbed, stored.
737+ assert_eq!(file.name, "avatar.exe");
738+ assert_eq!(file.mime, "image/png");
739+ assert_eq!(file.thumb_state, ThumbState::Ready);
740+ assert_eq!(scratch.store.file_bytes(&file.id).await.unwrap().unwrap(), bytes);
741+ assert!(scratch.storage.join("files").join(&file.id).is_file());
742+ let done = scratch.store.upload_session(&session.id).await.unwrap().unwrap();
743+ assert_eq!(done.state, UploadState::Done);
744+ assert!(!scratch.storage.join("uploads").join(&session.id).exists());
745+}
746+
747+#[tokio::test]
748+async fn an_empty_upload_finishes_an_empty_file() {
749+ let scratch = Scratch::open().await;
750+ let user = alice(&scratch.store).await;
751+ let session = scratch.store.create_upload_session(&user.id, None, "empty", 0).await.unwrap();
752+ let file = scratch.store.finish_upload(&session.id).await.unwrap();
753+ assert_eq!(file.size_bytes, 0);
754+ assert_eq!(scratch.store.file_bytes(&file.id).await.unwrap().unwrap(), Vec::<u8>::new());
755+}
756+
757+#[tokio::test]
758+async fn uploads_abort_and_prune() {
759+ let scratch = Scratch::open().await;
760+ let user = alice(&scratch.store).await;
761+ let session = scratch
762+ .store
763+ .create_upload_session(&user.id, None, "abandoned", 4)
764+ .await
765+ .unwrap();
766+ scratch.store.record_chunk(&session.id, 0, b"1234").await.unwrap();
767+ scratch.store.abort_upload(&session.id).await.unwrap();
768+ assert_eq!(
769+ scratch.store.upload_session(&session.id).await.unwrap().unwrap().state,
770+ UploadState::Aborted
771+ );
772+ assert!(!scratch.storage.join("uploads").join(&session.id).exists());
773+ // Chunks on a dead session are refused; aborting twice is fine.
774+ assert!(matches!(
775+ scratch.store.record_chunk(&session.id, 0, b"1234").await,
776+ Err(StoreError::UploadExpired)
777+ ));
778+ scratch.store.abort_upload(&session.id).await.unwrap();
779+
780+ // Expiry prunes: the row says aborted and the chunks are gone.
781+ let session = scratch.store.create_upload_session(&user.id, None, "stale", 4).await.unwrap();
782+ scratch.store.record_chunk(&session.id, 0, b"1234").await.unwrap();
783+ let pruned = scratch
784+ .store
785+ .prune_expired_uploads(OffsetDateTime::now_utc() + Duration::hours(25))
786+ .await
787+ .unwrap();
788+ assert_eq!(pruned, 1);
789+ assert!(!scratch.storage.join("uploads").join(&session.id).exists());
790+ // Nothing expired: nothing pruned.
791+ assert_eq!(
792+ scratch.store.prune_expired_uploads(OffsetDateTime::now_utc()).await.unwrap(),
793+ 0
794+ );
795+}
796+
797+#[tokio::test]
798+async fn search_finds_live_names_and_nothing_else() {
799+ let scratch = Scratch::open().await;
800+ let user = alice(&scratch.store).await;
801+ let other = bob(&scratch.store).await;
802+ scratch.store.insert_file(&user.id, None, "quarterly report", b"1").await.unwrap();
803+ scratch.store.insert_file(&user.id, None, "quarterly review", b"2").await.unwrap();
804+ scratch.store.create_folder(&user.id, None, "quarters").await.unwrap();
805+ let trashed = scratch.store.insert_file(&user.id, None, "quarterly old", b"3").await.unwrap();
806+ scratch.store.insert_file(&other.id, None, "quarterly theirs", b"4").await.unwrap();
807+ scratch.store.delete_file(&trashed.id).await.unwrap();
808+
809+ let hits = scratch.store.search(&user.id, "quarter", 50).await.unwrap();
810+ assert_eq!(hits.files.len(), 2);
811+ assert_eq!(hits.folders.len(), 1);
812+ // Wildcards in the query search literally.
813+ let hits = scratch.store.search(&user.id, "report%", 50).await.unwrap();
814+ assert!(hits.files.is_empty());
815+ assert!(scratch.store.search(&user.id, " ", 50).await.unwrap().files.is_empty());
816+}
817+
818+#[tokio::test]
819+async fn the_boot_sweep_deletes_files_no_row_names() {
820+ let mut scratch = Scratch::open().await;
821+ let stray = scratch.storage.join("files").join("stray");
822+ std::fs::write(&stray, b"orphan").unwrap();
823+ let ghost = scratch.storage.join("uploads").join("ghost");
824+ std::fs::create_dir_all(&ghost).unwrap();
825+ std::fs::write(ghost.join("0"), b"chunk").unwrap();
826+ scratch.reopen().await;
827+ assert!(!stray.exists());
828+ assert!(!ghost.exists());
829+}
830+
831+#[tokio::test]
832+async fn a_row_whose_file_is_missing_is_kept() {
833+ let mut scratch = Scratch::open().await;
834+ let user = alice(&scratch.store).await;
835+ let file = scratch.store.insert_file(&user.id, None, "lost", b"data").await.unwrap();
836+ std::fs::remove_file(scratch.storage.join("files").join(&file.id)).unwrap();
837+ scratch.reopen().await;
838+ // Said out loud at boot, kept in the database: a lost file is a lost
839+ // file, not a lost fact.
840+ assert!(scratch.store.file(&file.id).await.unwrap().is_some());
841+ assert!(scratch.store.file_bytes(&file.id).await.unwrap().is_none());
842+}
843+
844+#[tokio::test]
845+async fn the_boot_prune_aborts_expired_sessions() {
846+ let mut scratch = Scratch::open().await;
847+ let user = alice(&scratch.store).await;
848+ let session = scratch.store.create_upload_session(&user.id, None, "stale", 4).await.unwrap();
849+ scratch.store.record_chunk(&session.id, 0, b"1234").await.unwrap();
850+ // Backdate the expiry the way a day-old row would wear it.
851+ let conn = raw_conn(&scratch).await;
852+ conn.execute(
853+ "UPDATE upload_session SET expires_at = '2000-01-01T00:00:00Z' WHERE id = ?1",
854+ turso::params![session.id.as_str()],
855+ )
856+ .await
857+ .unwrap();
858+ drop(conn);
859+ scratch.reopen().await;
860+ let back = scratch.store.upload_session(&session.id).await.unwrap().unwrap();
861+ assert_eq!(back.state, UploadState::Aborted);
862+ assert!(!scratch.storage.join("uploads").join(&session.id).exists());
863+}
864+#[tokio::test]
865+async fn email_lookup_folds_case() {
866+ let scratch = Scratch::open().await;
867+ let user = scratch
868+ .store
869+ .provision_user("sub-mixed", "Mixed@Example.COM", "Mixed", 1024)
870+ .await
871+ .unwrap();
872+ // Stored folded, found however it is asked.
873+ assert_eq!(user.email, "mixed@example.com");
874+ for query in ["mixed@example.com", "MIXED@EXAMPLE.COM", " Mixed@Example.com "] {
875+ let found = scratch.store.user_by_email(query).await.unwrap().unwrap();
876+ assert_eq!(found.id, user.id);
877+ }
878+ assert!(scratch.store.user_by_email("nobody@example.com").await.unwrap().is_none());
879+}
880+
881+#[tokio::test]
882+async fn download_needs_the_flag() {
883+ let scratch = Scratch::open().await;
884+ let user = alice(&scratch.store).await;
885+ let friend = bob(&scratch.store).await;
886+ let file = scratch.store.insert_file(&user.id, None, "f", b"data").await.unwrap();
887+
888+ // The owner always downloads; a stranger never does.
889+ assert!(scratch.store.can_download(ShareKind::File, &file.id, &user.id).await.unwrap());
890+ assert!(!scratch.store.can_download(ShareKind::File, &file.id, &friend.id).await.unwrap());
891+ assert!(!scratch.store.can_download(ShareKind::File, "missing", &friend.id).await.unwrap());
892+
893+ // A view-only grant opens the page but not the bytes.
894+ scratch.store.add_share_user(&user.id, ShareKind::File, &file.id, &friend.id, false).await.unwrap();
895+ assert!(scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap());
896+ assert!(!scratch.store.can_download(ShareKind::File, &file.id, &friend.id).await.unwrap());
897+
898+ // Re-sharing with the flag flips the grant in place.
899+ scratch.store.add_share_user(&user.id, ShareKind::File, &file.id, &friend.id, true).await.unwrap();
900+ assert!(scratch.store.can_download(ShareKind::File, &file.id, &friend.id).await.unwrap());
901+
902+ // Unsharing closes both.
903+ scratch.store.remove_share_user(ShareKind::File, &file.id, &friend.id).await.unwrap();
904+ assert!(!scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap());
905+ assert!(!scratch.store.can_download(ShareKind::File, &file.id, &friend.id).await.unwrap());
906+}
907+
908+#[tokio::test]
909+async fn a_folder_grant_covers_everything_under_it() {
910+ let scratch = Scratch::open().await;
911+ let user = alice(&scratch.store).await;
912+ let friend = bob(&scratch.store).await;
913+ let parent = scratch.store.create_folder(&user.id, None, "parent").await.unwrap();
914+ let kid = scratch
915+ .store
916+ .create_folder(&user.id, Some(&parent.id), "kid")
917+ .await
918+ .unwrap();
919+ let file = scratch
920+ .store
921+ .insert_file(&user.id, Some(&kid.id), "deep.txt", b"deep")
922+ .await
923+ .unwrap();
924+ assert!(!scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap());
925+
926+ // One grant on the top folder opens the whole subtree, files included.
927+ scratch.store.add_share_user(&user.id, ShareKind::Folder, &parent.id, &friend.id, true).await.unwrap();
928+ assert!(scratch.store.can_see(ShareKind::Folder, &kid.id, &friend.id).await.unwrap());
929+ assert!(scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap());
930+ assert!(scratch.store.can_download(ShareKind::File, &file.id, &friend.id).await.unwrap());
931+
932+ // Revoking the one grant closes the whole subtree again.
933+ scratch.store.remove_share_user(ShareKind::Folder, &parent.id, &friend.id).await.unwrap();
934+ assert!(!scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap());
935+ assert!(!scratch.store.can_download(ShareKind::File, &file.id, &friend.id).await.unwrap());
936+
937+ // A view-only folder grant sees the subtree but downloads nothing in it.
938+ scratch.store.add_share_user(&user.id, ShareKind::Folder, &parent.id, &friend.id, false).await.unwrap();
939+ assert!(scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap());
940+ assert!(!scratch.store.can_download(ShareKind::File, &file.id, &friend.id).await.unwrap());
941+}
942+
943+#[tokio::test]
944+async fn open_does_not_purge_trash() {
945+ let mut scratch = Scratch::open().await;
946+ let user = alice(&scratch.store).await;
947+ let folder = scratch.store.create_folder(&user.id, None, "doomed").await.unwrap();
948+ scratch.store.delete_folder(&folder.id).await.unwrap();
949+ // Age the trash past any deployment's cutoff the way a month-old row
950+ // would wear it.
951+ let conn = raw_conn(&scratch).await;
952+ conn.execute(
953+ "UPDATE folder SET deleted_at = '2000-01-01T00:00:00Z' WHERE id = ?1",
954+ turso::params![folder.id.as_str()],
955+ )
956+ .await
957+ .unwrap();
958+ drop(conn);
959+ // Reopening prunes uploads and sweeps orphans, but the trash waits for
960+ // an explicit purge_expired with the deployment's own cutoff.
961+ scratch.reopen().await;
962+ assert!(scratch.store.folder(&folder.id).await.unwrap().unwrap().deleted_at.is_some());
963+ assert_eq!(
964+ scratch.store.purge_expired(OffsetDateTime::now_utc()).await.unwrap(),
965+ 1
966+ );
967+ assert!(scratch.store.folder(&folder.id).await.unwrap().is_none());
968+}
969+#[tokio::test]
970+async fn purge_folder_removes_the_whole_trashed_subtree() {
971+ let scratch = Scratch::open().await;
972+ let user = alice(&scratch.store).await;
973+ let root = scratch.store.create_folder(&user.id, None, "root").await.unwrap();
974+ let kid = scratch
975+ .store
976+ .create_folder(&user.id, Some(&root.id), "kid")
977+ .await
978+ .unwrap();
979+ let file = scratch
980+ .store
981+ .insert_file(&user.id, Some(&kid.id), "deep.txt", b"deep")
982+ .await
983+ .unwrap();
984+ // A live folder is never purged — trash it first — and neither is a
985+ // missing one.
986+ assert!(matches!(
987+ scratch.store.purge_folder(&root.id).await,
988+ Err(StoreError::NotFound)
989+ ));
990+ assert!(matches!(
991+ scratch.store.purge_folder("no-such-folder").await,
992+ Err(StoreError::NotFound)
993+ ));
994+
995+ scratch.store.delete_folder(&root.id).await.unwrap();
996+ // Two folders and one file go: rows, bytes, usage and shares together.
997+ assert_eq!(scratch.store.purge_folder(&root.id).await.unwrap(), 3);
998+ assert!(scratch.store.folder(&root.id).await.unwrap().is_none());
999+ assert!(scratch.store.folder(&kid.id).await.unwrap().is_none());
1000+ assert!(scratch.store.file(&file.id).await.unwrap().is_none());
1001+ assert!(!scratch.storage.join("files").join(&file.id).exists());
1002+ assert_eq!(scratch.store.user(&user.id).await.unwrap().unwrap().used_bytes, 0);
1003+ assert!(scratch.store.list_trash(&user.id).await.unwrap().folders.is_empty());
1004+}
1005+
1006+#[tokio::test]
1007+async fn finish_upload_refused_leaves_no_bytes_behind() {
1008+ let scratch = Scratch::open().await;
1009+ let user = alice(&scratch.store).await;
1010+ let session = scratch.store.create_upload_session(&user.id, None, "late", 4).await.unwrap();
1011+ scratch.store.record_chunk(&session.id, 0, b"1234").await.unwrap();
1012+ // The library fills while the chunks arrive: someone else's bytes land
1013+ // first and the ceiling drops under the session's total.
1014+ scratch.store.insert_file(&user.id, None, "filler", b"12345").await.unwrap();
1015+ scratch.store.set_user_quota(&user.id, 5).await.unwrap();
1016+ let before = {
1017+ let mut names: Vec<_> = std::fs::read_dir(scratch.storage.join("files"))
1018+ .unwrap()
1019+ .map(|entry| entry.unwrap().file_name())
1020+ .collect();
1021+ names.sort();
1022+ names
1023+ };
1024+ assert!(matches!(
1025+ scratch.store.finish_upload(&session.id).await,
1026+ Err(StoreError::QuotaExceeded)
1027+ ));
1028+ // Refused before the rename: files/ holds exactly what it held, with no
1029+ // assembled copy and no temp left behind — and the chunks stay staged
1030+ // for another attempt.
1031+ let after = {
1032+ let mut names: Vec<_> = std::fs::read_dir(scratch.storage.join("files"))
1033+ .unwrap()
1034+ .map(|entry| entry.unwrap().file_name())
1035+ .collect();
1036+ names.sort();
1037+ names
1038+ };
1039+ assert_eq!(before, after);
1040+ assert!(scratch.storage.join("uploads").join(&session.id).is_dir());
1041+}
1042+
1043+#[tokio::test]
1044+async fn a_download_grant_above_a_view_only_grant_still_downloads() {
1045+ let scratch = Scratch::open().await;
1046+ let user = alice(&scratch.store).await;
1047+ let friend = bob(&scratch.store).await;
1048+ let folder = scratch.store.create_folder(&user.id, None, "shared").await.unwrap();
1049+ let file = scratch.store.insert_file(&user.id, Some(&folder.id), "note", b"data").await.unwrap();
1050+ // Most permissive wins across the chain: the folder's download grant
1051+ // opens the bytes even with a view-only grant on the file itself.
1052+ scratch.store.add_share_user(&user.id, ShareKind::Folder, &folder.id, &friend.id, true).await.unwrap();
1053+ scratch.store.add_share_user(&user.id, ShareKind::File, &file.id, &friend.id, false).await.unwrap();
1054+ assert!(scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap());
1055+ assert!(scratch.store.can_download(ShareKind::File, &file.id, &friend.id).await.unwrap());
1056+}
1057+
1058+#[tokio::test]
1059+async fn restore_folder_keeps_files_trashed_before_it() {
1060+ let scratch = Scratch::open().await;
1061+ let user = alice(&scratch.store).await;
1062+ let folder = scratch.store.create_folder(&user.id, None, "box").await.unwrap();
1063+ let early = scratch.store.insert_file(&user.id, Some(&folder.id), "early", b"1").await.unwrap();
1064+ let with = scratch.store.insert_file(&user.id, Some(&folder.id), "with", b"2").await.unwrap();
1065+ // Trashed on its own first, then the folder takes the rest with it.
1066+ scratch.store.delete_file(&early.id).await.unwrap();
1067+ scratch.store.delete_folder(&folder.id).await.unwrap();
1068+ scratch.store.restore_folder(&folder.id).await.unwrap();
1069+ // The cascade comes back; the earlier trash stays trash.
1070+ assert!(scratch.store.folder(&folder.id).await.unwrap().unwrap().deleted_at.is_none());
1071+ assert!(scratch.store.file(&with.id).await.unwrap().unwrap().deleted_at.is_none());
1072+ assert!(scratch.store.file(&early.id).await.unwrap().unwrap().deleted_at.is_some());
1073+}
1074+
1075+#[tokio::test]
1076+async fn remove_share_user_works_on_trashed_targets() {
1077+ let scratch = Scratch::open().await;
1078+ let user = alice(&scratch.store).await;
1079+ let friend = bob(&scratch.store).await;
1080+ let file = scratch.store.insert_file(&user.id, None, "shared", b"data").await.unwrap();
1081+ scratch.store.add_share_user(&user.id, ShareKind::File, &file.id, &friend.id, true).await.unwrap();
1082+ // Trash does not stop an unshare: revoke while trashed, then restore
1083+ // to find the grant gone.
1084+ scratch.store.delete_file(&file.id).await.unwrap();
1085+ scratch.store.remove_share_user(ShareKind::File, &file.id, &friend.id).await.unwrap();
1086+ scratch.store.restore_file(&file.id).await.unwrap();
1087+ assert!(!scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap());
1088+ // Purged or missing targets still refuse: there is nothing to unshare.
1089+ scratch.store.delete_file(&file.id).await.unwrap();
1090+ scratch.store.purge_file(&file.id).await.unwrap();
1091+ assert!(matches!(
1092+ scratch.store.remove_share_user(ShareKind::File, &file.id, &friend.id).await,
1093+ Err(StoreError::NotFound)
1094+ ));
1095+ assert!(matches!(
1096+ scratch.store.remove_share_user(ShareKind::File, "missing", &friend.id).await,
1097+ Err(StoreError::NotFound)
1098+ ));
1099+}
1100+
1101+#[tokio::test]
1102+async fn add_share_user_needs_the_owner() {
1103+ let scratch = Scratch::open().await;
1104+ let user = alice(&scratch.store).await;
1105+ let friend = bob(&scratch.store).await;
1106+ let stranger = scratch.store.provision_user("sub-caro", "caro@example.com", "Caro", 1024).await.unwrap();
1107+ let file = scratch.store.insert_file(&user.id, None, "mine", b"data").await.unwrap();
1108+ // A stranger naming someone else's file is refused — and names no grant.
1109+ assert!(matches!(
1110+ scratch.store.add_share_user(&friend.id, ShareKind::File, &file.id, &stranger.id, true).await,
1111+ Err(StoreError::CrossOwner)
1112+ ));
1113+ assert!(!scratch.store.can_see(ShareKind::File, &file.id, &stranger.id).await.unwrap());
1114+ // A missing target is not-found, like the sibling link creator answers.
1115+ assert!(matches!(
1116+ scratch.store.add_share_user(&user.id, ShareKind::File, "missing", &stranger.id, true).await,
1117+ Err(StoreError::NotFound)
1118+ ));
1119+ // The owner shares freely.
1120+ scratch.store.add_share_user(&user.id, ShareKind::File, &file.id, &stranger.id, true).await.unwrap();
1121+ assert!(scratch.store.can_see(ShareKind::File, &file.id, &stranger.id).await.unwrap());
1122+}
crates/in-web/Cargo.tomladded+49 -0
@@ -0,0 +1,49 @@
1+[package]
2+name = "in-web"
3+version.workspace = true
4+edition.workspace = true
5+license.workspace = true
6+repository.workspace = true
7+description = "In web app: topcoat UI, routes and the server"
8+
9+[dependencies]
10+topcoat = { version = "0.6.2", default-features = false, features = [
11+ "router",
12+ "view",
13+ "runtime",
14+ "asset",
15+ "cookie",
16+ "discover",
17+ "serve",
18+ "compression",
19+ "multipart",
20+ "sse",
21+] }
22+in-core = { workspace = true, features = ["server"] }
23+in-client.workspace = true
24+serde.workspace = true
25+serde_json.workspace = true
26+time.workspace = true
27+thiserror.workspace = true
28+tokio.workspace = true
29+async-trait = "0.1.92"
30+# The live stream is built with `futures_util::stream::unfold`; topcoat does
31+# not re-export the futures traits, so this is named directly.
32+futures-util = { version = "0.3", default-features = false }
33+# Hashes the compiled stylesheet against the bundle's bytes at boot, so a
34+# bundle from another generation refuses the boot instead of serving under
35+# this binary (see `server.rs`'s `stylesheet_guard`).
36+sha2 = "0.10"
37+ulid = { workspace = true }
38+
39+[build-dependencies]
40+grass = "0.13"
41+sha2 = "0.10"
42+
43+[dev-dependencies]
44+http = "1.5"
45+# Reads an SSE body frame by frame, so a live-channel test can wait for the
46+# announcement it expects instead of for a clock.
47+http-body-util = "0.1"
48+ulid = { workspace = true }
49+in-client = { workspace = true, features = ["test-seam"] }
crates/in-web/build.rsadded+44 -0
@@ -0,0 +1,44 @@
1+//! Compiles `style/main.scss` to `assets/main.css` under this crate's
2+//! manifest directory, where `asset!("assets/main.css")` in `layout.rs`
3+//! expects to find it. Crate-relative rather than `OUT_DIR`-relative so the
4+//! asset's id does not churn with every profile/build-hash (see the topcoat
5+//! contract sheet, (a)).
6+//!
7+use sha2::Digest;
8+
9+fn main() {
10+ let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
11+ let scss = format!("{manifest_dir}/../../style/main.scss");
12+ println!("cargo:rerun-if-changed={scss}");
13+ // Partials pulled in via @use — without these, editing a skin file would
14+ // leave assets/main.css stale.
15+ println!("cargo:rerun-if-changed={manifest_dir}/../../style/_instrument.scss");
16+ println!("cargo:rerun-if-changed={manifest_dir}/../../style/_ledger.scss");
17+
18+ let css = grass::from_path(&scss, &grass::Options::default())
19+ .unwrap_or_else(|err| panic!("failed to compile {scss}: {err}"));
20+ let out_dir = format!("{manifest_dir}/assets");
21+ std::fs::create_dir_all(&out_dir).expect("failed to create assets/");
22+ std::fs::write(format!("{out_dir}/main.css"), &css).expect("failed to write assets/main.css");
23+
24+ // The binary carries the compiled stylesheet's fingerprint, so the
25+ // running server can tell a bundle of its own generation from one left
26+ // behind by another deploy (`server.rs`'s `stylesheet_guard` refuses the
27+ // boot on a mismatch). The bytes hashed here are exactly the bytes the
28+ // bundler later copies into the bundle, so the fingerprints agree.
29+ let fingerprint = sha2::Sha256::digest(css.as_bytes());
30+ let mut hex = String::with_capacity(fingerprint.len() * 2);
31+ for byte in fingerprint {
32+ hex.push_str(&format!("{byte:02x}"));
33+ }
34+ println!("cargo:rustc-env=IN_STYLE_FINGERPRINT=sha256:{hex}");
35+
36+ // The commit this binary was built from, served by `/healthz` and
37+ // asserted against after the deploy restart, so a stale process
38+ // holding the port cannot pass for this deploy. "dev" locally, where
39+ // nothing asserts it. The rerun-if-env-changed line is load-bearing:
40+ // without it a rust-cache hit would ship last deploy's sha.
41+ let sha = std::env::var("IN_BUILD_SHA").unwrap_or_else(|_| "dev".into());
42+ println!("cargo:rustc-env=IN_BUILD_SHA={sha}");
43+ println!("cargo:rerun-if-env-changed=IN_BUILD_SHA");
44+}
crates/in-web/src/drive.rsadded+547 -0
@@ -0,0 +1,547 @@
1+//! The drive browser.
2+//!
3+//! `GET /drive?folder=<id>` renders one directory — breadcrumbs back to the
4+//! root, subfolders then files — and the four owner-only folder mutations
5+//! ride beside it: `POST /api/folder/create|rename|move|delete`. Trashed
6+//! items never appear here; they wait in `trash.rs`. A folder whose ancestor
7+//! is trashed is unreachable, and a move that would nest a folder inside
8+//! itself is refused. Anything naming another owner's tree answers 404,
9+//! never 403.
10+
11+use in_core::store::{Folder, Store, StoreError, ThumbState};
12+use topcoat::router::request::uri;
13+use topcoat::router::{HeaderName, HeaderValue, StatusCode, header, page, query_params, route};
14+
15+use topcoat::Result;
16+use topcoat::context::Cx;
17+use topcoat::router::content::{Form, Json};
18+use topcoat::router::error::not_found;
19+use topcoat::view::view;
20+
21+use crate::i18n::{Key, lang, t};
22+use crate::layout::{NavPage, topbar};
23+use crate::server::{Refusal, app, back_to, refusal_of, require_user};
24+
25+/// A [`StoreError`] in the drive's own words. Cross-owner reads and writes
26+/// alike answer [`Refusal::NotFound`]: telling a stranger which ids exist is
27+/// the leak the distinction exists to prevent.
28+fn store_refusal(error: StoreError) -> Refusal {
29+ match error {
30+ StoreError::NameTaken => Refusal::NameTaken,
31+ StoreError::QuotaExceeded => Refusal::QuotaExceeded,
32+ StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound,
33+ // A move nesting a folder inside its own descendant.
34+ StoreError::Cycle => Refusal::Forbidden,
35+ _ => Refusal::Unavailable,
36+ }
37+}
38+
39+/// A 303 back to the page the form was posted from, carrying the refusal as
40+/// the body for `carry_refusal_on_redirect` to copy onto the query.
41+type Redirect = Result<(StatusCode, [(HeaderName, String); 1], Json<Option<Refusal>>)>;
42+
43+fn redirect(cx: &Cx, refusal: Option<Refusal>) -> Redirect {
44+ Ok((
45+ StatusCode::SEE_OTHER,
46+ [(header::LOCATION, back_to(cx, "/drive"))],
47+ Json(refusal),
48+ ))
49+}
50+
51+#[query_params]
52+struct DriveQuery {
53+ folder: Option<String>,
54+}
55+
56+/// The folder the query names, if it names one this account may open: owned,
57+/// live, and with no trashed ancestor. Anything else is not found rather
58+/// than forbidden.
59+async fn current_folder(
60+ store: &dyn Store,
61+ user_id: &str,
62+ folder_id: Option<&str>,
63+) -> Result<Option<Folder>, topcoat::Error> {
64+ let Some(id) = folder_id.filter(|id| !id.is_empty()) else {
65+ return Ok(None);
66+ };
67+ let Ok(Some(folder)) = store.folder(id).await else {
68+ return Err(not_found().into());
69+ };
70+ if folder.owner_id != user_id || folder.deleted_at.is_some() {
71+ return Err(not_found().into());
72+ }
73+ // Unreachable while any ancestor is trashed: the drive shows no path
74+ // back into it.
75+ let mut parent = folder.parent_id.clone();
76+ while let Some(id) = parent {
77+ match store.folder(&id).await {
78+ Ok(Some(next)) if next.owner_id == user_id && next.deleted_at.is_none() => {
79+ parent = next.parent_id.clone();
80+ }
81+ _ => return Err(not_found().into()),
82+ }
83+ }
84+ Ok(Some(folder))
85+}
86+
87+/// The breadcrumb path, root first, for the open folder.
88+async fn breadcrumbs(store: &dyn Store, folder: Option<&Folder>) -> Vec<Folder> {
89+ let mut chain = Vec::new();
90+ let mut next = folder.cloned();
91+ while let Some(current) = next {
92+ let parent = match &current.parent_id {
93+ Some(id) => store.folder(id).await.ok().flatten(),
94+ None => None,
95+ };
96+ chain.push(current);
97+ next = parent;
98+ }
99+ chain.reverse();
100+ chain
101+}
102+
103+/// Every live folder the account holds, with its root-first display path —
104+/// the move destination picker. Small trees only; the drive is not a
105+/// filesystem with ten thousand directories.
106+async fn folder_tree(store: &dyn Store, user_id: &str) -> Vec<(String, String)> {
107+ let mut out = Vec::new();
108+ // (parent id, path prefix)
109+ let mut queue: Vec<(Option<String>, String)> = vec![(None, String::new())];
110+ while let Some((parent, prefix)) = queue.pop() {
111+ let Ok(listing) = store.list_children(user_id, parent.as_deref()).await else {
112+ continue;
113+ };
114+ for folder in listing.folders {
115+ let path = if prefix.is_empty() {
116+ folder.name.clone()
117+ } else {
118+ format!("{prefix} / {}", folder.name)
119+ };
120+ queue.push((Some(folder.id.clone()), path.clone()));
121+ out.push((folder.id, path));
122+ }
123+ }
124+ out.sort_by(|a, b| a.1.cmp(&b.1));
125+ out
126+}
127+
128+fn human_size(bytes: u64) -> String {
129+ const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
130+ let mut size = bytes as f64;
131+ let mut unit = 0;
132+ while size >= 1024.0 && unit < 4 {
133+ size /= 1024.0;
134+ unit += 1;
135+ }
136+ if unit == 0 {
137+ format!("{bytes} {}", UNITS[unit])
138+ } else {
139+ format!("{size:.1} {}", UNITS[unit])
140+ }
141+}
142+fn page_refusal(cx: &Cx) -> Option<Refusal> {
143+ ["create", "rename", "move", "delete", "upload"]
144+ .iter()
145+ .find_map(|call| refusal_of(cx, call))
146+}
147+/// The just-minted token off the redirect's `?created=` pair, if present.
148+fn created_token(query: &str) -> Option<String> {
149+ query.split('&').find_map(|pair| {
150+ let (name, value) = pair.split_once('=')?;
151+ (name == "created" && !value.is_empty()).then(|| value.to_string())
152+ })
153+}
154+
155+/// `GET /drive?folder=<id>`: one directory.
156+#[page("/drive")]
157+async fn drive(cx: &Cx) -> Result {
158+ let user = match require_user(cx).await {
159+ Ok(user) => user,
160+ Err(_) => {
161+ let location = (header::LOCATION, HeaderValue::from_static("/"));
162+ return view! {
163+ cx =>
164+ (StatusCode::SEE_OTHER)
165+ (location)
166+ };
167+ }
168+ };
169+ let language = lang(cx);
170+ let store = app(cx).store.clone();
171+
172+ let wanted = query_params::<DriveQuery>(cx)
173+ .ok()
174+ .and_then(|query| query.folder.clone());
175+ let current = current_folder(store.as_ref(), &user.id, wanted.as_deref()).await?;
176+ let crumbs = breadcrumbs(store.as_ref(), current.as_ref()).await;
177+ let listing = match store
178+ .list_children(&user.id, current.as_ref().map(|folder| folder.id.as_str()))
179+ .await
180+ {
181+ Ok(listing) => listing,
182+ Err(_) => return Err(not_found().into()),
183+ };
184+ let destinations = folder_tree(store.as_ref(), &user.id).await;
185+ let refusal = page_refusal(cx);
186+ // A link minted from this surface redirects back here with the plaintext
187+ // token on `?created=` — rendered once, like the settings page does.
188+ let created = created_token(uri(cx).query().unwrap_or(""));
189+ let origin = app(cx).config.listen_url();
190+
191+ let current_id = current
192+ .as_ref()
193+ .map(|folder| folder.id.clone())
194+ .unwrap_or_default();
195+ let current_name = current
196+ .as_ref()
197+ .map(|folder| folder.name.clone())
198+ .unwrap_or_else(|| t(language, Key::Drive).to_string());
199+
200+ view! {
201+ cx =>
202+ (topbar(cx, NavPage::Drive, &user, language).await?)
203+ <main class="settings-stage">
204+ <div class="filterbar">
205+ <nav class="detail-crumbs" aria-label=(current_name.clone())>
206+ <a class="detail-crumb" href="/drive">(t(language, Key::Drive))</a>
207+ for crumb in crumbs.iter() {
208+ <span class="detail-crumb-sep">"/"</span>
209+ <a class="detail-crumb" href=(format!("/drive?folder={}", crumb.id))>(crumb.name.clone())</a>
210+ }
211+ </nav>
212+ <div class="spacer"></div>
213+ <form class="tag-form" method="post" action="/api/folder/create">
214+ <input type="hidden" name="parent_id" value=(current_id.clone())>
215+ <input class="field-input" type="text" name="name" maxlength="255"
216+ placeholder=(t(language, Key::FolderName)) required="" aria-label=(t(language, Key::FolderName))>
217+ <button class="primary" type="submit">(t(language, Key::CreateFolder))</button>
218+ </form>
219+ </div>
220+ if let Some(refusal) = refusal {
221+ <p class="field-error">(refusal.message_in(language))</p>
222+ }
223+ if let Some(token) = created {
224+ <section class="panel">
225+ <h2 class="panel-title">(t(language, Key::LinkCreated))</h2>
226+ <div class="panel-body">
227+ <p class="field-note">(t(language, Key::CopyLinkOnce))</p>
228+ <p class="member-link-value">(format!("{origin}/s/{token}"))</p>
229+ </div>
230+ </section>
231+ }
232+ <section class="panel">
233+ <div class="panel-head">
234+ <h2 class="panel-title">(t(language, Key::FoldersHeading))</h2>
235+ <span class="chip">(format!("{}", listing.folders.len()))</span>
236+ </div>
237+ <div class="panel-body">
238+ if listing.folders.is_empty() {
239+ <p class="detail-quiet">(t(language, Key::EmptyFolder))</p>
240+ }
241+ for folder in listing.folders.iter() {
242+ <div class="dep-row">
243+ <a class="dep-link" href=(format!("/drive?folder={}", folder.id))>(folder.name.clone())</a>
244+ <div class="spacer"></div>
245+ <form class="pop-row-form" method="post" action="/api/folder/rename">
246+ <input type="hidden" name="id" value=(folder.id.clone())>
247+ <input class="field-input" type="text" name="name" maxlength="255"
248+ value=(folder.name.clone()) required="" aria-label=(t(language, Key::RenameFolder))>
249+ <button class="quiet" type="submit">(t(language, Key::Rename))</button>
250+ </form>
251+ <form class="pop-row-form" method="post" action="/api/folder/move">
252+ <input type="hidden" name="id" value=(folder.id.clone())>
253+ <select class="field-input" name="parent_id" aria-label=(t(language, Key::MoveFolder))>
254+ <option value="">(t(language, Key::Drive))</option>
255+ for dest in destinations.iter() {
256+ if dest.0 != folder.id {
257+ <option value=(dest.0.clone())>(dest.1.clone())</option>
258+ }
259+ }
260+ </select>
261+ <button class="quiet" type="submit">(t(language, Key::Move))</button>
262+ </form>
263+ <form class="detail-delete-form" method="post" action="/api/folder/delete">
264+ <input type="hidden" name="id" value=(folder.id.clone())>
265+ <button class="quiet" type="submit">(t(language, Key::Delete))</button>
266+ </form>
267+ </div>
268+ }
269+ </div>
270+ </section>
271+ <section class="panel">
272+ <div class="panel-head">
273+ <h2 class="panel-title">(t(language, Key::FilesHeading))</h2>
274+ <span class="chip">(format!("{}", listing.files.len()))</span>
275+ </div>
276+ <div class="panel-body">
277+ <form id="upload-form" class="file-upload" method="post" action="/files"
278+ enctype="multipart/form-data" data-hard="" data-failed-label=(t(language, Key::UploadFailed))>
279+ <input type="hidden" name="folder_id" value=(current_id.clone())>
280+ <label class="file-upload-box">
281+ <span class="file-upload-name">(t(language, Key::ChooseFiles))</span>
282+ <input class="file-upload-input" type="file" name="file" multiple="">
283+ </label>
284+ <span class="field-note">(t(language, Key::DropFilesHere))</span>
285+ </form>
286+ <div class="file-list">
287+ for file in listing.files.iter() {
288+ <div class="dep-row">
289+ if file.thumb_state == ThumbState::Ready {
290+ <img class="file-chip" src=(format!("/thumb/{}", file.id)) alt="">
291+ } else {
292+ <span class="file-chip" aria-hidden="true">"▦"</span>
293+ }
294+ <a class="dep-link" href=(format!("/file/{}", file.id))>(file.name.clone())</a>
295+ <span class="file-chip-size">(human_size(file.size_bytes))</span>
296+ <div class="spacer"></div>
297+ <form class="pop-row-form" method="post" action="/api/file/rename">
298+ <input type="hidden" name="id" value=(file.id.clone())>
299+ <input class="field-input" type="text" name="name" maxlength="255"
300+ value=(file.name.clone()) required="" aria-label=(t(language, Key::RenameFile))>
301+ <button class="quiet" type="submit">(t(language, Key::Rename))</button>
302+ </form>
303+ <form class="pop-row-form" method="post" action="/api/file/move">
304+ <input type="hidden" name="id" value=(file.id.clone())>
305+ <select class="field-input" name="folder_id" aria-label=(t(language, Key::MoveFile))>
306+ <option value="">(t(language, Key::Drive))</option>
307+ for dest in destinations.iter() {
308+ <option value=(dest.0.clone())>(dest.1.clone())</option>
309+ }
310+ </select>
311+ <button class="quiet" type="submit">(t(language, Key::Move))</button>
312+ </form>
313+ <form class="detail-delete-form" method="post" action="/api/file/delete">
314+ <input type="hidden" name="id" value=(file.id.clone())>
315+ <button class="quiet" type="submit">(t(language, Key::Delete))</button>
316+ </form>
317+ </div>
318+ }
319+ </div>
320+ </div>
321+ </section>
322+ </main>
323+ (crate::dropdown::dropdown_script(cx).await?)
324+ (upload_script(cx).await?)
325+ }
326+}
327+
328+/// The upload control's client half: files under 8 MiB ride the form's own
329+/// multipart post; files at or over it are split into the chunked protocol's
330+/// calls with a progress bar.
331+///
332+/// The form wears `data-hard` so the soft-nav's multipart replay leaves it
333+/// alone — two uploaders racing the same bytes would double-insert, and the
334+/// progress the soft-nav draws knows nothing of chunks. Without script the
335+/// form posts plainly and the 303 lands back on the folder.
336+async fn upload_script(cx: &Cx) -> Result {
337+ use topcoat::view::Unescaped;
338+ const JS: &str = "\
339+ (function () { \
340+ if (window.__inUpload) { return; } \
341+ window.__inUpload = true; \
342+ var LIMIT = 8388608; \
343+ function bar(box, label) { \
344+ var wrap = document.createElement('div'); \
345+ wrap.className = 'upload-progress'; \
346+ var fill = document.createElement('div'); \
347+ fill.className = 'upload-progress-fill'; \
348+ wrap.appendChild(fill); \
349+ box.appendChild(window.__inAdded(wrap)); \
350+ if (label) { wrap.setAttribute('aria-label', label); } \
351+ return fill; \
352+ } \
353+ function fail(box, message) { \
354+ var note = document.createElement('p'); \
355+ note.className = 'field-error'; \
356+ note.textContent = message; \
357+ box.appendChild(window.__inAdded(note)); \
358+ } \
359+ async function startChunked(folder, name, size) { \
360+ var r = await fetch('/api/upload/start', { \
361+ method: 'POST', \
362+ headers: { 'content-type': 'application/json', accept: 'application/json' }, \
363+ body: JSON.stringify({ folder_id: folder || null, name: name, size_bytes: size }) \
364+ }); \
365+ var answer = await r.json(); \
366+ if (!answer.ok) { throw new Error(answer.err || 'start'); } \
367+ return answer.ok; \
368+ } \
369+ async function sendBig(file, folder, fill) { \
370+ var session = await startChunked(folder, file.name, file.size); \
371+ var index = 0; \
372+ for (var off = 0; off < file.size; off += LIMIT, index++) { \
373+ var piece = file.slice(off, Math.min(file.size, off + LIMIT)); \
374+ var r = await fetch('/api/upload/' + session.id + '/' + index, { \
375+ method: 'PUT', \
376+ headers: { 'content-type': 'application/octet-stream' }, \
377+ body: piece \
378+ }); \
379+ if (!r.ok) { throw new Error('chunk'); } \
380+ fill.style.width = Math.round(((off + piece.size) / file.size) * 100) + '%'; \
381+ } \
382+ var done = await fetch('/api/upload/' + session.id + '/finish', { method: 'POST' }); \
383+ var fin = await done.json(); \
384+ if (!fin.ok) { throw new Error((fin.err) || 'finish'); } \
385+ } \
386+ document.addEventListener('submit', function (e) { \
387+ var form = e.target; \
388+ if (!form || form.id !== 'upload-form') { return; } \
389+ e.preventDefault(); \
390+ var input = form.querySelector('.file-upload-input'); \
391+ var box = form.querySelector('.file-upload-box'); \
392+ var folder = form.querySelector('input[name=folder_id]').value; \
393+ var files = input && input.files ? Array.prototype.slice.call(input.files) : []; \
394+ if (!files.length) { return; } \
395+ if (form.__inBusy) { return; } \
396+ form.__inBusy = true; \
397+ if (input) { input.disabled = true; window.__inOwn(input, [], ['disabled']); } \
398+ var small = files.filter(function (f) { return f.size < LIMIT; }); \
399+ var big = files.filter(function (f) { return f.size >= LIMIT; }); \
400+ var failLabel = form.getAttribute('data-failed-label') || 'upload failed'; \
401+ var landing = window.location.href; \
402+ (async function () { \
403+ try { \
404+ if (small.length) { \
405+ var data = new FormData(); \
406+ data.append('folder_id', folder); \
407+ small.forEach(function (f) { data.append('file', f, f.name); }); \
408+ var fill = bar(box); \
409+ var r = await fetch(form.getAttribute('action'), { \
410+ method: 'POST', headers: { accept: 'text/html' }, body: data \
411+ }); \
412+ fill.style.width = '100%'; \
413+ landing = r.url || landing; \
414+ if (!r.ok) { fail(box, failLabel); } \
415+ } \
416+ for (var i = 0; i < big.length; i++) { \
417+ var fill2 = bar(box, big[i].name); \
418+ await sendBig(big[i], folder, fill2); \
419+ } \
420+ } catch (err) { fail(box, failLabel); } \
421+ input.value = ''; \
422+ form.__inBusy = false; \
423+ if (input) { input.disabled = false; } \
424+ if (window.__inGo) { window.__inGo(landing); } \
425+ else { window.location.href = landing; } \
426+ })(); \
427+ }); \
428+ })();";
429+ view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
430+}
431+
432+#[derive(serde::Deserialize)]
433+struct CreateFolderForm {
434+ #[serde(default)]
435+ parent_id: String,
436+ name: String,
437+}
438+
439+/// `POST /api/folder/create`: one folder under the open one, or the root.
440+#[route(POST "/api/folder/create")]
441+async fn create_folder(cx: &Cx, Form(input): Form<CreateFolderForm>) -> Redirect {
442+ let user = match require_user(cx).await {
443+ Ok(user) => user,
444+ Err(refusal) => return redirect(cx, Some(refusal)),
445+ };
446+ let store = app(cx).store.clone();
447+ let parent = if input.parent_id.is_empty() {
448+ None
449+ } else {
450+ Some(input.parent_id.as_str())
451+ };
452+ if let Some(id) = parent {
453+ match store.folder(id).await {
454+ Ok(Some(folder)) if folder.owner_id == user.id && folder.deleted_at.is_none() => {}
455+ _ => return redirect(cx, Some(Refusal::NotFound)),
456+ }
457+ }
458+ match store.create_folder(&user.id, parent, &input.name).await {
459+ Ok(_) => redirect(cx, None),
460+ Err(error) => redirect(cx, Some(store_refusal(error))),
461+ }
462+}
463+
464+#[derive(serde::Deserialize)]
465+struct FolderIdForm {
466+ id: String,
467+}
468+
469+#[derive(serde::Deserialize)]
470+struct RenameFolderForm {
471+ id: String,
472+ name: String,
473+}
474+
475+#[derive(serde::Deserialize)]
476+struct MoveFolderForm {
477+ id: String,
478+ #[serde(default)]
479+ parent_id: String,
480+}
481+
482+/// `POST /api/folder/rename`: a new label on an owned folder.
483+#[route(POST "/api/folder/rename")]
484+async fn rename_folder(cx: &Cx, Form(input): Form<RenameFolderForm>) -> Redirect {
485+ let user = match require_user(cx).await {
486+ Ok(user) => user,
487+ Err(refusal) => return redirect(cx, Some(refusal)),
488+ };
489+ let store = app(cx).store.clone();
490+ match store.folder(&input.id).await {
491+ Ok(Some(folder)) if folder.owner_id == user.id && folder.deleted_at.is_none() => {}
492+ _ => return redirect(cx, Some(Refusal::NotFound)),
493+ }
494+ match store.rename_folder(&input.id, &input.name).await {
495+ Ok(_) => redirect(cx, None),
496+ Err(error) => redirect(cx, Some(store_refusal(error))),
497+ }
498+}
499+
500+/// `POST /api/folder/move`: an owned folder under another owned folder, or
501+/// the root. Into its own descendant is refused, not looped.
502+#[route(POST "/api/folder/move")]
503+async fn move_folder(cx: &Cx, Form(input): Form<MoveFolderForm>) -> Redirect {
504+ let user = match require_user(cx).await {
505+ Ok(user) => user,
506+ Err(refusal) => return redirect(cx, Some(refusal)),
507+ };
508+ let store = app(cx).store.clone();
509+ match store.folder(&input.id).await {
510+ Ok(Some(folder)) if folder.owner_id == user.id && folder.deleted_at.is_none() => {}
511+ _ => return redirect(cx, Some(Refusal::NotFound)),
512+ }
513+ let parent = if input.parent_id.is_empty() {
514+ None
515+ } else {
516+ Some(input.parent_id.as_str())
517+ };
518+ if let Some(id) = parent {
519+ match store.folder(id).await {
520+ Ok(Some(folder)) if folder.owner_id == user.id && folder.deleted_at.is_none() => {}
521+ _ => return redirect(cx, Some(Refusal::NotFound)),
522+ }
523+ }
524+ match store.move_folder(&input.id, parent).await {
525+ Ok(_) => redirect(cx, None),
526+ Err(error) => redirect(cx, Some(store_refusal(error))),
527+ }
528+}
529+
530+/// `POST /api/folder/delete`: trash an owned folder — the whole subtree wears
531+/// the same timestamp, and the bytes wait in the trash for the purge.
532+#[route(POST "/api/folder/delete")]
533+async fn delete_folder(cx: &Cx, Form(input): Form<FolderIdForm>) -> Redirect {
534+ let user = match require_user(cx).await {
535+ Ok(user) => user,
536+ Err(refusal) => return redirect(cx, Some(refusal)),
537+ };
538+ let store = app(cx).store.clone();
539+ match store.folder(&input.id).await {
540+ Ok(Some(folder)) if folder.owner_id == user.id && folder.deleted_at.is_none() => {}
541+ _ => return redirect(cx, Some(Refusal::NotFound)),
542+ }
543+ match store.delete_folder(&input.id).await {
544+ Ok(_) => redirect(cx, None),
545+ Err(error) => redirect(cx, Some(store_refusal(error))),
546+ }
547+}
crates/in-web/src/dropdown.rsadded+294 -0
@@ -0,0 +1,294 @@
1+//! The house replacement for the native `<select>` popup.
2+//!
3+//! Every browser engine draws its own `<select>` list, and only Chromium's
4+//! `::picker(select)` lets that popup be themed — Firefox/WebKit never see
5+//! it, so styling the native popup is not a real cross-browser option.
6+//! Instead [`dropdown_script`] progressively enhances any `select.status-select`
7+//! or `select.field-input` already on the page: the native element stays in
8+//! the DOM (hidden, so its `name`/value still post the same form field
9+//! unchanged) while a `<button>` cloning its own classes becomes the
10+//! visible trigger — same closed look as the select it replaces — and a
11+//! `position: fixed` panel of option rows, portaled onto `<body>`, stands
12+//! in for the OS popup.
13+//!
14+//! ## The whole box is the hit area
15+//!
16+//! The trigger is one child among several inside a control box — a status
17+//! dot before it, a chevron after it, the box's own padding around all of
18+//! them — so a button-only listener leaves dead zones exactly where the
19+//! control looks clickable. That bug has been fixed one control at a time
20+//! before; this is the version that cannot come back. A delegated listener
21+//! walks up from whatever was clicked and, on finding the element that
22+//! *directly* contains a single `.dd-trigger`, opens that trigger's panel.
23+//!
24+//! "Directly contains" is the whole of the rule: it pins the hit area to
25+//! the visual box and no further, so a click on a field's outer row or on
26+//! the modal around it does not reach in and open something. Nothing has to
27+//! be marked up for this to work — a new control gets it by existing, which
28+//! is what makes it structural rather than another remembered convention.
29+//!
30+//! Anything else genuinely interactive keeps its own click — a link, a
31+//! button, a text field. `<label>` is deliberately *not* on that list: the
32+//! new-task modal wraps its status box in one, and bailing on labels put
33+//! every dead zone straight back.
34+//!
35+//! The delegated click also calls `preventDefault`. A `<label>` forwards a
36+//! click to the control it labels, so without it the browser delivered a
37+//! *second* click straight to the trigger, which toggled the panel shut
38+//! again in the same gesture — opening and closing looked exactly like the
39+//! dead zone the delegation was added to remove.
40+
41+use topcoat::Result;
42+use topcoat::context::Cx;
43+use topcoat::view::{Unescaped, view};
44+
45+/// Emitted once per page that renders a `<select>`; the enhancement is
46+/// per-element and idempotent (`data-dd-done`), re-run on `in:wire` so
47+/// selects arriving in a soft page swap get theirs too. A select that is
48+/// already done is not skipped but repaired: the live refresh morphs the
49+/// server's HTML over the live DOM, and what it writes is the select — its
50+/// selected option, its option list, its class — while the trigger and panel
51+/// standing in for it are the client's and are left untouched. So `resync`
52+/// re-asserts `dd-native`, re-reads the label off the select, and rebuilds
53+/// the rows when the options themselves changed. Without it the two halves
54+/// drift: the select unhides itself under its own trigger, or the trigger
55+/// keeps announcing a status somebody else has already changed. An open
56+/// panel is left alone — repairing under a pointer is worse than stale. Owns its own
57+/// `Escape` resolver on `window.__inEsc` (priority 95 — the dropdown
58+/// outranks the modal chain: Escape on an open panel closes just the
59+/// panel, never the modal above it. The old per-script listeners made
60+/// this order path-dependent — a modal swapped in by soft navigation
61+/// registered its listener last and lost to the dropdown; a full load
62+/// with `?task=` registered it first and the modal chain won, closing
63+/// the whole modal over an open dropdown — the registry pins the correct
64+/// order; the whole table lives in `layout.rs`'s `escape_manager_script`).
65+pub async fn dropdown_script(cx: &Cx) -> Result {
66+ const JS: &str = "\
67+ (function () {\
68+ if (window.__inDd) { return; }\
69+ window.__inDd = true;\
70+ function opts(select) { return Array.prototype.slice.call(select.options); }\
71+ function closeAll() {\
72+ document.querySelectorAll('.dd-panel.dd-open').forEach(function (panel) {\
73+ panel.classList.remove('dd-open');\
74+ if (panel.__ddTrigger) { panel.__ddTrigger.setAttribute('aria-expanded', 'false'); }\
75+ });\
76+ }\
77+ function place(panel, trigger) {\
78+ var r = trigger.getBoundingClientRect();\
79+ var h = panel.offsetHeight;\
80+ var w = panel.offsetWidth;\
81+ var top = r.bottom + 4;\
82+ if (top + h > window.innerHeight && r.top - h - 4 >= 0) { top = r.top - h - 4; }\
83+ top = Math.max(4, Math.min(top, window.innerHeight - h - 4));\
84+ var left = Math.max(4, Math.min(r.left, window.innerWidth - w - 4));\
85+ panel.style.left = left + 'px';\
86+ panel.style.top = top + 'px';\
87+ panel.style.minWidth = r.width + 'px';\
88+ }\
89+ function visibleRows(panel) { return Array.prototype.slice.call(panel.querySelectorAll('.dd-option:not(.dd-option-hidden)')); }\
90+ function activate(panel, row) {\
91+ panel.querySelectorAll('.dd-option-active').forEach(function (r) { r.classList.remove('dd-option-active'); });\
92+ if (!row) { return; }\
93+ row.classList.add('dd-option-active');\
94+ if (panel.__ddSearch) { row.scrollIntoView({ block: 'nearest' }); } else { row.focus(); }\
95+ }\
96+ function isTypeKey(e) { return e.key && e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey; }\
97+ function typeIntoSearch(search, e) {\
98+ search.focus();\
99+ search.value += e.key;\
100+ search.dispatchEvent(new Event('input', { bubbles: true }));\
101+ }\
102+ function filterRows(panel, query) {\
103+ var qTr = query.toLocaleLowerCase('tr');\
104+ var qEn = query.toLowerCase();\
105+ panel.querySelectorAll('.dd-option').forEach(function (r) {\
106+ var t = r.textContent;\
107+ var miss = t.toLocaleLowerCase('tr').indexOf(qTr) === -1 && t.toLowerCase().indexOf(qEn) === -1;\
108+ r.classList.toggle('dd-option-hidden', qEn !== '' && miss);\
109+ });\
110+ var vis = visibleRows(panel);\
111+ activate(panel, panel.querySelector('.dd-option-selected:not(.dd-option-hidden)') || vis[0]);\
112+ }\
113+ function pick(select, trigger, panel, row) {\
114+ select.value = row.dataset.value;\
115+ panel.querySelectorAll('.dd-option').forEach(function (r) {\
116+ r.classList.toggle('dd-option-selected', r === row);\
117+ r.setAttribute('aria-selected', r === row ? 'true' : 'false');\
118+ });\
119+ trigger.textContent = row.textContent;\
120+ panel.classList.remove('dd-open');\
121+ trigger.setAttribute('aria-expanded', 'false');\
122+ trigger.focus();\
123+ select.dispatchEvent(new Event('change', { bubbles: true }));\
124+ }\
125+ function openPanel(select, trigger, panel) {\
126+ closeAll();\
127+ var search = panel.__ddSearch;\
128+ if (search) {\
129+ search.value = '';\
130+ panel.querySelectorAll('.dd-option').forEach(function (r) { r.classList.remove('dd-option-hidden'); });\
131+ }\
132+ panel.classList.add('dd-open');\
133+ place(panel, trigger);\
134+ trigger.setAttribute('aria-expanded', 'true');\
135+ activate(panel, panel.querySelector('.dd-option-selected') || panel.querySelector('.dd-option'));\
136+ if (search) { search.focus(); }\
137+ }\
138+ function fillRows(panel, select) {\
139+ panel.querySelectorAll('.dd-option').forEach(function (r) { r.remove(); });\
140+ opts(select).forEach(function (opt) {\
141+ var row = document.createElement('button');\
142+ row.type = 'button';\
143+ row.className = 'dd-option' + (opt.selected ? ' dd-option-selected' : '');\
144+ row.textContent = opt.textContent;\
145+ row.dataset.value = opt.value;\
146+ row.setAttribute('role', 'option');\
147+ row.setAttribute('aria-selected', opt.selected ? 'true' : 'false');\
148+ panel.appendChild(row);\
149+ });\
150+ }\
151+ function rowsMatch(panel, select) {\
152+ var rows = panel.querySelectorAll('.dd-option');\
153+ var all = opts(select);\
154+ if (rows.length !== all.length) { return false; }\
155+ for (var i = 0; i < all.length; i++) {\
156+ if (rows[i].dataset.value !== all[i].value) { return false; }\
157+ if (rows[i].textContent !== all[i].textContent) { return false; }\
158+ }\
159+ return true;\
160+ }\
161+ function resync(select) {\
162+ var trigger = select.__ddTrigger, panel = select.__ddPanel;\
163+ if (!trigger || !panel) { return; }\
164+ window.__inOwn(select, ['dd-native'], []);\
165+ if (panel.classList.contains('dd-open')) { return; }\
166+ if (!rowsMatch(panel, select)) { fillRows(panel, select); }\
167+ var current = select.options[select.selectedIndex];\
168+ var label = current ? current.textContent : '';\
169+ if (trigger.textContent !== label) { trigger.textContent = label; }\
170+ panel.querySelectorAll('.dd-option').forEach(function (r) {\
171+ var on = !!current && r.dataset.value === current.value;\
172+ r.classList.toggle('dd-option-selected', on);\
173+ r.setAttribute('aria-selected', on ? 'true' : 'false');\
174+ });\
175+ }\
176+ function enhance(select) {\
177+ if (select.dataset.ddDone) { resync(select); return; }\
178+ window.__inOwn(select, [], ['data-dd-done']);\
179+ select.dataset.ddDone = '1';\
180+ var trigger = document.createElement('button');\
181+ trigger.type = 'button';\
182+ trigger.className = select.className + ' dd-trigger';\
183+ var current = select.options[select.selectedIndex];\
184+ trigger.textContent = current ? current.textContent : '';\
185+ trigger.setAttribute('aria-haspopup', 'listbox');\
186+ trigger.setAttribute('aria-expanded', 'false');\
187+ window.__inAdded(trigger);\
188+ select.parentNode.insertBefore(trigger, select);\
189+ window.__inOwn(select, ['dd-native'], []);\
190+ var panel = document.createElement('div');\
191+ panel.className = 'dd-panel';\
192+ panel.setAttribute('role', 'listbox');\
193+ panel.__ddTrigger = trigger;\
194+ trigger.__ddPanel = panel;\
195+ trigger.__ddSelect = select;\
196+ select.__ddTrigger = trigger;\
197+ select.__ddPanel = panel;\
198+ var allOpts = opts(select);\
199+ var search = null;\
200+ if (allOpts.length > 7 || select.hasAttribute('data-search')) {\
201+ search = document.createElement('input');\
202+ search.type = 'text';\
203+ search.className = 'dd-search';\
204+ panel.appendChild(search);\
205+ panel.__ddSearch = search;\
206+ }\
207+ fillRows(panel, select);\
208+ window.__inAdded(panel);\
209+ document.body.appendChild(panel);\
210+ trigger.addEventListener('click', function (e) {\
211+ e.stopPropagation();\
212+ if (panel.classList.contains('dd-open')) { closeAll(); } else { openPanel(select, trigger, panel); }\
213+ });\
214+ trigger.addEventListener('keydown', function (e) {\
215+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\
216+ e.preventDefault();\
217+ if (!panel.classList.contains('dd-open')) { openPanel(select, trigger, panel); return; }\
218+ var vis = visibleRows(panel);\
219+ var idx = vis.indexOf(panel.querySelector('.dd-option-active')) + (e.key === 'ArrowDown' ? 1 : -1);\
220+ if (idx >= 0 && idx < vis.length) { activate(panel, vis[idx]); }\
221+ } else if (e.key === 'Enter' && panel.classList.contains('dd-open')) {\
222+ e.preventDefault();\
223+ var active = panel.querySelector('.dd-option-active');\
224+ if (active) { pick(select, trigger, panel, active); }\
225+ } else if (search && isTypeKey(e)) {\
226+ e.preventDefault();\
227+ if (!panel.classList.contains('dd-open')) { openPanel(select, trigger, panel); }\
228+ typeIntoSearch(search, e);\
229+ }\
230+ });\
231+ if (search) {\
232+ search.addEventListener('input', function () { filterRows(panel, search.value); });\
233+ }\
234+ panel.addEventListener('keydown', function (e) {\
235+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\
236+ e.preventDefault();\
237+ var vis = visibleRows(panel);\
238+ var idx = vis.indexOf(panel.querySelector('.dd-option-active')) + (e.key === 'ArrowDown' ? 1 : -1);\
239+ if (idx >= 0 && idx < vis.length) { activate(panel, vis[idx]); }\
240+ } else if (e.key === 'Enter') {\
241+ e.preventDefault();\
242+ var vis = visibleRows(panel);\
243+ var active = panel.querySelector('.dd-option-active') || (vis.length === 1 ? vis[0] : null);\
244+ if (active) { pick(select, trigger, panel, active); }\
245+ } else if (search && e.target !== search && isTypeKey(e)) {\
246+ e.preventDefault();\
247+ typeIntoSearch(search, e);\
248+ }\
249+ });\
250+ panel.addEventListener('click', function (e) {\
251+ e.stopPropagation();\
252+ var row = e.target.closest('.dd-option');\
253+ if (row) { pick(select, trigger, panel, row); }\
254+ });\
255+ }\
256+ window.__inEsc.register(95, function () {\
257+ var panel = document.querySelector('.dd-panel.dd-open');\
258+ if (!panel) { return false; }\
259+ var trigger = panel.__ddTrigger;\
260+ closeAll();\
261+ if (trigger) { trigger.focus(); }\
262+ return true;\
263+ });\
264+ document.addEventListener('click', function (e) {\
265+ var el = e.target;\
266+ if (!el || !el.closest) { return; }\
267+ if (el.closest('.dd-panel') || el.closest('.dd-trigger')) { return; }\
268+ if (el.closest('a, button, input:not([type=hidden]), textarea')) { return; }\
269+ var box = el.nodeType === 1 ? el : el.parentNode;\
270+ for (var depth = 0; depth < 3 && box && box.querySelectorAll; depth++) {\
271+ var found = box.querySelectorAll('.dd-trigger');\
272+ if (found.length === 1 && found[0].parentNode === box && found[0].__ddPanel) {\
273+ var t = found[0];\
274+ e.stopPropagation();\
275+ e.preventDefault();\
276+ if (t.__ddPanel.classList.contains('dd-open')) { closeAll(); }\
277+ else { openPanel(t.__ddSelect, t, t.__ddPanel); }\
278+ return;\
279+ }\
280+ box = box.parentNode;\
281+ }\
282+ }, true);\
283+ document.addEventListener('click', closeAll);\
284+ window.addEventListener('scroll', function (e) {\
285+ var t = e.target;\
286+ if (t && t.nodeType === 1 && t.classList.contains('dd-panel')) { return; }\
287+ closeAll();\
288+ }, true);\
289+ function enhanceAll() { document.querySelectorAll('select.status-select, select.field-input').forEach(enhance); }\
290+ enhanceAll();\
291+ document.addEventListener('in:wire', enhanceAll);\
292+ })();";
293+ view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
294+}
crates/in-web/src/files.rsadded+515 -0
@@ -0,0 +1,515 @@
1+//! File bytes and small uploads.
2+//!
3+//! `GET /file/{id}` streams one file its owner may see — or a grantee may,
4+//! when the grant says so — honoring `?dl=1` (download disposition) and
5+//! `Range` (206 partial content), stamped `Cache-Control: private,
6+//! immutable`. `GET /thumb/{id}` serves the webp thumbnail under the same
7+//! visibility. `POST /files` (multipart, 64 MiB cap) takes files under 8
8+//! MiB through the same pipeline the chunked protocol uses — the store
9+//! sanitises the name, sniffs the mime, checks the quota and attempts the
10+//! thumbnail — and `POST /api/file/rename|move|delete` mutate the row.
11+//! Bytes for another owner's file answer 404, not 403.
12+
13+use in_core::store::{ShareKind, Store, StoreError};
14+use topcoat::Result;
15+use topcoat::context::Cx;
16+use topcoat::router::content::multipart::Multipart;
17+use topcoat::router::content::{Form, Json};
18+use topcoat::router::request::headers as request_headers;
19+use topcoat::router::{
20+ HeaderMap, HeaderName, HeaderValue, StatusCode, header, path_param, query_params, route,
21+};
22+
23+use crate::server::{Refusal, app, back_to, require_user};
24+
25+path_param!(id);
26+
27+/// A [`StoreError`] in the files' own words. Cross-owner answers
28+/// [`Refusal::NotFound`], same as a missing id.
29+fn store_refusal(error: StoreError) -> Refusal {
30+ match error {
31+ StoreError::NameTaken => Refusal::NameTaken,
32+ StoreError::QuotaExceeded => Refusal::QuotaExceeded,
33+ StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound,
34+ StoreError::UploadExpired => Refusal::UploadExpired,
35+ StoreError::BadChunk => Refusal::BadChunk,
36+ _ => Refusal::Unavailable,
37+ }
38+}
39+
40+/// A 303 with no body.
41+fn redirect_to(location: &str) -> (StatusCode, HeaderMap, Vec<u8>) {
42+ let mut headers = HeaderMap::new();
43+ if let Ok(value) = HeaderValue::from_str(location) {
44+ headers.insert(header::LOCATION, value);
45+ }
46+ (StatusCode::SEE_OTHER, headers, Vec::new())
47+}
48+
49+/// Back to the folder the upload was posted from, carrying the refusal on
50+/// the query the way a browser without script reads it.
51+fn back_to_folder(
52+ folder_id: Option<&str>,
53+ refusal: Option<Refusal>,
54+) -> (StatusCode, HeaderMap, Vec<u8>) {
55+ let mut location = match folder_id.filter(|id| !id.is_empty()) {
56+ Some(id) => format!("/drive?folder={id}"),
57+ None => "/drive".to_string(),
58+ };
59+ if let Some(refusal) = refusal {
60+ let sep = if location.contains('?') { '&' } else { '?' };
61+ location.push_str(&format!("{sep}refusal={}&on=upload", refusal.code()));
62+ }
63+ redirect_to(&location)
64+}
65+
66+fn not_found() -> (StatusCode, HeaderMap, Vec<u8>) {
67+ (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new())
68+}
69+
70+/// Whether the browser renders this stored mime on its own rather than only
71+/// offering to save it. Trusts the stored mime alone; nothing here sniffs
72+/// bytes a second time. `image/heic` is excluded: no engine decodes it, so
73+/// it stays a download link rather than a broken image.
74+fn renders_inline(mime: &str) -> bool {
75+ if mime == "image/heic" {
76+ return false;
77+ }
78+ mime.starts_with("image/")
79+ || mime.starts_with("video/")
80+ || mime.starts_with("audio/")
81+ || mime == "application/pdf"
82+ || mime == "text/plain"
83+}
84+
85+/// Whether `inline` disposition is safe for this mime: an uploaded HTML or
86+/// SVG file stays `attachment` either way, so it is offered to save rather
87+/// than run on In's origin.
88+fn inline_ok(mime: &str) -> bool {
89+ renders_inline(mime) && mime != "image/svg+xml" && mime != "text/html"
90+}
91+
92+/// The `Content-Disposition` for one download. The ASCII fallback keeps only
93+/// characters no quoting scheme could turn into a delimiter or a control
94+/// character; `filename*` carries the real name, percent-encoded.
95+fn disposition_of(file_name: &str, inline: bool) -> String {
96+ let kind = if inline { "inline" } else { "attachment" };
97+ let ascii: String = file_name
98+ .chars()
99+ .map(|c| {
100+ if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
101+ c
102+ } else {
103+ '_'
104+ }
105+ })
106+ .collect();
107+ let mut encoded = String::new();
108+ for &byte in file_name.as_bytes() {
109+ let c = byte as char;
110+ if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '~' | '-') {
111+ encoded.push(c);
112+ } else {
113+ encoded.push_str(&format!("%{byte:02X}"));
114+ }
115+ }
116+ format!("{kind}; filename=\"{ascii}\"; filename*=UTF-8''{encoded}")
117+}
118+
119+/// A single-range `Range: bytes=...` request resolved against `total` bytes,
120+/// as `(start, end)` inclusive. `None` for anything this does not parse as
121+/// exactly one `bytes=` range (a multi-range header included) — the caller
122+/// falls back to a full `200`, which is always a valid answer to a `Range`
123+/// request. `Err(())` for an unsatisfiable range, so the caller can answer
124+/// `416` instead of serving nonsense bytes.
125+fn parse_range(header: &str, total: u64) -> Option<std::result::Result<(u64, u64), ()>> {
126+ let spec = header.strip_prefix("bytes=")?;
127+ if spec.contains(',') {
128+ return None;
129+ }
130+ let (start, end) = spec.split_once('-')?;
131+ if start.is_empty() {
132+ // A suffix range: the last N bytes.
133+ let suffix: u64 = end.parse().ok()?;
134+ if suffix == 0 || total == 0 {
135+ return Some(Err(()));
136+ }
137+ let start = total.saturating_sub(suffix);
138+ return Some(Ok((start, total - 1)));
139+ }
140+ let start: u64 = start.parse().ok()?;
141+ if end.is_empty() {
142+ if start >= total {
143+ return Some(Err(()));
144+ }
145+ return Some(Ok((start, total - 1)));
146+ }
147+ let end: u64 = end.parse().ok()?;
148+ if start > end || start >= total {
149+ return Some(Err(()));
150+ }
151+ Some(Ok((start, end.min(total - 1))))
152+}
153+
154+/// A cheap, non-cryptographic hash — good enough for an `ETag` on bytes only
155+/// this server ever writes.
156+pub(crate) fn fnv1a(bytes: &[u8]) -> u64 {
157+ let mut hash: u64 = 0xcbf29ce484222325;
158+ for &b in bytes {
159+ hash ^= b as u64;
160+ hash = hash.wrapping_mul(0x100000001b3);
161+ }
162+ hash
163+}
164+
165+#[query_params]
166+struct DownloadQuery {
167+ dl: Option<String>,
168+}
169+
170+/// The file row this account may open: its owner may, and anyone holding a
171+/// live grant onto it may. Trashed files open for nobody here — the trash
172+/// has its own screen. `None` folds "no such file" and "not shared" into
173+/// one answer.
174+async fn visible_file(
175+ store: &dyn Store,
176+ user_id: &str,
177+ file_id: &str,
178+) -> Option<in_core::store::File> {
179+ let file = store.file(file_id).await.ok()??;
180+ if file.deleted_at.is_some() {
181+ return None;
182+ }
183+ if file.owner_id == user_id {
184+ return Some(file);
185+ }
186+ if store
187+ .can_see(ShareKind::File, file_id, user_id)
188+ .await
189+ .unwrap_or(false)
190+ {
191+ return Some(file);
192+ }
193+ None
194+}
195+
196+/// Serves one file's bytes, or the same not-found a stranger would see for
197+/// a file that does not exist — never a `403`, which would confirm the id
198+/// belongs to somebody else's drive.
199+#[route(GET "/file/{id}")]
200+async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {
201+ let id: &str = path_param::<Id>(cx);
202+
203+ let user = match require_user(cx).await {
204+ Ok(user) => user,
205+ // A byte route has no page to carry a refusal on: back to the
206+ // front door, where the sign-in card says what to do.
207+ Err(_) => return Ok(redirect_to("/")),
208+ };
209+
210+ let store = app(cx).store.clone();
211+ let Some(file) = visible_file(store.as_ref(), &user.id, id).await else {
212+ return Ok(not_found());
213+ };
214+ // A view-only grant opens the file's page but not its bytes.
215+ if file.owner_id != user.id
216+ && !store
217+ .can_download(ShareKind::File, id, &user.id)
218+ .await
219+ .unwrap_or(false)
220+ {
221+ return Ok(not_found());
222+ }
223+ let Ok(Some(bytes)) = store.file_bytes(id).await else {
224+ return Ok(not_found());
225+ };
226+
227+ let forced = query_params::<DownloadQuery>(cx)
228+ .ok()
229+ .and_then(|query| query.dl.clone())
230+ .is_some();
231+ let inline = !forced && inline_ok(&file.mime);
232+
233+ let mut headers = HeaderMap::new();
234+ headers.insert(
235+ header::CONTENT_TYPE,
236+ HeaderValue::from_str(&file.mime)
237+ .unwrap_or(HeaderValue::from_static("application/octet-stream")),
238+ );
239+ headers.insert(
240+ header::CONTENT_DISPOSITION,
241+ HeaderValue::from_str(&disposition_of(&file.name, inline))
242+ .unwrap_or(HeaderValue::from_static("attachment")),
243+ );
244+ // Safari refuses to play a `<video>`/`<audio>` element without a `206`
245+ // reply to its own `Range` probe; every other engine loses instant seek
246+ // without one. Sent on every response, not only media — harmless either
247+ // way and one less type to special-case.
248+ headers.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
249+ // A file's bytes are write-once — nothing rewrites a row — so the id in
250+ // the URL is already its own version. A year of `immutable` costs
251+ // nothing because the URL can never outlive its bytes; `private` keeps
252+ // a shared proxy from handing one drive's files to another.
253+ headers.insert(
254+ header::CACHE_CONTROL,
255+ HeaderValue::from_static("private, max-age=31536000, immutable"),
256+ );
257+
258+ let total = bytes.len() as u64;
259+ let range = request_headers(cx)
260+ .get(header::RANGE)
261+ .and_then(|value| value.to_str().ok());
262+ match range.and_then(|range| parse_range(range, total)) {
263+ Some(Ok((start, end))) => {
264+ let slice = bytes[start as usize..=end as usize].to_vec();
265+ headers.insert(
266+ header::CONTENT_RANGE,
267+ HeaderValue::from_str(&format!("bytes {start}-{end}/{total}")).unwrap(),
268+ );
269+ Ok((StatusCode::PARTIAL_CONTENT, headers, slice))
270+ }
271+ Some(Err(())) => {
272+ headers.insert(
273+ header::CONTENT_RANGE,
274+ HeaderValue::from_str(&format!("bytes */{total}")).unwrap(),
275+ );
276+ Ok((StatusCode::RANGE_NOT_SATISFIABLE, headers, Vec::new()))
277+ }
278+ None => Ok((StatusCode::OK, headers, bytes)),
279+ }
280+}
281+
282+/// Serves one file's webp thumbnail under the same visibility as the file
283+/// itself — a listing shows thumbnails wherever it shows names, and names
284+/// need only `can_see`.
285+#[route(GET "/thumb/{id}")]
286+async fn thumb(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {
287+ let id: &str = path_param::<Id>(cx);
288+
289+ let user = match require_user(cx).await {
290+ Ok(user) => user,
291+ Err(_) => return Ok(not_found()),
292+ };
293+
294+ let store = app(cx).store.clone();
295+ let Some(_) = visible_file(store.as_ref(), &user.id, id).await else {
296+ return Ok(not_found());
297+ };
298+ let Ok(Some(bytes)) = store.thumb_bytes(id).await else {
299+ return Ok(not_found());
300+ };
301+
302+ let etag = format!("\"{:x}\"", fnv1a(&bytes));
303+ let mut headers = HeaderMap::new();
304+ headers.insert(
305+ header::ETAG,
306+ HeaderValue::from_str(&etag).unwrap_or(HeaderValue::from_static("\"0\"")),
307+ );
308+ // The bytes are content-addressed by the file id and never rewritten —
309+ // a changed picture is a changed file — so a year of `immutable` never
310+ // shows a stale thumbnail. `private` because the route is gated and a
311+ // shared proxy must not answer a stranger from another drive's entry.
312+ headers.insert(
313+ header::CACHE_CONTROL,
314+ HeaderValue::from_static("private, max-age=31536000, immutable"),
315+ );
316+ headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("image/webp"));
317+
318+ let if_none_match = request_headers(cx)
319+ .get(header::IF_NONE_MATCH)
320+ .and_then(|value| value.to_str().ok());
321+ if if_none_match == Some(etag.as_str()) {
322+ return Ok((StatusCode::NOT_MODIFIED, headers, Vec::new()));
323+ }
324+ Ok((StatusCode::OK, headers, bytes))
325+}
326+
327+/// Takes the files the drive's upload form carries — one per `file` part,
328+/// and a `multiple` picker posts several. The route already caps the whole
329+/// request body at 64 MiB (`main.rs`); each part is buffered whole because
330+/// the store writes it in one go. Fields arrive in request order:
331+/// `folder_id` before the `file` parts, so the destination is known before
332+/// a byte of any file is kept.
333+#[route(POST "/files")]
334+async fn upload(
335+ cx: &Cx,
336+ mut multipart: Multipart,
337+) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {
338+ let user = match require_user(cx).await {
339+ Ok(user) => user,
340+ Err(refusal) => return Ok(back_to_folder(None, Some(refusal))),
341+ };
342+ let store = app(cx).store.clone();
343+
344+ let mut folder_id: Option<String> = None;
345+ let mut files: Vec<(String, Vec<u8>)> = Vec::new();
346+
347+ loop {
348+ let field = match multipart.next_field().await {
349+ Ok(Some(field)) => field,
350+ Ok(None) => break,
351+ Err(_) => {
352+ return Ok(back_to_folder(
353+ folder_id.as_deref(),
354+ Some(Refusal::Unavailable),
355+ ));
356+ }
357+ };
358+ match field.name() {
359+ Some("folder_id") => {
360+ folder_id = field.text().await.ok().filter(|value| !value.is_empty());
361+ }
362+ Some("file") => {
363+ let Some(name) = field.file_name().map(str::to_string) else {
364+ continue;
365+ };
366+ if name.is_empty() {
367+ continue;
368+ }
369+ let mut field = field;
370+ let mut collected = Vec::new();
371+ loop {
372+ match field.chunk().await {
373+ Ok(Some(chunk)) => collected.extend_from_slice(&chunk),
374+ Ok(None) => break,
375+ Err(_) => {
376+ return Ok(back_to_folder(
377+ folder_id.as_deref(),
378+ Some(Refusal::Unavailable),
379+ ));
380+ }
381+ }
382+ }
383+ files.push((name, collected));
384+ }
385+ _ => {}
386+ }
387+ }
388+
389+ // The destination must be an owned, live folder — or the root.
390+ if let Some(folder) = folder_id.as_deref() {
391+ match store.folder(folder).await {
392+ Ok(Some(row)) if row.owner_id == user.id && row.deleted_at.is_none() => {}
393+ _ => return Ok(back_to_folder(None, Some(Refusal::NotFound))),
394+ }
395+ }
396+ if files.is_empty() {
397+ return Ok(back_to_folder(folder_id.as_deref(), None));
398+ }
399+
400+ let mut refusal: Option<Refusal> = None;
401+ for (name, bytes) in files {
402+ // The store sanitises the label, sniffs the mime off the bytes,
403+ // checks the quota, writes the file and attempts the thumbnail.
404+ if let Err(error) = store
405+ .insert_file(&user.id, folder_id.as_deref(), &name, &bytes)
406+ .await
407+ {
408+ refusal = Some(store_refusal(error));
409+ break;
410+ }
411+ }
412+ Ok(back_to_folder(folder_id.as_deref(), refusal))
413+}
414+
415+/// A 303 back to the page the form was posted from, carrying the refusal as
416+/// the body for `carry_refusal_on_redirect` to copy onto the query.
417+type Redirect = Result<(StatusCode, [(HeaderName, String); 1], Json<Option<Refusal>>)>;
418+
419+fn redirect(cx: &Cx, refusal: Option<Refusal>) -> Redirect {
420+ Ok((
421+ StatusCode::SEE_OTHER,
422+ [(header::LOCATION, back_to(cx, "/drive"))],
423+ Json(refusal),
424+ ))
425+}
426+
427+/// The owned, live file the form names, or the refusal the caller returns
428+/// as-is. Another owner's file is not found rather than forbidden.
429+async fn owned_file(cx: &Cx, id: &str) -> std::result::Result<in_core::store::File, Redirect> {
430+ let user = match require_user(cx).await {
431+ Ok(user) => user,
432+ Err(refusal) => return Err(redirect(cx, Some(refusal))),
433+ };
434+ let store = app(cx).store.clone();
435+ match store.file(id).await {
436+ Ok(Some(file)) if file.owner_id == user.id && file.deleted_at.is_none() => Ok(file),
437+ _ => Err(redirect(cx, Some(Refusal::NotFound))),
438+ }
439+}
440+
441+#[derive(serde::Deserialize)]
442+struct FileIdForm {
443+ id: String,
444+}
445+
446+#[derive(serde::Deserialize)]
447+struct RenameFileForm {
448+ id: String,
449+ name: String,
450+}
451+
452+#[derive(serde::Deserialize)]
453+struct MoveFileForm {
454+ id: String,
455+ #[serde(default)]
456+ folder_id: String,
457+}
458+
459+/// `POST /api/file/rename`: a new label on an owned file.
460+#[route(POST "/api/file/rename")]
461+async fn rename_file(cx: &Cx, Form(input): Form<RenameFileForm>) -> Redirect {
462+ let file = match owned_file(cx, &input.id).await {
463+ Ok(file) => file,
464+ Err(answer) => return answer,
465+ };
466+ let store = app(cx).store.clone();
467+ match store.rename_file(&file.id, &input.name).await {
468+ Ok(_) => redirect(cx, None),
469+ Err(error) => redirect(cx, Some(store_refusal(error))),
470+ }
471+}
472+
473+/// `POST /api/file/move`: an owned file into an owned folder, or the root.
474+#[route(POST "/api/file/move")]
475+async fn move_file(cx: &Cx, Form(input): Form<MoveFileForm>) -> Redirect {
476+ let file = match owned_file(cx, &input.id).await {
477+ Ok(file) => file,
478+ Err(answer) => return answer,
479+ };
480+ let store = app(cx).store.clone();
481+ let folder = if input.folder_id.is_empty() {
482+ None
483+ } else {
484+ Some(input.folder_id.as_str())
485+ };
486+ if let Some(id) = folder {
487+ let user = match require_user(cx).await {
488+ Ok(user) => user,
489+ Err(refusal) => return redirect(cx, Some(refusal)),
490+ };
491+ match store.folder(id).await {
492+ Ok(Some(row)) if row.owner_id == user.id && row.deleted_at.is_none() => {}
493+ _ => return redirect(cx, Some(Refusal::NotFound)),
494+ }
495+ }
496+ match store.move_file(&file.id, folder).await {
497+ Ok(_) => redirect(cx, None),
498+ Err(error) => redirect(cx, Some(store_refusal(error))),
499+ }
500+}
501+
502+/// `POST /api/file/delete`: trash an owned file. The bytes stay on disk —
503+/// and counting toward quota — until the trash purges the row.
504+#[route(POST "/api/file/delete")]
505+async fn delete_file(cx: &Cx, Form(input): Form<FileIdForm>) -> Redirect {
506+ let file = match owned_file(cx, &input.id).await {
507+ Ok(file) => file,
508+ Err(answer) => return answer,
509+ };
510+ let store = app(cx).store.clone();
511+ match store.delete_file(&file.id).await {
512+ Ok(_) => redirect(cx, None),
513+ Err(error) => redirect(cx, Some(store_refusal(error))),
514+ }
515+}
crates/in-web/src/i18n.rsadded+358 -0
@@ -0,0 +1,358 @@
1+//! UI strings in two languages.
2+//!
3+//! v1 has no language column on the user row, so the reader's language comes
4+//! off the request: an `Accept-Language` tag starting with `tr` reads
5+//! Turkish, everything else reads English. An unrecognized tag is not a
6+//! refusal, just the default.
7+
8+use topcoat::context::Cx;
9+use topcoat::router::header;
10+use topcoat::router::request::headers;
11+
12+/// English or Turkish, read off the request's `Accept-Language`.
13+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14+pub enum Lang {
15+ En,
16+ Tr,
17+}
18+
19+impl Lang {
20+ /// Anything not `tr` is English.
21+ pub fn from_code(code: &str) -> Lang {
22+ match code {
23+ "tr" => Lang::Tr,
24+ _ => Lang::En,
25+ }
26+ }
27+
28+ /// The first language tag the browser asked for: `tr`, `tr-TR` and
29+ /// friends read Turkish, the rest — including a missing header — read
30+ /// English.
31+ pub fn from_header(value: &str) -> Lang {
32+ let tag = value.split(',').next().unwrap_or("").trim();
33+ let tag = tag.split(';').next().unwrap_or("").trim();
34+ let base = tag.split('-').next().unwrap_or("").trim().to_lowercase();
35+ Lang::from_code(&base)
36+ }
37+
38+ /// The `<html lang>` value.
39+ pub fn code(self) -> &'static str {
40+ match self {
41+ Lang::En => "en",
42+ Lang::Tr => "tr",
43+ }
44+ }
45+}
46+
47+/// The request's language: `Accept-Language` first, English when it says
48+/// nothing usable.
49+pub fn lang(cx: &Cx) -> Lang {
50+ headers(cx)
51+ .get(header::ACCEPT_LANGUAGE)
52+ .and_then(|value| value.to_str().ok())
53+ .map(Lang::from_header)
54+ .unwrap_or(Lang::En)
55+}
56+
57+/// One variant per UI phrase. A typo'd key fails to compile rather than
58+/// falling through to nothing at render time.
59+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60+pub enum Key {
61+ // Shared chrome.
62+ Cancel,
63+ Save,
64+ Close,
65+ Delete,
66+ Rename,
67+ Move,
68+ Create,
69+ Confirm,
70+ Back,
71+ Download,
72+ Retry,
73+ SomethingWentWrong,
74+ NothingAtThisAddress,
75+ BackToDrive,
76+ // Landing.
77+ WelcomeTitle,
78+ WelcomeBlurb,
79+ SignIn,
80+ // Topbar.
81+ NavDrive,
82+ NavShared,
83+ NavTrash,
84+ NavSearch,
85+ NavSettings,
86+ SignOut,
87+ AdminBadge,
88+ UserMenuLabel,
89+ // Drive browser.
90+ Drive,
91+ NewFolder,
92+ FolderName,
93+ CreateFolder,
94+ RenameFolder,
95+ MoveFolder,
96+ DeleteFolder,
97+ EmptyFolder,
98+ FoldersHeading,
99+ FilesHeading,
100+ NameColumn,
101+ SizeColumn,
102+ ModifiedColumn,
103+ // Upload.
104+ Upload,
105+ UploadFile,
106+ ChooseFiles,
107+ DropFilesHere,
108+ Uploading,
109+ UploadComplete,
110+ UploadFailed,
111+ CancelUpload,
112+ RetryUpload,
113+ // File view.
114+ FileDetails,
115+ PreviewUnavailable,
116+ RenameFile,
117+ MoveFile,
118+ DeleteFile,
119+ // Share.
120+ Share,
121+ ShareLink,
122+ CopyLink,
123+ RevokeLink,
124+ SharedWith,
125+ ShareWithUser,
126+ SharePlaceholder,
127+ CanDownload,
128+ RemoveAccess,
129+ SharedWithMe,
130+ NoSharedItems,
131+ // Trash.
132+ Trash,
133+ TrashEmpty,
134+ Restore,
135+ DeleteForever,
136+ EmptyTrash,
137+ // Search.
138+ SearchResults,
139+ SearchPlaceholder,
140+ NoResults,
141+ TypeToSearch,
142+ // Settings.
143+ Settings,
144+ Profile,
145+ DisplayName,
146+ EmailAddress,
147+ QuotaUsage,
148+ QuotaOf,
149+ AdminPanel,
150+ AllUsers,
151+ SetQuota,
152+ QuotaBytes,
153+ DisableUser,
154+ EnableUser,
155+ DisabledBadge,
156+ // Wave-2 share/trash/search/settings additions.
157+ LinkCreated,
158+ CopyLinkOnce,
159+ ExpiresLabel,
160+ NeverExpires,
161+ ViewOnly,
162+ NoLinks,
163+ ManageLinks,
164+}
165+
166+pub fn t(lang: Lang, key: Key) -> &'static str {
167+ use Key::*;
168+ match lang {
169+ Lang::En => match key {
170+ Cancel => "Cancel",
171+ Save => "Save",
172+ Close => "Close",
173+ Delete => "Delete",
174+ Rename => "Rename",
175+ Move => "Move",
176+ Create => "Create",
177+ Confirm => "Confirm",
178+ Back => "Back",
179+ Download => "Download",
180+ Retry => "Retry",
181+ SomethingWentWrong => "Something went wrong.",
182+ NothingAtThisAddress => "There is nothing at this address.",
183+ BackToDrive => "Back to the drive",
184+ WelcomeTitle => "In — your files",
185+ WelcomeBlurb => "Your folders and files, shared on your terms.",
186+ SignIn => "Sign in",
187+ NavDrive => "Drive",
188+ NavShared => "Shared",
189+ NavTrash => "Trash",
190+ NavSearch => "Search",
191+ NavSettings => "Settings",
192+ SignOut => "Sign out",
193+ AdminBadge => "admin",
194+ UserMenuLabel => "Account",
195+ Drive => "Drive",
196+ NewFolder => "New folder",
197+ FolderName => "Folder name",
198+ CreateFolder => "Create folder",
199+ RenameFolder => "Rename folder",
200+ MoveFolder => "Move folder",
201+ DeleteFolder => "Delete folder",
202+ EmptyFolder => "This folder is empty.",
203+ FoldersHeading => "Folders",
204+ FilesHeading => "Files",
205+ NameColumn => "Name",
206+ SizeColumn => "Size",
207+ ModifiedColumn => "Changed",
208+ Upload => "Upload",
209+ UploadFile => "Upload files",
210+ ChooseFiles => "Choose files",
211+ DropFilesHere => "Drop files here to upload them.",
212+ Uploading => "Uploading…",
213+ UploadComplete => "Upload complete.",
214+ UploadFailed => "The upload failed.",
215+ CancelUpload => "Cancel the upload",
216+ RetryUpload => "Try again",
217+ FileDetails => "File",
218+ PreviewUnavailable => "No preview for this kind of file.",
219+ RenameFile => "Rename file",
220+ MoveFile => "Move file",
221+ DeleteFile => "Delete file",
222+ Share => "Share",
223+ ShareLink => "Share link",
224+ CopyLink => "Copy the link",
225+ RevokeLink => "Revoke the link",
226+ SharedWith => "Shared with",
227+ ShareWithUser => "Share with someone",
228+ SharePlaceholder => "Name or address",
229+ CanDownload => "May download",
230+ RemoveAccess => "Remove access",
231+ SharedWithMe => "Shared with me",
232+ NoSharedItems => "Nothing is shared with you yet.",
233+ Trash => "Trash",
234+ TrashEmpty => "The trash is empty.",
235+ Restore => "Restore",
236+ DeleteForever => "Delete forever",
237+ EmptyTrash => "Empty the trash",
238+ SearchResults => "Search results",
239+ SearchPlaceholder => "Search files and folders…",
240+ NoResults => "Nothing found.",
241+ TypeToSearch => "Type above to search your files.",
242+ Settings => "Settings",
243+ Profile => "Profile",
244+ DisplayName => "Name",
245+ EmailAddress => "Address",
246+ QuotaUsage => "Storage used",
247+ QuotaOf => "of",
248+ AdminPanel => "Everyone",
249+ AllUsers => "Everyone",
250+ SetQuota => "Set the quota",
251+ QuotaBytes => "Quota in bytes",
252+ DisableUser => "Disable",
253+ EnableUser => "Enable",
254+ DisabledBadge => "disabled",
255+ LinkCreated => "Link created.",
256+ CopyLinkOnce => "Copy it now — it is shown once and never again.",
257+ ExpiresLabel => "Expires",
258+ NeverExpires => "Never",
259+ ViewOnly => "View only — preview, no downloads",
260+ NoLinks => "No share links yet.",
261+ ManageLinks => "Share links",
262+ },
263+ Lang::Tr => match key {
264+ Cancel => "Vazgeç",
265+ Save => "Kaydet",
266+ Close => "Kapat",
267+ Delete => "Sil",
268+ Rename => "Yeniden adlandır",
269+ Move => "Taşı",
270+ Create => "Oluştur",
271+ Confirm => "Onayla",
272+ Back => "Geri",
273+ Download => "İndir",
274+ Retry => "Tekrar dene",
275+ SomethingWentWrong => "Bir şeyler ters gitti.",
276+ NothingAtThisAddress => "Bu adreste bir şey yok.",
277+ BackToDrive => "Sürücüye dön",
278+ WelcomeTitle => "In — dosyaların",
279+ WelcomeBlurb => "Klasörlerin ve dosyaların, senin kurallarınla.",
280+ SignIn => "Oturum aç",
281+ NavDrive => "Sürücü",
282+ NavShared => "Paylaşılan",
283+ NavTrash => "Çöp",
284+ NavSearch => "Ara",
285+ NavSettings => "Ayarlar",
286+ SignOut => "Oturumu kapat",
287+ AdminBadge => "yönetici",
288+ UserMenuLabel => "Hesap",
289+ Drive => "Sürücü",
290+ NewFolder => "Yeni klasör",
291+ FolderName => "Klasör adı",
292+ CreateFolder => "Klasörü oluştur",
293+ RenameFolder => "Klasörü yeniden adlandır",
294+ MoveFolder => "Klasörü taşı",
295+ DeleteFolder => "Klasörü sil",
296+ EmptyFolder => "Bu klasör boş.",
297+ FoldersHeading => "Klasörler",
298+ FilesHeading => "Dosyalar",
299+ NameColumn => "Ad",
300+ SizeColumn => "Boyut",
301+ ModifiedColumn => "Değişiklik",
302+ Upload => "Yükle",
303+ UploadFile => "Dosya yükle",
304+ ChooseFiles => "Dosya seç",
305+ DropFilesHere => "Yüklemek için dosyaları buraya bırak.",
306+ Uploading => "Yükleniyor…",
307+ UploadComplete => "Yükleme tamamlandı.",
308+ UploadFailed => "Yükleme başarısız oldu.",
309+ CancelUpload => "Yüklemeyi iptal et",
310+ RetryUpload => "Yeniden dene",
311+ FileDetails => "Dosya",
312+ PreviewUnavailable => "Bu tür dosyanın önizlemesi yok.",
313+ RenameFile => "Dosyayı yeniden adlandır",
314+ MoveFile => "Dosyayı taşı",
315+ DeleteFile => "Dosyayı sil",
316+ Share => "Paylaş",
317+ ShareLink => "Paylaşım bağlantısı",
318+ CopyLink => "Bağlantıyı kopyala",
319+ RevokeLink => "Bağlantıyı iptal et",
320+ SharedWith => "Paylaşılanlar",
321+ ShareWithUser => "Biriyle paylaş",
322+ SharePlaceholder => "Ad ya da adres",
323+ CanDownload => "İndirebilir",
324+ RemoveAccess => "Erişimi kaldır",
325+ SharedWithMe => "Benimle paylaşılanlar",
326+ NoSharedItems => "Seninle henüz bir şey paylaşılmadı.",
327+ Trash => "Çöp",
328+ TrashEmpty => "Çöp boş.",
329+ Restore => "Geri al",
330+ DeleteForever => "Kalıcı olarak sil",
331+ EmptyTrash => "Çöpü boşalt",
332+ SearchResults => "Arama sonuçları",
333+ SearchPlaceholder => "Dosya ve klasör ara…",
334+ NoResults => "Bir şey bulunamadı.",
335+ TypeToSearch => "Dosyalarında aramak için yukarı yaz.",
336+ Settings => "Ayarlar",
337+ Profile => "Profil",
338+ DisplayName => "Ad",
339+ EmailAddress => "Adres",
340+ QuotaUsage => "Kullanılan alan",
341+ QuotaOf => "/",
342+ AdminPanel => "Herkes",
343+ AllUsers => "Herkes",
344+ SetQuota => "Kotayı ayarla",
345+ QuotaBytes => "Bayt olarak kota",
346+ DisableUser => "Devre dışı bırak",
347+ EnableUser => "Etkinleştir",
348+ DisabledBadge => "devre dışı",
349+ LinkCreated => "Bağlantı oluşturuldu.",
350+ CopyLinkOnce => "Şimdi kopyala — bir kez gösterilir, bir daha gösterilmez.",
351+ ExpiresLabel => "Bitiş",
352+ NeverExpires => "Süresiz",
353+ ViewOnly => "Yalnızca görüntüleme — önizleme, indirme yok",
354+ NoLinks => "Henüz paylaşım bağlantısı yok.",
355+ ManageLinks => "Paylaşım bağlantıları",
356+ },
357+ }
358+}
crates/in-web/src/layout.rsadded+908 -0
@@ -0,0 +1,908 @@
1+//! The document shell every page renders inside: the monogram, the wordmark,
2+//! the topbar, the client scripts, and the root layout with its 404 catch.
3+//!
4+//! The one document-level contract with the client lives in the scripts at
5+//! the bottom — `soft_nav_script`, `live_script` and the escape manager —
6+//! and the morph ownership flags they define (`__inOwn`, `__inAdded`,
7+//! `__inNav`).
8+
9+use topcoat::{
10+ Result,
11+ asset::{Asset, asset},
12+ context::Cx,
13+ router::{
14+ StatusCode,
15+ error::{NotFoundError, not_found},
16+ layout, page,
17+ },
18+ view::{Unescaped, view},
19+};
20+
21+use in_core::store::User;
22+
23+use crate::i18n::{Key, Lang, t};
24+use crate::server::current_user;
25+
26+/// The In monogram again, as the tab icon: the same drawing as `mark`,
27+/// inlined because it must carry its own colours — a data URI has no page to
28+/// inherit `currentColor` or the accent token from, so the two themes are
29+/// spelled out in a media query inside the SVG.
30+const FAVICON: &str = "data:image/svg+xml,\
31+ <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'>\
32+ <style>.i{fill:%231a1b1d}.t{fill:%2346557b}.s{stroke:%231a1b1d}\
33+ @media(prefers-color-scheme:dark){.i{fill:%23e6e4de}.t{fill:%238ba1e8}\
34+ .s{stroke:%23e6e4de}}</style>\
35+ <rect class='i' x='3.1' y='9.4' width='4.4' height='11.6' rx='2.2'/>\
36+ <circle class='t' cx='5.3' cy='4.9' r='2.6'/>\
37+ <path class='s' d='M11.4 19.8V10.6h2.4c2.6 0 4.2 1.7 4.2 4.3v4.9' fill='none' \
38+ stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'/></svg>";
39+
40+/// The In monogram — a dotted `i` beside a stroked `n`. It takes
41+/// `currentColor` for its strokes and the accent for its tittle, so one
42+/// drawing serves both skins and both themes.
43+///
44+/// The monogram and the wordmark are alternates, never a pair: standing them
45+/// side by side reads as a stutter no amount of space or framing repairs.
46+/// The mark carries the chrome, where the name is already known and the room
47+/// is 44px; the word carries the front door, where a stranger arrives and
48+/// nothing else has said it yet.
49+pub(crate) async fn mark(cx: &Cx) -> Result {
50+ view! {
51+ cx =>
52+ <a class="wordmark" href="/" aria-label="In">
53+ <svg class="wordmark-mark" width="24" height="24" viewBox="0 0 24 24"
54+ aria-hidden="true">
55+ <rect x="3.1" y="9.4" width="4.4" height="11.6" rx="2.2"
56+ fill="currentColor"></rect>
57+ <circle class="wordmark-tittle" cx="5.3" cy="4.9" r="2.6"></circle>
58+ <path d="M11.4 19.8V10.6h2.4c2.6 0 4.2 1.7 4.2 4.3v4.9" fill="none"
59+ stroke="currentColor" stroke-width="2.5" stroke-linecap="round"
60+ stroke-linejoin="round"></path>
61+ </svg>
62+ </a>
63+ }
64+}
65+
66+/// The wordmark, the monogram's other half: the name alone, in the one face
67+/// both skins agree on. The sign-in page wears it — see `mark`.
68+pub(crate) async fn wordmark(cx: &Cx) -> Result {
69+ view! {
70+ cx =>
71+ <a class="wordmark wordmark-lone" href="/">
72+ <span class="wordmark-text">"In"</span>
73+ </a>
74+ }
75+}
76+
77+/// A person as a circle (or, on the Instrument skin, a square): the initials,
78+/// toned by the id so every account has its own colour. Shared by the
79+/// topbar user menu on every signed-in page.
80+pub(crate) async fn avatar(cx: &Cx, user: &User, extra: &str) -> Result {
81+ let tone = user
82+ .id
83+ .bytes()
84+ .fold(0u32, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u32))
85+ % 5;
86+ let class = format!("avatar avatar-tone-{tone} {extra}");
87+ let name = user.display_name.clone();
88+ let initials = initials_of(&user.display_name);
89+ view! {
90+ cx =>
91+ <span class=(class) data-name=(name)>(initials)</span>
92+ }
93+}
94+
95+/// The first letters of the first two words, uppercased — "Ada Lovelace"
96+/// wears "AL", a bare address wears its first letter.
97+fn initials_of(name: &str) -> String {
98+ let mut out = String::new();
99+ for word in name.split_whitespace().take(2) {
100+ if let Some(first) = word.chars().next() {
101+ out.extend(first.to_uppercase());
102+ }
103+ }
104+ if out.is_empty() {
105+ out.push('?');
106+ }
107+ out
108+}
109+
110+/// The topbar's signed-in identity: the display name, opening on hover or
111+/// focus onto details (name, address) and sign-out. Shared by every
112+/// signed-in page's topbar.
113+pub async fn user_menu(cx: &Cx, user: &User, lang: Lang) -> Result {
114+ view! {
115+ cx =>
116+ <div class="user-menu">
117+ <button type="button" class="user-menu-trigger" aria-label=(t(lang, Key::UserMenuLabel))>
118+ (avatar(cx, user, "").await?)
119+ <span class="user-menu-trigger-name">(user.display_name.clone())</span>
120+ </button>
121+ <div class="user-menu-panel">
122+ <div class="user-menu-name">(user.display_name.clone())</div>
123+ <div class="user-menu-email">(user.email.clone())</div>
124+ if user.admin {
125+ <div class="user-menu-role">(t(lang, Key::AdminBadge))</div>
126+ }
127+ <a class="user-menu-item" href="/settings">(t(lang, Key::NavSettings))</a>
128+ <a class="user-menu-item" href="/auth/logout" data-hard="">(t(lang, Key::SignOut))</a>
129+ </div>
130+ </div>
131+ }
132+}
133+
134+/// The signed-in pages, as the topbar nav links between them.
135+#[derive(Clone, Copy, PartialEq)]
136+pub enum NavPage {
137+ Drive,
138+ Shared,
139+ Trash,
140+ Search,
141+ Settings,
142+}
143+
144+impl NavPage {
145+ const ALL: [Self; 5] = [
146+ Self::Drive,
147+ Self::Shared,
148+ Self::Trash,
149+ Self::Search,
150+ Self::Settings,
151+ ];
152+
153+ fn href(self) -> &'static str {
154+ match self {
155+ Self::Drive => "/drive",
156+ Self::Shared => "/shared",
157+ Self::Trash => "/trash",
158+ Self::Search => "/search",
159+ Self::Settings => "/settings",
160+ }
161+ }
162+
163+ fn label(self) -> Key {
164+ match self {
165+ Self::Drive => Key::NavDrive,
166+ Self::Shared => Key::NavShared,
167+ Self::Trash => Key::NavTrash,
168+ Self::Search => Key::NavSearch,
169+ Self::Settings => Key::NavSettings,
170+ }
171+ }
172+}
173+
174+/// The topbar's page nav, shared by every signed-in page, with the current
175+/// one marked. Plain `<a>`s — the soft-nav forwarder swaps them like any
176+/// same-origin link, so `data-hard` stays off.
177+pub async fn topbar_nav(cx: &Cx, active: NavPage, lang: Lang) -> Result {
178+ view! {
179+ cx =>
180+ <nav class="topbar-nav-links">
181+ for page in NavPage::ALL {
182+ <a
183+ class=(if page == active { "topbar-nav topbar-nav-on" } else { "topbar-nav" })
184+ href=(page.href())
185+ >
186+ (t(lang, page.label()))
187+ </a>
188+ }
189+ </nav>
190+ }
191+}
192+
193+/// The signed-in chrome: the monogram, the page nav, the identity menu.
194+/// Wave-2 pages render their content under this.
195+pub async fn topbar(cx: &Cx, active: NavPage, user: &User, lang: Lang) -> Result {
196+ view! {
197+ cx =>
198+ <header class="topbar">
199+ (mark(cx).await?)
200+ (topbar_nav(cx, active, lang).await?)
201+ (user_menu(cx, user, lang).await?)
202+ </header>
203+ }
204+}
205+
206+/// The page-swap machinery that keeps every mutation on the same document.
207+///
208+/// Every `/api/*` mutation is a plain form post answered with a 303 — sound
209+/// without script, but a full navigation repaints the whole page for a
210+/// one-field change. This script, emitted first in `<body>` on every page,
211+/// intercepts those submits (capture-phase, so `requestSubmit()` from any
212+/// auto-submit control lands here too), replays them over `fetch`, and swaps
213+/// the redirected page's `<body>` children in place — same bytes the hard
214+/// navigation would have shown, no reload. Refusal banners and saved chips
215+/// arrive with the swap because the redirect URL's query params rendered
216+/// them server-side; `history.replaceState` keeps the address bar honest.
217+///
218+/// The replay declares `Accept: text/html`, because a replayed form post is a
219+/// form post asking for the page back: `carry_refusal_on_redirect`
220+/// (`server.rs`) copies a refusing 303's answer onto the `Location` only for a
221+/// caller that wants the page, and a bare `fetch` asks for `*/*` — under which
222+/// the refusal stayed in a body nobody reads and the click looked like nothing
223+/// happening. A refused save and a clean one once landed on the same silent
224+/// page; the header is what keeps them apart.
225+///
226+/// Every fetch that ends in a swap carries the navigation counter it started
227+/// under (`window.__inNav`), and its answer is thrown away if that counter
228+/// has moved. Without it the newest paint is not the newest intent: the live
229+/// refresh fetches the URL it was on, and a click landing during that flight
230+/// pushed a new page that the refresh's answer then overwrote — the page
231+/// arriving and reverting to the previous one two hundred milliseconds later.
232+/// Navigations, form posts and the overlay closes each step the counter, so a
233+/// second click also wins over a first one still in flight, and a refresh —
234+/// which is not an intent, only an update of what is already on screen —
235+/// steps nothing and lands only if nothing else has happened.
236+///
237+/// The address bar and the `<html>` attributes are rewritten *before* the
238+/// new body's scripts run, never after: a swapped-in script that reads
239+/// `location.href` (the log-fit reload in `logs.rs`) would otherwise read
240+/// the page it just replaced and hard-navigate back to it.
241+///
242+/// Swapped-in `<script>` nodes are inert (parser-inserted only), so
243+/// `swap()` re-creates each one as a fresh element, which runs it; every
244+/// emitted script carries a one-shot `window.__in*` guard, so that
245+/// re-execution never stacks duplicate document-level listeners. There
246+/// is no topcoat re-hydrate entry, so per-element behavior is re-run by
247+/// the `in:wire` event (wave-2 enhancements re-derive what they draw from
248+/// server data on every wire) over the new nodes.
249+///
250+/// Forms that must really navigate (sign-in/out: the session cookie and the
251+/// whole page identity change) opt out with `data-hard`.
252+/// Overlay closes never hit the server at all: the drive is already
253+/// rendered under the modal, so `__inCloseModal`/`__inCloseViewer`
254+/// drop the overlay's DOM and rewrite the URL.
255+///
256+/// The click-forwarder at the end is the fix for the dead-zone clicks a
257+/// styled select first showed: any click inside a
258+/// `.field-box`/`.status-form`/`.member-role` that misses the `.dd-trigger`
259+/// (label, chevron glyph, box padding) is forwarded to the trigger.
260+///
261+/// Ordinary same-origin links get the same treatment: a delegated capture
262+/// click listener — registered after the close/scrim one, and skipped when
263+/// that one already `preventDefault`ed — fetches the href and swaps it in
264+/// under a `history.pushState`, so folder rows and file chips no longer
265+/// reload the page. Raw `/files/` byte routes, `download`/`target`/
266+/// `data-hard` links and modified clicks (ctrl/meta/shift/alt, non-left
267+/// button) stay browser-native. `popstate` replays the same fetch without
268+/// pushing. Fresh-URL navigations pass `swap`'s third argument to scroll
269+/// to top; in-place swaps (form posts, back) keep the scroll position.
270+/// `wire()` also pins every `.comment-list` to its bottom, on initial
271+/// load (DOMContentLoaded) included. (No comment lists in v1; the hook
272+/// stays so wave-2 additions inherit the behavior.)
273+pub async fn soft_nav_script(cx: &Cx) -> Result {
274+ const JS: &str = "\
275+ (function () { \
276+ if (window.__inSoft) { return; } \
277+ window.__inSoft = true; \
278+ window.__inBuild = document.documentElement.getAttribute('data-build') || ''; \
279+ window.__inOwn = function (node, classes, attrs) { \
280+ var own = node.__inMine; \
281+ if (!own) { own = node.__inMine = { c: [], a: [] }; } \
282+ (classes || []).forEach(function (c) { \
283+ if (own.c.indexOf(c) === -1) { own.c.push(c); } \
284+ node.classList.add(c); \
285+ }); \
286+ (attrs || []).forEach(function (a) { if (own.a.indexOf(a) === -1) { own.a.push(a); } }); \
287+ return node; \
288+ }; \
289+ window.__inAdded = function (node) { node.__inAdded = true; return node; }; \
290+ function wire() { \
291+ document.querySelectorAll('.comment-list').forEach(function (list) { list.scrollTop = list.scrollHeight; }); \
292+ document.dispatchEvent(new Event('in:wire')); \
293+ } \
294+ function keyOf(el) { \
295+ var form = el.form ? (el.form.getAttribute('action') || '') : ''; \
296+ return form + '|' + (el.name || '') + '|' + (el.type || '') + '|' + (el.tagName || ''); \
297+ } \
298+ function editable(el) { \
299+ return el.type !== 'hidden' && el.type !== 'password' && el.type !== 'file'; \
300+ } \
301+ function captureFields() { \
302+ var active = document.activeElement, out = []; \
303+ document.querySelectorAll('input, textarea, select').forEach(function (el) { \
304+ if (!editable(el)) { return; } \
305+ var moved; \
306+ if (el.type === 'checkbox' || el.type === 'radio') { moved = el.checked !== el.defaultChecked; } \
307+ else if (el.tagName === 'SELECT') { \
308+ var def = -1; \
309+ for (var j = 0; j < el.options.length; j++) { if (el.options[j].defaultSelected) { def = j; break; } } \
310+ if (def < 0) { def = 0; } \
311+ moved = el.selectedIndex !== def; \
312+ } else { moved = el.value !== el.defaultValue; } \
313+ var focused = el === active; \
314+ if (!moved && !focused) { return; } \
315+ var start = -1, end = -1; \
316+ try { if (el.selectionStart != null) { start = el.selectionStart; end = el.selectionEnd; } } catch (err) { } \
317+ out.push({ k: keyOf(el), v: el.value, c: el.checked, i: el.selectedIndex, f: focused, s: start, e: end }); \
318+ }); \
319+ return out; \
320+ } \
321+ function restoreFields(saved) { \
322+ if (!saved || !saved.length) { return; } \
323+ var fields = document.querySelectorAll('input, textarea, select'); \
324+ saved.forEach(function (was) { \
325+ var el = null; \
326+ for (var i = 0; i < fields.length; i++) { \
327+ if (keyOf(fields[i]) === was.k) { el = fields[i]; break; } \
328+ } \
329+ if (!el) { return; } \
330+ if (el.type === 'checkbox' || el.type === 'radio') { el.checked = was.c; } \
331+ else if (el.tagName === 'SELECT') { el.selectedIndex = was.i; } \
332+ else { el.value = was.v; } \
333+ if (was.f) { \
334+ try { \
335+ el.focus(); \
336+ if (was.s >= 0 && el.setSelectionRange) { el.setSelectionRange(was.s, was.e); } \
337+ } catch (err) { } \
338+ } \
339+ }); \
340+ } \
341+ function clientMade(node) { return node.__inAdded === true; } \
342+ function pairable(a, b) { \
343+ if (a.nodeType !== b.nodeType) { return false; } \
344+ if (a.nodeType !== 1) { return true; } \
345+ if (a.nodeName !== b.nodeName) { return false; } \
346+ if (a.id || b.id) { return a.id === b.id; } \
347+ return true; \
348+ } \
349+ function syncClass(from, to, own) { \
350+ var want = []; \
351+ to.classList.forEach(function (c) { want.push(c); }); \
352+ if (own) { \
353+ own.c.forEach(function (c) { \
354+ if (from.classList.contains(c) && want.indexOf(c) === -1) { want.push(c); } \
355+ }); \
356+ } \
357+ if (want.length) { from.setAttribute('class', want.join(' ')); } \
358+ else if (from.hasAttribute('class')) { from.removeAttribute('class'); } \
359+ } \
360+ function syncAttrs(from, to) { \
361+ var own = from.__inMine, i, at; \
362+ for (i = to.attributes.length - 1; i >= 0; i--) { \
363+ at = to.attributes[i]; \
364+ if (at.name === 'class') { continue; } \
365+ if (own && own.a.indexOf(at.name) !== -1) { continue; } \
366+ if (from.getAttribute(at.name) !== at.value) { from.setAttribute(at.name, at.value); } \
367+ } \
368+ for (i = from.attributes.length - 1; i >= 0; i--) { \
369+ at = from.attributes[i]; \
370+ if (at.name === 'class') { continue; } \
371+ if (own && own.a.indexOf(at.name) !== -1) { continue; } \
372+ if (!to.hasAttribute(at.name)) { from.removeAttribute(at.name); } \
373+ } \
374+ syncClass(from, to, own); \
375+ } \
376+ function morph(from, to) { \
377+ if (from.nodeType !== 1) { \
378+ if (from.nodeValue !== to.nodeValue) { from.nodeValue = to.nodeValue; } \
379+ return; \
380+ } \
381+ syncAttrs(from, to); \
382+ if (from.nodeName === 'SCRIPT') { \
383+ if (from.textContent !== to.textContent) { \
384+ var live = document.createElement('script'); \
385+ if (to.hasAttribute('src')) { live.setAttribute('src', to.getAttribute('src')); } \
386+ live.textContent = to.textContent; \
387+ from.replaceWith(live); \
388+ } \
389+ return; \
390+ } \
391+ morphChildren(from, to); \
392+ } \
393+ function morphChildren(from, to) { \
394+ var mine = [], theirs = [], n; \
395+ for (n = from.firstChild; n; n = n.nextSibling) { if (!clientMade(n)) { mine.push(n); } } \
396+ for (n = to.firstChild; n; n = n.nextSibling) { theirs.push(n); } \
397+ var i; \
398+ for (i = 0; i < theirs.length; i++) { \
399+ if (i < mine.length) { \
400+ if (pairable(mine[i], theirs[i])) { morph(mine[i], theirs[i]); } \
401+ else { mine[i].replaceWith(document.importNode(theirs[i], true)); } \
402+ } else { \
403+ from.appendChild(document.importNode(theirs[i], true)); \
404+ } \
405+ } \
406+ for (i = theirs.length; i < mine.length; i++) { mine[i].remove(); } \
407+ } \
408+ window.__inNav = 0; \
409+ function navStep() { return ++window.__inNav; } \
410+ function stillCurrent(n) { return window.__inNav === n; } \
411+ function swap(html, url, fresh, push, morphing) { \
412+ var doc = new DOMParser().parseFromString(html, 'text/html'); \
413+ var build = doc.documentElement.getAttribute('data-build') || ''; \
414+ if (build && window.__inBuild && build !== window.__inBuild) { \
415+ var dirty = captureFields().length > 0; \
416+ var reloaded = null; \
417+ try { reloaded = sessionStorage.getItem('inSkewFor'); } catch (err) { } \
418+ if (!dirty && reloaded !== build) { \
419+ try { sessionStorage.setItem('inSkewFor', build); } catch (err) { } \
420+ location.reload(); \
421+ return; \
422+ } \
423+ if (!dirty) { \
424+ window.__inBuild = build; \
425+ document.documentElement.setAttribute('data-build', build); \
426+ } \
427+ } \
428+ var keep = window.__inKeep ? captureFields() : null; \
429+ window.__inKeep = false; \
430+ var x = window.scrollX, y = window.scrollY; \
431+ var root = doc.documentElement; \
432+ if (root.getAttribute('lang')) { document.documentElement.setAttribute('lang', root.getAttribute('lang')); } \
433+ if (root.hasAttribute('data-theme')) { document.documentElement.setAttribute('data-theme', root.getAttribute('data-theme')); } \
434+ else { document.documentElement.removeAttribute('data-theme'); } \
435+ if (root.hasAttribute('data-ui')) { document.documentElement.setAttribute('data-ui', root.getAttribute('data-ui')); } \
436+ else { document.documentElement.removeAttribute('data-ui'); } \
437+ if (url) { history[push ? 'pushState' : 'replaceState'](null, '', url); } \
438+ if (morphing) { \
439+ morph(document.body, doc.body); \
440+ } else { \
441+ document.body.replaceChildren(); \
442+ while (doc.body.firstChild) { document.body.appendChild(doc.body.firstChild); } \
443+ document.body.querySelectorAll('script').forEach(function (old) { \
444+ var live = document.createElement('script'); \
445+ if (old.hasAttribute('src')) { live.setAttribute('src', old.getAttribute('src')); } \
446+ live.textContent = old.textContent; \
447+ old.replaceWith(live); \
448+ }); \
449+ window.scrollTo(fresh ? 0 : x, fresh ? 0 : y); \
450+ } \
451+ restoreFields(keep); \
452+ wire(); \
453+ } \
454+ function sweepPanels() { \
455+ document.querySelectorAll('.dd-panel').forEach(function (panel) { \
456+ if (panel.__ddTrigger && !document.contains(panel.__ddTrigger)) { panel.remove(); } \
457+ }); \
458+ } \
459+ window.__inGo = function (url) { \
460+ var n = navStep(); \
461+ fetch(url).then( \
462+ function (r) { return r.text().then(function (t) { if (stillCurrent(n)) { swap(t, r.url); } }); }, \
463+ function () { window.location.href = url; } \
464+ ); \
465+ }; \
466+ window.__inRefresh = function () { \
467+ var n = window.__inNav; \
468+ fetch(window.location.href).then( \
469+ function (r) { return r.text().then(function (t) { if (stillCurrent(n)) { swap(t, r.url, false, false, true); } }); }, \
470+ function () {} \
471+ ); \
472+ }; \
473+ window.__inQuery = function (url) { \
474+ var n = navStep(); \
475+ fetch(url).then( \
476+ function (r) { return r.text().then(function (t) { if (stillCurrent(n)) { swap(t, r.url, false, false, true); } }); }, \
477+ function () {} \
478+ ); \
479+ }; \
480+ window.__inPost = function (action, fields) { \
481+ var n = navStep(); \
482+ fetch(action, { method: 'POST', headers: { accept: 'text/html' }, body: new URLSearchParams(fields) }).then( \
483+ function (r) { return r.text().then(function (t) { if (stillCurrent(n)) { swap(t, r.url); } }); }, \
484+ function () {} \
485+ ); \
486+ }; \
487+ window.__inCloseViewer = function () { \
488+ var scrim = document.querySelector('.viewer-scrim'); \
489+ if (!scrim) { return false; } \
490+ var back = scrim.querySelector('.viewer-close').getAttribute('href'); \
491+ navStep(); \
492+ scrim.remove(); \
493+ sweepPanels(); \
494+ history.replaceState(null, '', back); \
495+ var modal = document.querySelector('.modal'); \
496+ if (modal) { modal.focus(); } \
497+ return true; \
498+ }; \
499+ window.__inCloseModal = function () { \
500+ var scrims = document.querySelectorAll('.modal-scrim'); \
501+ if (!scrims.length) { return false; } \
502+ navStep(); \
503+ scrims.forEach(function (el) { el.remove(); }); \
504+ sweepPanels(); \
505+ var u = new URL(window.location.href); \
506+ ['task', 'file', 'confirm', 'new', 'refusal', 'on'].forEach(function (k) { u.searchParams.delete(k); }); \
507+ var q = u.searchParams.toString(); \
508+ history.replaceState(null, '', u.pathname + (q ? '?' + q : '')); \
509+ return true; \
510+ }; \
511+ document.addEventListener('submit', function (e) { \
512+ var form = e.target; \
513+ if (!form || form.hasAttribute('data-hard')) { return; } \
514+ var method = (form.getAttribute('method') || 'get').toLowerCase(); \
515+ if (method !== 'post') { \
516+ e.preventDefault(); \
517+ var q = new URLSearchParams(new FormData(form)).toString(); \
518+ window.__inGo((form.getAttribute('action') || window.location.pathname) + (q ? '?' + q : '')); \
519+ return; \
520+ } \
521+ e.preventDefault(); \
522+ var data = e.submitter ? new FormData(form, e.submitter) : new FormData(form); \
523+ var multipart = (form.getAttribute('enctype') || '').indexOf('multipart') !== -1; \
524+ if (multipart) { \
525+ if (form.__inUploading) { return; } \
526+ form.__inUploading = true; \
527+ var n = navStep(); \
528+ var box = form.querySelector('.file-upload-box'); \
529+ var input = form.querySelector('.file-upload-input'); \
530+ var bar = null, drop = null; \
531+ if (box) { \
532+ bar = document.createElement('div'); \
533+ bar.className = 'upload-progress'; \
534+ var fill = document.createElement('div'); \
535+ fill.className = 'upload-progress-fill'; \
536+ bar.appendChild(fill); \
537+ box.appendChild(window.__inAdded(bar)); \
538+ drop = document.createElement('button'); \
539+ drop.type = 'button'; \
540+ drop.className = 'file-chip-drop upload-progress-drop'; \
541+ var cancelLabel = form.getAttribute('data-cancel-label'); \
542+ if (cancelLabel) { drop.setAttribute('aria-label', cancelLabel); } \
543+ drop.innerHTML = '<svg class=\"glyph\" width=\"13\" height=\"13\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" aria-hidden=\"true\"><path d=\"M4 4l8 8M12 4l-8 8\"></path></svg>'; \
544+ drop.addEventListener('click', function (e) { e.preventDefault(); e.stopPropagation(); x.abort(); }); \
545+ box.appendChild(window.__inAdded(drop)); \
546+ } \
547+ if (input) { input.disabled = true; window.__inOwn(input, [], ['disabled']); } \
548+ var settle = function () { \
549+ form.__inUploading = false; \
550+ if (input) { input.disabled = false; } \
551+ if (bar && bar.parentNode) { bar.parentNode.removeChild(bar); } \
552+ if (drop && drop.parentNode) { drop.parentNode.removeChild(drop); } \
553+ }; \
554+ var x = new XMLHttpRequest(); \
555+ x.open('POST', form.getAttribute('action') || window.location.href); \
556+ x.setRequestHeader('accept', 'text/html'); \
557+ x.upload.onprogress = function (ev) { \
558+ if (!fill) { return; } \
559+ if (!bar.isConnected) { box.appendChild(bar); if (drop) { box.appendChild(drop); } } \
560+ if (ev.lengthComputable && ev.total > 0) { fill.style.width = Math.min(100, Math.round((ev.loaded / ev.total) * 100)) + '%'; } \
561+ }; \
562+ x.onload = function () { \
563+ settle(); \
564+ if (!stillCurrent(n)) { return; } \
565+ swap(x.responseText, x.responseURL || form.getAttribute('action') || window.location.href); \
566+ }; \
567+ x.onerror = function () { settle(); form.submit(); }; \
568+ x.onabort = function () { \
569+ if (input) { input.value = ''; } \
570+ var name = box ? box.querySelector('.file-upload-name') : null; \
571+ var empty = form.getAttribute('data-empty-label'); \
572+ if (name && empty) { name.textContent = empty; } \
573+ settle(); \
574+ }; \
575+ x.send(data); \
576+ return; \
577+ } \
578+ var n = navStep(); \
579+ fetch(form.getAttribute('action'), { method: 'POST', headers: { accept: 'text/html' }, body: new URLSearchParams(data) }).then( \
580+ function (r) { return r.text().then(function (t) { if (stillCurrent(n)) { swap(t, r.url); } }); }, \
581+ function () { form.submit(); } \
582+ ); \
583+ }, true); \
584+ document.addEventListener('change', function (e) { \
585+ var control = e.target; \
586+ if (control.classList && control.classList.contains('file-upload-input')) { \
587+ var label = control.closest('label'); \
588+ var name = label ? label.querySelector('.file-upload-name') : null; \
589+ if (name && control.files && control.files[0]) { \
590+ name.textContent = control.files[0].name + (control.files.length > 1 ? ' +' + (control.files.length - 1) : ''); \
591+ } \
592+ control.form.requestSubmit(); \
593+ return; \
594+ } \
595+ if (control.hasAttribute && control.hasAttribute('data-autosubmit')) { control.form.requestSubmit(); } \
596+ }); \
597+ document.addEventListener('click', function (e) { \
598+ var link = e.target.closest ? e.target.closest('a') : null; \
599+ if (link) { \
600+ if (link.classList.contains('viewer-close') || (link.classList.contains('detail-close') && link.closest('.viewer-scrim'))) { \
601+ e.preventDefault(); \
602+ window.__inCloseViewer(); \
603+ return; \
604+ } \
605+ if (link.getAttribute('href') === '/' && link.closest('.modal-scrim')) { \
606+ e.preventDefault(); \
607+ window.__inCloseModal(); \
608+ return; \
609+ } \
610+ } \
611+ if (e.target.classList && e.target.classList.contains('modal-scrim')) { \
612+ if (e.target.classList.contains('viewer-scrim')) { window.__inCloseViewer(); } \
613+ else { window.__inCloseModal(); } \
614+ } \
615+ }, true); \
616+ window.addEventListener('popstate', function () { window.__inGo(window.location.href); }); \
617+ document.addEventListener('click', function (e) { \
618+ if (e.defaultPrevented || e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) { return; } \
619+ var link = e.target.closest ? e.target.closest('a') : null; \
620+ if (!link || link.hasAttribute('download') || link.hasAttribute('target') || link.hasAttribute('data-hard')) { return; } \
621+ var href = link.getAttribute('href'); \
622+ if (!href || href.charAt(0) !== '/' || href.indexOf('/files/') === 0) { return; } \
623+ e.preventDefault(); \
624+ var n = navStep(); \
625+ fetch(href).then( \
626+ function (r) { return r.text().then(function (t) { if (stillCurrent(n)) { swap(t, r.url, true, true); } }); }, \
627+ function () { window.location.href = href; } \
628+ ); \
629+ }, true); \
630+ document.addEventListener('click', function (e) { \
631+ if (e.target.closest && e.target.closest('.dd-trigger, .dd-panel, button, a, input, select, textarea')) { return; } \
632+ var box = e.target.closest ? e.target.closest('.field-box, .status-form, .member-role') : null; \
633+ if (!box) { return; } \
634+ var trigger = box.querySelector('.dd-trigger'); \
635+ if (trigger) { e.stopImmediatePropagation(); trigger.click(); } \
636+ }); \
637+ if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', wire); } else { wire(); } \
638+ })();";
639+ view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
640+}
641+
642+/// The one document-level capture `keydown` listener for `Escape`, emitted
643+/// once from `root_layout` before every page's own scripts. Owners install
644+/// no listeners of their own; their scripts call
645+/// `window.__inEsc.register(priority, fn)` and on `Escape` the manager
646+/// runs the resolvers highest-priority first — the first to return true
647+/// closes its surface and the manager stops the key. Every consuming press
648+/// gets `preventDefault()`: a real Escape's browser default is stop-loading
649+/// (it once cancelled the navigation these branches used to start; synthetic
650+/// keys carry no default, so only a live keyboard ever showed it).
651+///
652+/// The table below is the whole precedence order, topmost first; a resolver
653+/// whose surface is absent returns false so lower layers get the press.
654+/// Wave-2 pages register their closers here rather than installing their
655+/// own listeners:
656+///
657+/// | prio | closes | registered by |
658+/// |------|--------|---------------|
659+/// | 95 | the open dropdown panel (refocusing its trigger) | wave-2 `dropdown_script` |
660+/// | 90 | the viewer, then the delete confirm | wave-2 file/share pages |
661+/// | 40 | the topbar `.user-menu` (pin+blur) | `layout.rs`'s `escape_script` |
662+/// | 20 | the datepicker popover, if wave 2 adds one | wave-2 page script |
663+/// | 10 | the row context menu | wave-2 drive page script |
664+/// The live channel's browser half: one `EventSource` per tab, and the slow
665+/// tick that keeps clock-driven text honest.
666+///
667+/// Everything here is one script because both halves end in the same act —
668+/// re-fetch the current URL through `__inGo` and let `swap()` do what it
669+/// already does after every form post. There is deliberately no second render
670+/// path: a partial-update mechanism would be a second way for the page to be
671+/// wrong, and the full swap is the one the app exercises constantly.
672+///
673+/// Three things it must not get wrong:
674+///
675+/// The `__inLive` guard is not decoration. `swap()` re-executes every
676+/// swapped-in script, so without it each soft navigation would open another
677+/// `EventSource` and the tab would end up holding one connection per page it
678+/// had ever visited.
679+///
680+/// A refresh must not disturb what somebody is in the middle of. The first
681+/// attempt held the refresh back while a form was dirty, which was wrong twice
682+/// over: one unsubmitted form froze every other surface on the screen, and a
683+/// dropdown could never be used at all while the workspace was busy, because
684+/// each update slammed it shut.
685+///
686+/// The cause of both was the refresh throwing the whole page away. So the live
687+/// path does not: it MORPHS. `swap`'s morphing mode walks the freshly fetched
688+/// document against the live one and touches only what actually differs —
689+/// changed text, changed attributes, added and removed nodes. Everything else
690+/// is the same DOM node it was a moment ago, so an open dropdown stays open, a
691+/// caret stays where it was, a half-typed comment keeps its text, and a scrolled
692+/// panel keeps its position. Not because any of them is special-cased, but
693+/// because nothing touched them.
694+///
695+/// A `<script>` whose text is unchanged is left alone rather than re-created,
696+/// so the live path stops re-running every script on the page; the `__in*`
697+/// guards remain the backstop for the full-swap path, which still re-runs them.
698+///
699+/// ## The client declares what is its own
700+///
701+/// A morph rebuilds the page from HTML that knows nothing about the client.
702+/// Two things it would therefore destroy: nodes the client created, which
703+/// look like strays, and the marks an enhancement leaves on a node the server
704+/// *did* render — `dd-native` hiding a replaced select, `data-wired` on a
705+/// wired player, the position an open context menu was placed at.
706+///
707+/// The first version of this knew their names: `clientMade` tested for
708+/// `.dd-panel`/`.dd-trigger`, and the attribute sweep skipped anything
709+/// starting with `data-dd`. That is a list, and a list is wrong the first
710+/// time somebody adds an enhancement without reading it. It was already
711+/// wrong: `data-dd-done` was on the list and `class` was not, so a save
712+/// unhid every native select underneath its own trigger while `enhanceAll`
713+/// skipped them as already done — one dropdown drawn twice, per field.
714+///
715+/// So the morph knows no names at all. A node says what belongs to the
716+/// client, at the moment the client takes it:
717+///
718+/// - `__inOwn(node, classes, attrs)` — the classes and attributes on this
719+/// server-rendered node are the client's. It adds the classes itself, so
720+/// there is no way to apply one without registering it.
721+/// - `__inAdded(node)` — this whole node is the client's; it is not a
722+/// stray and must not be deleted.
723+///
724+/// Both record on a DOM *property*, which no morph can strip, and both are
725+/// defined here — before any script that could enhance anything runs.
726+/// `syncAttrs` then merges `class` (the server's list plus whatever owned
727+/// classes are still on the node) instead of overwriting it, and skips owned
728+/// attributes both when it copies the server's over and when it sweeps the
729+/// ones the server no longer has — an owned attribute is the client's fact,
730+/// stale server bytes say nothing against it. Nothing in this file mentions
731+/// a dropdown.
732+///
733+/// The other half of the contract is `in:wire`: an enhancement re-derives
734+/// whatever it draws from server data rather than assuming it is still true.
735+/// Ownership keeps the morph from breaking the enhancement; the wire pass is
736+/// how the enhancement follows the server when the data underneath it moves.
737+///
738+/// Morphing is used only for the live refresh. Navigations and form posts keep
739+/// the full replace: they are a different page or a submitted form, where
740+/// carrying the old DOM's state over is wrong rather than kind.
741+///
742+/// The tick exists because some text goes stale with no write behind it: a
743+/// trash countdown or a quota line changes because the clock
744+/// moved, and no announcement will ever fire for that. Rather than re-format
745+/// those in JavaScript — which would mean a second implementation of the
746+/// locale- and timezone-aware formatting the server already does, free to
747+/// disagree with it — the tick re-fetches, and the server stays the only thing
748+/// that decides what a moment reads as. It runs only on pages carrying a
749+/// `data-tick` element, so a page with no clock-driven text is silent.
750+pub async fn live_script(cx: &Cx) -> Result {
751+ const JS: &str = "\
752+ (function () { \
753+ if (window.__inLive) { return; } \
754+ window.__inLive = true; \
755+ var timer = null; \
756+ function refresh() { \
757+ window.__inKeep = true; \
758+ if (window.__inRefresh) { window.__inRefresh(); } \
759+ } \
760+ function schedule() { \
761+ if (timer) { clearTimeout(timer); } \
762+ timer = setTimeout(function () { timer = null; refresh(); }, 200); \
763+ } \
764+ function wanted(topic) { \
765+ if (topic === 'resync') { return true; } \
766+ var path = window.location.pathname; \
767+ if (path.indexOf('/settings') === 0) { return topic === 'admin'; } \
768+ if (path.indexOf('/shared') === 0) { return topic === 'shares'; } \
769+ if (path.indexOf('/trash') === 0) { return topic === 'trash'; } \
770+ return topic === 'library'; \
771+ } \
772+ try { \
773+ var src = new EventSource('/api/live'); \
774+ src.onmessage = function (e) { \
775+ var frame; \
776+ try { frame = JSON.parse(e.data); } catch (err) { return; } \
777+ if (frame && wanted(frame.topic)) { schedule(); } \
778+ }; \
779+ } catch (err) { } \
780+ setInterval(function () { \
781+ if (document.querySelector('[data-tick]')) { refresh(); } \
782+ }, 60000); \
783+ })(); \
784+ ";
785+ view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
786+}
787+
788+pub async fn escape_manager_script(cx: &Cx) -> Result {
789+ use topcoat::view::Unescaped;
790+ const JS: &str = "\
791+ (function () { \
792+ if (window.__inEsc) { return; } \
793+ window.__inEsc = { \
794+ resolvers: [], \
795+ register: function (priority, fn) { \
796+ window.__inEsc.resolvers.push({ priority: priority, fn: fn }); \
797+ window.__inEsc.resolvers.sort(function (a, b) { return b.priority - a.priority; }); \
798+ } \
799+ }; \
800+ document.addEventListener('keydown', function (e) { \
801+ if (e.key !== 'Escape') { return; } \
802+ for (var i = 0; i < window.__inEsc.resolvers.length; i++) { \
803+ if (window.__inEsc.resolvers[i].fn(e)) { \
804+ e.preventDefault(); \
805+ e.stopImmediatePropagation(); \
806+ return; \
807+ } \
808+ } \
809+ }, true); \
810+ })();";
811+ view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
812+}
813+/// Registers the topbar `Escape` resolver on `window.__inEsc`
814+/// (priority 40 — the table is on `escape_manager_script`): the topbar
815+/// `.user-menu` panel — hover-open included, pinned shut by a
816+/// `user-menu-esc` class that a `mouseenter` inside the menu clears.
817+pub async fn escape_script(cx: &Cx) -> Result {
818+ const JS: &str = "\
819+ (function () { \
820+ if (window.__inEscTop) { return; } \
821+ window.__inEscTop = true; \
822+ window.__inEsc.register(40, function () { \
823+ var menu = document.querySelector('.user-menu'); \
824+ if (menu && (menu.matches(':hover') || menu.contains(document.activeElement))) { \
825+ window.__inOwn(menu, ['user-menu-esc'], []); \
826+ var focused = document.activeElement; \
827+ if (focused && focused.closest('.user-menu')) { focused.blur(); } \
828+ return true; \
829+ } \
830+ return false; \
831+ }); \
832+ document.addEventListener('mouseenter', function (e) { \
833+ var menu = e.target.closest ? e.target.closest('.user-menu') : null; \
834+ if (menu) { menu.classList.remove('user-menu-esc'); } \
835+ }, true); \
836+ })();";
837+ view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
838+}
839+
840+/// Every path that matches no page raises a `NotFoundError`, so it renders
841+/// through `root_layout`'s catch below rather than the router's bare default.
842+/// `/` itself is served by `landing` above and never reaches this route.
843+#[page("/{*path}")]
844+async fn missing() -> Result {
845+ Err(not_found().into())
846+}
847+
848+/// `style/main.scss`, compiled by `build.rs` into `assets/main.css`.
849+const STYLE: Asset = asset!("assets/main.css");
850+
851+#[layout("/")]
852+async fn root_layout(cx: &Cx, slot: Result) -> Result {
853+ // v1 has no per-user theme or language: every page renders light, and
854+ // the language comes off the request's Accept-Language header.
855+ let asking = match current_user(cx).await {
856+ Ok(user) => user.is_some(),
857+ Err(_) => false,
858+ };
859+ let lang = crate::i18n::lang(cx);
860+
861+ let content = match slot {
862+ Err(error) if error.downcast_ref::<NotFoundError>().is_some() => view! {
863+ cx =>
864+ (StatusCode::NOT_FOUND)
865+ <main class="scaffold-note">
866+ <p>(t(lang, Key::NothingAtThisAddress))</p>
867+ </main>
868+ },
869+ content => content,
870+ }?;
871+
872+ // The build stamp rides the html element on every render — page load,
873+ // soft navigation and live refresh all answer through this layout, and
874+ // the swap path reads it off the fetched document before it touches the
875+ // page. A tab left open across a deploy keeps the old stylesheet link
876+ // (the morph swaps body children, never the head), so a mismatch is
877+ // the client's cue to hard-reload rather than wear the old css.
878+ let build = STYLE.id().as_u64().to_string();
879+ view! {
880+ <!DOCTYPE html>
881+ <html lang=(lang.code()) data-ui="ledger" data-build=(build)>
882+ <head>
883+ <meta charset="utf-8">
884+ <meta name="viewport" content="width=device-width, initial-scale=1">
885+ <link rel="preconnect" href="https://fonts.googleapis.com">
886+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="">
887+ <link
888+ rel="stylesheet"
889+ href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=Newsreader:ital,wght@0,400;0,600;1,400;1,600&display=swap"
890+ >
891+ <title>"In"</title>
892+ <link rel="icon" href=(FAVICON)>
893+ <link rel="stylesheet" href=(STYLE)>
894+ topcoat::runtime::script()
895+ topcoat::dev::script()
896+ </head>
897+ <body>
898+ (escape_manager_script(cx).await?)
899+ (soft_nav_script(cx).await?)
900+ // Only for a signed-in page: `/api/live` answers 401 to
901+ // everybody else, and an auth screen that opened a stream
902+ // would just reconnect against that refusal forever.
903+ if asking { (live_script(cx).await?) }
904+ (content)
905+ </body>
906+ </html>
907+ }
908+}
crates/in-web/src/lib.rsadded+18 -0
@@ -0,0 +1,18 @@
1+// topcoat's `view!` nests as deeply as the pages do for the same drive, so
2+// the raised limit carries over from day one rather than waiting for the
3+// first overflow.
4+#![recursion_limit = "256"]
5+
6+pub mod drive;
7+pub mod dropdown;
8+pub mod files;
9+pub mod i18n;
10+pub mod layout;
11+pub mod live;
12+pub mod pages;
13+pub mod search;
14+pub mod server;
15+pub mod settings;
16+pub mod share;
17+pub mod trash;
18+pub mod upload;
crates/in-web/src/live.rsadded+159 -0
@@ -0,0 +1,159 @@
1+//! The live channel: one long-lived connection per open tab, carrying the news
2+//! that something changed.
3+//!
4+//! What travels here is a topic and nothing else — never a row, never a name.
5+//! That is the whole security design. A channel that carried data would need
6+//! an ownership check on every message, and the day somebody adds a topic and
7+//! forgets the check is the day one person's drive leaks to another. A topic
8+//! name cannot leak anything: the client is told only *which* surface moved,
9+//! and re-fetches it through the ordinary route, where the ordinary owner
10+//! gate answers. The one thing this file must still get right is not naming
11+//! somebody else's surface to this reader — [`may_hear`] is that, and it is
12+//! the reason the filter runs here rather than in the browser.
13+
14+use std::time::Duration;
15+
16+use in_core::{Change, Topic};
17+use serde::Serialize;
18+use tokio::sync::broadcast::error::RecvError;
19+use tokio::time::Instant;
20+use topcoat::context::{Cx, try_app_context};
21+use topcoat::router::content::sse::{Event, KeepAlive, Sse};
22+use topcoat::router::response::{IntoResponse, Response};
23+use topcoat::router::{StatusCode, route};
24+
25+use crate::server::{app, require_user};
26+
27+/// How long one connection is held before the server ends it and the browser
28+/// opens another. Set from `config/in.toml`; absent — as in the test router
29+/// — the default stands in.
30+#[derive(Clone, Copy, Debug)]
31+pub struct LiveWindow(pub Duration);
32+
33+impl Default for LiveWindow {
34+ fn default() -> Self {
35+ Self(Duration::from_secs(300))
36+ }
37+}
38+
39+/// Tells a live stream that the process is going down.
40+///
41+/// Without this, stopping the server takes as long as its graceful shutdown
42+/// allows — thirty seconds by default. The server stops accepting connections
43+/// and then waits for in-flight requests to finish, and an open live stream is
44+/// an in-flight request that intends to sit there for minutes. Every open tab
45+/// is one. So the streams are told, and they end; the browser reconnects when
46+/// the server comes back, which is what it does after any dropped connection.
47+#[derive(Clone)]
48+pub struct Shutdown(pub tokio::sync::watch::Receiver<bool>);
49+
50+/// Whether this reader may be told that this surface moved.
51+///
52+/// Every topic carries its owner's id, and a reader hears only their own —
53+/// one person's drive never names itself on another person's connection. The
54+/// one exception is the admin surface, which an admin hears about: someone
55+/// who can act on every account may be told every account moved.
56+fn may_hear(topic: &Topic, me: &str, admin: bool) -> bool {
57+ if topic.id() == me {
58+ return true;
59+ }
60+ matches!(topic, Topic::Admin(_)) && admin
61+}
62+
63+/// What one announcement looks like on the wire.
64+#[derive(Serialize)]
65+struct Frame<'a> {
66+ topic: &'a str,
67+ /// The owner the topic is about. Always the reader's own id by the time
68+ /// it is sent — see `may_hear` — so it carries no news, only a handle
69+ /// for the client to route on.
70+ id: &'a str,
71+ seq: u64,
72+}
73+
74+/// A frame the client reads as "you may have missed something; re-read
75+/// everything you are showing".
76+const RESYNC: &str = r#"{"topic":"resync"}"#;
77+
78+#[route(GET "/api/live")]
79+async fn live(cx: &Cx) -> topcoat::Result<Response> {
80+ let Ok(user) = require_user(cx).await else {
81+ return (StatusCode::UNAUTHORIZED, "").into_response(cx);
82+ };
83+ let admin = user.admin;
84+ let me = user.id.clone();
85+ let rx = app(cx).store.subscribe();
86+ let stopping = try_app_context::<Shutdown>(cx).map(|s| s.0.clone());
87+ let deadline = Instant::now()
88+ + try_app_context::<LiveWindow>(cx)
89+ .copied()
90+ .unwrap_or_default()
91+ .0;
92+
93+ let events = futures_util::stream::unfold(
94+ (rx, admin, me, deadline, stopping),
95+ |(mut rx, admin, me, deadline, mut stopping)| async move {
96+ loop {
97+ // Already going down: say nothing and end, so this connection
98+ // is not one the shutdown has to sit and wait out.
99+ if stopping.as_ref().is_some_and(|watch| *watch.borrow()) {
100+ return None;
101+ }
102+ let left = deadline.saturating_duration_since(Instant::now());
103+ if left.is_zero() {
104+ return None;
105+ }
106+ // Three things end the wait: an announcement, the window
107+ // running out, and the server being told to stop. The third is
108+ // watched rather than polled, so Ctrl+C is felt at once.
109+ let heard = tokio::time::timeout(left, async {
110+ match stopping.as_mut() {
111+ Some(watch) => tokio::select! {
112+ _ = watch.changed() => None,
113+ got = rx.recv() => Some(got),
114+ },
115+ None => Some(rx.recv().await),
116+ }
117+ })
118+ .await;
119+ let frame = match heard {
120+ // The window closed, or the server is stopping. Ending the
121+ // stream is the point: the browser reconnects by itself and
122+ // authenticates again.
123+ Err(_) | Ok(None) => return None,
124+ // The store is gone, which means the process is going.
125+ Ok(Some(Err(RecvError::Closed))) => return None,
126+ // This reader fell far enough behind that announcements were
127+ // dropped. Which ones is unknowable, so the client is told to
128+ // re-read everything rather than shown a mix of before and
129+ // after. The stream stays open — a slow moment is not a fault.
130+ Ok(Some(Err(RecvError::Lagged(_)))) => Event::new().data(RESYNC),
131+ Ok(Some(Ok(Change { topic, seq }))) => {
132+ // Not merely unsent: never named. Another owner's
133+ // drive carries no evidence on this connection that
134+ // it exists at all.
135+ if !may_hear(&topic, &me, admin) {
136+ continue;
137+ }
138+ let frame = Frame {
139+ topic: topic.kind(),
140+ id: topic.id(),
141+ seq,
142+ };
143+ match Event::new().json_data(&frame) {
144+ Ok(event) => event,
145+ Err(problem) => {
146+ return Some((Err(problem), (rx, admin, me, deadline, stopping)));
147+ }
148+ }
149+ }
150+ };
151+ return Some((Ok(frame), (rx, admin, me, deadline, stopping)));
152+ }
153+ },
154+ );
155+
156+ Sse::new(events)
157+ .keep_alive(KeepAlive::new())
158+ .into_response(cx)
159+}
crates/in-web/src/main.rsadded+235 -0
@@ -0,0 +1,235 @@
1+use std::sync::Arc;
2+
3+use in_core::Config;
4+use in_core::store::TursoStore;
5+use topcoat::Result;
6+use topcoat::asset::{AssetBundle, RouterBuilderAssetExt};
7+use topcoat::cookie::RouterBuilderCookieExt;
8+use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, route};
9+
10+#[route(GET "/healthz")]
11+async fn healthz() -> Result<&'static str> {
12+ // The deploy asserts this against the commit it pushed, so a stale
13+ // process still holding the port fails the deploy instead of
14+ // answering a green health check.
15+ Ok(concat!("ok ", env!("IN_BUILD_SHA")))
16+}
17+
18+#[tokio::main]
19+async fn main() {
20+ let args: Vec<String> = std::env::args().collect();
21+ if args.get(1).map(|s| s.as_str()) == Some("reconcile") {
22+ let mut dry_run = false;
23+ let mut yes = false;
24+ for arg in &args[2..] {
25+ match arg.as_str() {
26+ "--dry-run" => dry_run = true,
27+ "--yes" => yes = true,
28+ _ => {
29+ eprintln!("in reconcile: unknown option {arg}");
30+ std::process::exit(2);
31+ }
32+ }
33+ }
34+ let config = match Config::load() {
35+ Ok(config) => config,
36+ Err(problem) => {
37+ eprintln!("in: {problem}");
38+ std::process::exit(2);
39+ }
40+ };
41+ if let Err(problem) = in_core::store::reconcile(
42+ &config.database,
43+ Some(config.storage.as_path()),
44+ in_core::store::ReconcileOptions {
45+ dry_run,
46+ yes,
47+ auto: false,
48+ },
49+ )
50+ .await
51+ {
52+ eprintln!("in reconcile: {problem}");
53+ std::process::exit(1);
54+ }
55+ return;
56+ }
57+
58+ // config/in.toml is read here, before anything is opened, and written with
59+ // development defaults if it is not there yet. A broken key stops the
60+ // boot with its name in the message: the failure this prevents is not an
61+ // empty database, it is a second In writing a different file while
62+ // everyone believes they share a drive.
63+ let config = match Config::load() {
64+ Ok(config) => config,
65+ Err(problem) => {
66+ eprintln!("in: {problem}");
67+ std::process::exit(2);
68+ }
69+ };
70+ // Said once, so the answer to "which file are we on" lives in the log.
71+ println!("in database {}", config.database);
72+ println!("in storage {}", config.storage.display());
73+ println!("in listen {}", config.listen);
74+
75+ // The bundle beside the executable is the only stylesheet this process
76+ // can serve, and nothing in topcoat binds it to this binary's
77+ // generation: a bundle left behind by another deploy loads as happily
78+ // as the right one, and the pages then reference a stylesheet whose
79+ // bytes are days old — the mixed generation a browser once caught on
80+ // production. The fingerprint build.rs stamped into this binary is
81+ // checked against the bundle's bytes, and a foreign bundle refuses the
82+ // boot rather than serving under it.
83+ let bundle = AssetBundle::load().unwrap_or_else(|err| {
84+ eprintln!("in: the asset bundle beside the executable failed to load: {err}");
85+ std::process::exit(2);
86+ });
87+ let stylesheet = match in_web::server::stylesheet_guard(&bundle) {
88+ Ok(line) => line,
89+ Err(problem) => {
90+ eprintln!("in: {problem}");
91+ std::process::exit(2);
92+ }
93+ };
94+ println!("in {stylesheet}");
95+
96+ // File bytes, thumbnails and staged chunks live beside the database, not
97+ // in a table. The tree is made before the store opens, because the
98+ // reconcile an old database triggers on the way needs somewhere to put
99+ // what it finds.
100+ ensure_storage_tree(&config.storage);
101+
102+ // One process per database file: Turso is a single-writer engine and a
103+ // second process on the same file loses writes rather than queueing.
104+ //
105+ // `open` applies any unapplied migration before it returns.
106+ let store = TursoStore::open(&config.database, Some(config.storage.as_path()))
107+ .await
108+ .expect("failed to open the database");
109+ let store: Arc<dyn in_core::store::Store> = Arc::new(store);
110+
111+ // Trash purge is policy, not storage hygiene, so it happens here with the
112+ // configured horizon rather than inside `open`: a deployment keeping trash
113+ // longer than any built-in default must never be over-purged by boot.
114+ let cutoff =
115+ time::OffsetDateTime::now_utc() - time::Duration::days(i64::from(config.purge_after_days));
116+ match store.purge_expired(cutoff).await {
117+ Ok(0) => {}
118+ Ok(purged) => println!("in purged {purged} trashed item(s)"),
119+ Err(problem) => eprintln!("in: trash purge failed: {problem}"),
120+ }
121+
122+ // The key sealing the OIDC session cookies, kept beside the database as
123+ // `in.key` — one key per deployment, never in the repository.
124+ let key_path = std::path::Path::new(&config.database)
125+ .parent()
126+ .map(|parent| parent.join("in.key"))
127+ .unwrap_or_else(|| std::path::PathBuf::from("in.key"));
128+ let cookie_key = match in_core::store::secret::load_or_create_key(&key_path) {
129+ Ok(key) => key,
130+ Err(problem) => {
131+ eprintln!("in: could not load {}: {problem}", key_path.display());
132+ std::process::exit(2);
133+ }
134+ };
135+ let oidc = in_client::Config {
136+ issuer: config.oidc.issuer.clone(),
137+ client_id: config.oidc.client_id.clone(),
138+ client_secret: config.oidc.client_secret.clone(),
139+ redirect_uri: config.oidc.redirect_uri.clone(),
140+ cookie_name: "in_session".to_string(),
141+ cookie_key,
142+ };
143+
144+ // Told when the process is stopping, so the live streams end instead of
145+ // being waited out. See `in_web::live::Shutdown`.
146+ let (stop, stopping) = tokio::sync::watch::channel(false);
147+ let live_seconds = config.live_seconds;
148+ let listen = config.listen;
149+
150+ let router = in_client::mount(
151+ Router::builder()
152+ .discover()
153+ .layer(BodyLimit::max(16 * 1024 * 1024).at("/api/upload"))
154+ .layer(BodyLimit::max(64 * 1024 * 1024).at("/files"))
155+ .cookies()
156+ .assets(bundle),
157+ oidc,
158+ )
159+ .app_context(in_web::server::App {
160+ store,
161+ config,
162+ shutdown: in_web::live::Shutdown(stopping),
163+ })
164+ .app_context(in_web::live::LiveWindow(std::time::Duration::from_secs(
165+ live_seconds,
166+ )))
167+ .build();
168+
169+ // `topcoat::start` binds HOST/PORT from the environment; the listen
170+ // address is a config/in.toml decision, so the listener is bound
171+ // explicitly against the same value the boot log just printed.
172+ let listener = tokio::net::TcpListener::bind(listen)
173+ .await
174+ .expect("failed to bind the listen address");
175+ // Not `topcoat::serve`, which installs its own signal handler and gives
176+ // no way to hear it. The handler is taken over so the live streams learn
177+ // about the stop before the graceful shutdown starts counting: without
178+ // that, every open tab holds a stream the shutdown waits its full thirty
179+ // seconds for, and Ctrl+C appears to hang.
180+ topcoat::serve_until(listener, router, async move {
181+ shutdown_signal().await;
182+ let _ = stop.send(true);
183+ })
184+ .await
185+ .expect("server error");
186+}
187+
188+/// Makes the storage tree the store keeps binary files in, if it is not
189+/// there: `<storage>/files`, `<storage>/thumbs` and `<storage>/uploads`,
190+/// private to the user the process runs as. A directory that exists is left
191+/// exactly as it is; one that cannot be made stops the boot — the failure
192+/// this prevents is an upload landing in a tree that is not there, and it is
193+/// better met before anything is opened.
194+fn ensure_storage_tree(storage: &std::path::Path) {
195+ let make = |dir: &std::path::Path| {
196+ if let Err(err) = std::fs::create_dir_all(dir) {
197+ eprintln!("in: could not create {}: {err}", dir.display());
198+ std::process::exit(2);
199+ }
200+ #[cfg(unix)]
201+ {
202+ use std::os::unix::fs::PermissionsExt;
203+ if let Err(err) = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
204+ {
205+ eprintln!("in: could not restrict {}: {err}", dir.display());
206+ std::process::exit(2);
207+ }
208+ }
209+ };
210+ make(storage);
211+ for name in ["files", "thumbs", "uploads"] {
212+ make(&storage.join(name));
213+ }
214+}
215+
216+/// Resolves when the process is asked to stop: Ctrl+C, or `SIGTERM` from a
217+/// service manager.
218+async fn shutdown_signal() {
219+ let interrupt = async {
220+ tokio::signal::ctrl_c()
221+ .await
222+ .expect("failed to install the Ctrl+C handler");
223+ };
224+ let terminate = async {
225+ tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
226+ .expect("failed to install the SIGTERM handler")
227+ .recv()
228+ .await;
229+ };
230+
231+ tokio::select! {
232+ () = interrupt => {}
233+ () = terminate => {}
234+ }
235+}
crates/in-web/src/pages.rsadded+64 -0
@@ -0,0 +1,64 @@
1+//! The front door.
2+//!
3+//! Which screen `/` is depends on the browser: a signed-in one is sent on
4+//! to the drive, a signed-out one is offered the sign-in card. There is no
5+//! setup screen — the first account is provisioned by signing in, and the
6+//! first user ever becomes the admin.
7+//!
8+//! Every page here is server-rendered on every request rather than fetched
9+//! once and patched: there is no hydration, so the gate a browser sees is
10+//! decided fresh each time.
11+
12+use topcoat::Result;
13+use topcoat::context::Cx;
14+use topcoat::router::{HeaderValue, StatusCode, header, page};
15+use topcoat::view::view;
16+
17+use crate::i18n::{Key, Lang, lang, t};
18+use crate::layout::wordmark;
19+use crate::server::current_user;
20+
21+/// The front door: the drive for a signed-in browser, the sign-in card for
22+/// everybody else.
23+#[page("/")]
24+async fn landing(cx: &Cx) -> Result {
25+ match current_user(cx).await {
26+ Ok(Some(_)) => {
27+ let location = (header::LOCATION, HeaderValue::from_static("/drive"));
28+ view! {
29+ cx =>
30+ (StatusCode::SEE_OTHER)
31+ (location)
32+ }
33+ }
34+ Ok(None) => sign_in_card(cx).await,
35+ Err(_) => view! {
36+ cx =>
37+ <main class="scaffold-note">
38+ <p>(t(Lang::En, Key::SomethingWentWrong))</p>
39+ </main>
40+ },
41+ }
42+}
43+
44+/// The sign-in card for a browser with nobody in it: the wordmark and one
45+/// link, which starts the OIDC round-trip at `/auth/login`.
46+async fn sign_in_card(cx: &Cx) -> Result {
47+ let language = lang(cx);
48+ view! {
49+ cx =>
50+ <main class="auth-stage">
51+ <div class="auth-column">
52+ <div class="auth-card">
53+ <div class="auth-head">
54+ <div class="auth-title">(wordmark(cx).await?)</div>
55+ <div class="auth-sub">(t(language, Key::WelcomeBlurb))</div>
56+ </div>
57+ <a class="auth-submit" href="/auth/login">
58+ <span class="auth-submit-text">(t(language, Key::SignIn))</span>
59+ </a>
60+ </div>
61+ </div>
62+ </main>
63+ }
64+}
crates/in-web/src/search.rsadded+105 -0
@@ -0,0 +1,105 @@
1+//! Name search over the reader's own drive.
2+//!
3+//! `GET /search?q=` matches the query against file and folder names with an
4+//! owner-scoped `LIKE`, non-trashed rows only. Results link straight to the
5+//! file view or the containing folder. An empty query renders the empty
6+//! prompt, not the whole drive.
7+
8+use topcoat::Result;
9+use topcoat::context::Cx;
10+use topcoat::router::page;
11+use topcoat::router::request::uri;
12+use topcoat::view::view;
13+
14+use crate::i18n::{Key, lang, t};
15+use crate::layout::{NavPage, topbar};
16+use crate::server::{app, require_user};
17+
18+/// How many hits each list carries at most.
19+const LIMIT: u32 = 50;
20+
21+/// The search box's text, trimmed. Anything else on the query is ignored.
22+fn searched(raw: Option<&str>) -> Option<String> {
23+ raw.map(str::trim)
24+ .filter(|query| !query.is_empty())
25+ .map(str::to_string)
26+}
27+
28+/// The reader's own live files and folders wearing the query in their name.
29+/// Never another owner's, never trashed, never everything on an empty box.
30+#[page("/search")]
31+async fn search(cx: &Cx) -> Result {
32+ let user = match require_user(cx).await {
33+ Ok(user) => user,
34+ Err(refusal) => {
35+ let language = lang(cx);
36+ return view! {
37+ cx =>
38+ <main class="scaffold-note">
39+ <p>(refusal.message_in(language))</p>
40+ <p><a href="/">(t(language, Key::BackToDrive))</a></p>
41+ </main>
42+ };
43+ }
44+ };
45+ let language = lang(cx);
46+ let asked = searched(query_value(uri(cx).query().unwrap_or(""), "q").as_deref());
47+ let hits = match asked.as_deref() {
48+ Some(query) => Some(app(cx).store.search(&user.id, query, LIMIT).await?),
49+ None => None,
50+ };
51+ let box_text = asked.clone().unwrap_or_default();
52+ view! {
53+ cx =>
54+ <main class="settings-shell">
55+ (topbar(cx, NavPage::Search, &user, language).await?)
56+ <h1 class="settings-title">(t(language, Key::SearchResults))</h1>
57+ <form class="field-box-search" method="get" action="/search">
58+ <input
59+ class="field-input"
60+ type="search"
61+ name="q"
62+ value=(box_text)
63+ placeholder=(t(language, Key::SearchPlaceholder))
64+ aria-label=(t(language, Key::SearchPlaceholder))
65+ >
66+ </form>
67+ if let Some(hits) = hits {
68+ if hits.folders.is_empty() && hits.files.is_empty() {
69+ <p class="field-note">(t(language, Key::NoResults))</p>
70+ }
71+ if !hits.folders.is_empty() {
72+ <section class="panel">
73+ <h2 class="panel-title">(t(language, Key::FoldersHeading))</h2>
74+ <div class="panel-body">
75+ for folder in &hits.folders {
76+ <p><a href=(format!("/drive?folder={}", folder.id))>(folder.name.clone())</a></p>
77+ }
78+ </div>
79+ </section>
80+ }
81+ if !hits.files.is_empty() {
82+ <section class="panel">
83+ <h2 class="panel-title">(t(language, Key::FilesHeading))</h2>
84+ <div class="panel-body">
85+ for file in &hits.files {
86+ <p><a href=(format!("/file/{}", file.id))>(file.name.clone())</a></p>
87+ }
88+ </div>
89+ </section>
90+ }
91+ } else {
92+ <p class="field-note">(t(language, Key::TypeToSearch))</p>
93+ }
94+ </main>
95+ }
96+}
97+
98+/// The value of one query pair, if present. A hand-edited query names
99+/// nothing rather than failing the page.
100+fn query_value(query: &str, key: &str) -> Option<String> {
101+ query.split('&').find_map(|pair| {
102+ let (name, value) = pair.split_once('=')?;
103+ (name == key).then(|| value.to_string())
104+ })
105+}
crates/in-web/src/server.rsadded+529 -0
@@ -0,0 +1,529 @@
1+//! Server-side plumbing: the application context, the person behind the
2+//! current request, and the role guards.
3+//!
4+//! Every guard here is the real one. The UI hides what a role may not do, but
5+//! the answer that matters is the one given in this module, on the server.
6+//!
7+//! There are no local passwords in v1 — im holds the central session over
8+//! OIDC and `in-client` (vendored from `im-client`) holds this app's side of
9+//! it. This module's `current_user` maps im's claims onto the local user row,
10+//! provisioning it on first sight.
11+
12+use std::sync::Arc;
13+
14+use in_core::Config;
15+use in_core::store::{Store, StoreError, User};
16+use serde::{Deserialize, Serialize};
17+use sha2::Digest;
18+use topcoat::asset::AssetBundle;
19+use topcoat::context::{Cx, app_context, memoize};
20+use topcoat::router::request::headers;
21+use topcoat::router::{Body, HeaderValue, Next, StatusCode, header, response::Response, to_bytes};
22+
23+/// The whole application context, put into the router by `main.rs`. One
24+/// struct rather than three separate contexts so a route needing two of them
25+/// reads both off the same value. The OIDC client state lives in the router
26+/// separately — `in_client::mount` puts it there — because its login routes
27+/// read it without going through this struct.
28+#[derive(Clone)]
29+pub struct App {
30+ /// The drive store. `Arc` over the trait so tests can hand a router a
31+ /// rehearsal double without touching Turso.
32+ pub store: Arc<dyn Store>,
33+ /// The loaded `config/in.toml` — every tunable wave 2 reads.
34+ pub config: Config,
35+ /// Told when the process is stopping, so the live streams end instead of
36+ /// being waited out.
37+ pub shutdown: crate::live::Shutdown,
38+}
39+
40+/// The application context this request runs under.
41+pub fn app(cx: &Cx) -> App {
42+ app_context::<App>(cx).clone()
43+}
44+
45+/// A stable-enough label for the client, for rate limiting. A proxy header is
46+/// only trusted because In is meant to sit behind one; the address bucket is
47+/// the limit that actually protects the login round-trip either way.
48+///
49+/// topcoat 0.6.2 exposes no peer address; x-forwarded-for or nothing.
50+pub fn client_label(cx: &Cx) -> String {
51+ let Some(forwarded) = headers(cx).get("x-forwarded-for") else {
52+ return "unknown".to_string();
53+ };
54+ let Ok(raw) = forwarded.to_str() else {
55+ return "unknown".to_string();
56+ };
57+ match raw.split(',').next() {
58+ Some(first) if !first.trim().is_empty() => first.trim().to_string(),
59+ _ => "unknown".to_string(),
60+ }
61+}
62+
63+/// The stylesheet this binary serves must be the one compiled into it.
64+///
65+/// `asset!` embeds an asset's declaration — its id and source path — into
66+/// the binary, but the served bytes live in the bundle directory beside the
67+/// executable, and topcoat loads whatever manifest it finds there. A bundle
68+/// left behind by another deploy sits beside a newer binary without a word
69+/// of complaint, and the pages then reference a stylesheet whose bytes are
70+/// from another generation — the mixed generation a browser once caught on
71+/// production. `build.rs` stamps the compiled stylesheet's SHA-256 into the
72+/// binary; this hashes the bundle's bytes against it, so a foreign bundle
73+/// refuses the boot instead of serving under it.
74+///
75+/// Returns the startup log line naming the served fingerprint, or the
76+/// reason the boot must not proceed.
77+pub fn stylesheet_guard(bundle: &AssetBundle) -> Result<String, String> {
78+ let expected = env!("IN_STYLE_FINGERPRINT");
79+ let stylesheet = bundle
80+ .catalog()
81+ .assets()
82+ .find(|asset| {
83+ let name = asset.name();
84+ name.starts_with("main-") && name.ends_with(".css")
85+ })
86+ .ok_or_else(|| {
87+ format!(
88+ "the asset bundle at {} carries no stylesheet",
89+ bundle.dir().display()
90+ )
91+ })?;
92+ let bytes = std::fs::read(bundle.dir().join(stylesheet.name())).map_err(|err| {
93+ format!(
94+ "the bundled stylesheet {} could not be read: {err}",
95+ stylesheet.name()
96+ )
97+ })?;
98+ let actual = format!("sha256:{:x}", sha2::Sha256::digest(&bytes));
99+ if actual != expected {
100+ return Err(format!(
101+ "the asset bundle at {} is from another build: stylesheet {} is {actual} but this binary was compiled against {expected}; run `topcoat asset bundle` and redeploy",
102+ bundle.dir().display(),
103+ stylesheet.name()
104+ ));
105+ }
106+ Ok(format!(
107+ "assets stylesheet {} ({actual})",
108+ stylesheet.name()
109+ ))
110+}
111+
112+/// The person behind this request, or nobody, or the store failing to say.
113+///
114+/// im is asked on every request — the cookie holds an opaque session token,
115+/// introspected per call — so an admin revoking the person in im signs them
116+/// out here at once. The first sight of a `sub` inserts the local row (and
117+/// the first user ever becomes the admin); every later sight refreshes the
118+/// address and name and stamps the last-seen time.
119+///
120+/// A store error is not "nobody" — a busy database mid-drag is a fact about
121+/// the database, not about whether this browser is signed in, and a caller
122+/// that folded the two together would send a signed-in person to a sign-in
123+/// screen because a write elsewhere held a lock for a moment.
124+///
125+/// A disabled account reads as nobody: the cookie is im's business and is
126+/// left untouched, but every guard below refuses as if signed out.
127+#[memoize(as_ref)]
128+pub async fn current_user(cx: &Cx) -> Result<Option<User>, StoreError> {
129+ let Some(claims) = in_client::current_user(cx).await else {
130+ return Ok(None);
131+ };
132+ let app = app(cx);
133+ let user = app
134+ .store
135+ .provision_user(
136+ &claims.sub,
137+ &claims.email,
138+ &claims.name,
139+ app.config.default_quota_bytes,
140+ )
141+ .await?;
142+ if user.disabled {
143+ return Ok(None);
144+ }
145+ Ok(Some(user))
146+}
147+
148+/// The person behind this request, or a refusal the caller can return as-is.
149+///
150+/// A store error becomes `Refusal::Unavailable` rather than `SignInFirst`,
151+/// which would tell a signed-in person to sign in again over what was only
152+/// a database hiccup.
153+pub async fn require_user(cx: &Cx) -> Result<User, Refusal> {
154+ match current_user(cx).await {
155+ Ok(Some(user)) => Ok(user.clone()),
156+ Ok(None) => Err(Refusal::SignInFirst),
157+ Err(_) => Err(Refusal::Unavailable),
158+ }
159+}
160+
161+/// The admin behind this request. Anyone else is refused *here*, not
162+/// merely hidden from in the UI.
163+pub async fn require_admin(cx: &Cx) -> Result<User, Refusal> {
164+ let user = require_user(cx).await?;
165+ if user.admin {
166+ Ok(user)
167+ } else {
168+ Err(Refusal::Forbidden)
169+ }
170+}
171+
172+impl From<StoreError> for Refusal {
173+ fn from(_: StoreError) -> Refusal {
174+ Refusal::Unavailable
175+ }
176+}
177+
178+/// Everything a refused call is allowed to say.
179+///
180+/// The codes are the contract's: a browser without script only ever sees
181+/// them through the address bar, so each one has a short word form
182+/// ([`Refusal::code`]) beside its sentence.
183+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
184+pub enum Refusal {
185+ /// No session, a revoked one, or a disabled account — deliberately one
186+ /// answer for all three.
187+ SignInFirst,
188+ /// Signed in, but not an admin (or not the owner). Cross-owner reads are
189+ /// answered with [`Refusal::NotFound`] instead — a 404, never a 403 —
190+ /// so this is only for surfaces whose existence is no secret.
191+ Forbidden,
192+ /// No such file or folder — or none this account may see. Deliberately
193+ /// one answer for both.
194+ NotFound,
195+ /// The bytes would not fit the remaining quota.
196+ QuotaExceeded,
197+ /// A sibling already carries that name.
198+ NameTaken,
199+ /// A folder with children stays until it is emptied.
200+ FolderNotEmpty,
201+ /// The target belongs to somebody else. Answered like [`Refusal::NotFound`]
202+ /// on the wire; a distinct code so the carry still names what happened.
203+ CrossOwner,
204+ /// A share link spent, expired, revoked, or never real.
205+ ShareRevoked,
206+ /// The upload session expired or was aborted before the finish landed.
207+ UploadExpired,
208+ /// A chunk arrived out of order, twice, or the wrong size.
209+ BadChunk,
210+ /// A restore was asked for while an ancestor folder is still trashed —
211+ /// restore the ancestor first.
212+ AncestorTrashed,
213+ /// The store failed to say. Never a sign-in prompt — see `require_user`.
214+ Unavailable,
215+}
216+
217+impl Refusal {
218+ /// The refusal in words.
219+ pub fn message(&self) -> String {
220+ match self {
221+ Refusal::SignInFirst => "Sign in first.".to_string(),
222+ Refusal::Forbidden => "Not permitted.".to_string(),
223+ Refusal::NotFound => "No such file or folder.".to_string(),
224+ Refusal::QuotaExceeded => "Over quota.".to_string(),
225+ Refusal::NameTaken => "That name is already taken here.".to_string(),
226+ Refusal::FolderNotEmpty => "That folder still has files in it.".to_string(),
227+ // Same sentence as NotFound: a cross-owner probe must not learn
228+ // the target exists.
229+ Refusal::CrossOwner => "No such file or folder.".to_string(),
230+ Refusal::ShareRevoked => "This link no longer works.".to_string(),
231+ Refusal::UploadExpired => "This upload expired — start it again.".to_string(),
232+ Refusal::BadChunk => "That piece arrived damaged — send it again.".to_string(),
233+ Refusal::AncestorTrashed => "Restore the folder it is in first.".to_string(),
234+ Refusal::Unavailable => "Something went wrong.".to_string(),
235+ }
236+ }
237+
238+ /// `message()`, in the reader's language.
239+ pub fn message_in(&self, lang: crate::i18n::Lang) -> String {
240+ use crate::i18n::Lang::Tr;
241+ if lang != Tr {
242+ return self.message();
243+ }
244+ match self {
245+ Refusal::SignInFirst => "Önce oturum aç.".to_string(),
246+ Refusal::Forbidden => "İzin verilmiyor.".to_string(),
247+ Refusal::NotFound => "Böyle bir dosya ya da klasör yok.".to_string(),
248+ Refusal::QuotaExceeded => "Kota doldu.".to_string(),
249+ Refusal::NameTaken => "Bu ad burada zaten var.".to_string(),
250+ Refusal::FolderNotEmpty => "Bu klasörde hâlâ dosyalar var.".to_string(),
251+ Refusal::CrossOwner => "Böyle bir dosya ya da klasör yok.".to_string(),
252+ Refusal::ShareRevoked => "Bu bağlantı artık çalışmıyor.".to_string(),
253+ Refusal::UploadExpired => "Bu yüklemenin süresi doldu — yeniden başlat.".to_string(),
254+ Refusal::BadChunk => "Bu parça bozuk geldi — yeniden gönder.".to_string(),
255+ Refusal::AncestorTrashed => "Önce içinde olduğu klasörü geri yükle.".to_string(),
256+ Refusal::Unavailable => "Bir şeyler ters gitti.".to_string(),
257+ }
258+ }
259+
260+ /// The refusal a `code` names, or nothing. Nothing for an unknown word: the
261+ /// query is whatever the address bar holds, so a code that is not one of
262+ /// ours says nothing at all rather than something invented.
263+ pub fn from_code(code: &str) -> Option<Refusal> {
264+ Some(match code {
265+ "sign-in-first" => Refusal::SignInFirst,
266+ "forbidden" => Refusal::Forbidden,
267+ "not-found" => Refusal::NotFound,
268+ "quota-exceeded" => Refusal::QuotaExceeded,
269+ "name-taken" => Refusal::NameTaken,
270+ "folder-not-empty" => Refusal::FolderNotEmpty,
271+ "cross-owner" => Refusal::CrossOwner,
272+ "share-revoked" => Refusal::ShareRevoked,
273+ "upload-expired" => Refusal::UploadExpired,
274+ "bad-chunk" => Refusal::BadChunk,
275+ "ancestor-trashed" => Refusal::AncestorTrashed,
276+ "unavailable" => Refusal::Unavailable,
277+ _ => return None,
278+ })
279+ }
280+
281+ /// The refusal as a short word, for the address bar.
282+ ///
283+ /// A browser without script never sees a call's return value: it posts the
284+ /// form, follows the redirect, and the page it lands on has to be told what
285+ /// happened. That telling goes through the query, so every refusal needs a
286+ /// name that survives a round trip through a URL.
287+ pub fn code(&self) -> &'static str {
288+ match self {
289+ Refusal::SignInFirst => "sign-in-first",
290+ Refusal::Forbidden => "forbidden",
291+ Refusal::NotFound => "not-found",
292+ Refusal::QuotaExceeded => "quota-exceeded",
293+ Refusal::NameTaken => "name-taken",
294+ Refusal::FolderNotEmpty => "folder-not-empty",
295+ Refusal::CrossOwner => "cross-owner",
296+ Refusal::ShareRevoked => "share-revoked",
297+ Refusal::UploadExpired => "upload-expired",
298+ Refusal::BadChunk => "bad-chunk",
299+ Refusal::AncestorTrashed => "ancestor-trashed",
300+ Refusal::Unavailable => "unavailable",
301+ }
302+ }
303+}
304+
305+/// Which call a carried refusal belongs to. Two forms on one page must not both
306+/// claim the same sentence, so the redirect names the call and this is the name:
307+/// the last piece of the server function's path, with anything that is not a
308+/// plain word dropped so it can only ever be compared, never rendered.
309+pub fn call_id(path: &str) -> String {
310+ path.rsplit('/')
311+ .next()
312+ .unwrap_or(path)
313+ .chars()
314+ .filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
315+ .collect()
316+}
317+
318+/// What a call refused with, however the browser without script carried it
319+/// back — read straight off the query, since there is no client-side action
320+/// value to check first the way a hydrated page in the old UI had.
321+///
322+/// Every topcoat page is rendered server-side on every request, so there is
323+/// only ever the query to read.
324+pub fn refusal_of(cx: &Cx, call: &str) -> Option<Refusal> {
325+ let query = topcoat::router::request::uri(cx).query()?;
326+ let mut code = None;
327+ let mut on = None;
328+ for pair in query.split('&') {
329+ if let Some((key, value)) = pair.split_once('=') {
330+ match key {
331+ "refusal" => code = Some(value),
332+ "on" => on = Some(value),
333+ _ => {}
334+ }
335+ }
336+ }
337+ if on? != call {
338+ return None;
339+ }
340+ Refusal::from_code(code?)
341+}
342+
343+/// The page a form was posted from: the `Referer`, with the answer any
344+/// earlier post left on its query dropped, or `nowhere` when no `Referer`
345+/// came with the request.
346+///
347+/// The feedback pairs — `refusal=`, `on=`, `why=`, `saved=` — are how a page
348+/// renders what the last post did. Sending the browser back with them still
349+/// on the query re-renders that old answer under the new post's own: a change
350+/// that succeeded right after one that was refused announces the refusal
351+/// again, and reads as having failed. The answer this redirect carries — the
352+/// pairs it was built with, or the body [`carry_refusal_on_redirect`] copies
353+/// onto the query — is the one that shows; an earlier one never survives the
354+/// trip.
355+pub fn back_to(cx: &Cx, nowhere: &str) -> String {
356+ let referer = headers(cx)
357+ .get(header::REFERER)
358+ .and_then(|value| value.to_str().ok())
359+ .unwrap_or(nowhere);
360+ let (path, query) = referer.split_once('?').unwrap_or((referer, ""));
361+ let pairs: Vec<&str> = query
362+ .split('&')
363+ .filter(|pair| {
364+ !pair.is_empty()
365+ && !["refusal", "on", "why", "saved"].iter().any(|key| {
366+ pair.strip_prefix(*key)
367+ .is_some_and(|rest| rest.starts_with('='))
368+ })
369+ })
370+ .collect();
371+ if pairs.is_empty() {
372+ return path.to_string();
373+ }
374+ format!("{path}?{}", pairs.join("&"))
375+}
376+
377+/// Puts a refusal on the redirect a browser without script follows.
378+///
379+/// A hydrated page reads the call's return value straight off the action. A
380+/// browser without script has no such thing: it posts the form, the server
381+/// function handler answers with a redirect back to the page it came from, and
382+/// the value — the whole refusal — sits in a body nobody will ever look at.
383+/// The click then looks like nothing happening, which is the worst answer
384+/// In can give.
385+///
386+/// So the refusal is copied onto the `Location`, as `?refusal=<code>&on=<call>`,
387+/// and the page renders it from the query. This is one place rather than a
388+/// dozen because the shape is the same for every refusing call, present
389+/// and future: nothing here knows what any of them do.
390+///
391+/// Requests carrying script are untouched — they are answered with the value
392+/// itself and never see a redirect.
393+///
394+/// Ported from axum's `middleware::from_fn` onto a topcoat `#[layer]`. topcoat's
395+/// Post/Redirect/Get helper (`error::see_other`) answers with `303 See Other`,
396+/// not the `302 Found` axum's server-function redirect used, so the status this
397+/// checks for is `SEE_OTHER` — the guard's three conditions are otherwise
398+/// unchanged.
399+#[topcoat::router::layer("/api")]
400+async fn carry_refusal_on_redirect(
401+ cx: &Cx,
402+ body: Body,
403+ next: Next<'_>,
404+) -> topcoat::Result<Response> {
405+ // A form post from a browser asks for a page back. A server-function call
406+ // from the hydrated bundle does not.
407+ let wants_page = headers(cx)
408+ .get(header::ACCEPT)
409+ .and_then(|value| value.to_str().ok())
410+ .is_some_and(|value| value.contains("text/html"));
411+ let called = call_id(topcoat::router::request::uri(cx).path());
412+ let has_referer = headers(cx).contains_key(header::REFERER);
413+ let response = next.run(cx, body).await?;
414+ if !wants_page || !has_referer || response.status() != StatusCode::SEE_OTHER {
415+ return Ok(response);
416+ }
417+
418+ let (mut parts, body) = response.into_parts();
419+ // The body of one of these redirects is a serialised `Option<Refusal>` and
420+ // nothing else; the cap is there so a response that is something else
421+ // entirely cannot be read into memory whole. A body that fails to parse —
422+ // an empty one included, the shape a route with nothing to say back sends
423+ // — is read as "no refusal", never as "leave the Location alone": the
424+ // Referer sanitization below has to run on every redirect this layer
425+ // sees, not only the ones that happen to carry a refusal.
426+ let Ok(bytes) = to_bytes(body, 64 * 1024).await else {
427+ return Ok(Response::from_parts(parts, Body::empty()));
428+ };
429+ let refusal = serde_json::from_slice::<Option<Refusal>>(&bytes)
430+ .ok()
431+ .flatten();
432+ if let Some(location) = parts
433+ .headers
434+ .get(header::LOCATION)
435+ .and_then(|v| v.to_str().ok())
436+ {
437+ let rewritten = match refusal {
438+ Some(refusal) => carrying(location, refusal.code(), &called),
439+ None => Some(same_origin(location).to_string()),
440+ };
441+ if let Some(carried) = rewritten
442+ && let Ok(value) = HeaderValue::from_str(&carried)
443+ {
444+ parts.headers.insert(header::LOCATION, value);
445+ }
446+ }
447+ Ok(Response::from_parts(parts, Body::from(bytes)))
448+}
449+
450+/// `location` with the refusal in its query.
451+///
452+/// The redirect goes back to the page the form was posted from, and that page
453+/// may already carry a query — `?folder=<id>` is how a browser without script
454+/// opens a folder at all — so the two pairs are merged in, and the pair from
455+/// any earlier refusal is dropped rather than stacked on top of.
456+fn carrying(location: &str, code: &str, called: &str) -> Option<String> {
457+ if called.is_empty() {
458+ return None;
459+ }
460+ // The Location we are rewriting came from the form post's Referer, and on a
461+ // cross-origin post the Referer is whatever the other site is. Sending the
462+ // browser back there would make In an open redirect, so the address is
463+ // rebuilt from its path and query alone and anything that is not a plain
464+ // absolute path is answered with the drive.
465+ let here = same_origin(location);
466+ let (path, query) = match here.split_once('?') {
467+ Some((path, query)) => (path, query),
468+ None => (here, ""),
469+ };
470+ let mut pairs: Vec<String> = query
471+ .split('&')
472+ .filter(|pair| {
473+ !pair.is_empty() && !pair.starts_with("refusal=") && !pair.starts_with("on=")
474+ })
475+ .map(str::to_string)
476+ .collect();
477+ pairs.push(format!("refusal={code}&on={called}"));
478+ Some(format!("{path}?{}", pairs.join("&")))
479+}
480+
481+/// The path and query of `location`, with scheme and authority dropped. A
482+/// protocol-relative address (`//elsewhere.example/`) is another host wearing a
483+/// path's clothes, and a browser reads a backslash there as a slash, so both
484+/// are answered with the drive rather than trusted.
485+fn same_origin(location: &str) -> &str {
486+ let rest = match location.split_once("://") {
487+ Some((_scheme, rest)) => match rest.find(['/', '?']) {
488+ Some(at) => &rest[at..],
489+ None => "/",
490+ },
491+ None => location,
492+ };
493+ let mut characters = rest.chars();
494+ match (characters.next(), characters.next()) {
495+ (Some('/'), Some('/' | '\\')) => "/",
496+ (Some('/'), _) => rest,
497+ _ => "/",
498+ }
499+}
500+
501+/// The cache directives a response cannot choose for itself.
502+///
503+/// HTML is revalidated on every load: a page the browser kept from before a
504+/// deploy is the old app answering under the new one's address, which is how a
505+/// fixed bug once came back after shipping. So every response whose body is a
506+/// document gets `no-cache`. Responses that already carry a directive keep it —
507+/// topcoat stamps the fingerprinted assets under `/_topcoat/assets` with a year
508+/// of `immutable` and the live stream with `no-cache`, and the file and
509+/// thumbnail handlers stamp their own — and everything else (redirects, JSON
510+/// answers) ships none, the idiom they already ride on: no directive, nothing
511+/// cached. One layer at `/`, because the decision is about what the bytes are,
512+/// not which route built them.
513+#[topcoat::router::layer("/")]
514+async fn cache_directives(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result<Response> {
515+ let response = next.run(cx, body).await?;
516+ let (mut parts, body) = response.into_parts();
517+ let is_html = parts
518+ .headers
519+ .get(header::CONTENT_TYPE)
520+ .and_then(|value| value.to_str().ok())
521+ .is_some_and(|value| value.starts_with("text/html"));
522+ if !is_html || parts.headers.contains_key(header::CACHE_CONTROL) {
523+ return Ok(Response::from_parts(parts, body));
524+ }
525+ parts
526+ .headers
527+ .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
528+ Ok(Response::from_parts(parts, body))
529+}
crates/in-web/src/settings.rsadded+268 -0
@@ -0,0 +1,268 @@
1+//! Settings: the reader's profile and quota, plus the admin's user panel.
2+//!
3+//! `GET /settings` shows the profile im vouches for (name, address) with the
4+//! quota usage bar beside it, and the reader's own live share links with
5+//! their revoke buttons — including the copy-once banner after a creation
6+//! (`?created=<token>` on the query, rendered once and never stored).
7+//! Admins additionally see every account with its quota and disabled flag.
8+//! `POST /api/settings/quota|disable` are admin-only: the first sets a
9+//! user's byte quota, the second disables or re-enables them (a disabled
10+//! account reads as signed-out everywhere, the im session untouched, and
11+//! disabling yourself is refused).
12+
13+use in_core::store::User;
14+use serde::Deserialize;
15+use topcoat::Result;
16+use topcoat::context::Cx;
17+use topcoat::router::content::Form;
18+use topcoat::router::request::uri;
19+use topcoat::router::{HeaderName, StatusCode, header, page, route};
20+use topcoat::view::view;
21+
22+use crate::i18n::{Key, lang, t};
23+use crate::layout::{NavPage, topbar};
24+use crate::server::{Refusal, app, back_to, require_admin, require_user};
25+use crate::share::{refusal_banner, refusal_of};
26+
27+/// Bytes in human units: `512 B`, `1.5 KiB`, `2.0 GiB`. One decimal past
28+/// bytes so a quota line reads at a glance.
29+pub fn human_bytes(bytes: u64) -> String {
30+ const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
31+ let mut value = bytes as f64;
32+ let mut unit = 0;
33+ while value >= 1024.0 && unit + 1 < UNITS.len() {
34+ value /= 1024.0;
35+ unit += 1;
36+ }
37+ if unit == 0 {
38+ format!("{bytes} {}", UNITS[unit])
39+ } else {
40+ format!("{value:.1} {}", UNITS[unit])
41+ }
42+}
43+
44+/// The share of the quota already held, for the usage bar's width.
45+fn quota_percent(user: &User) -> u8 {
46+ if user.quota_bytes == 0 {
47+ return 100;
48+ }
49+ (user.used_bytes.saturating_mul(100) / user.quota_bytes).min(100) as u8
50+}
51+
52+type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>;
53+
54+/// Back to settings, the refusal (if any) on the query.
55+fn redirect_back(cx: &Cx, call: &str, refusal: Option<Refusal>) -> Redirect {
56+ let back = back_to(cx, "/settings");
57+ let separator = if back.contains('?') { '&' } else { '?' };
58+ let location = match refusal {
59+ Some(refusal) => format!("{back}{separator}refusal={}&on={call}", refusal.code()),
60+ None => back,
61+ };
62+ Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)]))
63+}
64+
65+#[derive(Deserialize)]
66+struct QuotaForm {
67+ user_id: String,
68+ quota_bytes: u64,
69+}
70+
71+/// Sets one account's byte ceiling. The bytes it already holds are untouched —
72+/// a quota lowered under current usage refuses new uploads until the person
73+/// frees space, rather than deleting anything.
74+#[route(POST "/api/settings/quota")]
75+async fn set_quota(cx: &Cx, Form(input): Form<QuotaForm>) -> Redirect {
76+ if let Err(refusal) = require_admin(cx).await {
77+ return redirect_back(cx, "quota", Some(refusal));
78+ }
79+ match app(cx).store.set_user_quota(&input.user_id, input.quota_bytes).await {
80+ Ok(()) => redirect_back(cx, "quota", None),
81+ Err(error) => redirect_back(cx, "quota", Some(refusal_of(error))),
82+ }
83+}
84+
85+#[derive(Deserialize)]
86+struct DisableForm {
87+ user_id: String,
88+ #[serde(default)]
89+ disabled: Option<String>,
90+}
91+
92+/// Disables or re-enables one account. Disabling yourself is refused — the
93+/// install must never be left with no way back in through its only admin.
94+#[route(POST "/api/settings/disable")]
95+async fn set_disabled(cx: &Cx, Form(input): Form<DisableForm>) -> Redirect {
96+ let admin = match require_admin(cx).await {
97+ Ok(admin) => admin,
98+ Err(refusal) => return redirect_back(cx, "disable", Some(refusal)),
99+ };
100+ if input.user_id == admin.id {
101+ return redirect_back(cx, "disable", Some(Refusal::Forbidden));
102+ }
103+ let disabled = match input.disabled.as_deref() {
104+ None => true,
105+ Some(value) => !matches!(
106+ value.trim().to_lowercase().as_str(),
107+ "" | "0" | "false" | "no" | "off"
108+ ),
109+ };
110+ match app(cx)
111+ .store
112+ .set_user_disabled(&input.user_id, disabled)
113+ .await
114+ {
115+ Ok(()) => redirect_back(cx, "disable", None),
116+ Err(error) => redirect_back(cx, "disable", Some(refusal_of(error))),
117+ }
118+}
119+
120+/// The reader's profile and quota, their live share links, and — for an
121+/// admin — every account with its quota and kill switch.
122+#[page("/settings")]
123+async fn settings(cx: &Cx) -> Result {
124+ let user = match require_user(cx).await {
125+ Ok(user) => user,
126+ Err(refusal) => {
127+ let language = lang(cx);
128+ return view! {
129+ cx =>
130+ <main class="scaffold-note">
131+ <p>(refusal.message_in(language))</p>
132+ <p><a href="/">(t(language, Key::BackToDrive))</a></p>
133+ </main>
134+ };
135+ }
136+ };
137+ let language = lang(cx);
138+ let store = app(cx).store;
139+ // Re-read the row so the quota bar never shows a stale number.
140+ let fresh = store
141+ .user(&user.id)
142+ .await?
143+ .unwrap_or_else(|| user.clone());
144+ let links = store
145+ .share_links(&user.id)
146+ .await?;
147+ let live_links: Vec<_> = links
148+ .iter()
149+ .filter(|link| link.revoked_at.is_none())
150+ .collect();
151+ let users = if fresh.admin {
152+ store.users().await?
153+ } else {
154+ Vec::new()
155+ };
156+ let created = created_token(uri(cx).query().unwrap_or(""));
157+ let origin = app(cx).config.listen_url();
158+ view! {
159+ cx =>
160+ <main class="settings-shell">
161+ (topbar(cx, NavPage::Settings, &fresh, language).await?)
162+ <h1 class="settings-title">(t(language, Key::Settings))</h1>
163+ (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable"]).await?)
164+ if let Some(token) = created {
165+ <section class="panel">
166+ <h2 class="panel-title">(t(language, Key::LinkCreated))</h2>
167+ <div class="panel-body">
168+ <p class="field-note">(t(language, Key::CopyLinkOnce))</p>
169+ <p class="member-link-value">(format!("{origin}/s/{token}"))</p>
170+ </div>
171+ </section>
172+ }
173+ <section class="panel">
174+ <h2 class="panel-title">(t(language, Key::Profile))</h2>
175+ <div class="panel-body">
176+ <p><span class="field-label">(t(language, Key::DisplayName))</span> (fresh.display_name.clone())</p>
177+ <p><span class="field-label">(t(language, Key::EmailAddress))</span> (fresh.email.clone())</p>
178+ <p>
179+ <span class="field-label">(t(language, Key::QuotaUsage))</span>
180+ (format!("{} {} {}", human_bytes(fresh.used_bytes), t(language, Key::QuotaOf), human_bytes(fresh.quota_bytes)))
181+ </p>
182+ <div class="quota-bar" role="progressbar" aria-valuenow=(quota_percent(&fresh).to_string()) aria-valuemin="0" aria-valuemax="100">
183+ <div class="quota-fill" style=(format!("width: {}%", quota_percent(&fresh)))></div>
184+ </div>
185+ </div>
186+ </section>
187+ <section class="panel">
188+ <h2 class="panel-title">(t(language, Key::ManageLinks))</h2>
189+ <div class="panel-body">
190+ if live_links.is_empty() {
191+ <p class="field-note">(t(language, Key::NoLinks))</p>
192+ }
193+ for link in live_links {
194+ <div class="member-row">
195+ <span class="member-name">(format!("{} · {}", link.kind.as_str(), link.target_id.clone()))</span>
196+ <span class="field-note">(expiry_line(language, link.expires_at))</span>
197+ <span class="field-note">(if link.can_download { t(language, Key::CanDownload) } else { t(language, Key::ViewOnly) })</span>
198+ <form class="pop-row-form" method="post" action="/api/share/link/revoke">
199+ <input type="hidden" name="id" value=(link.id.clone())>
200+ <button type="submit">(t(language, Key::RevokeLink))</button>
201+ </form>
202+ </div>
203+ }
204+ </div>
205+ </section>
206+ if fresh.admin {
207+ <section class="panel">
208+ <h2 class="panel-title">(t(language, Key::AdminPanel))</h2>
209+ <div class="panel-body">
210+ <div class="member-table">
211+ for listed in &users {
212+ <div class="member-row">
213+ <span class="member-name">(listed.display_name.clone())</span>
214+ <span class="member-address">(listed.email.clone())</span>
215+ <span class="field-note">(format!("{} {} {}", human_bytes(listed.used_bytes), t(language, Key::QuotaOf), human_bytes(listed.quota_bytes)))</span>
216+ if listed.admin {
217+ <span class="chip chip-admin">(t(language, Key::AdminBadge))</span>
218+ }
219+ if listed.disabled {
220+ <span class="chip chip-off">(t(language, Key::DisabledBadge))</span>
221+ }
222+ <form class="pop-row-form" method="post" action="/api/settings/quota">
223+ <input type="hidden" name="user_id" value=(listed.id.clone())>
224+ <input class="field-input" type="number" name="quota_bytes" min="0" value=(listed.quota_bytes.to_string()) aria-label=(t(language, Key::QuotaBytes))>
225+ <button type="submit">(t(language, Key::SetQuota))</button>
226+ </form>
227+ if listed.id != fresh.id {
228+ <form class="pop-row-form" method="post" action="/api/settings/disable">
229+ <input type="hidden" name="user_id" value=(listed.id.clone())>
230+ if listed.disabled {
231+ <input type="hidden" name="disabled" value="0">
232+ <button type="submit">(t(language, Key::EnableUser))</button>
233+ } else {
234+ <input type="hidden" name="disabled" value="1">
235+ <button class="quiet-danger" type="submit">(t(language, Key::DisableUser))</button>
236+ }
237+ </form>
238+ }
239+ </div>
240+ }
241+ </div>
242+ </div>
243+ </section>
244+ }
245+ </main>
246+ }
247+}
248+
249+/// The just-minted token off the redirect's `?created=` pair, if present.
250+fn created_token(query: &str) -> Option<String> {
251+ query.split('&').find_map(|pair| {
252+ let (name, value) = pair.split_once('=')?;
253+ (name == "created" && !value.is_empty()).then(|| value.to_string())
254+ })
255+}
256+
257+/// When the link stops opening, or never on its own.
258+fn expiry_line(language: crate::i18n::Lang, expires_at: Option<time::OffsetDateTime>) -> String {
259+ match expires_at {
260+ Some(at) => format!(
261+ "{} {}",
262+ t(language, Key::ExpiresLabel),
263+ at.format(&time::format_description::well_known::Rfc3339)
264+ .unwrap_or_else(|_| "?".to_string())
265+ ),
266+ None => t(language, Key::NeverExpires).to_string(),
267+ }
268+}
crates/in-web/src/share.rsadded+776 -0
@@ -0,0 +1,776 @@
1+//! Sharing: public links, per-user grants, and the shared-with-me page.
2+//!
3+//! `POST /api/share/link/create|revoke` mints and kills bearer links over a
4+//! file or folder (`can_download`, optional expiry in days; only the token
5+//! hash is stored). `POST /api/share/user/add|remove` grants and revokes
6+//! named users the same way. `GET /s/{token}` is public — no auth —
7+//! rendering the viewer page, the download only when `can_download` allows,
8+//! and the stored webp preview on `?thumb=1` regardless of the flag; a spent,
9+//! expired or revoked token answers the dead card, never a stack.
10+//! `GET /shared` lists what others shared with the reader.
11+//!
12+//! Every mutation answers the way `board.rs` in iz does: a 303 back to the
13+//! page the form was posted from, the refusal (if any) on the redirect's
14+//! query. The one exception is link creation, whose plaintext token exists
15+//! only at creation: the redirect carries it once as `?created=<token>` so
16+//! a browser without script can copy it, and the drive and settings pages
17+//! render the copy-once banner off that pair.
18+
19+use in_core::hash_share_token;
20+use in_core::store::{ShareKind, Store, StoreError, User};
21+use serde::Deserialize;
22+use time::OffsetDateTime;
23+use topcoat::Result;
24+use topcoat::context::Cx;
25+use topcoat::router::content::Form;
26+use topcoat::router::request::{headers as request_headers, uri};
27+use topcoat::router::response::IntoResponse;
28+use topcoat::router::{HeaderName, StatusCode, header, page, path_param, route};
29+use topcoat::view::view;
30+
31+use crate::i18n::{Key, Lang, lang, t};
32+use crate::layout::{NavPage, topbar, wordmark};
33+use crate::server::{Refusal, app, back_to, require_user};
34+
35+path_param!(token);
36+
37+/// A refusal surfaced as a banner: the `?refusal=<code>&on=<call>` pair the
38+/// mutation redirects carry, rendered only when `on` names one of `calls`.
39+/// Shared by the trash and settings pages, which own no banner of their own.
40+pub(crate) async fn refusal_banner(cx: &Cx, language: Lang, calls: &[&str]) -> Result {
41+ let query = uri(cx).query().unwrap_or("");
42+ let refusal = query_value(query, "refusal").and_then(|code| Refusal::from_code(&code));
43+ let on = query_value(query, "on").unwrap_or_default();
44+ let mine = calls.iter().any(|call| *call == on);
45+ view! {
46+ cx =>
47+ if mine {
48+ if let Some(refusal) = refusal {
49+ <p class="field-error" role="alert">(refusal.message_in(language))</p>
50+ }
51+ }
52+ }
53+}
54+
55+/// The value of one query pair, if present.
56+fn query_value(query: &str, key: &str) -> Option<String> {
57+ query.split('&').find_map(|pair| {
58+ let (name, value) = pair.split_once('=')?;
59+ (name == key).then(|| value.to_string())
60+ })
61+}
62+
63+type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>;
64+
65+/// Back to the posting page, the refusal (if any) on the query.
66+fn redirect_back(cx: &Cx, nowhere: &str, call: &str, refusal: Option<Refusal>) -> Redirect {
67+ let back = back_to(cx, nowhere);
68+ let separator = if back.contains('?') { '&' } else { '?' };
69+ let location = match refusal {
70+ Some(refusal) => format!("{back}{separator}refusal={}&on={call}", refusal.code()),
71+ None => back,
72+ };
73+ Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)]))
74+}
75+
76+/// The store's failure in the route's words. Cross-owner reads answer as
77+/// not-found — a 404, never a 403 — so a stranger cannot probe which ids
78+/// exist.
79+pub(crate) fn refusal_of(error: StoreError) -> Refusal {
80+ match error {
81+ StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound,
82+ StoreError::NameTaken => Refusal::NameTaken,
83+ StoreError::QuotaExceeded => Refusal::QuotaExceeded,
84+ StoreError::AncestorTrashed => Refusal::AncestorTrashed,
85+ _ => Refusal::Unavailable,
86+ }
87+}
88+
89+/// `file` or `folder`, or nothing a route may act on.
90+fn parse_kind(raw: &str) -> Option<ShareKind> {
91+ match raw {
92+ "file" => Some(ShareKind::File),
93+ "folder" => Some(ShareKind::Folder),
94+ _ => None,
95+ }
96+}
97+
98+/// A checkbox-ish flag: absent means the control's default, present is true
99+/// unless it reads plainly false.
100+fn parse_flag(raw: Option<&str>, when_absent: bool) -> bool {
101+ match raw {
102+ None => when_absent,
103+ Some(value) => !matches!(
104+ value.trim().to_lowercase().as_str(),
105+ "" | "0" | "false" | "no" | "off"
106+ ),
107+ }
108+}
109+/// The link's expiry off `expires_in_days`: absent or empty means no expiry,
110+/// anything else must name a positive whole number of days. A mistyped value
111+/// silently minting a never-expiring link would be the wrong default, so it
112+/// is refused instead.
113+fn parse_expiry(raw: Option<&str>) -> std::result::Result<Option<OffsetDateTime>, Refusal> {
114+ let Some(raw) = raw.map(str::trim).filter(|raw| !raw.is_empty()) else {
115+ return Ok(None);
116+ };
117+ let days: i64 = raw.parse().map_err(|_| Refusal::Forbidden)?;
118+ if days <= 0 {
119+ return Err(Refusal::Forbidden);
120+ }
121+ let seconds = days.checked_mul(86_400).ok_or(Refusal::Forbidden)?;
122+ OffsetDateTime::now_utc()
123+ .checked_add(time::Duration::seconds(seconds))
124+ .map(Some)
125+ .ok_or(Refusal::Forbidden)
126+}
127+
128+/// The target the caller must own: present, untrashed, and theirs. Anything
129+/// else is not-found — a stranger learns nothing about whose it is.
130+async fn owned_target(
131+ store: &dyn Store,
132+ user: &User,
133+ kind: ShareKind,
134+ target_id: &str,
135+) -> std::result::Result<(), Refusal> {
136+ let owned = match kind {
137+ ShareKind::File => store
138+ .file(target_id)
139+ .await
140+ .map_err(|_| Refusal::Unavailable)?
141+ .is_some_and(|file| file.owner_id == user.id && file.deleted_at.is_none()),
142+ ShareKind::Folder => store
143+ .folder(target_id)
144+ .await
145+ .map_err(|_| Refusal::Unavailable)?
146+ .is_some_and(|folder| folder.owner_id == user.id && folder.deleted_at.is_none()),
147+ };
148+ if owned { Ok(()) } else { Err(Refusal::NotFound) }
149+}
150+/// The target the caller owns, trashed or not: unsharing a trashed target
151+/// still revokes the grant, and the grant row outlives the trash either way.
152+/// Anything else is not-found — a stranger learns nothing about whose it is.
153+async fn owned_target_for_unshare(
154+ store: &dyn Store,
155+ user: &User,
156+ kind: ShareKind,
157+ target_id: &str,
158+) -> std::result::Result<(), Refusal> {
159+ let owned = match kind {
160+ ShareKind::File => store
161+ .file(target_id)
162+ .await
163+ .map_err(|_| Refusal::Unavailable)?
164+ .is_some_and(|file| file.owner_id == user.id),
165+ ShareKind::Folder => store
166+ .folder(target_id)
167+ .await
168+ .map_err(|_| Refusal::Unavailable)?
169+ .is_some_and(|folder| folder.owner_id == user.id),
170+ };
171+ if owned { Ok(()) } else { Err(Refusal::NotFound) }
172+}
173+
174+#[derive(Deserialize)]
175+struct CreateLinkForm {
176+ kind: String,
177+ target_id: String,
178+ #[serde(default)]
179+ can_download: Option<String>,
180+ #[serde(default)]
181+ expires_in_days: Option<String>,
182+}
183+
184+/// Mints a bearer link. The token is shown once — in the redirect's
185+/// `?created=` pair, which the drive and settings pages render as the
186+/// copy-once banner — and never again; only its hash is stored.
187+#[route(POST "/api/share/link/create")]
188+async fn create_link(cx: &Cx, Form(input): Form<CreateLinkForm>) -> Redirect {
189+ let user = match require_user(cx).await {
190+ Ok(user) => user,
191+ Err(refusal) => return redirect_back(cx, "/settings", "create", Some(refusal)),
192+ };
193+ let Some(kind) = parse_kind(&input.kind) else {
194+ return redirect_back(cx, "/settings", "create", Some(Refusal::NotFound));
195+ };
196+ if let Err(refusal) = owned_target(app(cx).store.as_ref(), &user, kind, &input.target_id).await
197+ {
198+ return redirect_back(cx, "/settings", "create", Some(refusal));
199+ }
200+ let expires_at = match parse_expiry(input.expires_in_days.as_deref()) {
201+ Ok(expires_at) => expires_at,
202+ Err(refusal) => return redirect_back(cx, "/settings", "create", Some(refusal)),
203+ };
204+ let created = app(cx)
205+ .store
206+ .create_share_link(
207+ &user.id,
208+ kind,
209+ &input.target_id,
210+ parse_flag(input.can_download.as_deref(), true),
211+ expires_at,
212+ )
213+ .await;
214+ match created {
215+ Ok(link) => {
216+ let back = back_to(cx, "/settings");
217+ let separator = if back.contains('?') { '&' } else { '?' };
218+ let location = format!("{back}{separator}created={}", link.token);
219+ Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)]))
220+ }
221+ Err(error) => redirect_back(cx, "/settings", "create", Some(refusal_of(error))),
222+ }
223+}
224+
225+#[derive(Deserialize)]
226+struct RevokeLinkForm {
227+ id: String,
228+}
229+
230+/// Kills a bearer link. Only its creator may: anyone else is answered as if
231+/// it never existed. Revoking twice is not an error.
232+#[route(POST "/api/share/link/revoke")]
233+async fn revoke_link(cx: &Cx, Form(input): Form<RevokeLinkForm>) -> Redirect {
234+ let user = match require_user(cx).await {
235+ Ok(user) => user,
236+ Err(refusal) => return redirect_back(cx, "/settings", "revoke", Some(refusal)),
237+ };
238+ let store = app(cx).store;
239+ let mine = store
240+ .share_links(&user.id)
241+ .await
242+ .map_err(|_| Refusal::Unavailable);
243+ let Ok(links) = mine else {
244+ return redirect_back(cx, "/settings", "revoke", Some(Refusal::Unavailable));
245+ };
246+ if !links
247+ .iter()
248+ .any(|link| link.id == input.id && link.created_by == user.id)
249+ {
250+ return redirect_back(cx, "/settings", "revoke", Some(Refusal::NotFound));
251+ }
252+ match store.revoke_share_link(&input.id).await {
253+ Ok(()) => redirect_back(cx, "/settings", "revoke", None),
254+ Err(error) => redirect_back(cx, "/settings", "revoke", Some(refusal_of(error))),
255+ }
256+}
257+
258+/// Whether `at` is the link's target or sits under it: every step up must be
259+/// live, owned by the link's owner, and end at the target. A break anywhere
260+/// means the browse is outside the share.
261+async fn under_target(store: &dyn Store, owner_id: &str, target_id: &str, at: &str) -> bool {
262+ let mut current = at.to_string();
263+ loop {
264+ if current == target_id {
265+ return true;
266+ }
267+ let Ok(Some(folder)) = store.folder(&current).await else {
268+ return false;
269+ };
270+ if folder.owner_id != owner_id || folder.deleted_at.is_some() {
271+ return false;
272+ }
273+ match folder.parent_id {
274+ Some(parent) if parent != current => current = parent,
275+ _ => return false,
276+ }
277+ }
278+}
279+#[derive(Deserialize)]
280+struct ShareUserForm {
281+ kind: String,
282+ target_id: String,
283+ #[serde(default)]
284+ email: String,
285+ #[serde(default)]
286+ can_download: Option<String>,
287+}
288+
289+/// Shares one file or folder with one named person. The address is folded to
290+/// lowercase before lookup; an unknown address is not-found.
291+#[route(POST "/api/share/user/add")]
292+async fn add_share(cx: &Cx, Form(input): Form<ShareUserForm>) -> Redirect {
293+ let user = match require_user(cx).await {
294+ Ok(user) => user,
295+ Err(refusal) => return redirect_back(cx, "/settings", "add", Some(refusal)),
296+ };
297+ let Some(kind) = parse_kind(&input.kind) else {
298+ return redirect_back(cx, "/settings", "add", Some(Refusal::NotFound));
299+ };
300+ if let Err(refusal) = owned_target(app(cx).store.as_ref(), &user, kind, &input.target_id).await
301+ {
302+ return redirect_back(cx, "/settings", "add", Some(refusal));
303+ }
304+ let store = app(cx).store;
305+ let grantee = store
306+ .user_by_email(&input.email.trim().to_lowercase())
307+ .await
308+ .map_err(|_| Refusal::Unavailable);
309+ let Ok(Some(grantee)) = grantee else {
310+ return redirect_back(cx, "/settings", "add", Some(Refusal::NotFound));
311+ };
312+ match store
313+ .add_share_user(
314+ &user.id,
315+ kind,
316+ &input.target_id,
317+ &grantee.id,
318+ parse_flag(input.can_download.as_deref(), true),
319+ )
320+ .await
321+ {
322+ Ok(()) => redirect_back(cx, "/settings", "add", None),
323+ Err(error) => redirect_back(cx, "/settings", "add", Some(refusal_of(error))),
324+ }
325+}
326+
327+/// Unshares. Removing what was never shared is not an error; only the
328+/// target's owner may unshare, trashed or not.
329+#[route(POST "/api/share/user/remove")]
330+async fn remove_share(cx: &Cx, Form(input): Form<ShareUserForm>) -> Redirect {
331+ let user = match require_user(cx).await {
332+ Ok(user) => user,
333+ Err(refusal) => return redirect_back(cx, "/settings", "remove", Some(refusal)),
334+ };
335+ let Some(kind) = parse_kind(&input.kind) else {
336+ return redirect_back(cx, "/settings", "remove", Some(Refusal::NotFound));
337+ };
338+ if let Err(refusal) = owned_target_for_unshare(app(cx).store.as_ref(), &user, kind, &input.target_id).await
339+ {
340+ return redirect_back(cx, "/settings", "remove", Some(refusal));
341+ }
342+ let store = app(cx).store;
343+ let grantee = store
344+ .user_by_email(&input.email.trim().to_lowercase())
345+ .await
346+ .map_err(|_| Refusal::Unavailable);
347+ let Ok(Some(grantee)) = grantee else {
348+ return redirect_back(cx, "/settings", "remove", Some(Refusal::NotFound));
349+ };
350+ match store
351+ .remove_share_user(kind, &input.target_id, &grantee.id)
352+ .await
353+ {
354+ Ok(()) => redirect_back(cx, "/settings", "remove", None),
355+ Err(error) => redirect_back(cx, "/settings", "remove", Some(refusal_of(error))),
356+ }
357+}
358+
359+/// The public viewer's query: which folder is browsed, which file is named,
360+/// whether the bytes (rather than the card) are wanted, and whether the
361+/// stored webp preview is wanted — the preview a view-only link grants.
362+struct SharedQuery {
363+ folder: Option<String>,
364+ file: Option<String>,
365+ dl: bool,
366+ thumb: bool,
367+}
368+
369+/// The query off the request's own URI. Unparseable pairs are ignored —
370+/// a hand-edited query browses nothing rather than failing the page.
371+fn shared_query(cx: &Cx) -> SharedQuery {
372+ let query = uri(cx).query().unwrap_or("");
373+ SharedQuery {
374+ folder: query_value(query, "folder"),
375+ file: query_value(query, "file"),
376+ dl: has_flag(query, "dl"),
377+ thumb: has_flag(query, "thumb"),
378+ }
379+}
380+
381+/// Whether the query names the bare flag, as `?dl` or `?dl=1`.
382+fn has_flag(query: &str, key: &str) -> bool {
383+ query
384+ .split('&')
385+ .any(|pair| pair == key || pair.starts_with(&format!("{key}=")))
386+}
387+
388+/// The dead card: a spent, expired, revoked or never-real token, a trashed
389+/// target, or a download the link may not open. One answer for all of them —
390+/// a stranger learns nothing about which tokens exist.
391+async fn dead_link(cx: &Cx) -> Result {
392+ let language = lang(cx);
393+ view! {
394+ cx =>
395+ <main class="scaffold-note">
396+ (wordmark(cx).await?)
397+ <p>(Refusal::ShareRevoked.message_in(language))</p>
398+ <p><a href="/">(t(language, Key::BackToDrive))</a></p>
399+ </main>
400+ }
401+}
402+
403+/// The public viewer. No auth: the token in the path is the whole
404+/// credential. A file target renders its card (and its bytes on `?dl=1`
405+/// when the link may download); a folder target renders the listing of the
406+/// browsed folder, downloads gated per file on the same flag.
407+#[route(GET "/s/{token}")]
408+async fn shared_link(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> {
409+ let token: &str = path_param::<Token>(cx);
410+ let store = app(cx).store;
411+ let now = OffsetDateTime::now_utc();
412+ let link = store
413+ .resolve_share_link(&hash_share_token(token), now)
414+ .await
415+ .ok()
416+ .flatten();
417+ let Some(link) = link else {
418+ return dead_link(cx).await.into_response(cx);
419+ };
420+ let query = shared_query(cx);
421+ match link.kind {
422+ ShareKind::File => {
423+ let file = store
424+ .file(&link.target_id)
425+ .await
426+ .map_err(|_| Refusal::Unavailable);
427+ let Ok(Some(file)) = file else {
428+ return dead_link(cx).await.into_response(cx);
429+ };
430+ if file.deleted_at.is_some() {
431+ return dead_link(cx).await.into_response(cx);
432+ }
433+ if query.dl {
434+ return download_bytes(cx, store.as_ref(), &file.id, &file.name, &file.mime, link.can_download).await;
435+ }
436+ if query.thumb {
437+ return public_thumb(cx, store.as_ref(), &file.id).await;
438+ }
439+ file_card(cx, &link, &file).await
440+ }
441+ ShareKind::Folder => {
442+ let root = store
443+ .folder(&link.target_id)
444+ .await
445+ .map_err(|_| Refusal::Unavailable);
446+ let Ok(Some(root)) = root else {
447+ return dead_link(cx).await.into_response(cx);
448+ };
449+ if root.deleted_at.is_some() {
450+ return dead_link(cx).await.into_response(cx);
451+ }
452+ let at = query.folder.as_deref().unwrap_or(&root.id).to_string();
453+ if !under_target(store.as_ref(), &root.owner_id, &root.id, &at).await {
454+ return dead_link(cx).await.into_response(cx);
455+ }
456+ if query.dl {
457+ let Some(file_id) = query.file.as_deref() else {
458+ return dead_link(cx).await.into_response(cx);
459+ };
460+ let file = store
461+ .file(file_id)
462+ .await
463+ .map_err(|_| Refusal::Unavailable);
464+ let Ok(Some(file)) = file else {
465+ return dead_link(cx).await.into_response(cx);
466+ };
467+ if file.deleted_at.is_some()
468+ || file.owner_id != root.owner_id
469+ || file.folder_id.as_deref() != Some(at.as_str())
470+ {
471+ return dead_link(cx).await.into_response(cx);
472+ }
473+ return download_bytes(cx, store.as_ref(), &file.id, &file.name, &file.mime, link.can_download).await;
474+ }
475+ if query.thumb {
476+ let Some(file_id) = query.file.as_deref() else {
477+ return dead_link(cx).await.into_response(cx);
478+ };
479+ let file = store
480+ .file(file_id)
481+ .await
482+ .map_err(|_| Refusal::Unavailable);
483+ let Ok(Some(file)) = file else {
484+ return dead_link(cx).await.into_response(cx);
485+ };
486+ if file.deleted_at.is_some()
487+ || file.owner_id != root.owner_id
488+ || file.folder_id.as_deref() != Some(at.as_str())
489+ {
490+ return dead_link(cx).await.into_response(cx);
491+ }
492+ return public_thumb(cx, store.as_ref(), &file.id).await;
493+ }
494+ folder_card(cx, store.as_ref(), &link, &root, &at, token).await
495+ }
496+ }
497+}
498+
499+/// The bytes behind a public link. A view-only link answers the dead card
500+/// here — the same answer as a spent token — so the surface never says which
501+/// tokens exist.
502+async fn download_bytes(
503+ cx: &Cx,
504+ store: &dyn Store,
505+ file_id: &str,
506+ name: &str,
507+ mime: &str,
508+ can_download: bool,
509+) -> topcoat::Result<topcoat::router::response::Response> {
510+ use topcoat::router::response::IntoResponse;
511+ use topcoat::router::{HeaderMap, HeaderValue};
512+ if !can_download {
513+ return dead_link(cx).await.into_response(cx);
514+ }
515+ let bytes = store
516+ .file_bytes(file_id)
517+ .await
518+ .map_err(|_| Refusal::Unavailable);
519+ let Ok(Some(bytes)) = bytes else {
520+ return dead_link(cx).await.into_response(cx);
521+ };
522+ let mut headers = HeaderMap::new();
523+ if let Ok(value) = HeaderValue::from_str(mime) {
524+ headers.insert(header::CONTENT_TYPE, value);
525+ }
526+ let disposition = format!("attachment; filename=\"{}\"", safe_name(name));
527+ if let Ok(value) = HeaderValue::from_str(&disposition) {
528+ headers.insert(header::CONTENT_DISPOSITION, value);
529+ }
530+ headers.insert(
531+ header::CACHE_CONTROL,
532+ HeaderValue::from_static("private, no-cache"),
533+ );
534+ Ok((StatusCode::OK, headers, bytes).into_response(cx)?)
535+}
536+
537+/// The stored webp preview behind a public link. Unlike the bytes, the
538+/// preview is what a view-only link grants, so this answers regardless of
539+/// `can_download` — and anything unservable is the dead card, like every
540+/// other answer on this surface. Headers twin the `files.rs` thumbnail route.
541+async fn public_thumb(
542+ cx: &Cx,
543+ store: &dyn Store,
544+ file_id: &str,
545+) -> topcoat::Result<topcoat::router::response::Response> {
546+ use topcoat::router::response::IntoResponse;
547+ use topcoat::router::{HeaderMap, HeaderValue};
548+ let Ok(Some(bytes)) = store.thumb_bytes(file_id).await else {
549+ return dead_link(cx).await.into_response(cx);
550+ };
551+ let etag = format!("\"{:x}\"", crate::files::fnv1a(&bytes));
552+ let mut headers = HeaderMap::new();
553+ headers.insert(
554+ header::ETAG,
555+ HeaderValue::from_str(&etag).unwrap_or(HeaderValue::from_static("\"0\"")),
556+ );
557+ headers.insert(
558+ header::CACHE_CONTROL,
559+ HeaderValue::from_static("private, max-age=31536000, immutable"),
560+ );
561+ headers.insert(
562+ header::CONTENT_TYPE,
563+ HeaderValue::from_static("image/webp"),
564+ );
565+ let if_none_match = request_headers(cx)
566+ .get(header::IF_NONE_MATCH)
567+ .and_then(|value| value.to_str().ok());
568+ if if_none_match == Some(etag.as_str()) {
569+ return Ok((StatusCode::NOT_MODIFIED, headers, Vec::new()).into_response(cx)?);
570+ }
571+ Ok((StatusCode::OK, headers, bytes).into_response(cx)?)
572+}
573+
574+/// A filename safe for a header: quotes and backslashes stripped, never
575+/// empty.
576+fn safe_name(name: &str) -> String {
577+ let cleaned: String = name
578+ .chars()
579+ .filter(|c| !c.is_control() && *c != '"' && *c != '\\')
580+ .collect();
581+ if cleaned.is_empty() {
582+ "file".to_string()
583+ } else {
584+ cleaned
585+ }
586+}
587+
588+/// A shared file's card: its name, size and type, an image preview off the
589+/// public thumbnail route, and the download while the link allows it.
590+async fn file_card(
591+ cx: &Cx,
592+ link: &in_core::store::ShareLink,
593+ file: &in_core::store::File,
594+) -> topcoat::Result<topcoat::router::response::Response> {
595+ let language = lang(cx);
596+ let preview = file.mime.starts_with("image/");
597+ let token_path = current_path(cx);
598+ view! {
599+ cx =>
600+ <main class="scaffold-note">
601+ (wordmark(cx).await?)
602+ <h1 class="settings-title">(file.name.clone())</h1>
603+ <p class="field-note">(format!("{} · {}", file.mime.clone(), crate::settings::human_bytes(file.size_bytes)))</p>
604+ if preview {
605+ <img src=(format!("{token_path}?thumb=1")) alt=(file.name.clone())>
606+ } else {
607+ <p class="field-note">(t(language, Key::PreviewUnavailable))</p>
608+ }
609+ if link.can_download {
610+ <p><a class="primary" href=(format!("{token_path}?dl=1"))>(t(language, Key::Download))</a></p>
611+ } else {
612+ <p class="field-note">(t(language, Key::ViewOnly))</p>
613+ }
614+ </main>
615+ }
616+ .into_response(cx)
617+}
618+
619+/// A shared folder's listing: subfolders then files, downloads gated on the
620+/// link's flag. Subfolders browse in place under the same token.
621+async fn folder_card(
622+ cx: &Cx,
623+ store: &dyn Store,
624+ link: &in_core::store::ShareLink,
625+ root: &in_core::store::Folder,
626+ at: &str,
627+ token: &str,
628+) -> topcoat::Result<topcoat::router::response::Response> {
629+ let language = lang(cx);
630+ let here = store
631+ .folder(at)
632+ .await?;
633+ let Some(here) = here else {
634+ return dead_link(cx).await.into_response(cx);
635+ };
636+ let listing = store
637+ .list_children(&root.owner_id, Some(at))
638+ .await?;
639+ let base = format!("/s/{token}");
640+ view! {
641+ cx =>
642+ <main class="settings-shell">
643+ (wordmark(cx).await?)
644+ <h1 class="settings-title">(here.name.clone())</h1>
645+ <section class="panel">
646+ <h2 class="panel-title">(t(language, Key::FoldersHeading))</h2>
647+ <div class="panel-body">
648+ if listing.folders.is_empty() {
649+ <p class="field-note">(t(language, Key::EmptyFolder))</p>
650+ }
651+ for folder in &listing.folders {
652+ <p><a href=(format!("{base}?folder={}", folder.id))>(folder.name.clone())</a></p>
653+ }
654+ </div>
655+ </section>
656+ <section class="panel">
657+ <h2 class="panel-title">(t(language, Key::FilesHeading))</h2>
658+ <div class="panel-body">
659+ if listing.files.is_empty() {
660+ <p class="field-note">(t(language, Key::EmptyFolder))</p>
661+ }
662+ for file in &listing.files {
663+ <p>
664+ <span>(file.name.clone())</span>
665+ (format!(" · {}", crate::settings::human_bytes(file.size_bytes)))
666+ if link.can_download {
667+ <a href=(format!("{base}?folder={at}&file={}&dl=1", file.id))>(t(language, Key::Download))</a>
668+ } else {
669+ <span class="field-note">(t(language, Key::ViewOnly))</span>
670+ }
671+ </p>
672+ }
673+ </div>
674+ </section>
675+ </main>
676+ }
677+ .into_response(cx)
678+}
679+
680+/// The request's own path, without its query: the download links the public
681+/// cards render point back at the same token.
682+fn current_path(cx: &Cx) -> String {
683+ let path = uri(cx).path();
684+ if path.is_empty() { "/".to_string() } else { path.to_string() }
685+}
686+
687+/// Everything others shared with the reader, files and folders in their own
688+/// groups, newest grant first. The reader's own library never appears here.
689+#[page("/shared")]
690+async fn shared(cx: &Cx) -> Result {
691+ let user = match require_user(cx).await {
692+ Ok(user) => user,
693+ Err(refusal) => {
694+ let language = lang(cx);
695+ return view! {
696+ cx =>
697+ <main class="scaffold-note">
698+ <p>(refusal.message_in(language))</p>
699+ <p><a href="/">(t(language, Key::BackToDrive))</a></p>
700+ </main>
701+ };
702+ }
703+ };
704+ let language = lang(cx);
705+ let store = app(cx).store;
706+ let items = store
707+ .shares_for_user(&user.id)
708+ .await?;
709+ let mut owners: std::collections::HashMap<String, String> = std::collections::HashMap::new();
710+ for item in &items {
711+ if !owners.contains_key(&item.owner_id) {
712+ let name = store
713+ .user(&item.owner_id)
714+ .await
715+ .ok()
716+ .flatten()
717+ .map(|owner| owner.display_name)
718+ .unwrap_or_default();
719+ owners.insert(item.owner_id.clone(), name);
720+ }
721+ }
722+ view! {
723+ cx =>
724+ <main class="settings-shell">
725+ (topbar(cx, NavPage::Shared, &user, language).await?)
726+ <h1 class="settings-title">(t(language, Key::SharedWithMe))</h1>
727+ if items.is_empty() {
728+ <p class="field-note">(t(language, Key::NoSharedItems))</p>
729+ }
730+ <section class="panel">
731+ <h2 class="panel-title">(t(language, Key::FoldersHeading))</h2>
732+ <div class="panel-body">
733+ for item in items.iter().filter(|item| item.kind == ShareKind::Folder) {
734+ <p>
735+ <a href=(format!("/drive?folder={}", item.target_id))>(item.name.clone())</a>
736+ (owner_chip(item, &owners))
737+ (access_chip(language, item.can_download))
738+ </p>
739+ }
740+ </div>
741+ </section>
742+ <section class="panel">
743+ <h2 class="panel-title">(t(language, Key::FilesHeading))</h2>
744+ <div class="panel-body">
745+ for item in items.iter().filter(|item| item.kind == ShareKind::File) {
746+ <p>
747+ <a href=(format!("/file/{}", item.target_id))>(item.name.clone())</a>
748+ (owner_chip(item, &owners))
749+ (access_chip(language, item.can_download))
750+ </p>
751+ }
752+ </div>
753+ </section>
754+ </main>
755+ }
756+}
757+
758+/// `by <name>`, when the owner's name is known.
759+fn owner_chip(
760+ item: &in_core::store::SharedItem,
761+ owners: &std::collections::HashMap<String, String>,
762+) -> String {
763+ match owners.get(&item.owner_id) {
764+ Some(name) if !name.is_empty() => format!(" · {name}"),
765+ _ => String::new(),
766+ }
767+}
768+
769+/// What the grant opens: the download, or the view alone.
770+fn access_chip(language: Lang, can_download: bool) -> &'static str {
771+ if can_download {
772+ t(language, Key::CanDownload)
773+ } else {
774+ t(language, Key::ViewOnly)
775+ }
776+}
crates/in-web/src/trash.rsadded+222 -0
@@ -0,0 +1,222 @@
1+//! Trash: the soft-deleted shelf and its three mutations.
2+//!
3+//! `GET /trash` lists the reader's trashed files and folders. Trashed bytes
4+//! stay on disk and keep counting toward the quota until the purge. Folder
5+//! trash and restore cascade to descendants under one timestamp, and an item
6+//! whose ancestor is still trashed cannot be restored.
7+//! `POST /api/trash/restore|purge|empty` bring back, destroy one row (plus
8+//! its bytes), or destroy them all. Purge is the only delete that touches
9+//! the filesystem. Folder purge has no store method yet (hubbed to Main via
10+//! the orchestrator) and is refused until it lands.
11+
12+use in_core::store::{ShareKind, Store, User};
13+use serde::Deserialize;
14+use topcoat::Result;
15+use topcoat::context::Cx;
16+use topcoat::router::content::Form;
17+use topcoat::router::{HeaderName, StatusCode, header, page, route};
18+use topcoat::view::view;
19+
20+use crate::i18n::{Key, lang, t};
21+use crate::layout::{NavPage, topbar};
22+use crate::server::{Refusal, app, back_to, require_user};
23+use crate::share::{refusal_banner, refusal_of};
24+
25+/// The reader's own trashed row, or nothing a mutation may touch.
26+/// Cross-owner ids answer as not-found, never forbidden.
27+async fn trashed_row(
28+ store: &dyn Store,
29+ user: &User,
30+ kind: ShareKind,
31+ id: &str,
32+) -> std::result::Result<(), Refusal> {
33+ let owned = match kind {
34+ ShareKind::File => store
35+ .file(id)
36+ .await
37+ .map_err(|_| Refusal::Unavailable)?
38+ .is_some_and(|file| file.owner_id == user.id && file.deleted_at.is_some()),
39+ ShareKind::Folder => store
40+ .folder(id)
41+ .await
42+ .map_err(|_| Refusal::Unavailable)?
43+ .is_some_and(|folder| folder.owner_id == user.id && folder.deleted_at.is_some()),
44+ };
45+ if owned { Ok(()) } else { Err(Refusal::NotFound) }
46+}
47+
48+type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>;
49+
50+/// Back to the trash, the refusal (if any) on the query.
51+fn redirect_back(cx: &Cx, call: &str, refusal: Option<Refusal>) -> Redirect {
52+ let back = back_to(cx, "/trash");
53+ let separator = if back.contains('?') { '&' } else { '?' };
54+ let location = match refusal {
55+ Some(refusal) => format!("{back}{separator}refusal={}&on={call}", refusal.code()),
56+ None => back,
57+ };
58+ Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)]))
59+}
60+
61+#[derive(Deserialize)]
62+struct TrashTargetForm {
63+ kind: String,
64+ id: String,
65+}
66+
67+/// Brings one trashed row back. Refused while an ancestor folder is still
68+/// trashed (as forbidden — there is no code of its own yet), or while a
69+/// live sibling wears its name.
70+#[route(POST "/api/trash/restore")]
71+async fn restore(cx: &Cx, Form(input): Form<TrashTargetForm>) -> Redirect {
72+ let user = match require_user(cx).await {
73+ Ok(user) => user,
74+ Err(refusal) => return redirect_back(cx, "restore", Some(refusal)),
75+ };
76+ let kind = match input.kind.as_str() {
77+ "file" => ShareKind::File,
78+ "folder" => ShareKind::Folder,
79+ _ => return redirect_back(cx, "restore", Some(Refusal::NotFound)),
80+ };
81+ if let Err(refusal) = trashed_row(app(cx).store.as_ref(), &user, kind, &input.id).await {
82+ return redirect_back(cx, "restore", Some(refusal));
83+ }
84+ let store = app(cx).store;
85+ let outcome = match kind {
86+ ShareKind::File => store.restore_file(&input.id).await,
87+ ShareKind::Folder => store.restore_folder(&input.id).await,
88+ };
89+ match outcome {
90+ Ok(()) => redirect_back(cx, "restore", None),
91+ Err(error) => redirect_back(cx, "restore", Some(refusal_of(error))),
92+ }
93+}
94+
95+/// Destroys one trashed file for good: the row goes and the bytes and
96+/// thumbnail follow. A live file is never purged — trash it first. Folder
97+/// purge waits on a store method (see the module docs) and is refused.
98+#[route(POST "/api/trash/purge")]
99+async fn purge(cx: &Cx, Form(input): Form<TrashTargetForm>) -> Redirect {
100+ let user = match require_user(cx).await {
101+ Ok(user) => user,
102+ Err(refusal) => return redirect_back(cx, "purge", Some(refusal)),
103+ };
104+ let kind = match input.kind.as_str() {
105+ "file" => ShareKind::File,
106+ "folder" => ShareKind::Folder,
107+ _ => return redirect_back(cx, "purge", Some(Refusal::NotFound)),
108+ };
109+ if let Err(refusal) = trashed_row(app(cx).store.as_ref(), &user, kind, &input.id).await {
110+ return redirect_back(cx, "purge", Some(refusal));
111+ }
112+ match kind {
113+ ShareKind::File => match app(cx).store.purge_file(&input.id).await {
114+ Ok(true) => redirect_back(cx, "purge", None),
115+ Ok(false) => redirect_back(cx, "purge", Some(Refusal::NotFound)),
116+ Err(error) => redirect_back(cx, "purge", Some(refusal_of(error))),
117+ },
118+ ShareKind::Folder => match app(cx).store.purge_folder(&input.id).await {
119+ Ok(_) => redirect_back(cx, "purge", None),
120+ Err(error) => redirect_back(cx, "purge", Some(refusal_of(error))),
121+ },
122+ }
123+}
124+
125+/// Destroys everything the reader trashed, files before folders.
126+#[route(POST "/api/trash/empty")]
127+async fn empty(cx: &Cx) -> Redirect {
128+ let user = match require_user(cx).await {
129+ Ok(user) => user,
130+ Err(refusal) => return redirect_back(cx, "empty", Some(refusal)),
131+ };
132+ match app(cx).store.empty_trash(&user.id).await {
133+ Ok(_) => redirect_back(cx, "empty", None),
134+ Err(error) => redirect_back(cx, "empty", Some(refusal_of(error))),
135+ }
136+}
137+
138+/// The reader's trash: every trashed folder and file, newest trash first,
139+/// each row carrying its way back and its way gone, plus the button that
140+/// destroys them all.
141+#[page("/trash")]
142+async fn trash(cx: &Cx) -> Result {
143+ let user = match require_user(cx).await {
144+ Ok(user) => user,
145+ Err(refusal) => {
146+ let language = lang(cx);
147+ return view! {
148+ cx =>
149+ <main class="scaffold-note">
150+ <p>(refusal.message_in(language))</p>
151+ <p><a href="/">(t(language, Key::BackToDrive))</a></p>
152+ </main>
153+ };
154+ }
155+ };
156+ let language = lang(cx);
157+ let listing = app(cx)
158+ .store
159+ .list_trash(&user.id)
160+ .await?;
161+ view! {
162+ cx =>
163+ <main class="settings-shell">
164+ (topbar(cx, NavPage::Trash, &user, language).await?)
165+ <h1 class="settings-title">(t(language, Key::Trash))</h1>
166+ (refusal_banner(cx, language, &["restore", "purge", "empty"]).await?)
167+ if listing.folders.is_empty() && listing.files.is_empty() {
168+ <p class="field-note">(t(language, Key::TrashEmpty))</p>
169+ }
170+ if !listing.folders.is_empty() || !listing.files.is_empty() {
171+ <form method="post" action="/api/trash/empty">
172+ <button class="quiet-danger" type="submit">(t(language, Key::EmptyTrash))</button>
173+ </form>
174+ }
175+ if !listing.folders.is_empty() {
176+ <section class="panel">
177+ <h2 class="panel-title">(t(language, Key::FoldersHeading))</h2>
178+ <div class="panel-body">
179+ for folder in &listing.folders {
180+ <div class="member-row">
181+ <span class="member-name">(folder.name.clone())</span>
182+ <form class="pop-row-form" method="post" action="/api/trash/restore">
183+ <input type="hidden" name="kind" value="folder">
184+ <input type="hidden" name="id" value=(folder.id.clone())>
185+ <button type="submit">(t(language, Key::Restore))</button>
186+ </form>
187+ <form class="pop-row-form" method="post" action="/api/trash/purge">
188+ <input type="hidden" name="kind" value="folder">
189+ <input type="hidden" name="id" value=(folder.id.clone())>
190+ <button class="quiet-danger" type="submit">(t(language, Key::DeleteForever))</button>
191+ </form>
192+ </div>
193+ }
194+ </div>
195+ </section>
196+ }
197+ if !listing.files.is_empty() {
198+ <section class="panel">
199+ <h2 class="panel-title">(t(language, Key::FilesHeading))</h2>
200+ <div class="panel-body">
201+ for file in &listing.files {
202+ <div class="member-row">
203+ <span class="member-name">(file.name.clone())</span>
204+ <span class="field-note">(crate::settings::human_bytes(file.size_bytes))</span>
205+ <form class="pop-row-form" method="post" action="/api/trash/restore">
206+ <input type="hidden" name="kind" value="file">
207+ <input type="hidden" name="id" value=(file.id.clone())>
208+ <button type="submit">(t(language, Key::Restore))</button>
209+ </form>
210+ <form class="pop-row-form" method="post" action="/api/trash/purge">
211+ <input type="hidden" name="kind" value="file">
212+ <input type="hidden" name="id" value=(file.id.clone())>
213+ <button class="quiet-danger" type="submit">(t(language, Key::DeleteForever))</button>
214+ </form>
215+ </div>
216+ }
217+ </div>
218+ </section>
219+ }
220+ </main>
221+ }
222+}
crates/in-web/src/upload.rsadded+165 -0
@@ -0,0 +1,165 @@
1+//! The chunked-upload protocol.
2+//!
3+//! Four owner-only JSON calls, all UTF-8: `POST /api/upload/start`
4+//! `{folder_id, name, size_bytes}` answers `{id, chunk_size}` with the
5+//! server-fixed 8 MiB chunk size (`Refusal::QuotaExceeded` when the quota
6+//! says no); `PUT /api/upload/{id}/{index}` takes one raw chunk (16 MiB
7+//! cap, layered in `main.rs`); `POST /api/upload/{id}/finish` assembles the
8+//! staged chunks, sniffs the mime, moves the bytes to `files/<new file id>`
9+//! and answers with the created file id; `POST /api/upload/{id}/abort`
10+//! drops the session and its staged bytes. Quota is enforced at start *and*
11+//! at finish. The UI picks this path at 8 MiB and over; below that it posts
12+//! straight to `POST /files`.
13+//!
14+//! Answers are `200` JSON throughout — `{ok: ...}` or `{err: <refusal>}` —
15+//! because the caller is script, not a form: there is no page to redirect
16+//! back to, and the progress bar reads the refusal straight off the body.
17+
18+use in_core::store::StoreError;
19+use topcoat::Result;
20+use topcoat::context::Cx;
21+use topcoat::router::content::Json;
22+use topcoat::router::request::{Bytes, uri};
23+use topcoat::router::{path_param, route};
24+
25+use crate::server::{Refusal, app, require_user};
26+
27+path_param!(id);
28+
29+/// What the script side reads: the value, or the refusal it failed with.
30+/// Serialises as `{"ok":...}` / `{"err":...}`.
31+type Answer<T> = std::result::Result<T, Refusal>;
32+
33+/// A [`StoreError`] in the upload's own words. Another owner's session id
34+/// answers [`Refusal::NotFound`]: the id space is not theirs to probe.
35+fn store_refusal(error: StoreError) -> Refusal {
36+ match error {
37+ StoreError::QuotaExceeded => Refusal::QuotaExceeded,
38+ StoreError::UploadExpired => Refusal::UploadExpired,
39+ StoreError::BadChunk => Refusal::BadChunk,
40+ StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound,
41+ StoreError::NameTaken => Refusal::NameTaken,
42+ _ => Refusal::Unavailable,
43+ }
44+}
45+
46+/// The owned, active session the call names, or the refusal its answer
47+/// carries. Another owner's session is not found rather than forbidden.
48+async fn owned_session(
49+ cx: &Cx,
50+ id: &str,
51+) -> std::result::Result<in_core::store::UploadSession, Refusal> {
52+ let user = require_user(cx).await?;
53+ let store = app(cx).store.clone();
54+ match store.upload_session(id).await {
55+ Ok(Some(session)) if session.owner_id == user.id => Ok(session),
56+ Ok(_) => Err(Refusal::NotFound),
57+ Err(_) => Err(Refusal::Unavailable),
58+ }
59+}
60+
61+#[derive(serde::Deserialize)]
62+struct StartIn {
63+ folder_id: Option<String>,
64+ name: String,
65+ size_bytes: u64,
66+}
67+
68+#[derive(serde::Serialize)]
69+struct StartOut {
70+ id: String,
71+ chunk_size: u64,
72+}
73+
74+/// Opens an upload session after the quota pre-check: the declared total
75+/// must fit the remaining quota, or the browser learns before sending a
76+/// single chunk.
77+#[route(POST "/api/upload/start")]
78+async fn start(cx: &Cx, Json(input): Json<StartIn>) -> Result<Json<Answer<StartOut>>> {
79+ let user = match require_user(cx).await {
80+ Ok(user) => user,
81+ Err(refusal) => return Ok(Json(Err(refusal))),
82+ };
83+ let store = app(cx).store.clone();
84+ let folder = input.folder_id.as_deref().filter(|id| !id.is_empty());
85+ if let Some(id) = folder {
86+ match store.folder(id).await {
87+ Ok(Some(row)) if row.owner_id == user.id && row.deleted_at.is_none() => {}
88+ Ok(_) => return Ok(Json(Err(Refusal::NotFound))),
89+ Err(_) => return Ok(Json(Err(Refusal::Unavailable))),
90+ }
91+ }
92+ match store
93+ .create_upload_session(&user.id, folder, &input.name, input.size_bytes)
94+ .await
95+ {
96+ Ok(session) => Ok(Json(Ok(StartOut {
97+ id: session.id,
98+ chunk_size: session.chunk_size,
99+ }))),
100+ Err(error) => Ok(Json(Err(store_refusal(error)))),
101+ }
102+}
103+
104+#[derive(serde::Serialize)]
105+struct ChunkOut {
106+ received_bytes: u64,
107+ size_bytes: u64,
108+}
109+
110+/// Stages one raw chunk. The store refuses a wrong-sized or out-of-range
111+/// piece with [`StoreError::BadChunk`] and an expired session with
112+/// [`StoreError::UploadExpired`]; this layer only gates the owner.
113+#[route(PUT "/api/upload/{id}/{index}")]
114+async fn chunk(cx: &Cx, body: Bytes) -> Result<Json<Answer<ChunkOut>>> {
115+ let id: &str = path_param::<Id>(cx);
116+ let index: u64 = match uri(cx).path().rsplit('/').next().and_then(|raw| raw.parse().ok()) {
117+ Some(index) => index,
118+ None => return Ok(Json(Err(Refusal::BadChunk))),
119+ };
120+ let session = match owned_session(cx, id).await {
121+ Ok(session) => session,
122+ Err(refusal) => return Ok(Json(Err(refusal))),
123+ };
124+ let store = app(cx).store.clone();
125+ match store.record_chunk(&session.id, index, &body).await {
126+ Ok(session) => Ok(Json(Ok(ChunkOut {
127+ received_bytes: session.received_bytes,
128+ size_bytes: session.size_bytes,
129+ }))),
130+ Err(error) => Ok(Json(Err(store_refusal(error)))),
131+ }
132+}
133+
134+/// Assembles the staged chunks — rechecking the quota, sniffing the mime
135+/// off the bytes, attempting the thumbnail — and answers the created file
136+/// id. The chunks stay staged on refusal, so the browser may retry.
137+#[route(POST "/api/upload/{id}/finish")]
138+async fn finish(cx: &Cx) -> Result<Json<Answer<String>>> {
139+ let id: &str = path_param::<Id>(cx);
140+ let session = match owned_session(cx, id).await {
141+ Ok(session) => session,
142+ Err(refusal) => return Ok(Json(Err(refusal))),
143+ };
144+ let store = app(cx).store.clone();
145+ match store.finish_upload(&session.id).await {
146+ Ok(file) => Ok(Json(Ok(file.id))),
147+ Err(error) => Ok(Json(Err(store_refusal(error)))),
148+ }
149+}
150+
151+/// Aborts a session: the row says `aborted` and the staged chunks go.
152+/// Aborting twice — or aborting nothing — is not an error.
153+#[route(POST "/api/upload/{id}/abort")]
154+async fn abort(cx: &Cx) -> Result<Json<Answer<()>>> {
155+ let id: &str = path_param::<Id>(cx);
156+ let session = match owned_session(cx, id).await {
157+ Ok(session) => session,
158+ Err(refusal) => return Ok(Json(Err(refusal))),
159+ };
160+ let store = app(cx).store.clone();
161+ match store.abort_upload(&session.id).await {
162+ Ok(_) => Ok(Json(Ok(()))),
163+ Err(error) => Ok(Json(Err(store_refusal(error)))),
164+ }
165+}
crates/in-web/tests/http.rsadded+1898 -0
@@ -0,0 +1,1898 @@
1+//! The drive driven the way a browser drives it: real router, real store,
2+//! real session cookie, fake im.
3+//!
4+//! Auth in tests: the OIDC dance cannot run against a live im, so each test
5+//! spins a fake one — a bare TCP server answering `POST /introspect` — and
6+//! signs users in with `in_client::mint_session_cookie` (feature
7+//! `test-seam`). The token<->claims map is per-test, so one test's session
8+//! is meaningless to the next.
9+//!
10+//! New HTTP tests belong in this file rather than a new `tests/*.rs`: one
11+//! test binary links and runs once.
12+
13+use std::collections::HashMap;
14+use std::path::PathBuf;
15+use std::sync::{Arc, Mutex};
16+
17+use http::{HeaderValue, Request, StatusCode, header};
18+use in_core::store::{ShareKind, Store, TursoStore};
19+use in_core::{Config, OidcConfig};
20+use in_web::server::App;
21+use topcoat::asset::{AssetBundle, RouterBuilderAssetExt};
22+use topcoat::cookie::RouterBuilderCookieExt;
23+use topcoat::router::{Body, BodyLimit, Router, RouterBuilderDiscoverExt, to_bytes};
24+use ulid::Ulid;
25+
26+/// The bundle `cargo build -p in-web` + `topcoat asset bundle --bin in-web`
27+/// write next to the crate's own `target/debug`, not next to the test
28+/// binary (which lives in `target/debug/deps`) — `AssetBundle::load` looks
29+/// beside `current_exe` and would miss it, so the path is given explicitly
30+/// instead.
31+fn asset_dir() -> PathBuf {
32+ PathBuf::from(concat!(
33+ env!("CARGO_MANIFEST_DIR"),
34+ "/../../target/debug/assets"
35+ ))
36+}
37+
38+/// A fake im: answers `POST /introspect` from its token map, `{"active":
39+/// false}` for anything it does not know. Bare TCP + hand-rolled HTTP/1.1 —
40+/// just enough for the client's form post.
41+struct FakeIm {
42+ addr: std::net::SocketAddr,
43+ tokens: Arc<Mutex<HashMap<String, serde_json::Value>>>,
44+}
45+
46+impl FakeIm {
47+ async fn spawn() -> Self {
48+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
49+ let addr = listener.local_addr().unwrap();
50+ let tokens: Arc<Mutex<HashMap<String, serde_json::Value>>> =
51+ Arc::new(Mutex::new(HashMap::new()));
52+ let map = tokens.clone();
53+ tokio::spawn(async move {
54+ loop {
55+ let Ok((socket, _)) = listener.accept().await else {
56+ return;
57+ };
58+ let map = map.clone();
59+ tokio::spawn(async move {
60+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
61+ let mut socket = socket;
62+ let mut buf = vec![0u8; 8192];
63+ let mut req = Vec::new();
64+ // One request after another on the same connection:
65+ // closing it after every answer races the client's
66+ // pool, which may hand out the dead socket for the
67+ // next introspection and read that as signed-out.
68+ loop {
69+ let body_start = loop {
70+ let Ok(n) = socket.read(&mut buf).await else {
71+ return;
72+ };
73+ if n == 0 {
74+ return;
75+ }
76+ req.extend_from_slice(&buf[..n]);
77+ if let Some(end) = headers_end(&req) {
78+ let head = String::from_utf8_lossy(&req[..end]).to_string();
79+ let len = content_length(&head);
80+ if req.len() >= end + len {
81+ break end;
82+ }
83+ }
84+ if req.len() > 1_000_000 {
85+ return;
86+ }
87+ };
88+ let head = String::from_utf8_lossy(&req[..body_start]).to_string();
89+ let first = head.lines().next().unwrap_or("").to_string();
90+ // The body may already hold the next pipelined
91+ // request's first bytes; take exactly this one.
92+ let len = content_length(&head);
93+ let body: Vec<u8> = req[body_start..body_start + len].to_vec();
94+ req.drain(..body_start + len);
95+ let answer = answer_for(&map, &first, &body);
96+ let payload = serde_json::to_vec(&answer).unwrap();
97+ let response = format!(
98+ "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n",
99+ payload.len()
100+ );
101+ if socket.write_all(response.as_bytes()).await.is_err() {
102+ return;
103+ }
104+ if socket.write_all(&payload).await.is_err() {
105+ return;
106+ }
107+ }
108+ });
109+ }
110+ });
111+ Self { addr, tokens }
112+ }
113+
114+ fn url(&self) -> String {
115+ format!("http://{}", self.addr)
116+ }
117+}
118+
119+fn headers_end(req: &[u8]) -> Option<usize> {
120+ req.windows(4)
121+ .position(|w| w == b"\r\n\r\n")
122+ .map(|pos| pos + 4)
123+}
124+
125+fn content_length(head: &str) -> usize {
126+ head.lines()
127+ .find_map(|line| {
128+ let (name, value) = line.split_once(':')?;
129+ (name.trim().eq_ignore_ascii_case("content-length"))
130+ .then(|| value.trim().parse().ok())?
131+ })
132+ .unwrap_or(0)
133+}
134+
135+/// Percent-decoding, enough for the opaque tokens these tests mint.
136+fn decode(raw: &str) -> String {
137+ let mut out = String::with_capacity(raw.len());
138+ let mut bytes = raw.as_bytes().iter();
139+ while let Some(&b) = bytes.next() {
140+ if b == b'+' {
141+ out.push(' ');
142+ } else if b == b'%' {
143+ let hi = bytes.next().copied().unwrap_or(b'0');
144+ let lo = bytes.next().copied().unwrap_or(b'0');
145+ let hex = |c: u8| (c as char).to_digit(16).unwrap_or(0) as u8;
146+ out.push((hex(hi) * 16 + hex(lo)) as char);
147+ } else {
148+ out.push(b as char);
149+ }
150+ }
151+ out
152+}
153+
154+fn answer_for(
155+ map: &Arc<Mutex<HashMap<String, serde_json::Value>>>,
156+ request_line: &str,
157+ body: &[u8],
158+) -> serde_json::Value {
159+ let mut head = request_line.split_whitespace();
160+ let is_introspect = head.next() == Some("POST") && head.next() == Some(in_client::introspect_path());
161+ if !is_introspect {
162+ return serde_json::json!({"active": false});
163+ }
164+ let text = String::from_utf8_lossy(body).to_string();
165+ let token = text
166+ .split('&')
167+ .filter_map(|pair| pair.split_once('='))
168+ .find(|(name, _)| *name == "token")
169+ .map(|(_, value)| decode(value));
170+ match token.and_then(|token| map.lock().unwrap().get(&token).cloned()) {
171+ Some(claims) => claims,
172+ None => serde_json::json!({"active": false}),
173+ }
174+}
175+
176+/// A throwaway workspace: its own database file, its own fake im, its own
177+/// router.
178+struct TestApp {
179+ dir: PathBuf,
180+ router: Router,
181+ store: Arc<dyn Store>,
182+ config: Config,
183+ client: in_client::Config,
184+ fake: FakeIm,
185+ stop: tokio::sync::watch::Sender<bool>,
186+}
187+
188+impl TestApp {
189+ async fn build() -> Self {
190+ let dir = std::env::temp_dir().join(format!("in-http-{}", Ulid::new()));
191+ std::fs::create_dir_all(&dir).unwrap();
192+ let db = dir.join("in.db");
193+ let storage = dir.join("storage");
194+ let store: Arc<dyn Store> = Arc::new(
195+ TursoStore::open(db.to_str().unwrap(), Some(storage.as_path()))
196+ .await
197+ .unwrap(),
198+ );
199+ let fake = FakeIm::spawn().await;
200+ let client = in_client::Config {
201+ issuer: fake.url(),
202+ client_id: "in-test".to_string(),
203+ client_secret: "s3cr3t".to_string(),
204+ redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(),
205+ cookie_name: "in_session".to_string(),
206+ cookie_key: [7u8; 32],
207+ };
208+ let config = Config {
209+ database: db.to_str().unwrap().to_string(),
210+ storage,
211+ listen: "127.0.0.1:7655".parse().unwrap(),
212+ live_seconds: 300,
213+ purge_after_days: 30,
214+ default_quota_bytes: 10 * 1024 * 1024 * 1024,
215+ oidc: OidcConfig {
216+ issuer: fake.url(),
217+ client_id: "in-test".to_string(),
218+ client_secret: "s3cr3t".to_string(),
219+ redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(),
220+ },
221+ ignored: Vec::new(),
222+ defaulted: false,
223+ };
224+ let (stop, stopping) = tokio::sync::watch::channel(false);
225+ let router = in_client::mount(
226+ Router::builder()
227+ .discover()
228+ .layer(BodyLimit::max(16 * 1024 * 1024).at("/api/upload"))
229+ .layer(BodyLimit::max(64 * 1024 * 1024).at("/files"))
230+ .cookies()
231+ .assets(
232+ AssetBundle::load_dir(asset_dir())
233+ .expect("run `topcoat asset bundle` before the http suite"),
234+ ),
235+ client.clone(),
236+ )
237+ .app_context(App {
238+ store: store.clone(),
239+ config: config.clone(),
240+ shutdown: in_web::live::Shutdown(stopping),
241+ })
242+ .app_context(in_web::live::LiveWindow(std::time::Duration::from_secs(10)))
243+ .build();
244+ Self {
245+ dir,
246+ router,
247+ store,
248+ config,
249+ client,
250+ fake,
251+ stop,
252+ }
253+ }
254+
255+ /// Provisions the row and mints a session for it, returning the `Cookie`
256+ /// header value to send.
257+ async fn sign_in(&self, sub: &str, email: &str, name: &str) -> String {
258+ let user = self
259+ .store
260+ .provision_user(sub, email, name, self.config.default_quota_bytes)
261+ .await
262+ .unwrap();
263+ let token = format!("tok-{}", Ulid::new());
264+ let exp = time::OffsetDateTime::now_utc() + time::Duration::hours(1);
265+ self.fake.tokens.lock().unwrap().insert(
266+ token.clone(),
267+ serde_json::json!({
268+ "active": true,
269+ "sub": user.oidc_sub,
270+ "email": user.email,
271+ "name": user.display_name,
272+ "exp": exp.unix_timestamp(),
273+ }),
274+ );
275+ let value = in_client::mint_session_cookie(&self.client, &token, exp);
276+ format!("in_session={value}")
277+ }
278+
279+ /// Posts a form the way a hydrated caller does: `Accept:
280+ /// application/json`, no `Referer`. Every mutating `/api/*` route
281+ /// answers `303 See Other` regardless — [`Router::handle`] never follows
282+ /// a redirect, so the answer is read straight off this response.
283+ async fn post(&self, path: &str, cookie: Option<&str>, form: &[(&str, &str)]) -> Answer {
284+ let body = form
285+ .iter()
286+ .map(|(key, value)| format!("{}={}", encode(key), encode(value)))
287+ .collect::<Vec<_>>()
288+ .join("&");
289+ let mut request = Request::builder()
290+ .method("POST")
291+ .uri(path)
292+ .header(header::ACCEPT, "application/json")
293+ .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
294+ if let Some(cookie) = cookie {
295+ request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap());
296+ }
297+ let response = self
298+ .router
299+ .handle(request.body(Body::from(body)).unwrap())
300+ .await;
301+ Answer::from_response(response).await
302+ }
303+
304+ /// Posts JSON the way the upload script does.
305+ async fn post_json(
306+ &self,
307+ path: &str,
308+ cookie: Option<&str>,
309+ value: serde_json::Value,
310+ ) -> Answer {
311+ let mut request = Request::builder()
312+ .method("POST")
313+ .uri(path)
314+ .header(header::ACCEPT, "application/json")
315+ .header(header::CONTENT_TYPE, "application/json");
316+ if let Some(cookie) = cookie {
317+ request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap());
318+ }
319+ let response = self
320+ .router
321+ .handle(request.body(Body::from(value.to_string())).unwrap())
322+ .await;
323+ Answer::from_response(response).await
324+ }
325+
326+ /// Puts raw bytes the way the upload script sends one chunk.
327+ async fn put_bytes(&self, path: &str, cookie: Option<&str>, bytes: &[u8]) -> Answer {
328+ let mut request = Request::builder()
329+ .method("PUT")
330+ .uri(path)
331+ .header(header::ACCEPT, "application/json")
332+ .header(header::CONTENT_TYPE, "application/octet-stream");
333+ if let Some(cookie) = cookie {
334+ request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap());
335+ }
336+ let response = self
337+ .router
338+ .handle(request.body(Body::from(bytes.to_vec())).unwrap())
339+ .await;
340+ Answer::from_response(response).await
341+ }
342+
343+ /// Posts a multipart form the way the drive's upload control does,
344+ /// hand-built rather than pulling in a client crate for it: the fields
345+ /// first, in the order given, then one `file` part per file.
346+ async fn post_multipart(
347+ &self,
348+ path: &str,
349+ cookie: Option<&str>,
350+ fields: &[(&str, &str)],
351+ files: &[(&str, &str, &[u8])],
352+ ) -> Answer {
353+ const BOUNDARY: &str = "in-test-boundary";
354+ let mut body = Vec::new();
355+ for (name, value) in fields {
356+ body.extend_from_slice(
357+ format!(
358+ "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n"
359+ )
360+ .as_bytes(),
361+ );
362+ }
363+ for (filename, content_type, bytes) in files {
364+ body.extend_from_slice(
365+ format!(
366+ "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\nContent-Type: {content_type}\r\n\r\n"
367+ )
368+ .as_bytes(),
369+ );
370+ body.extend_from_slice(bytes);
371+ body.extend_from_slice(b"\r\n");
372+ }
373+ body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes());
374+
375+ let mut request = Request::builder().method("POST").uri(path).header(
376+ header::CONTENT_TYPE,
377+ format!("multipart/form-data; boundary={BOUNDARY}"),
378+ );
379+ if let Some(cookie) = cookie {
380+ request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap());
381+ }
382+ let response = self
383+ .router
384+ .handle(request.body(Body::from(body)).unwrap())
385+ .await;
386+ Answer::from_response(response).await
387+ }
388+
389+ /// Gets a page or a download the way a browser does, raw bytes back
390+ /// untouched — a download's body is not always UTF-8.
391+ async fn get(&self, path: &str, cookie: Option<&str>) -> Raw {
392+ self.get_with(path, cookie, None, None).await
393+ }
394+
395+ /// Like `get`, but with a `Range` header, for the partial-content path.
396+ async fn get_with_range(&self, path: &str, cookie: Option<&str>, range: &str) -> Raw {
397+ self.get_with(path, cookie, Some(range), None).await
398+ }
399+
400+ /// Like `get`, but with `If-None-Match`, for the thumbnail revalidate
401+ /// path.
402+ async fn get_with_if_none_match(&self, path: &str, cookie: Option<&str>, etag: &str) -> Raw {
403+ self.get_with(path, cookie, None, Some(etag)).await
404+ }
405+
406+ async fn get_with(
407+ &self,
408+ path: &str,
409+ cookie: Option<&str>,
410+ range: Option<&str>,
411+ if_none_match: Option<&str>,
412+ ) -> Raw {
413+ let mut request = Request::builder().method("GET").uri(path);
414+ if let Some(cookie) = cookie {
415+ request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap());
416+ }
417+ if let Some(range) = range {
418+ request = request.header(header::RANGE, range);
419+ }
420+ if let Some(if_none_match) = if_none_match {
421+ request = request.header(header::IF_NONE_MATCH, if_none_match);
422+ }
423+ let response = self
424+ .router
425+ .handle(request.body(Body::empty()).unwrap())
426+ .await;
427+ let status = response.status();
428+ let headers = response.headers().clone();
429+ let header = |name| {
430+ headers
431+ .get(name)
432+ .and_then(|value| value.to_str().ok())
433+ .map(str::to_string)
434+ };
435+ let bytes = to_bytes(response.into_body(), usize::MAX)
436+ .await
437+ .unwrap()
438+ .to_vec();
439+ Raw {
440+ status,
441+ content_type: header(header::CONTENT_TYPE),
442+ disposition: header(header::CONTENT_DISPOSITION),
443+ content_range: header(header::CONTENT_RANGE),
444+ accept_ranges: header(header::ACCEPT_RANGES),
445+ cache_control: header(header::CACHE_CONTROL),
446+ etag: header(header::ETAG),
447+ location: header(header::LOCATION),
448+ bytes,
449+ }
450+ }
451+}
452+
453+impl Drop for TestApp {
454+ fn drop(&mut self) {
455+ let _ = self.stop.send(true);
456+ let _ = std::fs::remove_dir_all(&self.dir);
457+ }
458+}
459+/// A mutating call's answer: always a 303, carrying the refusal (or its
460+/// absence) as JSON — the same body a hydrated caller reads.
461+struct Answer {
462+ status: StatusCode,
463+ body: String,
464+ location: Option<String>,
465+}
466+
467+impl Answer {
468+ async fn from_response(response: topcoat::router::response::Response) -> Self {
469+ let status = response.status();
470+ let location = response
471+ .headers()
472+ .get(header::LOCATION)
473+ .and_then(|value| value.to_str().ok())
474+ .map(str::to_string);
475+ let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
476+ Answer {
477+ status,
478+ location,
479+ body: String::from_utf8(bytes.to_vec()).unwrap(),
480+ }
481+ }
482+
483+ fn json(&self) -> serde_json::Value {
484+ serde_json::from_str(&self.body).unwrap()
485+ }
486+
487+ fn refused(&self, code: &str, call: &str) -> bool {
488+ self.status == StatusCode::SEE_OTHER
489+ && self
490+ .location
491+ .as_deref()
492+ .is_some_and(|location| {
493+ location.contains(&format!("refusal={code}")) && location.contains(&format!("on={call}"))
494+ })
495+ }
496+
497+ fn accepted(&self) -> bool {
498+ self.status == StatusCode::SEE_OTHER
499+ && self
500+ .location
501+ .as_deref()
502+ .is_some_and(|location| !location.contains("refusal="))
503+ }
504+}
505+
506+/// A GET answer kept as raw bytes: a page's HTML or a download's file.
507+struct Raw {
508+ status: StatusCode,
509+ content_type: Option<String>,
510+ disposition: Option<String>,
511+ content_range: Option<String>,
512+ accept_ranges: Option<String>,
513+ cache_control: Option<String>,
514+ etag: Option<String>,
515+ location: Option<String>,
516+ bytes: Vec<u8>,
517+}
518+
519+impl Raw {
520+ fn text(&self) -> String {
521+ String::from_utf8(self.bytes.clone()).unwrap()
522+ }
523+}
524+
525+/// Form encoding, enough for the names these tests send.
526+fn encode(raw: &str) -> String {
527+ let mut out = String::with_capacity(raw.len());
528+ for byte in raw.bytes() {
529+ match byte {
530+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
531+ out.push(byte as char)
532+ }
533+ b' ' => out.push('+'),
534+ other => out.push_str(&format!("%{other:02X}")),
535+ }
536+ }
537+ out
538+}
539+
540+/// The 1x1 transparent PNG: the smallest thing the thumbnailer must accept.
541+fn tiny_png() -> Vec<u8> {
542+ vec![
543+ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
544+ 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00,
545+ 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78,
546+ 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00,
547+ 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
548+ ]
549+}
550+
551+/// The newest live folder with this name under this parent, read straight
552+/// off the store.
553+async fn folder_id(app: &TestApp, owner: &str, parent: Option<&str>, name: &str) -> String {
554+ app.store
555+ .list_children(owner, parent)
556+ .await
557+ .unwrap()
558+ .folders
559+ .iter()
560+ .find(|folder| folder.name == name)
561+ .expect("folder was not created")
562+ .id
563+ .clone()
564+}
565+/// The token off a creation redirect's `?created=` pair.
566+fn created_token(location: &str) -> String {
567+ let query = location.split_once('?').map(|(_, query)| query).unwrap_or("");
568+ query
569+ .split('&')
570+ .filter_map(|pair| pair.split_once('='))
571+ .find(|(name, _)| *name == "created")
572+ .map(|(_, value)| value.to_string())
573+ .expect("creation set no token")
574+}
575+
576+async fn file_id(app: &TestApp, owner: &str, name: &str, bytes: &[u8]) -> String {
577+ app.store
578+ .insert_file(owner, None, name, bytes)
579+ .await
580+ .unwrap()
581+ .id
582+}
583+
584+async fn owner_of(app: &TestApp, sub: &str) -> String {
585+ app.store
586+ .provision_user(sub, "x@y.z", "X", app.config.default_quota_bytes)
587+ .await
588+ .unwrap()
589+ .id
590+}
591+
592+#[tokio::test]
593+async fn drive_redirects_without_session() {
594+ let app = TestApp::build().await;
595+ let page = app.get("/drive", None).await;
596+ assert_eq!(page.status, StatusCode::SEE_OTHER);
597+ assert_eq!(page.location.as_deref(), Some("/"));
598+}
599+
600+#[tokio::test]
601+async fn folder_crud_and_cycle_is_refused() {
602+ let app = TestApp::build().await;
603+ let cookie = app.sign_in("sub-crud", "crud@in.test", "Crud").await;
604+ let user = app
605+ .store
606+ .user_by_oidc_sub("sub-crud")
607+ .await
608+ .unwrap()
609+ .unwrap();
610+
611+ let answer = app
612+ .post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "projects")])
613+ .await;
614+ assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
615+ assert_eq!(answer.body, "null", "creating was refused");
616+
617+ let projects = folder_id(&app, &user.id, None, "projects").await;
618+ let answer = app
619+ .post(
620+ "/api/folder/create",
621+ Some(&cookie),
622+ &[("parent_id", &projects), ("name", "sub")],
623+ )
624+ .await;
625+ assert_eq!(answer.body, "null", "creating was refused");
626+ let sub = folder_id(&app, &user.id, Some(&projects), "sub").await;
627+
628+ // Nesting `projects` inside its own descendant is refused, not looped.
629+ let answer = app
630+ .post(
631+ "/api/folder/move",
632+ Some(&cookie),
633+ &[("id", &projects), ("parent_id", &sub)],
634+ )
635+ .await;
636+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
637+ assert!(
638+ answer.body.contains("Forbidden"),
639+ "cycle was not refused: {}",
640+ answer.body
641+ );
642+
643+ // A legal move, a rename and a delete all land clean.
644+ let answer = app
645+ .post("/api/folder/move", Some(&cookie), &[("id", &sub), ("parent_id", "")])
646+ .await;
647+ assert_eq!(answer.body, "null", "moving was refused: {}", answer.body);
648+ let answer = app
649+ .post(
650+ "/api/folder/rename",
651+ Some(&cookie),
652+ &[("id", &sub), ("name", "moved")],
653+ )
654+ .await;
655+ assert_eq!(answer.body, "null", "renaming was refused: {}", answer.body);
656+ let answer = app
657+ .post("/api/folder/delete", Some(&cookie), &[("id", &sub)])
658+ .await;
659+ assert_eq!(answer.body, "null", "deleting was refused: {}", answer.body);
660+
661+ // The drive page names what is left.
662+ let page = app.get("/drive", Some(&cookie)).await;
663+ assert_eq!(page.status, StatusCode::OK);
664+ assert!(page.text().contains("projects"), "drive hides the folder");
665+}
666+
667+#[tokio::test]
668+async fn small_upload_round_trip() {
669+ let app = TestApp::build().await;
670+ let cookie = app.sign_in("sub-small", "small@in.test", "Small").await;
671+ let user = app
672+ .store
673+ .user_by_oidc_sub("sub-small")
674+ .await
675+ .unwrap()
676+ .unwrap();
677+
678+ let bytes = b"hello in";
679+ let answer = app
680+ .post_multipart(
681+ "/files",
682+ Some(&cookie),
683+ &[("folder_id", "")],
684+ &[("hello.txt", "text/plain", bytes)],
685+ )
686+ .await;
687+ assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.location.unwrap_or_default());
688+ assert!(
689+ !answer.location.as_deref().unwrap_or("").contains("refusal="),
690+ "upload was refused: {}",
691+ answer.location.unwrap_or_default()
692+ );
693+
694+ let file = app
695+ .store
696+ .list_children(&user.id, None)
697+ .await
698+ .unwrap()
699+ .files
700+ .into_iter()
701+ .find(|file| file.name == "hello.txt")
702+ .expect("file was not stored");
703+ assert_eq!(file.mime, "text/plain");
704+
705+ let got = app.get(&format!("/file/{}", file.id), Some(&cookie)).await;
706+ assert_eq!(got.status, StatusCode::OK);
707+ assert_eq!(got.bytes, bytes);
708+ assert_eq!(got.accept_ranges.as_deref(), Some("bytes"));
709+ assert!(
710+ got.cache_control.as_deref().unwrap_or("").contains("immutable"),
711+ "missing immutable cache directive"
712+ );
713+}
714+
715+#[tokio::test]
716+async fn chunked_upload_round_trip() {
717+ let app = TestApp::build().await;
718+ let cookie = app.sign_in("sub-chunk", "chunk@in.test", "Chunk").await;
719+ let user = app
720+ .store
721+ .user_by_oidc_sub("sub-chunk")
722+ .await
723+ .unwrap()
724+ .unwrap();
725+
726+ // Two chunks: the 8 MiB server size plus a tail, so the finish assembles
727+ // more than one staged piece.
728+ let total = 8 * 1024 * 1024 + 100;
729+ let mut bytes = Vec::with_capacity(total);
730+ for i in 0..total {
731+ bytes.push((i % 251) as u8);
732+ }
733+
734+ let answer = app
735+ .post_json(
736+ "/api/upload/start",
737+ Some(&cookie),
738+ serde_json::json!({"folder_id": null, "name": "big.bin", "size_bytes": total}),
739+ )
740+ .await;
741+ assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
742+ let started = answer.json();
743+ let session = started["Ok"]["id"].as_str().expect("start was refused").to_string();
744+ assert_eq!(started["Ok"]["chunk_size"].as_u64(), Some(8 * 1024 * 1024));
745+
746+ let answer = app
747+ .put_bytes(
748+ &format!("/api/upload/{session}/0"),
749+ Some(&cookie),
750+ &bytes[..8 * 1024 * 1024],
751+ )
752+ .await;
753+ assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
754+ assert_eq!(answer.json()["Ok"]["received_bytes"].as_u64(), Some(8 * 1024 * 1024));
755+
756+ let answer = app
757+ .put_bytes(&format!("/api/upload/{session}/1"), Some(&cookie), &bytes[8 * 1024 * 1024..])
758+ .await;
759+ assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
760+ assert_eq!(answer.json()["Ok"]["received_bytes"].as_u64(), Some(total as u64));
761+
762+ let answer = app
763+ .post_json(
764+ &format!("/api/upload/{session}/finish"),
765+ Some(&cookie),
766+ serde_json::json!({}),
767+ )
768+ .await;
769+ assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
770+ let file_id = answer.json()["Ok"].as_str().expect("finish was refused").to_string();
771+
772+ let got = app.get(&format!("/file/{file_id}"), Some(&cookie)).await;
773+ assert_eq!(got.status, StatusCode::OK);
774+ assert_eq!(got.bytes, bytes);
775+
776+ let row = app.store.file(&file_id).await.unwrap().unwrap();
777+ assert_eq!(row.owner_id, user.id);
778+}
779+
780+#[tokio::test]
781+async fn range_request_serves_a_slice() {
782+ let app = TestApp::build().await;
783+ let cookie = app.sign_in("sub-range", "range@in.test", "Range").await;
784+ let user = app
785+ .store
786+ .user_by_oidc_sub("sub-range")
787+ .await
788+ .unwrap()
789+ .unwrap();
790+
791+ let bytes = b"hello in";
792+ app.post_multipart(
793+ "/files",
794+ Some(&cookie),
795+ &[("folder_id", "")],
796+ &[("hello.txt", "text/plain", bytes)],
797+ )
798+ .await;
799+ let file = app
800+ .store
801+ .list_children(&user.id, None)
802+ .await
803+ .unwrap()
804+ .files
805+ .into_iter()
806+ .next()
807+ .unwrap();
808+
809+ let slice = app
810+ .get_with_range(&format!("/file/{}", file.id), Some(&cookie), "bytes=0-4")
811+ .await;
812+ assert_eq!(slice.status, StatusCode::PARTIAL_CONTENT);
813+ assert_eq!(slice.bytes, b"hello");
814+ assert_eq!(slice.content_range.as_deref(), Some("bytes 0-4/8"));
815+
816+ let past_end = app
817+ .get_with_range(&format!("/file/{}", file.id), Some(&cookie), "bytes=99-")
818+ .await;
819+ assert_eq!(past_end.status, StatusCode::RANGE_NOT_SATISFIABLE);
820+}
821+
822+#[tokio::test]
823+async fn quota_is_refused_before_and_during_upload() {
824+ let app = TestApp::build().await;
825+ let cookie = app.sign_in("sub-quota", "quota@in.test", "Quota").await;
826+ let user = app
827+ .store
828+ .user_by_oidc_sub("sub-quota")
829+ .await
830+ .unwrap()
831+ .unwrap();
832+ app.store.set_user_quota(&user.id, 10).await.unwrap();
833+
834+ let answer = app
835+ .post_json(
836+ "/api/upload/start",
837+ Some(&cookie),
838+ serde_json::json!({"folder_id": null, "name": "too-big.bin", "size_bytes": 100}),
839+ )
840+ .await;
841+ assert_eq!(answer.status, StatusCode::OK, "{}", answer.body);
842+ assert_eq!(
843+ answer.json()["Err"].as_str(),
844+ Some("QuotaExceeded"),
845+ "start was not refused: {}",
846+ answer.body
847+ );
848+
849+ let answer = app
850+ .post_multipart(
851+ "/files",
852+ Some(&cookie),
853+ &[("folder_id", "")],
854+ &[("twenty.txt", "text/plain", b"12345678901234567890")],
855+ )
856+ .await;
857+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
858+ let location = answer.location.unwrap_or_default();
859+ assert!(
860+ location.contains("quota-exceeded"),
861+ "small upload was not refused: {location}"
862+ );
863+}
864+
865+#[tokio::test]
866+async fn thumbnail_is_served_after_image_upload() {
867+ let app = TestApp::build().await;
868+ let cookie = app.sign_in("sub-thumb", "thumb@in.test", "Thumb").await;
869+ let user = app
870+ .store
871+ .user_by_oidc_sub("sub-thumb")
872+ .await
873+ .unwrap()
874+ .unwrap();
875+
876+ let png = tiny_png();
877+ let answer = app
878+ .post_multipart(
879+ "/files",
880+ Some(&cookie),
881+ &[("folder_id", "")],
882+ &[("dot.png", "image/png", &png)],
883+ )
884+ .await;
885+ assert!(
886+ !answer.location.as_deref().unwrap_or("").contains("refusal="),
887+ "image upload was refused: {}",
888+ answer.location.unwrap_or_default()
889+ );
890+ let file = app
891+ .store
892+ .list_children(&user.id, None)
893+ .await
894+ .unwrap()
895+ .files
896+ .into_iter()
897+ .find(|file| file.name == "dot.png")
898+ .expect("image was not stored");
899+ assert_eq!(file.mime, "image/png");
900+
901+ let thumb = app.get(&format!("/thumb/{}", file.id), Some(&cookie)).await;
902+ assert_eq!(thumb.status, StatusCode::OK, "no thumbnail served");
903+ assert_eq!(thumb.content_type.as_deref(), Some("image/webp"));
904+ assert_eq!(&thumb.bytes[0..4], b"RIFF");
905+ assert_eq!(&thumb.bytes[8..12], b"WEBP");
906+
907+ let etag = thumb.etag.clone().expect("no etag on the thumbnail");
908+ let cached = app
909+ .get_with_if_none_match(&format!("/thumb/{}", file.id), Some(&cookie), &etag)
910+ .await;
911+ assert_eq!(cached.status, StatusCode::NOT_MODIFIED);
912+}
913+
914+#[tokio::test]
915+async fn cross_owner_answers_not_found() {
916+ let app = TestApp::build().await;
917+ let alice = app.sign_in("sub-alice", "alice@in.test", "Alice").await;
918+ let alice_user = app.store.user_by_oidc_sub("sub-alice").await.unwrap().unwrap();
919+ let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
920+
921+ app.post("/api/folder/create", Some(&alice), &[("parent_id", ""), ("name", "hers")])
922+ .await;
923+ let hers = folder_id(&app, &alice_user.id, None, "hers").await;
924+ app.post_multipart(
925+ "/files",
926+ Some(&alice),
927+ &[("folder_id", "")],
928+ &[("hers.txt", "text/plain", b"hers")],
929+ )
930+ .await;
931+ let file = app
932+ .store
933+ .list_children(&alice_user.id, None)
934+ .await
935+ .unwrap()
936+ .files
937+ .into_iter()
938+ .next()
939+ .unwrap();
940+
941+ let bytes = app.get(&format!("/file/{}", file.id), Some(&bob)).await;
942+ assert_eq!(bytes.status, StatusCode::NOT_FOUND);
943+ let thumb = app.get(&format!("/thumb/{}", file.id), Some(&bob)).await;
944+ assert_eq!(thumb.status, StatusCode::NOT_FOUND);
945+ let page = app.get(&format!("/drive?folder={hers}"), Some(&bob)).await;
946+ assert_eq!(page.status, StatusCode::NOT_FOUND);
947+
948+ let answer = app
949+ .post("/api/folder/rename", Some(&bob), &[("id", &hers), ("name", "theirs")])
950+ .await;
951+ assert!(
952+ answer.body.contains("NotFound"),
953+ "cross-owner write was not refused as not-found: {}",
954+ answer.body
955+ );
956+ let answer = app
957+ .post("/api/file/delete", Some(&bob), &[("id", &file.id)])
958+ .await;
959+ assert!(
960+ answer.body.contains("NotFound"),
961+ "cross-owner delete was not refused as not-found: {}",
962+ answer.body
963+ );
964+}
965+
966+#[tokio::test]
967+async fn file_rename_move_and_delete() {
968+ let app = TestApp::build().await;
969+ let cookie = app.sign_in("sub-fops", "fops@in.test", "Fops").await;
970+ let user = app.store.user_by_oidc_sub("sub-fops").await.unwrap().unwrap();
971+
972+ app.post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "box")])
973+ .await;
974+ let boxed = folder_id(&app, &user.id, None, "box").await;
975+ app.post_multipart(
976+ "/files",
977+ Some(&cookie),
978+ &[("folder_id", "")],
979+ &[("note.txt", "text/plain", b"note")],
980+ )
981+ .await;
982+ let file = app
983+ .store
984+ .list_children(&user.id, None)
985+ .await
986+ .unwrap()
987+ .files
988+ .into_iter()
989+ .next()
990+ .unwrap();
991+
992+ let answer = app
993+ .post("/api/file/rename", Some(&cookie), &[("id", &file.id), ("name", "renamed.txt")])
994+ .await;
995+ assert_eq!(answer.body, "null", "renaming was refused: {}", answer.body);
996+ let answer = app
997+ .post("/api/file/move", Some(&cookie), &[("id", &file.id), ("folder_id", &boxed)])
998+ .await;
999+ assert_eq!(answer.body, "null", "moving was refused: {}", answer.body);
1000+ let moved = app.store.file(&file.id).await.unwrap().unwrap();
1001+ assert_eq!(moved.name, "renamed.txt");
1002+ assert_eq!(moved.folder_id.as_deref(), Some(boxed.as_str()));
1003+
1004+ let answer = app.post("/api/file/delete", Some(&cookie), &[("id", &file.id)]).await;
1005+ assert_eq!(answer.body, "null", "deleting was refused: {}", answer.body);
1006+ let trashed = app.store.file(&file.id).await.unwrap().unwrap();
1007+ assert!(trashed.deleted_at.is_some(), "delete did not trash the file");
1008+ // And the bytes answer 404 once trashed.
1009+ let gone = app.get(&format!("/file/{}", file.id), Some(&cookie)).await;
1010+ assert_eq!(gone.status, StatusCode::NOT_FOUND);
1011+}
1012+
1013+#[tokio::test]
1014+async fn upload_abort_and_bad_chunk() {
1015+ let app = TestApp::build().await;
1016+ let cookie = app.sign_in("sub-abort", "abort@in.test", "Abort").await;
1017+
1018+ let answer = app
1019+ .post_json(
1020+ "/api/upload/start",
1021+ Some(&cookie),
1022+ serde_json::json!({"folder_id": null, "name": "never.bin", "size_bytes": 100}),
1023+ )
1024+ .await;
1025+ let session = answer.json()["Ok"]["id"].as_str().unwrap().to_string();
1026+
1027+ // A short piece is a bad chunk, not a short file.
1028+ let answer = app.put_bytes(&format!("/api/upload/{session}/0"), Some(&cookie), b"short").await;
1029+ assert_eq!(
1030+ answer.json()["Err"].as_str(),
1031+ Some("BadChunk"),
1032+ "short chunk was not refused: {}",
1033+ answer.body
1034+ );
1035+
1036+ let answer = app
1037+ .post_json(&format!("/api/upload/{session}/abort"), Some(&cookie), serde_json::json!({}))
1038+ .await;
1039+ assert_eq!(answer.json()["Ok"], serde_json::Value::Null, "{}", answer.body);
1040+
1041+ // The finish after the abort finds an expired session, with the chunks
1042+ // still staged for nothing.
1043+ let answer = app
1044+ .post_json(&format!("/api/upload/{session}/finish"), Some(&cookie), serde_json::json!({}))
1045+ .await;
1046+ assert_eq!(
1047+ answer.json()["Err"].as_str(),
1048+ Some("UploadExpired"),
1049+ "finish after abort was not refused: {}",
1050+ answer.body
1051+ );
1052+}
1053+
1054+#[tokio::test]
1055+async fn forced_download_is_attachment() {
1056+ let app = TestApp::build().await;
1057+ let cookie = app.sign_in("sub-dl", "dl@in.test", "Dl").await;
1058+ let user = app.store.user_by_oidc_sub("sub-dl").await.unwrap().unwrap();
1059+
1060+ app.post_multipart(
1061+ "/files",
1062+ Some(&cookie),
1063+ &[("folder_id", "")],
1064+ &[("readme.txt", "text/plain", b"read me")],
1065+ )
1066+ .await;
1067+ let file = app
1068+ .store
1069+ .list_children(&user.id, None)
1070+ .await
1071+ .unwrap()
1072+ .files
1073+ .into_iter()
1074+ .next()
1075+ .unwrap();
1076+
1077+ let inline = app.get(&format!("/file/{}", file.id), Some(&cookie)).await;
1078+ assert!(
1079+ inline.disposition.as_deref().unwrap_or("").starts_with("inline"),
1080+ "text should render inline: {:?}",
1081+ inline.disposition
1082+ );
1083+ let forced = app.get(&format!("/file/{}?dl=1", file.id), Some(&cookie)).await;
1084+ assert_eq!(forced.status, StatusCode::OK);
1085+ assert!(
1086+ forced.disposition.as_deref().unwrap_or("").starts_with("attachment"),
1087+ "?dl=1 did not force attachment: {:?}",
1088+ forced.disposition
1089+ );
1090+ assert_eq!(forced.bytes, b"read me");
1091+}
1092+
1093+// -- public links (merged from http_d2.rs; one binary per crate) ------------
1094+
1095+#[tokio::test]
1096+async fn link_create_public_view_revoke_gone() {
1097+ let app = TestApp::build().await;
1098+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1099+ let owner = owner_of(&app, "sub-admin").await;
1100+ let file = file_id(&app, &owner, "notes.txt", b"hello in").await;
1101+
1102+ let answer = app
1103+ .post(
1104+ "/api/share/link/create",
1105+ Some(&admin),
1106+ &[
1107+ ("kind", "file"),
1108+ ("target_id", &file),
1109+ ("can_download", "1"),
1110+ ],
1111+ )
1112+ .await;
1113+ assert!(answer.accepted(), "create refused: {:?}", answer.location);
1114+ let token = created_token(answer.location.as_deref().unwrap());
1115+
1116+ // Public: no cookie, the card renders.
1117+ let page = app.get(&format!("/s/{token}"), None).await;
1118+ assert_eq!(page.status, StatusCode::OK, "{}", page.text());
1119+ assert!(page.text().contains("notes.txt"), "{}", page.text());
1120+
1121+ // Public download carries the bytes.
1122+ let bytes = app.get(&format!("/s/{token}?dl=1"), None).await;
1123+ assert_eq!(bytes.status, StatusCode::OK);
1124+ assert_eq!(bytes.bytes, b"hello in");
1125+
1126+ // Revoke: only the id travels; look it up straight off the store.
1127+ let id = app.store.share_links(&owner).await.unwrap()[0].id.clone();
1128+ let answer = app
1129+ .post("/api/share/link/revoke", Some(&admin), &[("id", &id)])
1130+ .await;
1131+ assert!(answer.accepted(), "revoke refused: {:?}", answer.location);
1132+
1133+ let gone = app.get(&format!("/s/{token}"), None).await;
1134+ assert_eq!(gone.status, StatusCode::OK);
1135+ assert!(
1136+ gone.text().contains("no longer works"),
1137+ "revoked link showed: {}",
1138+ gone.text()
1139+ );
1140+}
1141+
1142+#[tokio::test]
1143+async fn expired_link_is_dead() {
1144+ let app = TestApp::build().await;
1145+ let _ = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1146+ let owner = owner_of(&app, "sub-admin").await;
1147+ let file = file_id(&app, &owner, "old.txt", b"old").await;
1148+ let past = time::OffsetDateTime::now_utc() - time::Duration::days(1);
1149+ let created = app
1150+ .store
1151+ .create_share_link(&owner, ShareKind::File, &file, true, Some(past))
1152+ .await
1153+ .unwrap();
1154+ let page = app.get(&format!("/s/{}", created.token), None).await;
1155+ assert_eq!(page.status, StatusCode::OK);
1156+ assert!(
1157+ page.text().contains("no longer works"),
1158+ "expired link showed: {}",
1159+ page.text()
1160+ );
1161+}
1162+
1163+#[tokio::test]
1164+async fn view_only_link_download_is_dead_card() {
1165+ let app = TestApp::build().await;
1166+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1167+ let owner = owner_of(&app, "sub-admin").await;
1168+ let file = file_id(&app, &owner, "secret.txt", b"eyes only").await;
1169+ let answer = app
1170+ .post(
1171+ "/api/share/link/create",
1172+ Some(&admin),
1173+ &[
1174+ ("kind", "file"),
1175+ ("target_id", &file),
1176+ ("can_download", "0"),
1177+ ],
1178+ )
1179+ .await;
1180+ assert!(answer.accepted(), "create refused: {:?}", answer.location);
1181+ let token = created_token(answer.location.as_deref().unwrap());
1182+
1183+ let page = app.get(&format!("/s/{token}"), None).await;
1184+ assert_eq!(page.status, StatusCode::OK, "{}", page.text());
1185+ assert!(page.text().contains("secret.txt"), "{}", page.text());
1186+
1187+ let blocked = app.get(&format!("/s/{token}?dl=1"), None).await;
1188+ assert_eq!(blocked.status, StatusCode::OK, "{}", blocked.text());
1189+ assert!(
1190+ blocked.text().contains("no longer works"),
1191+ "view-only download showed: {}",
1192+ blocked.text()
1193+ );
1194+}
1195+
1196+#[tokio::test]
1197+async fn folder_link_lists_and_serves_children() {
1198+ let app = TestApp::build().await;
1199+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1200+ let owner = owner_of(&app, "sub-admin").await;
1201+ let folder = app
1202+ .store
1203+ .create_folder(&owner, None, "shared")
1204+ .await
1205+ .unwrap();
1206+ app.store
1207+ .insert_file(&owner, Some(&folder.id), "child.txt", b"child bytes")
1208+ .await
1209+ .unwrap();
1210+ let answer = app
1211+ .post(
1212+ "/api/share/link/create",
1213+ Some(&admin),
1214+ &[
1215+ ("kind", "folder"),
1216+ ("target_id", &folder.id),
1217+ ("can_download", "1"),
1218+ ],
1219+ )
1220+ .await;
1221+ assert!(answer.accepted(), "create refused: {:?}", answer.location);
1222+ let token = created_token(answer.location.as_deref().unwrap());
1223+
1224+ let page = app.get(&format!("/s/{token}"), None).await;
1225+ assert_eq!(page.status, StatusCode::OK, "{}", page.text());
1226+ assert!(page.text().contains("child.txt"), "{}", page.text());
1227+
1228+ let child = app
1229+ .store
1230+ .list_children(&owner, Some(&folder.id))
1231+ .await
1232+ .unwrap()
1233+ .files[0]
1234+ .id
1235+ .clone();
1236+ let bytes = app
1237+ .get(
1238+ &format!("/s/{token}?folder={}&file={child}&dl=1", folder.id),
1239+ None,
1240+ )
1241+ .await;
1242+ assert_eq!(bytes.status, StatusCode::OK, "{}", bytes.text());
1243+ assert_eq!(bytes.bytes, b"child bytes");
1244+}
1245+
1246+#[tokio::test]
1247+async fn cross_owner_link_create_is_not_found() {
1248+ let app = TestApp::build().await;
1249+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1250+ let _ = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
1251+ let bob = owner_of(&app, "sub-bob").await;
1252+ let file = file_id(&app, &bob, "bobs.txt", b"bob").await;
1253+ // Ada names Bob's file: answered as not-found, never forbidden.
1254+ let answer = app
1255+ .post(
1256+ "/api/share/link/create",
1257+ Some(&admin),
1258+ &[("kind", "file"), ("target_id", &file), ("can_download", "1")],
1259+ )
1260+ .await;
1261+ assert!(answer.refused("not-found", "create"), "{:?}", answer.location);
1262+}
1263+
1264+// -- per-user shares --------------------------------------------------------
1265+
1266+#[tokio::test]
1267+async fn per_user_share_lands_in_shared_with_me() {
1268+ let app = TestApp::build().await;
1269+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1270+ let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
1271+ let cara = app.sign_in("sub-cara", "cara@in.test", "Cara").await;
1272+ let owner = owner_of(&app, "sub-admin").await;
1273+ let file = file_id(&app, &owner, "joint.txt", b"joint").await;
1274+
1275+ let answer = app
1276+ .post(
1277+ "/api/share/user/add",
1278+ Some(&admin),
1279+ &[
1280+ ("kind", "file"),
1281+ ("target_id", &file),
1282+ ("email", "BOB@in.test"),
1283+ ("can_download", "1"),
1284+ ],
1285+ )
1286+ .await;
1287+ assert!(answer.accepted(), "add refused: {:?}", answer.location);
1288+
1289+ let bobs = app.get("/shared", Some(&bob)).await;
1290+ assert_eq!(bobs.status, StatusCode::OK, "{}", bobs.text());
1291+ assert!(bobs.text().contains("joint.txt"), "{}", bobs.text());
1292+
1293+ let caras = app.get("/shared", Some(&cara)).await;
1294+ assert_eq!(caras.status, StatusCode::OK, "{}", caras.text());
1295+ assert!(!caras.text().contains("joint.txt"), "{}", caras.text());
1296+
1297+ // Unknown addresses are not-found, not a stack.
1298+ let answer = app
1299+ .post(
1300+ "/api/share/user/add",
1301+ Some(&admin),
1302+ &[
1303+ ("kind", "file"),
1304+ ("target_id", &file),
1305+ ("email", "ghost@in.test"),
1306+ ("can_download", "1"),
1307+ ],
1308+ )
1309+ .await;
1310+ assert!(answer.refused("not-found", "add"), "{:?}", answer.location);
1311+
1312+ // Unshare and it leaves Bob's page.
1313+ let answer = app
1314+ .post(
1315+ "/api/share/user/remove",
1316+ Some(&admin),
1317+ &[
1318+ ("kind", "file"),
1319+ ("target_id", &file),
1320+ ("email", "bob@in.test"),
1321+ ],
1322+ )
1323+ .await;
1324+ assert!(answer.accepted(), "remove refused: {:?}", answer.location);
1325+ let bobs = app.get("/shared", Some(&bob)).await;
1326+ assert!(!bobs.text().contains("joint.txt"), "{}", bobs.text());
1327+}
1328+
1329+// -- trash ------------------------------------------------------------------
1330+
1331+#[tokio::test]
1332+async fn trash_restore_purge_empty_flows() {
1333+ let app = TestApp::build().await;
1334+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1335+ let owner = owner_of(&app, "sub-admin").await;
1336+ let one = file_id(&app, &owner, "one.txt", b"one").await;
1337+ let two = file_id(&app, &owner, "two.txt", b"two").await;
1338+ app.store.delete_file(&one).await.unwrap();
1339+ app.store.delete_file(&two).await.unwrap();
1340+
1341+ let page = app.get("/trash", Some(&admin)).await;
1342+ assert_eq!(page.status, StatusCode::OK, "{}", page.text());
1343+ assert!(page.text().contains("one.txt"), "{}", page.text());
1344+ assert!(page.text().contains("two.txt"), "{}", page.text());
1345+
1346+ // Restore one: it leaves the trash and keeps its bytes.
1347+ let answer = app
1348+ .post("/api/trash/restore", Some(&admin), &[("kind", "file"), ("id", &one)])
1349+ .await;
1350+ assert!(answer.accepted(), "restore refused: {:?}", answer.location);
1351+ assert!(
1352+ app.store.file(&one).await.unwrap().unwrap().deleted_at.is_none()
1353+ );
1354+
1355+ // Purge the other: the row and its bytes go.
1356+ let answer = app
1357+ .post("/api/trash/purge", Some(&admin), &[("kind", "file"), ("id", &two)])
1358+ .await;
1359+ assert!(answer.accepted(), "purge refused: {:?}", answer.location);
1360+ assert!(app.store.file(&two).await.unwrap().is_none());
1361+
1362+ // Empty takes the rest.
1363+ let three = file_id(&app, &owner, "three.txt", b"three").await;
1364+ app.store.delete_file(&three).await.unwrap();
1365+ let answer = app.post("/api/trash/empty", Some(&admin), &[]).await;
1366+ assert!(answer.accepted(), "empty refused: {:?}", answer.location);
1367+ assert!(
1368+ app.store
1369+ .list_trash(&owner)
1370+ .await
1371+ .unwrap()
1372+ .files
1373+ .is_empty()
1374+ );
1375+}
1376+
1377+#[tokio::test]
1378+async fn restore_under_trashed_ancestor_is_refused() {
1379+ let app = TestApp::build().await;
1380+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1381+ let owner = owner_of(&app, "sub-admin").await;
1382+ let folder = app
1383+ .store
1384+ .create_folder(&owner, None, "box")
1385+ .await
1386+ .unwrap();
1387+ let file = app
1388+ .store
1389+ .insert_file(&owner, Some(&folder.id), "inbox.txt", b"in")
1390+ .await
1391+ .unwrap();
1392+ app.store.delete_folder(&folder.id).await.unwrap();
1393+
1394+ let answer = app
1395+ .post(
1396+ "/api/trash/restore",
1397+ Some(&admin),
1398+ &[("kind", "file"), ("id", &file.id)],
1399+ )
1400+ .await;
1401+ assert!(
1402+ answer.refused("ancestor-trashed", "restore"),
1403+ "{:?}",
1404+ answer.location
1405+ );
1406+
1407+ // The folder itself restores with its child.
1408+ let answer = app
1409+ .post(
1410+ "/api/trash/restore",
1411+ Some(&admin),
1412+ &[("kind", "folder"), ("id", &folder.id)],
1413+ )
1414+ .await;
1415+ assert!(answer.accepted(), "restore refused: {:?}", answer.location);
1416+}
1417+
1418+#[tokio::test]
1419+async fn folder_purge_destroys_its_tree() {
1420+ let app = TestApp::build().await;
1421+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1422+ let owner = owner_of(&app, "sub-admin").await;
1423+ let folder = app
1424+ .store
1425+ .create_folder(&owner, None, "doomed")
1426+ .await
1427+ .unwrap();
1428+ let file = app
1429+ .store
1430+ .insert_file(&owner, Some(&folder.id), "gone.txt", b"gone")
1431+ .await
1432+ .unwrap();
1433+ app.store.delete_folder(&folder.id).await.unwrap();
1434+
1435+ let answer = app
1436+ .post(
1437+ "/api/trash/purge",
1438+ Some(&admin),
1439+ &[("kind", "folder"), ("id", &folder.id)],
1440+ )
1441+ .await;
1442+ assert!(answer.accepted(), "purge refused: {:?}", answer.location);
1443+ assert!(app.store.folder(&folder.id).await.unwrap().is_none());
1444+ assert!(app.store.file(&file.id).await.unwrap().is_none());
1445+}
1446+
1447+// -- search -----------------------------------------------------------------
1448+
1449+#[tokio::test]
1450+async fn search_scopes_to_owner_and_hides_trashed() {
1451+ let app = TestApp::build().await;
1452+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1453+ let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
1454+ let ada = owner_of(&app, "sub-admin").await;
1455+ let bob_id = owner_of(&app, "sub-bob").await;
1456+ let mine = file_id(&app, &ada, "quarterly report.txt", b"a").await;
1457+ let _ = file_id(&app, &bob_id, "quarterly notes.txt", b"b").await;
1458+ let buried = file_id(&app, &ada, "quarterly draft.txt", b"c").await;
1459+ app.store.delete_file(&buried).await.unwrap();
1460+
1461+ // Empty query is the prompt, not the whole drive.
1462+ let page = app.get("/search", Some(&admin)).await;
1463+ assert_eq!(page.status, StatusCode::OK, "{}", page.text());
1464+ assert!(!page.text().contains("quarterly report.txt"), "{}", page.text());
1465+
1466+ let page = app.get("/search?q=quarterly", Some(&admin)).await;
1467+ assert_eq!(page.status, StatusCode::OK, "{}", page.text());
1468+ assert!(page.text().contains("quarterly report.txt"), "{}", page.text());
1469+ assert!(!page.text().contains("quarterly notes.txt"), "{}", page.text());
1470+ assert!(!page.text().contains("quarterly draft.txt"), "{}", page.text());
1471+ assert!(app.store.file(&mine).await.unwrap().is_some());
1472+
1473+ let page = app.get("/search?q=quarterly", Some(&bob)).await;
1474+ assert!(page.text().contains("quarterly notes.txt"), "{}", page.text());
1475+ assert!(!page.text().contains("quarterly report.txt"), "{}", page.text());
1476+}
1477+
1478+// -- settings ---------------------------------------------------------------
1479+
1480+#[tokio::test]
1481+async fn settings_quota_and_disable_guards() {
1482+ let app = TestApp::build().await;
1483+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1484+ let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
1485+ let bob_id = owner_of(&app, "sub-bob").await;
1486+ let admin_id = owner_of(&app, "sub-admin").await;
1487+
1488+ let page = app.get("/settings", Some(&admin)).await;
1489+ assert_eq!(page.status, StatusCode::OK, "{}", page.text());
1490+ assert!(page.text().contains("ada@in.test"), "{}", page.text());
1491+
1492+ // Admin sets Bob's quota.
1493+ let answer = app
1494+ .post(
1495+ "/api/settings/quota",
1496+ Some(&admin),
1497+ &[("user_id", &bob_id), ("quota_bytes", "123456")],
1498+ )
1499+ .await;
1500+ assert!(answer.accepted(), "quota refused: {:?}", answer.location);
1501+ assert_eq!(app.store.user(&bob_id).await.unwrap().unwrap().quota_bytes, 123456);
1502+
1503+ // A non-admin is refused the same call.
1504+ let answer = app
1505+ .post(
1506+ "/api/settings/quota",
1507+ Some(&bob),
1508+ &[("user_id", &bob_id), ("quota_bytes", "999")],
1509+ )
1510+ .await;
1511+ assert!(answer.refused("forbidden", "quota"), "{:?}", answer.location);
1512+
1513+ // Disabling yourself is refused; disabling Bob signs him out.
1514+ let answer = app
1515+ .post(
1516+ "/api/settings/disable",
1517+ Some(&admin),
1518+ &[("user_id", &admin_id), ("disabled", "1")],
1519+ )
1520+ .await;
1521+ assert!(answer.refused("forbidden", "disable"), "{:?}", answer.location);
1522+
1523+ let answer = app
1524+ .post(
1525+ "/api/settings/disable",
1526+ Some(&admin),
1527+ &[("user_id", &bob_id), ("disabled", "1")],
1528+ )
1529+ .await;
1530+ assert!(answer.accepted(), "disable refused: {:?}", answer.location);
1531+ let page = app.get("/settings", Some(&bob)).await;
1532+ assert_eq!(page.status, StatusCode::OK, "{}", page.text());
1533+ assert!(
1534+ !page.text().contains("bob@in.test"),
1535+ "disabled account still served: {}",
1536+ page.text()
1537+ );
1538+}
1539+
1540+#[tokio::test]
1541+async fn signed_out_mutations_ask_to_sign_in() {
1542+ let app = TestApp::build().await;
1543+ for (path, call, form) in [
1544+ (
1545+ "/api/share/link/create",
1546+ "create",
1547+ &[("kind", "file"), ("target_id", "x"), ("can_download", "1")][..],
1548+ ),
1549+ ("/api/share/link/revoke", "revoke", &[("id", "x")][..]),
1550+ (
1551+ "/api/share/user/add",
1552+ "add",
1553+ &[("kind", "file"), ("target_id", "x"), ("email", "a@b.c")][..],
1554+ ),
1555+ (
1556+ "/api/trash/restore",
1557+ "restore",
1558+ &[("kind", "file"), ("id", "x")][..],
1559+ ),
1560+ ("/api/trash/empty", "empty", &[][..]),
1561+ (
1562+ "/api/settings/quota",
1563+ "quota",
1564+ &[("user_id", "x"), ("quota_bytes", "1")][..],
1565+ ),
1566+ ] {
1567+ let answer = app.post(path, None, form).await;
1568+ assert!(
1569+ answer.refused("sign-in-first", call),
1570+ "{path}: {:?}",
1571+ answer.location
1572+ );
1573+ }
1574+ // A never-real token is the dead card, not a stack.
1575+ let page = app.get("/s/never-real-token", None).await;
1576+ assert_eq!(page.status, StatusCode::OK);
1577+ assert!(page.text().contains("no longer works"), "{}", page.text());
1578+}
1579+
1580+#[tokio::test]
1581+async fn empty_file_upload_round_trip() {
1582+ let app = TestApp::build().await;
1583+ let cookie = app.sign_in("sub-empty", "empty@in.test", "Empty").await;
1584+ let user = app
1585+ .store
1586+ .user_by_oidc_sub("sub-empty")
1587+ .await
1588+ .unwrap()
1589+ .unwrap();
1590+
1591+ let answer = app
1592+ .post_multipart(
1593+ "/files",
1594+ Some(&cookie),
1595+ &[("folder_id", "")],
1596+ &[("empty.txt", "text/plain", &[])],
1597+ )
1598+ .await;
1599+ assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.location.clone().unwrap_or_default());
1600+ assert!(
1601+ !answer.location.as_deref().unwrap_or("").contains("refusal="),
1602+ "empty upload was refused: {}",
1603+ answer.location.clone().unwrap_or_default()
1604+ );
1605+
1606+ let file = app
1607+ .store
1608+ .list_children(&user.id, None)
1609+ .await
1610+ .unwrap()
1611+ .files
1612+ .into_iter()
1613+ .find(|file| file.name == "empty.txt")
1614+ .expect("empty file was not stored");
1615+ assert_eq!(file.size_bytes, 0);
1616+
1617+ let got = app.get(&format!("/file/{}", file.id), Some(&cookie)).await;
1618+ assert_eq!(got.status, StatusCode::OK);
1619+ assert!(got.bytes.is_empty(), "expected 0 bytes, got {}", got.bytes.len());
1620+}
1621+
1622+// -- share review regressions (FullSilkworm) ------------------------------------
1623+
1624+#[tokio::test]
1625+async fn view_only_download_matches_dead_token() {
1626+ let app = TestApp::build().await;
1627+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1628+ let owner = owner_of(&app, "sub-admin").await;
1629+ let file = file_id(&app, &owner, "quiet.txt", b"quiet").await;
1630+ let answer = app
1631+ .post(
1632+ "/api/share/link/create",
1633+ Some(&admin),
1634+ &[
1635+ ("kind", "file"),
1636+ ("target_id", &file),
1637+ ("can_download", "0"),
1638+ ],
1639+ )
1640+ .await;
1641+ assert!(answer.accepted(), "create refused: {:?}", answer.location);
1642+ let token = created_token(answer.location.as_deref().unwrap());
1643+
1644+ // A view-only download attempt is the dead card — the same answer as a
1645+ // token that never existed, so the surface never says which tokens exist.
1646+ let blocked = app.get(&format!("/s/{token}?dl=1"), None).await;
1647+ let dead = app.get("/s/never-real-token", None).await;
1648+ assert_eq!(blocked.status, dead.status, "{}", blocked.text());
1649+ assert_eq!(blocked.status, StatusCode::OK, "{}", blocked.text());
1650+ assert!(
1651+ blocked.text().contains("no longer works"),
1652+ "view-only download showed: {}",
1653+ blocked.text()
1654+ );
1655+ assert!(
1656+ dead.text().contains("no longer works"),
1657+ "dead token showed: {}",
1658+ dead.text()
1659+ );
1660+}
1661+
1662+#[tokio::test]
1663+async fn malformed_expiry_is_forbidden() {
1664+ let app = TestApp::build().await;
1665+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1666+ let owner = owner_of(&app, "sub-admin").await;
1667+ let file = file_id(&app, &owner, "lease.txt", b"lease").await;
1668+ // Non-numeric, zero and negative values must not mint a link — and must
1669+ // never silently mint a never-expiring one.
1670+ for raw in ["not-a-number", "0", "-2", "1.5"] {
1671+ let answer = app
1672+ .post(
1673+ "/api/share/link/create",
1674+ Some(&admin),
1675+ &[
1676+ ("kind", "file"),
1677+ ("target_id", &file),
1678+ ("can_download", "1"),
1679+ ("expires_in_days", raw),
1680+ ],
1681+ )
1682+ .await;
1683+ assert!(
1684+ answer.refused("forbidden", "create"),
1685+ "{raw:?}: {:?}",
1686+ answer.location
1687+ );
1688+ }
1689+ assert!(
1690+ app.store.share_links(&owner).await.unwrap().is_empty(),
1691+ "a refused mint left a link behind"
1692+ );
1693+ // A positive value still mints an expiring link; an empty one still means
1694+ // no expiry.
1695+ let answer = app
1696+ .post(
1697+ "/api/share/link/create",
1698+ Some(&admin),
1699+ &[
1700+ ("kind", "file"),
1701+ ("target_id", &file),
1702+ ("can_download", "1"),
1703+ ("expires_in_days", "30"),
1704+ ],
1705+ )
1706+ .await;
1707+ assert!(answer.accepted(), "good expiry refused: {:?}", answer.location);
1708+ let links = app.store.share_links(&owner).await.unwrap();
1709+ assert_eq!(links.len(), 1);
1710+ assert!(
1711+ links[0].expires_at.is_some(),
1712+ "a 30-day link carries no expiry"
1713+ );
1714+ let answer = app
1715+ .post(
1716+ "/api/share/link/create",
1717+ Some(&admin),
1718+ &[
1719+ ("kind", "file"),
1720+ ("target_id", &file),
1721+ ("can_download", "1"),
1722+ ("expires_in_days", ""),
1723+ ],
1724+ )
1725+ .await;
1726+ assert!(answer.accepted(), "empty expiry refused: {:?}", answer.location);
1727+ let links = app.store.share_links(&owner).await.unwrap();
1728+ assert_eq!(links.len(), 2);
1729+ assert!(
1730+ links.iter().any(|link| link.expires_at.is_none()),
1731+ "an empty expiry should mean no expiry"
1732+ );
1733+}
1734+
1735+#[tokio::test]
1736+async fn unshare_trashed_target_still_revokes() {
1737+ let app = TestApp::build().await;
1738+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1739+ let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await;
1740+ let owner = owner_of(&app, "sub-admin").await;
1741+ let file = file_id(&app, &owner, "doomed.txt", b"doomed").await;
1742+ let answer = app
1743+ .post(
1744+ "/api/share/user/add",
1745+ Some(&admin),
1746+ &[
1747+ ("kind", "file"),
1748+ ("target_id", &file),
1749+ ("email", "bob@in.test"),
1750+ ("can_download", "1"),
1751+ ],
1752+ )
1753+ .await;
1754+ assert!(answer.accepted(), "add refused: {:?}", answer.location);
1755+ let bobs = app.get("/shared", Some(&bob)).await;
1756+ assert!(bobs.text().contains("doomed.txt"), "{}", bobs.text());
1757+
1758+ // Trash the target: unsharing must still go through for the owner.
1759+ app.store.delete_file(&file).await.unwrap();
1760+ let answer = app
1761+ .post(
1762+ "/api/share/user/remove",
1763+ Some(&admin),
1764+ &[("kind", "file"), ("target_id", &file), ("email", "bob@in.test")],
1765+ )
1766+ .await;
1767+ assert!(answer.accepted(), "remove refused: {:?}", answer.location);
1768+ // The grant row is really gone: restoring the file does not bring the
1769+ // share back to Bob's page.
1770+ app.store.restore_file(&file).await.unwrap();
1771+ let bobs = app.get("/shared", Some(&bob)).await;
1772+ assert!(!bobs.text().contains("doomed.txt"), "{}", bobs.text());
1773+}
1774+
1775+#[tokio::test]
1776+async fn view_only_public_thumb_serves_webp() {
1777+ let app = TestApp::build().await;
1778+ let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await;
1779+ let owner = owner_of(&app, "sub-admin").await;
1780+ let png = tiny_png();
1781+ let answer = app
1782+ .post_multipart(
1783+ "/files",
1784+ Some(&admin),
1785+ &[("folder_id", "")],
1786+ &[("dot.png", "image/png", &png)],
1787+ )
1788+ .await;
1789+ assert!(
1790+ !answer.location.as_deref().unwrap_or("").contains("refusal="),
1791+ "image upload was refused: {}",
1792+ answer.location.unwrap_or_default()
1793+ );
1794+ let file = app
1795+ .store
1796+ .list_children(&owner, None)
1797+ .await
1798+ .unwrap()
1799+ .files
1800+ .into_iter()
1801+ .find(|file| file.name == "dot.png")
1802+ .expect("image was not stored");
1803+ let answer = app
1804+ .post(
1805+ "/api/share/link/create",
1806+ Some(&admin),
1807+ &[
1808+ ("kind", "file"),
1809+ ("target_id", &file.id),
1810+ ("can_download", "0"),
1811+ ],
1812+ )
1813+ .await;
1814+ assert!(answer.accepted(), "create refused: {:?}", answer.location);
1815+ let token = created_token(answer.location.as_deref().unwrap());
1816+ // The card previews through the thumb route, never the raw bytes.
1817+ let page = app.get(&format!("/s/{token}"), None).await;
1818+ assert_eq!(page.status, StatusCode::OK, "{}", page.text());
1819+ assert!(
1820+ page.text().contains("?thumb=1"),
1821+ "card previews off nothing public: {}",
1822+ page.text()
1823+ );
1824+ assert!(
1825+ !page.text().contains("?dl=1"),
1826+ "card must not point at the raw bytes: {}",
1827+ page.text()
1828+ );
1829+
1830+ // View-only still grants the 512px preview: webp bytes, etag revalidates.
1831+ let thumb = app.get(&format!("/s/{token}?thumb=1"), None).await;
1832+ assert_eq!(thumb.status, StatusCode::OK, "{}", thumb.text());
1833+ assert_eq!(thumb.content_type.as_deref(), Some("image/webp"));
1834+ assert_eq!(&thumb.bytes[0..4], b"RIFF");
1835+ assert_eq!(&thumb.bytes[8..12], b"WEBP");
1836+ let etag = thumb.etag.clone().expect("no etag on the public thumbnail");
1837+ let cached = app
1838+ .get_with_if_none_match(&format!("/s/{token}?thumb=1"), None, &etag)
1839+ .await;
1840+ assert_eq!(cached.status, StatusCode::NOT_MODIFIED);
1841+
1842+ // The full bytes stay behind the download gate even so.
1843+ let blocked = app.get(&format!("/s/{token}?dl=1"), None).await;
1844+ assert_eq!(blocked.status, StatusCode::OK, "{}", blocked.text());
1845+ assert!(
1846+ blocked.text().contains("no longer works"),
1847+ "view-only download showed: {}",
1848+ blocked.text()
1849+ );
1850+
1851+ // A dead token's thumb is the dead card, not a stack.
1852+ let dead = app.get("/s/never-real-token?thumb=1", None).await;
1853+ assert_eq!(dead.status, StatusCode::OK, "{}", dead.text());
1854+ assert!(
1855+ dead.text().contains("no longer works"),
1856+ "dead thumb showed: {}",
1857+ dead.text()
1858+ );
1859+}
1860+
1861+#[tokio::test]
1862+async fn a_refused_upload_carries_a_well_formed_query() {
1863+ let app = TestApp::build().await;
1864+ let cookie = app.sign_in("sub-dupe", "dupe@in.test", "Dupe").await;
1865+
1866+ // One file in, then the same name again: the refusal redirect must join
1867+ // the feedback pairs with `?`, not `&` — a `/drive&refusal=...` Location
1868+ // is a different path entirely and 404s (observed live).
1869+ for _ in 0..2 {
1870+ app.post_multipart(
1871+ "/files",
1872+ Some(&cookie),
1873+ &[("folder_id", "")],
1874+ &[("same.txt", "text/plain", b"first or second")],
1875+ )
1876+ .await;
1877+ }
1878+ let answer = app
1879+ .post_multipart(
1880+ "/files",
1881+ Some(&cookie),
1882+ &[("folder_id", "")],
1883+ &[("same.txt", "text/plain", b"third")],
1884+ )
1885+ .await;
1886+ let location = answer.location.expect("no Location on the refusal");
1887+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
1888+ assert!(
1889+ location.starts_with("/drive?"),
1890+ "refusal Location was: {location}"
1891+ );
1892+ assert!(location.contains("refusal=name-taken"), "{location}");
1893+
1894+ // And the browser that follows it lands on the drive page, not the 404.
1895+ let page = app.get(&location, Some(&cookie)).await;
1896+ assert_eq!(page.status, StatusCode::OK, "{}", page.text());
1897+ assert!(page.text().contains("already taken"), "{}", page.text());
1898+}
public/.gitkeepadded+0 -0
style/_instrument.scssadded+283 -0
@@ -0,0 +1,283 @@
1+// Instrument UI skin — dense, neutral-cool, chrome-quiet. Tokens live in
2+// main.scss; skin-specific overrides and component rules for
3+// [data-ui="instrument"] land here.
4+//
5+// Cascade note: this file is `@use`d at the TOP of main.scss, before every
6+// component rule, so any override must out-specify its base rule rather than
7+// rely on source order. Everything below sits inside the wrapper block, which
8+// adds one attribute selector (0,1,0) to every rule.
9+
10+[data-ui="instrument"] {
11+
12+ // --- Instrument skin: chrome (topbar, nav) ---------------------------------
13+
14+ // 44px chrome strip.
15+ .topbar {
16+ height: 44px;
17+ }
18+
19+ .filterbar {
20+ height: 40px;
21+ }
22+
23+ // Active nav underlines in accent, not ink.
24+ .topbar-nav-on {
25+ box-shadow: inset 0 -2px 0 var(--accent);
26+ }
27+
28+ // Active detail tab underlines in accent, same idiom as the topbar nav.
29+ .detail-tab-on {
30+ box-shadow: inset 0 -2px 0 var(--accent);
31+ }
32+
33+ // --- Instrument skin: board (ruled columns) --------------------------------
34+
35+ // Columns are not floating wells; they are panels separated by hairline
36+ // rules. Cards keep surface/1px border/radius-3/no-shadow — the instrument
37+ // tokens already supply all four, so .card itself needs no override.
38+ .board-columns {
39+ gap: 0;
40+ }
41+
42+ .column {
43+ background: transparent;
44+ border-right: 1px solid var(--border);
45+
46+ &:last-child {
47+ border-right: none;
48+ }
49+ }
50+
51+ // --- Instrument skin: chips (status LEDs) ----------------------------------
52+
53+ // Tint fills go away; a chip is its colored text plus a 6px LED square.
54+ // Per-variant colors (.chip-overdue etc.) survive untouched — this rule
55+ // never declares `color`.
56+ .chip {
57+ background: transparent;
58+ font-family: var(--font-mono);
59+ font-size: 10px;
60+ font-weight: 500;
61+ letter-spacing: 0.08em;
62+ text-transform: uppercase;
63+
64+ &::before {
65+ content: "";
66+ width: 6px;
67+ height: 6px;
68+ margin-right: 6px;
69+ flex: none;
70+ background: currentColor;
71+ }
72+ }
73+
74+ // --- Instrument skin: avatars (squares) ------------------------------------
75+
76+ // Circles become 18px squares; the 2px overlap ring is gone, so assignees
77+ // butt closer. 2px is intentional (below the 3px radius token) — squares
78+ // must not read as chips.
79+ .avatar {
80+ width: 18px;
81+ height: 18px;
82+ border-radius: 2px;
83+ border: none;
84+ }
85+
86+ .avatar + .avatar {
87+ margin-left: -4px;
88+ }
89+
90+ // The upload veil squares off with the avatar under it.
91+ .avatar-upload::after {
92+ border-radius: 2px;
93+ }
94+
95+ // Keep the empty-assignee slot's dashed outline, which the border: none
96+ // above would otherwise silence.
97+ .avatar-none {
98+ border: 1px dashed var(--border-strong);
99+ background: transparent;
100+ }
101+
102+ // --- Instrument skin: fields & controls -------------------------------------
103+
104+ // The primary action is an outlined target, not a filled one.
105+ .primary {
106+ background: transparent;
107+ border: 1px solid var(--accent-border);
108+ color: var(--accent);
109+
110+ &:hover {
111+ background: transparent;
112+ border-color: var(--accent);
113+ color: var(--accent);
114+ }
115+ }
116+
117+ // Quiet stays outline-muted; only the fill drops so fields and buttons
118+ // share one flat ground.
119+ .quiet {
120+ background: transparent;
121+ }
122+
123+ // --- Instrument skin: mono metadata idiom -----------------------------------
124+
125+ // Timestamps, card meta and member statuses join .field-label/.detail-label
126+ // in tracked uppercase mono. (Emails stay sentence-case — .member-address
127+ // keeps its mono but gains no uppercase; uppercase addresses hurt reading.)
128+ .comment-when {
129+ font-size: 10px;
130+ letter-spacing: 0.08em;
131+ text-transform: uppercase;
132+ }
133+
134+ .card-comments,
135+ .card-deadline {
136+ letter-spacing: 0.08em;
137+ text-transform: uppercase;
138+ }
139+
140+ .member-status {
141+ font-family: var(--font-mono);
142+ font-size: 10px;
143+ letter-spacing: 0.08em;
144+ text-transform: uppercase;
145+ }
146+
147+ .member-you {
148+ font-family: var(--font-mono);
149+ font-size: 10px;
150+ letter-spacing: 0.08em;
151+ text-transform: uppercase;
152+ border-radius: var(--radius-sm);
153+ }
154+
155+ // --- Instrument skin: density & spacing --------------------------------------
156+
157+ // (Deliberately sparse: density lives in the chrome heights, the gapless
158+ // ruled columns and the square avatars above. Token values — control
159+ // heights, radii, shadows — already carry the rest.)
160+
161+ // --- Instrument skin: activity log -----------------------------------------
162+
163+ .log-row {
164+ padding: 6px 2px;
165+ }
166+
167+ // --- Instrument skin: settings rail -----------------------------------------
168+
169+ .settings-sections { width: 200px; }
170+
171+ .settings-section-link {
172+ font-size: 13px;
173+ letter-spacing: normal;
174+ text-transform: none;
175+
176+ &.active {
177+ background: var(--row-hover);
178+ box-shadow: inset 2px 0 0 var(--accent);
179+ }
180+ }
181+
182+}
183+
184+// -- task detail: 560px side panel over the board ----------------------------
185+// The board stays live underneath; the panel docks right and dims the board
186+// through the scrim. The base `.modal-task` only fixes the frame — this rule
187+// moves it out of the centered flow and gives it the panel geometry.
188+[data-ui="instrument"] .modal-scrim:has(> .modal-task) {
189+ background: color-mix(in srgb, var(--scrim) 65%, transparent);
190+ justify-content: flex-end;
191+ padding: 0;
192+}
193+
194+[data-ui="instrument"] .modal-task {
195+ position: fixed;
196+ top: 0;
197+ right: 0;
198+ bottom: 0;
199+ width: 560px;
200+ max-width: 100%;
201+ max-height: none;
202+ background: var(--surface);
203+ border: none;
204+ border-radius: 0;
205+ box-shadow: var(--shadow-3);
206+}
207+
208+// Header: key + title left (stacked), Esc and the close cross right. The
209+// header's own state chip is suppressed — status lives in the body's field
210+// grid. The tab strip sits directly under it, so the header itself carries
211+// no bottom rule any more.
212+[data-ui="instrument"] .modal-task .detail-head {
213+ align-items: flex-start;
214+ gap: 12px;
215+ padding: 14px 16px;
216+}
217+
218+[data-ui="instrument"] .detail-tabs {
219+ padding: 0 16px;
220+}
221+
222+[data-ui="instrument"] .detail-state,
223+[data-ui="instrument"] .detail-board {
224+ display: none;
225+}
226+
227+[data-ui="instrument"] .detail-body {
228+ flex: 1;
229+ min-height: 0;
230+ overflow-y: auto;
231+ padding: 20px;
232+}
233+
234+[data-ui="instrument"] .detail-title {
235+ font-size: 20px;
236+}
237+
238+// The fields ride in the masthead, so they carry its inset themselves.
239+[data-ui="instrument"] .detail-fields {
240+ gap: 10px;
241+ padding: 0 16px 14px;
242+ margin-top: 14px;
243+}
244+
245+// Blocks run down the panel body below the title; only the composer pins.
246+[data-ui="instrument"] .detail-block {
247+ margin-top: 18px;
248+}
249+
250+// Pinned at the panel's foot, wearing the composer's rule and padding: the
251+// two are the same kind of thing, a bar the body scrolls beneath.
252+[data-ui="instrument"] .detail-foot {
253+ padding: 14px 20px;
254+ margin-top: 0;
255+ border-top: 1px solid var(--border);
256+}
257+
258+// Composer is the last child of `.modal-task` (outside `.detail-body`), so on
259+// the flex panel it stays pinned while the body above scrolls.
260+[data-ui="instrument"] .comment-composer {
261+ flex: none;
262+ padding: 14px 20px;
263+ border-top: 1px solid var(--border);
264+}
265+// -- mobile (narrow viewports) -----------------------------------------------
266+// Geometry that the skin sets with [data-ui]-prefixed rules and that the
267+// shared mobile layer in main.scss cannot out-specify.
268+@media (max-width: 620px) {
269+ // The rail is a strip; its width is a desktop's and its active rule runs
270+ // under the section, not beside it.
271+ [data-ui="instrument"] .settings-sections { width: auto; }
272+
273+ [data-ui="instrument"] .settings-section-link.active {
274+ background: none;
275+ box-shadow: inset 0 -2px 0 var(--accent);
276+ }
277+
278+ // The filterbar wraps at this width; the skin's fixed 40px would clip it.
279+ [data-ui="instrument"] .filterbar { height: auto; }
280+
281+ // A phone carries no Escape key; the hint is chrome for a keyboard.
282+ [data-ui="instrument"] .modal-task .detail-esc { display: none; }
283+}
style/_ledger.scssadded+503 -0
@@ -0,0 +1,503 @@
1+// Ledger UI skin — warm paper, hairline rules, serif display (Newsreader).
2+// Tokens live in main.scss; skin-specific overrides and component rules for
3+// [data-ui="ledger"] land here.
4+
5+// Every selector carries the [data-ui="ledger"] prefix (one nested block
6+// below). That attribute+class specificity outranks the same-name class
7+// rules in main.scss, so the order of the @use never matters.
8+
9+[data-ui="ledger"] {
10+ // --- Ledger skin: typography -------------------------------------------------
11+
12+ // The display face carries named things: page/board/panel titles, task
13+ // titles, people. Keys, dates, counts and labels stay IBM Plex Mono 10px
14+ // uppercase — main.scss's metadata idiom is left alone, and so is the
15+ // wordmark, which is the same lockup on both skins.
16+ .auth-title,
17+ .settings-title,
18+ .detail-title,
19+ .title-input,
20+ .panel-title,
21+ .column-name,
22+ .card-title,
23+ .member-name {
24+ font-family: var(--font-display);
25+ }
26+
27+ .settings-title { font-size: 22px; }
28+ .panel-title { font-size: 15px; }
29+ .card-title { font-size: 16px; }
30+
31+ // --- Ledger skin: rules & ornaments (no boxes) -------------------------------
32+
33+ // Panels and cards give up their chrome: the paper itself is the surface
34+ // and a hairline separates entries. Section heads sit on a 2px ink rule.
35+ .panel {
36+ background: transparent;
37+ border: none;
38+ box-shadow: none;
39+ }
40+
41+ .panel-head {
42+ border-bottom: 2px solid var(--rule-strong);
43+ padding: 0 0 10px;
44+ }
45+
46+ .auth-card {
47+ background: transparent;
48+ border: none;
49+ box-shadow: none;
50+ padding: 0;
51+ }
52+
53+ .column {
54+ background: transparent;
55+ border-radius: 0;
56+ }
57+
58+ .column-empty {
59+ background: transparent;
60+ border-color: var(--border-soft);
61+ }
62+
63+ .column-head {
64+ padding: 2px 4px 8px;
65+ border-bottom: 2px solid var(--rule-strong);
66+ }
67+
68+ // A card is an entry in the ledger: no box, a hairline under it, and the
69+ // hover darkens that rule instead of flooding a background.
70+ .card {
71+ background: transparent;
72+ border: none;
73+ border-bottom: 1px solid var(--border);
74+ border-radius: 0;
75+ box-shadow: none;
76+ padding: 12px 2px 14px 2px;
77+ transition: border-color var(--dur-fast) var(--ease);
78+
79+ &:hover {
80+ background: transparent;
81+ border-bottom-color: var(--rule-strong);
82+ }
83+ }
84+
85+ .card-done {
86+ background: transparent;
87+
88+ .card-title { text-decoration: line-through; }
89+ }
90+
91+ // Ledger entries stack into a continuous ruled column — no gaps between rows.
92+ .column-cards {
93+ gap: 0;
94+ }
95+
96+ .rule-row {
97+ background: transparent;
98+ border: none;
99+ border-bottom: 1px solid var(--border);
100+ border-radius: 0;
101+ padding: 14px 2px;
102+
103+ &-off { background: transparent; }
104+ }
105+
106+ .tag-row {
107+ background: transparent;
108+ border: none;
109+ border-bottom: 1px solid var(--border);
110+ border-radius: 0;
111+ padding: 14px 2px;
112+ }
113+
114+ // Activity log reads as a ruled ledger column too: no boxes, the actor
115+ // named in the display face like .member-name.
116+ .log-row {
117+ border-bottom: 1px solid var(--border);
118+ }
119+
120+ .log-actor {
121+ font-family: var(--font-display);
122+ }
123+
124+ // --- Ledger skin: baseline header --------------------------------------------
125+
126+ .topbar {
127+ background: transparent;
128+ border-bottom: 1px solid var(--rule-strong);
129+ }
130+
131+ .topbar-nav-on {
132+ border-bottom: 2px solid var(--rule-strong);
133+ box-shadow: none;
134+ }
135+
136+ .detail-tab-on {
137+ border-bottom: 2px solid var(--ink);
138+ box-shadow: none;
139+ }
140+
141+ // --- Ledger skin: chips as inked text ----------------------------------------
142+
143+ .chip {
144+ display: inline-flex;
145+ align-items: baseline;
146+ height: auto;
147+ padding: 0;
148+ background: transparent;
149+ border: none;
150+ border-bottom: 1px dotted currentColor;
151+ border-radius: 0;
152+ font-family: var(--font-mono);
153+ font-size: 10px;
154+ font-weight: 500;
155+ letter-spacing: 0.08em;
156+ text-transform: uppercase;
157+
158+ // The tint fills and boxes go; the hue stays on as the ink color.
159+ &-overdue,
160+ &-blocked,
161+ &-role,
162+ &-admin,
163+ &-connected,
164+ &-off { background: transparent; }
165+
166+ &-role,
167+ &-admin { border: none; border-bottom: 1px dotted currentColor; }
168+
169+ &-role,
170+ &-admin,
171+ &-connected,
172+ &-off { text-transform: uppercase; }
173+ }
174+
175+ // --- Ledger skin: controls -----------------------------------------------------
176+
177+ // Outlined-ink controls; the primary action is set in solid ink with paper
178+ // text, inverting cleanly in the dark set because both sides are tokens.
179+ .primary {
180+ background: var(--ink);
181+ border-color: var(--ink);
182+ color: var(--bg);
183+
184+ &:hover {
185+ background: var(--ink-soft);
186+ border-color: var(--ink-soft);
187+ color: var(--bg);
188+ }
189+ }
190+
191+ .auth-submit,
192+ .edit-save,
193+ .comment-post {
194+ background: var(--ink);
195+ color: var(--bg);
196+ }
197+
198+ .auth-submit:hover,
199+ .edit-save:hover,
200+ .comment-post:hover {
201+ background: var(--ink-soft);
202+ }
203+
204+ .quiet {
205+ background: transparent;
206+ border-color: var(--ink-soft);
207+
208+ &:hover {
209+ border-color: var(--ink);
210+ color: var(--ink);
211+ }
212+ }
213+
214+ .quiet-danger {
215+ border-color: var(--danger);
216+
217+ &:hover {
218+ border-color: var(--danger);
219+ background: transparent;
220+ }
221+ }
222+
223+ .detail-delete {
224+ background: transparent;
225+ border-color: var(--danger);
226+ }
227+
228+ // Fields rule themselves onto the paper: transparent ground, ink outline.
229+ .auth-input,
230+ .field-input,
231+ .title-input {
232+ background: transparent;
233+ border-color: var(--ink-soft);
234+
235+ &:focus-visible {
236+ background: transparent;
237+ border-color: var(--ink);
238+ }
239+
240+ &:disabled { background: transparent; }
241+ }
242+
243+ .auth-locked,
244+ .field-box,
245+ .status-form {
246+ background: transparent;
247+ border-color: var(--ink-soft);
248+ }
249+
250+ // --- Ledger skin: toggles ------------------------------------------------------
251+
252+ // The switch becomes what a mark is on paper: an empty ink square when
253+ // off, a filled one when on. The knob has no role here.
254+ .rule-switch {
255+ width: 14px;
256+ height: 14px;
257+ border: 1px solid var(--ink);
258+ border-radius: 0;
259+ background: transparent;
260+
261+ .rule-switch-knob { display: none; }
262+ }
263+
264+ .rule-switch-on { background: var(--ink); }
265+}
266+
267+// -- task detail: its own page ------------------------------------------------
268+// No chrome, no floating card: the modal opens as an opaque paper page. The
269+// scrim carries the paper ground and the invisible panning; the column is
270+// static content on top of it, so nothing inside ever scrolls or shows a
271+// scrollbar.
272+[data-ui="ledger"] .modal-scrim:has(> .modal-task) {
273+ background: var(--bg);
274+ justify-content: center;
275+ // Neither top nor bottom padding: the sticky masthead and foot carry the
276+ // page's margins in their own padding, so both sit flush on the pan
277+ // surface's edges instead of floating with text showing past them.
278+ padding: 0 40px;
279+}
280+
281+[data-ui="ledger"] .modal-task {
282+ position: static;
283+ width: 720px;
284+ max-width: 100%;
285+ max-height: none;
286+ overflow: visible;
287+ display: block;
288+ background: transparent;
289+ border: none;
290+ border-radius: 0;
291+ box-shadow: none;
292+}
293+
294+[data-ui="ledger"] .detail-body {
295+ overflow: visible;
296+}
297+
298+// Meta row: key + state chip left, `<- Board` right. The panel chrome — Esc
299+// hint, close cross — and the body's status fieldbox (the chip already says
300+// it) are suppressed.
301+[data-ui="ledger"] .modal-task .detail-head {
302+ align-items: center;
303+ gap: 12px;
304+ padding: 0;
305+}
306+
307+[data-ui="ledger"] .detail-tabs {
308+ padding: 0;
309+ margin-top: 14px;
310+}
311+
312+// The masthead holds at the top of the paper: the task names itself however
313+// far down the comments you are.
314+[data-ui="ledger"] .detail-mast {
315+ position: sticky;
316+ top: 0;
317+ z-index: 2;
318+ padding: 36px 0 6px;
319+ background: var(--bg);
320+}
321+
322+[data-ui="ledger"] .modal-task .detail-esc,
323+[data-ui="ledger"] .modal-task .detail-close,
324+[data-ui="ledger"] .detail-body .detail-field-status {
325+ display: none;
326+}
327+
328+// Dependency rows lose the card chrome - the page reads as ruled paper.
329+[data-ui="ledger"] .dep-row {
330+ border: 0;
331+ border-bottom: 1px solid var(--border);
332+ border-radius: 0;
333+ background: transparent;
334+}
335+
336+[data-ui="ledger"] .modal-task .detail-key {
337+ font-size: 10px;
338+ letter-spacing: 0.08em;
339+ text-transform: uppercase;
340+ color: var(--ink);
341+ text-decoration: underline dotted;
342+ text-underline-offset: 3px;
343+}
344+
345+[data-ui="ledger"] .detail-state {
346+ font-family: var(--font-mono);
347+ font-size: 10px;
348+ letter-spacing: 0.08em;
349+ text-transform: uppercase;
350+}
351+
352+[data-ui="ledger"] .detail-state .field-box,
353+[data-ui="ledger"] .detail-state .status-form {
354+ height: auto;
355+ padding: 0;
356+ background: transparent;
357+ border: none;
358+ font: inherit;
359+ color: var(--ink);
360+}
361+
362+[data-ui="ledger"] .detail-state .status-select {
363+ width: auto;
364+ flex: none;
365+ font: inherit;
366+ text-transform: uppercase;
367+}
368+
369+[data-ui="ledger"] .detail-state .status-dot {
370+ display: none;
371+}
372+
373+[data-ui="ledger"] .detail-board {
374+ margin-left: auto;
375+ font-size: 10px;
376+ letter-spacing: 0.08em;
377+ text-transform: uppercase;
378+ color: var(--ink);
379+ background: transparent;
380+ border: none;
381+ height: auto;
382+}
383+
384+// Serif title over a heavy rule; the edit form gets the same rule so the
385+// title area holds still while editing. The title now lives in the header,
386+// stacked under the key, ahead of the tab strip.
387+[data-ui="ledger"] .detail-head .detail-title,
388+[data-ui="ledger"] .title-form {
389+ padding-bottom: 10px;
390+ border-bottom: 2px solid var(--ink);
391+}
392+
393+[data-ui="ledger"] .detail-title {
394+ font-family: var(--font-serif, Georgia, serif);
395+ font-size: 32px;
396+ font-weight: 400;
397+ line-height: 1.15;
398+ letter-spacing: 0;
399+}
400+
401+[data-ui="ledger"] .title-input {
402+ height: auto;
403+ padding: 0;
404+ border: none;
405+ background: transparent;
406+ font-family: var(--font-serif, Georgia, serif);
407+ font-size: 32px;
408+ font-weight: 400;
409+}
410+
411+// Hairline ruled rows instead of boxed controls.
412+[data-ui="ledger"] .detail-fields {
413+ display: block;
414+ padding: 0;
415+ margin-top: 14px;
416+ border-top: 1px solid var(--border);
417+}
418+
419+[data-ui="ledger"] .detail-field {
420+ display: flex;
421+ flex-direction: row;
422+ align-items: baseline;
423+ gap: 16px;
424+ padding: 10px 0;
425+ border-bottom: 1px solid var(--border);
426+}
427+
428+[data-ui="ledger"] .detail-field > .detail-label {
429+ flex: none;
430+ width: 130px;
431+}
432+
433+[data-ui="ledger"] .detail-field .field-box,
434+[data-ui="ledger"] .detail-field .status-form {
435+ background: transparent;
436+ border: none;
437+ border-radius: 0;
438+ padding: 0;
439+ height: auto;
440+}
441+
442+[data-ui="ledger"] .detail-field .status-dot {
443+ display: none;
444+}
445+
446+// Long-form sections run as prose on paper.
447+[data-ui="ledger"] .detail-block {
448+ margin-top: 24px;
449+}
450+
451+[data-ui="ledger"] .comment-list {
452+ border-top: 1px solid var(--border);
453+}
454+
455+// Composer sits in the flow at the end of the page — the body above is
456+// static, so it simply follows the sections.
457+// The page pans, but the way out must not pan with it. The foot and the
458+// composer hold at the bottom of the paper with the ground under them, so a
459+// description or a comment run of any length still ends within reach.
460+[data-ui="ledger"] .detail-foot,
461+[data-ui="ledger"] .comment-composer {
462+ position: sticky;
463+ bottom: 0;
464+ margin-top: 24px;
465+ padding: 16px 0 36px;
466+ background: var(--bg);
467+ border-top: 1px solid var(--border);
468+}
469+
470+// Settings rail: a narrower column, mono/uppercase stays, the active section
471+// marked with an ink rule rather than a fill.
472+[data-ui="ledger"] .settings-sections {
473+ width: 170px;
474+}
475+
476+[data-ui="ledger"] .settings-section-link.active {
477+ border-bottom: 2px solid var(--ink);
478+}
479+// -- mobile (narrow viewports) -----------------------------------------------
480+// Geometry that the skin sets with [data-ui]-prefixed rules and that the
481+// shared mobile layer in main.scss cannot out-specify.
482+@media (max-width: 620px) {
483+ // The paper page keeps its mast and foot flush; only the side margins give.
484+ [data-ui="ledger"] .modal-scrim:has(> .modal-task) { padding: 0 12px; }
485+
486+ [data-ui="ledger"] .detail-mast { padding: 20px 0 6px; }
487+
488+ [data-ui="ledger"] .detail-title,
489+ [data-ui="ledger"] .title-input { font-size: 24px; }
490+
491+ // The labeled rows stack: no third of a phone holds label and value side
492+ // by side.
493+ [data-ui="ledger"] .detail-field {
494+ flex-direction: column;
495+ align-items: stretch;
496+ gap: 4px;
497+ }
498+
499+ [data-ui="ledger"] .detail-field > .detail-label { width: auto; }
500+
501+ // The rail is a strip; the 170px column is a desktop's.
502+ [data-ui="ledger"] .settings-sections { width: auto; }
503+}
style/main.scssadded+4297 -0

Diff too large; view file

@@ -0,0 +1,4297 @@
1+// Design tokens — two design languages selected by <html data-ui>:
2+//
3+// instrument dense, neutral-cool tool (the default; the bare :root in the
4+// first block doubles as its light set and as a fallback for any
5+// document that somehow reaches this stylesheet without data-ui)
6+// ledger warm paper, hairline rules, serif display face
7+//
8+// data-theme="dark" (settings.rs SaveProfileForm.theme) flips either language.
9+// Component rules below read only these custom properties; the per-UI skins
10+// (_instrument.scss, _ledger.scss) add overrides on top.
11+@use "instrument";
12+@use "ledger";
13+
14+// Instrument, light: warm-gray ground, quiet borders, shared accent family.
15+:root,
16+[data-ui="instrument"] {
17+ color-scheme: light;
18+ --bg: #f2f2f0;
19+ --surface: #fbfbfa;
20+ --border: #dcdcd8;
21+ --border-strong: #d0d0cb;
22+ --ink: #1a1b1d;
23+ --muted: #6b7078;
24+ --muted-soft: #6b7078;
25+ --accent: #46557b;
26+ --accent-tint: #eef0f5;
27+ --accent-ink: #2f3c5c;
28+
29+ --field-bg: #f5f5f3;
30+ --surface-sunken: #e9e9e7;
31+ --surface-muted: #f5f5f3;
32+ --ink-soft: #3d4045;
33+ --row-hover: #ececea;
34+ --panel-sunken: #eeeeec;
35+ --border-soft: #d3d3ce;
36+ --scrim: rgba(26, 27, 29, 0.46);
37+
38+ --danger: #a04a24;
39+ --danger-tint: #f9ece4;
40+ --danger-tint-soft: #fdf6f2;
41+ --danger-tint-alt: #fbf1ec;
42+ --danger-border: #e8c9b8;
43+ --danger-border-soft: #eddcd3;
44+ --danger-border-alt: #ecd0bf;
45+
46+ --warn-ink: #7a5c1e;
47+ --warn-tint: #f7f0dd;
48+ --warn-tint-soft: #fdfaf1;
49+ --warn-border: #e6d7ae;
50+
51+ --positive: #5c7b46;
52+ --positive-ink: #4a6636;
53+ --positive-tint: #eef3e9;
54+ --positive-border: #d3e0c6;
55+
56+ --accent-strong: #5a6a94;
57+ --accent-border: #d6dbe8;
58+ --accent-border-strong: #d8dce6;
59+
60+ --avatar-tone-1: #7b6846;
61+ --avatar-tone-3: #7b4655;
62+ --avatar-tone-4: #46707b;
63+
64+ --violet-tint: #f1eaf7;
65+ --violet-border: #ddc4ec;
66+ --violet-ink: #6a3f82;
67+
68+ --font-sans: system-ui, sans-serif;
69+ --font-mono: 'IBM Plex Mono', ui-monospace, monospace;
70+ --font-display: var(--font-sans);
71+
72+ --control-h: 32px;
73+ --control-h-lg: 40px;
74+ --rule-strong: #d0d0cb;
75+
76+ --radius: 3px;
77+ --radius-sm: var(--radius);
78+ --radius-md: 3px;
79+ --radius-lg: 3px;
80+ --topbar-height: 56px;
81+
82+ --shadow-1: none;
83+ --shadow-2: none;
84+ --shadow-3: none;
85+
86+ --dur-fast: 120ms;
87+ --ease: ease-out;
88+}
89+
90+// Instrument, dark: near-black neutral-cool; tint fills go translucent and
91+// tint borders go alpha so the ground shows through.
92+[data-ui="instrument"][data-theme="dark"] {
93+ color-scheme: dark;
94+ --bg: #0d0e10;
95+ --surface: #14161a;
96+ --border: #23262c;
97+ --border-strong: #2e323a;
98+ --ink: #e6e4de;
99+ --muted: #7d8590;
100+ --muted-soft: #4a4f58;
101+ --accent: #8ba1e8;
102+ --accent-tint: rgba(139, 161, 232, 0.14);
103+ --accent-ink: #b9c6ee;
104+
105+ --field-bg: #101216;
106+ --surface-sunken: #101216;
107+ --surface-muted: #0f1013;
108+ --ink-soft: #c9c7c0;
109+ --row-hover: #1a1d22;
110+ --panel-sunken: #101216;
111+ --border-soft: #1f2226;
112+ --scrim: rgba(0, 0, 0, 0.75);
113+
114+ --danger: #e0906a;
115+ --danger-tint: rgba(224, 144, 106, 0.13);
116+ --danger-tint-soft: rgba(224, 144, 106, 0.07);
117+ --danger-tint-alt: rgba(224, 144, 106, 0.05);
118+ --danger-border: rgba(224, 144, 106, 0.45);
119+ --danger-border-soft: rgba(224, 144, 106, 0.3);
120+ --danger-border-alt: rgba(224, 144, 106, 0.35);
121+
122+ --warn-ink: #d4b16a;
123+ --warn-tint: rgba(212, 177, 106, 0.14);
124+ --warn-tint-soft: rgba(212, 177, 106, 0.07);
125+ --warn-border: rgba(212, 177, 106, 0.4);
126+
127+ --positive: #9db98a;
128+ --positive-ink: #b4cba3;
129+ --positive-tint: rgba(157, 185, 138, 0.13);
130+ --positive-border: rgba(157, 185, 138, 0.4);
131+
132+ --accent-strong: #7e93d9;
133+ --accent-border: #3a4152;
134+ --accent-border-strong: #2b3b63;
135+
136+ --avatar-tone-1: #937d58;
137+ --avatar-tone-3: #96606e;
138+ --avatar-tone-4: #5b93a1;
139+
140+ --violet-tint: rgba(185, 138, 151, 0.14);
141+ --violet-border: rgba(185, 138, 151, 0.4);
142+ --violet-ink: #b98a97;
143+
144+ --font-sans: system-ui, sans-serif;
145+ --font-mono: 'IBM Plex Mono', ui-monospace, monospace;
146+ --font-display: var(--font-sans);
147+
148+ --control-h: 32px;
149+ --control-h-lg: 40px;
150+ --rule-strong: #2e323a;
151+
152+ --radius: 3px;
153+ --radius-sm: var(--radius);
154+ --radius-md: 3px;
155+ --radius-lg: 3px;
156+ --topbar-height: 56px;
157+
158+ --shadow-1: none;
159+ --shadow-2: none;
160+ --shadow-3: none;
161+
162+ --dur-fast: 120ms;
163+ --ease: ease-out;
164+}
165+
166+// Ledger, light: warm paper; hairline rules carry structure, ink carries
167+// emphasis. Tint trio stays on the proven warm palette.
168+[data-ui="ledger"] {
169+ color-scheme: light;
170+ --bg: #f6f1e6;
171+ --surface: #f6f1e6;
172+ --border: #ddd5c2;
173+ --border-strong: #221f18;
174+ --ink: #221f18;
175+ --muted: #7a7466;
176+ --muted-soft: #a39b88;
177+ --accent: #46557b;
178+ --accent-tint: #eef0f5;
179+ --accent-ink: #2f3c5c;
180+
181+ --field-bg: #f1ebdd;
182+ --surface-sunken: #efe9da;
183+ --surface-muted: #f2ecdf;
184+ --ink-soft: #4a453a;
185+ --row-hover: #efe9da;
186+ --panel-sunken: #f1ebdd;
187+ --border-soft: #cfc6b0;
188+ --scrim: rgba(34, 31, 24, 0.46);
189+
190+ --danger: #a04a24;
191+ --danger-tint: #f9ece4;
192+ --danger-tint-soft: #fdf6f2;
193+ --danger-tint-alt: #fbf1ec;
194+ --danger-border: #e8c9b8;
195+ --danger-border-soft: #eddcd3;
196+ --danger-border-alt: #ecd0bf;
197+
198+ --warn-ink: #7a5c1e;
199+ --warn-tint: #f7f0dd;
200+ --warn-tint-soft: #fdfaf1;
201+ --warn-border: #e6d7ae;
202+
203+ --positive: #5c7b46;
204+ --positive-ink: #4a6636;
205+ --positive-tint: #eef3e9;
206+ --positive-border: #d3e0c6;
207+
208+ --accent-strong: #5a6a94;
209+ --accent-border: #d6dbe8;
210+ --accent-border-strong: #d8dce6;
211+
212+ --avatar-tone-1: #7b6846;
213+ --avatar-tone-3: #7b4655;
214+ --avatar-tone-4: #46707b;
215+
216+ --violet-tint: #f1eaf7;
217+ --violet-border: #ddc4ec;
218+ --violet-ink: #6a3f82;
219+
220+ --font-sans: system-ui, sans-serif;
221+ --font-mono: 'IBM Plex Mono', ui-monospace, monospace;
222+ --font-display: 'Newsreader', Georgia, serif;
223+
224+ --control-h: 32px;
225+ --control-h-lg: 40px;
226+ --rule-strong: #221f18;
227+
228+ --radius: 2px;
229+ --radius-sm: var(--radius);
230+ --radius-md: 2px;
231+ --radius-lg: 2px;
232+ --topbar-height: 56px;
233+
234+ --shadow-1: none;
235+ --shadow-2: none;
236+ --shadow-3: none;
237+
238+ --dur-fast: 120ms;
239+ --ease: ease-out;
240+}
241+
242+// Ledger, dark: dimmed paper ground; semantic hues lifted for contrast, tint
243+// fills translucent over the paper tone.
244+[data-ui="ledger"][data-theme="dark"] {
245+ color-scheme: dark;
246+ --bg: #171511;
247+ --surface: #171511;
248+ --border: #3a352a;
249+ --border-strong: #e8e2d4;
250+ --ink: #e8e2d4;
251+ --muted: #97907f;
252+ --muted-soft: #6e6757;
253+ --accent: #9db0dd;
254+ --accent-tint: rgba(157, 176, 221, 0.14);
255+ --accent-ink: #c3cfee;
256+
257+ --field-bg: #1c1915;
258+ --surface-sunken: #14120e;
259+ --surface-muted: #1c1915;
260+ --ink-soft: #cfc8b6;
261+ --row-hover: #201c16;
262+ --panel-sunken: #1b1814;
263+ --border-soft: #2e2a20;
264+ --scrim: rgba(0, 0, 0, 0.75);
265+
266+ --danger: #d28a5a;
267+ --danger-tint: rgba(210, 138, 90, 0.13);
268+ --danger-tint-soft: rgba(210, 138, 90, 0.07);
269+ --danger-tint-alt: rgba(210, 138, 90, 0.05);
270+ --danger-border: rgba(210, 138, 90, 0.45);
271+ --danger-border-soft: rgba(210, 138, 90, 0.3);
272+ --danger-border-alt: rgba(210, 138, 90, 0.35);
273+
274+ --warn-ink: #d4b16a;
275+ --warn-tint: rgba(212, 177, 106, 0.14);
276+ --warn-tint-soft: rgba(212, 177, 106, 0.07);
277+ --warn-border: rgba(212, 177, 106, 0.4);
278+
279+ --positive: #a3bd8b;
280+ --positive-ink: #b8cda4;
281+ --positive-tint: rgba(163, 189, 139, 0.13);
282+ --positive-border: rgba(163, 189, 139, 0.4);
283+
284+ --accent-strong: #8497c9;
285+ --accent-border: #3f4658;
286+ --accent-border-strong: #2c3550;
287+
288+ --avatar-tone-1: #937d58;
289+ --avatar-tone-3: #96606e;
290+ --avatar-tone-4: #5b93a1;
291+
292+ --violet-tint: rgba(201, 163, 222, 0.14);
293+ --violet-border: rgba(201, 163, 222, 0.4);
294+ --violet-ink: #c9a3de;
295+
296+ --font-sans: system-ui, sans-serif;
297+ --font-mono: 'IBM Plex Mono', ui-monospace, monospace;
298+ --font-display: 'Newsreader', Georgia, serif;
299+
300+ --control-h: 32px;
301+ --control-h-lg: 40px;
302+ --rule-strong: #e8e2d4;
303+
304+ --radius: 2px;
305+ --radius-sm: var(--radius);
306+ --radius-md: 2px;
307+ --radius-lg: 2px;
308+ --topbar-height: 56px;
309+
310+ --shadow-1: none;
311+ --shadow-2: none;
312+ --shadow-3: none;
313+
314+ --dur-fast: 120ms;
315+ --ease: ease-out;
316+}
317+
318+* { box-sizing: border-box; }
319+
320+body {
321+ margin: 0;
322+ background: var(--bg);
323+ color: var(--ink);
324+ font-family: var(--font-sans);
325+ font-size: 13px;
326+}
327+
328+// The board page owns the viewport: chrome and the occasional refusal line
329+// keep their natural height, the stage absorbs the rest, the document never
330+// scrolls.
331+body:has(.board-stage) {
332+ // dvh follows the browser chrome phones raise and lower; vh is the fallback
333+ // for engines without it.
334+ height: 100vh;
335+ height: 100dvh;
336+ overflow: hidden;
337+ display: flex;
338+ flex-direction: column;
339+
340+ > * { flex: none; }
341+ > .board-stage { flex: 1; min-height: 0; }
342+}
343+
344+body:has(.settings-shell) {
345+ height: 100vh;
346+ height: 100dvh;
347+ overflow: hidden;
348+ display: flex;
349+ flex-direction: column;
350+
351+ > * { flex: none; }
352+ > .settings-shell { flex: 1; min-height: 0; }
353+}
354+
355+// A profile is one column of its own; it pans inside itself like every other
356+// page here, and the document never grows a scrollbar.
357+body:has(.people-shell) {
358+ height: 100vh;
359+ height: 100dvh;
360+ overflow: hidden;
361+ display: flex;
362+ flex-direction: column;
363+
364+ > * { flex: none; }
365+ > .people-shell { flex: 1; min-height: 0; }
366+}
367+// The account screens take the same lock: the card centers in what is left
368+// of the viewport, and a card taller than it (a landscape phone) pans inside
369+// the stage instead of growing the document.
370+body:has(.auth-stage) {
371+ height: 100vh;
372+ height: 100dvh;
373+ overflow: hidden;
374+ display: flex;
375+ flex-direction: column;
376+
377+ > * { flex: none; }
378+ > .auth-stage {
379+ flex: 1;
380+ min-height: 0;
381+ overflow-y: auto;
382+ scrollbar-width: none;
383+
384+ &::-webkit-scrollbar { display: none; }
385+ }
386+}
387+
388+a {
389+ color: var(--accent);
390+ transition: color var(--dur-fast) var(--ease);
391+ &:hover { color: var(--accent-ink); }
392+}
393+
394+.topbar {
395+ height: var(--topbar-height);
396+ background: var(--surface);
397+ border-bottom: 1px solid var(--border);
398+ display: flex;
399+ align-items: center;
400+ gap: 16px;
401+ padding: 0 24px;
402+}
403+
404+// The brand lockup is the one thing the two skins do NOT restyle: same
405+// monogram, same face, same size in Instrument and Ledger, light and dark.
406+// The mark takes the ink from `currentColor` and the tittle from the accent,
407+// so it re-tints with the theme without a second drawing.
408+.wordmark {
409+ display: flex;
410+ align-items: center;
411+ gap: 10px;
412+ text-decoration: none;
413+ color: inherit;
414+
415+ &:hover { color: inherit; }
416+
417+ &-mark {
418+ flex: none;
419+ display: block;
420+ width: 24px;
421+ height: 24px;
422+ }
423+
424+ // The word without the mark, on the sign-in and setup pages: nothing else
425+ // in that chrome, so it can take the room the topbar version cannot.
426+ &-lone &-text {
427+ font-size: 18px;
428+ letter-spacing: 0.01em;
429+ }
430+
431+ &-tittle {
432+ fill: var(--accent);
433+ }
434+
435+ // Lower case, and not by taste: capitalised, the dotted `i` becomes `I` and
436+ // the name reads as the English word. The tittle is the Turkish one, in the
437+ // word as it is in the mark.
438+ &-text {
439+ font-family: var(--font-mono);
440+ font-size: 15px;
441+ font-weight: 500;
442+ letter-spacing: 0.02em;
443+ }
444+}
445+
446+.topbar-divider {
447+ width: 1px;
448+ height: 20px;
449+ background: var(--border);
450+}
451+
452+.topbar-nav-links {
453+ display: flex;
454+ gap: 16px;
455+ margin-left: auto;
456+}
457+
458+// The spacer's flex-grow eats the free space before auto margins see any, so
459+// inside the chrome the nav's auto margin does the pushing instead.
460+.topbar > .spacer { display: none; }
461+
462+.topbar-nav {
463+ font-family: var(--font-mono);
464+ font-size: 10px;
465+ letter-spacing: 0.08em;
466+ text-transform: uppercase;
467+ color: var(--muted);
468+ text-decoration: none;
469+ // A two-word label ("Mail rules") folds under pressure and reads as two
470+ // stacked links; the nav gives up room some other way.
471+ white-space: nowrap;
472+ padding-bottom: 2px;
473+
474+ &:hover { color: var(--ink); }
475+
476+ &-on {
477+ color: var(--ink);
478+ box-shadow: inset 0 -2px 0 var(--ink);
479+ }
480+}
481+
482+.scaffold-note {
483+ margin: 24px;
484+ padding: 20px 24px;
485+ background: var(--surface);
486+ border: 1px solid var(--border);
487+ border-radius: var(--radius-lg);
488+ color: var(--muted);
489+}
490+
491+// --- Account screens (FirstLogin artboard) ---------------------------------
492+
493+.auth-stage {
494+ min-height: calc(100vh - var(--topbar-height));
495+ display: flex;
496+ align-items: center;
497+ justify-content: center;
498+ padding: 0 40px 40px;
499+}
500+
501+.auth-column {
502+ width: 520px;
503+ max-width: 100%;
504+ display: flex;
505+ flex-direction: column;
506+ gap: 10px;
507+}
508+
509+.auth-card {
510+ background: var(--surface);
511+ border: 1px solid var(--border);
512+ border-radius: var(--radius-lg);
513+ padding: 28px 28px;
514+ display: flex;
515+ flex-direction: column;
516+ gap: 18px;
517+ box-shadow: var(--shadow-2);
518+
519+ form {
520+ display: flex;
521+ flex-direction: column;
522+ gap: 20px;
523+ }
524+}
525+
526+.auth-head {
527+ display: flex;
528+ flex-direction: column;
529+ gap: 6px;
530+}
531+
532+.auth-title {
533+ font-size: 18px;
534+ font-weight: 600;
535+ letter-spacing: -0.01em;
536+}
537+
538+.auth-sub {
539+ font-size: 13px;
540+ color: var(--muted);
541+ line-height: 1.5;
542+}
543+
544+.auth-field {
545+ display: flex;
546+ flex-direction: column;
547+ gap: 6px;
548+}
549+
550+.auth-label {
551+ font-family: var(--font-mono);
552+ font-size: 10px;
553+ letter-spacing: 0.08em;
554+ color: var(--muted-soft);
555+}
556+
557+// The address an invited member signs in as: shown, never edited.
558+.auth-locked {
559+ display: flex;
560+ align-items: center;
561+ gap: 8px;
562+ height: 40px;
563+ padding: 0 12px;
564+ background: var(--panel-sunken);
565+ border: 1px solid var(--border-strong);
566+ border-radius: var(--radius);
567+}
568+
569+.auth-locked-value {
570+ font-family: var(--font-mono);
571+ font-size: 13px;
572+ color: var(--muted);
573+ flex-grow: 1;
574+}
575+
576+.auth-submit {
577+ height: var(--control-h-lg);
578+ display: flex;
579+ align-items: center;
580+ justify-content: center;
581+ gap: 8px;
582+ background: var(--accent);
583+ color: var(--surface);
584+ border: 0;
585+ border-radius: var(--radius);
586+ cursor: pointer;
587+ font-family: var(--font-sans);
588+
589+ &:disabled {
590+ opacity: 0.45;
591+ cursor: default;
592+ }
593+}
594+
595+.auth-submit-text {
596+ font-size: 13px;
597+ font-weight: 600;
598+}
599+
600+.auth-key {
601+ font-family: var(--font-mono);
602+ font-size: 10px;
603+ background: var(--accent-strong);
604+ border-radius: var(--radius-sm);
605+ padding: 1px 4px;
606+}
607+
608+.auth-problem {
609+ font-size: 13px;
610+ color: var(--danger);
611+ background: var(--danger-tint-alt);
612+ border: 1px solid var(--danger-border-soft);
613+ border-radius: var(--radius);
614+ padding: 10px 12px;
615+}
616+
617+.auth-note {
618+ font-size: 13px;
619+ color: var(--muted);
620+ background: var(--panel-sunken);
621+ border: 1px solid var(--border-soft);
622+ border-radius: var(--radius);
623+ padding: 10px 12px;
624+}
625+
626+.auth-alt {
627+ font-size: 12px;
628+ color: var(--muted);
629+ text-decoration: none;
630+ align-self: center;
631+
632+ &:hover { color: var(--accent-ink); }
633+}
634+
635+// -- the board (Main and EmptyBoard artboards) -------------------------------
636+
637+.spacer { flex-grow: 1; }
638+
639+.user-menu { position: relative; }
640+
641+.user-menu-trigger {
642+ display: inline-flex;
643+ align-items: center;
644+ gap: 8px;
645+ padding: 0;
646+ background: none;
647+ border: none;
648+ font-family: inherit;
649+ font-size: 13px;
650+ color: var(--muted);
651+ cursor: pointer;
652+ transition: color var(--dur-fast) var(--ease);
653+
654+ &:hover { color: var(--accent-ink); }
655+}
656+
657+.user-menu-panel {
658+ position: absolute;
659+ top: 100%;
660+ right: 0;
661+ z-index: 30;
662+ width: 220px;
663+ padding: 8px 0;
664+ background: var(--surface);
665+ border: 1px solid var(--border-strong);
666+ border-radius: var(--radius-lg);
667+ box-shadow: var(--shadow-2);
668+ visibility: hidden;
669+ opacity: 0;
670+ pointer-events: none;
671+ transition: opacity var(--dur-fast) var(--ease), visibility var(--dur-fast) var(--ease);
672+}
673+
674+.user-menu:hover .user-menu-panel,
675+.user-menu:focus-within .user-menu-panel {
676+ visibility: visible;
677+ opacity: 1;
678+ pointer-events: auto;
679+}
680+.user-menu.user-menu-esc .user-menu-panel { visibility: hidden; opacity: 0; pointer-events: none; }
681+
682+.user-menu-name {
683+ padding: 4px 14px 0;
684+ font-size: 13px;
685+ font-weight: 600;
686+}
687+
688+.user-menu-email {
689+ padding: 2px 14px 0;
690+ font-size: 12px;
691+ color: var(--muted);
692+ word-break: break-all;
693+}
694+
695+.user-menu-role {
696+ padding: 2px 14px 6px;
697+ font-size: 12px;
698+ color: var(--muted-soft);
699+ text-transform: capitalize;
700+}
701+
702+.user-menu-item {
703+ display: flex;
704+ align-items: center;
705+ width: 100%;
706+ height: 32px;
707+ padding: 0 14px;
708+ border: none;
709+ background: none;
710+ font-family: inherit;
711+ font-size: 13px;
712+ color: var(--ink-soft);
713+ text-decoration: none;
714+ text-align: left;
715+ cursor: pointer;
716+ transition: background-color var(--dur-fast) var(--ease), color var(--dur-fast) var(--ease);
717+
718+ &:hover { background: var(--row-hover); color: var(--ink); }
719+}
720+
721+.user-menu-item-form { display: block; }
722+
723+.filterbar {
724+ min-height: 52px;
725+ background: var(--surface);
726+ border-bottom: 1px solid var(--border);
727+ display: flex;
728+ align-items: center;
729+ flex-wrap: wrap;
730+ row-gap: 8px;
731+ gap: 14px;
732+ padding: 8px 24px;
733+}
734+
735+.segmented {
736+ display: flex;
737+ align-items: center;
738+ background: var(--panel-sunken);
739+ border: 1px solid var(--border-strong);
740+ border-radius: var(--radius);
741+ padding: 2px;
742+ gap: 2px;
743+}
744+
745+.chip {
746+ display: flex;
747+ align-items: center;
748+ height: 24px;
749+ padding: 0 10px;
750+ border-radius: var(--radius);
751+ font-size: 11px;
752+ font-weight: 600;
753+
754+ &-overdue {
755+ background: var(--danger-tint);
756+ color: var(--danger);
757+ }
758+
759+ &-blocked {
760+ background: var(--warn-tint);
761+ color: var(--warn-ink);
762+ }
763+
764+ &-role,
765+ &-admin,
766+ &-connected,
767+ &-off {
768+ text-transform: capitalize;
769+ }
770+
771+ &-role { background: var(--surface-sunken); border: 1px solid var(--border-strong); color: var(--ink-soft); }
772+ &-admin { background: var(--panel-sunken); border: 1px solid var(--border-strong); color: var(--muted); }
773+ &-connected { background: var(--positive-tint); color: var(--positive-ink); }
774+ &-off { background: var(--warn-tint); color: var(--warn-ink); }
775+}
776+
777+.board-stage {
778+ position: relative;
779+ display: flex;
780+ flex-direction: column;
781+ flex: 1;
782+ min-height: 0;
783+ padding: 20px 24px 24px 24px;
784+}
785+
786+.board-columns {
787+ flex: 1;
788+ min-height: 0;
789+ display: grid;
790+ grid-template-columns: repeat(auto-fit, minmax(0, 1fr));
791+ gap: 16px;
792+ align-items: stretch;
793+}
794+
795+.column {
796+ background: var(--surface-sunken);
797+ border-radius: var(--radius-lg);
798+ padding: 12px;
799+ display: flex;
800+ flex-direction: column;
801+ gap: 10px;
802+ min-height: 120px;
803+}
804+
805+.column-head {
806+ display: flex;
807+ align-items: center;
808+ gap: 8px;
809+ padding: 2px 4px;
810+}
811+
812+.column-name {
813+ font-size: 13px;
814+ font-weight: 600;
815+}
816+
817+.column-count {
818+ font-family: var(--font-mono);
819+ font-size: 11px;
820+ font-variant-numeric: tabular-nums;
821+ color: var(--muted-soft);
822+ background: var(--panel-sunken);
823+ border-radius: var(--radius);
824+ padding: 1px 6px;
825+}
826+
827+.column-cards {
828+ display: flex;
829+ flex-direction: column;
830+ gap: 8px;
831+ flex: 1;
832+ min-height: 0;
833+ overflow-y: auto;
834+ scrollbar-width: none;
835+
836+ &::-webkit-scrollbar { display: none; }
837+}
838+
839+.column-empty {
840+ flex: 1;
841+ display: flex;
842+ align-items: center;
843+ justify-content: center;
844+ min-height: 60px;
845+ border: 1px dashed var(--border-strong);
846+ border-radius: var(--radius-md);
847+ background: var(--surface-sunken);
848+ font-size: 12px;
849+ color: var(--muted-soft);
850+}
851+
852+.card {
853+ // The card is an anchor so it has an address; it must not read as one.
854+ display: block;
855+ text-decoration: none;
856+ color: inherit;
857+ background: var(--surface);
858+ border: 1px solid var(--border);
859+ border-radius: var(--radius-md);
860+ padding: 10px 12px;
861+ box-shadow: var(--shadow-1);
862+ cursor: pointer;
863+ transition: background-color var(--dur-fast) var(--ease), border-color var(--dur-fast) var(--ease);
864+
865+ &:hover {
866+ background: var(--row-hover);
867+ border-color: var(--border-strong);
868+ }
869+}
870+
871+/* Where a dragged card may land. Only columns it is not already in light up:
872+ the card's own column is not a destination. */
873+.column-drop {
874+ outline: 1px dashed var(--border-strong);
875+ outline-offset: 4px;
876+ border-radius: var(--radius-md);
877+ background: var(--accent-tint);
878+}
879+
880+.card-done {
881+ background: var(--surface-muted);
882+ box-shadow: none;
883+
884+ .card-title { color: var(--muted); }
885+}
886+
887+.card-keys {
888+ display: flex;
889+ align-items: baseline;
890+ gap: 6px;
891+ font-family: var(--font-mono);
892+ font-size: 10px;
893+}
894+
895+.card-key { color: var(--muted); }
896+
897+.card-blocks,
898+.card-blocked-by { color: var(--warn-ink); }
899+
900+.card-title {
901+ font-size: 13px;
902+ font-weight: 600;
903+ line-height: 1.4;
904+ margin-top: 4px;
905+}
906+
907+.card-foot {
908+ display: flex;
909+ align-items: center;
910+ gap: 6px;
911+ margin-top: 10px;
912+ flex-wrap: wrap;
913+}
914+
915+.card-deadline {
916+ display: flex;
917+ align-items: center;
918+ font-family: var(--font-mono);
919+ font-size: 11px;
920+ font-variant-numeric: tabular-nums;
921+ color: var(--muted);
922+ background: var(--surface-sunken);
923+ border-radius: var(--radius-sm);
924+ padding: 2px 6px;
925+
926+ &-overdue {
927+ color: var(--danger);
928+ background: var(--danger-tint);
929+ }
930+
931+ &-none {
932+ color: var(--muted-soft);
933+ background: transparent;
934+ padding-left: 0;
935+ }
936+}
937+
938+.card-comments,
939+.card-subtasks {
940+ font-family: var(--font-mono);
941+ font-size: 11px;
942+ color: var(--muted);
943+}
944+
945+.card-tag {
946+ font-family: var(--font-mono);
947+ font-size: 11px;
948+ color: var(--muted);
949+ background: var(--surface-sunken);
950+ border-radius: var(--radius-sm);
951+ padding: 2px 6px;
952+}
953+
954+/// Parts still open is the same warning the blocker chips carry: this card
955+/// cannot reach the done column yet.
956+.card-subtasks-open { color: var(--warn-ink); }
957+
958+.avatars {
959+ display: flex;
960+ align-items: center;
961+ min-width: 0;
962+ overflow: hidden;
963+
964+ // The data-name tooltip pokes above the row; hovering drops the clip so it
965+ // is not cut off by the overlap truncation.
966+ &:has(.avatar:hover) { overflow: visible; }
967+}
968+
969+.avatar {
970+ width: 22px;
971+ height: 22px;
972+ border-radius: 50%;
973+ border: 2px solid var(--surface);
974+ color: var(--surface);
975+ font-family: var(--font-mono);
976+ font-size: 10px;
977+ display: flex;
978+ align-items: center;
979+ justify-content: center;
980+ position: relative;
981+
982+ & + & { margin-left: -8px; }
983+
984+ &-none {
985+ border: 1px dashed var(--border-strong);
986+ background: transparent;
987+ }
988+
989+ // The modal asks for two other sizes: 18px inside an assignee chip, 28px
990+ // beside a comment. The border is the board's overlap trick and has no job
991+ // on a lone avatar, so these drop it.
992+ //
993+ // They are written as `.avatar.avatar-sm` on purpose: the Instrument skin
994+ // sizes `.avatar` from a `[data-ui]` scope, which outweighs a lone class —
995+ // a plain `.avatar-lg` lost to it, and every size modifier collapsed to
996+ // 18px on that skin without anybody noticing.
997+ &.avatar-sm {
998+ width: 18px;
999+ height: 18px;
1000+ border: none;
1001+ font-size: 10px;
1002+ }
1003+
1004+ &.avatar-lg {
1005+ width: 28px;
1006+ height: 28px;
1007+ border: none;
1008+ font-size: 11px;
1009+ flex: none;
1010+ }
1011+
1012+ // The profile page's own picture: the one place a face is the subject of
1013+ // the screen rather than a mark beside somebody's name.
1014+ &.avatar-xl {
1015+ width: 92px;
1016+ height: 92px;
1017+ border: none;
1018+ font-size: 30px;
1019+ font-weight: 500;
1020+ flex: none;
1021+ }
1022+
1023+ // A bare avatar carries `data-name`; hovering raises a house tooltip in
1024+ // place of the native `title`.
1025+ &[data-name]:hover::after {
1026+ content: attr(data-name);
1027+ position: absolute;
1028+ bottom: calc(100% + 6px);
1029+ left: 50%;
1030+ transform: translateX(-50%);
1031+ background: var(--surface);
1032+ border: 1px solid var(--border);
1033+ border-radius: var(--radius-sm);
1034+ padding: 3px 8px;
1035+ font-size: 11px;
1036+ color: var(--ink-soft);
1037+ box-shadow: var(--shadow-2);
1038+ white-space: nowrap;
1039+ z-index: 30;
1040+ pointer-events: none;
1041+ }
1042+
1043+ &-tone-0 { background: var(--accent); }
1044+ &-tone-1 { background: var(--avatar-tone-1); }
1045+ &-tone-2 { background: var(--positive); }
1046+ &-tone-3 { background: var(--avatar-tone-3); }
1047+ &-tone-4 { background: var(--avatar-tone-4); }
1048+}
1049+
1050+// A photo avatar is the same box with the picture where the tone fill was;
1051+// size and shape ride the shared .avatar classes.
1052+img.avatar {
1053+ object-fit: cover;
1054+ display: block;
1055+}
1056+
1057+// The avatar leads the profile panel. Without a photo it is itself the
1058+// upload control — the file input rides its `form` attribute to a hidden
1059+// sibling form, so nothing nests inside the profile form. With one, the
1060+// click opens the photo viewer and a Change button owns the picker instead.
1061+.identity-row {
1062+ display: flex;
1063+ align-items: center;
1064+ gap: 14px;
1065+}
1066+
1067+// The two faces of the profile picture box: the picker label and, once a
1068+// photo exists, the viewer trigger. The person page's own card wears the
1069+// trigger too — the box rules are shared, the size is not.
1070+.avatar-upload,
1071+.avatar-view {
1072+ position: relative;
1073+ flex: none;
1074+ cursor: pointer;
1075+
1076+ // The name tooltip has no job on your own picture.
1077+ .avatar[data-name]:hover::after { content: none; }
1078+}
1079+
1080+// The settings row's picture is 64px whatever size class the avatar wears;
1081+// the person card's keeps its xl.
1082+.identity-row .avatar-upload .avatar,
1083+.identity-row .avatar-view .avatar {
1084+ width: 64px;
1085+ height: 64px;
1086+ font-size: 20px;
1087+}
1088+
1089+// The trigger is the label's box with a button's chrome stripped.
1090+.avatar-view {
1091+ appearance: none;
1092+ background: none;
1093+ border: none;
1094+ padding: 0;
1095+}
1096+
1097+.avatar-upload {
1098+ // The upload affordance: a veil and a plus over the picture, on hover or
1099+ // keyboard focus only.
1100+ &::after {
1101+ content: "+";
1102+ position: absolute;
1103+ inset: 0;
1104+ display: flex;
1105+ align-items: center;
1106+ justify-content: center;
1107+ background: rgb(0 0 0 / 0.4);
1108+ border-radius: 50%;
1109+ color: #fff;
1110+ font-size: 24px;
1111+ font-weight: 300;
1112+ opacity: 0;
1113+ transition: opacity var(--dur-fast) var(--ease);
1114+ pointer-events: none;
1115+ }
1116+
1117+ &:hover::after,
1118+ &:has(.file-upload-input:focus-visible)::after { opacity: 1; }
1119+}
1120+
1121+// -- the card context menu ---------------------------------------------------
1122+//
1123+// A right-click opens this at the cursor; `card_menu_script` (board.rs) sets
1124+// its position and the `card-menu-open` class, and a document click closes
1125+// whichever one is open. The panel and its rows wear the same floating-list
1126+// chrome as the assignee and link pickers (`.pop-panel`/`.pop-list`/`.pop-row`).
1127+
1128+.card-menu {
1129+ display: none;
1130+ position: fixed;
1131+ z-index: 25;
1132+ min-width: 160px;
1133+
1134+ &-open { display: block; }
1135+}
1136+
1137+.card-menu-move { position: relative; }
1138+
1139+.card-menu-submenu {
1140+ display: none;
1141+ position: absolute;
1142+ left: 100%;
1143+ top: 0;
1144+ margin-left: 4px;
1145+ min-width: 140px;
1146+}
1147+
1148+.card-menu-move:hover > .card-menu-submenu,
1149+.card-menu-move-trigger:focus + .card-menu-submenu { display: block; }
1150+
1151+.card-menu-danger { color: var(--danger); }
1152+
1153+// -- the task detail modal --------------------------------------------------
1154+//
1155+// The modal is a view. Every region that can be changed is a `<form>` wearing
1156+// the view's clothes: the read-only shape is a `<label>`, the form beneath it
1157+// is hidden until a visually-hidden checkbox is checked, and the checkbox is
1158+// checked by clicking that label. Cancel is a second label pointing at the
1159+// same checkbox, so entering and leaving the edit state both work with wasm
1160+// blocked. Nothing else on the screen changes when one region opens.
1161+
1162+.modal-scrim {
1163+ position: fixed;
1164+ inset: 0;
1165+ background: var(--scrim);
1166+ display: flex;
1167+ align-items: flex-start;
1168+ justify-content: center;
1169+ padding: 48px 24px;
1170+ overflow-y: auto;
1171+ // The scrim is the silent pan surface for tall page-style modals: it may
1172+ // scroll, but it never shows a scrollbar.
1173+ scrollbar-width: none;
1174+
1175+ &::-webkit-scrollbar { display: none; }
1176+
1177+ z-index: 20;
1178+}
1179+
1180+.modal {
1181+ width: 780px;
1182+ max-width: 100%;
1183+ max-height: calc(100vh - 96px);
1184+ overflow-y: auto;
1185+ background: var(--surface);
1186+ border: 1px solid var(--border);
1187+ border-radius: var(--radius-lg);
1188+ box-shadow: var(--shadow-3);
1189+ padding: 0;
1190+ outline: none;
1191+}
1192+
1193+.modal-loading { height: 220px; }
1194+
1195+.modal-note,
1196+.modal-problem {
1197+ margin: 8px 24px 0;
1198+ font-size: 13px;
1199+ color: var(--danger);
1200+}
1201+
1202+.modal-new-task { width: 480px; }
1203+
1204+// The task-detail modal shares `.modal` with the new-task modal and the
1205+// viewer, which stay centered. The base only fixes the frame — a header on
1206+// top, one body that pans invisibly between header and composer — because
1207+// the skins reshape it: instrument docks it as a 560px side panel, ledger
1208+// lays it out as its own opaque page.
1209+.modal-task {
1210+ display: flex;
1211+ flex-direction: column;
1212+ max-height: none;
1213+ overflow: visible;
1214+}
1215+
1216+.detail-mast {
1217+ flex: none;
1218+}
1219+
1220+// Dependencies ride in the mast, and a task can be blocked by any number of
1221+// others — so the list keeps three whole rows' worth of room and pans inside itself,
1222+// silently, rather than pushing the task's own text off the screen.
1223+.detail-mast .dep-list {
1224+ max-height: 160px;
1225+ overflow-y: auto;
1226+ scrollbar-width: none;
1227+
1228+ &::-webkit-scrollbar { display: none; }
1229+}
1230+
1231+.detail-mast .detail-block {
1232+ margin-top: 14px;
1233+}
1234+
1235+.detail-body {
1236+ flex: 1;
1237+ min-height: 0;
1238+ overflow-y: auto;
1239+ scrollbar-width: none;
1240+
1241+ &::-webkit-scrollbar { display: none; }
1242+}
1243+
1244+// The in-app file viewer: same scrim/panel chrome as the task modal, rendered
1245+// as a later sibling of it so the task modal underneath hides while it is
1246+// open — one popup on screen at a time, the same rule the delete confirm
1247+// uses. Closing is a `.viewer-close` anchor stretched over the whole scrim
1248+// under the panel — outside clicks land on it and navigate, clicks on the
1249+// media land on the panel above it and stay.
1250+.viewer-close { position: absolute; inset: 0; cursor: default; }
1251+
1252+.modal-scrim:has(~ .viewer-scrim) { visibility: hidden; }
1253+
1254+.viewer { position: relative; width: auto; max-width: min(90vw, 960px); }
1255+
1256+.viewer-body {
1257+ display: flex;
1258+ align-items: center;
1259+ justify-content: center;
1260+ padding: 20px 24px 24px;
1261+}
1262+
1263+.viewer-media { max-width: 100%; max-height: 78vh; border-radius: var(--radius-md); }
1264+
1265+// The house audio player: the native pill is browser chrome — it ignores the
1266+// theme's shape language and swallows Escape while focused, so the viewer
1267+// draws its own controls over a hidden `<audio>`.
1268+.audio-player {
1269+ display: flex;
1270+ align-items: center;
1271+ gap: 12px;
1272+ width: min(480px, 80vw);
1273+ padding: 12px 16px;
1274+ background: var(--surface);
1275+ border: 1px solid var(--border);
1276+ border-radius: var(--radius-md);
1277+
1278+ .audio-el { display: none; }
1279+}
1280+
1281+.audio-play {
1282+ display: grid;
1283+ place-items: center;
1284+ width: 32px;
1285+ height: 32px;
1286+ flex: none;
1287+ padding: 0;
1288+ border: 1px solid var(--accent-border);
1289+ border-radius: 50%;
1290+ background: var(--accent-tint);
1291+ color: var(--accent-ink);
1292+ cursor: pointer;
1293+
1294+ .glyph-pause { display: none; }
1295+ &:hover { border-color: var(--accent-strong); }
1296+}
1297+
1298+.audio-playing .audio-play {
1299+ .glyph-play { display: none; }
1300+ .glyph-pause { display: block; }
1301+}
1302+
1303+.audio-time {
1304+ font-family: var(--font-mono);
1305+ font-size: 12px;
1306+ color: var(--muted);
1307+ min-width: 34px;
1308+ text-align: center;
1309+}
1310+
1311+.audio-seek {
1312+ flex: 1;
1313+ appearance: none;
1314+ height: 4px;
1315+ margin: 0;
1316+ background: var(--border);
1317+ border-radius: 2px;
1318+ cursor: pointer;
1319+
1320+ &::-webkit-slider-thumb {
1321+ appearance: none;
1322+ width: 12px;
1323+ height: 12px;
1324+ border: none;
1325+ border-radius: 50%;
1326+ background: var(--accent);
1327+ }
1328+
1329+ &::-moz-range-thumb {
1330+ width: 12px;
1331+ height: 12px;
1332+ border: none;
1333+ border-radius: 50%;
1334+ background: var(--accent);
1335+ }
1336+
1337+ &::-moz-range-track {
1338+ height: 4px;
1339+ background: var(--border);
1340+ border-radius: 2px;
1341+ }
1342+
1343+ &::-moz-range-progress {
1344+ height: 4px;
1345+ background: var(--accent);
1346+ border-radius: 2px;
1347+ }
1348+}
1349+
1350+.viewer-pdf { width: 100%; height: 78vh; border: 1px solid var(--border); border-radius: var(--radius-md); }
1351+
1352+// A workbook has no element of its own, so the viewer draws it: a tab strip
1353+// when the book has more than one sheet, and a grid that pans inside its own
1354+// box — the document never scrolls.
1355+// A workbook is wider and taller than anything else the viewer opens, so it
1356+// takes the panel the whole way out: the modal grows to the viewport and no
1357+// further, and the grid takes whatever is left under the tab strip and pans
1358+// inside that — the panel itself never leaves the screen.
1359+.viewer:has(.viewer-sheet) {
1360+ width: auto;
1361+ max-width: min(96vw, 1400px);
1362+ display: flex;
1363+ flex-direction: column;
1364+ overflow: hidden;
1365+
1366+ .viewer-body {
1367+ flex: 1;
1368+ min-height: 0;
1369+ align-items: stretch;
1370+ padding: 16px 20px 20px;
1371+ }
1372+}
1373+
1374+.viewer-sheet {
1375+ display: flex;
1376+ flex-direction: column;
1377+ gap: 10px;
1378+ width: 100%;
1379+ // The viewer body is a row flex, so without these the sheet's automatic
1380+ // minimum size is the whole table's width and height, and a wide book
1381+ // pushes the panel off the screen instead of panning inside it.
1382+ min-width: 0;
1383+ min-height: 0;
1384+}
1385+
1386+.sheet-tabs {
1387+ display: flex;
1388+ gap: 6px;
1389+ overflow-x: auto;
1390+ scrollbar-width: none;
1391+
1392+ &::-webkit-scrollbar { display: none; }
1393+}
1394+
1395+.sheet-tab {
1396+ padding: 4px 10px;
1397+ border: 1px solid var(--border);
1398+ border-radius: var(--radius-sm);
1399+ color: var(--text-dim);
1400+ font-size: 12px;
1401+ white-space: nowrap;
1402+ text-decoration: none;
1403+}
1404+
1405+.sheet-tab-on {
1406+ color: var(--text);
1407+ border-color: var(--accent);
1408+}
1409+
1410+// A window is sized to land on a screen, so the grid takes only the room its
1411+// own rows need — the pagers below it stay in view rather than being pushed
1412+// off by a table that always claims the whole panel.
1413+.sheet-grid {
1414+ flex: 0 1 auto;
1415+ min-width: 0;
1416+ min-height: 0;
1417+ overflow: auto;
1418+ scrollbar-width: none;
1419+ border: 1px solid var(--border);
1420+ border-radius: var(--radius-md);
1421+
1422+ &::-webkit-scrollbar { display: none; }
1423+}
1424+
1425+.sheet-table {
1426+ border-collapse: collapse;
1427+ font-size: 12px;
1428+ font-variant-numeric: tabular-nums;
1429+
1430+ th,
1431+ td {
1432+ padding: 4px 8px;
1433+ border-right: 1px solid var(--border);
1434+ border-bottom: 1px solid var(--border);
1435+ max-width: 180px;
1436+ overflow: hidden;
1437+ text-overflow: ellipsis;
1438+ white-space: nowrap;
1439+ text-align: left;
1440+ }
1441+
1442+ // The column letters and row numbers are chrome, not data: dim, sticky at
1443+ // the edges they name, so a cell keeps its address while the grid pans.
1444+ thead th {
1445+ position: sticky;
1446+ top: 0;
1447+ z-index: 1;
1448+ background: var(--surface);
1449+ color: var(--text-dim);
1450+ font-weight: 500;
1451+ }
1452+
1453+ .sheet-gutter {
1454+ position: sticky;
1455+ left: 0;
1456+ background: var(--surface);
1457+ color: var(--text-dim);
1458+ font-weight: 500;
1459+ text-align: right;
1460+ }
1461+
1462+ thead .sheet-gutter { z-index: 2; }
1463+}
1464+
1465+.sheet-note {
1466+ margin: 0;
1467+ color: var(--text-dim);
1468+ font-size: 12px;
1469+}
1470+
1471+// A sheet is read one window at a time, and these move it: the rows down the
1472+// left, the columns across the right, each counted against the whole sheet.
1473+// A step with nowhere to go stays in place, dimmed, so the pair never moves
1474+// under the pointer.
1475+.sheet-foot {
1476+ display: flex;
1477+ align-items: center;
1478+ justify-content: space-between;
1479+ gap: 16px;
1480+}
1481+
1482+.sheet-pager {
1483+ display: flex;
1484+ align-items: center;
1485+ gap: 4px;
1486+}
1487+
1488+.sheet-range {
1489+ color: var(--text-dim);
1490+ font-size: 12px;
1491+ font-variant-numeric: tabular-nums;
1492+ margin-right: 4px;
1493+}
1494+
1495+.sheet-step {
1496+ display: inline-flex;
1497+ align-items: center;
1498+ justify-content: center;
1499+ width: 26px;
1500+ height: 24px;
1501+ border: 1px solid var(--border);
1502+ border-radius: var(--radius-sm);
1503+ color: var(--text-dim);
1504+
1505+ &:hover { color: var(--text); border-color: var(--accent); }
1506+}
1507+
1508+// One chevron points down; the other three are that chevron turned.
1509+.sheet-step-up .glyph { transform: rotate(180deg); }
1510+.sheet-step-left .glyph { transform: rotate(90deg); }
1511+.sheet-step-right .glyph { transform: rotate(-90deg); }
1512+
1513+.sheet-step-off {
1514+ opacity: 0.3;
1515+
1516+ &:hover { color: var(--text-dim); border-color: var(--border); }
1517+}
1518+
1519+// A deck is the second format no browser renders, read the same way a
1520+// workbook is: the panel takes the viewer the whole way out, the outline
1521+// pans inside its own box, and the document never scrolls. The slide strip
1522+// is the sheet tab strip with numbers instead of names; the pager is the
1523+// sheet's pair with one step set.
1524+.viewer:has(.viewer-slides) {
1525+ display: flex;
1526+ flex-direction: column;
1527+ overflow: hidden;
1528+
1529+ .viewer-body {
1530+ flex: 1;
1531+ min-height: 0;
1532+ align-items: stretch;
1533+ padding: 16px 20px 20px;
1534+ }
1535+}
1536+
1537+.viewer-slides {
1538+ display: flex;
1539+ flex-direction: column;
1540+ gap: 10px;
1541+ width: 100%;
1542+ min-width: 0;
1543+ min-height: 0;
1544+}
1545+
1546+.slides-nav {
1547+ display: flex;
1548+ gap: 6px;
1549+ overflow-x: auto;
1550+ scrollbar-width: none;
1551+
1552+ &::-webkit-scrollbar { display: none; }
1553+}
1554+
1555+.slide-tab {
1556+ padding: 4px 10px;
1557+ border: 1px solid var(--border);
1558+ border-radius: var(--radius-sm);
1559+ color: var(--text-dim);
1560+ font-size: 12px;
1561+ font-variant-numeric: tabular-nums;
1562+ white-space: nowrap;
1563+ text-decoration: none;
1564+}
1565+
1566+.slide-tab-on {
1567+ color: var(--text);
1568+ border-color: var(--accent);
1569+}
1570+
1571+// The outline is what the deck says, not what it draws, so the card takes
1572+// the room left under the strip and pans inside itself when a slide runs
1573+// long rather than pushing the pager out of view.
1574+.slide-card {
1575+ flex: 1;
1576+ min-width: 0;
1577+ min-height: 0;
1578+ overflow: auto;
1579+ scrollbar-width: none;
1580+ padding: 20px 24px;
1581+ border: 1px solid var(--border);
1582+ border-radius: var(--radius-md);
1583+
1584+ &::-webkit-scrollbar { display: none; }
1585+}
1586+
1587+.slide-title {
1588+ margin: 0 0 12px;
1589+ font-size: 16px;
1590+}
1591+
1592+.slide-line {
1593+ margin: 0 0 8px;
1594+ font-size: 13px;
1595+}
1596+
1597+.slides-foot {
1598+ display: flex;
1599+ align-items: center;
1600+ justify-content: space-between;
1601+ gap: 16px;
1602+}
1603+
1604+.slides-pager {
1605+ display: flex;
1606+ align-items: center;
1607+ gap: 4px;
1608+}
1609+
1610+.slides-range {
1611+ color: var(--text-dim);
1612+ font-size: 12px;
1613+ font-variant-numeric: tabular-nums;
1614+ margin-right: 4px;
1615+}
1616+
1617+.slides-step {
1618+ display: inline-flex;
1619+ align-items: center;
1620+ justify-content: center;
1621+ width: 26px;
1622+ height: 24px;
1623+ border: 1px solid var(--border);
1624+ border-radius: var(--radius-sm);
1625+ color: var(--text-dim);
1626+
1627+ &:hover { color: var(--text); border-color: var(--accent); }
1628+}
1629+
1630+// The chevron points down; the pair turns it sideways.
1631+.slides-step-left .glyph { transform: rotate(90deg); }
1632+.slides-step-right .glyph { transform: rotate(-90deg); }
1633+
1634+.slides-step-off {
1635+ opacity: 0.3;
1636+
1637+ &:hover { color: var(--text-dim); border-color: var(--border); }
1638+}
1639+
1640+.new-task-form {
1641+ display: flex;
1642+ flex-direction: column;
1643+ gap: 20px;
1644+ padding: 20px 24px 24px;
1645+}
1646+
1647+.new-task-row {
1648+ display: flex;
1649+ gap: 16px;
1650+}
1651+
1652+.new-task-foot {
1653+ display: flex;
1654+ align-items: center;
1655+ gap: 10px;
1656+}
1657+
1658+// -- the edit state ---------------------------------------------------------
1659+
1660+.edit { position: relative; }
1661+
1662+// Focusable but invisible: it is the state, and a keyboard must be able to
1663+// reach it. Not `display: none` — that would take it out of the tab order.
1664+.edit-toggle {
1665+ position: absolute;
1666+ width: 1px;
1667+ height: 1px;
1668+ margin: 0;
1669+ padding: 0;
1670+ opacity: 0;
1671+ pointer-events: none;
1672+}
1673+
1674+.edit-hit { cursor: text; }
1675+
1676+.edit-form { display: none; }
1677+
1678+.edit:not(.edit-pop) > .edit-toggle:checked ~ .edit-view { display: none; }
1679+.edit-toggle:checked ~ .edit-form { display: block; }
1680+.edit-toggle:checked ~ .title-form { display: flex; }
1681+.detail-head:has(.edit-toggle:checked) .detail-state,
1682+.detail-head:has(.edit-toggle:checked) .spacer,
1683+.detail-head:has(.edit-toggle:checked) .detail-esc,
1684+.detail-head:has(.edit-toggle:checked) .detail-close,
1685+.detail-head:has(.edit-toggle:checked) .detail-board {
1686+ display: none;
1687+}
1688+.edit-toggle:focus-visible ~ .edit-view {
1689+ outline: 2px solid var(--accent);
1690+ outline-offset: 2px;
1691+ border-radius: var(--radius-sm);
1692+}
1693+
1694+.edit-row {
1695+ display: flex;
1696+ align-items: center;
1697+ gap: 8px;
1698+ margin-top: 8px;
1699+}
1700+
1701+.edit-save,
1702+.comment-post {
1703+ height: var(--control-h);
1704+ padding: 0 12px;
1705+ border: none;
1706+ border-radius: var(--radius);
1707+ background: var(--accent);
1708+ color: var(--surface);
1709+ font-family: inherit;
1710+ font-size: 12px;
1711+ cursor: pointer;
1712+ transition: background var(--dur-fast) var(--ease);
1713+
1714+ &:hover { background: var(--accent-strong); }
1715+
1716+ &:disabled { opacity: 0.5; cursor: default; }
1717+}
1718+
1719+.edit-cancel {
1720+ font-size: 12px;
1721+ color: var(--muted);
1722+ cursor: pointer;
1723+ transition: color var(--dur-fast) var(--ease);
1724+
1725+ &:hover { color: var(--ink); }
1726+}
1727+
1728+// A popover is the same machinery, floated.
1729+.edit-pop {
1730+ .edit-form {
1731+ position: absolute;
1732+ top: calc(100% + 6px);
1733+ left: 0;
1734+ z-index: 4;
1735+ }
1736+}
1737+
1738+.pop-panel {
1739+ min-width: 200px;
1740+ padding: 8px;
1741+ background: var(--surface);
1742+ border: 1px solid var(--border-strong);
1743+ border-radius: var(--radius-md);
1744+ box-shadow: var(--shadow-2);
1745+}
1746+
1747+.pop-panel-wide { min-width: 320px; }
1748+
1749+.pop-list {
1750+ display: flex;
1751+ flex-direction: column;
1752+ gap: 2px;
1753+}
1754+
1755+.pop-list-scroll {
1756+ max-height: 220px;
1757+ overflow-y: auto;
1758+}
1759+
1760+.pop-row-form { display: block; }
1761+
1762+.pop-row {
1763+ display: flex;
1764+ align-items: center;
1765+ gap: 8px;
1766+ width: 100%;
1767+ padding: 4px 6px;
1768+ border: none;
1769+ border-radius: var(--radius-sm);
1770+ background: transparent;
1771+ font-family: inherit;
1772+ font-size: 13px;
1773+ color: var(--ink);
1774+ text-align: left;
1775+ text-decoration: none;
1776+ cursor: pointer;
1777+ transition: background-color var(--dur-fast) var(--ease);
1778+
1779+ &:hover { background: var(--row-hover); }
1780+}
1781+
1782+.pop-row-name { font-size: 12px; }
1783+
1784+
1785+.pick-row {
1786+ display: flex;
1787+ align-items: center;
1788+ gap: 8px;
1789+ padding: 4px 6px;
1790+ border-radius: var(--radius-sm);
1791+ font-size: 12px;
1792+ cursor: pointer;
1793+ transition: background-color var(--dur-fast) var(--ease);
1794+
1795+ &:hover { background: var(--row-hover); }
1796+}
1797+
1798+.pick-title { color: var(--muted); }
1799+
1800+.pick-direction {
1801+ display: flex;
1802+ align-items: center;
1803+ gap: 12px;
1804+ margin: 8px 0 0;
1805+ padding: 8px 6px 0;
1806+ border: none;
1807+ border-top: 1px solid var(--border);
1808+ font-size: 12px;
1809+
1810+ label {
1811+ display: inline-flex;
1812+ align-items: center;
1813+ gap: 4px;
1814+ cursor: pointer;
1815+ }
1816+}
1817+
1818+// -- header -----------------------------------------------------------------
1819+
1820+.detail-head {
1821+ display: flex;
1822+ align-items: flex-start;
1823+ gap: 10px;
1824+ // Measured against the artboard: the key sits 26px below the modal's own top
1825+ // edge, and every row under it inherits that.
1826+ padding: 22px 24px 0;
1827+}
1828+
1829+.detail-headline {
1830+ flex: 1;
1831+ min-width: 0;
1832+}
1833+
1834+// -- tab strip ----------------------------------------------------------
1835+
1836+.detail-tabs {
1837+ display: flex;
1838+ gap: 2px;
1839+ flex: none;
1840+ padding: 0 16px;
1841+ border-bottom: 1px solid var(--border);