diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..5e07764 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,228 @@ +on: + push: + branches: + - main + +# The deploy swaps a release directory and restarts one service; two of them +# racing would leave the binary and the running process from different builds. +concurrency: + group: deploy + cancel-in-progress: false + +env: + # A gnu binary links against the runner's glibc, so the runner is pinned + # (see runs-on below) to the same 24.04 the server runs; the day either + # side moves, the pin is what forces a conscious decision rather than a + # broken deploy. In exchange: no cross-toolchain, and the linker is + # rustc's default bundled lld. + TARGET: x86_64-unknown-linux-gnu + # The systemd user unit that owns the process. See in.service. + SERVICE: in + # `release` keeps fat LTO in one codegen unit for when the last few percent + # are worth five minutes. `dist` is that profile with thin LTO and the cores + # actually used: measured on a 12-core machine, the relink every deploy pays + # for goes from 2m27s to 25s, for a binary this server will never be + # CPU-bound on. See the profile in Cargo.toml. + PROFILE: dist + TOPCOAT: 0.6.2 + # The deploy lives in this subdirectory of the SSH user's home. The home + # itself is resolved on the server ($HOME), so switching the deploy user + # moves the path with it — a baked-in absolute path once kept pointing at + # the previous user's home and failed the deploy on permissions. + DEPLOY_SUBDIR: in + # Baked into the binary by build.rs and asserted against after the + # deploy restart: a /healthz answered by a stale process from an old + # deploy now fails and rolls back instead of reporting green (observed + # on the initial in deploy). + IN_BUILD_SHA: ${{ github.sha }} + +jobs: + deploy: + name: Deploy + # Pinned, not `latest`: ubuntu-latest floating to the next LTS would + # one day ship a glibc newer than the server's, and the gnu binary + # would stop running there. See the TARGET comment above. + runs-on: ubuntu-24.04 + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up Rust + run: rustup toolchain install stable --profile minimal + + - name: Cache cargo + uses: Swatinem/rust-cache@v2 + with: + cache-all-crates: true + # Bump when the target, the profile or any rustflags change: the + # key does not otherwise see those, and a run that restores the + # old key reports it up-to-date at save time — discarding the + # recompiled dependencies and silently recompiling them on every + # later run (observed when the musl→gnu move landed on this key). + prefix-key: v1-rust-gnu + + # Compiling the CLI from source costs minutes and it changes only when + # the pinned version does, so it is cached on that version alone. + - name: Cache the topcoat CLI + id: topcoat-cache + uses: actions/cache@v4 + with: + path: ~/.cargo/bin/topcoat + key: topcoat-cli-${{ env.TOPCOAT }}-${{ runner.os }} + + - name: Install the topcoat CLI + # Installed before the cargo config below exists, so the CLI itself + # is built for the host and not for the deploy target. + if: steps.topcoat-cache.outputs.cache-hit != 'true' + run: cargo install topcoat-cli@${{ env.TOPCOAT }} --locked + + - name: Point cargo at the deploy target + run: | + set -euo pipefail + # `topcoat asset bundle` runs its own `cargo build` and strips every + # CARGO_* variable from it, so the target cannot be passed by + # environment; it goes into the cargo config that inner build + # reads. This file is written in CI only; it is not committed. + # + # With the gnu target the linker is rustc's default — the bundled + # rust-lld — and it matters: a warm relink of this binary measured + # 142s under the BFD that an explicit `linker = "gcc"` would pick, + # against 23s under lld. That link is the largest single chunk of + # the deploy build, so the default is deliberately left alone. + mkdir -p .cargo + printf '[build]\ntarget = "%s"\n' "$TARGET" >> .cargo/config.toml + + - name: Build the binary and bundle its assets + run: | + set -euo pipefail + # One compile: this builds in-web and writes out the asset bundle + # embedded in the binary it produced. + topcoat asset bundle --package in-web --profile "$PROFILE" --out stage/assets + cp "target/$TARGET/$PROFILE/in-web" stage/in-web + strip stage/in-web + ls -l stage stage/assets + + - name: Install SSH keys + run: | + mkdir -p ~/.ssh + echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa && chmod 600 ~/.ssh/id_rsa + ssh-keyscan -H ${{ secrets.SSH_HOST }} > ~/.ssh/known_hosts + + - name: Upload the release + run: | + set -euo pipefail + ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" + + # The server's login shell is not bash, and ssh would hand this + # script to it; `bash -s` takes it on stdin instead, so the login + # shell only ever parses one plain command. + # + # The deploy path is $DEPLOY_SUBDIR under the SSH user's home, + # resolved on the server as $HOME: there is no path secret to go + # stale, and switching the deploy user moves the deploy with it. + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" <<'REMOTE' + set -euo pipefail + case "$1" in + ''|/*|*..*) + echo "Refusing a broad deploy subdirectory: '$1'" >&2 + exit 1 + ;; + esac + deploy_path=$HOME/$1 + # The deploy path is the service's working directory: config/, + # in.db and in.key live there and are never touched from here. + # Only 'current' is replaced. + mkdir -p -- "$deploy_path" + rm -rf -- "$deploy_path/current.new" + mkdir -p -- "$deploy_path/current.new" + REMOTE + # stdin carries the tarball, so the script cannot; the extraction + # still goes through bash -c because the login shell is fish and + # would not expand $HOME. + tar -C stage -czf - . | ssh "$ssh_target" "bash -c 'exec tar -xzf - -C \"\$HOME/\$1/current.new\"' -- '$DEPLOY_SUBDIR'" + + - name: Swap and restart + run: | + set -euo pipefail + ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" + + # bash -s for the same reason as above: the login shell is not + # bash and must never see this script. + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$GITHUB_SHA'" <<'REMOTE' + set -euo pipefail + deploy_path=$HOME/$1 + service=$2 + expected="ok $3" + export XDG_RUNTIME_DIR=/run/user/$(id -u) + # Read before anything moves: a config the health check cannot + # read is a failure to stop on, not one to roll back from. + listen=$(sed -n 's/^listen[[:space:]]*=[[:space:]]*"\(.*\)"/\1/p' "$deploy_path/config/in.toml") + if [ -z "$listen" ]; then + echo "no listen address in $deploy_path/config/in.toml" >&2 + exit 1 + fi + chmod +x -- "$deploy_path/current.new/in-web" + rm -rf -- "$deploy_path/current.previous" + if [ -e "$deploy_path/current" ]; then + mv -- "$deploy_path/current" "$deploy_path/current.previous" + fi + mv -- "$deploy_path/current.new" "$deploy_path/current" + systemctl --user restart "$service" + # The unit is Type=simple, so a restart returns before the new + # process has bound its port — and before an old one has let go + # of it. Wait for the health route rather than a clock, and + # check the answer names this commit: a stale process can still + # answer, and did once (the initial in deploy deployed green over + # a stale server). + rollback() { + rm -rf -- "$deploy_path/current" + mv -- "$deploy_path/current.previous" "$deploy_path/current" + systemctl --user restart "$service" + } + for _ in $(seq 1 30); do + served=$(curl -fsS "http://$listen/healthz" 2>/dev/null) || { sleep 1; continue; } + if [ "$served" != "$expected" ]; then + echo "/healthz answered '$served', wanted '$expected'; rolling back" >&2 + rollback + exit 1 + fi + echo 'in is up' + rm -rf -- "$deploy_path/current.previous" + exit 0 + done + echo 'in did not answer /healthz; rolling back' >&2 + rollback + exit 1 + REMOTE + + # The boot-time fingerprint guard refuses a foreign bundle, so a + # mixed generation cannot get this far unnoticed — this is the + # independent after-the-fact check: the page's stylesheet URL must + # answer with bytes byte-identical to the bundle this deploy staged. + - name: Verify the served stylesheet is this deploy's + run: | + set -euo pipefail + ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" + # One remote script: mixing runner-side and server-side variables in + # nested ssh quoting once shipped a check that failed on a healthy + # deploy. Everything server-side happens inside the heredoc; only the + # stylesheet bytes come back on stdout. + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" > served-stylesheet.css <<'REMOTE' + set -euo pipefail + deploy_path=$HOME/$1 + listen=$(sed -n 's/^listen[[:space:]]*=[[:space:]]*"\(.*\)"/\1/p' "$deploy_path/config/in.toml") + url=$(curl -fsS "http://${listen}/" | grep -oE '/_topcoat/assets/main-[a-f0-9]+\.css' | head -n1) + if [ -z "$url" ]; then + echo 'the served page references no stylesheet' >&2 + exit 1 + fi + echo "served stylesheet url: $url" >&2 + curl -fsS "http://${listen}${url}" + REMOTE + staged=$(sha256sum stage/assets/main-*.css | cut -d' ' -f1) + served=$(sha256sum served-stylesheet.css | cut -d' ' -f1) + echo "staged sha256:$staged, served sha256:$served" + test "$staged" = "$served" + + - name: Cleaning + run: rm -rf ~/.ssh diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..70f4c6f --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +/target +/dist +/style/main.css +*.db +*.db-* +/storage +.env +in.key +/config/in.toml +CLAUDE.md +/crates/in-web/assets +*.db.backup-* diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..019adbf --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,5387 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common 0.1.7", + "generic-array", +] + +[[package]] +name = "aegis" +version = "0.9.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58541132f980da31e9aa99f7bdee69bc84bf1e168b9b91ef2dbe8abb7b4ce5dd" +dependencies = [ + "cc", + "softaes", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "allocator-api2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c880a97d28a3681c0267bd29cff89621202715b065127cd445fa0f0fe0aa2880" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "antithesis_sdk" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8ed6751597568a284314fd9e2db420665898600109dedc7d8d9b588f00ae9c4" +dependencies = [ + "libc", + "libloading", + "linkme", + "once_cell", + "rand 0.8.8", + "rustc_version_runtime", + "serde", + "serde_json", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "anymap3" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9" + +[[package]] +name = "arc-swap" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" +dependencies = [ + "rustversion", +] + +[[package]] +name = "aristo" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcdeefa800110050103e2459a2f8dbdbd560ad046e30f1f87e24ce19c2cb8bde" +dependencies = [ + "aristo-macros", +] + +[[package]] +name = "aristo-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d64a66d21a80182b35b1741997a6d2456911f54b7eb1918aa4e2382fc205268d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "assoc" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfdc70193dadb9d7287fa4b633f15f90c876915b31f6af17da307fc59c9859a8" + +[[package]] +name = "async-compression" +version = "0.4.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "515a1f282e33d55983c499d7e9e87082e81cbc32974825bf9032f928392d5844" +dependencies = [ + "compression-codecs", + "compression-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "aws-lc-rs" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bigdecimal" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d6867f1565b3aad85681f1015055b087fcfd840d6aeee6eee7f2da317603695" +dependencies = [ + "autocfg", + "libm", + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "bindgen" +version = "0.69.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools 0.12.1", + "lazy_static", + "lazycell", + "log", + "prettyplease 0.2.37", + "proc-macro2", + "quote", + "regex", + "rustc-hash 1.1.0", + "shlex 1.3.0", + "syn 2.0.119", + "which", +] + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "bitpacking" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96a7139abd3d9cebf8cd6f920a389cf3dc9576172e32f4563f188cae3c3eb019" +dependencies = [ + "crunchy", +] + +[[package]] +name = "bitvec" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bon" +version = "3.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e3fac94a66da67200398458a25412bcc3f9b6443b5119a6cad9cf3ccfcd8cc6" +dependencies = [ + "bon-macros", +] + +[[package]] +name = "bon-macros" +version = "3.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4654961ad0494e4774c5c60b4cb4cd0ae9b9d92d039d901638b1dba97ebebf5" +dependencies = [ + "darling", + "ident_case", + "prettyplease 0.3.0", + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "branches" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7436b21fd6195415058eb41c9090e156b556bc7e0377bb57c5c026a421521525" +dependencies = [ + "rustc_version", +] + +[[package]] +name = "brotli" +version = "8.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0e56a716f1e132ff6bf4bdac1c944a3fcdc1cae65f70a4a2a1ac3b401d2d1f" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "005ec2760ca554fae18df7a11195552ec576cd665632a881bc011d5bb2fd4d80" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex 2.0.1", +] + +[[package]] +name = "census" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f4c707c6a209cbe82d10abd08e1ea8995e9ea937d2550646e02798948992be0" + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom 7.1.3", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "cfg_block" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18758054972164c3264f7c8386f5fc6da6114cb46b619fd365d4e3b2dc3ae487" + +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20 0.9.1", + "cipher", + "poly1305", + "zeroize", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout", + "zeroize", +] + +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "clap" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "codemap" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e769b5c8c8283982a987c6e948e540254f1058d5a74b8794914d4ef5fc2a24" + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "combine" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "compression-codecs" +version = "0.4.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fe67f2944eef52fc7b106b8c9450d243a88701a0c065f7f57235e76abaed7df" +dependencies = [ + "brotli", + "compression-core", + "flate2", + "memchr", +] + +[[package]] +name = "compression-core" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e8ccc4ea9f6acc32d102c0f6d471d11d913ad15f20c04de743374861fa1d414" + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "cookie" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +dependencies = [ + "aes-gcm", + "base64 0.22.1", + "hkdf", + "hmac", + "percent-encoding", + "rand 0.8.8", + "sha2 0.10.9", + "subtle", + "time", + "version_check", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32c" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47" +dependencies = [ + "rustc_version", +] + +[[package]] +name = "crc32fast" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8498c871161e1742aaa9d52551b2d6ebdd4c3d45a3be423e3728f33b955be550" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d85363c37faeca707aef026efa9f3b34d077bce547e48f770770625c6013679e" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.4", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "datasketches" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c286de4e81ea2590afc24d754e0f83810c566f50a1388fa75ebd57928c0d9745" + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "const-oid 0.9.6", + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.2", + "crypto-common 0.2.2", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "downcast-rs" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc" + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "either" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" + +[[package]] +name = "elsa" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9abf33c656a7256451ebb7d0082c5a471820c31269e49d807c538c252352186e" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "email-encoding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "420b9da095f052ea597503e39073b5b3c522f7db933fbac202d91d24492693fd" +dependencies = [ + "base64 0.23.1", + "memchr", +] + +[[package]] +name = "email_address" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449" + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "env_filter" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6" +dependencies = [ + "env_filter", + "log", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "erased-serde" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fastbloom" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7f34442dbe69c60fe8eaf58a8cafff81a1f278816d8ab4db255b3bef4ac3c4" +dependencies = [ + "getrandom 0.3.4", + "libm", + "siphasher", +] + +[[package]] +name = "fastdivide" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afc2bd4d5a73106dd53d10d73d3401c2f32730ba2c0b93ddb888a8983680471" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs4" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4" +dependencies = [ + "rustix 1.1.4", + "windows-sys 0.59.0", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-sink", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "genawaiter" +version = "0.99.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86bd0361bcbde39b13475e6e36cb24c329964aa2611be285289d1e4b751c1a0" +dependencies = [ + "genawaiter-macro", +] + +[[package]] +name = "genawaiter-macro" +version = "0.99.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b32dfe1fdfc0bbde1f22a5da25355514b5e450c33a6af6770884c8750aedfbc" + +[[package]] +name = "generator" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3b854b0e584ead1a33f18b2fcad7cf7be18b3875c78816b753639aa501513ae" +dependencies = [ + "cc", + "cfg-if", + "libc", + "log", + "rustversion", + "windows-link", + "windows-result", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "grass" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7a68216437ef68f0738e48d6c7bb9e6e6a92237e001b03d838314b068f33c94" +dependencies = [ + "clap", + "getrandom 0.2.17", + "grass_compiler", +] + +[[package]] +name = "grass_compiler" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d9e3df7f0222ce5184154973d247c591d9aadc28ce7a73c6cd31100c9facff6" +dependencies = [ + "codemap", + "indexmap", + "lasso", + "once_cell", + "phf", + "rand 0.8.8", +] + +[[package]] +name = "h2" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", + "allocator-api2 0.2.21", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2 0.2.21", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "hostname" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd" +dependencies = [ + "cfg-if", + "libc", + "windows-link", +] + +[[package]] +name = "htmlescape" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9025058dae765dee5070ec375f591e2ba14638c63feff74f13805a72e523163" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collator" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08984ed58ac439ebf3e13d2cf26b0c46a60afcd21721c1d14087c0b240344dda" +dependencies = [ + "icu_collator_data", + "icu_collections", + "icu_locale_core", + "icu_locale_fallback", + "icu_normalizer", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "zerovec", +] + +[[package]] +name = "icu_collator_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7d7e54efdddeb1208c08dd5d32b53a879ac00d2d3d051b2255fd26821d16368" + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "785f595c61ef57169a467eeed7b4b6936a66f6cacbb116a96ee86da983251bf4" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_locale_data", + "icu_locale_fallback", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "serde", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locale_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d37d91460e362a5cf58907cd7ce871411775ee6294e49a5cc8e6cec16dfa75ea" + +[[package]] +name = "icu_locale_fallback" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8" + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "utf16_iter", + "utf8_iter", + "write16", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "serde", + "stable_deref_trait", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "in-client" +version = "0.1.0" +dependencies = [ + "base64 0.22.1", + "chacha20poly1305", + "http", + "rand 0.10.2", + "rand_core 0.6.4", + "reqwest", + "rsa", + "serde", + "serde_json", + "sha2 0.10.9", + "sha2 0.11.0", + "subtle", + "thiserror", + "time", + "tokio", + "topcoat", +] + +[[package]] +name = "in-core" +version = "0.1.0" +dependencies = [ + "async-trait", + "base64 0.22.1", + "chacha20poly1305", + "image", + "rand 0.10.2", + "serde", + "serde_json", + "sha2 0.11.0", + "subtle", + "tempfile", + "thiserror", + "time", + "tokio", + "toml", + "turso", + "ulid", + "zip", +] + +[[package]] +name = "in-web" +version = "0.1.0" +dependencies = [ + "async-trait", + "futures-util", + "grass", + "http", + "http-body-util", + "in-client", + "in-core", + "serde", + "serde_json", + "sha2 0.10.9", + "thiserror", + "time", + "tokio", + "topcoat", + "ulid", +] + +[[package]] +name = "indexmap" +version = "2.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07aa2048142242915a31d35844fb311e0e53fcca590c3a0a40dcf1b841fa09eb" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "intrusive-collections" +version = "0.9.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86" +dependencies = [ + "memoffset", +] + +[[package]] +name = "inventory" +version = "0.3.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4f0c30c76f2f4ccee3fe55a2435f691ca00c0e4bd87abe4f4a851b1d4dac39b" +dependencies = [ + "rustversion", +] + +[[package]] +name = "io-uring" +version = "0.7.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d64d8ca234d152948ceaede1f419b6a83983a5ecccaac05fb337a809c96d3aa6" +dependencies = [ + "bitflags", + "cfg-if", + "libc", +] + +[[package]] +name = "ipnet" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a756c3fac73139e83f14c2d742155dd2b78d3ee56597b419a0579b7bdd6dd78" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lasso" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e14eda50a3494b3bf7b9ce51c52434a761e383d7238ce1dd5dcec2fbc13e9fb" +dependencies = [ + "hashbrown 0.14.5", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin", +] + +[[package]] +name = "lazycell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" + +[[package]] +name = "lettre" +version = "0.11.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2c646bd5cc763b1087b15493e29a64be6147ba8f19342004fa52048ee596eae" +dependencies = [ + "email-encoding", + "email_address", + "fastrand", + "hostname", + "httpdate", + "idna", + "mime", + "nom 8.0.0", + "quoted_printable", +] + +[[package]] +name = "levenshtein_automata" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c2cdeb66e45e9f36bfad5bbdb4d2384e70936afbee843c6f6543f0c551ebb25" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libmimalloc-sys" +version = "0.1.49" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9" +dependencies = [ + "cc", +] + +[[package]] +name = "linkme" +version = "0.3.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3045e122bd98aef8ec3ad58ce84f0791f64e70163d1a02710af4aa11a4d54cc5" +dependencies = [ + "linkme-impl", +] + +[[package]] +name = "linkme-impl" +version = "0.3.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77060ebe535362c3da75682cd17b0431017b6e7c5661e714fc69a7ad017d1301" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "loom" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "419e0dc8046cb947daa77eb95ae174acfbddb7673b4151f56d1eed8e93fbfaca" +dependencies = [ + "cfg-if", + "generator", + "scoped-tls", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "lru" +version = "0.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39" +dependencies = [ + "hashbrown 0.16.1", +] + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "lz4_flex" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef0d4ed8669f8f8826eb00dc878084aa8f253506c4fd5e8f58f5bce72ddb97e" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8863b587001c1b9a8a4e36008cebc6b3612cb1226fe2de94858e06092687b608" + +[[package]] +name = "measure_time" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51c55d61e72fc3ab704396c5fa16f4c184db37978ae4e94ca8959693a235fc0e" +dependencies = [ + "log", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "miette" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7" +dependencies = [ + "cfg-if", + "miette-derive", + "unicode-width", +] + +[[package]] +name = "miette-derive" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "mimalloc" +version = "0.1.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d4139bb28d14ad1facf21d5eb8825051b326e172d216b39f6d31df53cc97862" +dependencies = [ + "libmimalloc-sys", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", +] + +[[package]] +name = "murmurhash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2195bf6aa996a481483b29d62a7663eed3fe39600c460e323f8ff41e90bdd89b" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.8", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "oneshot" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "269bca4c2591a28585d6bf10d9ed0332b7d76900a1b02bec41bdc3a2cdcda107" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "ordered-float" +version = "5.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ownedbytes" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fbd56f7631767e61784dc43f8580f403f4475bd4aaa4da003e6295e1bab4a7e" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "owo-colors" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f" + +[[package]] +name = "pack1" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3b7bb0ecf2e447b1f20ee94ee79ef6eed1e9d4b3c36ce1903b9dea3bf205523" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared", + "rand 0.8.8", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.4", + "windows-sys 0.61.2", +] + +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "serde_core", + "writeable", + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn 3.0.4", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "prost" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" +dependencies = [ + "anyhow", + "itertools 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quinn" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash 2.1.3", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04759210543be93709136e28212294a659ef5001836ff4eab4d663e4529bba83" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.2", + "rand_pcg 0.10.2", + "ring", + "rustc-hash 2.1.3", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "quoted_printable" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "478e0585659a122aa407eb7e3c0e1fa51b1d8a870038bd29f0cf4a8551eea972" + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +dependencies = [ + "chacha20 0.10.2", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59cad018caf63deb318e5a4586d99a24424a364f40f1e5778c29aca23f4fc73e" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "rapidhash" +version = "4.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5da7e78a036ce858e8d55b7e7dc8ba3a88b78350fd2155d3591bbd966b58589e" +dependencies = [ + "rustversion", +] + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http 0.6.11", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "roaring" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18bd8a37d17a58532776dcdf6041ce64929adca78e8489d5cacbafe99229d3e1" +dependencies = [ + "bytemuck", + "byteorder", +] + +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rust-stemmers" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e46a2036019fdb888131db7a4c847a1063a7493f971ed94ea82c67eada63ca54" +dependencies = [ + "serde", + "serde_derive", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustc_version_runtime" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dd18cd2bae1820af0b6ad5e54f4a51d0f3fcc53b05f845675074efcc7af071d" +dependencies = [ + "rustc_version", + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06" +dependencies = [ + "aws-lc-rs", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "shuttle" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab17edba38d63047f46780cf7360acf7467fec2c048928689a5c1dd1c2b4e31" +dependencies = [ + "assoc", + "bitvec", + "cfg-if", + "generator", + "hex", + "owo-colors", + "rand 0.8.8", + "rand_core 0.6.4", + "rand_pcg 0.3.1", + "scoped-tls", + "smallvec", + "tracing", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "simsimd" +version = "6.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4fb3bc3cdce07a7d7d4caa4c54f8aa967f6be41690482b54b24100a2253fa70" +dependencies = [ + "cc", +] + +[[package]] +name = "siphasher" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" + +[[package]] +name = "sketches-ddsketch" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "513c3f5f732bfd6fbb187619c2dfe9d2f25f1a2976f01d575f0fd329d565df56" +dependencies = [ + "serde", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9be42f50aa861c555654aa3a37f52f4b1074bacf4e48fe0ef7fa584e80f1f0f" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "softaes" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45e14297decde697ddf377c25752aead0927d5cfc89c2684d2af96901a4ceeea" + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "symlink" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6275cddf4610d1775e6d1fe9469b2e77d0f39fd98fb7450901b821e0c53649f" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tantivy" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edde6a10743fff00a4e1a8c9ef020bf5f3cbad301b7d2d39f2b07f123c4eac07" +dependencies = [ + "aho-corasick", + "arc-swap", + "base64 0.22.1", + "bitpacking", + "bon", + "byteorder", + "census", + "crc32fast", + "crossbeam-channel", + "datasketches", + "downcast-rs", + "fastdivide", + "fnv", + "fs4", + "htmlescape", + "itertools 0.14.0", + "levenshtein_automata", + "log", + "lru", + "lz4_flex", + "measure_time", + "memmap2", + "once_cell", + "oneshot", + "rayon", + "regex", + "rust-stemmers", + "rustc-hash 2.1.3", + "serde", + "serde_json", + "sketches-ddsketch", + "smallvec", + "tantivy-bitpacker", + "tantivy-columnar", + "tantivy-common", + "tantivy-fst", + "tantivy-query-grammar", + "tantivy-stacker", + "tantivy-tokenizer-api", + "tempfile", + "thiserror", + "time", + "typetag", + "uuid", + "winapi", +] + +[[package]] +name = "tantivy-bitpacker" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fed3d674429bcd2de5d0a6d1aa5495fed8afd9c5ecce993019caf7615f53fa4" +dependencies = [ + "bitpacking", +] + +[[package]] +name = "tantivy-columnar" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c57166f5bcfd478f370ab8445afb4678dce44801fa5ce5c451aaf8595583c5dc" +dependencies = [ + "downcast-rs", + "fastdivide", + "itertools 0.14.0", + "serde", + "tantivy-bitpacker", + "tantivy-common", + "tantivy-sstable", + "tantivy-stacker", +] + +[[package]] +name = "tantivy-common" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbf10915aa75da3c3b0d58b58853d2e889efbaf32d4982a4c3715dde6bba23e5" +dependencies = [ + "async-trait", + "byteorder", + "ownedbytes", + "serde", + "time", +] + +[[package]] +name = "tantivy-fst" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d60769b80ad7953d8a7b2c70cdfe722bbcdcac6bccc8ac934c40c034d866fc18" +dependencies = [ + "byteorder", + "regex-syntax", + "utf8-ranges", +] + +[[package]] +name = "tantivy-query-grammar" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfadb8526b6da90704feb293b0701a6aae62ea14983143344be2dc5ce30f1d82" +dependencies = [ + "fnv", + "nom 7.1.3", + "ordered-float", + "serde", + "serde_json", +] + +[[package]] +name = "tantivy-sstable" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a2cfc3ac5164cbadc28965ffb145a8f47582a60ae5897859ad8d4316596c606" +dependencies = [ + "futures-util", + "itertools 0.14.0", + "tantivy-bitpacker", + "tantivy-common", + "tantivy-fst", + "zstd", +] + +[[package]] +name = "tantivy-stacker" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cbb051742da9d53ca9e8fff43a9b10e319338b24e2c0e15d0372df19ffeb951" +dependencies = [ + "murmurhash32", + "tantivy-common", +] + +[[package]] +name = "tantivy-tokenizer-api" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eac258c2c6390673f2685813afeeafcb8c4e0ee7de8dd3fc46838dcc37263f98" +dependencies = [ + "serde", +] + +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.4", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cf0ded5c4e56918d8f8a339e1bb67d038d3bc6d144ac407904015ba2e4cde9b" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12c0ba9680044b4ce98d391a62094047eada0d64860b80166c39f4a6b5640785" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.13+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" + +[[package]] +name = "topcoat" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050c11e7b0e146a2b1eb15855abd5fa03e2754eb880922f8b6cab5ec71cac5aa" +dependencies = [ + "futures-util", + "inventory", + "serde", + "serde_urlencoded", + "tokio", + "tokio-tungstenite", + "topcoat-asset", + "topcoat-cookie", + "topcoat-core", + "topcoat-core-macro", + "topcoat-font", + "topcoat-font-macro", + "topcoat-mail", + "topcoat-router", + "topcoat-router-macro", + "topcoat-runtime", + "topcoat-runtime-macro", + "topcoat-session", + "topcoat-view", + "topcoat-view-macro", +] + +[[package]] +name = "topcoat-asset" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a72e4ba8cb6a9d29613a25c2151e72d887b4a79b3f179b497734eed0e65ea702" +dependencies = [ + "http", + "memchr", + "serde", + "sha2 0.11.0", + "thiserror", + "tokio", + "toml", + "topcoat-core", + "topcoat-router", + "topcoat-view", +] + +[[package]] +name = "topcoat-cookie" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f68c83654c4bf075f667d39463cd38ef0be9fee057054454b06612efe16e7a37" +dependencies = [ + "cookie", + "getrandom 0.2.17", + "http", + "serde", + "serde_json", + "topcoat-core", + "topcoat-router", +] + +[[package]] +name = "topcoat-core" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f94adaa301d7a4b949d650fa803323c00cc8ffa8bf1984511c1ec5d390b6c6" +dependencies = [ + "anyhow", + "anymap3", + "elsa", + "http", + "pin-project-lite", + "siphasher", + "thiserror", + "tokio", +] + +[[package]] +name = "topcoat-core-grammar" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0756aa9285794c155624494bc563d56859e35205313db883a89d7dabfa6d0393" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "topcoat-core-macro" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4908dba6268c8592be73e9059cdefa053066e1b1bc879c1c9a5d8d3b6e97aad" +dependencies = [ + "quote", + "syn 2.0.119", + "topcoat-core-grammar", +] + +[[package]] +name = "topcoat-font" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7b8308aff65f46bbe2f58371fc9823db596236bd0ea3c9d87de6534fd977e60" +dependencies = [ + "heck", + "inventory", + "serde", + "serde_json", + "topcoat-asset", + "topcoat-core", + "topcoat-router", + "topcoat-view", + "topcoat-view-macro", +] + +[[package]] +name = "topcoat-font-grammar" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b7d68e226827fb7531d0dba69cb74fa7b82515f8428fd1a75f556f5a2bf87c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "topcoat-core-grammar", + "topcoat-font", +] + +[[package]] +name = "topcoat-font-macro" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e655c430bcb380f879603ea750c6222ade2ff3ade33869d9eaa32e3fc49f5469" +dependencies = [ + "quote", + "syn 2.0.119", + "topcoat-font-grammar", +] + +[[package]] +name = "topcoat-mail" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "959c9c32172ad3840f94c589a29bd143c072661c9abf2215a68fd76440ed2300" +dependencies = [ + "lettre", + "thiserror", + "time", + "topcoat-core", + "topcoat-router", + "topcoat-view", +] + +[[package]] +name = "topcoat-router" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e062bd348df5647f6904f4f4045b3c92c08c4a8826196e8e91a51aade00b5764" +dependencies = [ + "bytes", + "form_urlencoded", + "futures-core", + "futures-util", + "heck", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "inventory", + "matchit", + "multer", + "percent-encoding", + "ref-cast", + "serde", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "tokio", + "topcoat-core", + "topcoat-view", + "tower", + "tower-http 0.7.1", +] + +[[package]] +name = "topcoat-router-grammar" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c052423d2aa4039036f1ac5567d1e2dac48897602d34561b3024a87830e5bdce" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", + "topcoat-core-grammar", +] + +[[package]] +name = "topcoat-router-macro" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cea98692b786bab3adda35a60d71981f60b2a98c6e7105ac92e582b7c9ce9cab" +dependencies = [ + "quote", + "syn 2.0.119", + "topcoat-router-grammar", +] + +[[package]] +name = "topcoat-runtime" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dea200c86ca554bab7410f09cae8790a8adcbfd8f306eb78db7092ca71f8aae" +dependencies = [ + "inventory", + "ref-cast", + "serde", + "serde_json", + "topcoat-asset", + "topcoat-core", + "topcoat-router", + "topcoat-view", + "uuid", +] + +[[package]] +name = "topcoat-runtime-grammar" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87b73f7e4e10f49e006a71dd43e8ee629c76c08451acbc51faa7ec5b6952c53c" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "serde_json", + "syn 2.0.119", + "topcoat-core-grammar", + "topcoat-runtime", + "uuid", +] + +[[package]] +name = "topcoat-runtime-macro" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dc3e4e245abcaea6af780437cae072e8f2157c9852ec5b3058a658c61b9e0bf" +dependencies = [ + "quote", + "syn 2.0.119", + "topcoat-runtime-grammar", +] + +[[package]] +name = "topcoat-session" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e079e8c5a63987d7f929ab05a75922feab1fe390a9cfa2c101eb35829e67eac2" +dependencies = [ + "base64 0.22.1", + "getrandom 0.4.3", + "sha2 0.11.0", + "thiserror", + "tokio", + "topcoat-cookie", + "topcoat-core", + "topcoat-router", + "web-time", +] + +[[package]] +name = "topcoat-view" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5904449bd6f633759d187fa621ded68178b551428c297959fd53d8fb91f3e6f6" +dependencies = [ + "futures-core", + "futures-util", + "http", + "itoa", + "memchr", + "pin-project-lite", + "smallvec", + "topcoat-core", +] + +[[package]] +name = "topcoat-view-grammar" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bf4293156d7c5fa7960edc573b686eb27426dcd888bfbe9e532304178cdda24" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", + "topcoat-core-grammar", + "topcoat-view", +] + +[[package]] +name = "topcoat-view-macro" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58ab2b200eda4516abdb543f307006d83fedd3681b871d2042c17106c688f716" +dependencies = [ + "quote", + "syn 2.0.119", + "topcoat-view-grammar", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-http" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08a05a66a4fdd61cbbe0a1d755ffe0ca6aba159dd4820936a0ff8a8278245b9c" +dependencies = [ + "async-compression", + "bitflags", + "bytes", + "futures-core", + "http", + "http-body", + "percent-encoding", + "pin-project-lite", + "tokio", + "tokio-util", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-appender" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" +dependencies = [ + "crossbeam-channel", + "symlink", + "thiserror", + "time", + "tracing-subscriber", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror", +] + +[[package]] +name = "turso" +version = "0.8.0-pre.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9adfdd5efe2e9ee9d1c38039f874a2773f26553ab06b0b58104efd5ff6dadda6" +dependencies = [ + "mimalloc", + "thiserror", + "tracing", + "tracing-subscriber", + "turso_core", + "turso_sdk_kit", + "turso_sync_sdk_kit", +] + +[[package]] +name = "turso_core" +version = "0.8.0-pre.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8aa9df0e2dd9894ddc61cf6c35e0726f4fc26dd08c584afebd319c1969aaf504" +dependencies = [ + "aegis", + "aes", + "aes-gcm", + "allocator-api2 0.4.0", + "antithesis_sdk", + "arc-swap", + "aristo", + "bigdecimal", + "bitflags", + "branches", + "bumpalo", + "bytemuck", + "cfg_aliases", + "cfg_block", + "chrono", + "crc32c", + "crc32fast", + "crossbeam-epoch", + "crossbeam-utils", + "either", + "fallible-iterator", + "fastbloom", + "getrandom 0.2.17", + "getrandom 0.3.4", + "hex", + "icu_collator", + "icu_locale", + "intrusive-collections", + "io-uring", + "libc", + "libloading", + "libm", + "loom", + "miette", + "num-bigint", + "num-traits", + "pack1", + "parking_lot", + "pastey", + "polling", + "rand 0.9.5", + "rapidhash", + "regex", + "regex-syntax", + "roaring", + "rustc-hash 2.1.3", + "rustix 1.1.4", + "ryu", + "serde_json", + "shuttle", + "simdutf8", + "simsimd", + "smallvec", + "strum", + "strum_macros", + "tantivy", + "tempfile", + "thiserror", + "tracing", + "tracing-subscriber", + "turso_ext", + "turso_macros", + "turso_parser", + "twox-hash", + "uncased", + "uuid", + "windows-sys 0.61.2", +] + +[[package]] +name = "turso_ext" +version = "0.8.0-pre.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a27e351e5f30b21d186a62895761a59a944e209111ea7ba84bf8c611068d87fc" +dependencies = [ + "chrono", + "getrandom 0.4.3", + "turso_macros", +] + +[[package]] +name = "turso_macros" +version = "0.8.0-pre.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5c30032b9cd45798d5ed012a3728d9cf4e39a8dbb7d820d82908facb4b665dc" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "turso_parser" +version = "0.8.0-pre.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6823c91624d12ae67d6c6dfc819406a279265ca8879307f92c12d7de77bc6846" +dependencies = [ + "bitflags", + "memchr", + "miette", + "strum", + "strum_macros", + "thiserror", + "turso_macros", +] + +[[package]] +name = "turso_sdk_kit" +version = "0.8.0-pre.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e73f5242b4cbbee9fe8fddbe1ea7be4154f9c4a647199010ea97e479f0f28b28" +dependencies = [ + "bindgen", + "env_logger", + "parking_lot", + "tracing", + "tracing-appender", + "tracing-subscriber", + "turso_core", + "turso_ext", + "turso_sdk_kit_macros", +] + +[[package]] +name = "turso_sdk_kit_macros" +version = "0.8.0-pre.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca9b8b244a1e289b1db7d35c32822f0f2f3af4ceba07cb9447064436c72306d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "turso_sync_engine" +version = "0.8.0-pre.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89d84c7f7973983c2a81dcfa2c94296d29d46a6856cc4b735abc18878e315efe" +dependencies = [ + "base64 0.22.1", + "bytes", + "crc32c", + "genawaiter", + "http", + "libc", + "prost", + "roaring", + "serde", + "serde_json", + "thiserror", + "tracing", + "turso_core", + "turso_parser", + "uuid", +] + +[[package]] +name = "turso_sync_sdk_kit" +version = "0.8.0-pre.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357e81612a02848114f2ad4fbbc7ede242c7eb4a8ca981092fae2278984deba5" +dependencies = [ + "bindgen", + "env_logger", + "genawaiter", + "parking_lot", + "tracing", + "tracing-appender", + "tracing-subscriber", + "turso_core", + "turso_sdk_kit", + "turso_sdk_kit_macros", + "turso_sync_engine", +] + +[[package]] +name = "twox-hash" +version = "2.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5283634e518fe9e82c7b20520bb4bc209009fd16c82077c802f8111ecbb0117a" +dependencies = [ + "rand 0.10.2", +] + +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "typetag" +version = "0.2.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c90e86058a30d42a1a928dfb4b49bb33c98c3a2b4909492e6b0881cd94798ec2" +dependencies = [ + "erased-serde", + "inventory", + "once_cell", + "serde", + "typetag-impl", +] + +[[package]] +name = "typetag-impl" +version = "0.2.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f153acc4e99a5f2a5aefa09fb078be54e26271b2813f6041200b224c098d8328" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "ulid" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "470dbf6591da1b39d43c14523b2b469c86879a53e8b758c8e090a470fe7b1fbe" +dependencies = [ + "rand 0.9.5", + "web-time", +] + +[[package]] +name = "uncased" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697" +dependencies = [ + "version_check", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf16_iter" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" + +[[package]] +name = "utf8-ranges" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fcfc827f90e53a02eaef5e535ee14266c1d569214c6aa70133a624d8a3164ba" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uuid" +version = "1.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5772d71c9be8a8a6ac2117d949c5b224c1b72241bb611d9a3012edcf8af7812" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "sha1_smol", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b7777d5cc23d0e91404e53ce2d5e8ec7acae3026b16233dba62cd3246457950" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c435338968042f4f59a557f690a253676d47ce13ceb55d70100e7facf6620a30" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "which" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" +dependencies = [ + "either", + "home", + "once_cell", + "rustix 0.38.44", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "write16" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "serde", + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.4", +] + +[[package]] +name = "zip" +version = "8.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +dependencies = [ + "crc32fast", + "flate2", + "indexmap", + "memchr", + "typed-path", + "zopfli", +] + +[[package]] +name = "zlib-rs" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zopfli" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.16+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" +dependencies = [ + "cc", + "pkg-config", +] + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..b33f77d --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,47 @@ +[workspace] +resolver = "3" +members = ["crates/in-core", "crates/in-client", "crates/in-web"] + +[workspace.package] +version = "0.1.0" +edition = "2024" +license = "GPL-3.0-or-later" +repository = "https://github.com/DizeyLab/in" + +[workspace.dependencies] +in-core = { path = "crates/in-core", default-features = false } +in-client = { path = "crates/in-client" } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.145" +thiserror = "2.0.20" +ulid = "1" +time = { version = "0.3.55", features = ["serde", "formatting", "parsing", "macros"] } +tokio = { version = "1.53.1", features = ["full"] } +turso = "=0.8.0-pre.8" +rand = "0.10.2" +sha2 = "0.11.0" +subtle = "2.6.1" +chacha20poly1305 = "0.10.1" +base64 = "0.22.1" +toml = "1" +async-trait = "0.1.92" +image = { version = "0.25", default-features = false, features = [ + "jpeg", + "png", + "gif", + "webp", +] } + +[profile.release] +codegen-units = 1 +lto = true + +# What the deploy builds. Fat LTO and one codegen unit buy the last few +# percent by optimizing the whole program in a single non-parallel pass — +# worth it for something CPU-bound, not for a server whose time goes to +# SQLite, TLS and the network. Thin LTO still optimizes across crates, in +# parallel, so `release` stays available for when the trade is worth making. +[profile.dist] +inherits = "release" +lto = "thin" +codegen-units = 16 diff --git a/crates/in-client/Cargo.toml b/crates/in-client/Cargo.toml new file mode 100644 index 0000000..2205491 --- /dev/null +++ b/crates/in-client/Cargo.toml @@ -0,0 +1,49 @@ +[package] +name = "in-client" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +description = "Drop-in OIDC client for topcoat apps authenticating against im" + +[dependencies] +topcoat = { version = "0.6.2", default-features = false, features = [ + "router", + "cookie", +] } +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +time.workspace = true +tokio.workspace = true +base64.workspace = true +rand.workspace = true +sha2.workspace = true +subtle.workspace = true +chacha20poly1305.workspace = true +# rsa 0.9 verifies through the digest 0.10 traits, so its hasher comes from +# the sha2 0.10 line; the workspace sha2 0.11 stays for PKCE. +sha2-for-rsa = { package = "sha2", version = "0.10", features = ["oid"] } +rsa = "0.9.10" +reqwest = { version = "0.13.4", default-features = false, features = [ + "rustls", + "json", + "form", +] } + + +[features] +test-seam = [] + +[dev-dependencies] +topcoat = { version = "0.6.2", default-features = false, features = [ + "router", + "cookie", + "view", + "serve", + "discover", +] } +http = "1.5" +# Tests generate their own RSA keys, and rsa 0.9's RNG is the rand_core 0.6 +# line. +rand_core06 = { package = "rand_core", version = "0.6.4", features = ["getrandom"] } diff --git a/crates/in-client/src/lib.rs b/crates/in-client/src/lib.rs new file mode 100644 index 0000000..7d14240 --- /dev/null +++ b/crates/in-client/src/lib.rs @@ -0,0 +1,1310 @@ +//! in-client: drop-in OIDC client for topcoat apps authenticating against im. +//! +//! An app adds three things: `in_client::mount(builder, config)` when it +//! builds its router, `.discover()` as usual (the `/auth/login`, +//! `/auth/callback`, `/auth/logout` routes register themselves), and +//! `in_client::current_user(cx)` wherever it needs the person. +//! +//! The model: im holds the central session; this crate holds the app's side +//! of it — an encrypted cookie with the identity claims and the refresh +//! token. When the access token ages out, `current_user` silently rotates it +//! against im; when im has revoked the central session, the rotation is +//! refused and the app sees a signed-out user. + +use base64::Engine; +use base64::engine::general_purpose::URL_SAFE_NO_PAD as b64url; +use chacha20poly1305::aead::Aead; +use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; +use rand::Rng; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use subtle::ConstantTimeEq; +use time::OffsetDateTime; +use topcoat::context::{Cx, try_app_context}; +use topcoat::cookie::{Cookie, Cookies, cookie, cookies}; +use topcoat::router::response::{IntoResponse, Response}; +use topcoat::router::{HeaderValue, RouterBuilder, StatusCode, header, route}; + +// --------------------------------------------------------------------------- +// Configuration and state +// --------------------------------------------------------------------------- + +/// Everything the app knows about its im registration. `client_secret` and +/// `cookie_key` are secrets: the first authenticates the app to im, the +/// second seals the browser cookies this crate writes. +#[derive(Clone)] +pub struct Config { + /// im's base URL, e.g. `http://127.0.0.1:7650` or `https://auth.example.com`. + pub issuer: String, + pub client_id: String, + pub client_secret: String, + /// Must exactly match one of the URIs registered with im. + pub redirect_uri: String, + /// The app's session cookie name, e.g. `in_session`. + pub cookie_name: String, + /// 32 bytes, generated once per app and kept out of the repository. + pub cookie_key: [u8; 32], +} + +/// The registered state: the config, one HTTP client, and the JWKS cache. +pub struct InClient { + config: Config, + http: reqwest::Client, + jwks: tokio::sync::RwLock>, +} + +struct JwksCache { + fetched_at: OffsetDateTime, + /// kid -> public key + keys: Vec<(String, rsa::RsaPublicKey)>, +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("http: {0}")] + Http(String), + #[error("im refused: {0}")] + Refused(String), + #[error("bad token: {0}")] + Token(String), +} + +pub type Result = std::result::Result; + +impl InClient { + pub fn new(config: Config) -> Self { + InClient { + config, + http: reqwest::Client::new(), + jwks: tokio::sync::RwLock::new(None), + } + } +} + +/// Registers the client state on the router. The routes themselves register +/// through `discover()` — call it as usual. +pub fn mount(builder: RouterBuilder, config: Config) -> RouterBuilder { + builder.app_context(InClient::new(config)) +} + +fn client(cx: &Cx) -> &InClient { + try_app_context::(cx).expect("in_client::mount was called on the router") +} + +/// The authenticated person, if this browser has one. Every call asks im: +/// the cookie holds an opaque session token, introspected per request, so an +/// admin revoking the person signs them out of this app immediately — there +/// is no token-validity window in which a ghost lives. +pub async fn current_user(cx: &Cx) -> Option { + let state = client(cx); + let sealed = cookies(cx).get(&state.config.cookie_name)?; + let session: Session = open_json(&state.config.cookie_key, sealed.value())?; + if session.exp <= OffsetDateTime::now_utc().unix_timestamp() { + clear_cookie(cx, &state.config.cookie_name); + return None; + } + match introspect(state, &session.app_session).await { + Introspected::Active(user, _exp) => Some(user), + Introspected::Revoked => { + clear_cookie(cx, &state.config.cookie_name); + None + } + // The question went unanswered — a blackholed route, a dropped + // connection, a body that is not the JSON im speaks. Nothing was + // learned about the session, so this request reads as signed-out + // while the cookie stays for the next request to try again. + Introspected::Unanswered => None, + } +} + +/// Path of im's RFC 7662 introspection endpoint, relative to the issuer. +const INTROSPECT_PATH: &str = "/introspect"; + +/// What one introspection round-trip settled. +enum Introspected { + /// im answered `"active": true` with usable claims. + Active(User, i64), + /// im answered `"active": false`: the central session is gone and the + /// app cookie goes with it. + Revoked, + /// The question itself went unanswered — the transport failed, the body + /// was not JSON, or the claims were missing their fields. Nothing about + /// the session was learned, so the cookie must stay. + Unanswered, +} + +async fn introspect(state: &InClient, token: &str) -> Introspected { + let Ok(reply) = state + .http + .post(format!("{}{}", state.config.issuer, INTROSPECT_PATH)) + .form(&[ + ("token", token), + ("client_id", &state.config.client_id), + ("client_secret", &state.config.client_secret), + ]) + .send() + .await + else { + return Introspected::Unanswered; + }; + let Ok(answer): Result = reply.json().await else { + return Introspected::Unanswered; + }; + // Only an explicit `"active": false` revokes. A missing or non-boolean + // `active` is a malformed answer, not a revocation. + match answer.get("active") { + Some(serde_json::Value::Bool(true)) => {} + Some(serde_json::Value::Bool(false)) => return Introspected::Revoked, + _ => return Introspected::Unanswered, + } + let (Some(sub), Some(email), Some(name), Some(exp)) = ( + answer["sub"].as_str(), + answer["email"].as_str(), + answer["name"].as_str(), + answer["exp"].as_i64(), + ) else { + return Introspected::Unanswered; + }; + Introspected::Active( + User { + sub: sub.to_string(), + email: email.to_string(), + name: name.to_string(), + }, + exp, + ) +} + +/// Who this browser is, from the claims. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct User { + pub sub: String, + pub email: String, + pub name: String, +} + +// --------------------------------------------------------------------------- +// The app session cookie +// --------------------------------------------------------------------------- + +#[derive(Serialize, Deserialize)] +struct Session { + /// The opaque token im issued at the code exchange; introspected per + /// request, never trusted on its own. + app_session: String, + exp: i64, +} + +/// Test seam for integration tests: seals a session cookie exactly like the +/// `/auth/callback` handler does, without a live im. Returns the cookie +/// VALUE only; tests set the `Cookie` header themselves. +#[cfg(feature = "test-seam")] +pub fn mint_session_cookie( + config: &Config, + app_session: &str, + exp: time::OffsetDateTime, +) -> String { + seal_json( + &config.cookie_key, + &Session { + app_session: app_session.to_string(), + exp: exp.unix_timestamp(), + }, + ) +} + +/// The introspection path `current_user` POSTs to, so a fake-im test server +/// can mount the right route. +#[cfg(feature = "test-seam")] +pub fn introspect_path() -> &'static str { + INTROSPECT_PATH +} + +/// The in-flight login: PKCE verifier, state, nonce, and where to land after. +#[derive(Serialize, Deserialize)] +struct InFlight { + verifier: String, + state: String, + nonce: String, + next: String, + exp: i64, +} + +const IN_FLIGHT_MINUTES: i64 = 10; + +fn seal(key: &[u8; 32], plaintext: &[u8]) -> String { + let cipher = XChaCha20Poly1305::new(key.into()); + let mut nonce_bytes = [0u8; 24]; + rand::rng().fill_bytes(&mut nonce_bytes); + let ciphertext = cipher + .encrypt(XNonce::from_slice(&nonce_bytes), plaintext) + .expect("XChaCha20-Poly1305 cannot fail on a payload this small"); + let mut payload = nonce_bytes.to_vec(); + payload.extend_from_slice(&ciphertext); + b64url.encode(payload) +} + +fn open(key: &[u8; 32], sealed: &str) -> Option> { + let payload = b64url.decode(sealed).ok()?; + if payload.len() < 24 { + return None; + } + let (nonce_bytes, ciphertext) = payload.split_at(24); + let cipher = XChaCha20Poly1305::new(key.into()); + cipher + .decrypt(XNonce::from_slice(nonce_bytes), ciphertext) + .ok() +} + +fn seal_json(key: &[u8; 32], value: &T) -> String { + seal(key, &serde_json::to_vec(value).expect("plain data")) +} + +fn open_json Deserialize<'de>>(key: &[u8; 32], sealed: &str) -> Option { + serde_json::from_slice(&open(key, sealed)?).ok() +} + +fn app_cookies(cx: &Cx) -> impl Cookies { + cookies(cx) + .default_secure(client(cx).config.issuer.starts_with("https://")) + .default_http_only(true) + .default_same_site(topcoat::cookie::SameSite::Lax) + .default_path("/") +} + +fn set_session_cookie(cx: &Cx, state: &InClient, session: &Session) { + let name = state.config.cookie_name.clone(); + app_cookies(cx).add(cookie! { + name = seal_json(&state.config.cookie_key, session); + Path = "/"; + HttpOnly; + SameSite = Lax; + MaxAge = time::Duration::days(30) + }); +} + +fn clear_cookie(cx: &Cx, name: &str) { + app_cookies(cx).remove(Cookie::build((name.to_string(), "")).path("/").build()); +} + +// --------------------------------------------------------------------------- +// Routes +// --------------------------------------------------------------------------- + +fn see(cx: &Cx, location: &str) -> Result { + ( + StatusCode::SEE_OTHER, + [(header::LOCATION, location_value(location))], + ) + .into_response(cx) +} + +/// A `Location` value that cannot panic its handler: anything `HeaderValue` +/// still refuses (a hostile `next` sealed before the strict validation, a +/// query echo) lands on `/` instead of killing the request. +fn location_value(location: &str) -> HeaderValue { + HeaderValue::from_str(location).unwrap_or_else(|_| HeaderValue::from_static("/")) +} + +/// A `next` worth honoring: a local absolute path, never `//elsewhere`, +/// never carrying control bytes, never touching a backslash. The query +/// arrives percent-decoded, so `%0D%0A` is a real CR LF by the time it is +/// checked — and a sealed `next` is rendered into a `Location` header, so +/// anything `HeaderValue` would choke on must die here. Backslashes die +/// here too: browsers normalize `\` to `/` in `Location`, turning +/// `/\evil` into a cross-origin hop. +fn safe_next(raw: &str) -> &str { + if raw.starts_with('/') + && !raw.starts_with("//") + && !raw.contains('\\') + && !raw.chars().any(|c| c.is_control()) + { + raw + } else { + "/" + } +} + +/// A JWKS older than this is refreshed before the next validation. +const JWKS_TTL_SECONDS: i64 = 3600; + +async fn jwks_stale(state: &InClient) -> bool { + match state.jwks.read().await.as_ref() { + None => true, + Some(cache) => { + cache.fetched_at < OffsetDateTime::now_utc() - time::Duration::seconds(JWKS_TTL_SECONDS) + } + } +} + +fn query_value(query: &str, key: &str) -> Option { + query.split('&').find_map(|pair| { + let (k, v) = pair.split_once('=')?; + (k == key).then(|| urldecode(v)) + }) +} + +/// Percent-decodes a query value (`+` is a space, form-style). +fn urldecode(raw: &str) -> String { + let bytes = raw.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'+' => { + out.push(b' '); + i += 1; + } + b'%' if i + 2 < bytes.len() => { + let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or(""); + match u8::from_str_radix(hex, 16) { + Ok(byte) => { + out.push(byte); + i += 3; + } + Err(_) => { + out.push(b'%'); + i += 1; + } + } + } + byte => { + out.push(byte); + i += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +fn random_b64(bytes: usize) -> String { + let mut buf = vec![0u8; bytes]; + rand::rng().fill_bytes(&mut buf); + b64url.encode(buf) +} + +/// Sends the browser to im's `/authorize` with a fresh PKCE pair. +#[route(GET "/auth/login")] +async fn in_login(cx: &Cx) -> Result { + let state = client(cx); + let query = topcoat::router::request::uri(cx) + .query() + .unwrap_or("") + .to_string(); + let next = safe_next(query_value(&query, "next").as_deref().unwrap_or("/")).to_string(); + + let flight = InFlight { + verifier: random_b64(32), + state: random_b64(16), + nonce: random_b64(16), + next, + exp: OffsetDateTime::now_utc().unix_timestamp() + IN_FLIGHT_MINUTES * 60, + }; + let challenge = b64url.encode(Sha256::digest(flight.verifier.as_bytes())); + let cookie_name = format!("{}_pkce", state.config.cookie_name); + app_cookies(cx).add(cookie! { + cookie_name = seal_json(&state.config.cookie_key, &flight); + Path = "/"; + HttpOnly; + SameSite = Lax; + MaxAge = time::Duration::minutes(IN_FLIGHT_MINUTES) + }); + + let url = format!( + "{}/authorize?response_type=code&client_id={}&redirect_uri={}&scope=openid%20profile%20email&state={}&nonce={}&code_challenge={}&code_challenge_method=S256", + state.config.issuer, + state.config.client_id, + urlencoded(&state.config.redirect_uri), + flight.state, + flight.nonce, + challenge, + ); + see(cx, &url) +} + +/// im's answer lands here: exchange the code, validate the id_token, mint +/// the app session. +#[route(GET "/auth/callback")] +async fn in_callback(cx: &Cx) -> Result { + let state = client(cx); + let query = topcoat::router::request::uri(cx) + .query() + .unwrap_or("") + .to_string(); + if let Some(error) = query_value(&query, "error") { + return see(cx, &format!("/?auth_error={error}")); + } + let (Some(code), Some(presented_state)) = + (query_value(&query, "code"), query_value(&query, "state")) + else { + return see(cx, "/?auth_error=invalid_request"); + }; + let cookie_name = format!("{}_pkce", state.config.cookie_name); + let flight: Option = cookies(cx) + .get(&cookie_name) + .and_then(|c| open_json(&state.config.cookie_key, c.value())); + let Some(flight) = flight else { + return see(cx, "/?auth_error=invalid_request"); + }; + clear_cookie(cx, &cookie_name); + if flight.exp <= OffsetDateTime::now_utc().unix_timestamp() + || flight + .state + .as_bytes() + .ct_eq(presented_state.as_bytes()) + .unwrap_u8() + != 1 + { + return see(cx, "/?auth_error=invalid_state"); + } + + match exchange_code(state, &code, &flight).await { + Ok(session) => { + set_session_cookie(cx, state, &session); + // Re-validated, not trusted: the flight cookie may predate the + // strict `next` rules, and its bytes land in a header. + see(cx, safe_next(&flight.next)) + } + Err(_) => see(cx, "/?auth_error=exchange_failed"), + } +} + +/// Signs out of the app only. To end the central session too, post to im's +/// `/logout` — a link there is a silent re-login, by design. +#[route(GET "/auth/logout")] +async fn in_logout(cx: &Cx) -> Result { + clear_cookie(cx, &client(cx).config.cookie_name); + see(cx, "/") +} + +fn urlencoded(raw: &str) -> String { + let mut out = String::with_capacity(raw.len()); + for byte in raw.bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + out.push(byte as char) + } + _ => out.push_str(&format!("%{byte:02X}")), + } + } + out +} + +// --------------------------------------------------------------------------- +// Token exchange, refresh, validation +// --------------------------------------------------------------------------- + +#[derive(Deserialize)] +struct TokenAnswer { + /// Validated for its nonce and signature; the identity the app serves + /// comes from introspection, not from these claims. + id_token: String, + /// Not OIDC — im's own: the opaque session this crate introspects per + /// request. Absent means the issuer is not a current im. + app_session: Option, +} + +async fn exchange_code(state: &InClient, code: &str, flight: &InFlight) -> Result { + let answer: TokenAnswer = state + .http + .post(format!("{}/token", state.config.issuer)) + .form(&[ + ("grant_type", "authorization_code"), + ("code", code), + ("redirect_uri", &state.config.redirect_uri), + ("client_id", &state.config.client_id), + ("client_secret", &state.config.client_secret), + ("code_verifier", &flight.verifier), + ]) + .send() + .await + .map_err(|e| Error::Http(e.to_string()))? + .error_for_status() + .map_err(|e| Error::Refused(e.to_string()))? + .json() + .await + .map_err(|e| Error::Http(e.to_string()))?; + let claims = validate_id_token(state, &answer.id_token).await?; + if claims["nonce"].as_str() != Some(flight.nonce.as_str()) { + return Err(Error::Token("nonce mismatch".into())); + } + let app_session = answer + .app_session + .ok_or_else(|| Error::Token("issuer gave no app session".into()))?; + // The session's expiry and identity come from a live introspection, not + // from the token answer — the same check every later request will make. + // Any non-answer (revoked or unanswered alike) means there is no fresh + // session to mint. + let (_user, exp) = match introspect(state, &app_session).await { + Introspected::Active(user, exp) => (user, exp), + Introspected::Revoked | Introspected::Unanswered => { + return Err(Error::Refused("fresh app session does not introspect".into())); + } + }; + Ok(Session { app_session, exp }) +} + +/// Validates an id_token: RS256 against im's JWKS, issuer, audience, expiry. +/// The nonce is the caller's to check (only the callback holds one). +async fn validate_id_token(state: &InClient, token: &str) -> Result { + let parts: Vec<&str> = token.split('.').collect(); + if parts.len() != 3 { + return Err(Error::Token("not a compact JWT".into())); + } + let header: serde_json::Value = serde_json::from_slice( + &b64url + .decode(parts[0]) + .map_err(|e| Error::Token(e.to_string()))?, + ) + .map_err(|e| Error::Token(e.to_string()))?; + if header["alg"] != "RS256" { + return Err(Error::Token("unexpected alg".into())); + } + let kid = header["kid"] + .as_str() + .ok_or_else(|| Error::Token("no kid".into()))? + .to_string(); + + if jwks_stale(state).await { + refetch_jwks(state).await?; + } + let key = match cached_key(state, &kid).await { + Some(key) => key, + None => { + refetch_jwks(state).await?; + cached_key(state, &kid) + .await + .ok_or_else(|| Error::Token("unknown kid after refetch".into()))? + } + }; + + verify_claims(&parts, &key, &state.config.issuer, &state.config.client_id) +} + +/// The pure half of [`validate_id_token`]: signature, issuer, audience, +/// expiry. Split out so the test suite signs its own tokens without standing +/// a server up. +fn verify_claims( + parts: &[&str], + key: &rsa::RsaPublicKey, + issuer: &str, + client_id: &str, +) -> Result { + use rsa::signature::Verifier; + let signature_bytes = b64url + .decode(parts[2]) + .map_err(|e| Error::Token(e.to_string()))?; + let signature = rsa::pkcs1v15::Signature::try_from(signature_bytes.as_slice()) + .map_err(|e| Error::Token(e.to_string()))?; + let verifying = rsa::pkcs1v15::VerifyingKey::::new(key.clone()); + verifying + .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &signature) + .map_err(|_| Error::Token("bad signature".into()))?; + + let claims: serde_json::Value = serde_json::from_slice( + &b64url + .decode(parts[1]) + .map_err(|e| Error::Token(e.to_string()))?, + ) + .map_err(|e| Error::Token(e.to_string()))?; + if claims["iss"].as_str() != Some(issuer) { + return Err(Error::Token("wrong issuer".into())); + } + if claims["aud"].as_str() != Some(client_id) { + return Err(Error::Token("wrong audience".into())); + } + match claims["exp"].as_i64() { + Some(exp) if exp > OffsetDateTime::now_utc().unix_timestamp() => {} + _ => return Err(Error::Token("expired".into())), + } + Ok(claims) +} + +async fn cached_key(state: &InClient, kid: &str) -> Option { + state + .jwks + .read() + .await + .as_ref()? + .keys + .iter() + .find(|(k, _)| k == kid) + .map(|(_, key)| key.clone()) +} + +/// Fetches and caches im's JWKS. Cached for an hour at most; an unknown kid +/// forces an immediate refetch above. +async fn refetch_jwks(state: &InClient) -> Result<()> { + let doc: serde_json::Value = state + .http + .get(format!("{}/jwks.json", state.config.issuer)) + .send() + .await + .map_err(|e| Error::Http(e.to_string()))? + .error_for_status() + .map_err(|e| Error::Refused(e.to_string()))? + .json() + .await + .map_err(|e| Error::Http(e.to_string()))?; + let mut keys = Vec::new(); + for jwk in doc["keys"].as_array().into_iter().flatten() { + let (Some(kid), Some(n), Some(e)) = + (jwk["kid"].as_str(), jwk["n"].as_str(), jwk["e"].as_str()) + else { + continue; + }; + let (Ok(n), Ok(e)) = (b64url.decode(n), b64url.decode(e)) else { + continue; + }; + let key = rsa::RsaPublicKey::new( + rsa::BigUint::from_bytes_be(&n), + rsa::BigUint::from_bytes_be(&e), + ) + .map_err(|err| Error::Token(format!("bad jwk {kid}: {err}")))?; + keys.push((kid.to_string(), key)); + } + *state.jwks.write().await = Some(JwksCache { + fetched_at: OffsetDateTime::now_utc(), + keys, + }); + Ok(()) +} +#[cfg(test)] +mod tests { + use super::*; + use rsa::signature::{SignatureEncoding, Signer}; + use rsa::traits::PublicKeyParts; + use topcoat::cookie::RouterBuilderCookieExt; + use topcoat::router::{Body, Router, to_bytes}; + use std::sync::{Arc, OnceLock}; + + fn keypair() -> (rsa::RsaPrivateKey, rsa::RsaPublicKey) { + // 2048-bit generation is slow for a unit test; 1024 is the smallest + // rsa 0.9 accepts and the signature math under test is identical. + let private = rsa::RsaPrivateKey::new(&mut rand_core06::OsRng, 1024).unwrap(); + let public = private.to_public_key(); + (private, public) + } + + fn sign(claims: serde_json::Value, key: &rsa::RsaPrivateKey) -> String { + let header = serde_json::json!({"alg": "RS256", "typ": "JWT", "kid": "test"}); + let mut out = b64url.encode(header.to_string()); + out.push('.'); + out.push_str(&b64url.encode(claims.to_string())); + let signing = rsa::pkcs1v15::SigningKey::::new(key.clone()); + let signature = signing.sign(out.as_bytes()); + format!("{}.{}", out, b64url.encode(signature.to_bytes())) + } + + fn good_claims() -> serde_json::Value { + serde_json::json!({ + "iss": "http://im.test", + "sub": "user-1", + "aud": "client-1", + "exp": OffsetDateTime::now_utc().unix_timestamp() + 600, + "iat": OffsetDateTime::now_utc().unix_timestamp(), + "email": "ann@example.com", + "name": "Ann", + }) + } + + #[test] + fn valid_token_validates() { + let (private, public) = keypair(); + let token = sign(good_claims(), &private); + let parts: Vec<&str> = token.split('.').collect(); + let claims = verify_claims(&parts, &public, "http://im.test", "client-1").unwrap(); + assert_eq!(claims["sub"], "user-1"); + } + + #[test] + fn tampered_payload_rejected() { + let (private, public) = keypair(); + let token = sign(good_claims(), &private); + let parts: Vec<&str> = token.split('.').collect(); + let forged_payload = b64url.encode(r#"{"sub":"mallory"}"#); + let forged = vec![parts[0], forged_payload.as_str(), parts[2]]; + assert!(verify_claims(&forged, &public, "http://im.test", "client-1").is_err()); + } + + #[test] + fn wrong_key_rejected() { + let (private, _) = keypair(); + let (_, other_public) = keypair(); + let token = sign(good_claims(), &private); + let parts: Vec<&str> = token.split('.').collect(); + assert!(verify_claims(&parts, &other_public, "http://im.test", "client-1").is_err()); + } + + #[test] + fn wrong_audience_rejected() { + let (private, public) = keypair(); + let token = sign(good_claims(), &private); + let parts: Vec<&str> = token.split('.').collect(); + assert!(verify_claims(&parts, &public, "http://im.test", "another-app").is_err()); + } + + #[test] + fn wrong_issuer_rejected() { + let (private, public) = keypair(); + let token = sign(good_claims(), &private); + let parts: Vec<&str> = token.split('.').collect(); + assert!(verify_claims(&parts, &public, "https://elsewhere.example", "client-1").is_err()); + } + + #[test] + fn expired_rejected() { + let (private, public) = keypair(); + let mut claims = good_claims(); + claims["exp"] = (OffsetDateTime::now_utc().unix_timestamp() - 10).into(); + let token = sign(claims, &private); + let parts: Vec<&str> = token.split('.').collect(); + assert!(verify_claims(&parts, &public, "http://im.test", "client-1").is_err()); + } + + #[test] + fn pkce_rfc7636_vector() { + // RFC 7636 Appendix B. + let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; + let challenge = b64url.encode(Sha256::digest(verifier.as_bytes())); + assert_eq!(challenge, "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"); + } + + #[test] + fn cookie_seal_roundtrip() { + let key = [7u8; 32]; + let session = Session { + app_session: "opaque-token".into(), + exp: 1, + }; + let sealed = seal_json(&key, &session); + let back: Session = open_json(&key, &sealed).unwrap(); + assert_eq!(back.app_session, "opaque-token"); + assert!(open_json::(&[8u8; 32], &sealed).is_none()); + assert!(open_json::(&key, "garbage").is_none()); + } + + #[cfg(feature = "test-seam")] + #[test] + fn seam_cookie_reads_back() { + let config = Config { + issuer: "http://im.test".into(), + client_id: "client-1".into(), + client_secret: "secret".into(), + redirect_uri: "http://app.test/auth/callback".into(), + cookie_name: "in_session".into(), + cookie_key: [7u8; 32], + }; + assert_eq!(introspect_path(), "/introspect"); + let exp = OffsetDateTime::now_utc() + time::Duration::hours(1); + let sealed = mint_session_cookie(&config, "opaque-token", exp); + let back: Session = open_json(&config.cookie_key, &sealed).unwrap(); + assert_eq!(back.app_session, "opaque-token"); + assert_eq!(back.exp, exp.unix_timestamp()); + } + // -- review regressions ------------------------------------------------- + // + // Strict `next` (CRLF injection + backslash), a `Location` that cannot + // panic, and a `current_user` that only clears the cookie on an explicit + // `active:false`. + + #[test] + fn next_allows_plain_local_paths() { + assert_eq!(safe_next("/"), "/"); + assert_eq!(safe_next("/drive/folder/a"), "/drive/folder/a"); + assert_eq!(safe_next("/?auth_error=exchange_failed"), "/?auth_error=exchange_failed"); + } + + #[test] + fn login_next_with_crlf_injection_is_neutralized() { + // The login half of the repro: the query arrives percent-encoded, + // `query_value` decodes it, `safe_next` judges the decoded bytes. + let decoded = query_value("next=/%0d%0aX-evil:1", "next").unwrap(); + assert_eq!(decoded, "/\r\nX-evil:1"); + assert_eq!(safe_next(&decoded), "/"); + assert_eq!(safe_next("/\r\nX-evil:1"), "/"); + assert_eq!(safe_next("/ok\r/evil"), "/"); + assert_eq!(safe_next("/tab\there"), "/"); + } + + #[test] + fn next_rejects_backslash_paths() { + // Browsers normalize `\` to `/` in `Location`, so a backslash-led + // path is an open redirect wearing a local costume. + assert_eq!(safe_next("/\\evil"), "/"); + assert_eq!(safe_next("/drive/\\evil"), "/"); + assert_eq!(safe_next("\\evil"), "/"); + assert_eq!(safe_next("//evil.example"), "/"); + assert_eq!(safe_next("https://evil.example/"), "/"); + assert_eq!(safe_next(""), "/"); + } + + #[test] + fn location_value_falls_back_to_root() { + // `HeaderValue` refuses the injected bytes; the redirect must land + // on `/` rather than panic its handler. + assert!(HeaderValue::from_str("/\r\nX-evil:1").is_err()); + assert_eq!(location_value("/\r\nX-evil:1"), HeaderValue::from_static("/")); + assert_eq!( + location_value("/drive"), + HeaderValue::from_str("/drive").unwrap() + ); + } + + #[route(GET "/whoami")] + async fn whoami(cx: &Cx) -> Result { + match current_user(cx).await { + Some(user) => user.email.into_response(cx), + None => "anon".into_response(cx), + } + } + + fn test_config(issuer: String) -> Config { + Config { + issuer, + client_id: "client-1".into(), + client_secret: "s3cr3t".into(), + redirect_uri: "http://app.test/auth/callback".into(), + cookie_name: "in_session".into(), + cookie_key: [7u8; 32], + } + } + + fn test_router(config: Config) -> Router { + mount(Router::builder(), config) + .discover_routes() + .cookies() + .build() + } + + fn get(uri: &str, cookie: Option<&str>) -> http::Request { + let mut builder = http::Request::builder().method("GET").uri(uri); + if let Some(cookie) = cookie { + builder = builder.header(http::header::COOKIE, cookie); + } + builder.body(Body::empty()).unwrap() + } + + struct TestResponse { + status: http::StatusCode, + location: Option, + set_cookies: Vec, + body: Vec, + } + + impl TestResponse { + async fn of(response: Response) -> Self { + let status = response.status(); + let headers = response.headers().clone(); + let location = headers + .get(http::header::LOCATION) + .and_then(|v| v.to_str().ok()) + .map(str::to_string); + let set_cookies = headers + .get_all(http::header::SET_COOKIE) + .iter() + .filter_map(|v| v.to_str().ok().map(str::to_string)) + .collect(); + let body = to_bytes(response.into_body(), usize::MAX) + .await + .unwrap() + .to_vec(); + Self { + status, + location, + set_cookies, + body, + } + } + + fn text(&self) -> &str { + std::str::from_utf8(&self.body).unwrap() + } + + /// The session cookie was cleared iff a `Set-Cookie` names it — + /// the test routes set no cookies of their own. + fn clears_session(&self) -> bool { + self.set_cookies + .iter() + .any(|c| c.starts_with("in_session=")) + } + } + + fn session_cookie(token: &str) -> String { + let session = Session { + app_session: token.into(), + exp: OffsetDateTime::now_utc().unix_timestamp() + 3600, + }; + format!("in_session={}", seal_json(&[7u8; 32], &session)) + } + + /// Canned bodies served per path over plain HTTP/1.1 with keep-alive, + /// behind locks so the test learns the URL first and fills them after. + /// Raw strings, so a test can answer garbage on purpose. + #[derive(Clone, Default)] + struct CannedIm { + token: Arc>, + jwks: Arc>, + introspect: Arc>, + } + + struct FakeIm { + addr: std::net::SocketAddr, + } + + impl FakeIm { + async fn spawn(canned: CannedIm) -> Self { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + loop { + let Ok((socket, _)) = listener.accept().await else { + return; + }; + let canned = canned.clone(); + tokio::spawn(async move { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let mut socket = socket; + let mut buf = vec![0u8; 8192]; + let mut req = Vec::new(); + loop { + let body_start = loop { + let Ok(n) = socket.read(&mut buf).await else { + return; + }; + if n == 0 { + return; + } + req.extend_from_slice(&buf[..n]); + if let Some(end) = headers_end(&req) { + let head = + String::from_utf8_lossy(&req[..end]).to_string(); + let len = content_length(&head); + if req.len() >= end + len { + break end; + } + } + if req.len() > 1_000_000 { + return; + } + }; + let head = + String::from_utf8_lossy(&req[..body_start]).to_string(); + let first = head.lines().next().unwrap_or("").to_string(); + let len = content_length(&head); + req.drain(..body_start + len); + let payload = if first.starts_with("POST /token ") { + canned.token.get().cloned().unwrap_or_default() + } else if first.starts_with("GET /jwks.json ") { + canned.jwks.get().cloned().unwrap_or_default() + } else { + canned.introspect.get().cloned().unwrap_or_default() + }; + let response = format!( + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: keep-alive\r\n\r\n", + payload.len() + ); + if socket.write_all(response.as_bytes()).await.is_err() { + return; + } + if socket.write_all(payload.as_bytes()).await.is_err() { + return; + } + } + }); + } + }); + Self { addr } + } + + fn url(&self) -> String { + format!("http://{}", self.addr) + } + } + + fn headers_end(req: &[u8]) -> Option { + req.windows(4) + .position(|w| w == b"\r\n\r\n") + .map(|pos| pos + 4) + } + + fn content_length(head: &str) -> usize { + head.lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.trim() + .eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse().unwrap_or(0)) + }) + .unwrap_or(0) + } + + fn jwk_of(public: &rsa::RsaPublicKey, kid: &str) -> serde_json::Value { + serde_json::json!({ + "kty": "RSA", + "kid": kid, + "n": b64url.encode(public.n().to_bytes_be()), + "e": b64url.encode(public.e().to_bytes_be()), + }) + } + + /// The named repro end to end: `GET /auth/login?next=/%0d%0aX-evil:1`, + /// then a completed callback. Pre-fix the sealed `next` carried the CR + /// LF into `see()` and the callback died (500 via the panic boundary); + /// now the browser lands on `/`. + #[tokio::test] + async fn login_then_callback_with_injected_next_lands_on_root() { + let (private, public) = keypair(); + // Login touches no im endpoint, so any issuer will do; the flight + // cookie below is opened with the test-known key. + let login_router = test_router(test_config("http://im.test".into())); + let login = TestResponse::of( + login_router + .handle(get("/auth/login?next=/%0d%0aX-evil:1", None)) + .await, + ) + .await; + assert_eq!(login.status, http::StatusCode::SEE_OTHER); + let sealed = login + .set_cookies + .iter() + .find(|c| c.starts_with("in_session_pkce=")) + .expect("login sets the flight cookie"); + let sealed = sealed["in_session_pkce=".len()..] + .split(';') + .next() + .unwrap(); + let flight: InFlight = open_json(&[7u8; 32], sealed).unwrap(); + // Neutralized at login: the hostile bytes never reach the seal. + assert_eq!(flight.next, "/"); + + // Now complete the dance against a fake im. + let canned = CannedIm::default(); + let fake = FakeIm::spawn(canned.clone()).await; + let now = OffsetDateTime::now_utc().unix_timestamp(); + let id_token = sign( + serde_json::json!({ + "iss": fake.url(), + "sub": "user-1", + "aud": "client-1", + "exp": now + 600, + "iat": now, + "nonce": flight.nonce, + }), + &private, + ); + let _ = canned + .jwks + .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string()); + let _ = canned + .token + .set(serde_json::json!({ + "id_token": id_token, + "app_session": "tok-1", + }) + .to_string()); + let _ = canned + .introspect + .set(serde_json::json!({ + "active": true, + "sub": "user-1", + "email": "ann@example.com", + "name": "Ann", + "exp": now + 3600, + }) + .to_string()); + + let router = test_router(test_config(fake.url())); + let callback = TestResponse::of( + router + .handle(get( + &format!("/auth/callback?code=code-1&state={}", flight.state), + Some(&format!("in_session_pkce={sealed}")), + )) + .await, + ) + .await; + assert_eq!(callback.status, http::StatusCode::SEE_OTHER); + assert_eq!(callback.location.as_deref(), Some("/")); + } + + /// A flight cookie sealed before the strict rules (hand-sealed hostile + /// here): the callback re-validates before rendering the header, so + /// even this lands on `/` instead of panicking. + #[tokio::test] + async fn callback_with_hostile_stored_next_lands_on_root() { + let (private, public) = keypair(); + let canned = CannedIm::default(); + let fake = FakeIm::spawn(canned.clone()).await; + let now = OffsetDateTime::now_utc().unix_timestamp(); + let flight = InFlight { + verifier: "verifier".into(), + state: "state-1".into(), + nonce: "nonce-1".into(), + next: "/\r\nX-evil:1".into(), + exp: now + 600, + }; + let sealed = seal_json(&[7u8; 32], &flight); + let id_token = sign( + serde_json::json!({ + "iss": fake.url(), + "sub": "user-1", + "aud": "client-1", + "exp": now + 600, + "iat": now, + "nonce": "nonce-1", + }), + &private, + ); + let _ = canned + .jwks + .set(serde_json::json!({"keys": [jwk_of(&public, "test")]}).to_string()); + let _ = canned + .token + .set(serde_json::json!({ + "id_token": id_token, + "app_session": "tok-1", + }) + .to_string()); + let _ = canned + .introspect + .set(serde_json::json!({ + "active": true, + "sub": "user-1", + "email": "ann@example.com", + "name": "Ann", + "exp": now + 3600, + }) + .to_string()); + + let router = test_router(test_config(fake.url())); + let callback = TestResponse::of( + router + .handle(get( + "/auth/callback?code=code-1&state=state-1", + Some(&format!("in_session_pkce={sealed}")), + )) + .await, + ) + .await; + assert_eq!(callback.status, http::StatusCode::SEE_OTHER); + assert_eq!(callback.location.as_deref(), Some("/")); + } + + #[tokio::test] + async fn current_user_keeps_cookie_when_im_is_blackholed() { + // Nothing listens: the POST fails, the request reads as signed-out, + // and the cookie survives for the next try. + let probe = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = probe.local_addr().unwrap().port(); + drop(probe); + let router = test_router(test_config(format!("http://127.0.0.1:{port}"))); + let res = TestResponse::of( + router + .handle(get("/whoami", Some(&session_cookie("tok-1")))) + .await, + ) + .await; + assert_eq!(res.text(), "anon"); + assert!( + !res.clears_session(), + "a blackholed introspection must not clear the cookie: {:?}", + res.set_cookies + ); + } + + #[tokio::test] + async fn current_user_keeps_cookie_on_unparseable_introspection() { + let canned = CannedIm::default(); + let _ = canned.introspect.set("not-json{{{".into()); + let fake = FakeIm::spawn(canned).await; + let router = test_router(test_config(fake.url())); + let res = TestResponse::of( + router + .handle(get("/whoami", Some(&session_cookie("tok-1")))) + .await, + ) + .await; + assert_eq!(res.text(), "anon"); + assert!( + !res.clears_session(), + "an unparseable introspection must not clear the cookie: {:?}", + res.set_cookies + ); + } + + #[tokio::test] + async fn current_user_keeps_cookie_when_active_is_missing() { + // A malformed answer is not a revocation. + let canned = CannedIm::default(); + let _ = canned + .introspect + .set(serde_json::json!({"sub": "user-1"}).to_string()); + let fake = FakeIm::spawn(canned).await; + let router = test_router(test_config(fake.url())); + let res = TestResponse::of( + router + .handle(get("/whoami", Some(&session_cookie("tok-1")))) + .await, + ) + .await; + assert_eq!(res.text(), "anon"); + assert!( + !res.clears_session(), + "an answer without `active` must not clear the cookie: {:?}", + res.set_cookies + ); + } + + #[tokio::test] + async fn current_user_clears_cookie_when_session_revoked() { + let canned = CannedIm::default(); + let _ = canned + .introspect + .set(serde_json::json!({"active": false}).to_string()); + let fake = FakeIm::spawn(canned).await; + let router = test_router(test_config(fake.url())); + let res = TestResponse::of( + router + .handle(get("/whoami", Some(&session_cookie("tok-1")))) + .await, + ) + .await; + assert_eq!(res.text(), "anon"); + assert!( + res.clears_session(), + "an `active:false` answer must clear the cookie: {:?}", + res.set_cookies + ); + } + + #[tokio::test] + async fn current_user_serves_the_introspected_user() { + let now = OffsetDateTime::now_utc().unix_timestamp(); + let canned = CannedIm::default(); + let _ = canned + .introspect + .set(serde_json::json!({ + "active": true, + "sub": "user-1", + "email": "ann@example.com", + "name": "Ann", + "exp": now + 3600, + }) + .to_string()); + let fake = FakeIm::spawn(canned).await; + let router = test_router(test_config(fake.url())); + let res = TestResponse::of( + router + .handle(get("/whoami", Some(&session_cookie("tok-1")))) + .await, + ) + .await; + assert_eq!(res.text(), "ann@example.com"); + assert!( + !res.clears_session(), + "a live session must not clear the cookie: {:?}", + res.set_cookies + ); + } +} diff --git a/crates/in-core/Cargo.toml b/crates/in-core/Cargo.toml new file mode 100644 index 0000000..e66198e --- /dev/null +++ b/crates/in-core/Cargo.toml @@ -0,0 +1,49 @@ +[package] +name = "in-core" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +description = "Domain model and storage for In" + +[features] +# The domain vocabulary (record shapes) compiles anywhere, including the wasm +# bundle. Everything that touches a database, a secret or a CSPRNG lives +# behind `server` so none of it is shipped to the browser. +default = ["server"] +server = [ + "dep:async-trait", + "dep:base64", + "dep:chacha20poly1305", + "dep:image", + "dep:rand", + "dep:sha2", + "dep:subtle", + "dep:tokio", + "dep:turso", + "dep:ulid", +] + +[dependencies] +async-trait = { version = "0.1.92", optional = true } +base64 = { workspace = true, optional = true } +chacha20poly1305 = { workspace = true, optional = true } +image = { workspace = true, optional = true } +rand = { workspace = true, optional = true } +sha2 = { workspace = true, optional = true } +subtle = { workspace = true, optional = true } +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +time.workspace = true +toml.workspace = true +tokio = { workspace = true, optional = true } +turso = { workspace = true, optional = true } +ulid = { workspace = true, optional = true } + +[dev-dependencies] +async-trait = "0.1.92" +serde_json.workspace = true +tokio = { workspace = true } +tempfile = "3" +zip = { version = "8.6.0", default-features = false, features = ["deflate"] } diff --git a/crates/in-core/migrations/0001_init.sql b/crates/in-core/migrations/0001_init.sql new file mode 100644 index 0000000..27eb0e3 --- /dev/null +++ b/crates/in-core/migrations/0001_init.sql @@ -0,0 +1,135 @@ +-- In's schema, whole, in one file. +-- +-- One plain SQL file, applied at boot to an empty database: Turso has no +-- migration runner of its own, and keeping the schema as SQL is what makes +-- the store trait swappable. +-- Timestamps are RFC 3339 text in UTC. Ids are ULIDs as text — sortable by +-- creation. +-- +-- This file is the first migration, not the whole schema any more. Everything +-- after it is a numbered `0002_*.sql` beside it, and an empty database is +-- built by applying them in order. A live database is brought up by +-- `in reconcile`, not by re-running the files, so a change to a table lands +-- in three places — the newest migration, this file's table, and that tool's +-- copy map. + +-- An account. There is no password column on purpose: sign-in is the OIDC +-- provider's business, and this database never sees a secret worth stealing. +-- `oidc_sub` is the provider's stable subject for the person; the row is +-- created on first sight of a sub (JIT provisioning) and refreshed on every +-- sight after. The first row ever provisioned is the admin. +-- +-- `quota_bytes` is the person's ceiling, `used_bytes` the running total of +-- every live AND trashed byte they hold — trash counts, because a file that +-- can be restored is a file that still costs. `used_bytes` is recomputed +-- from the rows after every mutation, never blindly incremented, so a crash +-- between two writes cannot drift it from the truth. +CREATE TABLE user ( + id TEXT PRIMARY KEY, + oidc_sub TEXT NOT NULL, + email TEXT NOT NULL, + display_name TEXT NOT NULL, + admin INTEGER NOT NULL DEFAULT 0, + disabled INTEGER NOT NULL DEFAULT 0, + quota_bytes INTEGER NOT NULL, + used_bytes INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + last_seen_at TEXT +); +CREATE UNIQUE INDEX user_oidc_sub ON user(oidc_sub); + +-- A folder. `parent_id` NULL is the person's root: everything an account +-- holds hangs, directly or not, under nothing. Names are unique among live +-- siblings — two folders called the same thing in one place is one folder +-- spelled twice — and trashed rows do not count, so deleting a name frees it. +-- +-- Trash is `deleted_at`: a folder trash stamps the folder, every descendant +-- folder and every file under them with the same timestamp, in one +-- transaction. The bytes stay on disk until a purge takes the rows. +CREATE TABLE folder ( + id TEXT PRIMARY KEY, + owner_id TEXT NOT NULL REFERENCES user(id), + parent_id TEXT REFERENCES folder(id), + name TEXT NOT NULL, + created_at TEXT NOT NULL, + deleted_at TEXT +); +CREATE INDEX folder_by_parent ON folder(owner_id, parent_id); + +-- A file. The bytes are deliberately not on this type: they sit at +-- `/files/`, named by the row's own id, and a thumbnail — when +-- the bytes are an image — at `/thumbs/`. The directory is state +-- the same way the database file is — back the two up together, and boot +-- deletes any file no row names. And a name is still exactly where an +-- uploaded file name must never end up: `../../etc` is a valid file name and +-- a terrible path, so `name` remains a label printed on a row; the file a row +-- names is found by its id alone, never resolved from anything the row was +-- given. +-- +-- `mime` is what the server decided the bytes are, never what the upload +-- claimed. `thumb_state` is `none` for bytes no thumbnail is attempted for, +-- `pending` while one is being made, and `ready` or `failed` once it is. +CREATE TABLE file ( + id TEXT PRIMARY KEY, + owner_id TEXT NOT NULL REFERENCES user(id), + folder_id TEXT REFERENCES folder(id), + name TEXT NOT NULL, + mime TEXT NOT NULL, + size_bytes INTEGER NOT NULL, + thumb_state TEXT NOT NULL DEFAULT 'none', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + deleted_at TEXT +); +CREATE INDEX file_by_folder ON file(owner_id, folder_id); + +-- A public share link. Only the hash is stored: the plaintext token is shown +-- once when the link is created, and anyone who holds it reads through it. +-- `kind` names which table `target_id` points at — `file` or `folder` — and +-- `expires_at` / `revoked_at` end the link without deleting the row, so a +-- dead link stays distinguishable from a wrong token. +CREATE TABLE share_link ( + id TEXT PRIMARY KEY, + token_hash TEXT NOT NULL, + kind TEXT NOT NULL, + target_id TEXT NOT NULL, + created_by TEXT NOT NULL REFERENCES user(id), + can_download INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL, + expires_at TEXT, + revoked_at TEXT +); +CREATE UNIQUE INDEX share_link_token ON share_link(token_hash); + +-- A per-person share: `user_id` may see one file or folder of somebody +-- else's. `kind` names which table `target_id` points at, as on `share_link`. +-- The row is the whole of the permission — no role, no hierarchy — so +-- removing it unshares completely. +CREATE TABLE share_user ( + kind TEXT NOT NULL, + target_id TEXT NOT NULL, + user_id TEXT NOT NULL REFERENCES user(id), + can_download INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL, + PRIMARY KEY (kind, target_id, user_id) +); + +-- A chunked upload on its way in. Chunks land at +-- `/uploads//`, staged until the finish assembles them in +-- order, sniffs what they are, and moves the result to its file row. A +-- session whose `expires_at` passes is aborted and its chunks deleted — by +-- the boot sweep, and by anyone who asks — so an abandoned upload cannot pin +-- disk forever. `state` is `active`, `done` or `aborted`: a finished or +-- aborted session keeps its row as the record of what happened. +CREATE TABLE upload_session ( + id TEXT PRIMARY KEY, + owner_id TEXT NOT NULL REFERENCES user(id), + folder_id TEXT REFERENCES folder(id), + name TEXT NOT NULL, + size_bytes INTEGER NOT NULL, + chunk_size INTEGER NOT NULL, + received_bytes INTEGER NOT NULL DEFAULT 0, + state TEXT NOT NULL DEFAULT 'active', + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL +); diff --git a/crates/in-core/src/config.rs b/crates/in-core/src/config.rs new file mode 100644 index 0000000..d231918 --- /dev/null +++ b/crates/in-core/src/config.rs @@ -0,0 +1,746 @@ +//! Everything In reads from `config/in.toml`, in one place. +//! +//! Nothing here has a silent default once the file exists. A key that is +//! missing, empty or unusable stops the boot and says which key and which +//! file, because the alternative is worse than not starting: a wrong +//! `database` does not mean "no data", it means a second In quietly +//! writing a different file while everyone believes they are looking at the +//! same drive — and Turso is single-writer, so the two are not even +//! reconcilable afterwards. +//! +//! Development still needs to be one command, so the *absence* of +//! `config/in.toml` is the opt-in that takes the development defaults: the +//! app writes the file itself, with those defaults in it and comments saying +//! what each key does, and then stops — the `[oidc]` keys have no default +//! worth guessing, so the first boot writes the file and says which keys to +//! fill in rather than starting half-authenticated. That is opt-in on purpose +//! too — it only ever happens once, because the second boot finds the file +//! it wrote the first time and reads it like any other. A real deployment is +//! handed the same file and edits it; it never writes itself over a +//! deployment's choices, because it only writes when the file is not there +//! at all. +//! +//! Whatever is finally resolved is printed once at startup — the database +//! path absolute, the address bound, the issuer sign-ins go to — so "which +//! file are we on" is answered by the log rather than by someone's memory. +//! +//! The file is kept complete: a top-level key it does not mention is added, +//! with its comment and the default already in effect, so reading the file +//! is the way to learn what can be changed. `redirect_uri` is the one +//! exception: it defaults from `listen` on every boot, and freezing the +//! derived value into the file would desync it the day `listen` moves. A key +//! nobody here knows is named in the startup report rather than obeyed or +//! refused — a typo should be visible without being a boot failure, and a key +//! this file has stopped honouring must never half-configure anything. + +use serde::Deserialize; +use std::fmt; +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; + +/// The path, relative to the working directory, of the file `Config::load` +/// reads and, failing that, writes. +const FILE_NAME: &str = "config/in.toml"; + +/// What a freshly written `config/in.toml` says, comments included. +/// Development defaults, except for `[oidc]`: no issuer, id or secret has a +/// default worth guessing, so the file is written with blanks and the boot +/// stops until they are filled in. +const DEVELOPMENT_DEFAULTS: &str = r#"# Where the one database file lives. One process holds it. +database = "in.db" +# The address the server listens on. Environment variables are ignored — +# this is the only thing that decides where In binds. +listen = "127.0.0.1:7655" +# How long a live-update connection is held before the browser is asked to +# reconnect, in seconds. The reconnect is what re-checks the session, so a +# revoked sign-in stops receiving within this long. +live_seconds = 300 +# How many days a trashed file or folder waits before the boot sweep purges +# it for good. Trash counts toward quota until then. +purge_after_days = 30 +# The quota a newly provisioned account starts on, in bytes. 10 GiB. +default_quota_bytes = 10737418240 +# Where drive files, thumbnails and staged upload chunks live as files, +# created on boot. Not written here: it defaults to beside the database file, +# and the boot completes this file with the value it resolved. +[oidc] +# The provider that signs people in. Required: no default is guessed. +issuer = "" +# The client id In presents to the provider. Required. +client_id = "" +# The client secret In presents to the provider. Required. The file holds a +# live credential once this is filled in, so it is created mode 0600. +client_secret = "" +# Where the provider sends the browser back after sign-in. Not written here: +# it defaults from `listen` on every boot, so moving the address never leaves +# a stale callback behind. Set it only when the public address differs from +# the bind address (a proxy in front, for instance). +# redirect_uri = "http://127.0.0.1:7655/auth/callback" +"#; + +/// The default `listen` when the file is silent about it. A file missing this +/// key is completed with it on the next boot, so the silence lasts one run. +/// +/// 7655 rather than a round number: 3000, 4000, 5000, 8000 and 8080 are what +/// every other thing on a developer's machine already took, and a first run +/// that dies on "address already in use" is a first run that teaches nothing. +const DEFAULT_LISTEN: &str = "127.0.0.1:7655"; + +/// How long one live-update connection lasts before the server ends it and the +/// browser opens another. Five minutes is a compromise: a stream is +/// authenticated once, when it opens, so a session revoked mid-stream keeps +/// hearing until the next reconnect — and a reconnect costs one request, so +/// doing it every few seconds to shorten that window would be worse than the +/// window. Long enough to be cheap, short enough that a revoked session goes +/// quiet while the person who revoked it is still watching. +const DEFAULT_LIVE_SECONDS: u64 = 300; + +/// How many days trash waits before the boot sweep purges it for good. +const DEFAULT_PURGE_AFTER_DAYS: u32 = 30; + +/// The quota a newly provisioned account starts on: 10 GiB. +const DEFAULT_QUOTA_BYTES: u64 = 10 * 1024 * 1024 * 1024; + +/// Every completable top-level key, with the comment and default a file +/// missing it is completed with. `database` is not here: it has no default +/// worth guessing, so its absence stops the boot instead. `storage` is +/// neither: its default is derived from `database`, so its completed line is +/// built per-file rather than printed from a constant. `redirect_uri` is not +/// here either: it derives from `listen` on every boot (see the module docs). +const OPTIONAL_KEYS: &[(&str, &str)] = &[ + ( + "listen", + concat!( + "# The address the server listens on. Environment variables are ignored —\n", + "# this is the only thing that decides where In binds.\n", + "listen = \"127.0.0.1:7655\"\n" + ), + ), + ( + "live_seconds", + concat!( + "# How long a live-update connection is held before the browser is asked to\n", + "# reconnect, in seconds. The reconnect is what re-checks the session, so a\n", + "# revoked sign-in stops receiving within this long.\n", + "live_seconds = 300\n" + ), + ), + ( + "purge_after_days", + concat!( + "# How many days a trashed file or folder waits before the boot sweep purges\n", + "# it for good. Trash counts toward quota until then.\n", + "purge_after_days = 30\n" + ), + ), + ( + "default_quota_bytes", + concat!( + "# The quota a newly provisioned account starts on, in bytes. 10 GiB.\n", + "default_quota_bytes = 10737418240\n" + ), + ), +]; + +/// The `[oidc]` table of `config/in.toml`, before the values are checked. +/// Anything else the section says lands in `other`, which is read for its key +/// names only. +#[derive(Deserialize)] +struct OidcToml { + issuer: Option, + client_id: Option, + client_secret: Option, + redirect_uri: Option, + #[serde(flatten, default)] + other: std::collections::BTreeMap, +} + +/// The shape of `config/in.toml`, before the values are checked. Anything +/// else the file says lands in `other`, which is read for its key names only +/// — enough for the report to say a key was seen and not obeyed. +#[derive(Deserialize)] +struct Toml { + database: Option, + storage: Option, + listen: Option, + live_seconds: Option, + purge_after_days: Option, + default_quota_bytes: Option, + oidc: Option, + #[serde(flatten)] + other: std::collections::BTreeMap, +} + +/// The OIDC provider In trusts, and how In presents itself to it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OidcConfig { + /// The provider's issuer URL. Sign-ins from anywhere else are refused. + pub issuer: String, + /// The client id In presents to the provider. + pub client_id: String, + /// The client secret In presents to the provider. Never printed. + pub client_secret: String, + /// Where the provider sends the browser after sign-in. Defaults from + /// `listen` when the file is silent about it. + pub redirect_uri: String, +} + +/// What the process needs to know before it opens a socket. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Config { + /// The database file, absolute, as a string — the form + /// [`crate::store::TursoStore::open`] takes. + pub database: String, + /// Where drive files, thumbnails and staged upload chunks live as files, + /// absolute. Bytes never sit in the database: this directory and the + /// database file are backed up together, or not at all. + pub storage: PathBuf, + /// The address the server binds. The only source for this — `HOST` and + /// `PORT` environment variables are never read. + pub listen: SocketAddr, + /// How long one live-update connection is held open before the browser is + /// asked to reconnect. The reconnect re-authenticates, which is how a + /// session revoked mid-stream stops being fed. + pub live_seconds: u64, + /// How many days trash waits before the boot sweep purges it for good. + pub purge_after_days: u32, + /// The quota a newly provisioned account starts on, in bytes. + pub default_quota_bytes: u64, + /// The OIDC provider In trusts. + pub oidc: OidcConfig, + /// Keys the file sets that nothing here reads, in the order the file + /// gives them. Named at startup so a typo is visible. + pub ignored: Vec, + /// Whether `config/in.toml` did not exist and was just written with the + /// development defaults this boot. + pub defaulted: bool, +} + +/// Why the process is not starting. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ConfigError { + /// The file exists but is not valid TOML. + Unparseable { why: String }, + /// A key is missing or set to an empty value. + Missing(&'static str), + /// A key is set to something the app cannot use. + Invalid { key: &'static str, why: String }, + /// The file could not be read for a reason other than "it is not there" + /// (permissions, for instance), or the default could not be written. + Io(String), +} + +impl fmt::Display for ConfigError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ConfigError::Unparseable { why } => { + write!(f, "not starting: {FILE_NAME} is not valid TOML — {why}") + } + ConfigError::Missing(key) => { + write!( + f, + "not starting: {FILE_NAME} has no {key}. Add it, or delete {FILE_NAME} to take the development defaults." + ) + } + ConfigError::Invalid { key, why } => { + write!( + f, + "not starting: {FILE_NAME}'s {key} is set to something unusable — {why}" + ) + } + ConfigError::Io(why) => write!(f, "not starting: {why}"), + } + } +} + +impl std::error::Error for ConfigError {} + +impl Config { + /// Reads `config/in.toml` from the current directory, writing it with + /// the development defaults first if it is not there. + pub fn load() -> Result { + Config::load_from(Path::new(".")) + } + + /// The same reading, against any directory — which is how it is tested + /// without a test being able to disturb another test's working + /// directory, or another test's `config/in.toml`. + pub fn load_from(dir: &Path) -> Result { + let path = dir.join(FILE_NAME); + match std::fs::read_to_string(&path) { + Ok(text) => { + let config = Config::parse(&text, dir, false)?; + complete(&path, &text, dir); + Ok(config) + } + Err(err) if err.kind() == std::io::ErrorKind::NotFound => { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|err| { + ConfigError::Io(format!("could not create {}: {err}", parent.display())) + })?; + } + std::fs::write(&path, DEVELOPMENT_DEFAULTS).map_err(|err| { + ConfigError::Io(format!("could not write {}: {err}", path.display())) + })?; + // The file will hold a live client secret once the admin + // fills it in; close it now, before it does. + let _ = crate::store::secret::restrict(&path); + println!( + "in wrote {FILE_NAME} with development defaults — fill in [oidc] for a real deployment" + ); + Config::parse(DEVELOPMENT_DEFAULTS, dir, true) + } + Err(err) => Err(ConfigError::Io(format!( + "could not read {}: {err}", + path.display() + ))), + } + } + + /// The reading itself, against a string — which is how it is tested + /// without a test being able to disturb another test's filesystem. + pub fn parse(text: &str, dir: &Path, defaulted: bool) -> Result { + let toml: Toml = toml::from_str(text).map_err(|err| ConfigError::Unparseable { + why: err.to_string(), + })?; + + let value = |raw: Option| raw.filter(|value| !value.trim().is_empty()); + + let database = value(toml.database).ok_or(ConfigError::Missing("database"))?; + let database_path = absolute(dir, Path::new(&database)); + + let storage = match value(toml.storage) { + Some(raw) => absolute(dir, Path::new(&raw)), + None => default_storage(&database_path), + }; + + let listen = value(toml.listen).unwrap_or_else(|| DEFAULT_LISTEN.to_string()); + let listen: SocketAddr = listen.parse().map_err(|err| ConfigError::Invalid { + key: "listen", + why: format!("{listen:?} is not a host:port address — {err}"), + })?; + + // Zero would mean a stream that ends the moment it opens, which is a + // reconnect loop rather than a live feed; the key is refused rather + // than quietly corrected, because a deployment that meant to say + // "never expire" should find out here and not at three in the morning. + let live_seconds = toml.live_seconds.unwrap_or(DEFAULT_LIVE_SECONDS); + if live_seconds == 0 { + return Err(ConfigError::Invalid { + key: "live_seconds", + why: "0 would close every live connection as soon as it opened".to_string(), + }); + } + + let purge_after_days = toml.purge_after_days.unwrap_or(DEFAULT_PURGE_AFTER_DAYS); + let default_quota_bytes = toml.default_quota_bytes.unwrap_or(DEFAULT_QUOTA_BYTES); + + let oidc_toml = toml.oidc.ok_or(ConfigError::Missing("[oidc]"))?; + let issuer = value(oidc_toml.issuer).ok_or(ConfigError::Missing("oidc.issuer"))?; + let client_id = value(oidc_toml.client_id).ok_or(ConfigError::Missing("oidc.client_id"))?; + let client_secret = + value(oidc_toml.client_secret).ok_or(ConfigError::Missing("oidc.client_secret"))?; + // Derived from the address bound, on every boot: a deployment behind + // a proxy sets this key, and everyone else follows `listen` for free. + let redirect_uri = value(oidc_toml.redirect_uri) + .unwrap_or_else(|| format!("{}/auth/callback", listen_url_of(&listen))); + + let mut ignored: Vec = toml.other.into_keys().collect(); + ignored.extend(oidc_toml.other.into_keys().map(|key| format!("oidc.{key}"))); + + Ok(Config { + database: database_path.display().to_string(), + storage, + listen, + live_seconds, + purge_after_days, + default_quota_bytes, + oidc: OidcConfig { + issuer, + client_id, + client_secret, + redirect_uri, + }, + ignored, + defaulted, + }) + } + + /// The address the server binds, as a URL. + /// + /// A bind that names no interface — `0.0.0.0`, `::` — answers everywhere + /// and is reachable at none of it by name, so the loopback stands in: a + /// link somebody on the box can click beats a link nobody can. Whoever + /// puts In behind a proxy sets the real address where it is needed (and + /// `redirect_uri` in `[oidc]`), which is the only thing this defers to. + pub fn listen_url(&self) -> String { + listen_url_of(&self.listen) + } + + /// The lines to print once at startup. Nothing secret is among them. + pub fn report(&self) -> Vec { + let mut lines = vec![ + format!("database {}", self.database), + format!("storage {}", self.storage.display()), + format!("listen {}", self.listen), + format!("oidc {}", self.oidc.issuer), + ]; + if !self.ignored.is_empty() { + lines.push(format!( + "ignored {FILE_NAME} sets {}, which nothing reads", + self.ignored.join(", ") + )); + } + if self.defaulted { + lines.push(format!( + "dev {FILE_NAME} did not exist, development defaults written and taken" + )); + } + lines + } +} + +/// The address bound, as a URL — the shape `redirect_uri` defaults from. +fn listen_url_of(listen: &SocketAddr) -> String { + let ip = listen.ip(); + let host = if ip.is_unspecified() { + "127.0.0.1".to_string() + } else if listen.is_ipv6() { + format!("[{ip}]") + } else { + ip.to_string() + }; + match listen.port() { + 80 => format!("http://{host}"), + port => format!("http://{host}:{port}"), + } +} + +/// Adds the top-level keys the file does not mention, each with its own +/// comment and the default already in effect. The file is how a reader learns +/// what can be changed, so a key that is silently defaulted is a key nobody +/// discovers. +/// +/// Only ever adds, never rewrites: whatever else the file says — comments, +/// ordering, a value somebody chose — is theirs. The additions go before the +/// first `[table]` header when there is one, because a key appended past one +/// would belong to that table rather than to the file. A file that cannot be +/// written is not a reason not to start; the defaults it is missing are the +/// ones already in force, so the run is correct either way and the note says +/// what could not be done. +fn complete(path: &Path, text: &str, base: &Path) { + let mut missing: Vec<(&str, String)> = OPTIONAL_KEYS + .iter() + .filter(|(key, _)| !mentions(text, key)) + .map(|(key, block)| (*key, (*block).to_string())) + .collect(); + // `storage` has no fixed default to print: a file silent about it derives + // the directory from where `database` points, so the completed line says + // the value this boot actually resolved rather than a placeholder. + if !mentions(text, "storage") { + // The same base `parse` resolves against, or the completed line would + // point somewhere this boot never looks (config/ vs the directory + // the app runs from). + let database: Option = toml::from_str::(text) + .ok() + .and_then(|t| t.database) + .filter(|value| !value.trim().is_empty()); + let storage = database + .as_deref() + .map(|db| default_storage(&absolute(base, Path::new(db)))) + .unwrap_or_else(|| PathBuf::from("storage")); + missing.push(( + "storage", + format!( + "# Where drive files, thumbnails and staged upload chunks live as files, created on boot.\n\ + storage = {:?}\n", + storage.display().to_string() + ), + )); + } + if missing.is_empty() { + return; + } + let block = missing + .iter() + .map(|(_, block)| block.as_str()) + .collect::>() + .join("\n"); + // Top-level keys must land before any `[table]` header, or TOML would + // read them as that table's. A file with no tables takes them at the end. + let completed = match text.lines().position(|line| { + let trimmed = line.trim_start(); + trimmed.starts_with('[') && !trimmed.starts_with("[ ") + }) { + Some(idx) => { + let mut lines: Vec<&str> = text.lines().collect(); + // A `[` that is not a header — `[[bin]]` aside, a bracketed value + // cannot start a line in valid TOML outside a header — but only a + // header matters here, and a false positive merely moves the + // insertion up, never into another table. + lines.insert(idx, block.as_str()); + let mut out = lines.join("\n"); + if text.ends_with('\n') { + out.push('\n'); + } + out + } + None => { + let mut completed = text.to_string(); + if !completed.is_empty() && !completed.ends_with('\n') { + completed.push('\n'); + } + completed.push('\n'); + completed.push_str(&block); + completed + } + }; + match std::fs::write(path, completed) { + Ok(()) => println!( + "in added {} to {FILE_NAME}, at the default already in use", + missing + .iter() + .map(|(key, _)| *key) + .collect::>() + .join(", ") + ), + Err(err) => println!("in could not complete {FILE_NAME}: {err}"), + } +} + +/// Whether the file sets this top-level key — a line whose first word it is. +/// A key named inside a comment, a value, or an `[oidc]`-style table does not +/// count. (An indented `redirect_uri` inside `[oidc]` does count for its own +/// name: `trim_start` puts it at the line's start.) +fn mentions(text: &str, key: &str) -> bool { + text.lines().any(|line| { + line.trim_start() + .strip_prefix(key) + .is_some_and(|rest| rest.trim_start().starts_with('=')) + }) +} + +/// Where binary files live when the file is silent about it: beside the +/// database file. The two are one backup unit — a backup that takes the +/// database but not the files beside it restores a drive whose contents are +/// gone — so the default keeps them siblings. +fn default_storage(database: &Path) -> PathBuf { + database + .parent() + .map(|parent| parent.join("storage")) + .unwrap_or_else(|| PathBuf::from("storage")) +} + +/// An absolute path for a file that may not exist yet: the directory is +/// resolved against `base` (the directory `config/in.toml` was read +/// from), the file name is kept as written. +fn absolute(base: &Path, path: &Path) -> PathBuf { + if path.is_absolute() { + return path.to_path_buf(); + } + let base = base + .canonicalize() + .unwrap_or_else(|_| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))); + let joined = base.join(path); + match (joined.parent(), joined.file_name()) { + (Some(parent), Some(name)) => match parent.canonicalize() { + Ok(parent) => parent.join(name), + Err(_) => joined.clone(), + }, + _ => joined, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A scratch directory, cleaned up when the test ends, so `load_from` can + /// be driven without touching the working directory. + struct Scratch { + dir: PathBuf, + } + + impl Scratch { + fn new() -> Self { + let dir = std::env::temp_dir().join(format!("in-config-test-{}", Ulid::new())); + std::fs::create_dir_all(dir.join("config")).unwrap(); + Self { dir } + } + + fn write(&self, text: &str) { + std::fs::write(self.dir.join(FILE_NAME), text).unwrap(); + } + + fn load(&self) -> Result { + Config::load_from(&self.dir) + } + } + + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } + } + + use ulid::Ulid; + + const FULL: &str = r#"database = "in.db" +listen = "127.0.0.1:7655" +live_seconds = 300 +purge_after_days = 30 +default_quota_bytes = 10737418240 +[oidc] +issuer = "https://id.example.com" +client_id = "in" +client_secret = "s3cret" +"#; + + #[test] + fn a_missing_file_is_written_with_defaults_and_then_refuses_oidc() { + let scratch = Scratch::new(); + // The fresh file has blank [oidc] keys, so the first boot writes and + // then stops on the first of them. + let err = scratch.load().unwrap_err(); + assert_eq!(err, ConfigError::Missing("oidc.issuer")); + let written = std::fs::read_to_string(scratch.dir.join(FILE_NAME)).unwrap(); + assert!(written.contains("database = \"in.db\"")); + assert!(written.contains("client_secret")); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + let mode = std::fs::metadata(scratch.dir.join(FILE_NAME)) + .unwrap() + .permissions() + .mode() + & 0o777; + assert_eq!(mode, 0o600, "the config file holds a live secret one day"); + } + } + + #[test] + fn a_full_file_loads() { + let scratch = Scratch::new(); + scratch.write(FULL); + let config = scratch.load().unwrap(); + assert!(config.database.ends_with("in.db")); + assert_eq!(config.listen.port(), 7655); + assert_eq!(config.live_seconds, 300); + assert_eq!(config.purge_after_days, 30); + assert_eq!(config.default_quota_bytes, 10 * 1024 * 1024 * 1024); + assert_eq!(config.oidc.issuer, "https://id.example.com"); + assert_eq!( + config.oidc.redirect_uri, + "http://127.0.0.1:7655/auth/callback" + ); + assert!(!config.defaulted); + assert!(config.ignored.is_empty()); + } + + #[test] + fn redirect_uri_defaults_from_listen() { + let scratch = Scratch::new(); + scratch.write(&FULL.replace("127.0.0.1:7655", "0.0.0.0:9000")); + let config = scratch.load().unwrap(); + // An unspecified bind is not a name anyone can reach; the loopback + // stands in. + assert_eq!(config.oidc.redirect_uri, "http://127.0.0.1:9000/auth/callback"); + } + #[test] + fn an_explicit_redirect_uri_wins() { + let scratch = Scratch::new(); + scratch.write( + r#"database = "in.db" +[oidc] +issuer = "https://id.example.com" +client_id = "in" +client_secret = "s3cret" +redirect_uri = "https://files.example.com/auth/callback" +"#, + ); + let config = scratch.load().unwrap(); + assert_eq!( + config.oidc.redirect_uri, + "https://files.example.com/auth/callback" + ); + } + + #[test] + fn zero_live_seconds_is_refused() { + let scratch = Scratch::new(); + scratch.write(&FULL.replace("live_seconds = 300", "live_seconds = 0")); + assert!(matches!( + scratch.load().unwrap_err(), + ConfigError::Invalid { key: "live_seconds", .. } + )); + } + + #[test] + fn a_missing_database_is_refused() { + let scratch = Scratch::new(); + scratch.write( + r#"[oidc] +issuer = "https://id.example.com" +client_id = "in" +client_secret = "s3cret" +"#, + ); + assert_eq!(scratch.load().unwrap_err(), ConfigError::Missing("database")); + } + + #[test] + fn unknown_keys_are_ignored_and_reported() { + let scratch = Scratch::new(); + scratch.write( + r#"database = "in.db" +typo_key = 1 +[oidc] +issuer = "https://id.example.com" +client_id = "in" +client_secret = "s3cret" +oidc_typo = 1 +"#, + ); + let config = scratch.load().unwrap(); + assert!(config.ignored.contains(&"typo_key".to_string())); + assert!(config.ignored.contains(&"oidc.oidc_typo".to_string())); + assert!(config.report().iter().any(|line| line.contains("typo_key"))); + } + + #[test] + fn a_silent_file_is_completed_with_top_level_defaults() { + let scratch = Scratch::new(); + scratch.write( + r#"database = "in.db" +[oidc] +issuer = "https://id.example.com" +client_id = "in" +client_secret = "s3cret" +"#, + ); + let config = scratch.load().unwrap(); + assert_eq!(config.live_seconds, 300); + let completed = std::fs::read_to_string(scratch.dir.join(FILE_NAME)).unwrap(); + // Completed top-level keys land before the [oidc] header, never + // inside it. + let oidc_at = completed.find("[oidc]").unwrap(); + let listen_at = completed.find("listen = ").unwrap(); + assert!(listen_at < oidc_at); + let reparsed: toml::Value = toml::from_str(&completed).unwrap(); + assert!(reparsed.get("listen").is_some()); + } + + #[test] + fn storage_defaults_beside_the_database() { + let scratch = Scratch::new(); + scratch.write(FULL); + let config = scratch.load().unwrap(); + assert_eq!( + config.storage, + PathBuf::from(&config.database) + .parent() + .unwrap() + .join("storage") + ); + } +} diff --git a/crates/in-core/src/lib.rs b/crates/in-core/src/lib.rs new file mode 100644 index 0000000..5eeead6 --- /dev/null +++ b/crates/in-core/src/lib.rs @@ -0,0 +1,29 @@ +//! Domain model and storage for In. +//! +//! The vocabulary — the account, folder, file, share and upload shapes — +//! compiles everywhere, so the UI and the server speak the same types. The +//! `server` feature adds the halves that must never reach the browser: the +//! store, the config, the live announcements and the thumbnailing. + +pub mod store; + +#[cfg(feature = "server")] +pub mod config; +#[cfg(feature = "server")] +pub mod live; +#[cfg(feature = "server")] +pub mod thumbs; + +pub use store::{ + CHUNK_SIZE, CreatedLink, File, Folder, Listing, ShareKind, ShareLink, ShareUser, SharedItem, + ThumbState, UPLOAD_TTL_HOURS, UploadSession, UploadState, User, +}; + +#[cfg(feature = "server")] +pub use config::{Config, ConfigError, OidcConfig}; +#[cfg(feature = "server")] +pub use live::{Change, Topic, next_seq}; +#[cfg(feature = "server")] +pub use store::{ + ReconcileOptions, Result, Store, StoreError, TursoStore, hash_share_token, reconcile, +}; diff --git a/crates/in-core/src/live.rs b/crates/in-core/src/live.rs new file mode 100644 index 0000000..69717f1 --- /dev/null +++ b/crates/in-core/src/live.rs @@ -0,0 +1,68 @@ +//! Committed-write announcements. +//! +//! A write that committed publishes one [`Change`] per surface it touches, +//! and the change carries a topic — never data. That is deliberate: a +//! channel that carried rows would need a per-message authorisation check, +//! and one forgotten filter would leak. A topic cannot leak anything; the +//! woken client re-fetches through the ordinary route, and the existing gate +//! answers there. +//! +//! [`Change::seq`] is a process-local counter, so a client that sees 41 and +//! then 43 knows it missed one and can resync instead of rendering a mix of +//! before and after. + +use std::sync::atomic::{AtomicU64, Ordering}; + +/// The surface a committed write touched. Every variant carries the user the +/// surface belongs to: a change is only ever heard by its own user — or, for +/// [`Topic::Admin`], by an admin. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Topic { + /// The person's library: folders, files, uploads, thumbnails. + Library(String), + /// The person's trash: what was trashed, restored, purged or emptied. + Trash(String), + /// Shares: links created or revoked, per-person grants added or removed. + Shares(String), + /// Users, quotas, disablements — the admin's surface. + Admin(String), +} + +impl Topic { + /// The name the wire uses for this topic: the SSE `event:` field, and + /// the key the listener filter decides on. + pub fn kind(&self) -> &'static str { + match self { + Topic::Library(_) => "library", + Topic::Trash(_) => "trash", + Topic::Shares(_) => "shares", + Topic::Admin(_) => "admin", + } + } + + /// The user this topic is about. A listener may hear a topic when this + /// is its own id — or, for [`Topic::Admin`], when it is an admin. + pub fn id(&self) -> &str { + match self { + Topic::Library(id) | Topic::Trash(id) | Topic::Shares(id) | Topic::Admin(id) => id, + } + } +} + +/// One committed write: which surface changed, and where this change sits +/// in the store's sequence. Everything a client needs to know to refresh — +/// and nothing about what changed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Change { + pub topic: Topic, + pub seq: u64, +} + +static SEQ: AtomicU64 = AtomicU64::new(0); + +/// The next sequence number, starting at 1. Process-local on purpose: the +/// sequence exists to catch a dropped event inside one stream, not to order +/// two servers. +pub fn next_seq() -> u64 { + SEQ.fetch_add(1, Ordering::Relaxed) + 1 +} diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs new file mode 100644 index 0000000..63ad245 --- /dev/null +++ b/crates/in-core/src/store/mod.rs @@ -0,0 +1,607 @@ +//! Storage boundary. +//! +//! Everything the app does to persistent state goes through [`Store`]. The +//! only implementation today is Turso (in-process, SQLite-compatible); a +//! Postgres swap is a new impl of this trait and nothing else. +//! +//! The record shapes — [`User`], [`Folder`], [`File`] and the rest — are the +//! vocabulary and compile everywhere. Everything that touches a database, a +//! secret or a CSPRNG lives behind `server` so none of it is shipped to the +//! browser. + +use serde::{Deserialize, Serialize}; +use time::OffsetDateTime; + +#[cfg(feature = "server")] +pub mod reconcile; +#[cfg(feature = "server")] +pub mod schema; +#[cfg(feature = "server")] +pub mod secret; +#[cfg(feature = "server")] +pub mod sniff; +#[cfg(feature = "server")] +pub mod turso_store; + +#[cfg(feature = "server")] +pub use turso_store::{TursoStore, hash_share_token}; +#[cfg(feature = "server")] +pub use reconcile::{ReconcileOptions, reconcile}; + +/// What the store can fail with. A caller that needs to distinguish "no such +/// row" from "someone else's row" gets [`StoreError::NotFound`] for the +/// first and [`StoreError::CrossOwner`] for the second — and the route layer +/// answers 404 to both, because telling a stranger which ids exist is the +/// leak the distinction exists to prevent. +#[derive(Debug, thiserror::Error)] +pub enum StoreError { + /// The name is already taken among the live siblings. + #[error("that name is already taken here")] + NameTaken, + /// The database refused the write or could not be read. + #[error("database: {0}")] + Backend(String), + /// No such row. + #[error("not found")] + NotFound, + /// The row belongs to another owner. Answered as 404, never 403. + #[error("not found")] + CrossOwner, + /// The owner's quota has no room for these bytes. + #[error("quota exceeded")] + QuotaExceeded, + /// The upload session is past `expires_at`, or is no longer active. + #[error("upload expired")] + UploadExpired, + /// A chunk that does not fit the session: wrong size, wrong index, or + /// bytes past the declared total. + #[error("bad chunk")] + BadChunk, + /// The restore is refused: an ancestor is still trashed, and restoring + /// under it would resurrect the row into a trash it never left. + #[error("an ancestor is still trashed")] + AncestorTrashed, + /// The folder move would put a folder inside its own descendant. + #[error("that move would make a circle")] + Cycle, + /// A stored value is not valid — a timestamp that does not parse, a state + /// the code does not know. + #[error("stored value is not valid: {0}")] + Corrupt(String), +} + +pub type Result = std::result::Result; + +/// An account. There is no password here on purpose: sign-in is the OIDC +/// provider's business, and this record is what handlers load and what pages +/// serialise, so a secret with a field here is a secret one careless response +/// away from the wire. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct User { + pub id: String, + /// The provider's stable subject. The row is created on first sight of a + /// sub and refreshed on every sight after. + pub oidc_sub: String, + pub email: String, + pub display_name: String, + pub admin: bool, + pub disabled: bool, + /// The person's ceiling, in bytes. Set at provisioning, changed by an + /// admin afterwards. + pub quota_bytes: u64, + /// Every live AND trashed byte the person holds. Trash counts, because a + /// file that can be restored still costs. Recomputed from the rows after + /// every mutation, never blindly incremented. + pub used_bytes: u64, + pub created_at: OffsetDateTime, + pub last_seen_at: Option, +} + +/// A folder. `parent_id` NULL is the person's root. `deleted_at` is the +/// trash: `Some` while trashed, with the same timestamp its whole trashed +/// subtree wears. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Folder { + pub id: String, + pub owner_id: String, + pub parent_id: Option, + /// What the person called it. A label, never a path. + pub name: String, + pub created_at: OffsetDateTime, + pub deleted_at: Option, +} + +/// A file, as a screen lists it: a name, a type, a size and where it sits. +/// The bytes are deliberately not on this type — it is what handlers load and +/// pages serialise, and a file's contents have no business travelling with a +/// list of file names. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct File { + pub id: String, + pub owner_id: String, + pub folder_id: Option, + /// What the person called it. A label, never a path. + pub name: String, + /// What the server decided the bytes are, never what the upload claimed. + pub mime: String, + pub size_bytes: u64, + pub thumb_state: ThumbState, + pub created_at: OffsetDateTime, + pub updated_at: OffsetDateTime, + pub deleted_at: Option, +} + +/// Whether a file's thumbnail exists. `None` for bytes no thumbnail is +/// attempted for; `Pending` while one is being made; `Ready` or `Failed` +/// once the attempt settled. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ThumbState { + None, + Pending, + Ready, + Failed, +} + +impl ThumbState { + pub fn as_str(self) -> &'static str { + match self { + ThumbState::None => "none", + ThumbState::Pending => "pending", + ThumbState::Ready => "ready", + ThumbState::Failed => "failed", + } + } + + pub fn parse(raw: &str) -> Result { + match raw { + "none" => Ok(ThumbState::None), + "pending" => Ok(ThumbState::Pending), + "ready" => Ok(ThumbState::Ready), + "failed" => Ok(ThumbState::Failed), + _ => Err(StoreError::Corrupt(format!("thumb state {raw:?}"))), + } + } +} + +/// Which table a share points at — one file, or one folder and everything +/// under it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ShareKind { + File, + Folder, +} + +impl ShareKind { + pub fn as_str(self) -> &'static str { + match self { + ShareKind::File => "file", + ShareKind::Folder => "folder", + } + } + + pub fn parse(raw: &str) -> Result { + match raw { + "file" => Ok(ShareKind::File), + "folder" => Ok(ShareKind::Folder), + _ => Err(StoreError::Corrupt(format!("share kind {raw:?}"))), + } + } +} + +/// A public share link. The row holds only the token's hash; the plaintext +/// is shown once at creation and never again. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ShareLink { + pub id: String, + pub token_hash: String, + pub kind: ShareKind, + pub target_id: String, + pub created_by: String, + pub can_download: bool, + pub created_at: OffsetDateTime, + pub expires_at: Option, + pub revoked_at: Option, +} + +impl ShareLink { + /// Whether the link opens today: unrevoked and unexpired. + pub fn is_live(&self, now: OffsetDateTime) -> bool { + self.revoked_at.is_none() && self.expires_at.is_none_or(|at| at > now) + } +} + +/// A freshly created link, with the one thing the row does not keep: the +/// plaintext token, shown once and then forgotten. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CreatedLink { + pub link: ShareLink, + pub token: String, +} + +/// One file or folder shared with one person. The row is the whole of the +/// permission — removing it unshares completely. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ShareUser { + pub kind: ShareKind, + pub target_id: String, + pub user_id: String, + pub can_download: bool, + pub created_at: OffsetDateTime, +} + +/// A target shared with the reader, with the name the listing prints. What a +/// "shared with me" screen reads; the owner's own library never appears here. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SharedItem { + pub kind: ShareKind, + pub target_id: String, + pub name: String, + /// The file's mime, when the target is one. + pub mime: Option, + pub owner_id: String, + pub can_download: bool, + pub created_at: OffsetDateTime, +} + +/// A chunked upload on its way in. `state` is `active` while chunks are +/// still arriving, `done` once the finish assembled them, `aborted` once +/// anyone gave up on it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct UploadSession { + pub id: String, + pub owner_id: String, + pub folder_id: Option, + /// What the person called the coming file. A label, never a path. + pub name: String, + /// The total the finish must add up to, in bytes. + pub size_bytes: u64, + /// The server-fixed chunk size every non-final chunk must match. + pub chunk_size: u64, + /// The bytes staged so far. + pub received_bytes: u64, + pub state: UploadState, + pub created_at: OffsetDateTime, + pub expires_at: OffsetDateTime, +} + +/// What an upload session is doing: arriving, arrived, or given up on. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum UploadState { + Active, + Done, + Aborted, +} + +impl UploadState { + pub fn as_str(self) -> &'static str { + match self { + UploadState::Active => "active", + UploadState::Done => "done", + UploadState::Aborted => "aborted", + } + } + + pub fn parse(raw: &str) -> Result { + match raw { + "active" => Ok(UploadState::Active), + "done" => Ok(UploadState::Done), + "aborted" => Ok(UploadState::Aborted), + _ => Err(StoreError::Corrupt(format!("upload state {raw:?}"))), + } + } +} + +/// One directory's live contents — or one search's live hits. Trashed rows +/// never appear here; the trash has its own listing. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Listing { + pub folders: Vec, + pub files: Vec, +} + +/// The chunk size the server fixes for every upload session: 8 MiB. The +/// upload route caps bodies above it, and the UI sends single-POST below it. +pub const CHUNK_SIZE: u64 = 8 * 1024 * 1024; + +/// How long an upload session gets before it expires: a day is long enough +/// for a browser left open overnight and short enough that an abandoned +/// upload cannot pin disk for a season. +pub const UPLOAD_TTL_HOURS: u32 = 24; + +#[cfg(feature = "server")] +#[async_trait::async_trait] +pub trait Store: 'static + Send + Sync { + /// A receiver of committed-write announcements. One [`Change`](crate::live::Change) + /// per write that committed, carrying the topic to re-fetch and no data: + /// the channel cannot say more than the reader may hear, because it says + /// nothing — the woken client re-fetches through the ordinary gated + /// route. Sending to zero subscribers is normal and silent, and a slow + /// subscriber's overflow is the client's cue to resync. + fn subscribe(&self) -> tokio::sync::broadcast::Receiver; + + // -- users ------------------------------------------------------------- + + /// The account holding `sub`, if it has ever signed in. + async fn user_by_oidc_sub(&self, sub: &str) -> Result>; + + /// Lookup by address, folded to lowercase before comparing — the provider + /// may capitalise what the row stored plainly, and the two must still + /// meet. What the share UI uses to turn a typed address into a grantee. + async fn user_by_email(&self, email: &str) -> Result>; + + /// One account, by id. + async fn user(&self, id: &str) -> Result>; + + /// Every account, oldest first — the admin's settings screen. + async fn users(&self) -> Result>; + + /// JIT upsert on OIDC login: unknown sub inserts (first user ever gets + /// admin=1, quota = default_quota_bytes), known sub refreshes + /// email/display_name and stamps last_seen_at. Returns the row. + async fn provision_user( + &self, + sub: &str, + email: &str, + display_name: &str, + default_quota_bytes: u64, + ) -> Result; + + /// Writes an account's ceiling. The bytes it already holds are untouched + /// — a quota lowered under current usage refuses new uploads until the + /// person frees space, rather than deleting anything. + async fn set_user_quota(&self, user_id: &str, quota_bytes: u64) -> Result<()>; + + /// Disables an account. A disabled account signs in to nothing: the auth + /// layer reads this and treats the person as signed out. + async fn set_user_disabled(&self, user_id: &str, disabled: bool) -> Result<()>; + + // -- folders ----------------------------------------------------------- + + /// Creates a folder. A parent of another owner is [`StoreError::CrossOwner`], + /// not a refusal — the asker named a thing that is not theirs. + async fn create_folder( + &self, + owner_id: &str, + parent_id: Option<&str>, + name: &str, + ) -> Result; + + /// One folder, by id, trashed or not. The caller decides what trashed + /// means for its screen. + async fn folder(&self, id: &str) -> Result>; + + /// Renames a folder. A name a live sibling wears is [`StoreError::NameTaken`]. + async fn rename_folder(&self, id: &str, name: &str) -> Result<()>; + + /// Moves a folder. Into its own descendant is [`StoreError::Cycle`]; + /// across owners is [`StoreError::CrossOwner`]. + async fn move_folder(&self, id: &str, parent_id: Option<&str>) -> Result<()>; + + /// Trashes a folder: the folder, every descendant folder and every file + /// under them wear the same `deleted_at`, in one transaction. The bytes + /// stay on disk until a purge takes the rows. + async fn delete_folder(&self, id: &str) -> Result<()>; + + /// One directory's live contents: the folders and files whose parent is + /// `parent_id` (`None` is the root) and whose trash timestamp is empty. + async fn list_children( + &self, + owner_id: &str, + parent_id: Option<&str>, + ) -> Result; + + // -- files ------------------------------------------------------------- + + /// Stores small bytes straight through: sanitises the name, checks the + /// quota, sniffs the mime (never trusting the uploader), writes the + /// file, attempts a thumbnail for images and video, and recomputes usage. The + /// chunked upload's finish is the same pipeline over assembled chunks. + async fn insert_file( + &self, + owner_id: &str, + folder_id: Option<&str>, + name: &str, + bytes: &[u8], + ) -> Result; + + /// One file's row, still without its bytes. + async fn file(&self, id: &str) -> Result>; + + /// Renames a file. A name a live sibling wears is [`StoreError::NameTaken`]. + async fn rename_file(&self, id: &str, name: &str) -> Result<()>; + + /// Moves a file. Across owners is [`StoreError::CrossOwner`]. + async fn move_file(&self, id: &str, folder_id: Option<&str>) -> Result<()>; + + /// Trashes a file. The bytes stay on disk — and counting toward quota — + /// until a purge takes the row. + async fn delete_file(&self, id: &str) -> Result<()>; + + /// The bytes themselves, for the one handler that serves them. `None` + /// when there is no such row, or its file went missing. + async fn file_bytes(&self, id: &str) -> Result>>; + + /// The thumbnail's bytes, for the one handler that serves them. `None` + /// when no thumbnail was made, or its file went missing. + async fn thumb_bytes(&self, id: &str) -> Result>>; + + // -- trash ------------------------------------------------------------- + + /// Everything the person trashed and has not purged: folders and files + /// wearing a `deleted_at`, newest trash first. + async fn list_trash(&self, owner_id: &str) -> Result; + + /// Restores a trashed file. Refused with [`StoreError::AncestorTrashed`] + /// while any ancestor folder is still trashed, and with + /// [`StoreError::NameTaken`] while a live sibling wears its name. + async fn restore_file(&self, id: &str) -> Result<()>; + + /// Restores a trashed folder and everything under it that it took with + /// it — descendants wearing the folder's own trash timestamp. Anything + /// trashed individually before the folder keeps its earlier moment and + /// stays trashed. Same refusals as [`Store::restore_file`]. + async fn restore_folder(&self, id: &str) -> Result<()>; + + /// Purges one trashed file for good: the row goes and the bytes and + /// thumbnail follow. `false` when there was no such row. A live file is + /// never purged — trash it first. + async fn purge_file(&self, id: &str) -> Result; + + /// Purges one trashed folder for good: the folder row, every trashed + /// descendant folder and every trashed file under them, deepest rows + /// first. Links and grants naming the purged rows go with them; bytes + /// and thumbnails follow the commit. Returns how many rows went. A + /// folder that is not trashed is refused with [`StoreError::NotFound`] — + /// trash it first. + async fn purge_folder(&self, id: &str) -> Result; + + /// Purges every file and folder trashed before `before`, deepest folders + /// first, and returns how many rows went. The boot sweep calls this with + /// "purge_after_days ago". + async fn purge_expired(&self, before: OffsetDateTime) -> Result; + + /// Purges everything the person trashed, files before folders, and + /// returns how many rows went. + async fn empty_trash(&self, owner_id: &str) -> Result; + + // -- share links ------------------------------------------------------- + + /// Creates a public link onto one file or folder. Returns the row and the + /// plaintext token — the only moment the token exists outside its hash. + /// A target of another owner is [`StoreError::CrossOwner`]. + async fn create_share_link( + &self, + created_by: &str, + kind: ShareKind, + target_id: &str, + can_download: bool, + expires_at: Option, + ) -> Result; + + /// Revokes a link. The row stays, so a dead link reads as revoked rather + /// than wrong. Revoking twice is not an error. + async fn revoke_share_link(&self, id: &str) -> Result<()>; + + /// Every link the person created, newest first — the shares screen. + async fn share_links(&self, owner_id: &str) -> Result>; + + /// Resolves a token hash to its link, if the link is live: unrevoked and + /// unexpired at `now`. A dead link and a wrong token both answer `None`, + /// because telling a stranger which tokens exist is the leak the + /// distinction would be. + async fn resolve_share_link( + &self, + token_hash: &str, + now: OffsetDateTime, + ) -> Result>; + + // -- per-person shares ------------------------------------------------- + + /// Shares one file or folder with one person. The caller must own the + /// live target — another owner's target is [`StoreError::CrossOwner`], + /// a missing or trashed one [`StoreError::NotFound`], the same rule as + /// [`Store::create_share_link`]. Sharing with the owner, or + /// re-sharing what is already shared, is not an error — the second write + /// only refreshes `can_download`. + async fn add_share_user( + &self, + caller_id: &str, + kind: ShareKind, + target_id: &str, + user_id: &str, + can_download: bool, + ) -> Result<()>; + + /// Unshares. Removing what was never shared is not an error. + async fn remove_share_user( + &self, + kind: ShareKind, + target_id: &str, + user_id: &str, + ) -> Result<()>; + + /// Everything shared with the person that is still live: untrashed + /// targets, newest grant first. The person's own library never appears + /// here. + async fn shares_for_user(&self, user_id: &str) -> Result>; + + /// Whether `user_id` may see the target: its owner may, and anyone + /// holding a live grant onto the target — or onto any live folder above + /// it — may. A grant on a folder covers everything under it. Nobody else + /// may — and the answer never says which of "no such target" and "not + /// shared" it was. + async fn can_see(&self, kind: ShareKind, target_id: &str, user_id: &str) + -> Result; + + /// Whether `user_id` may download the target: its owner always may, and + /// anyone may who sees it through a grant whose `can_download` is set — + /// on the target itself or on any live folder above it. The most + /// permissive grant on the chain wins: a download grant above the target + /// opens the bytes even under a view-only grant on the target itself. + /// A view-only grant alone opens the page but not the bytes. + async fn can_download( + &self, + kind: ShareKind, + target_id: &str, + user_id: &str, + ) -> Result; + + // -- chunked uploads --------------------------------------------------- + + /// Opens an upload session: checks the quota against the declared total, + /// and answers [`StoreError::QuotaExceeded`] while there is still nothing + /// on disk to clean up. A folder of another owner is + /// [`StoreError::CrossOwner`]. + async fn create_upload_session( + &self, + owner_id: &str, + folder_id: Option<&str>, + name: &str, + size_bytes: u64, + ) -> Result; + + /// One session, whatever its state. + async fn upload_session(&self, id: &str) -> Result>; + + /// Stages one chunk: `bytes` land at `uploads//`, and the + /// session's received count follows the files on disk, not the calls — + /// re-sending an index replaces its bytes rather than counting them + /// twice. Anything past the declared total, or on a session that is not + /// active and unexpired, is refused. + async fn record_chunk( + &self, + id: &str, + index: u64, + bytes: &[u8], + ) -> Result; + + /// Assembles a session's chunks in order, rechecks the quota, sniffs the + /// mime (never trusting anything the uploader said), writes the file, + /// attempts a thumbnail for images and video, inserts the row and marks the session + /// done — and returns the file. A session whose chunks do not add up, or + /// whose owner filled their quota while it was arriving, is refused with + /// the chunks still staged for another attempt. + async fn finish_upload(&self, id: &str) -> Result; + + /// Aborts a session: the row says `aborted` and the staged chunks are + /// deleted. Aborting twice is not an error. + async fn abort_upload(&self, id: &str) -> Result<()>; + + /// Aborts every active session past `expires_at` and deletes its chunks. + /// The boot sweep calls this with now; a janitor may call it any time. + async fn prune_expired_uploads(&self, now: OffsetDateTime) -> Result; + + // -- search ------------------------------------------------------------ + + /// Owner-scoped substring search over live file and folder names, files + /// and folders in their own lists. At most `limit` of each. + async fn search( + &self, + owner_id: &str, + query: &str, + limit: u32, + ) -> Result; +} diff --git a/crates/in-core/src/store/reconcile.rs b/crates/in-core/src/store/reconcile.rs new file mode 100644 index 0000000..5aa2498 --- /dev/null +++ b/crates/in-core/src/store/reconcile.rs @@ -0,0 +1,580 @@ +//! Reconcile a live Turso database with the declared whole schema. +//! +//! The live file is never altered in place. Instead a new file is built from +//! `migrations/0001_init.sql`, the data is copied with an explicit per-table +//! column map, the copy is verified, and only then the files are swapped. The +//! original file is kept as a timestamped backup and is never deleted. +//! +//! Binary is the one thing that needs no extraction here: In never kept +//! bytes in its tables — files, thumbnails and chunks live under the storage +//! directory from the first schema, keyed by row id — so the copy moves rows +//! only, and the tree beside the database is untouched throughout. + +use super::schema::{declared_fingerprint, diff_report, fingerprint, schema_sql}; +use super::{Result, StoreError}; + +use turso::{Builder, Connection}; +pub struct ReconcileOptions { + /// Print the diff and plan, then stop without touching anything. + pub dry_run: bool, + /// Skip the interactive confirmation. + pub yes: bool, + /// Boot path: do not prompt, log what happened and proceed. + pub auto: bool, +} + +/// Rebuilds the database at `path` to match the declared schema. +/// +/// - Empty or already-current databases are a no-op. +/// - A differing database is backed up, rebuilt, verified and swapped into +/// place. +/// - `storage` is accepted for the call shape the boot path shares with +/// databases that once kept binary in their tables; In never did, so the +/// tree beside the database is left exactly as it was. +/// - A rebuild that fails verification deletes the `.rebuilt` file and leaves +/// the original untouched. +pub async fn reconcile( + path: &str, + storage: Option<&std::path::Path>, + opts: ReconcileOptions, +) -> Result<()> { + let _ = storage; + if path == ":memory:" { + return Err(StoreError::Backend( + "reconcile is not meaningful on an in-memory database".into(), + )); + } + let db_path = std::path::Path::new(path); + if !db_path.exists() { + return Err(StoreError::Backend(format!("database not found: {}", path))); + } + + // Open the live database read-only to inspect its fingerprint. + let old_db = Builder::new_local(path) + .build() + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + let old_conn = old_db + .connect() + .map_err(|e| StoreError::Backend(e.to_string()))?; + + let old_fp = fingerprint(&old_conn).await?; + let new_fp = declared_fingerprint().await?; + + if old_fp == new_fp { + if !opts.auto { + println!("database already matches the declared schema"); + } + return Ok(()); + } + + let diff = diff_report(&old_fp, &new_fp); + + if opts.dry_run { + println!("schema difference:\n{}", diff); + println!("dry run: would rebuild {}", path); + return Ok(()); + } + + if opts.auto { + eprintln!("database schema differs from declared schema; rebuilding automatically"); + eprintln!("difference:\n{}", diff); + } else { + println!("schema difference:\n{}", diff); + if !opts.yes { + print!("rebuild {}? [y/N] ", path); + let _ = std::io::Write::flush(&mut std::io::stdout()); + let mut answer = String::new(); + match std::io::stdin().read_line(&mut answer) { + Ok(_) if answer.trim().eq_ignore_ascii_case("y") => {} + _ => { + println!("rebuild cancelled"); + return Ok(()); + } + } + } + } + + let rebuilt_path = format!("{}.rebuilt", path); + cleanup_rebuilt(&rebuilt_path); + + let result = rebuild(path, &rebuilt_path, &old_conn).await; + + // Close the read-only connection before any file moves; this also + // releases the WAL locks on the original file. + drop(old_conn); + drop(old_db); + + if let Err(e) = result { + cleanup_rebuilt(&rebuilt_path); + return Err(e); + } + + let backup_path = backup_name(path)?; + std::fs::rename(path, &backup_path).map_err(|e| { + StoreError::Backend(format!( + "failed to move original database to backup {}: {}", + backup_path, e + )) + })?; + // SQLite WAL/SHM siblings belong to the main file; the backup must be a + // complete database on its own, and the rebuilt file starts with none. + rename_sibling(path, &backup_path, "-wal"); + rename_sibling(path, &backup_path, "-shm"); + if let Err(e) = std::fs::rename(&rebuilt_path, path) { + // Best-effort undo so the live file is not gone. If this also fails, + // the caller has both the backup and the rebuilt file to recover from. + let _ = std::fs::rename(&backup_path, path); + let _ = rename_sibling(&backup_path, path, "-wal"); + let _ = rename_sibling(&backup_path, path, "-shm"); + return Err(StoreError::Backend(format!( + "failed to move rebuilt database into place {}: {}", + rebuilt_path, e + ))); + } + // The rebuilt file was checkpointed before the swap, so its own sidecars + // hold nothing — but a `.rebuilt-wal` left lying about would be adopted by + // the NEXT rebuild's fresh `.rebuilt` file, which is how a stale WAL + // corrupts a database that was otherwise fine. + let _ = std::fs::remove_file(format!("{}-wal", rebuilt_path)); + let _ = std::fs::remove_file(format!("{}-shm", rebuilt_path)); + + if opts.auto { + eprintln!( + "database rebuilt and verified; original backed up to {}", + backup_path + ); + eprintln!("rebuilt database now at {}", path); + } else { + println!("database rebuilt and verified"); + println!("original backed up to {}", backup_path); + println!("rebuilt database now at {}", path); + } + + Ok(()) +} + +/// Does the actual rebuild: creates `.rebuilt`, copies the data, and verifies +/// the result. On success the rebuilt file is complete and checkpointed; on +/// failure the caller deletes it. +async fn rebuild(path: &str, rebuilt_path: &str, old_conn: &Connection) -> Result<()> { + // The copy runs as `INSERT ... SELECT FROM old.`, which needs + // ATTACH — still gated in this engine, and switched on only here, for the + // one connection that does the rebuild. The verification afterwards is + // what protects the data, not the copy's mechanism. + let new_db = Builder::new_local(rebuilt_path) + .experimental_attach(true) + .build() + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + let new_conn = new_db + .connect() + .map_err(|e| StoreError::Backend(e.to_string()))?; + + new_conn + .execute_batch(&schema_sql()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + + copy_data(old_conn, &new_conn, path).await?; + verify(old_conn, &new_conn).await?; + + // A checkpoint PRAGMA answers with a row, so it is a query: `execute` + // treats a row as a failure ("unexpected row during execution"). + let mut checkpoint = new_conn + .query("PRAGMA wal_checkpoint(TRUNCATE)", ()) + .await + .map_err(|e| StoreError::Backend(format!("checkpoint: {e}")))?; + while checkpoint + .next() + .await + .map_err(|e| StoreError::Backend(format!("checkpoint: {e}")))? + .is_some() + {} + + Ok(()) +} + +/// A per-table column map. Every destination column must appear exactly once; +/// `copy_data` validates this against the declared schema before inserting. +struct TableMap { + name: &'static str, + columns: Vec<(&'static str, String)>, +} + +/// Builds the explicit column map. Every table maps every column to its old +/// self: In's first schema is the declared one, so a database old enough to +/// be reconciled carries the same columns, and the map is the receipt that +/// says nothing was dropped, renamed or defaulted on the way across. +fn build_maps() -> Vec { + vec![ + TableMap { + name: "user", + columns: old_cols(&[ + "id", + "oidc_sub", + "email", + "display_name", + "admin", + "disabled", + "quota_bytes", + "used_bytes", + "created_at", + "last_seen_at", + ]), + }, + TableMap { + name: "folder", + columns: old_cols(&[ + "id", + "owner_id", + "parent_id", + "name", + "created_at", + "deleted_at", + ]), + }, + TableMap { + name: "file", + columns: old_cols(&[ + "id", + "owner_id", + "folder_id", + "name", + "mime", + "size_bytes", + "thumb_state", + "created_at", + "updated_at", + "deleted_at", + ]), + }, + TableMap { + name: "share_link", + columns: old_cols(&[ + "id", + "token_hash", + "kind", + "target_id", + "created_by", + "can_download", + "created_at", + "expires_at", + "revoked_at", + ]), + }, + TableMap { + name: "share_user", + columns: old_cols(&["kind", "target_id", "user_id", "can_download", "created_at"]), + }, + TableMap { + name: "upload_session", + columns: old_cols(&[ + "id", + "owner_id", + "folder_id", + "name", + "size_bytes", + "chunk_size", + "received_bytes", + "state", + "created_at", + "expires_at", + ]), + }, + ] +} + +fn old_cols(cols: &[&'static str]) -> Vec<(&'static str, String)> { + cols.iter().map(|c| (*c, format!("old.{}", c))).collect() +} + +/// Validates that every destination column is covered and that no map +/// references a column that does not exist. A missing column is a startup +/// error, never a silent NULL. +async fn validate_maps(conn: &Connection, maps: &[TableMap]) -> Result<()> { + use std::collections::HashSet; + + for map in maps { + let sql = format!("PRAGMA table_info({})", map.name); + let mut rows = conn + .query(&sql, ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + let mut actual = HashSet::new(); + while let Some(row) = rows + .next() + .await + .map_err(|e| StoreError::Backend(e.to_string()))? + { + let name: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?; + actual.insert(name); + } + + for (col, _) in &map.columns { + if !actual.contains(*col) { + return Err(StoreError::Backend(format!( + "reconcile map for {} references missing column {}", + map.name, col + ))); + } + } + for col in actual { + if !map.columns.iter().any(|(c, _)| c == &col) { + return Err(StoreError::Backend(format!( + "reconcile map for {} is missing column {} (would become NULL)", + map.name, col + ))); + } + } + } + + // Every table the declared schema creates must have a map: a declared + // table without one is a table the rebuild would create empty while the + // copy ran. Engine bookkeeping (`sqlite_*`) is not user data. A table the + // old database carries but the declared schema does not is dropped on + // purpose; it is the declared side that may never go unmapped. + let mut rows = conn + .query("SELECT name FROM sqlite_master WHERE type = 'table'", ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + let mut declared = Vec::new(); + while let Some(row) = rows + .next() + .await + .map_err(|e| StoreError::Backend(e.to_string()))? + { + let name: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?; + if !name.starts_with("sqlite_") { + declared.push(name); + } + } + for table in declared { + if !maps.iter().any(|m| m.name == table) { + return Err(StoreError::Backend(format!( + "reconcile has no map for declared table {table} (its rows would be dropped)" + ))); + } + } + Ok(()) +} + +/// Copies every mapped table from the attached old database into the new +/// main schema, in foreign-key-safe order: owners before folders, folders +/// before the files and sessions that name them, everything before the +/// shares that name all of it. +async fn copy_data(_old_conn: &Connection, new_conn: &Connection, path: &str) -> Result<()> { + let escaped = path.replace('\'', "''"); + new_conn + .execute(&format!("ATTACH DATABASE '{}' AS old", escaped), ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + + let maps = build_maps(); + validate_maps(new_conn, &maps).await?; + + // Foreign keys stay off during the copy and are checked by `verify` + // instead: folder rows copy in rowid order, which is not a topological + // order for the self-referencing parent link, and a child copied ahead of + // its parent is a good row in a bad moment rather than a bad row. + new_conn + .execute("PRAGMA foreign_keys = OFF", ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + for map in maps { + let cols = map + .columns + .iter() + .map(|(c, _)| *c) + .collect::>() + .join(", "); + // `old` is the attached SCHEMA, not a table, so `old.id` in a select + // list reads as "table old, column id". The source table is aliased + // and the maps' `old.` prefix rewritten onto that alias. + let exprs = map + .columns + .iter() + .map(|(_, e)| e.replace("old.", "src.")) + .collect::>() + .join(", "); + let sql = format!( + "INSERT INTO main.{} ({}) SELECT {} FROM old.{} AS src", + map.name, cols, exprs, map.name + ); + new_conn.execute(&sql, ()).await.map_err(|e| { + StoreError::Backend(format!("{} while copying {}: {}", e, map.name, sql)) + })?; + } + new_conn + .execute("PRAGMA foreign_keys = ON", ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + + new_conn + .execute("DETACH DATABASE old", ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + + Ok(()) +} + +/// Verifies the rebuilt database before the swap: foreign keys, integrity, +/// and row counts table by table. Anything lost or invented fails here +/// instead of shipping. +async fn verify(old_conn: &Connection, new_conn: &Connection) -> Result<()> { + let mut rows = new_conn + .query("PRAGMA foreign_key_check", ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + let mut fk_errors = Vec::new(); + while let Some(row) = rows + .next() + .await + .map_err(|e| StoreError::Backend(e.to_string()))? + { + let table: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?; + let rowid: i64 = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?; + let parent: String = row.get(2).map_err(|e| StoreError::Backend(e.to_string()))?; + let fkid: i64 = row.get(3).map_err(|e| StoreError::Backend(e.to_string()))?; + fk_errors.push(format!( + "{} rowid {} references {} (foreign key {})", + table, rowid, parent, fkid + )); + } + if !fk_errors.is_empty() { + return Err(StoreError::Backend(format!( + "foreign key check failed:\n{}", + fk_errors.join("\n") + ))); + } + + let mut rows = new_conn + .query("PRAGMA integrity_check", ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + let mut integrity = Vec::new(); + while let Some(row) = rows + .next() + .await + .map_err(|e| StoreError::Backend(e.to_string()))? + { + let msg: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?; + integrity.push(msg); + } + if integrity.len() != 1 || integrity[0] != "ok" { + return Err(StoreError::Backend(format!( + "integrity check failed: {:?}", + integrity + ))); + } + + let tables = [ + "user", + "folder", + "file", + "share_link", + "share_user", + "upload_session", + ]; + for table in tables { + let old_count = count_rows(old_conn, table).await?; + let new_count = count_rows(new_conn, table).await?; + if old_count != new_count { + return Err(StoreError::Backend(format!( + "row count mismatch for {}: old {} new {}", + table, old_count, new_count + ))); + } + } + + Ok(()) +} + +async fn count_rows(conn: &Connection, table: &str) -> Result { + let sql = format!("SELECT COUNT(*) FROM {}", table); + let mut rows = conn + .query(&sql, ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + let Some(row) = rows + .next() + .await + .map_err(|e| StoreError::Backend(e.to_string()))? + else { + return Err(StoreError::Backend(format!( + "could not count rows in {}", + table + ))); + }; + row.get::(0) + .map_err(|e| StoreError::Backend(e.to_string())) +} + +fn cleanup_rebuilt(rebuilt_path: &str) { + let _ = std::fs::remove_file(rebuilt_path); + let _ = std::fs::remove_file(format!("{}-wal", rebuilt_path)); + let _ = std::fs::remove_file(format!("{}-shm", rebuilt_path)); +} + +/// Move a SQLite sidecar file (`-wal` or `-shm`) if it exists. A missing +/// sibling is fine: WAL mode may not have created one, and the backup is +/// still consistent without it. +fn rename_sibling(from: &str, to: &str, suffix: &str) { + let from_path = format!("{}{}", from, suffix); + let to_path = format!("{}{}", to, suffix); + if std::path::Path::new(&from_path).exists() { + let _ = std::fs::rename(&from_path, &to_path); + } +} + +fn backup_name(path: &str) -> Result { + let format = time::format_description::parse_borrowed::<2>( + "[year]-[month]-[day]T[hour][minute][second]Z", + ) + .map_err(|e| StoreError::Backend(format!("invalid time format: {}", e)))?; + let stamp = time::OffsetDateTime::now_utc() + .format(&format) + .map_err(|e| StoreError::Backend(format!("time format failed: {}", e)))?; + + let candidate = format!("{}.backup-{}", path, stamp); + if !std::path::Path::new(&candidate).exists() { + return Ok(candidate); + } + let mut n = 1; + loop { + let candidate = format!("{}.backup-{}-{}", path, stamp, n); + if !std::path::Path::new(&candidate).exists() { + return Ok(candidate); + } + n += 1; + if n > 1000 { + return Err(StoreError::Backend( + "could not find an unused backup name".into(), + )); + } + } +} + +/// A probe the copy plan can ask: whether the old database already carries +/// `column` on `table`. Unused while the declared schema is the first one — +/// every database old enough to be reconciled predates every column it +/// would probe — and kept because the second migration will need exactly +/// this question on its first day. +#[allow(dead_code)] +async fn old_has_column(conn: &Connection, table: &str, column: &str) -> Result { + let mut rows = conn + .query(&format!("PRAGMA table_info({table})"), ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + while let Some(row) = rows + .next() + .await + .map_err(|e| StoreError::Backend(e.to_string()))? + { + let name: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?; + if name == column { + return Ok(true); + } + } + Ok(false) +} diff --git a/crates/in-core/src/store/schema.rs b/crates/in-core/src/store/schema.rs new file mode 100644 index 0000000..e34ab0b --- /dev/null +++ b/crates/in-core/src/store/schema.rs @@ -0,0 +1,373 @@ +//! Schema fingerprinting: compare the database SQLite actually has with the +//! declared whole schema in `migrations/0001_init.sql`. +//! +//! SQLite stores `CREATE` statements as written, comments and all, so two +//! databases built from the same logical schema but different comments or +//! whitespace would otherwise look different. The normaliser here strips the +//! cosmetic differences that do not change what the schema means. + +use super::{Result, StoreError}; +use turso::Connection; + +/// The declared migrations, in order. An empty database is built by applying +/// them one after another; each one applies cleanly to what the ones before +/// it built, so their concatenation is itself a valid whole-schema script. +pub(crate) const MIGRATIONS: &[&str] = &[include_str!("../../migrations/0001_init.sql")]; + +/// The whole declared schema — every migration applied in order — as one +/// batch of SQL. +pub(crate) fn schema_sql() -> String { + let mut sql = String::new(); + for migration in MIGRATIONS { + sql.push_str(migration); + sql.push('\n'); + } + sql +} + +/// Reads and normalises the schema of the connected database. +/// +/// The fingerprint is a deterministic text built from `sqlite_master`: +/// `type|name|normalised_sql` for every non-sqlite object, ordered by type +/// and name. Two schemas that mean the same thing produce the same string; +/// two schemas that differ in tables, indexes, columns or constraints do not. +pub async fn fingerprint(conn: &Connection) -> Result { + let mut rows = conn + .query( + "SELECT type, name, sql FROM sqlite_master \ + WHERE name NOT LIKE 'sqlite_%' \ + ORDER BY type, name", + (), + ) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + + let mut out = String::new(); + while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? { + let t: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?; + let name: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?; + let sql: Option = + row.get(2).map_err(|e| StoreError::Backend(e.to_string()))?; + out.push_str(&t); + out.push('|'); + out.push_str(&name); + out.push('|'); + if let Some(sql) = sql { + out.push_str(&normalize_schema(&sql)); + } + out.push('\n'); + } + Ok(out) +} + +/// Builds an in-memory database from the declared schema and fingerprints it. +pub async fn declared_fingerprint() -> Result { + let db = turso::Builder::new_local(":memory:") + .build() + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + let conn = db.connect().map_err(|e| StoreError::Backend(e.to_string()))?; + conn.execute_batch(&schema_sql()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + fingerprint(&conn).await +} + +/// A single schema object for diff reporting. +#[derive(Debug, Clone)] +pub(crate) struct SchemaObject { + pub(crate) kind: String, + pub(crate) name: String, + pub(crate) sql: String, +} + +/// Parses the normalised schema into objects keyed by (kind, name). +pub(crate) fn parse_objects(fingerprint: &str) -> Vec { + fingerprint + .lines() + .filter(|line| !line.is_empty()) + .filter_map(|line| { + let mut parts = line.splitn(3, '|'); + let kind = parts.next()?.to_string(); + let name = parts.next()?.to_string(); + let sql = parts.next().unwrap_or("").to_string(); + Some(SchemaObject { kind, name, sql }) + }) + .collect() +} + +/// Human-readable description of how two fingerprints differ. +pub(crate) fn diff_report(old: &str, new: &str) -> String { + let old_objs = parse_objects(old); + let new_objs = parse_objects(new); + + let mut missing = Vec::new(); + let mut extra = Vec::new(); + let mut changed = Vec::new(); + + for old_obj in &old_objs { + match new_objs.iter().find(|n| n.kind == old_obj.kind && n.name == old_obj.name) { + Some(new_obj) if new_obj.sql != old_obj.sql => changed.push((old_obj, new_obj)), + Some(_) => {} + None => missing.push(old_obj), + } + } + for new_obj in &new_objs { + if !old_objs.iter().any(|o| o.kind == new_obj.kind && o.name == new_obj.name) { + extra.push(new_obj); + } + } + + let mut lines = Vec::new(); + for obj in missing { + lines.push(format!("- {} {} (removed)", obj.kind, obj.name)); + } + for obj in extra { + lines.push(format!("+ {} {} (added)", obj.kind, obj.name)); + } + for (old_obj, new_obj) in changed { + lines.push(format!("~ {} {} (changed)", old_obj.kind, old_obj.name)); + if old_obj.kind == "table" { + let old_cols = extract_column_names(&old_obj.sql); + let new_cols = extract_column_names(&new_obj.sql); + let added: Vec<&str> = new_cols + .iter() + .filter(|c| !old_cols.contains(c)) + .map(String::as_str) + .collect(); + let removed: Vec<&str> = old_cols + .iter() + .filter(|c| !new_cols.contains(c)) + .map(String::as_str) + .collect(); + if !added.is_empty() { + lines.push(format!(" added columns: {}", added.join(", "))); + } + if !removed.is_empty() { + lines.push(format!(" removed columns: {}", removed.join(", "))); + } + } + } + + if lines.is_empty() { + "schemas differ (cosmetic normalisation only)".to_string() + } else { + lines.join("\n") + } +} + +/// Extracts the column names from a normalised CREATE TABLE statement. +/// Constraints at the table level are ignored; only top-level definitions +/// that start with an identifier are collected. +fn extract_column_names(sql: &str) -> Vec { + let body = match sql.strip_prefix("CREATE TABLE ") { + Some(rest) => rest, + None => return Vec::new(), + }; + let body = remove_if_not_exists(body); + let Some(start) = body.find('(') else { + return Vec::new(); + }; + let Some(end) = body.rfind(')') else { + return Vec::new(); + }; + let body = &body[start + 1..end]; + + let mut cols = Vec::new(); + let mut depth = 0i32; + let mut current = String::new(); + for ch in body.chars() { + match ch { + '(' => { + depth += 1; + current.push(ch); + } + ')' => { + depth -= 1; + current.push(ch); + } + ',' if depth == 0 => { + if let Some(col) = first_identifier(¤t) { + cols.push(col); + } + current.clear(); + } + _ => current.push(ch), + } + } + if !current.is_empty() { + if let Some(col) = first_identifier(¤t) { + cols.push(col); + } + } + cols +} + +fn first_identifier(item: &str) -> Option { + let item = item.trim(); + if item.is_empty() { + return None; + } + let first = item.split_whitespace().next()?; + let first = first.to_lowercase(); + if first == "constraint" + || first == "primary" + || first == "unique" + || first == "check" + || first == "foreign" + { + return None; + } + Some(first) +} + +/// Normalises SQL text so that cosmetic differences disappear. +/// +/// Differences deliberately ignored: +/// - whitespace runs collapse to a single space; +/// - SQL comments (`--` to end of line, `/* ... */`) are removed; +/// - `IF NOT EXISTS` is removed (case-insensitive, whole tokens only). +/// +/// Differences deliberately preserved: +/// - identifier case and spelling; +/// - string literal contents, including any whitespace or comment-like text +/// inside them; +/// - numeric literals, keyword order and constraint text. +fn normalize_schema(sql: &str) -> String { + let mut out = String::with_capacity(sql.len()); + let mut chars = sql.chars().peekable(); + let mut in_string = false; + let mut prev_ws = false; + + while let Some(ch) = chars.next() { + if in_string { + out.push(ch); + if ch == '\'' { + if chars.peek() == Some(&'\'') { + out.push(chars.next().unwrap()); + } else { + in_string = false; + } + } + continue; + } + + if ch == '-' && chars.peek() == Some(&'-') { + chars.next(); + while let Some(c) = chars.next() { + if c == '\n' { + break; + } + } + prev_ws = true; + continue; + } + + if ch == '/' && chars.peek() == Some(&'*') { + chars.next(); + while let Some(c) = chars.next() { + if c == '*' && chars.peek() == Some(&'/') { + chars.next(); + break; + } + } + prev_ws = true; + continue; + } + + if ch == '\'' { + in_string = true; + out.push(ch); + prev_ws = false; + continue; + } + + if ch.is_whitespace() { + prev_ws = true; + continue; + } + + if prev_ws && !out.is_empty() { + out.push(' '); + } + out.push(ch); + prev_ws = false; + } + + remove_if_not_exists(&out) +} + +/// Strips a normalised `IF NOT EXISTS` token sequence, preserving whitespace +/// around it. Because `normalize_schema` has already collapsed whitespace, the +/// sequence appears as separate tokens separated by single spaces. +fn remove_if_not_exists(sql: &str) -> String { + let tokens: Vec<&str> = sql.split(' ').collect(); + let mut out = Vec::with_capacity(tokens.len()); + let mut i = 0; + while i < tokens.len() { + if i + 2 < tokens.len() + && tokens[i].eq_ignore_ascii_case("IF") + && tokens[i + 1].eq_ignore_ascii_case("NOT") + && tokens[i + 2].eq_ignore_ascii_case("EXISTS") + { + i += 3; + } else { + out.push(tokens[i]); + i += 1; + } + } + out.join(" ") +} + +#[cfg(test)] +mod tests { + use super::{normalize_schema, parse_objects}; + + #[test] + fn comments_and_whitespace_do_not_change_meaning() { + let a = "CREATE TABLE foo (\n id INTEGER, -- the key\n name TEXT /* a comment */\n);"; + let b = "CREATE TABLE foo ( id INTEGER, name TEXT );"; + assert_eq!(normalize_schema(a), normalize_schema(b)); + } + + #[test] + fn if_not_exists_is_ignored() { + let a = "CREATE TABLE IF NOT EXISTS foo (id INTEGER);"; + let b = "CREATE TABLE foo (id INTEGER);"; + assert_eq!(normalize_schema(a), normalize_schema(b)); + } + + #[test] + fn string_literals_are_preserved() { + let a = "CREATE TABLE foo (name TEXT DEFAULT 'a -- b /* c */');"; + let b = "CREATE TABLE foo (name TEXT DEFAULT 'a -- b /* c */');"; + assert_eq!(normalize_schema(a), normalize_schema(b)); + } + + #[test] + fn real_differences_still_differ() { + let a = "CREATE TABLE foo (id INTEGER);"; + let b = "CREATE TABLE foo (id TEXT);"; + assert_ne!(normalize_schema(a), normalize_schema(b)); + } + + #[test] + fn if_not_exists_does_not_corrupt_identifiers() { + // The stripper looks for whole tokens; words that merely appear + // inside identifiers or string literals must stay put. + let a = "CREATE TABLE IF NOT EXISTS notification (if_not_exists TEXT DEFAULT 'IF NOT EXISTS');"; + let b = "CREATE TABLE notification (if_not_exists TEXT DEFAULT 'IF NOT EXISTS');"; + assert_eq!(normalize_schema(a), normalize_schema(b)); + } + + #[test] + fn partial_index_where_clause_is_parsed_safely() { + // Partial-index SQL contains a WHERE clause; diff_report must not + // try to extract column names from it, and parsing must not panic. + let fp = "index|tag_one_default|CREATE UNIQUE INDEX tag_one_default ON tag(board_id) WHERE is_default = 1\n"; + let objs = parse_objects(fp); + assert_eq!(objs.len(), 1); + assert_eq!(objs[0].kind, "index"); + assert_eq!(objs[0].name, "tag_one_default"); + } +} diff --git a/crates/in-core/src/store/secret.rs b/crates/in-core/src/store/secret.rs new file mode 100644 index 0000000..8d1e963 --- /dev/null +++ b/crates/in-core/src/store/secret.rs @@ -0,0 +1,199 @@ +//! The SMTP password's second lock. +//! +//! File permissions on the database (see [`TursoStore::open`]) stop a casual +//! `ls` on the server from reading the password, but a copy of the database +//! file — a backup, a snapshot, an `scp` by someone who should not have had +//! it — carries the plaintext right along with it. This module is the fix: +//! the column holds ciphertext, and the key that opens it lives in a second +//! file (`in.key`, beside the database) that a database backup does not +//! automatically include. +//! +//! The envelope is `v1:` followed by base64 of a 24-byte XChaCha20-Poly1305 +//! nonce and the sealed bytes it protects. The prefix is what lets +//! [`TursoStore::open`] tell a value we sealed apart from a plaintext +//! password left behind by a deployment from before this module existed — +//! see the migration note there. There is deliberately no `v2` yet; add one +//! the day the algorithm changes, and keep `open` accepting both prefixes for +//! as long as ciphertext under the old one might still be sitting in a row. +//! +//! Losing the key file — a backup restored without its sibling, most likely — +//! is not a crash. [`open`] returns `None` on anything it cannot make sense +//! of: wrong key, damaged ciphertext, a value that never was one of ours. +//! The caller in [`TursoStore::smtp_password`] turns that into "no password +//! set", which is the same screen an admin sees on a workspace that never had +//! a sender configured, and the same fix: type the password in again. + +use std::io; +use std::path::Path; + +use base64::Engine; +use base64::engine::general_purpose::STANDARD as base64; +use chacha20poly1305::aead::Aead; +use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; +use rand::Rng; + +/// A key is 32 raw bytes; nothing here derives it from a password, because +/// there is no password to derive it from — it is the thing that protects +/// one. +pub const KEY_BYTES: usize = 32; +pub type Key = [u8; KEY_BYTES]; + +const PREFIX: &str = "v1:"; +const NONCE_BYTES: usize = 24; + +/// True for a value already in our envelope — the test the migration-at-open +/// logic uses to skip a row it has already sealed. +pub fn is_sealed(value: &str) -> bool { + value.starts_with(PREFIX) +} + +/// Encrypts `plaintext` under `key`, returning the envelope ready to store. +/// +/// A fresh random nonce is drawn every call, so sealing the same password +/// twice gives two different strings. XChaCha20-Poly1305's 24-byte nonce is +/// wide enough that "draw at random and never track reuse" is safe for the +/// volume of writes a settings panel produces in a workspace's lifetime. +pub fn seal(key: &Key, plaintext: &str) -> String { + let cipher = XChaCha20Poly1305::new(key.into()); + let mut nonce_bytes = [0u8; NONCE_BYTES]; + rand::rng().fill_bytes(&mut nonce_bytes); + let nonce = XNonce::from_slice(&nonce_bytes); + let ciphertext = cipher + .encrypt(nonce, plaintext.as_bytes()) + .expect("XChaCha20-Poly1305 cannot fail to encrypt a plaintext this small"); + let mut payload = Vec::with_capacity(NONCE_BYTES + ciphertext.len()); + payload.extend_from_slice(&nonce_bytes); + payload.extend_from_slice(&ciphertext); + format!("{PREFIX}{}", base64.encode(payload)) +} + +/// Reverses [`seal`]. `None` covers every way this can fail to come back — +/// not our prefix, not valid base64, too short to hold a nonce, wrong key, +/// or a tampered/truncated ciphertext that fails the Poly1305 tag check — +/// and every one of those is meant to degrade to "no password", never panic +/// or bubble an error past the mailer. +pub fn open(key: &Key, sealed: &str) -> Option { + let body = sealed.strip_prefix(PREFIX)?; + let payload = base64.decode(body).ok()?; + if payload.len() < NONCE_BYTES { + return None; + } + let (nonce_bytes, ciphertext) = payload.split_at(NONCE_BYTES); + let cipher = XChaCha20Poly1305::new(key.into()); + let nonce = XNonce::from_slice(nonce_bytes); + let plaintext = cipher.decrypt(nonce, ciphertext).ok()?; + String::from_utf8(plaintext).ok() +} + +/// Reads the key at `path`, generating and writing a fresh one (mode 0600, +/// where the platform has modes) if the file is not there yet. +/// +/// Called once, at [`TursoStore::open`] — the key is loaded, not re-read per +/// query, so a corrupted key file is a boot-time failure, not a per-send one. +pub fn load_or_create_key(path: &Path) -> io::Result { + match std::fs::read(path) { + Ok(bytes) => { + let key: Key = bytes.try_into().map_err(|bytes: Vec| { + io::Error::new( + io::ErrorKind::InvalidData, + format!( + "{} holds {} bytes, not the {KEY_BYTES} of a key", + path.display(), + bytes.len() + ), + ) + })?; + Ok(key) + } + Err(e) if e.kind() == io::ErrorKind::NotFound => { + let mut key = [0u8; KEY_BYTES]; + rand::rng().fill_bytes(&mut key); + std::fs::write(path, key)?; + restrict(path)?; + Ok(key) + } + Err(e) => Err(e), + } +} + +/// 0600 on a freshly written file holding key material or a live credential. +#[cfg(unix)] +pub fn restrict(path: &Path) -> io::Result<()> { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)) +} + +#[cfg(not(unix))] +pub fn restrict(_path: &Path) -> io::Result<()> { + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn key() -> Key { + let mut k = [0u8; KEY_BYTES]; + rand::rng().fill_bytes(&mut k); + k + } + + #[test] + fn roundtrip() { + let k = key(); + let sealed = seal(&k, "hunter2"); + assert!(is_sealed(&sealed)); + assert_eq!(open(&k, &sealed).as_deref(), Some("hunter2")); + } + + #[test] + fn tamper_fails() { + let k = key(); + let mut sealed = seal(&k, "hunter2").into_bytes(); + let last = sealed.len() - 1; + sealed[last] ^= 0x01; + let sealed = String::from_utf8(sealed).unwrap(); + assert_eq!(open(&k, &sealed), None); + } + + #[test] + fn wrong_key_fails() { + let sealed = seal(&key(), "hunter2"); + assert_eq!(open(&key(), &sealed), None); + } + + #[test] + fn non_envelope_fails() { + let k = key(); + assert_eq!(open(&k, "hunter2"), None); + assert_eq!(open(&k, ""), None); + assert_eq!(open(&k, "v1:not-base64!!"), None); + } + + #[test] + fn load_or_create_key_persists_and_restricts() { + let dir = std::env::temp_dir().join(format!("in-key-test-{}", unique_suffix())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("in.key"); + let first = load_or_create_key(&path).unwrap(); + let second = load_or_create_key(&path).unwrap(); + assert_eq!(first, second, "a second open reuses the same key"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + } + let _ = std::fs::remove_dir_all(&dir); + } + + // A tiny stand-in so this module does not reach for the `ulid` crate just + // to name a scratch directory. + fn unique_suffix() -> u64 { + use std::time::{SystemTime, UNIX_EPOCH}; + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() as u64 + } +} diff --git a/crates/in-core/src/store/sniff.rs b/crates/in-core/src/store/sniff.rs new file mode 100644 index 0000000..d83a465 --- /dev/null +++ b/crates/in-core/src/store/sniff.rs @@ -0,0 +1,366 @@ +//! What uploaded bytes are, decided from the bytes themselves — never from a +//! part's `content_type()`, which is whatever the browser felt like sending. +//! +//! Pure `bytes -> mime`, with no I/O and nothing browser-shaped in it, living +//! behind the same `server` gate as the store it serves. The upload path +//! sniffs a file once when it arrives; [`TursoStore::open`] additionally runs +//! [`refine`] over rows whose stored type is one of the [`GENERIC_MIME_TYPES`] +//! buckets, so attachments written before the sniffer could name OOXML files +//! come out of the next restart carrying their real type. One definition +//! serves both callers: the store cannot reach the web crate, and a second +//! sniffer would drift. + +/// The mime types the upload path can store that name nothing: a zip that is +/// not an office document, bytes no magic matched, and an OLE container with +/// no stream name to narrow it. The boot pass reads only rows wearing one of +/// these; `text/plain` is deliberately absent — no window of a text file can +/// ever refine it, so sweeping it would read every text blob on every boot +/// for a guaranteed no-op. +pub const GENERIC_MIME_TYPES: &[&str] = &[ + "application/zip", + "application/octet-stream", + "application/x-ole-storage", +]; + +/// Head bytes read per generic row: every prefix-magic format this sniffer +/// knows decides from the first bytes, an OpenDocument file's `mimetype` +/// entry is required to be the first thing in the file, and an OLE +/// container's directory sectors precede its stream data. +pub const HEAD_WINDOW: i64 = 64 * 1024; +/// Tail bytes read per generic row. A zip ends with its end-of-central- +/// directory record, which — comment included — can sit at most +/// 22 + 65535 bytes from the end of the file, so a tail this wide can never +/// miss it, and it usually holds much of the central directory besides. +pub const TAIL_WINDOW: i64 = 128 * 1024; +/// A central directory larger than this — tens of thousands of entries — is +/// left unread and the row left exactly as stored. +pub const DIRECTORY_CAP: i64 = 4 * 1024 * 1024; + +pub fn sniff(bytes: &[u8]) -> &'static str { + if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) { + "image/png" + } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { + "image/jpeg" + } else if bytes.starts_with(b"GIF8") { + "image/gif" + } else if bytes.starts_with(b"%PDF-") { + "application/pdf" + } else if bytes.starts_with(b"PK\x03\x04") { + // Every OOXML and OpenDocument file is a zip; what kind it is lives in + // the entry names, which a zip stores uncompressed. `xl/workbook.xml` + // is the one part an xlsx cannot be without, an ods declares its + // type in the `mimetype` entry the format requires be stored first, + // and `ppt/presentation.xml` is the one part a pptx cannot be + // without. + zip_mime(bytes) + } else if bytes.starts_with(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]) { + // The pre-2007 OLE compound file .xls, .doc and .ppt all share. Its + // directory holds stream names in UTF-16, and only a workbook carries + // one called `Workbook` — a .doc or .ppt stays an unnamed container. + if contains(bytes, b"W\0o\0r\0k\0b\0o\0o\0k\0") { + "application/vnd.ms-excel" + } else { + "application/x-ole-storage" + } + } else if bytes.starts_with(&[0x1F, 0x8B]) { + "application/gzip" + } else if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" && &bytes[8..12] == b"avif" { + "image/avif" + } else if bytes.len() >= 12 + && &bytes[4..8] == b"ftyp" + && matches!( + &bytes[8..12], + b"heic" | b"heix" | b"hevc" | b"heif" | b"mif1" | b"msf1" + ) + { + // Apple's HEIC container reuses the ISO-BMFF `ftyp` box video shares; + // the brand at bytes 8..12 is what tells a photo from a video apart. + "image/heic" + } else if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" && &bytes[8..12] == b"qt " { + "video/quicktime" + } else if bytes.len() >= 8 && &bytes[4..8] == b"ftyp" { + "video/mp4" + } else if bytes.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]) { + "video/webm" + } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP" { + "image/webp" + } else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WAVE" { + "audio/wav" + } else if bytes.starts_with(b"fLaC") { + "audio/flac" + } else if bytes.starts_with(b"OggS") { + "audio/ogg" + } else if bytes.starts_with(b"ID3") + || bytes.starts_with(&[0xFF, 0xFB]) + || bytes.starts_with(&[0xFF, 0xF3]) + || bytes.starts_with(&[0xFF, 0xF2]) + { + "audio/mpeg" + } else if std::str::from_utf8(bytes).is_ok() { + "text/plain" + } else { + "application/octet-stream" + } +} + +/// Which office document a zip's bytes declare, decided the way every reader +/// of the format does: by the entry names a zip stores uncompressed. Ends in +/// [`GENERIC_MIME_TYPES`]' zip bucket when the names name nothing. +fn zip_mime(bytes: &[u8]) -> &'static str { + if contains(bytes, b"xl/workbook.xml") { + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + } else if contains(bytes, b"opendocument.spreadsheet") { + "application/vnd.oasis.opendocument.spreadsheet" + } else if contains(bytes, b"ppt/presentation.xml") { + "application/vnd.openxmlformats-officedocument.presentationml.presentation" + } else { + "application/zip" + } +} + +/// Whether `haystack` holds `needle` anywhere in it. Used on zip bytes, where +/// the entry names sit in the clear even when the entries themselves do not. +fn contains(haystack: &[u8], needle: &[u8]) -> bool { + haystack + .windows(needle.len()) + .any(|window| window == needle) +} + +/// The office mime declared by the zip entry names in `bytes` — the central +/// directory's vocabulary, where every entry a file holds is listed. An +/// OpenDocument file is deliberately absent: its marker is the *content* of +/// the `mimetype` entry the format requires be stored first, not an entry +/// name, so it is decided from the head window and could never be found here. +pub(crate) fn office_entry_mime(bytes: &[u8]) -> Option<&'static str> { + if contains(bytes, b"xl/workbook.xml") { + Some("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") + } else if contains(bytes, b"ppt/presentation.xml") { + Some("application/vnd.openxmlformats-officedocument.presentationml.presentation") + } else { + None + } +} + +/// What one generic row's byte windows decided. +#[derive(Debug)] +pub(crate) enum Verdict { + /// Nothing left to read. `Some` is a candidate more specific than the + /// stored bucket (subject to [`refinement`]), `None` means the windows + /// could not improve on what is stored — and, for a zip, never will: + /// whatever the central directory says, the search already covered it. + Settle(Option<&'static str>), + /// A zip whose windows name no office part. `offset`/`size` locate the + /// central directory as the end record states them; reading it is the + /// last word, because every entry name the file has is listed there. + ReadDirectory { offset: u64, size: u64 }, +} + +/// Decides a generic row from its head and tail windows alone. When the +/// windows themselves hold a verdict it settles; only a zip with no office +/// marker in either window asks for the central directory. +pub(crate) fn refine(stored: &str, head: &[u8], tail: &[u8]) -> Verdict { + let mut windows = Vec::with_capacity(head.len() + tail.len()); + windows.extend_from_slice(head); + windows.extend_from_slice(tail); + match sniff(&windows) { + "application/zip" => match end_of_central_directory(tail) { + Some((offset, size)) => Verdict::ReadDirectory { offset, size }, + None => Verdict::Settle(None), + }, + candidate => Verdict::Settle(refinement(stored, Some(candidate))), + } +} + +/// Whether `candidate` may replace `stored`: something specific, something +/// other than what is stored, and never `text/plain` — a window cannot prove +/// a whole blob is UTF-8, so a text verdict out of windows is unverifiable, +/// and a text row would gain nothing from the sweep anyway. Everything else +/// the sniffer names is either a prefix-magic fact (true of the whole blob +/// when true of its head) or an office marker, both safe to act on. +pub(crate) fn refinement(stored: &str, candidate: Option<&'static str>) -> Option<&'static str> { + let candidate = candidate?; + if candidate == stored + || candidate == "text/plain" + || GENERIC_MIME_TYPES.contains(&candidate) + { + return None; + } + Some(candidate) +} + +/// The end-of-central-directory record every zip ends with: `PK\x05\x06`, +/// then the directory's size (12..16) and offset (16..20), then a comment +/// whose declared length must land exactly at the end of the bytes. Scanning +/// from the end, the first signature satisfying that anchor is the record. +/// `None` when there is none to trust: no record at all, or a zip64 one — +/// the `u32::MAX` sentinels say the real numbers live in a zip64 locator +/// this pass declines to parse, and a row it declines stays as stored. +pub(crate) fn end_of_central_directory(tail: &[u8]) -> Option<(u64, u64)> { + if tail.len() < 22 { + return None; + } + for i in (0..=tail.len() - 22).rev() { + if &tail[i..i + 4] != b"PK\x05\x06" { + continue; + } + let comment = u16::from_le_bytes([tail[i + 20], tail[i + 21]]) as usize; + if i + 22 + comment != tail.len() { + continue; + } + let size = u32::from_le_bytes(tail[i + 12..i + 16].try_into().ok()?) as u64; + let offset = u32::from_le_bytes(tail[i + 16..i + 20].try_into().ok()?) as u64; + if offset == u32::MAX as u64 || size == u32::MAX as u64 { + return None; + } + return Some((offset, size)); + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sniffs_the_magic_numbers() { + assert_eq!(sniff(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A]), "image/png"); + assert_eq!(sniff(&[0xFF, 0xD8, 0xFF, 0xE0]), "image/jpeg"); + assert_eq!(sniff(b"hello, this is plainly text"), "text/plain"); + assert_eq!( + sniff(&[0x00, 0x01, 0xFE, 0xFF, 0x02]), + "application/octet-stream" + ); + } + + #[test] + fn sniffs_the_media_types() { + assert_eq!( + sniff(b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00"), + "video/mp4" + ); + assert_eq!( + sniff(b"\x00\x00\x00\x18ftypavif\x00\x00\x00\x00"), + "image/avif" + ); + assert_eq!( + sniff(b"\x00\x00\x00\x18ftypheic\x00\x00\x00\x00"), + "image/heic" + ); + assert_eq!( + sniff(b"\x00\x00\x00\x18ftypmif1\x00\x00\x00\x00"), + "image/heic" + ); + assert_eq!( + sniff(b"\x00\x00\x00\x14ftypqt \x00\x00\x00\x00"), + "video/quicktime" + ); + assert_eq!(sniff(&[0x1A, 0x45, 0xDF, 0xA3, 0x00, 0x00]), "video/webm"); + assert_eq!(sniff(b"RIFF\x00\x00\x00\x00WEBPVP8 "), "image/webp"); + assert_eq!(sniff(b"RIFF\x00\x00\x00\x00WAVEfmt "), "audio/wav"); + assert_eq!(sniff(b"fLaC\x00\x00\x00\x00"), "audio/flac"); + assert_eq!(sniff(b"OggS\x00\x00\x00\x00"), "audio/ogg"); + assert_eq!(sniff(b"ID3\x03\x00\x00\x00"), "audio/mpeg"); + assert_eq!(sniff(&[0xFF, 0xFB, 0x90, 0x00]), "audio/mpeg"); + } + + /// A zip of the named entries, bytes inside irrelevant: the sniff reads + /// the entry names a zip stores uncompressed. + fn zip_with(names: &[&str]) -> Vec { + use std::io::Write as _; + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for name in names { + zip.start_file(*name, zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(b"").unwrap(); + } + zip.finish().unwrap().into_inner() + } + + #[test] + fn a_presentation_sniffs_its_presentation_mime_and_a_plain_zip_stays_a_zip() { + let pptx = zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]); + assert_eq!( + sniff(&pptx), + "application/vnd.openxmlformats-officedocument.presentationml.presentation" + ); + assert_eq!(sniff(&zip_with(&["notes.txt"])), "application/zip"); + } + + #[test] + fn a_workbook_declared_only_in_its_central_directory_is_found_by_the_directory_search() { + let bytes = zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]); + let head = &bytes[..bytes.len() / 2]; + // Both windows of a cut in half hold the marker, so the windows alone + // settle a small file. + assert!(contains(head, b"ppt/presentation.xml")); + match refine("application/zip", head, &bytes[bytes.len() / 2..]) { + Verdict::Settle(Some( + "application/vnd.openxmlformats-officedocument.presentationml.presentation", + )) => {} + other => panic!("expected a settled presentation, got {other:?}"), + } + // The real end record survives its move into the synthetic tail. + let (offset, size) = end_of_central_directory(&bytes).expect("a real zip has an EOCD"); + let directory = &bytes[offset as usize..(offset + size) as usize]; + assert_eq!( + office_entry_mime(directory), + Some("application/vnd.openxmlformats-officedocument.presentationml.presentation") + ); + } + + #[test] + fn an_eocd_is_found_by_its_anchor_and_declined_when_zip64_or_absent() { + // A hand-built record: signature, the two disk fields, two entry + // counts, size, offset, a one-byte comment. + let mut tail = Vec::new(); + tail.extend_from_slice(b"PK\x05\x06"); + tail.extend_from_slice(&[0, 0, 0, 0]); // disk numbers + tail.extend_from_slice(&[1, 0, 1, 0]); // entry counts + tail.extend_from_slice(&0x1122_3344u32.to_le_bytes()); // size + tail.extend_from_slice(&0x5566_7788u32.to_le_bytes()); // offset + tail.extend_from_slice(&1u16.to_le_bytes()); // comment length + tail.push(b'!'); + assert_eq!( + end_of_central_directory(&tail), + Some((0x5566_7788, 0x1122_3344)) + ); + // A lie about the comment length leaves the record unanchored. + let mut drifting = tail.clone(); + *drifting.last_mut().unwrap() = b'?'; + drifting.push(b'!'); + assert_eq!(end_of_central_directory(&drifting), None); + // zip64 sentinels are declined rather than mis-read. + let mut zip64 = tail.clone(); + zip64[16..20].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(end_of_central_directory(&zip64), None); + // No record, no verdict. + assert_eq!(end_of_central_directory(b"PK\x03\x04 not a tail"), None); + assert_eq!(end_of_central_directory(&[]), None); + } + + #[test] + fn a_refinement_must_be_specific_different_and_never_text() { + assert_eq!(refinement("application/zip", Some("image/png")), Some("image/png")); + assert_eq!(refinement("image/png", Some("image/png")), None, "no rewrite of the same value"); + assert_eq!(refinement("application/zip", Some("text/plain")), None, "windows cannot prove text"); + assert_eq!(refinement("application/zip", Some("application/zip")), None, "never narrowed"); + assert_eq!(refinement("application/zip", Some("application/octet-stream")), None); + assert_eq!(refinement("application/zip", None), None); + } + + #[test] + fn an_opendocument_file_is_decided_from_the_head_window_alone() { + // The format requires the `mimetype` entry first, stored + // uncompressed: its marker is the first thing in the file. + let head = b"PK\x03\x04\x08\x00\x00\x00mimetypeapplication/vnd.oasis.opendocument.spreadsheet"; + match refine("application/zip", head, b"") { + Verdict::Settle(Some( + "application/vnd.oasis.opendocument.spreadsheet", + )) => {} + other => panic!("expected a settled spreadsheet, got {other:?}"), + } + // And the directory search, which reads entry names only, never + // claims one — the marker is entry content, not an entry name. + assert_eq!(office_entry_mime(head), None); + } +} diff --git a/crates/in-core/src/store/turso_store.rs b/crates/in-core/src/store/turso_store.rs new file mode 100644 index 0000000..6799a1d --- /dev/null +++ b/crates/in-core/src/store/turso_store.rs @@ -0,0 +1,2888 @@ +//! Turso implementation of [`Store`]. +//! +//! Turso is in-process and SQLite-compatible, so the schema is plain SQL and +//! there is no server to run alongside the binary. It ships no migration +//! runner of its own; [`TursoStore::open`] applies the numbered files in +//! `crates/in-core/migrations` at boot and verifies the result. + +use async_trait::async_trait; +use rand::Rng; +use time::format_description::well_known::Rfc3339; +use time::OffsetDateTime; +use turso::transaction::{Transaction, TransactionBehavior}; +use turso::{Builder, Connection, Row, params}; +use ulid::Ulid; + +use super::secret; +use super::{ + CHUNK_SIZE, CreatedLink, File, Folder, Listing, Result, ShareKind, ShareLink, SharedItem, + Store, StoreError, ThumbState, UPLOAD_TTL_HOURS, UploadSession, UploadState, User, +}; +use super::{ReconcileOptions, reconcile, schema, sniff}; +use crate::live::{Change, Topic}; +use crate::thumbs; + +/// Where one file's bytes live: `/files/`, named by the row's +/// own id. What an upload carried never decides a path here — the name is +/// always store-made, so `name` stays a label. +const FILES_DIR: &str = "files"; +/// Where thumbnails live: `/thumbs/`, webp, longest edge 512. +const THUMBS_DIR: &str = "thumbs"; +/// Where upload chunks stage: `/uploads//`. +const UPLOADS_DIR: &str = "uploads"; + +/// Thumbnails are attempted only below this source size: 64 MiB. Past it the +/// row wears `failed` rather than pinning memory the size of the file. +const THUMB_SOURCE_CAP: u64 = 64 * 1024 * 1024; + +const USER_COLUMNS: &str = + "id, oidc_sub, email, display_name, admin, disabled, quota_bytes, used_bytes, created_at, last_seen_at"; +const FOLDER_COLUMNS: &str = "id, owner_id, parent_id, name, created_at, deleted_at"; +const FILE_COLUMNS: &str = + "id, owner_id, folder_id, name, mime, size_bytes, thumb_state, created_at, updated_at, deleted_at"; +const LINK_COLUMNS: &str = + "id, token_hash, kind, target_id, created_by, can_download, created_at, expires_at, revoked_at"; +const SESSION_COLUMNS: &str = + "id, owner_id, folder_id, name, size_bytes, chunk_size, received_bytes, state, created_at, expires_at"; + +pub struct TursoStore { + /// Shared by every single-statement call. Turso serialises statements on a + /// connection, so this is safe; transactions are the exception and take a + /// connection of their own. + conn: tokio::sync::Mutex, + db: turso::Database, + /// Where committed writes are announced. Held as the sender so the store + /// can hand out a receiver per subscriber; nothing is ever read from here + /// by the store itself. + live: tokio::sync::broadcast::Sender, + /// Root of the file tree the binary payloads live under: `files/` for + /// file bytes, `thumbs/` for thumbnails, `uploads/` for staged chunks — + /// one raw file per row, named by the row's own id. The database keeps + /// the facts and this tree keeps the bytes; a boot sweep deletes + /// whichever half outlives the other. + storage: std::path::PathBuf, +} + +impl TursoStore { + /// Announces a committed write. Called only once the write is durable — + /// after commit for a transaction, and never on a path that returned an + /// error — because a subscriber's whole job is to re-read, and waking it + /// before the row lands makes it read the past. + /// + /// A send with no subscribers returns `Err`, which is the ordinary state + /// of a server nobody is looking at. It is dropped on purpose: an + /// announcement nobody is waiting for is not a problem, and logging it + /// would fill the log with the sound of an idle app. + fn announce(&self, topics: impl IntoIterator) { + for topic in topics { + let _ = self.live.send(Change { + topic, + seq: crate::live::next_seq(), + }); + } + } + + /// Opens (creating if needed) the database at `path` and brings it up to + /// date. `storage` is the root of the file tree the binary payloads live + /// under — created here if missing, derived to sit beside the database + /// when `None`. + /// + /// The boot, in order: create the storage tree, rebuild a stale database + /// before any long-lived handle opens it, migrate an empty one, abort + /// upload sessions past their expiry, and sweep files no row names. + /// Trash is never purged here — see the note on the sweep below. + pub async fn open(database: &str, storage: Option<&std::path::Path>) -> Result { + let storage_buf; + let storage: &std::path::Path = match storage { + Some(dir) => dir, + None => { + // Beside the database: the two are one backup unit, so the + // default keeps them siblings. + storage_buf = default_storage(database); + &storage_buf + } + }; + // Before anything else, including the reconcile below that may need + // this tree: a fresh storage path is a normal first boot, and every + // writer past this point assumes the tree is there. + ensure_storage_dirs(storage)?; + let existed = database != ":memory:" && std::path::Path::new(database).exists(); + // Before anything holds this file open: a database of an older shape + // is rebuilt now, while no handle of ours points at the file that the + // rebuild is about to replace. + Self::repair_if_stale(database, storage).await?; + let db = Builder::new_local(database).build().await.map_err(backend)?; + let conn = db.connect().map_err(backend)?; + // Turso is a single-writer engine. Two connections on one Database + // handle serialise by themselves, but a second handle on the same file + // (a second process, or a careless second open) fails outright with + // "database is locked" and silently drops the write unless a busy + // timeout is set. Both pragmas are set on every connection we hand out. + for pragma in ["PRAGMA foreign_keys = ON", "PRAGMA busy_timeout = 5000"] { + conn.execute(pragma, ()).await.map_err(backend)?; + } + // The database file sits beside other local users; 0600 right after + // creation closes the window between "file exists" and "file is ours + // alone" — a WAL file, if this engine leaves one beside the main + // file, gets the same restriction while it's still there to restrict. + if !existed && database != ":memory:" { + restrict_if_present(std::path::Path::new(database))?; + restrict_if_present(&sibling(database, "-wal"))?; + restrict_if_present(&sibling(database, "-shm"))?; + } + // 256 is deep enough that a client which pauses for a moment catches + // up without noticing, and shallow enough that one wedged subscriber + // cannot pin an unbounded backlog. Overflowing it is not a failure: + // the reader is told it lagged and resyncs, which is cheaper than the + // memory a larger buffer would cost to avoid saying so. + let (live, _) = tokio::sync::broadcast::channel(256); + let store = Self { + conn: tokio::sync::Mutex::new(conn), + db, + live, + storage: storage.to_path_buf(), + }; + store.migrate(database).await?; + store.prune_expired_uploads(OffsetDateTime::now_utc()).await?; + // Trash is deliberately NOT purged here: the age cutoff is the + // deployment's `purge_after_days`, which this signature never sees. + // The server calls `purge_expired` with its configured cutoff right + // after opening; this boot only aborts expired uploads and sweeps + // files no row names. + store.sweep_orphan_files().await?; + // The file may have been rebuilt from a backup; its permissions and + // any transient WAL/SHM siblings should still be private. + if database != ":memory:" { + restrict_if_present(std::path::Path::new(database))?; + restrict_if_present(&sibling(database, "-wal"))?; + restrict_if_present(&sibling(database, "-shm"))?; + } + Ok(store) + } + + /// Sets the storage tree against the database, once per boot. The + /// database and the tree are two halves of one state, and a crash between + /// a row write and its file write — either order — leaves exactly one + /// half behind. A file no row names goes, including a `.tmp` a crash + /// abandoned mid-write and a staged chunk whose session is gone; a row + /// whose file is gone is only said out loud and otherwise kept, because + /// deleting the row would turn a lost file into a lost fact — the row is + /// still what screens list, and a re-upload replaces it cleanly. + async fn sweep_orphan_files(&self) -> Result<()> { + let conn = self.conn.lock().await; + let files = known_ids(&conn, "SELECT id FROM file").await?; + let thumbs = known_ids( + &conn, + "SELECT id FROM file WHERE thumb_state = 'ready'", + ) + .await?; + let sessions = known_ids( + &conn, + "SELECT id FROM upload_session WHERE state = 'active'", + ) + .await?; + drop(conn); + for (dir, known, kind) in [ + (self.storage.join(FILES_DIR), &files, "file"), + (self.storage.join(THUMBS_DIR), &thumbs, "thumbnail"), + ] { + for id in known.iter() { + if !dir.join(id).is_file() { + eprintln!("{kind} {id} names a file that is not there"); + } + } + let entries = match std::fs::read_dir(&dir) { + Ok(entries) => entries, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, + Err(e) => return Err(backend(e)), + }; + for entry in entries { + let entry = entry.map_err(backend)?; + let path = entry.path(); + if !path.is_file() { + continue; + } + let named = entry + .file_name() + .to_str() + .is_some_and(|n| known.contains(n)); + if !named && let Err(e) = std::fs::remove_file(&path) { + eprintln!( + "could not delete orphaned storage file {}: {e}", + path.display() + ); + } + } + } + // A staged-chunk directory outlives its session only through a crash + // between the session write and the first chunk, or a removed session + // row — either way nothing will ever finish it, so it goes. + let uploads = self.storage.join(UPLOADS_DIR); + let entries = match std::fs::read_dir(&uploads) { + Ok(entries) => entries, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(e) => return Err(backend(e)), + }; + for entry in entries { + let entry = entry.map_err(backend)?; + let path = entry.path(); + if !path.is_dir() { + continue; + } + let named = entry + .file_name() + .to_str() + .is_some_and(|n| sessions.contains(n)); + if !named && let Err(e) = std::fs::remove_dir_all(&path) { + eprintln!( + "could not delete orphaned upload directory {}: {e}", + path.display() + ); + } + } + Ok(()) + } + + /// Brings the database to the declared schema. + /// + /// - An empty database is created from the migrations. + /// - A database that already matches the declared schema is left alone. + /// - A stale database is backed up, rebuilt, and re-verified once. + /// If the rebuilt database still does not match, the process stops + /// with the original backed up and untouched. + /// + /// SQLite's DDL is transactional, so a schema that dies halfway leaves + /// nothing behind: a half-created database is a boot that starts over, + /// not a database with a hole in it. + async fn migrate(&self, path: &str) -> Result<()> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT COUNT(*) FROM sqlite_master \ + WHERE type = 'table' AND name NOT LIKE 'sqlite_%'", + (), + ) + .await + .map_err(backend)?; + + let empty = match rows.next().await.map_err(backend)? { + Some(row) => row.get::(0).map_err(backend)? == 0, + None => true, + }; + drop(rows); + + if empty { + conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?; + if let Err(e) = conn.execute_batch(&super::schema::schema_sql()).await { + let _ = conn.execute("ROLLBACK", ()).await; + return Err(backend(e)); + } + return conn + .execute("COMMIT", ()) + .await + .map_err(backend) + .map(|_| ()); + } + + if path == ":memory:" { + // Tests own an in-memory database; its schema is whatever the + // test created, and the open should not try to reconcile it. + return Ok(()); + } + + // `repair_if_stale` ran before this handle was ever opened, so by now + // the file on disk matches. Saying so here is cheap and turns a + // reordering mistake into a refusal to start rather than a store + // running against a schema the code does not expect. + let have = schema::fingerprint(&conn).await.map_err(backend)?; + let want = schema::declared_fingerprint().await.map_err(backend)?; + if have != want { + return Err(StoreError::Backend(format!( + "database does not match the declared schema and was not repaired; \ + do not restart. diff:\n{}", + schema::diff_report(&have, &want) + ))); + } + Ok(()) + } + + /// Brings a database of an older shape onto the declared schema, BEFORE + /// any long-lived handle is opened on it. + /// + /// The order matters and is the whole reason this is not part of + /// `migrate`: `reconcile` swaps a rebuilt file into place, so a + /// `turso::Database` opened beforehand still refers to the file that is + /// now the backup. Reconnecting such a handle reads the old database and + /// makes a successful rebuild look like a failed one. + async fn repair_if_stale(path: &str, storage: &std::path::Path) -> Result<()> { + if path == ":memory:" || !std::path::Path::new(path).exists() { + return Ok(()); + } + let (have, empty) = { + let db = Builder::new_local(path).build().await.map_err(backend)?; + let conn = db.connect().map_err(backend)?; + let mut rows = conn + .query( + "SELECT COUNT(*) FROM sqlite_master \ + WHERE type = 'table' AND name NOT LIKE 'sqlite_%'", + (), + ) + .await + .map_err(backend)?; + let empty = match rows.next().await.map_err(backend)? { + Some(row) => row.get::(0).map_err(backend)? == 0, + None => true, + }; + drop(rows); + let have = if empty { + String::new() + } else { + schema::fingerprint(&conn).await.map_err(backend)? + }; + (have, empty) + }; + if empty { + return Ok(()); + } + let want = schema::declared_fingerprint().await.map_err(backend)?; + if have == want { + return Ok(()); + } + + eprintln!( + "database schema differs from the declared schema; rebuilding automatically\n{}", + schema::diff_report(&have, &want) + ); + reconcile( + path, + Some(storage), + ReconcileOptions { + dry_run: false, + yes: false, + auto: true, + }, + ) + .await?; + + // Check the result once, on a handle opened after the swap. A + // normalisation bug that rebuilt forever would otherwise write a + // full-size backup on every restart until the disk filled. + let db = Builder::new_local(path).build().await.map_err(backend)?; + let conn = db.connect().map_err(backend)?; + let after = schema::fingerprint(&conn).await.map_err(backend)?; + if after != want { + return Err(StoreError::Backend(format!( + "rebuild did not match the declared schema; the original is backed up beside it \ + and this is not retried. diff:\n{}", + schema::diff_report(&after, &want) + ))); + } + Ok(()) + } + + /// A connection of its own, for work that opens a transaction. + /// `Connection::transaction` takes `&mut self`, and a transaction on the + /// shared connection would swallow everyone else's statements. + async fn tx_conn(&self) -> Result { + let conn = self.db.connect().map_err(backend)?; + for pragma in ["PRAGMA foreign_keys = ON", "PRAGMA busy_timeout = 5000"] { + conn.execute(pragma, ()).await.map_err(backend)?; + } + Ok(conn) + } + + async fn one_row(&self, sql: &str, args: impl turso::IntoParams) -> Result> { + let conn = self.conn.lock().await; + let mut rows = conn.query(sql, args).await.map_err(backend)?; + rows.next().await.map_err(backend) + } +} + +/// Recomputes one account's usage from the rows: the sum of every file size +/// it holds, trashed or not. Runs inside the caller's transaction, so the +/// mutation and the total commit as one — usage can never drift from the +/// rows, because it is never carried anywhere except from them. +async fn refresh_usage(conn: &Connection, owner_id: &str) -> Result<()> { + conn.execute( + "UPDATE user SET used_bytes = \ + (SELECT COALESCE(SUM(size_bytes), 0) FROM file WHERE owner_id = ?1) \ + WHERE id = ?1", + params![owner_id], + ) + .await + .map_err(backend)?; + Ok(()) +} + +/// Refuses the write while there is still nothing on disk to clean up: the +/// owner's used bytes plus `extra` must fit the ceiling. +async fn check_quota(conn: &Connection, owner_id: &str) -> Result<(u64, u64)> { + let mut rows = conn + .query( + "SELECT quota_bytes, used_bytes FROM user WHERE id = ?1", + params![owner_id], + ) + .await + .map_err(backend)?; + match rows.next().await.map_err(backend)? { + Some(row) => { + let quota = row.get::(0).map_err(backend)?.max(0) as u64; + let used = row.get::(1).map_err(backend)?.max(0) as u64; + Ok((quota, used)) + } + None => Err(StoreError::NotFound), + } +} + +fn fit_quota(quota: u64, used: u64, extra: u64) -> Result<()> { + // A zero-byte write costs nothing, so it always fits — even under an + // account whose quota was lowered below current usage, which must still + // be able to trash and rearrange. + if extra > 0 && used.saturating_add(extra) > quota { + return Err(StoreError::QuotaExceeded); + } + Ok(()) +} + +/// The label an uploaded or typed name becomes: the last path segment, with +/// control characters stripped and surrounding whitespace trimmed. A name +/// that is a path (`../../etc`) is a valid file name and a terrible path, so +/// only the tail survives; a name that sanitises to nothing becomes +/// `Untitled` rather than failing the upload. +pub(crate) fn label_of(name: &str) -> String { + let base = name.rsplit(['/', '\\']).next().unwrap_or(name); + let clean: String = base.chars().filter(|c| !c.is_control()).collect(); + let trimmed = clean.trim().to_string(); + if trimmed.is_empty() { + "Untitled".to_string() + } else { + trimmed + } +} + +/// Addresses match case-insensitively: the provider may capitalise what +/// the row stored, so both sides fold before comparing. Provisioning folds +/// on the way in, and every lookup folds the question. +fn fold_email(email: &str) -> String { + email.trim().to_lowercase() +} + +/// Escapes a substring search for LIKE: backslash first, then the two +/// wildcards, so `100%` searches for a percent rather than everything. +fn like_pattern(query: &str) -> String { + let mut out = String::with_capacity(query.len() + 2); + out.push('%'); + for c in query.chars() { + if matches!(c, '\\' | '%' | '_') { + out.push('\\'); + } + out.push(c); + } + out.push('%'); + out +} + +/// A fresh public-link token: 32 random bytes, base64url without padding. +/// Shown once at creation; only its hash is stored. +fn new_token() -> String { + use base64::Engine as _; + let mut bytes = [0u8; 32]; + rand::rng().fill_bytes(&mut bytes); + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes) +} + +/// The token's hash, as stored: base64url SHA-256. Constant-length and +/// content-hiding — the row answers equality and nothing else. +/// +/// Public because resolving is by hash: the route holding the plaintext token +/// hashes it with this and calls [`Store::resolve_share_link`]. The two must +/// never disagree about the function, so there is exactly one. +pub fn hash_share_token(token: &str) -> String { + use base64::Engine as _; + use sha2::Digest as _; + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sha2::Sha256::digest(token.as_bytes())) +} +/// zero-byte upload has no chunks; its finish assembles the empty file. +fn chunk_count(size_bytes: u64) -> u64 { + if size_bytes == 0 { + 0 + } else { + size_bytes.div_ceil(CHUNK_SIZE) + } +} + +/// The exact bytes chunk `index` must carry: full [`CHUNK_SIZE`] except the +/// final one, which carries the remainder. +fn expected_chunk_len(size_bytes: u64, index: u64) -> u64 { + let full_before = index.saturating_mul(CHUNK_SIZE); + (size_bytes.saturating_sub(full_before)).min(CHUNK_SIZE) +} + +/// Where file `id`'s bytes live. +fn file_path(storage: &std::path::Path, id: &str) -> std::path::PathBuf { + storage.join(FILES_DIR).join(id) +} + +/// Where `id`'s thumbnail lives. +fn thumb_path(storage: &std::path::Path, id: &str) -> std::path::PathBuf { + storage.join(THUMBS_DIR).join(id) +} + +/// Where session `id`'s chunks stage. +fn session_dir(storage: &std::path::Path, id: &str) -> std::path::PathBuf { + storage.join(UPLOADS_DIR).join(id) +} + +/// Where chunk `index` of session `id` stages. +fn chunk_path( + storage: &std::path::Path, + id: &str, + index: u64, +) -> std::path::PathBuf { + session_dir(storage, id).join(index.to_string()) +} + +/// The staged bytes a session holds, summed from the chunk files on disk — +/// never from a counter a re-sent chunk could have double-counted. +fn staged_received(storage: &std::path::Path, id: &str) -> u64 { + let mut total = 0u64; + let dir = session_dir(storage, id); + let entries = match std::fs::read_dir(&dir) { + Ok(entries) => entries, + Err(_) => return 0, + }; + for entry in entries.flatten() { + if entry.path().is_file() { + total = total.saturating_add(entry.metadata().map(|m| m.len()).unwrap_or(0)); + } + } + total +} +/// Creates the storage tree — the root and one directory per payload kind — +/// and locks each to 0700 on unix. Every writer past `open` assumes the tree +/// is there. +fn ensure_storage_dirs(storage: &std::path::Path) -> Result<()> { + for dir in [ + storage.to_path_buf(), + storage.join(FILES_DIR), + storage.join(THUMBS_DIR), + storage.join(UPLOADS_DIR), + ] { + std::fs::create_dir_all(&dir) + .map_err(|e| StoreError::Backend(format!("could not create {}: {e}", dir.display())))?; + restrict_dir(&dir)?; + } + Ok(()) +} + +/// 0700 on a directory holding someone's files. +#[cfg(unix)] +fn restrict_dir(path: &std::path::Path) -> Result<()> { + use std::os::unix::fs::PermissionsExt as _; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).map_err(backend)?; + Ok(()) +} + +#[cfg(not(unix))] +fn restrict_dir(_path: &std::path::Path) -> Result<()> { + Ok(()) +} + +/// Where binary files live when no storage directory is handed in: beside +/// the database file. The two are one backup unit — a backup that takes the +/// database but not the files beside it restores a drive whose contents are +/// gone — so the default keeps them siblings. +fn default_storage(database: &str) -> std::path::PathBuf { + std::path::Path::new(database) + .parent() + .map(|parent| parent.join("storage")) + .unwrap_or_else(|| std::path::PathBuf::from("storage")) +} + +/// Writes `bytes` to `path` through a temp name in the same directory and a +/// rename, so a reader of the final name never sees a partial file — and a +/// crash mid-write leaves a temp name the boot sweep deletes rather than a +/// half file wearing a real one. The caller owns what happens next: the row +/// goes in after, and a failed row write unlinks this file best-effort. +fn write_file_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { + use std::io::Write as _; + let tmp = path.with_extension(format!("{}.tmp", Ulid::new())); + let mut file = std::fs::File::create(&tmp)?; + file.write_all(bytes)?; + file.flush()?; + match std::fs::rename(&tmp, path) { + Ok(()) => Ok(()), + Err(err) => { + let _ = std::fs::remove_file(&tmp); + Err(err) + } + } +} + +/// Reads up to `buf.len()` bytes from the start of the file at `path`. What +/// the sniffer and the thumbnailer decide from when the whole file is not +/// yet — or not affordably — in memory. +fn read_up_to(path: &std::path::Path, buf: &mut [u8]) -> std::io::Result { + use std::io::Read as _; + let mut file = std::fs::File::open(path)?; + let mut filled = 0; + while filled < buf.len() { + match file.read(&mut buf[filled..])? { + 0 => break, + n => filled += n, + } + } + Ok(filled) +} + +/// Every id `sql` hands back — the set of files the sweep must keep. +async fn known_ids(conn: &Connection, sql: &str) -> Result> { + let mut rows = conn.query(sql, ()).await.map_err(backend)?; + let mut out = std::collections::HashSet::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.insert(row.get::(0).map_err(backend)?); + } + Ok(out) +} + +/// A database sidecar (`in.db-wal`, `in.db-shm`): the file beside the main +/// one, wearing the same name plus the suffix. +fn sibling(path: &str, suffix: &str) -> std::path::PathBuf { + let base = std::path::Path::new(path); + let mut name = base + .file_name() + .map(|n| n.to_os_string()) + .unwrap_or_default(); + name.push(suffix); + base.parent() + .map(|parent| parent.join(&name)) + .unwrap_or_else(|| std::path::PathBuf::from(name)) +} + +/// 0600 on a file holding live state, when it is there to restrict. +fn restrict_if_present(path: &std::path::Path) -> Result<()> { + if path.exists() { + secret::restrict(path).map_err(backend)?; + } + Ok(()) +} + +fn backend(e: E) -> StoreError { + StoreError::Backend(e.to_string()) +} + +/// Whether this engine error is a uniqueness refusal rather than a +/// malfunction. The store checks names before writing, so this is only ever +/// the backstop for a race two Immediate transactions could not serialise — +/// and it answers with the name the check would have used. +fn is_constraint_violation(e: &turso::Error) -> bool { + let text = e.to_string().to_lowercase(); + text.contains("constraint") || text.contains("unique") +} + +fn now_text() -> Result { + stamp(OffsetDateTime::now_utc()) +} + +/// An RFC 3339 UTC timestamp: lexicographically sortable, which is what lets +/// expiry and purge comparisons live in SQL string order. +fn stamp(at: OffsetDateTime) -> Result { + at.format(&Rfc3339) + .map_err(|e| StoreError::Corrupt(format!("timestamp: {e}"))) +} + +fn parse_stamp(raw: &str) -> Result { + OffsetDateTime::parse(raw, &Rfc3339) + .map_err(|e| StoreError::Corrupt(format!("timestamp {raw:?}: {e}"))) +} +fn opt_stamp(row: &Row, idx: usize) -> Result> { + match row.get::>(idx).map_err(backend)? { + Some(raw) => Ok(Some(parse_stamp(&raw)?)), + None => Ok(None), + } +} + +/// One user row, in [`USER_COLUMNS`] order. +fn user_from(row: &Row) -> Result { + Ok(User { + id: text(row, 0)?, + oidc_sub: text(row, 1)?, + email: text(row, 2)?, + display_name: text(row, 3)?, + admin: row.get::(4).map_err(backend)? != 0, + disabled: row.get::(5).map_err(backend)? != 0, + quota_bytes: row.get::(6).map_err(backend)?.max(0) as u64, + used_bytes: row.get::(7).map_err(backend)?.max(0) as u64, + created_at: parse_stamp(&text(row, 8)?)?, + last_seen_at: opt_stamp(row, 9)?, + }) +} + +/// One folder row, in [`FOLDER_COLUMNS`] order. +fn folder_from(row: &Row) -> Result { + Ok(Folder { + id: text(row, 0)?, + owner_id: text(row, 1)?, + parent_id: opt_text(row, 2)?, + name: text(row, 3)?, + created_at: parse_stamp(&text(row, 4)?)?, + deleted_at: opt_stamp(row, 5)?, + }) +} + +/// One file row, in [`FILE_COLUMNS`] order — still without its bytes, which +/// no listing carries. +fn file_from(row: &Row) -> Result { + Ok(File { + id: text(row, 0)?, + owner_id: text(row, 1)?, + folder_id: opt_text(row, 2)?, + name: text(row, 3)?, + mime: text(row, 4)?, + size_bytes: row.get::(5).map_err(backend)?.max(0) as u64, + thumb_state: ThumbState::parse(&text(row, 6)?)?, + created_at: parse_stamp(&text(row, 7)?)?, + updated_at: parse_stamp(&text(row, 8)?)?, + deleted_at: opt_stamp(row, 9)?, + }) +} + +/// One share-link row, in [`LINK_COLUMNS`] order. +fn link_from(row: &Row) -> Result { + Ok(ShareLink { + id: text(row, 0)?, + token_hash: text(row, 1)?, + kind: ShareKind::parse(&text(row, 2)?)?, + target_id: text(row, 3)?, + created_by: text(row, 4)?, + can_download: row.get::(5).map_err(backend)? != 0, + created_at: parse_stamp(&text(row, 6)?)?, + expires_at: opt_stamp(row, 7)?, + revoked_at: opt_stamp(row, 8)?, + }) +} + +/// One upload-session row, in [`SESSION_COLUMNS`] order. +fn session_from(row: &Row) -> Result { + Ok(UploadSession { + id: text(row, 0)?, + owner_id: text(row, 1)?, + folder_id: opt_text(row, 2)?, + name: text(row, 3)?, + size_bytes: row.get::(4).map_err(backend)?.max(0) as u64, + chunk_size: row.get::(5).map_err(backend)?.max(0) as u64, + received_bytes: row.get::(6).map_err(backend)?.max(0) as u64, + state: UploadState::parse(&text(row, 7)?)?, + created_at: parse_stamp(&text(row, 8)?)?, + expires_at: parse_stamp(&text(row, 9)?)?, + }) +} + +fn text(row: &Row, idx: usize) -> Result { + row.get::(idx).map_err(backend) +} + +fn opt_text(row: &Row, idx: usize) -> Result> { + row.get::>(idx).map_err(backend) +} + +#[async_trait] +impl Store for TursoStore { + fn subscribe(&self) -> tokio::sync::broadcast::Receiver { + self.live.subscribe() + } + + async fn user_by_oidc_sub(&self, sub: &str) -> Result> { + let sql = format!("SELECT {USER_COLUMNS} FROM user WHERE oidc_sub = ?1"); + match self.one_row(&sql, params![sub]).await? { + Some(row) => Ok(Some(user_from(&row)?)), + None => Ok(None), + } + } + + async fn user_by_email(&self, email: &str) -> Result> { + let sql = format!("SELECT {USER_COLUMNS} FROM user WHERE email = ?1"); + match self.one_row(&sql, params![fold_email(email)]).await? { + Some(row) => Ok(Some(user_from(&row)?)), + None => Ok(None), + } + } + + async fn user(&self, id: &str) -> Result> { + let sql = format!("SELECT {USER_COLUMNS} FROM user WHERE id = ?1"); + match self.one_row(&sql, params![id]).await? { + Some(row) => Ok(Some(user_from(&row)?)), + None => Ok(None), + } + } + + async fn users(&self) -> Result> { + let conn = self.conn.lock().await; + let sql = format!("SELECT {USER_COLUMNS} FROM user ORDER BY created_at, id"); + let mut rows = conn.query(&sql, ()).await.map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(user_from(&row)?); + } + Ok(out) + } + + async fn provision_user( + &self, + sub: &str, + email: &str, + display_name: &str, + default_quota_bytes: u64, + ) -> Result { + let email = fold_email(email); + // IMMEDIATE: "first user ever" is read-then-write. Two concurrent + // first sign-ins each count zero users, each claim admin, and the + // deployment starts with two admins instead of one. + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + let sql = format!("SELECT {USER_COLUMNS} FROM user WHERE oidc_sub = ?1"); + let mut rows = tx.query(&sql, params![sub]).await.map_err(backend)?; + if let Some(row) = rows.next().await.map_err(backend)? { + let user = user_from(&row)?; + drop(rows); + // A returning person: the provider may have a new address or a + // new name for them, and the row follows the provider — but the + // admin flag and the quota are ours, and this write touches + // neither. + tx.execute( + "UPDATE user SET email = ?1, display_name = ?2, last_seen_at = ?3 WHERE id = ?4", + params![email, display_name, now_text()?, user.id], + ) + .await + .map_err(backend)?; + let mut back = tx.query(&sql, params![sub]).await.map_err(backend)?; + let row = back.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?; + let user = user_from(&row)?; + drop(back); + tx.commit().await.map_err(backend)?; + return Ok(user); + } + drop(rows); + let mut count = tx + .query("SELECT COUNT(*) FROM user", ()) + .await + .map_err(backend)?; + let n = match count.next().await.map_err(backend)? { + Some(row) => row.get::(0).map_err(backend)?, + None => 0, + }; + drop(count); + // The first account ever provisioned is the admin: there is no one + // else to make one, and a deployment with no admin is a deployment + // nobody can administer. + let admin = n == 0; + let id = Ulid::new().to_string(); + let now = now_text()?; + tx.execute( + "INSERT INTO user (id, oidc_sub, email, display_name, admin, disabled, \ + quota_bytes, used_bytes, created_at, last_seen_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, 0, ?6, 0, ?7, ?7)", + params![ + id.clone(), + sub, + email, + display_name, + if admin { 1 } else { 0 }, + default_quota_bytes as i64, + now + ], + ) + .await + .map_err(backend)?; + let mut back = tx + .query( + &format!("SELECT {USER_COLUMNS} FROM user WHERE id = ?1"), + params![id], + ) + .await + .map_err(backend)?; + let row = back.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?; + let user = user_from(&row)?; + drop(back); + tx.commit().await.map_err(backend)?; + self.announce([Topic::Admin(user.id.clone())]); + Ok(user) + } + + async fn set_user_quota(&self, user_id: &str, quota_bytes: u64) -> Result<()> { + let conn = self.conn.lock().await; + let n = conn + .execute( + "UPDATE user SET quota_bytes = ?1 WHERE id = ?2", + params![quota_bytes as i64, user_id], + ) + .await + .map_err(backend)?; + if n == 0 { + return Err(StoreError::NotFound); + } + drop(conn); + self.announce([Topic::Admin(user_id.to_string())]); + Ok(()) + } + + async fn set_user_disabled(&self, user_id: &str, disabled: bool) -> Result<()> { + let conn = self.conn.lock().await; + let n = conn + .execute( + "UPDATE user SET disabled = ?1 WHERE id = ?2", + params![if disabled { 1 } else { 0 }, user_id], + ) + .await + .map_err(backend)?; + if n == 0 { + return Err(StoreError::NotFound); + } + drop(conn); + self.announce([Topic::Admin(user_id.to_string())]); + Ok(()) + } + + async fn create_folder( + &self, + owner_id: &str, + parent_id: Option<&str>, + name: &str, + ) -> Result { + let name = label_of(name); + // IMMEDIATE: the name check is read-then-write. Two concurrent + // creates of one name each read no sibling, each pass, and the pair + // leaves two folders with one name. + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + check_live_parent(&tx, owner_id, parent_id).await?; + if folder_name_taken(&tx, owner_id, parent_id, &name, None).await? { + return Err(StoreError::NameTaken); + } + let id = Ulid::new().to_string(); + let now = now_text()?; + tx.execute( + "INSERT INTO folder (id, owner_id, parent_id, name, created_at, deleted_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, NULL)", + params![id.clone(), owner_id, parent_id, name, now], + ) + .await + .map_err(|e| map_constraint(e, StoreError::NameTaken))?; + let mut rows = tx + .query( + &format!("SELECT {FOLDER_COLUMNS} FROM folder WHERE id = ?1"), + params![id], + ) + .await + .map_err(backend)?; + let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?; + let folder = folder_from(&row)?; + drop(rows); + tx.commit().await.map_err(backend)?; + self.announce([Topic::Library(owner_id.to_string())]); + Ok(folder) + } + + async fn folder(&self, id: &str) -> Result> { + let sql = format!("SELECT {FOLDER_COLUMNS} FROM folder WHERE id = ?1"); + match self.one_row(&sql, params![id]).await? { + Some(row) => Ok(Some(folder_from(&row)?)), + None => Ok(None), + } + } + + async fn rename_folder(&self, id: &str, name: &str) -> Result<()> { + let name = label_of(name); + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + let folder = folder_row(&tx, id).await?.ok_or(StoreError::NotFound)?; + if folder.deleted_at.is_some() { + return Err(StoreError::NotFound); + } + if folder_name_taken(&tx, &folder.owner_id, folder.parent_id.as_deref(), &name, Some(id)) + .await? + { + return Err(StoreError::NameTaken); + } + tx.execute("UPDATE folder SET name = ?1 WHERE id = ?2", params![name, id]) + .await + .map_err(|e| map_constraint(e, StoreError::NameTaken))?; + refresh_usage(&tx, &folder.owner_id).await?; + tx.commit().await.map_err(backend)?; + self.announce([Topic::Library(folder.owner_id)]); + Ok(()) + } + + async fn move_folder(&self, id: &str, parent_id: Option<&str>) -> Result<()> { + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + let folder = folder_row(&tx, id).await?.ok_or(StoreError::NotFound)?; + if folder.deleted_at.is_some() { + return Err(StoreError::NotFound); + } + // The destination is vetted before the cycle walk: a stranger's, a + // missing, or a trashed folder refuses before ancestry is even asked. + check_live_parent(&tx, &folder.owner_id, parent_id).await?; + // The cycle walk: the destination's ancestry must not contain the + // folder being moved. Moving onto itself is the one-step circle. + let mut cursor = parent_id.map(str::to_string); + while let Some(current) = cursor { + if current == id { + return Err(StoreError::Cycle); + } + cursor = parent_of(&tx, ¤t).await?; + } + if folder_name_taken(&tx, &folder.owner_id, parent_id, &folder.name, Some(id)).await? { + return Err(StoreError::NameTaken); + } + tx.execute( + "UPDATE folder SET parent_id = ?1 WHERE id = ?2", + params![parent_id, id], + ) + .await + .map_err(|e| map_constraint(e, StoreError::NameTaken))?; + refresh_usage(&tx, &folder.owner_id).await?; + tx.commit().await.map_err(backend)?; + self.announce([Topic::Library(folder.owner_id)]); + Ok(()) + } + + async fn delete_folder(&self, id: &str) -> Result<()> { + let owner = { + let folder = self.folder(id).await?.ok_or(StoreError::NotFound)?; + if folder.deleted_at.is_some() { + return Ok(()); + } + folder.owner_id.clone() + }; + let now = now_text()?; + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + // One timestamp for the whole subtree: the trash lists one moment, + // and the purge takes it in one pass. Rows already trashed keep + // their own earlier moment — a file trashed on its own before the + // folder must still wear its own timestamp after, so a later + // restore of the folder can tell the cascade apart from it. + tx.execute( + "WITH RECURSIVE sub(id) AS ( \ + SELECT ?1 \ + UNION ALL \ + SELECT f.id FROM folder f JOIN sub s ON f.parent_id = s.id \ + ) \ + UPDATE folder SET deleted_at = ?2 WHERE owner_id = ?3 AND deleted_at IS NULL \ + AND id IN (SELECT id FROM sub)", + params![id, now.as_str(), owner.as_str()], + ) + .await + .map_err(backend)?; + tx.execute( + "WITH RECURSIVE sub(id) AS ( \ + SELECT ?1 \ + UNION ALL \ + SELECT f.id FROM folder f JOIN sub s ON f.parent_id = s.id \ + ) \ + UPDATE file SET deleted_at = ?2, updated_at = ?2 \ + WHERE owner_id = ?3 AND deleted_at IS NULL AND folder_id IN (SELECT id FROM sub)", + params![id, now.as_str(), owner.as_str()], + ) + .await + .map_err(backend)?; + refresh_usage(&tx, &owner).await?; + tx.commit().await.map_err(backend)?; + self.announce([Topic::Library(owner.clone()), Topic::Trash(owner)]); + Ok(()) + } + + async fn list_children( + &self, + owner_id: &str, + parent_id: Option<&str>, + ) -> Result { + let conn = self.conn.lock().await; + let mut folders = Vec::new(); + let mut files = Vec::new(); + match parent_id { + Some(parent) => { + let mut rows = conn + .query( + &format!( + "SELECT {FOLDER_COLUMNS} FROM folder \ + WHERE owner_id = ?1 AND parent_id = ?2 AND deleted_at IS NULL \ + ORDER BY name, id" + ), + params![owner_id, parent], + ) + .await + .map_err(backend)?; + while let Some(row) = rows.next().await.map_err(backend)? { + folders.push(folder_from(&row)?); + } + let mut rows = conn + .query( + &format!( + "SELECT {FILE_COLUMNS} FROM file \ + WHERE owner_id = ?1 AND folder_id = ?2 AND deleted_at IS NULL \ + ORDER BY name, id" + ), + params![owner_id, parent], + ) + .await + .map_err(backend)?; + while let Some(row) = rows.next().await.map_err(backend)? { + files.push(file_from(&row)?); + } + } + None => { + let mut rows = conn + .query( + &format!( + "SELECT {FOLDER_COLUMNS} FROM folder \ + WHERE owner_id = ?1 AND parent_id IS NULL AND deleted_at IS NULL \ + ORDER BY name, id" + ), + params![owner_id], + ) + .await + .map_err(backend)?; + while let Some(row) = rows.next().await.map_err(backend)? { + folders.push(folder_from(&row)?); + } + let mut rows = conn + .query( + &format!( + "SELECT {FILE_COLUMNS} FROM file \ + WHERE owner_id = ?1 AND folder_id IS NULL AND deleted_at IS NULL \ + ORDER BY name, id" + ), + params![owner_id], + ) + .await + .map_err(backend)?; + while let Some(row) = rows.next().await.map_err(backend)? { + files.push(file_from(&row)?); + } + } + } + Ok(Listing { folders, files }) + } + async fn insert_file( + &self, + owner_id: &str, + folder_id: Option<&str>, + name: &str, + bytes: &[u8], + ) -> Result { + let name = label_of(name); + let size = bytes.len() as u64; + // IMMEDIATE: the quota read, the name check and the row write are one + // write set. Two concurrent uploads each read room for themselves and + // the pair lands over quota. + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + check_live_parent(&tx, owner_id, folder_id).await?; + let (quota, used) = check_quota(&tx, owner_id).await?; + fit_quota(quota, used, size)?; + if file_name_taken(&tx, owner_id, folder_id, &name, None).await? { + return Err(StoreError::NameTaken); + } + let mime = sniff::sniff(bytes).to_string(); + let (thumb_state, thumb_bytes) = thumb_for(&mime, size, Some(bytes)); + // The bytes land first, temp-plus-rename, then the row says they are + // there: a crash in between leaves an orphan file the boot sweep + // deletes, never a row pointing at nothing. + let id = Ulid::new().to_string(); + let path = file_path(&self.storage, &id); + write_file_atomic(&path, bytes).map_err(|e| StoreError::Backend(e.to_string()))?; + if let Some(thumb) = thumb_bytes.as_ref() { + if write_file_atomic(&thumb_path(&self.storage, &id), thumb).is_err() { + // A thumbnail that cannot be written is a miss, not a failed + // upload: the file is what matters, and the row says so. + let _ = std::fs::remove_file(thumb_path(&self.storage, &id)); + } + } + let stored_thumb = if thumb_bytes.is_some() + && thumb_path(&self.storage, &id).is_file() + { + ThumbState::Ready + } else if thumb_state == ThumbState::Ready { + ThumbState::Failed + } else { + thumb_state + }; + let now = now_text()?; + let written = tx + .execute( + "INSERT INTO file (id, owner_id, folder_id, name, mime, size_bytes, \ + thumb_state, created_at, updated_at, deleted_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?8, NULL)", + params![ + id.clone(), + owner_id, + folder_id, + name, + mime, + size as i64, + stored_thumb.as_str(), + now + ], + ) + .await; + if let Err(e) = written { + // The row was never born, so the bytes must not outlive it under + // a name nothing points at. + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(thumb_path(&self.storage, &id)); + return Err(map_constraint(e, StoreError::NameTaken)); + } + refresh_usage(&tx, owner_id).await?; + let mut rows = tx + .query( + &format!("SELECT {FILE_COLUMNS} FROM file WHERE id = ?1"), + params![id], + ) + .await + .map_err(backend)?; + let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?; + let file = file_from(&row)?; + drop(rows); + tx.commit().await.map_err(backend)?; + self.announce([Topic::Library(owner_id.to_string())]); + Ok(file) + } + + async fn file(&self, id: &str) -> Result> { + let sql = format!("SELECT {FILE_COLUMNS} FROM file WHERE id = ?1"); + match self.one_row(&sql, params![id]).await? { + Some(row) => Ok(Some(file_from(&row)?)), + None => Ok(None), + } + } + + async fn rename_file(&self, id: &str, name: &str) -> Result<()> { + let name = label_of(name); + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + let file = file_row(&tx, id).await?.ok_or(StoreError::NotFound)?; + if file.deleted_at.is_some() { + return Err(StoreError::NotFound); + } + if file_name_taken(&tx, &file.owner_id, file.folder_id.as_deref(), &name, Some(id)).await? + { + return Err(StoreError::NameTaken); + } + let now = now_text()?; + tx.execute( + "UPDATE file SET name = ?1, updated_at = ?2 WHERE id = ?3", + params![name, now, id], + ) + .await + .map_err(|e| map_constraint(e, StoreError::NameTaken))?; + refresh_usage(&tx, &file.owner_id).await?; + tx.commit().await.map_err(backend)?; + self.announce([Topic::Library(file.owner_id)]); + Ok(()) + } + + async fn move_file(&self, id: &str, folder_id: Option<&str>) -> Result<()> { + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + let file = file_row(&tx, id).await?.ok_or(StoreError::NotFound)?; + if file.deleted_at.is_some() { + return Err(StoreError::NotFound); + } + check_live_parent(&tx, &file.owner_id, folder_id).await?; + if file_name_taken(&tx, &file.owner_id, folder_id, &file.name, Some(id)).await? { + return Err(StoreError::NameTaken); + } + let now = now_text()?; + tx.execute( + "UPDATE file SET folder_id = ?1, updated_at = ?2 WHERE id = ?3", + params![folder_id, now, id], + ) + .await + .map_err(|e| map_constraint(e, StoreError::NameTaken))?; + refresh_usage(&tx, &file.owner_id).await?; + tx.commit().await.map_err(backend)?; + self.announce([Topic::Library(file.owner_id)]); + Ok(()) + } + + async fn delete_file(&self, id: &str) -> Result<()> { + let owner = { + let file = self.file(id).await?.ok_or(StoreError::NotFound)?; + if file.deleted_at.is_some() { + return Ok(()); + } + file.owner_id.clone() + }; + let now = now_text()?; + let conn = self.conn.lock().await; + conn.execute( + "UPDATE file SET deleted_at = ?1, updated_at = ?1 WHERE id = ?2", + params![now, id], + ) + .await + .map_err(backend)?; + refresh_usage(&conn, &owner).await?; + drop(conn); + self.announce([Topic::Library(owner.clone()), Topic::Trash(owner)]); + Ok(()) + } + + async fn file_bytes(&self, id: &str) -> Result>> { + let conn = self.conn.lock().await; + let mut rows = conn + .query("SELECT 1 FROM file WHERE id = ?1", params![id]) + .await + .map_err(backend)?; + let known = rows.next().await.map_err(backend)?.is_some(); + drop(conn); + if !known { + return Ok(None); + } + match std::fs::read(file_path(&self.storage, id)) { + Ok(bytes) => Ok(Some(bytes)), + // A row whose file went missing is reported at boot; the read + // answers "nothing to serve" rather than failing the panel. + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(StoreError::Backend(e.to_string())), + } + } + + async fn thumb_bytes(&self, id: &str) -> Result>> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT thumb_state FROM file WHERE id = ?1", + params![id], + ) + .await + .map_err(backend)?; + let ready = match rows.next().await.map_err(backend)? { + Some(row) => text(&row, 0)? == ThumbState::Ready.as_str(), + None => return Ok(None), + }; + drop(conn); + if !ready { + return Ok(None); + } + match std::fs::read(thumb_path(&self.storage, id)) { + Ok(bytes) => Ok(Some(bytes)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(StoreError::Backend(e.to_string())), + } + } + async fn list_trash(&self, owner_id: &str) -> Result { + let conn = self.conn.lock().await; + let mut folders = Vec::new(); + let mut files = Vec::new(); + let mut rows = conn + .query( + &format!( + "SELECT {FOLDER_COLUMNS} FROM folder \ + WHERE owner_id = ?1 AND deleted_at IS NOT NULL \ + ORDER BY deleted_at DESC, id" + ), + params![owner_id], + ) + .await + .map_err(backend)?; + while let Some(row) = rows.next().await.map_err(backend)? { + folders.push(folder_from(&row)?); + } + let mut rows = conn + .query( + &format!( + "SELECT {FILE_COLUMNS} FROM file \ + WHERE owner_id = ?1 AND deleted_at IS NOT NULL \ + ORDER BY deleted_at DESC, id" + ), + params![owner_id], + ) + .await + .map_err(backend)?; + while let Some(row) = rows.next().await.map_err(backend)? { + files.push(file_from(&row)?); + } + Ok(Listing { folders, files }) + } + + async fn restore_file(&self, id: &str) -> Result<()> { + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + let file = file_row(&tx, id).await?.ok_or(StoreError::NotFound)?; + if file.deleted_at.is_none() { + return Ok(()); + } + // A file restored under trash would be trashed the moment it + // arrives: every ancestor folder must be live first. + if let Some(folder_id) = file.folder_id.as_deref() { + ancestor_trashed(&tx, folder_id).await?; + } + if file_name_taken( + &tx, + &file.owner_id, + file.folder_id.as_deref(), + &file.name, + Some(id), + ) + .await? + { + return Err(StoreError::NameTaken); + } + let now = now_text()?; + tx.execute( + "UPDATE file SET deleted_at = NULL, updated_at = ?1 WHERE id = ?2", + params![now, id], + ) + .await + .map_err(|e| map_constraint(e, StoreError::NameTaken))?; + refresh_usage(&tx, &file.owner_id).await?; + tx.commit().await.map_err(backend)?; + self.announce([ + Topic::Library(file.owner_id.clone()), + Topic::Trash(file.owner_id), + ]); + Ok(()) + } + + async fn restore_folder(&self, id: &str) -> Result<()> { + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + let folder = folder_row(&tx, id).await?.ok_or(StoreError::NotFound)?; + let Some(trashed_at) = folder.deleted_at else { + return Ok(()); + }; + let trashed_at = stamp(trashed_at)?; + // Same refusal as the file: no resurrection into a trash that never + // left. Only the ancestors above the folder are asked — the subtree + // below comes back with it. + if let Some(parent_id) = folder.parent_id.as_deref() { + ancestor_trashed(&tx, parent_id).await?; + } + if folder_name_taken( + &tx, + &folder.owner_id, + folder.parent_id.as_deref(), + &folder.name, + Some(id), + ) + .await? + { + return Err(StoreError::NameTaken); + } + let now = now_text()?; + // Only the cascade comes back: descendants wear the folder's own + // trash timestamp when the folder took them with it, while anything + // trashed individually before keeps its earlier moment and stays + // trashed. + tx.execute( + "WITH RECURSIVE sub(id) AS ( \ + SELECT ?1 \ + UNION ALL \ + SELECT f.id FROM folder f JOIN sub s ON f.parent_id = s.id \ + ) \ + UPDATE folder SET deleted_at = NULL \ + WHERE id IN (SELECT id FROM sub) AND deleted_at = ?2", + params![id, trashed_at.clone()], + ) + .await + .map_err(backend)?; + tx.execute( + "WITH RECURSIVE sub(id) AS ( \ + SELECT ?1 \ + UNION ALL \ + SELECT f.id FROM folder f JOIN sub s ON f.parent_id = s.id \ + ) \ + UPDATE file SET deleted_at = NULL, updated_at = ?2 \ + WHERE folder_id IN (SELECT id FROM sub) AND deleted_at = ?3", + params![id, now, trashed_at], + ) + .await + .map_err(backend)?; + refresh_usage(&tx, &folder.owner_id).await?; + tx.commit().await.map_err(backend)?; + self.announce([ + Topic::Library(folder.owner_id.clone()), + Topic::Trash(folder.owner_id), + ]); + Ok(()) + } + + async fn purge_file(&self, id: &str) -> Result { + let owner = { + let file = self.file(id).await?.ok_or(StoreError::NotFound)?; + // A live file is never purged — trash it first. This answers + // `false` rather than failing, because the purge's contract is + // "take the trash", and a live file is not trash. + if file.deleted_at.is_none() { + return Ok(false); + } + file.owner_id.clone() + }; + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + delete_file_rows(&tx, &[id.to_string()]).await?; + refresh_usage(&tx, &owner).await?; + tx.commit().await.map_err(backend)?; + // After the delete: the bytes may only follow a delete that + // committed, or a crash in between would leave a row whose file is + // gone. Best-effort — a file that survives is orphaned bytes the + // boot sweep collects. + let _ = std::fs::remove_file(file_path(&self.storage, id)); + let _ = std::fs::remove_file(thumb_path(&self.storage, id)); + self.announce([Topic::Library(owner.clone()), Topic::Trash(owner)]); + Ok(true) + } + + async fn purge_folder(&self, id: &str) -> Result { + let folder = self.folder(id).await?.ok_or(StoreError::NotFound)?; + // A live folder is never purged — trash it first. + if folder.deleted_at.is_none() { + return Err(StoreError::NotFound); + } + let owner = folder.owner_id.clone(); + let conn = self.conn.lock().await; + // The trashed subtree: the folder itself and every trashed folder + // under it. A live row under trash cannot exist — nothing is created + // or moved under a trashed folder, and restores cascade — so the + // trashed set is the whole subtree; the foreign key would say so + // loudly if that ever stopped being true. + let mut folder_rows = Vec::new(); + let mut rows = conn + .query( + "WITH RECURSIVE sub(id) AS ( \ + SELECT ?1 \ + UNION ALL \ + SELECT f.id FROM folder f JOIN sub s ON f.parent_id = s.id \ + ) \ + SELECT id, parent_id FROM folder WHERE owner_id = ?2 AND id IN (SELECT id FROM sub) AND deleted_at IS NOT NULL", + params![id, owner.as_str()], + ) + .await + .map_err(backend)?; + while let Some(row) = rows.next().await.map_err(backend)? { + folder_rows.push((text(&row, 0)?, opt_text(&row, 1)?)); + } + drop(rows); + let mut file_ids = Vec::new(); + let mut rows = conn + .query( + "WITH RECURSIVE sub(id) AS ( \ + SELECT ?1 \ + UNION ALL \ + SELECT f.id FROM folder f JOIN sub s ON f.parent_id = s.id \ + ) \ + SELECT id FROM file WHERE owner_id = ?2 AND folder_id IN (SELECT id FROM sub) AND deleted_at IS NOT NULL", + params![id, owner.as_str()], + ) + .await + .map_err(backend)?; + while let Some(row) = rows.next().await.map_err(backend)? { + file_ids.push(text(&row, 0)?); + } + drop(rows); + drop(conn); + let folder_ids = order_deepest_first(&folder_rows); + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + delete_file_rows(&tx, &file_ids).await?; + delete_folder_rows(&tx, &folder_ids).await?; + refresh_usage(&tx, &owner).await?; + tx.commit().await.map_err(backend)?; + // After the delete: bytes may only follow a delete that committed. + // Best-effort — survivors are orphaned bytes the boot sweep collects. + for file_id in &file_ids { + let _ = std::fs::remove_file(file_path(&self.storage, file_id)); + let _ = std::fs::remove_file(thumb_path(&self.storage, file_id)); + } + let purged = (file_ids.len() + folder_ids.len()) as u64; + self.announce([Topic::Library(owner.clone()), Topic::Trash(owner)]); + Ok(purged) + } + + async fn purge_expired(&self, before: OffsetDateTime) -> Result { + let before = stamp(before)?; + let conn = self.conn.lock().await; + let mut file_ids = Vec::new(); + let mut rows = conn + .query( + "SELECT id, owner_id FROM file WHERE deleted_at IS NOT NULL AND deleted_at < ?1", + params![before.as_str()], + ) + .await + .map_err(backend)?; + while let Some(row) = rows.next().await.map_err(backend)? { + file_ids.push((text(&row, 0)?, text(&row, 1)?)); + } + let mut folder_rows = Vec::new(); + let mut rows = conn + .query( + "SELECT id, owner_id, parent_id FROM folder \ + WHERE deleted_at IS NOT NULL AND deleted_at < ?1", + params![before], + ) + .await + .map_err(backend)?; + while let Some(row) = rows.next().await.map_err(backend)? { + folder_rows.push((text(&row, 0)?, text(&row, 1)?, opt_text(&row, 2)?)); + } + drop(conn); + if file_ids.is_empty() && folder_rows.is_empty() { + return Ok(0); + } + // Folders deepest first: a parent row cannot go while a child row + // still names it. + let folder_ids = order_deepest_first( + &folder_rows + .iter() + .map(|(id, _, parent)| (id.clone(), parent.clone())) + .collect::>(), + ); + let owners = { + let mut owners: Vec = file_ids.iter().map(|(_, o)| o.clone()).collect(); + owners.extend(folder_rows.iter().map(|(_, o, _)| o.clone())); + owners.sort(); + owners.dedup(); + owners + }; + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + delete_file_rows( + &tx, + &file_ids.iter().map(|(id, _)| id.clone()).collect::>(), + ) + .await?; + delete_folder_rows(&tx, &folder_ids).await?; + for owner in &owners { + refresh_usage(&tx, owner).await?; + } + tx.commit().await.map_err(backend)?; + for (id, _) in &file_ids { + let _ = std::fs::remove_file(file_path(&self.storage, id)); + let _ = std::fs::remove_file(thumb_path(&self.storage, id)); + } + let purged = (file_ids.len() + folder_ids.len()) as u64; + for owner in owners { + self.announce([Topic::Library(owner.clone()), Topic::Trash(owner)]); + } + Ok(purged) + } + + async fn empty_trash(&self, owner_id: &str) -> Result { + let conn = self.conn.lock().await; + let mut file_ids = Vec::new(); + let mut rows = conn + .query( + "SELECT id FROM file WHERE owner_id = ?1 AND deleted_at IS NOT NULL", + params![owner_id], + ) + .await + .map_err(backend)?; + while let Some(row) = rows.next().await.map_err(backend)? { + file_ids.push(text(&row, 0)?); + } + let mut folder_rows = Vec::new(); + let mut rows = conn + .query( + "SELECT id, parent_id FROM folder WHERE owner_id = ?1 AND deleted_at IS NOT NULL", + params![owner_id], + ) + .await + .map_err(backend)?; + while let Some(row) = rows.next().await.map_err(backend)? { + folder_rows.push((text(&row, 0)?, opt_text(&row, 1)?)); + } + drop(conn); + if file_ids.is_empty() && folder_rows.is_empty() { + return Ok(0); + } + let folder_ids = order_deepest_first(&folder_rows); + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + delete_file_rows(&tx, &file_ids).await?; + delete_folder_rows(&tx, &folder_ids).await?; + refresh_usage(&tx, owner_id).await?; + tx.commit().await.map_err(backend)?; + for id in &file_ids { + let _ = std::fs::remove_file(file_path(&self.storage, id)); + let _ = std::fs::remove_file(thumb_path(&self.storage, id)); + } + let purged = (file_ids.len() + folder_ids.len()) as u64; + self.announce([ + Topic::Library(owner_id.to_string()), + Topic::Trash(owner_id.to_string()), + ]); + Ok(purged) + } + async fn create_share_link( + &self, + created_by: &str, + kind: ShareKind, + target_id: &str, + can_download: bool, + expires_at: Option, + ) -> Result { + // The sharer must own a live target: a stranger's, a missing, or a + // trashed target refuses before any token exists to leak. + match target_owner(&self.conn, kind, target_id).await? { + Some(owner) if owner == created_by => {} + Some(_) => return Err(StoreError::CrossOwner), + None => return Err(StoreError::NotFound), + } + let token = new_token(); + let token_hash = hash_share_token(&token); + let id = Ulid::new().to_string(); + let now = now_text()?; + let expires = expires_at.map(stamp).transpose()?; + let conn = self.conn.lock().await; + conn.execute( + "INSERT INTO share_link (id, token_hash, kind, target_id, created_by, \ + can_download, created_at, expires_at, revoked_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, NULL)", + params![ + id.clone(), + token_hash, + kind.as_str(), + target_id, + created_by, + if can_download { 1 } else { 0 }, + now, + expires + ], + ) + .await + .map_err(backend)?; + let mut rows = conn + .query( + &format!("SELECT {LINK_COLUMNS} FROM share_link WHERE id = ?1"), + params![id], + ) + .await + .map_err(backend)?; + let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?; + let link = link_from(&row)?; + drop(rows); + drop(conn); + self.announce([Topic::Shares(created_by.to_string())]); + Ok(CreatedLink { link, token }) + } + + async fn revoke_share_link(&self, id: &str) -> Result<()> { + let created_by = { + let row = self + .one_row( + &format!("SELECT {LINK_COLUMNS} FROM share_link WHERE id = ?1"), + params![id], + ) + .await?; + match row { + Some(row) => link_from(&row)?.created_by.clone(), + None => return Err(StoreError::NotFound), + } + }; + let conn = self.conn.lock().await; + conn.execute( + "UPDATE share_link SET revoked_at = COALESCE(revoked_at, ?1) WHERE id = ?2", + params![now_text()?, id], + ) + .await + .map_err(backend)?; + drop(conn); + self.announce([Topic::Shares(created_by)]); + Ok(()) + } + + async fn share_links(&self, owner_id: &str) -> Result> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + &format!( + "SELECT {LINK_COLUMNS} FROM share_link \ + WHERE created_by = ?1 ORDER BY created_at DESC, id" + ), + params![owner_id], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(link_from(&row)?); + } + Ok(out) + } + + async fn resolve_share_link( + &self, + token_hash: &str, + now: OffsetDateTime, + ) -> Result> { + let sql = format!("SELECT {LINK_COLUMNS} FROM share_link WHERE token_hash = ?1"); + match self.one_row(&sql, params![token_hash]).await? { + Some(row) => { + let link = link_from(&row)?; + // A dead link and a wrong token both answer `None`: telling a + // stranger which tokens exist is the leak the distinction + // would be. + if link.is_live(now) { + Ok(Some(link)) + } else { + Ok(None) + } + } + None => Ok(None), + } + } + + async fn add_share_user( + &self, + caller_id: &str, + kind: ShareKind, + target_id: &str, + user_id: &str, + can_download: bool, + ) -> Result<()> { + // The caller must own a live target — the same rule as + // create_share_link: a stranger's, a missing, or a trashed target + // refuses before any grant names it. The grantee must exist, or the + // row would point at nobody. + let owner = match target_owner(&self.conn, kind, target_id).await? { + Some(owner) if owner == caller_id => owner, + Some(_) => return Err(StoreError::CrossOwner), + None => return Err(StoreError::NotFound), + }; + if self.user(user_id).await?.is_none() { + return Err(StoreError::NotFound); + } + if owner == user_id { + // Sharing with the owner is a no-op with a success answer: the + // owner already sees everything. + return Ok(()); + } + let conn = self.conn.lock().await; + conn.execute( + "INSERT INTO share_user (kind, target_id, user_id, can_download, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5) \ + ON CONFLICT (kind, target_id, user_id) \ + DO UPDATE SET can_download = excluded.can_download", + params![ + kind.as_str(), + target_id, + user_id, + if can_download { 1 } else { 0 }, + now_text()? + ], + ) + .await + .map_err(backend)?; + drop(conn); + self.announce([ + Topic::Shares(owner), + Topic::Shares(user_id.to_string()), + ]); + Ok(()) + } + + async fn remove_share_user( + &self, + kind: ShareKind, + target_id: &str, + user_id: &str, + ) -> Result<()> { + // The owner is read before the delete: after it there may be nothing + // left to announce to. Trash does not stop an unshare — the grant is + // gone either way, and the owner is still listening. + let owner = row_owner(&self.conn, kind, target_id) + .await? + .ok_or(StoreError::NotFound)?; + let conn = self.conn.lock().await; + conn.execute( + "DELETE FROM share_user WHERE kind = ?1 AND target_id = ?2 AND user_id = ?3", + params![kind.as_str(), target_id, user_id], + ) + .await + .map_err(backend)?; + drop(conn); + self.announce([ + Topic::Shares(owner), + Topic::Shares(user_id.to_string()), + ]); + Ok(()) + } + + async fn shares_for_user(&self, user_id: &str) -> Result> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT kind, target_id, can_download, created_at FROM share_user \ + WHERE user_id = ?1 ORDER BY created_at DESC", + params![user_id], + ) + .await + .map_err(backend)?; + let mut grants = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + grants.push(( + ShareKind::parse(&text(&row, 0)?)?, + text(&row, 1)?, + row.get::(2).map_err(backend)? != 0, + parse_stamp(&text(&row, 3)?)?, + )); + } + drop(rows); + // Targets that went missing or were trashed since the grant fall out + // silently: the grant row stays (the owner may restore the target), + // but the listing shows only what opens today. + let mut out = Vec::new(); + for (kind, target_id, can_download, created_at) in grants { + let (name, mime, owner_id) = match kind { + ShareKind::File => { + let mut rows = conn + .query( + "SELECT name, mime, owner_id FROM file \ + WHERE id = ?1 AND deleted_at IS NULL", + params![target_id.as_str()], + ) + .await + .map_err(backend)?; + match rows.next().await.map_err(backend)? { + Some(row) => (text(&row, 0)?, Some(text(&row, 1)?), text(&row, 2)?), + None => continue, + } + } + ShareKind::Folder => { + let mut rows = conn + .query( + "SELECT name, owner_id FROM folder \ + WHERE id = ?1 AND deleted_at IS NULL", + params![target_id.as_str()], + ) + .await + .map_err(backend)?; + match rows.next().await.map_err(backend)? { + Some(row) => (text(&row, 0)?, None, text(&row, 1)?), + None => continue, + } + } + }; + if owner_id == user_id { + continue; + } + out.push(SharedItem { + kind, + target_id, + name, + mime, + owner_id, + can_download, + created_at, + }); + } + Ok(out) + } + + async fn can_see(&self, kind: ShareKind, target_id: &str, user_id: &str) -> Result { + // Ownership survives the trash: the owner sees the row trashed or + // not. Anyone else needs a live grant onto the live target or a live + // folder above it — and a missing target is simply not seen, never + // distinguished. + match row_owner(&self.conn, kind, target_id).await? { + Some(owner) if owner == user_id => Ok(true), + Some(_) => { + if target_owner(&self.conn, kind, target_id).await?.is_none() { + return Ok(false); + } + let conn = self.conn.lock().await; + Ok(effective_grant(&conn, kind, target_id, user_id) + .await? + .is_some()) + } + None => Ok(false), + } + } + + async fn can_download( + &self, + kind: ShareKind, + target_id: &str, + user_id: &str, + ) -> Result { + // The owner always downloads. Anyone else downloads only through a + // grant whose `can_download` is set — on the target or above it. A + // view-only grant opens the page but not the bytes. + match row_owner(&self.conn, kind, target_id).await? { + Some(owner) if owner == user_id => Ok(true), + Some(_) => { + if target_owner(&self.conn, kind, target_id).await?.is_none() { + return Ok(false); + } + let conn = self.conn.lock().await; + Ok(effective_grant(&conn, kind, target_id, user_id) + .await? + .is_some_and(|granted| granted)) + } + None => Ok(false), + } + } + async fn create_upload_session( + &self, + owner_id: &str, + folder_id: Option<&str>, + name: &str, + size_bytes: u64, + ) -> Result { + let name = label_of(name); + // The quota is checked before anything exists on disk: refusing now + // leaves nothing to clean up, and the finish rechecks anyway for + // whatever filled up while the chunks were arriving. + let conn = self.conn.lock().await; + check_live_parent_on(&conn, owner_id, folder_id).await?; + let (quota, used) = check_quota(&conn, owner_id).await?; + fit_quota(quota, used, size_bytes)?; + let id = Ulid::new().to_string(); + let now = OffsetDateTime::now_utc(); + let created = stamp(now)?; + let expires = stamp(now + time::Duration::hours(UPLOAD_TTL_HOURS as i64))?; + conn.execute( + "INSERT INTO upload_session (id, owner_id, folder_id, name, size_bytes, \ + chunk_size, received_bytes, state, created_at, expires_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0, 'active', ?7, ?8)", + params![ + id.clone(), + owner_id, + folder_id, + name, + size_bytes as i64, + CHUNK_SIZE as i64, + created, + expires + ], + ) + .await + .map_err(backend)?; + let mut rows = conn + .query( + &format!("SELECT {SESSION_COLUMNS} FROM upload_session WHERE id = ?1"), + params![id.as_str()], + ) + .await + .map_err(backend)?; + let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?; + let session = session_from(&row)?; + drop(rows); + drop(conn); + std::fs::create_dir_all(session_dir(&self.storage, &id)) + .map_err(|e| StoreError::Backend(e.to_string()))?; + Ok(session) + } + + async fn upload_session(&self, id: &str) -> Result> { + let sql = format!("SELECT {SESSION_COLUMNS} FROM upload_session WHERE id = ?1"); + match self.one_row(&sql, params![id]).await? { + Some(row) => Ok(Some(session_from(&row)?)), + None => Ok(None), + } + } + + async fn record_chunk(&self, id: &str, index: u64, bytes: &[u8]) -> Result { + let session = self.upload_session(id).await?.ok_or(StoreError::NotFound)?; + if session.state != UploadState::Active || session.expires_at <= OffsetDateTime::now_utc() + { + return Err(StoreError::UploadExpired); + } + let count = chunk_count(session.size_bytes); + // Every refusal here is about shape, never about content: the bytes + // are opaque until the finish sniffs them. + if index >= count { + return Err(StoreError::BadChunk); + } + if bytes.len() as u64 != expected_chunk_len(session.size_bytes, index) { + return Err(StoreError::BadChunk); + } + let dir = session_dir(&self.storage, &id); + std::fs::create_dir_all(&dir).map_err(|e| StoreError::Backend(e.to_string()))?; + write_file_atomic(&chunk_path(&self.storage, &id, index), bytes) + .map_err(|e| StoreError::Backend(e.to_string()))?; + let received = staged_received(&self.storage, &id); + let conn = self.conn.lock().await; + conn.execute( + "UPDATE upload_session SET received_bytes = ?1 WHERE id = ?2", + params![received as i64, id], + ) + .await + .map_err(backend)?; + let mut rows = conn + .query( + &format!("SELECT {SESSION_COLUMNS} FROM upload_session WHERE id = ?1"), + params![id], + ) + .await + .map_err(backend)?; + let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?; + let session = session_from(&row)?; + drop(rows); + drop(conn); + Ok(session) + } + + async fn finish_upload(&self, id: &str) -> Result { + let session = self.upload_session(id).await?.ok_or(StoreError::NotFound)?; + if session.state != UploadState::Active || session.expires_at <= OffsetDateTime::now_utc() + { + return Err(StoreError::UploadExpired); + } + // Every chunk present, every chunk exact: the finish assembles what + // the session promised, byte for byte, or refuses with the chunks + // still staged for another attempt. + let count = chunk_count(session.size_bytes); + for index in 0..count { + let len = std::fs::metadata(chunk_path(&self.storage, &id, index)) + .map(|m| m.len()) + .unwrap_or(u64::MAX); + if len != expected_chunk_len(session.size_bytes, index) { + return Err(StoreError::BadChunk); + } + } + // Assemble through a temp name in the files directory: a crash + // mid-assemble leaves a temp the sweep deletes, never a half file + // wearing a real name. + let file_id = Ulid::new().to_string(); + let dest = file_path(&self.storage, &file_id); + let tmp = dest.with_extension(format!("{}.tmp", Ulid::new())); + { + use std::io::Write as _; + let mut out = + std::fs::File::create(&tmp).map_err(|e| StoreError::Backend(e.to_string()))?; + let mut total = 0u64; + for index in 0..count { + let mut chunk = std::fs::File::open(chunk_path(&self.storage, &id, index)) + .map_err(|e| StoreError::Backend(e.to_string()))?; + total += std::io::copy(&mut chunk, &mut out) + .map_err(|e| StoreError::Backend(e.to_string()))?; + } + out.flush().map_err(|e| StoreError::Backend(e.to_string()))?; + drop(out); + if total != session.size_bytes { + let _ = std::fs::remove_file(&tmp); + return Err(StoreError::BadChunk); + } + } + // The mime comes from the assembled bytes, never from anything the + // uploader said along the way. + let mut head = vec![0u8; 1024 * 1024]; + let head_len = read_up_to(&tmp, &mut head).map_err(|e| { + let _ = std::fs::remove_file(&tmp); + StoreError::Backend(e.to_string()) + })?; + head.truncate(head_len.min(session.size_bytes as usize)); + let mime = sniff::sniff(&head).to_string(); + let thumb_bytes = if !thumbs::thumbnailed(&mime) || session.size_bytes > THUMB_SOURCE_CAP + { + None + } else if thumbs::is_video_mime(&mime) { + // The assembled file is already on disk: frame it in place + // rather than reading it whole into memory first. + thumbs::thumbnail_for_video_file(&tmp) + } else { + match std::fs::read(&tmp) { + Ok(full) => thumbs::thumbnail_for_bytes(&full), + Err(_) => None, + } + }; + let thumb_state = if !thumbs::thumbnailed(&mime) { + ThumbState::None + } else if session.size_bytes > THUMB_SOURCE_CAP { + ThumbState::Failed + } else if thumb_bytes.is_some() { + ThumbState::Ready + } else if thumbs::is_video_mime(&mime) && !thumbs::ffmpeg_available() { + ThumbState::None + } else { + ThumbState::Failed + }; + // IMMEDIATE: the quota recheck, the name check and the row writes + // are one write set — the library may have filled while the chunks + // were arriving. Every check runs before the assembled bytes take + // their real name: a refusal leaves files/ untouched, with the + // chunks still staged for another attempt. + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + let vetted: Result<()> = async { + check_live_parent(&tx, &session.owner_id, session.folder_id.as_deref()).await?; + let (quota, used) = check_quota(&tx, &session.owner_id).await?; + fit_quota(quota, used, session.size_bytes)?; + if file_name_taken( + &tx, + &session.owner_id, + session.folder_id.as_deref(), + &session.name, + None, + ) + .await? + { + return Err(StoreError::NameTaken); + } + Ok(()) + } + .await; + if let Err(e) = vetted { + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + if std::fs::rename(&tmp, &dest).is_err() { + let _ = std::fs::remove_file(&tmp); + return Err(StoreError::Backend("could not place the assembled file".into())); + } + if let Some(thumb) = thumb_bytes.as_ref() { + if write_file_atomic(&thumb_path(&self.storage, &file_id), thumb).is_err() { + let _ = std::fs::remove_file(thumb_path(&self.storage, &file_id)); + } + } + let stored_thumb = + if thumb_state == ThumbState::Ready && thumb_path(&self.storage, &file_id).is_file() { + ThumbState::Ready + } else if thumb_state == ThumbState::Ready { + ThumbState::Failed + } else { + thumb_state + }; + let now = now_text()?; + let written = tx + .execute( + "INSERT INTO file (id, owner_id, folder_id, name, mime, size_bytes, \ + thumb_state, created_at, updated_at, deleted_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?8, NULL)", + params![ + file_id.clone(), + session.owner_id.as_str(), + session.folder_id.as_deref(), + session.name.as_str(), + mime, + session.size_bytes as i64, + stored_thumb.as_str(), + now + ], + ) + .await; + if let Err(e) = written { + // The row was never born: the assembled bytes must not outlive + // it, but the chunks stay staged — the attempt, not the upload, + // is what failed. + let _ = std::fs::remove_file(&dest); + let _ = std::fs::remove_file(thumb_path(&self.storage, &file_id)); + return Err(map_constraint(e, StoreError::NameTaken)); + } + tx.execute( + "UPDATE upload_session SET state = 'done', received_bytes = ?1 WHERE id = ?2", + params![session.size_bytes as i64, id], + ) + .await + .map_err(backend)?; + refresh_usage(&tx, &session.owner_id).await?; + let mut rows = tx + .query( + &format!("SELECT {FILE_COLUMNS} FROM file WHERE id = ?1"), + params![file_id], + ) + .await + .map_err(backend)?; + let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?; + let file = file_from(&row)?; + drop(rows); + tx.commit().await.map_err(backend)?; + // After the commit: the chunks served their purpose. + let _ = std::fs::remove_dir_all(session_dir(&self.storage, &id)); + self.announce([Topic::Library(session.owner_id)]); + Ok(file) + } + + async fn abort_upload(&self, id: &str) -> Result<()> { + let conn = self.conn.lock().await; + conn.execute( + "UPDATE upload_session SET state = 'aborted' WHERE id = ?1 AND state = 'active'", + params![id], + ) + .await + .map_err(backend)?; + drop(conn); + let _ = std::fs::remove_dir_all(session_dir(&self.storage, &id)); + Ok(()) + } + + async fn prune_expired_uploads(&self, now: OffsetDateTime) -> Result { + let now = stamp(now)?; + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT id FROM upload_session WHERE state = 'active' AND expires_at <= ?1", + params![now], + ) + .await + .map_err(backend)?; + let mut ids = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + ids.push(text(&row, 0)?); + } + drop(rows); + for id in &ids { + conn.execute( + "UPDATE upload_session SET state = 'aborted' WHERE id = ?1", + params![id.as_str()], + ) + .await + .map_err(backend)?; + } + drop(conn); + for id in &ids { + let _ = std::fs::remove_dir_all(session_dir(&self.storage, &id)); + } + Ok(ids.len() as u64) + } + + async fn search(&self, owner_id: &str, query: &str, limit: u32) -> Result { + // An empty query matches everything under LIKE `%%`; the route keeps + // that from ever arriving, and the store answers it with nothing + // rather than the whole library. + if query.trim().is_empty() { + return Ok(Listing { + folders: Vec::new(), + files: Vec::new(), + }); + } + let pattern = like_pattern(query.trim()); + let limit = limit.clamp(1, 100) as i64; + let conn = self.conn.lock().await; + let mut folders = Vec::new(); + let mut rows = conn + .query( + &format!( + "SELECT {FOLDER_COLUMNS} FROM folder \ + WHERE owner_id = ?1 AND deleted_at IS NULL AND name LIKE ?2 ESCAPE '\\' \ + ORDER BY name, id LIMIT ?3" + ), + params![owner_id, pattern.as_str(), limit], + ) + .await + .map_err(backend)?; + while let Some(row) = rows.next().await.map_err(backend)? { + folders.push(folder_from(&row)?); + } + let mut files = Vec::new(); + let mut rows = conn + .query( + &format!( + "SELECT {FILE_COLUMNS} FROM file \ + WHERE owner_id = ?1 AND deleted_at IS NULL AND name LIKE ?2 ESCAPE '\\' \ + ORDER BY name, id LIMIT ?3" + ), + params![owner_id, pattern, limit], + ) + .await + .map_err(backend)?; + while let Some(row) = rows.next().await.map_err(backend)? { + files.push(file_from(&row)?); + } + Ok(Listing { folders, files }) + } +} // impl Store for TursoStore + +/// One folder row for a write to vet: locks nothing itself, runs on the +/// caller's connection — plain or transactional. +async fn folder_row(conn: &Connection, id: &str) -> Result> { + let mut rows = conn + .query( + &format!("SELECT {FOLDER_COLUMNS} FROM folder WHERE id = ?1"), + params![id], + ) + .await + .map_err(backend)?; + match rows.next().await.map_err(backend)? { + Some(row) => Ok(Some(folder_from(&row)?)), + None => Ok(None), + } +} + +/// One file row for a write to vet, same shape as [`folder_row`]. +async fn file_row(conn: &Connection, id: &str) -> Result> { + let mut rows = conn + .query( + &format!("SELECT {FILE_COLUMNS} FROM file WHERE id = ?1"), + params![id], + ) + .await + .map_err(backend)?; + match rows.next().await.map_err(backend)? { + Some(row) => Ok(Some(file_from(&row)?)), + None => Ok(None), + } +} + +/// The parent of one folder, for the cycle and ancestor walks. +async fn parent_of(conn: &Connection, id: &str) -> Result> { + let mut rows = conn + .query("SELECT parent_id FROM folder WHERE id = ?1", params![id]) + .await + .map_err(backend)?; + match rows.next().await.map_err(backend)? { + Some(row) => Ok(opt_text(&row, 0)?), + None => Ok(None), + } +} + +/// Vets a destination folder: missing is [`StoreError::NotFound`], another +/// owner's is [`StoreError::CrossOwner`], trashed is `NotFound` — trash is +/// invisible to writes that are not restore, purge or empty. +async fn check_live_parent( + conn: &Connection, + owner_id: &str, + parent_id: Option<&str>, +) -> Result<()> { + let Some(parent_id) = parent_id else { + return Ok(()); + }; + match folder_row(conn, parent_id).await? { + None => Err(StoreError::NotFound), + Some(folder) if folder.owner_id != owner_id => Err(StoreError::CrossOwner), + Some(folder) if folder.deleted_at.is_some() => Err(StoreError::NotFound), + Some(_) => Ok(()), + } +} + +/// [`check_live_parent`] on the shared connection, for the single-statement +/// writes that take no transaction of their own. +async fn check_live_parent_on( + conn: &tokio::sync::MutexGuard<'_, Connection>, + owner_id: &str, + parent_id: Option<&str>, +) -> Result<()> { + check_live_parent(conn, owner_id, parent_id).await +} + +/// Whether a live sibling folder already wears `name`. Trashed rows do not +/// count — deleting a name frees it — and `exclude` skips the row being +/// renamed or moved. +async fn folder_name_taken( + conn: &Connection, + owner_id: &str, + parent_id: Option<&str>, + name: &str, + exclude: Option<&str>, +) -> Result { + let exclude = exclude.unwrap_or(""); + let mut rows = match parent_id { + Some(parent) => { + conn.query( + "SELECT 1 FROM folder WHERE owner_id = ?1 AND parent_id = ?2 \ + AND name = ?3 AND deleted_at IS NULL AND id <> ?4", + params![owner_id, parent, name, exclude], + ) + .await + .map_err(backend)? + } + None => { + conn.query( + "SELECT 1 FROM folder WHERE owner_id = ?1 AND parent_id IS NULL \ + AND name = ?2 AND deleted_at IS NULL AND id <> ?3", + params![owner_id, name, exclude], + ) + .await + .map_err(backend)? + } + }; + Ok(rows.next().await.map_err(backend)?.is_some()) +} + +/// Whether a live sibling file already wears `name`, same rules as +/// [`folder_name_taken`]. Folders and files keep separate namespaces: a +/// folder and a file may share a name in one directory. +async fn file_name_taken( + conn: &Connection, + owner_id: &str, + folder_id: Option<&str>, + name: &str, + exclude: Option<&str>, +) -> Result { + let exclude = exclude.unwrap_or(""); + let mut rows = match folder_id { + Some(folder) => { + conn.query( + "SELECT 1 FROM file WHERE owner_id = ?1 AND folder_id = ?2 \ + AND name = ?3 AND deleted_at IS NULL AND id <> ?4", + params![owner_id, folder, name, exclude], + ) + .await + .map_err(backend)? + } + None => { + conn.query( + "SELECT 1 FROM file WHERE owner_id = ?1 AND folder_id IS NULL \ + AND name = ?2 AND deleted_at IS NULL AND id <> ?3", + params![owner_id, name, exclude], + ) + .await + .map_err(backend)? + } + }; + Ok(rows.next().await.map_err(backend)?.is_some()) +} + +/// Refuses with [`StoreError::AncestorTrashed`] while any folder at or above +/// `folder_id` wears trash. The walk starts at the folder itself, so callers +/// pass the parent chain's head and get the whole ancestry vetted. +async fn ancestor_trashed(conn: &Connection, folder_id: &str) -> Result<()> { + let mut cursor = Some(folder_id.to_string()); + while let Some(current) = cursor { + match folder_row(conn, ¤t).await? { + None => return Ok(()), + Some(folder) if folder.deleted_at.is_some() => { + return Err(StoreError::AncestorTrashed); + } + Some(folder) => cursor = folder.parent_id, + } + } + Ok(()) +} + +/// The download flag of the grant that opens `target_id` for `user_id`, +/// if any: the most permissive grant on the target or any live folder +/// above it wins. A folder grant covers everything under it, so seeing a +/// file means asking about its whole ancestry — and a download grant +/// anywhere on that chain opens the bytes, even under a view-only grant +/// on the target itself. +/// +/// The walk is cycle-safe — ancestry cannot circle (a move into its own +/// descendant is refused), and the visited set makes that a fact rather than +/// a trust. Only live folders pass the grant down: a grant on trash opens +/// nothing below it. +async fn effective_grant( + conn: &Connection, + kind: ShareKind, + target_id: &str, + user_id: &str, +) -> Result> { + let mut chain = vec![(kind, target_id.to_string())]; + let mut cursor: Option = match kind { + ShareKind::Folder => Some(target_id.to_string()), + ShareKind::File => file_row(conn, target_id) + .await? + .and_then(|file| file.folder_id), + }; + let mut visited = std::collections::HashSet::new(); + while let Some(current) = cursor { + if !visited.insert(current.clone()) { + break; + } + match folder_row(conn, ¤t).await? { + Some(folder) if folder.deleted_at.is_none() => { + chain.push((ShareKind::Folder, current)); + cursor = folder.parent_id; + } + _ => break, + } + } + // Most permissive wins across the whole chain: every grant is read and + // any download flag opens the bytes. Visibility only needs one grant + // anywhere, so callers keep reading `is_some` for `can_see` and the flag + // for `can_download`. + let mut seen = false; + let mut downloadable = false; + for (kind, id) in chain { + let mut rows = conn + .query( + "SELECT can_download FROM share_user \ + WHERE kind = ?1 AND target_id = ?2 AND user_id = ?3", + params![kind.as_str(), id, user_id], + ) + .await + .map_err(backend)?; + if let Some(row) = rows.next().await.map_err(backend)? { + seen = true; + if row.get::(0).map_err(backend)? != 0 { + downloadable = true; + } + } + } + Ok(seen.then_some(downloadable)) +} + +/// The owner of a share target's row, trashed or not — the ownership half +/// of [`Store::can_see`]. `None` only when there is no such row at all. +async fn row_owner( + conn: &tokio::sync::Mutex, + kind: ShareKind, + target_id: &str, +) -> Result> { + let conn = conn.lock().await; + let mut rows = match kind { + ShareKind::File => { + conn.query("SELECT owner_id FROM file WHERE id = ?1", params![target_id]) + .await + .map_err(backend)? + } + ShareKind::Folder => { + conn.query( + "SELECT owner_id FROM folder WHERE id = ?1", + params![target_id], + ) + .await + .map_err(backend)? + } + }; + match rows.next().await.map_err(backend)? { + Some(row) => Ok(Some(text(&row, 0)?)), + None => Ok(None), + } +} + +/// The live owner of a share target, or `None` when the target is missing or +/// trashed. Grants and links are vetted against this: shares never name what +/// is not live. +async fn target_owner( + conn: &tokio::sync::Mutex, + kind: ShareKind, + target_id: &str, +) -> Result> { + let conn = conn.lock().await; + let mut rows = match kind { + ShareKind::File => { + conn.query( + "SELECT owner_id FROM file WHERE id = ?1 AND deleted_at IS NULL", + params![target_id], + ) + .await + .map_err(backend)? + } + ShareKind::Folder => { + conn.query( + "SELECT owner_id FROM folder WHERE id = ?1 AND deleted_at IS NULL", + params![target_id], + ) + .await + .map_err(backend)? + } + }; + match rows.next().await.map_err(backend)? { + Some(row) => Ok(Some(text(&row, 0)?)), + None => Ok(None), + } +} + +/// Deletes file rows and every share naming them: links and grants onto a +/// purged file are dead, and the purge is what says so. Upload sessions that +/// named these files never exist — sessions name folders, not files. +async fn delete_file_rows(tx: &Transaction<'_>, ids: &[String]) -> Result<()> { + for id in ids { + tx.execute( + "DELETE FROM share_link WHERE target_id = ?1 AND kind = 'file'", + params![id.as_str()], + ) + .await + .map_err(backend)?; + tx.execute( + "DELETE FROM share_user WHERE target_id = ?1 AND kind = 'file'", + params![id.as_str()], + ) + .await + .map_err(backend)?; + tx.execute("DELETE FROM file WHERE id = ?1", params![id.as_str()]) + .await + .map_err(backend)?; + } + Ok(()) +} + +/// Deletes folder rows deepest first, with every share naming them. Active +/// upload sessions staged into these folders keep their rows — the upload +/// may still finish into the root's listing — but lose the folder: a session +/// cannot finish into trash that has been purged. +async fn delete_folder_rows(tx: &Transaction<'_>, ids: &[String]) -> Result<()> { + for id in ids { + tx.execute( + "DELETE FROM share_link WHERE target_id = ?1 AND kind = 'folder'", + params![id.as_str()], + ) + .await + .map_err(backend)?; + tx.execute( + "DELETE FROM share_user WHERE target_id = ?1 AND kind = 'folder'", + params![id.as_str()], + ) + .await + .map_err(backend)?; + tx.execute( + "UPDATE upload_session SET folder_id = NULL WHERE folder_id = ?1", + params![id.as_str()], + ) + .await + .map_err(backend)?; + tx.execute("DELETE FROM folder WHERE id = ?1", params![id.as_str()]) + .await + .map_err(backend)?; + } + Ok(()) +} + +/// Orders `(id, parent_id)` rows deepest first, so a purge deletes children +/// before the parents whose foreign keys still name them. A row whose parent +/// is outside the set counts depth only within it — the purge set of a trash +/// sweep always contains whole subtrees, so an outside parent is live and +/// never in the way. +fn order_deepest_first(rows: &[(String, Option)]) -> Vec { + use std::collections::{HashMap, HashSet}; + let in_set: HashSet<&str> = rows.iter().map(|(id, _)| id.as_str()).collect(); + let parents: HashMap<&str, &str> = rows + .iter() + .filter_map(|(id, parent)| parent.as_deref().map(|p| (id.as_str(), p))) + .collect(); + let mut ids: Vec = rows.iter().map(|(id, _)| id.clone()).collect(); + ids.sort_by_key(|id| std::cmp::Reverse(depth_in(id.as_str(), &parents, &in_set))); + ids +} + +/// How deep `id` sits inside `rows`: the ancestors it names that are +/// themselves in the set. A row whose parent is outside the set counts depth +/// only within it. +fn depth_in(id: &str, parents: &std::collections::HashMap<&str, &str>, in_set: &std::collections::HashSet<&str>) -> usize { + let mut depth = 0; + let mut cursor = id; + while let Some(parent) = parents.get(cursor) { + if !in_set.contains(parent) { + break; + } + depth += 1; + cursor = parent; + } + depth +} + +/// Decides a file's thumbnail: none for bytes no thumbnail is attempted for, +/// an attempted webp for images and video with affordable bytes, `failed` +/// for everything else. Video without `ffmpeg` on `PATH` wears `none` — no +/// attempt was possible — while a failed extraction wears `failed` like an +/// undecodable image. The bytes are `None` when the caller did not read the +/// file back — too big to thumbnail reads as failed, never as a second full +/// read. +fn thumb_for(mime: &str, size: u64, bytes: Option<&[u8]>) -> (ThumbState, Option>) { + if !thumbs::thumbnailed(mime) { + return (ThumbState::None, None); + } + if size > THUMB_SOURCE_CAP { + return (ThumbState::Failed, None); + } + if thumbs::is_video_mime(mime) { + if !thumbs::ffmpeg_available() { + return (ThumbState::None, None); + } + return match bytes.and_then(thumbs::thumbnail_for_video_bytes) { + Some(thumb) => (ThumbState::Ready, Some(thumb)), + None => (ThumbState::Failed, None), + }; + } + match bytes.and_then(thumbs::thumbnail_for_bytes) { + Some(thumb) => (ThumbState::Ready, Some(thumb)), + None => (ThumbState::Failed, None), + } +} + +/// A uniqueness refusal is the name check's answer, not a malfunction: the +/// backstop for a race two Immediate transactions could not serialise. +fn map_constraint(e: turso::Error, taken: StoreError) -> StoreError { + if is_constraint_violation(&e) { + taken + } else { + backend(e) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_are_labels_never_paths() { + assert_eq!(label_of("../../etc/passwd"), "passwd"); + assert_eq!(label_of("C:\\Windows\\x.txt"), "x.txt"); + assert_eq!(label_of(" spaced "), "spaced"); + assert_eq!(label_of("a\u{0}b"), "ab"); + } + + #[test] + fn an_empty_name_becomes_untitled() { + assert_eq!(label_of(""), "Untitled"); + assert_eq!(label_of("///"), "Untitled"); + assert_eq!(label_of(" "), "Untitled"); + } + + #[test] + fn chunk_arithmetic() { + assert_eq!(chunk_count(0), 0); + assert_eq!(chunk_count(1), 1); + assert_eq!(chunk_count(CHUNK_SIZE), 1); + assert_eq!(chunk_count(CHUNK_SIZE + 1), 2); + assert_eq!(expected_chunk_len(10, 0), 10); + assert_eq!(expected_chunk_len(CHUNK_SIZE * 2 + 7, 0), CHUNK_SIZE); + assert_eq!(expected_chunk_len(CHUNK_SIZE * 2 + 7, 2), 7); + } + + #[test] + fn deepest_folders_go_first() { + let rows = vec![ + ("root".to_string(), None), + ("kid".to_string(), Some("root".to_string())), + ("grand".to_string(), Some("kid".to_string())), + ]; + let ordered = order_deepest_first(&rows); + assert_eq!(ordered, vec!["grand", "kid", "root"]); + } + + #[test] + fn like_queries_escape_their_wildcards() { + assert_eq!(like_pattern("100%"), "%100\\%%"); + assert_eq!(like_pattern("a_b\\c"), "%a\\_b\\\\c%"); + } +} \ No newline at end of file diff --git a/crates/in-core/src/thumbs.rs b/crates/in-core/src/thumbs.rs new file mode 100644 index 0000000..2befbd8 --- /dev/null +++ b/crates/in-core/src/thumbs.rs @@ -0,0 +1,299 @@ +//! Thumbnails: one small webp per image or video file. +//! +//! Images decode in-process (`bytes -> bytes`, with no I/O and nothing +//! store-shaped in it); video needs a decoder the `image` crate does not have, +//! so those frames come from `ffmpeg` on `PATH` instead (see +//! [`thumbnail_for_video_file`]). The upload path calls into here once per +//! finished file, and the store writes whatever comes back to +//! `/thumbs/`. Anything that cannot be made into a thumbnail +//! answers `None`, and the row wears `failed` — or `none` when no attempt was +//! even possible — so the attempt is never repeated: a thumbnail that cannot +//! be made is a fact, not an error. + +use std::io::Read as _; +use std::path::Path; +use std::process::{Command, Stdio}; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +/// The longest edge a thumbnail keeps, in pixels. Big enough to be legible +/// on a file card, small enough that a library of them stays cheap. +pub const THUMB_MAX_DIM: u32 = 512; + +/// How long one `ffmpeg` extraction may run before it is killed. A single +/// frame out of a local file is milliseconds; ten seconds is already a wedged +/// binary, not a slow one. +pub const FFMPEG_TIMEOUT: Duration = Duration::from_secs(10); + +/// Makes the thumbnail for `bytes`: decoded, resized so the longest edge is +/// [`THUMB_MAX_DIM`], encoded as webp. `None` for bytes that are not an +/// image the decoder knows, or that fail to encode — the caller records the +/// miss and moves on. +pub fn thumbnail_for_bytes(bytes: &[u8]) -> Option> { + let image = image::load_from_memory(bytes).ok()?; + let thumb = image.thumbnail(THUMB_MAX_DIM, THUMB_MAX_DIM); + let mut out = Vec::new(); + thumb + .write_to( + &mut std::io::Cursor::new(&mut out), + image::ImageFormat::WebP, + ) + .ok()?; + if out.is_empty() { None } else { Some(out) } +} + +/// Whether a thumbnail is even attempted for this mime: images, decoded +/// in-process, and the video containers the sniffer names, framed by +/// `ffmpeg`. Anything else wears `none` without a decoder ever looking at it. +pub fn thumbnailed(mime: &str) -> bool { + mime.starts_with("image/") || is_video_mime(mime) +} + +/// Whether `mime` is a video container this crate frames via `ffmpeg`: +/// exactly the video mimes the sniffer can name. +pub fn is_video_mime(mime: &str) -> bool { + matches!(mime, "video/mp4" | "video/webm" | "video/quicktime") +} + +/// Whether `ffmpeg` is on `PATH`. The verdict comes from one `ffmpeg +/// -version` run and is cached for the process: a missing binary must degrade +/// every video to its icon, not fork a failing child per upload. +pub fn ffmpeg_available() -> bool { + static HAVE_FFMPEG: OnceLock = OnceLock::new(); + *HAVE_FFMPEG.get_or_init(|| { + Command::new("ffmpeg") + .arg("-version") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .map(|status| status.success()) + .unwrap_or(false) + }) +} + +/// Makes the thumbnail for the video at `path`: the frame at one second, +/// scaled so the longest edge is [`THUMB_MAX_DIM`], encoded as webp. Clips +/// shorter than a second fall back to their first frame. `None` without +/// `ffmpeg` on `PATH`, or when the file is not a video `ffmpeg` can read — +/// the caller records the miss and moves on, never the upload. +pub fn thumbnail_for_video_file(path: &Path) -> Option> { + if !ffmpeg_available() { + return None; + } + run_ffmpeg_frame(path, true).or_else(|| run_ffmpeg_frame(path, false)) +} + +/// Makes the thumbnail for video `bytes`, spilled to a temp file because +/// `ffmpeg` seeks its input and a pipe is not seekable. Same `None` contract +/// as [`thumbnail_for_video_file`]. +pub fn thumbnail_for_video_bytes(bytes: &[u8]) -> Option> { + if !ffmpeg_available() || bytes.is_empty() { + return None; + } + static COUNTER: AtomicU64 = AtomicU64::new(0); + let tmp = std::env::temp_dir().join(format!( + "in-thumb-{}-{}.bin", + std::process::id(), + COUNTER.fetch_add(1, Ordering::Relaxed) + )); + std::fs::write(&tmp, bytes).ok()?; + let out = thumbnail_for_video_file(&tmp); + let _ = std::fs::remove_file(&tmp); + out +} + +/// Runs one `ffmpeg` frame extraction: `seek_one_second` takes the frame at +/// one second, otherwise the first frame. The webp comes back over the +/// stdout pipe; anything else — a nonzero exit, an empty pipe, bytes that are +/// not a webp — is `None`. A run past [`FFMPEG_TIMEOUT`] is killed. +fn run_ffmpeg_frame(path: &Path, seek_one_second: bool) -> Option> { + let scale = format!( + "scale={0}:{0}:force_original_aspect_ratio=decrease", + THUMB_MAX_DIM + ); + let mut cmd = Command::new("ffmpeg"); + cmd.args(["-v", "error"]); + if seek_one_second { + // Before `-i`: fast input seeking, good enough for a thumbnail. + cmd.args(["-ss", "1"]); + } + cmd.arg("-i") + .arg(path) + .args(["-frames:v", "1", "-vf", &scale]) + // `-c:v libwebp` matters: without it this ffmpeg answers `-f webp` + // with its animated encoder, which refuses a single frame. + .args(["-c:v", "libwebp", "-f", "webp", "-"]); + let mut child = cmd + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .ok()?; + // The webp is read on its own thread: the pipe buffer is small, and a + // parent that only `try_wait`s while the child fills the buffer would + // deadlock against it. + let stdout = child.stdout.take(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut buf = Vec::new(); + if let Some(mut out) = stdout { + let _ = out.read_to_end(&mut buf); + } + let _ = tx.send(buf); + }); + let start = Instant::now(); + loop { + match child.try_wait() { + Ok(Some(status)) => { + let buf = rx.recv().ok()?; + if !status.success() || buf.len() < 12 { + return None; + } + // Whatever left the pipe must be the webp asked for. + if &buf[0..4] == b"RIFF" && &buf[8..12] == b"WEBP" { + return Some(buf); + } + return None; + } + Ok(None) => { + if start.elapsed() >= FFMPEG_TIMEOUT { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + std::thread::sleep(Duration::from_millis(20)); + } + Err(_) => { + let _ = child.kill(); + return None; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A 1x1 PNG, hand-built: the smallest thing the decoder must accept. + fn tiny_png() -> Vec { + let img = image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255])); + let mut out = Vec::new(); + img.write_to( + &mut std::io::Cursor::new(&mut out), + image::ImageFormat::Png, + ) + .unwrap(); + out + } + + #[test] + fn an_image_makes_a_webp_thumbnail() { + let thumb = thumbnail_for_bytes(&tiny_png()).unwrap(); + // A webp RIFF header, not the PNG that went in. + assert_eq!(&thumb[0..4], b"RIFF"); + assert_eq!(&thumb[8..12], b"WEBP"); + let back = image::load_from_memory(&thumb).unwrap(); + assert!(back.width() <= THUMB_MAX_DIM && back.height() <= THUMB_MAX_DIM); + } + + #[test] + fn non_images_make_no_thumbnail() { + assert!(thumbnail_for_bytes(b"just some text").is_none()); + assert!(thumbnail_for_bytes(&[]).is_none()); + } + + #[test] + fn images_and_covered_video_are_thumbnailed() { + assert!(thumbnailed("image/png")); + assert!(thumbnailed("image/webp")); + assert!(thumbnailed("video/mp4")); + assert!(thumbnailed("video/webm")); + assert!(thumbnailed("video/quicktime")); + assert!(!thumbnailed("application/pdf")); + assert!(!thumbnailed("text/plain")); + assert!(!thumbnailed("audio/mpeg")); + assert!(!thumbnailed("application/octet-stream")); + } + + /// Renders a tiny mp4 with `ffmpeg`'s own test pattern, for the tests + /// that need a real video. `None` when the render itself fails. + fn make_test_mp4(duration_secs: &str) -> Option> { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let path = std::env::temp_dir().join(format!( + "in-test-video-{}-{}.mp4", + std::process::id(), + COUNTER.fetch_add(1, Ordering::Relaxed) + )); + let rendered = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &format!("testsrc=duration={duration_secs}:size=64x64:rate=10"), + "-pix_fmt", + "yuv420p", + "-c:v", + "mpeg4", + "-y", + ]) + .arg(&path) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .ok()?; + let bytes = if rendered.success() { + std::fs::read(&path).ok() + } else { + None + }; + let _ = std::fs::remove_file(&path); + bytes + } + + #[test] + fn a_video_frame_makes_a_webp_thumbnail() { + if !ffmpeg_available() { + // No decoder on PATH, no test: the upload path degrades the same + // way and asserts nothing here. + return; + } + let mp4 = make_test_mp4("2").expect("ffmpeg renders the fixture"); + let thumb = thumbnail_for_video_bytes(&mp4).expect("a frame is framed"); + assert_eq!(&thumb[0..4], b"RIFF"); + assert_eq!(&thumb[8..12], b"WEBP"); + let back = image::load_from_memory(&thumb).unwrap(); + assert!(back.width() <= THUMB_MAX_DIM && back.height() <= THUMB_MAX_DIM); + } + + #[test] + fn a_sub_second_clip_falls_back_to_its_first_frame() { + if !ffmpeg_available() { + return; + } + let mp4 = make_test_mp4("0.3").expect("ffmpeg renders the fixture"); + let thumb = thumbnail_for_video_bytes(&mp4).expect("short clips frame too"); + assert_eq!(&thumb[0..4], b"RIFF"); + assert_eq!(&thumb[8..12], b"WEBP"); + } + + #[test] + fn garbage_video_makes_no_thumbnail() { + // Bytes `ffmpeg` cannot read — and a path that is not a file at all — + // degrade to `None`, on every machine: with `ffmpeg` the extraction + // fails, without it no attempt runs. Either way nothing panics and + // nothing hangs. + let mut garbage = b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00".to_vec(); + garbage.extend_from_slice(&[0xA5u8; 4096]); + assert!(thumbnail_for_video_bytes(&garbage).is_none()); + assert!(thumbnail_for_video_bytes(&[]).is_none()); + assert!( + thumbnail_for_video_file(Path::new("/nonexistent/in-thumb-probe")).is_none() + ); + } +} diff --git a/crates/in-core/tests/store.rs b/crates/in-core/tests/store.rs new file mode 100644 index 0000000..7372b38 --- /dev/null +++ b/crates/in-core/tests/store.rs @@ -0,0 +1,1122 @@ +//! Integration tests for in-core: the storage boundary driven through the +//! Turso implementation, and the provisioning and drive flows on top of it. +//! +//! New integration tests belong in this file rather than a new `tests/*.rs`: +//! one test binary links and runs once. + +use std::path::PathBuf; + +use in_core::store::{ + CHUNK_SIZE, ShareKind, Store, StoreError, ThumbState, TursoStore, UploadState, +}; +use in_core::{File, Folder, User}; +use time::{Duration, OffsetDateTime}; +use ulid::Ulid; + +/// A throwaway database on disk. Turso's in-memory mode is not what production +/// runs, so the tests exercise a real file. +struct Scratch { + dir: PathBuf, + db: PathBuf, + storage: PathBuf, + store: TursoStore, +} + +impl Scratch { + async fn open() -> Self { + let dir = std::env::temp_dir().join(format!("in-test-{}", Ulid::new())); + std::fs::create_dir_all(&dir).unwrap(); + let db = dir.join("in.db"); + let storage = dir.join("storage"); + let store = TursoStore::open(db.to_str().unwrap(), Some(&storage)) + .await + .unwrap(); + Self { + dir, + db, + storage, + store, + } + } + + /// Reopens the same database file, running the boot path again — the + /// sweep, the prune, the purge — against what the test left behind. + async fn reopen(&mut self) { + drop(std::mem::replace( + &mut self.store, + TursoStore::open(self.db.to_str().unwrap(), Some(&self.storage.clone())) + .await + .unwrap(), + )); + } +} + +/// A second, independent connection to the scratch database, for tests that +/// need to write a column the way it actually sits on disk rather than +/// through [`Store`]'s API. +async fn raw_conn(scratch: &Scratch) -> turso::Connection { + let db = turso::Builder::new_local(scratch.db.to_str().unwrap()) + .build() + .await + .unwrap(); + db.connect().unwrap() +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +async fn alice(store: &TursoStore) -> User { + store + .provision_user("sub-alice", "alice@example.com", "Alice", 1024 * 1024 * 1024) + .await + .unwrap() +} + +async fn bob(store: &TursoStore) -> User { + store + .provision_user("sub-bob", "bob@example.com", "Bob", 1024 * 1024 * 1024) + .await + .unwrap() +} + +/// A 4x4 red PNG: the smallest thing the thumbnailer must accept. +fn png_bytes() -> Vec { + let img = image::RgbImage::from_pixel(4, 4, image::Rgb([200, 30, 30])); + let mut out = Vec::new(); + img.write_to( + &mut std::io::Cursor::new(&mut out), + image::ImageFormat::Png, + ) + .unwrap(); + out +} + +#[tokio::test] +async fn the_schema_is_created_once_and_survives_reopen() { + let dir = std::env::temp_dir().join(format!("in-test-{}", Ulid::new())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("in.db").to_string_lossy().into_owned(); + + let first = TursoStore::open(&path, None).await.unwrap(); + alice(&first).await; + drop(first); + + // Re-opening a database that already has tables must not re-run the + // schema (its CREATE TABLE would fail on the first one) and must not + // lose what the first open wrote. `None` storage derives beside the + // database, so the second open finds the same tree. + let second = TursoStore::open(&path, None).await.unwrap(); + assert_eq!( + second + .user_by_oidc_sub("sub-alice") + .await + .unwrap() + .unwrap() + .email, + "alice@example.com" + ); + assert!(dir.join("storage").join("files").is_dir()); + drop(second); + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test] +async fn the_first_user_is_admin_and_sign_ins_refresh_the_row() { + let scratch = Scratch::open().await; + let first = alice(&scratch.store).await; + assert!(first.admin); + assert_eq!(first.quota_bytes, 1024 * 1024 * 1024); + assert_eq!(first.used_bytes, 0); + assert!(first.last_seen_at.is_some()); + + let second = bob(&scratch.store).await; + assert!(!second.admin); + + // A returning person keeps their id, admin flag and quota; the provider's + // new address and name win, and the sighting is stamped. + let again = scratch + .store + .provision_user("sub-alice", "alice@new.com", "Alice New", 1) + .await + .unwrap(); + assert_eq!(again.id, first.id); + assert!(again.admin); + assert_eq!(again.email, "alice@new.com"); + assert_eq!(again.display_name, "Alice New"); + assert_eq!(again.quota_bytes, 1024 * 1024 * 1024); +} + +#[tokio::test] +async fn quota_and_disablement_round_trip() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + scratch.store.set_user_quota(&user.id, 42).await.unwrap(); + scratch + .store + .set_user_disabled(&user.id, true) + .await + .unwrap(); + let back = scratch.store.user(&user.id).await.unwrap().unwrap(); + assert_eq!(back.quota_bytes, 42); + assert!(back.disabled); + assert!(matches!( + scratch.store.set_user_quota("no-such-user", 1).await, + Err(StoreError::NotFound) + )); +} + +#[tokio::test] +async fn folders_nest_and_names_are_unique_among_live_siblings() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let root = scratch + .store + .create_folder(&user.id, None, "root") + .await + .unwrap(); + let kid = scratch + .store + .create_folder(&user.id, Some(&root.id), "kid") + .await + .unwrap(); + assert_eq!(kid.parent_id.as_deref(), Some(root.id.as_str())); + + assert!(matches!( + scratch.store.create_folder(&user.id, None, "root").await, + Err(StoreError::NameTaken) + )); + // Same name in a different directory is a different name. + scratch + .store + .create_folder(&user.id, Some(&root.id), "root") + .await + .unwrap(); + + let listing = scratch.store.list_children(&user.id, None).await.unwrap(); + assert_eq!(listing.folders.len(), 1); + let listing = scratch + .store + .list_children(&user.id, Some(&root.id)) + .await + .unwrap(); + assert_eq!(listing.folders.len(), 2); +} + +#[tokio::test] +async fn a_folder_moved_into_its_descendant_is_refused() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let a = scratch.store.create_folder(&user.id, None, "a").await.unwrap(); + let b = scratch + .store + .create_folder(&user.id, Some(&a.id), "b") + .await + .unwrap(); + let c = scratch + .store + .create_folder(&user.id, Some(&b.id), "c") + .await + .unwrap(); + + assert!(matches!( + scratch.store.move_folder(&a.id, Some(&c.id)).await, + Err(StoreError::Cycle) + )); + assert!(matches!( + scratch.store.move_folder(&a.id, Some(&a.id)).await, + Err(StoreError::Cycle) + )); + // The refused moves changed nothing. + let back: Folder = scratch.store.folder(&a.id).await.unwrap().unwrap(); + assert_eq!(back.parent_id, None); + + // A legal move lands. + scratch.store.move_folder(&c.id, None).await.unwrap(); + let back: Folder = scratch.store.folder(&c.id).await.unwrap().unwrap(); + assert_eq!(back.parent_id, None); +} + +#[tokio::test] +async fn strangers_folders_answer_cross_owner() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let other = bob(&scratch.store).await; + let folder = scratch + .store + .create_folder(&user.id, None, "mine") + .await + .unwrap(); + + // The store names the mismatch; the route layer answers 404 to it, never + // 403, so a stranger learns nothing about which ids exist. + assert!(matches!( + scratch + .store + .create_folder(&other.id, Some(&folder.id), "squat") + .await, + Err(StoreError::CrossOwner) + )); + let file = scratch + .store + .insert_file(&user.id, None, "note", b"data") + .await + .unwrap(); + let bobs_folder = scratch + .store + .create_folder(&other.id, None, "bobs") + .await + .unwrap(); + assert!(matches!( + scratch.store.move_file(&file.id, Some(&bobs_folder.id)).await, + Err(StoreError::CrossOwner) + )); +} +#[tokio::test] +async fn moving_across_owners_is_refused() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let other = bob(&scratch.store).await; + let folder = scratch + .store + .create_folder(&user.id, None, "mine") + .await + .unwrap(); + let theirs = scratch + .store + .create_folder(&other.id, None, "theirs") + .await + .unwrap(); + assert!(matches!( + scratch.store.move_folder(&folder.id, Some(&theirs.id)).await, + Err(StoreError::CrossOwner) + )); +} + +#[tokio::test] +async fn names_are_labels_never_paths() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let folder = scratch + .store + .create_folder(&user.id, None, "../../etc") + .await + .unwrap(); + assert_eq!(folder.name, "etc"); + let file = scratch + .store + .insert_file(&user.id, None, "", b"data") + .await + .unwrap(); + assert_eq!(file.name, "Untitled"); +} + +#[tokio::test] +async fn an_inserted_file_round_trips_through_its_row_and_bytes() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let mut rx = scratch.store.subscribe(); + let bytes = png_bytes(); + let file: File = scratch + .store + .insert_file(&user.id, None, "photo.png", &bytes) + .await + .unwrap(); + // The mime is sniffed from the bytes, the thumbnail is attempted for an + // image, and the bytes land on disk under the row's id. + assert_eq!(file.mime, "image/png"); + assert_eq!(file.thumb_state, ThumbState::Ready); + assert_eq!(file.size_bytes, bytes.len() as u64); + assert_eq!(scratch.store.file_bytes(&file.id).await.unwrap().unwrap(), bytes); + assert!(scratch.storage.join("files").join(&file.id).is_file()); + let thumb = scratch.store.thumb_bytes(&file.id).await.unwrap().unwrap(); + assert_eq!(&thumb[0..4], b"RIFF"); + // The committed write announced the library. + let change = rx.try_recv().unwrap(); + assert_eq!(change.topic.kind(), "library"); + + // What the sniffer cannot name stays generic, and no thumbnail is + // attempted for it. + let text = scratch + .store + .insert_file(&user.id, None, "notes.txt", b"hello") + .await + .unwrap(); + assert_eq!(text.mime, "text/plain"); + assert_eq!(text.thumb_state, ThumbState::None); + assert!(scratch.store.thumb_bytes(&text.id).await.unwrap().is_none()); +} + +/// Renders a tiny mp4 with `ffmpeg`'s own test pattern. `None` when there is +/// no `ffmpeg` on `PATH`, or the render itself fails — callers skip silently. +fn make_test_mp4() -> Option> { + if !in_core::thumbs::ffmpeg_available() { + return None; + } + let path = std::env::temp_dir().join(format!("in-test-upload-{}.mp4", Ulid::new())); + let rendered = std::process::Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + "testsrc=duration=2:size=64x64:rate=10", + "-pix_fmt", + "yuv420p", + "-c:v", + "mpeg4", + "-y", + ]) + .arg(&path) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .ok()?; + let bytes = if rendered.success() { + std::fs::read(&path).ok() + } else { + None + }; + let _ = std::fs::remove_file(&path); + bytes +} + +#[tokio::test] +async fn a_broken_video_uploads_fine_without_a_thumbnail() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + // Wears an mp4's magic but holds garbage: `ffmpeg` — when present — + // cannot frame it, and the upload must not care. + let mut bytes = b"\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00".to_vec(); + bytes.extend_from_slice(&[0xA5u8; 4096]); + let file = scratch + .store + .insert_file(&user.id, None, "clip.mp4", &bytes) + .await + .unwrap(); + assert_eq!(file.mime, "video/mp4"); + // `Failed` when `ffmpeg` tried and missed, `None` when no attempt was + // possible: never `Ready`, and never an upload error. + assert!(matches!( + file.thumb_state, + ThumbState::Failed | ThumbState::None + )); + assert!(scratch.store.thumb_bytes(&file.id).await.unwrap().is_none()); + assert_eq!(scratch.store.file_bytes(&file.id).await.unwrap().unwrap(), bytes); +} + +#[tokio::test] +async fn a_real_video_uploads_with_a_thumbnail() { + let Some(bytes) = make_test_mp4() else { + // No decoder on PATH, no test: the upload degrades to its icon. + return; + }; + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let file = scratch + .store + .insert_file(&user.id, None, "clip.mp4", &bytes) + .await + .unwrap(); + assert_eq!(file.mime, "video/mp4"); + assert_eq!(file.thumb_state, ThumbState::Ready); + let thumb = scratch.store.thumb_bytes(&file.id).await.unwrap().unwrap(); + assert_eq!(&thumb[0..4], b"RIFF"); + assert_eq!(&thumb[8..12], b"WEBP"); +} + +#[tokio::test] +async fn a_chunked_video_upload_finishes_with_a_thumbnail() { + let Some(bytes) = make_test_mp4() else { + return; + }; + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let session = scratch + .store + .create_upload_session(&user.id, None, "clip.mp4", bytes.len() as u64) + .await + .unwrap(); + scratch.store.record_chunk(&session.id, 0, &bytes).await.unwrap(); + let file = scratch.store.finish_upload(&session.id).await.unwrap(); + assert_eq!(file.mime, "video/mp4"); + assert_eq!(file.thumb_state, ThumbState::Ready); + let thumb = scratch.store.thumb_bytes(&file.id).await.unwrap().unwrap(); + assert_eq!(&thumb[0..4], b"RIFF"); + assert_eq!(&thumb[8..12], b"WEBP"); +} + +#[tokio::test] +async fn a_claimed_mime_is_never_trusted() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + // Named like an executable, holding a PNG: the row says image, because + // the bytes do. + let file = scratch + .store + .insert_file(&user.id, None, "evil.exe", &png_bytes()) + .await + .unwrap(); + assert_eq!(file.mime, "image/png"); +} + +#[tokio::test] +async fn trashing_a_folder_cascades_and_restore_needs_live_ancestors() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let root = scratch.store.create_folder(&user.id, None, "root").await.unwrap(); + let kid = scratch + .store + .create_folder(&user.id, Some(&root.id), "kid") + .await + .unwrap(); + let file = scratch + .store + .insert_file(&user.id, Some(&kid.id), "deep.txt", b"deep") + .await + .unwrap(); + + scratch.store.delete_folder(&root.id).await.unwrap(); + assert!(scratch.store.folder(&root.id).await.unwrap().unwrap().deleted_at.is_some()); + assert!(scratch.store.folder(&kid.id).await.unwrap().unwrap().deleted_at.is_some()); + assert!(scratch.store.file(&file.id).await.unwrap().unwrap().deleted_at.is_some()); + // Trashed rows leave the listing but join the trash. + assert!(scratch.store.list_children(&user.id, None).await.unwrap().folders.is_empty()); + let trash = scratch.store.list_trash(&user.id).await.unwrap(); + assert_eq!(trash.folders.len(), 2); + assert_eq!(trash.files.len(), 1); + + // Restoring from under trash is refused: the ancestor is still down. + assert!(matches!( + scratch.store.restore_folder(&kid.id).await, + Err(StoreError::AncestorTrashed) + )); + assert!(matches!( + scratch.store.restore_file(&file.id).await, + Err(StoreError::AncestorTrashed) + )); + + // Restoring the root brings the whole subtree back. + scratch.store.restore_folder(&root.id).await.unwrap(); + assert!(scratch.store.folder(&kid.id).await.unwrap().unwrap().deleted_at.is_none()); + assert!(scratch.store.file(&file.id).await.unwrap().unwrap().deleted_at.is_none()); + assert_eq!(scratch.store.list_children(&user.id, None).await.unwrap().folders.len(), 1); +} + +#[tokio::test] +async fn a_trashed_name_is_free_until_restored() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let first = scratch.store.create_folder(&user.id, None, "x").await.unwrap(); + scratch.store.delete_folder(&first.id).await.unwrap(); + // Deleting frees the name; restoring onto a live squatter is refused. + scratch.store.create_folder(&user.id, None, "x").await.unwrap(); + assert!(matches!( + scratch.store.restore_folder(&first.id).await, + Err(StoreError::NameTaken) + )); +} + +#[tokio::test] +async fn used_bytes_counts_trash_and_purge_frees_it() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let a = scratch.store.insert_file(&user.id, None, "a", &[0u8; 10]).await.unwrap(); + let b = scratch.store.insert_file(&user.id, None, "b", &[0u8; 20]).await.unwrap(); + assert_eq!(scratch.store.user(&user.id).await.unwrap().unwrap().used_bytes, 30); + + // Trash counts: the bytes are still on disk, still restorable. + scratch.store.delete_file(&a.id).await.unwrap(); + assert_eq!(scratch.store.user(&user.id).await.unwrap().unwrap().used_bytes, 30); + scratch.store.restore_file(&a.id).await.unwrap(); + assert_eq!(scratch.store.user(&user.id).await.unwrap().unwrap().used_bytes, 30); + + // Purge frees: the row goes and the bytes follow. + scratch.store.delete_file(&a.id).await.unwrap(); + assert!(scratch.store.purge_file(&a.id).await.unwrap()); + assert_eq!(scratch.store.user(&user.id).await.unwrap().unwrap().used_bytes, 20); + assert!(!scratch.storage.join("files").join(&a.id).exists()); + + // A live file is never purged, and a missing one is not found. + assert!(!scratch.store.purge_file(&b.id).await.unwrap()); + assert!(matches!( + scratch.store.purge_file("no-such-file").await, + Err(StoreError::NotFound) + )); + + // Emptying the trash takes the rest. + scratch.store.delete_file(&b.id).await.unwrap(); + assert_eq!(scratch.store.empty_trash(&user.id).await.unwrap(), 1); + assert_eq!(scratch.store.user(&user.id).await.unwrap().unwrap().used_bytes, 0); + assert!(scratch.store.list_trash(&user.id).await.unwrap().files.is_empty()); +} + +#[tokio::test] +async fn quota_is_enforced_at_start_and_at_finish() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + scratch.store.set_user_quota(&user.id, 100).await.unwrap(); + + // Over quota at open: refused with nothing on disk to clean up. + assert!(matches!( + scratch.store.create_upload_session(&user.id, None, "big", 101).await, + Err(StoreError::QuotaExceeded) + )); + + // Fits at open, over quota by finish: the chunks stay staged for another + // attempt once space is freed. + let session = scratch + .store + .create_upload_session(&user.id, None, "late", 90) + .await + .unwrap(); + scratch.store.record_chunk(&session.id, 0, &[7u8; 90]).await.unwrap(); + scratch.store.insert_file(&user.id, None, "filler", &[0u8; 20]).await.unwrap(); + assert!(matches!( + scratch.store.finish_upload(&session.id).await, + Err(StoreError::QuotaExceeded) + )); + let back = scratch.store.upload_session(&session.id).await.unwrap().unwrap(); + assert_eq!(back.state, UploadState::Active); + + // Room freed, the same chunks finish. + scratch.store.set_user_quota(&user.id, 200).await.unwrap(); + let file = scratch.store.finish_upload(&session.id).await.unwrap(); + assert_eq!(file.size_bytes, 90); +} + +#[tokio::test] +async fn trash_writes_are_invisible_and_purge_takes_subtrees() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let root = scratch.store.create_folder(&user.id, None, "root").await.unwrap(); + scratch.store.delete_folder(&root.id).await.unwrap(); + + // Nothing is created, moved or uploaded under trash. + assert!(matches!( + scratch.store.create_folder(&user.id, Some(&root.id), "kid").await, + Err(StoreError::NotFound) + )); + assert!(matches!( + scratch.store.insert_file(&user.id, Some(&root.id), "f", b"x").await, + Err(StoreError::NotFound) + )); + + // Purging the expired takes the folder row itself. + let purged = scratch + .store + .purge_expired(OffsetDateTime::now_utc() + Duration::days(31)) + .await + .unwrap(); + assert_eq!(purged, 1); + assert!(scratch.store.folder(&root.id).await.unwrap().is_none()); + // Too fresh to purge: a cutoff taken before the trash moment matches + // nothing. + let root2 = scratch.store.create_folder(&user.id, None, "root2").await.unwrap(); + let cutoff = OffsetDateTime::now_utc(); + scratch.store.delete_folder(&root2.id).await.unwrap(); + assert_eq!(scratch.store.purge_expired(cutoff).await.unwrap(), 0); +} +#[tokio::test] +async fn share_links_open_until_revoked_or_expired() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let file = scratch.store.insert_file(&user.id, None, "f", b"data").await.unwrap(); + let now = OffsetDateTime::now_utc(); + + let created = scratch + .store + .create_share_link(&user.id, ShareKind::File, &file.id, true, None) + .await + .unwrap(); + // The token is shown once; the row keeps only the hash. + assert!(!created.token.is_empty()); + assert_ne!(created.link.token_hash, created.token); + // The route hashes the plaintext with the store's own function. + assert_eq!(in_core::hash_share_token(&created.token), created.link.token_hash); + let resolved = scratch + .store + .resolve_share_link(&created.link.token_hash, now) + .await + .unwrap() + .unwrap(); + assert_eq!(resolved.target_id, file.id); + assert!(resolved.can_download); + + // A wrong token and a revoked link both answer None. + assert!(scratch.store.resolve_share_link("wrong", now).await.unwrap().is_none()); + scratch.store.revoke_share_link(&created.link.id).await.unwrap(); + assert!(scratch.store.resolve_share_link(&created.link.token_hash, now).await.unwrap().is_none()); + // Revoking twice is not an error. + scratch.store.revoke_share_link(&created.link.id).await.unwrap(); + + // An already-expired link never opens. + let past = scratch + .store + .create_share_link( + &user.id, + ShareKind::File, + &file.id, + false, + Some(now - Duration::hours(1)), + ) + .await + .unwrap(); + assert!(!past.link.is_live(now)); + assert!(scratch.store.resolve_share_link(&past.link.token_hash, now).await.unwrap().is_none()); + assert_eq!(scratch.store.share_links(&user.id).await.unwrap().len(), 2); +} + +#[tokio::test] +async fn per_person_shares_gate_visibility() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let friend = bob(&scratch.store).await; + let stranger = scratch + .store + .provision_user("sub-caro", "caro@example.com", "Caro", 1024) + .await + .unwrap(); + let file = scratch.store.insert_file(&user.id, None, "shared", b"data").await.unwrap(); + + assert!(!scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap()); + scratch.store.add_share_user(&user.id, ShareKind::File, &file.id, &friend.id, true).await.unwrap(); + assert!(scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap()); + // The owner always sees; a stranger never does; a missing target is + // simply not seen. + assert!(scratch.store.can_see(ShareKind::File, &file.id, &user.id).await.unwrap()); + assert!(!scratch.store.can_see(ShareKind::File, &file.id, &stranger.id).await.unwrap()); + assert!(!scratch.store.can_see(ShareKind::File, "missing", &friend.id).await.unwrap()); + + let shared = scratch.store.shares_for_user(&friend.id).await.unwrap(); + assert_eq!(shared.len(), 1); + assert_eq!(shared[0].name, "shared"); + assert_eq!(shared[0].mime.as_deref(), Some("text/plain")); + + // Trash hides the target from the grantee but not from the owner; purge + // takes the grant with the row. + scratch.store.delete_file(&file.id).await.unwrap(); + assert!(scratch.store.shares_for_user(&friend.id).await.unwrap().is_empty()); + assert!(!scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap()); + assert!(scratch.store.can_see(ShareKind::File, &file.id, &user.id).await.unwrap()); + + scratch.store.remove_share_user(ShareKind::File, &file.id, &friend.id).await.unwrap(); + scratch.store.restore_file(&file.id).await.unwrap(); + assert!(!scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap()); +} + +#[tokio::test] +async fn an_upload_assembles_chunks_in_order_and_sniffs() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let bytes = png_bytes(); + let session = scratch + .store + .create_upload_session(&user.id, None, "avatar.exe", bytes.len() as u64) + .await + .unwrap(); + assert_eq!(session.chunk_size, CHUNK_SIZE); + // A chunk that is not exactly the promised bytes is refused. + assert!(matches!( + scratch.store.record_chunk(&session.id, 0, b"short").await, + Err(StoreError::BadChunk) + )); + assert!(matches!( + scratch.store.record_chunk(&session.id, 1, &bytes).await, + Err(StoreError::BadChunk) + )); + let back = scratch.store.record_chunk(&session.id, 0, &bytes).await.unwrap(); + assert_eq!(back.received_bytes, bytes.len() as u64); + + let file = scratch.store.finish_upload(&session.id).await.unwrap(); + // Named like an executable, holding a PNG: sniffed, thumbed, stored. + assert_eq!(file.name, "avatar.exe"); + assert_eq!(file.mime, "image/png"); + assert_eq!(file.thumb_state, ThumbState::Ready); + assert_eq!(scratch.store.file_bytes(&file.id).await.unwrap().unwrap(), bytes); + assert!(scratch.storage.join("files").join(&file.id).is_file()); + let done = scratch.store.upload_session(&session.id).await.unwrap().unwrap(); + assert_eq!(done.state, UploadState::Done); + assert!(!scratch.storage.join("uploads").join(&session.id).exists()); +} + +#[tokio::test] +async fn an_empty_upload_finishes_an_empty_file() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let session = scratch.store.create_upload_session(&user.id, None, "empty", 0).await.unwrap(); + let file = scratch.store.finish_upload(&session.id).await.unwrap(); + assert_eq!(file.size_bytes, 0); + assert_eq!(scratch.store.file_bytes(&file.id).await.unwrap().unwrap(), Vec::::new()); +} + +#[tokio::test] +async fn uploads_abort_and_prune() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let session = scratch + .store + .create_upload_session(&user.id, None, "abandoned", 4) + .await + .unwrap(); + scratch.store.record_chunk(&session.id, 0, b"1234").await.unwrap(); + scratch.store.abort_upload(&session.id).await.unwrap(); + assert_eq!( + scratch.store.upload_session(&session.id).await.unwrap().unwrap().state, + UploadState::Aborted + ); + assert!(!scratch.storage.join("uploads").join(&session.id).exists()); + // Chunks on a dead session are refused; aborting twice is fine. + assert!(matches!( + scratch.store.record_chunk(&session.id, 0, b"1234").await, + Err(StoreError::UploadExpired) + )); + scratch.store.abort_upload(&session.id).await.unwrap(); + + // Expiry prunes: the row says aborted and the chunks are gone. + let session = scratch.store.create_upload_session(&user.id, None, "stale", 4).await.unwrap(); + scratch.store.record_chunk(&session.id, 0, b"1234").await.unwrap(); + let pruned = scratch + .store + .prune_expired_uploads(OffsetDateTime::now_utc() + Duration::hours(25)) + .await + .unwrap(); + assert_eq!(pruned, 1); + assert!(!scratch.storage.join("uploads").join(&session.id).exists()); + // Nothing expired: nothing pruned. + assert_eq!( + scratch.store.prune_expired_uploads(OffsetDateTime::now_utc()).await.unwrap(), + 0 + ); +} + +#[tokio::test] +async fn search_finds_live_names_and_nothing_else() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let other = bob(&scratch.store).await; + scratch.store.insert_file(&user.id, None, "quarterly report", b"1").await.unwrap(); + scratch.store.insert_file(&user.id, None, "quarterly review", b"2").await.unwrap(); + scratch.store.create_folder(&user.id, None, "quarters").await.unwrap(); + let trashed = scratch.store.insert_file(&user.id, None, "quarterly old", b"3").await.unwrap(); + scratch.store.insert_file(&other.id, None, "quarterly theirs", b"4").await.unwrap(); + scratch.store.delete_file(&trashed.id).await.unwrap(); + + let hits = scratch.store.search(&user.id, "quarter", 50).await.unwrap(); + assert_eq!(hits.files.len(), 2); + assert_eq!(hits.folders.len(), 1); + // Wildcards in the query search literally. + let hits = scratch.store.search(&user.id, "report%", 50).await.unwrap(); + assert!(hits.files.is_empty()); + assert!(scratch.store.search(&user.id, " ", 50).await.unwrap().files.is_empty()); +} + +#[tokio::test] +async fn the_boot_sweep_deletes_files_no_row_names() { + let mut scratch = Scratch::open().await; + let stray = scratch.storage.join("files").join("stray"); + std::fs::write(&stray, b"orphan").unwrap(); + let ghost = scratch.storage.join("uploads").join("ghost"); + std::fs::create_dir_all(&ghost).unwrap(); + std::fs::write(ghost.join("0"), b"chunk").unwrap(); + scratch.reopen().await; + assert!(!stray.exists()); + assert!(!ghost.exists()); +} + +#[tokio::test] +async fn a_row_whose_file_is_missing_is_kept() { + let mut scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let file = scratch.store.insert_file(&user.id, None, "lost", b"data").await.unwrap(); + std::fs::remove_file(scratch.storage.join("files").join(&file.id)).unwrap(); + scratch.reopen().await; + // Said out loud at boot, kept in the database: a lost file is a lost + // file, not a lost fact. + assert!(scratch.store.file(&file.id).await.unwrap().is_some()); + assert!(scratch.store.file_bytes(&file.id).await.unwrap().is_none()); +} + +#[tokio::test] +async fn the_boot_prune_aborts_expired_sessions() { + let mut scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let session = scratch.store.create_upload_session(&user.id, None, "stale", 4).await.unwrap(); + scratch.store.record_chunk(&session.id, 0, b"1234").await.unwrap(); + // Backdate the expiry the way a day-old row would wear it. + let conn = raw_conn(&scratch).await; + conn.execute( + "UPDATE upload_session SET expires_at = '2000-01-01T00:00:00Z' WHERE id = ?1", + turso::params![session.id.as_str()], + ) + .await + .unwrap(); + drop(conn); + scratch.reopen().await; + let back = scratch.store.upload_session(&session.id).await.unwrap().unwrap(); + assert_eq!(back.state, UploadState::Aborted); + assert!(!scratch.storage.join("uploads").join(&session.id).exists()); +} +#[tokio::test] +async fn email_lookup_folds_case() { + let scratch = Scratch::open().await; + let user = scratch + .store + .provision_user("sub-mixed", "Mixed@Example.COM", "Mixed", 1024) + .await + .unwrap(); + // Stored folded, found however it is asked. + assert_eq!(user.email, "mixed@example.com"); + for query in ["mixed@example.com", "MIXED@EXAMPLE.COM", " Mixed@Example.com "] { + let found = scratch.store.user_by_email(query).await.unwrap().unwrap(); + assert_eq!(found.id, user.id); + } + assert!(scratch.store.user_by_email("nobody@example.com").await.unwrap().is_none()); +} + +#[tokio::test] +async fn download_needs_the_flag() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let friend = bob(&scratch.store).await; + let file = scratch.store.insert_file(&user.id, None, "f", b"data").await.unwrap(); + + // The owner always downloads; a stranger never does. + assert!(scratch.store.can_download(ShareKind::File, &file.id, &user.id).await.unwrap()); + assert!(!scratch.store.can_download(ShareKind::File, &file.id, &friend.id).await.unwrap()); + assert!(!scratch.store.can_download(ShareKind::File, "missing", &friend.id).await.unwrap()); + + // A view-only grant opens the page but not the bytes. + scratch.store.add_share_user(&user.id, ShareKind::File, &file.id, &friend.id, false).await.unwrap(); + assert!(scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap()); + assert!(!scratch.store.can_download(ShareKind::File, &file.id, &friend.id).await.unwrap()); + + // Re-sharing with the flag flips the grant in place. + scratch.store.add_share_user(&user.id, ShareKind::File, &file.id, &friend.id, true).await.unwrap(); + assert!(scratch.store.can_download(ShareKind::File, &file.id, &friend.id).await.unwrap()); + + // Unsharing closes both. + scratch.store.remove_share_user(ShareKind::File, &file.id, &friend.id).await.unwrap(); + assert!(!scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap()); + assert!(!scratch.store.can_download(ShareKind::File, &file.id, &friend.id).await.unwrap()); +} + +#[tokio::test] +async fn a_folder_grant_covers_everything_under_it() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let friend = bob(&scratch.store).await; + let parent = scratch.store.create_folder(&user.id, None, "parent").await.unwrap(); + let kid = scratch + .store + .create_folder(&user.id, Some(&parent.id), "kid") + .await + .unwrap(); + let file = scratch + .store + .insert_file(&user.id, Some(&kid.id), "deep.txt", b"deep") + .await + .unwrap(); + assert!(!scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap()); + + // One grant on the top folder opens the whole subtree, files included. + scratch.store.add_share_user(&user.id, ShareKind::Folder, &parent.id, &friend.id, true).await.unwrap(); + assert!(scratch.store.can_see(ShareKind::Folder, &kid.id, &friend.id).await.unwrap()); + assert!(scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap()); + assert!(scratch.store.can_download(ShareKind::File, &file.id, &friend.id).await.unwrap()); + + // Revoking the one grant closes the whole subtree again. + scratch.store.remove_share_user(ShareKind::Folder, &parent.id, &friend.id).await.unwrap(); + assert!(!scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap()); + assert!(!scratch.store.can_download(ShareKind::File, &file.id, &friend.id).await.unwrap()); + + // A view-only folder grant sees the subtree but downloads nothing in it. + scratch.store.add_share_user(&user.id, ShareKind::Folder, &parent.id, &friend.id, false).await.unwrap(); + assert!(scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap()); + assert!(!scratch.store.can_download(ShareKind::File, &file.id, &friend.id).await.unwrap()); +} + +#[tokio::test] +async fn open_does_not_purge_trash() { + let mut scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let folder = scratch.store.create_folder(&user.id, None, "doomed").await.unwrap(); + scratch.store.delete_folder(&folder.id).await.unwrap(); + // Age the trash past any deployment's cutoff the way a month-old row + // would wear it. + let conn = raw_conn(&scratch).await; + conn.execute( + "UPDATE folder SET deleted_at = '2000-01-01T00:00:00Z' WHERE id = ?1", + turso::params![folder.id.as_str()], + ) + .await + .unwrap(); + drop(conn); + // Reopening prunes uploads and sweeps orphans, but the trash waits for + // an explicit purge_expired with the deployment's own cutoff. + scratch.reopen().await; + assert!(scratch.store.folder(&folder.id).await.unwrap().unwrap().deleted_at.is_some()); + assert_eq!( + scratch.store.purge_expired(OffsetDateTime::now_utc()).await.unwrap(), + 1 + ); + assert!(scratch.store.folder(&folder.id).await.unwrap().is_none()); +} +#[tokio::test] +async fn purge_folder_removes_the_whole_trashed_subtree() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let root = scratch.store.create_folder(&user.id, None, "root").await.unwrap(); + let kid = scratch + .store + .create_folder(&user.id, Some(&root.id), "kid") + .await + .unwrap(); + let file = scratch + .store + .insert_file(&user.id, Some(&kid.id), "deep.txt", b"deep") + .await + .unwrap(); + // A live folder is never purged — trash it first — and neither is a + // missing one. + assert!(matches!( + scratch.store.purge_folder(&root.id).await, + Err(StoreError::NotFound) + )); + assert!(matches!( + scratch.store.purge_folder("no-such-folder").await, + Err(StoreError::NotFound) + )); + + scratch.store.delete_folder(&root.id).await.unwrap(); + // Two folders and one file go: rows, bytes, usage and shares together. + assert_eq!(scratch.store.purge_folder(&root.id).await.unwrap(), 3); + assert!(scratch.store.folder(&root.id).await.unwrap().is_none()); + assert!(scratch.store.folder(&kid.id).await.unwrap().is_none()); + assert!(scratch.store.file(&file.id).await.unwrap().is_none()); + assert!(!scratch.storage.join("files").join(&file.id).exists()); + assert_eq!(scratch.store.user(&user.id).await.unwrap().unwrap().used_bytes, 0); + assert!(scratch.store.list_trash(&user.id).await.unwrap().folders.is_empty()); +} + +#[tokio::test] +async fn finish_upload_refused_leaves_no_bytes_behind() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let session = scratch.store.create_upload_session(&user.id, None, "late", 4).await.unwrap(); + scratch.store.record_chunk(&session.id, 0, b"1234").await.unwrap(); + // The library fills while the chunks arrive: someone else's bytes land + // first and the ceiling drops under the session's total. + scratch.store.insert_file(&user.id, None, "filler", b"12345").await.unwrap(); + scratch.store.set_user_quota(&user.id, 5).await.unwrap(); + let before = { + let mut names: Vec<_> = std::fs::read_dir(scratch.storage.join("files")) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + names.sort(); + names + }; + assert!(matches!( + scratch.store.finish_upload(&session.id).await, + Err(StoreError::QuotaExceeded) + )); + // Refused before the rename: files/ holds exactly what it held, with no + // assembled copy and no temp left behind — and the chunks stay staged + // for another attempt. + let after = { + let mut names: Vec<_> = std::fs::read_dir(scratch.storage.join("files")) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + names.sort(); + names + }; + assert_eq!(before, after); + assert!(scratch.storage.join("uploads").join(&session.id).is_dir()); +} + +#[tokio::test] +async fn a_download_grant_above_a_view_only_grant_still_downloads() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let friend = bob(&scratch.store).await; + let folder = scratch.store.create_folder(&user.id, None, "shared").await.unwrap(); + let file = scratch.store.insert_file(&user.id, Some(&folder.id), "note", b"data").await.unwrap(); + // Most permissive wins across the chain: the folder's download grant + // opens the bytes even with a view-only grant on the file itself. + scratch.store.add_share_user(&user.id, ShareKind::Folder, &folder.id, &friend.id, true).await.unwrap(); + scratch.store.add_share_user(&user.id, ShareKind::File, &file.id, &friend.id, false).await.unwrap(); + assert!(scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap()); + assert!(scratch.store.can_download(ShareKind::File, &file.id, &friend.id).await.unwrap()); +} + +#[tokio::test] +async fn restore_folder_keeps_files_trashed_before_it() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let folder = scratch.store.create_folder(&user.id, None, "box").await.unwrap(); + let early = scratch.store.insert_file(&user.id, Some(&folder.id), "early", b"1").await.unwrap(); + let with = scratch.store.insert_file(&user.id, Some(&folder.id), "with", b"2").await.unwrap(); + // Trashed on its own first, then the folder takes the rest with it. + scratch.store.delete_file(&early.id).await.unwrap(); + scratch.store.delete_folder(&folder.id).await.unwrap(); + scratch.store.restore_folder(&folder.id).await.unwrap(); + // The cascade comes back; the earlier trash stays trash. + assert!(scratch.store.folder(&folder.id).await.unwrap().unwrap().deleted_at.is_none()); + assert!(scratch.store.file(&with.id).await.unwrap().unwrap().deleted_at.is_none()); + assert!(scratch.store.file(&early.id).await.unwrap().unwrap().deleted_at.is_some()); +} + +#[tokio::test] +async fn remove_share_user_works_on_trashed_targets() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let friend = bob(&scratch.store).await; + let file = scratch.store.insert_file(&user.id, None, "shared", b"data").await.unwrap(); + scratch.store.add_share_user(&user.id, ShareKind::File, &file.id, &friend.id, true).await.unwrap(); + // Trash does not stop an unshare: revoke while trashed, then restore + // to find the grant gone. + scratch.store.delete_file(&file.id).await.unwrap(); + scratch.store.remove_share_user(ShareKind::File, &file.id, &friend.id).await.unwrap(); + scratch.store.restore_file(&file.id).await.unwrap(); + assert!(!scratch.store.can_see(ShareKind::File, &file.id, &friend.id).await.unwrap()); + // Purged or missing targets still refuse: there is nothing to unshare. + scratch.store.delete_file(&file.id).await.unwrap(); + scratch.store.purge_file(&file.id).await.unwrap(); + assert!(matches!( + scratch.store.remove_share_user(ShareKind::File, &file.id, &friend.id).await, + Err(StoreError::NotFound) + )); + assert!(matches!( + scratch.store.remove_share_user(ShareKind::File, "missing", &friend.id).await, + Err(StoreError::NotFound) + )); +} + +#[tokio::test] +async fn add_share_user_needs_the_owner() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let friend = bob(&scratch.store).await; + let stranger = scratch.store.provision_user("sub-caro", "caro@example.com", "Caro", 1024).await.unwrap(); + let file = scratch.store.insert_file(&user.id, None, "mine", b"data").await.unwrap(); + // A stranger naming someone else's file is refused — and names no grant. + assert!(matches!( + scratch.store.add_share_user(&friend.id, ShareKind::File, &file.id, &stranger.id, true).await, + Err(StoreError::CrossOwner) + )); + assert!(!scratch.store.can_see(ShareKind::File, &file.id, &stranger.id).await.unwrap()); + // A missing target is not-found, like the sibling link creator answers. + assert!(matches!( + scratch.store.add_share_user(&user.id, ShareKind::File, "missing", &stranger.id, true).await, + Err(StoreError::NotFound) + )); + // The owner shares freely. + scratch.store.add_share_user(&user.id, ShareKind::File, &file.id, &stranger.id, true).await.unwrap(); + assert!(scratch.store.can_see(ShareKind::File, &file.id, &stranger.id).await.unwrap()); +} diff --git a/crates/in-web/Cargo.toml b/crates/in-web/Cargo.toml new file mode 100644 index 0000000..75a0df2 --- /dev/null +++ b/crates/in-web/Cargo.toml @@ -0,0 +1,49 @@ +[package] +name = "in-web" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +description = "In web app: topcoat UI, routes and the server" + +[dependencies] +topcoat = { version = "0.6.2", default-features = false, features = [ + "router", + "view", + "runtime", + "asset", + "cookie", + "discover", + "serve", + "compression", + "multipart", + "sse", +] } +in-core = { workspace = true, features = ["server"] } +in-client.workspace = true +serde.workspace = true +serde_json.workspace = true +time.workspace = true +thiserror.workspace = true +tokio.workspace = true +async-trait = "0.1.92" +# The live stream is built with `futures_util::stream::unfold`; topcoat does +# not re-export the futures traits, so this is named directly. +futures-util = { version = "0.3", default-features = false } +# Hashes the compiled stylesheet against the bundle's bytes at boot, so a +# bundle from another generation refuses the boot instead of serving under +# this binary (see `server.rs`'s `stylesheet_guard`). +sha2 = "0.10" +ulid = { workspace = true } + +[build-dependencies] +grass = "0.13" +sha2 = "0.10" + +[dev-dependencies] +http = "1.5" +# Reads an SSE body frame by frame, so a live-channel test can wait for the +# announcement it expects instead of for a clock. +http-body-util = "0.1" +ulid = { workspace = true } +in-client = { workspace = true, features = ["test-seam"] } diff --git a/crates/in-web/build.rs b/crates/in-web/build.rs new file mode 100644 index 0000000..eea9457 --- /dev/null +++ b/crates/in-web/build.rs @@ -0,0 +1,44 @@ +//! Compiles `style/main.scss` to `assets/main.css` under this crate's +//! manifest directory, where `asset!("assets/main.css")` in `layout.rs` +//! expects to find it. Crate-relative rather than `OUT_DIR`-relative so the +//! asset's id does not churn with every profile/build-hash (see the topcoat +//! contract sheet, (a)). +//! +use sha2::Digest; + +fn main() { + let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap(); + let scss = format!("{manifest_dir}/../../style/main.scss"); + println!("cargo:rerun-if-changed={scss}"); + // Partials pulled in via @use — without these, editing a skin file would + // leave assets/main.css stale. + println!("cargo:rerun-if-changed={manifest_dir}/../../style/_instrument.scss"); + println!("cargo:rerun-if-changed={manifest_dir}/../../style/_ledger.scss"); + + let css = grass::from_path(&scss, &grass::Options::default()) + .unwrap_or_else(|err| panic!("failed to compile {scss}: {err}")); + let out_dir = format!("{manifest_dir}/assets"); + std::fs::create_dir_all(&out_dir).expect("failed to create assets/"); + std::fs::write(format!("{out_dir}/main.css"), &css).expect("failed to write assets/main.css"); + + // The binary carries the compiled stylesheet's fingerprint, so the + // running server can tell a bundle of its own generation from one left + // behind by another deploy (`server.rs`'s `stylesheet_guard` refuses the + // boot on a mismatch). The bytes hashed here are exactly the bytes the + // bundler later copies into the bundle, so the fingerprints agree. + let fingerprint = sha2::Sha256::digest(css.as_bytes()); + let mut hex = String::with_capacity(fingerprint.len() * 2); + for byte in fingerprint { + hex.push_str(&format!("{byte:02x}")); + } + println!("cargo:rustc-env=IN_STYLE_FINGERPRINT=sha256:{hex}"); + + // The commit this binary was built from, served by `/healthz` and + // asserted against after the deploy restart, so a stale process + // holding the port cannot pass for this deploy. "dev" locally, where + // nothing asserts it. The rerun-if-env-changed line is load-bearing: + // without it a rust-cache hit would ship last deploy's sha. + let sha = std::env::var("IN_BUILD_SHA").unwrap_or_else(|_| "dev".into()); + println!("cargo:rustc-env=IN_BUILD_SHA={sha}"); + println!("cargo:rerun-if-env-changed=IN_BUILD_SHA"); +} diff --git a/crates/in-web/src/drive.rs b/crates/in-web/src/drive.rs new file mode 100644 index 0000000..ed653ee --- /dev/null +++ b/crates/in-web/src/drive.rs @@ -0,0 +1,547 @@ +//! The drive browser. +//! +//! `GET /drive?folder=` renders one directory — breadcrumbs back to the +//! root, subfolders then files — and the four owner-only folder mutations +//! ride beside it: `POST /api/folder/create|rename|move|delete`. Trashed +//! items never appear here; they wait in `trash.rs`. A folder whose ancestor +//! is trashed is unreachable, and a move that would nest a folder inside +//! itself is refused. Anything naming another owner's tree answers 404, +//! never 403. + +use in_core::store::{Folder, Store, StoreError, ThumbState}; +use topcoat::router::request::uri; +use topcoat::router::{HeaderName, HeaderValue, StatusCode, header, page, query_params, route}; + +use topcoat::Result; +use topcoat::context::Cx; +use topcoat::router::content::{Form, Json}; +use topcoat::router::error::not_found; +use topcoat::view::view; + +use crate::i18n::{Key, lang, t}; +use crate::layout::{NavPage, topbar}; +use crate::server::{Refusal, app, back_to, refusal_of, require_user}; + +/// A [`StoreError`] in the drive's own words. Cross-owner reads and writes +/// alike answer [`Refusal::NotFound`]: telling a stranger which ids exist is +/// the leak the distinction exists to prevent. +fn store_refusal(error: StoreError) -> Refusal { + match error { + StoreError::NameTaken => Refusal::NameTaken, + StoreError::QuotaExceeded => Refusal::QuotaExceeded, + StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound, + // A move nesting a folder inside its own descendant. + StoreError::Cycle => Refusal::Forbidden, + _ => Refusal::Unavailable, + } +} + +/// A 303 back to the page the form was posted from, carrying the refusal as +/// the body for `carry_refusal_on_redirect` to copy onto the query. +type Redirect = Result<(StatusCode, [(HeaderName, String); 1], Json>)>; + +fn redirect(cx: &Cx, refusal: Option) -> Redirect { + Ok(( + StatusCode::SEE_OTHER, + [(header::LOCATION, back_to(cx, "/drive"))], + Json(refusal), + )) +} + +#[query_params] +struct DriveQuery { + folder: Option, +} + +/// The folder the query names, if it names one this account may open: owned, +/// live, and with no trashed ancestor. Anything else is not found rather +/// than forbidden. +async fn current_folder( + store: &dyn Store, + user_id: &str, + folder_id: Option<&str>, +) -> Result, topcoat::Error> { + let Some(id) = folder_id.filter(|id| !id.is_empty()) else { + return Ok(None); + }; + let Ok(Some(folder)) = store.folder(id).await else { + return Err(not_found().into()); + }; + if folder.owner_id != user_id || folder.deleted_at.is_some() { + return Err(not_found().into()); + } + // Unreachable while any ancestor is trashed: the drive shows no path + // back into it. + let mut parent = folder.parent_id.clone(); + while let Some(id) = parent { + match store.folder(&id).await { + Ok(Some(next)) if next.owner_id == user_id && next.deleted_at.is_none() => { + parent = next.parent_id.clone(); + } + _ => return Err(not_found().into()), + } + } + Ok(Some(folder)) +} + +/// The breadcrumb path, root first, for the open folder. +async fn breadcrumbs(store: &dyn Store, folder: Option<&Folder>) -> Vec { + let mut chain = Vec::new(); + let mut next = folder.cloned(); + while let Some(current) = next { + let parent = match ¤t.parent_id { + Some(id) => store.folder(id).await.ok().flatten(), + None => None, + }; + chain.push(current); + next = parent; + } + chain.reverse(); + chain +} + +/// Every live folder the account holds, with its root-first display path — +/// the move destination picker. Small trees only; the drive is not a +/// filesystem with ten thousand directories. +async fn folder_tree(store: &dyn Store, user_id: &str) -> Vec<(String, String)> { + let mut out = Vec::new(); + // (parent id, path prefix) + let mut queue: Vec<(Option, String)> = vec![(None, String::new())]; + while let Some((parent, prefix)) = queue.pop() { + let Ok(listing) = store.list_children(user_id, parent.as_deref()).await else { + continue; + }; + for folder in listing.folders { + let path = if prefix.is_empty() { + folder.name.clone() + } else { + format!("{prefix} / {}", folder.name) + }; + queue.push((Some(folder.id.clone()), path.clone())); + out.push((folder.id, path)); + } + } + out.sort_by(|a, b| a.1.cmp(&b.1)); + out +} + +fn human_size(bytes: u64) -> String { + const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"]; + let mut size = bytes as f64; + let mut unit = 0; + while size >= 1024.0 && unit < 4 { + size /= 1024.0; + unit += 1; + } + if unit == 0 { + format!("{bytes} {}", UNITS[unit]) + } else { + format!("{size:.1} {}", UNITS[unit]) + } +} +fn page_refusal(cx: &Cx) -> Option { + ["create", "rename", "move", "delete", "upload"] + .iter() + .find_map(|call| refusal_of(cx, call)) +} +/// The just-minted token off the redirect's `?created=` pair, if present. +fn created_token(query: &str) -> Option { + query.split('&').find_map(|pair| { + let (name, value) = pair.split_once('=')?; + (name == "created" && !value.is_empty()).then(|| value.to_string()) + }) +} + +/// `GET /drive?folder=`: one directory. +#[page("/drive")] +async fn drive(cx: &Cx) -> Result { + let user = match require_user(cx).await { + Ok(user) => user, + Err(_) => { + let location = (header::LOCATION, HeaderValue::from_static("/")); + return view! { + cx => + (StatusCode::SEE_OTHER) + (location) + }; + } + }; + let language = lang(cx); + let store = app(cx).store.clone(); + + let wanted = query_params::(cx) + .ok() + .and_then(|query| query.folder.clone()); + let current = current_folder(store.as_ref(), &user.id, wanted.as_deref()).await?; + let crumbs = breadcrumbs(store.as_ref(), current.as_ref()).await; + let listing = match store + .list_children(&user.id, current.as_ref().map(|folder| folder.id.as_str())) + .await + { + Ok(listing) => listing, + Err(_) => return Err(not_found().into()), + }; + let destinations = folder_tree(store.as_ref(), &user.id).await; + let refusal = page_refusal(cx); + // A link minted from this surface redirects back here with the plaintext + // token on `?created=` — rendered once, like the settings page does. + let created = created_token(uri(cx).query().unwrap_or("")); + let origin = app(cx).config.listen_url(); + + let current_id = current + .as_ref() + .map(|folder| folder.id.clone()) + .unwrap_or_default(); + let current_name = current + .as_ref() + .map(|folder| folder.name.clone()) + .unwrap_or_else(|| t(language, Key::Drive).to_string()); + + view! { + cx => + (topbar(cx, NavPage::Drive, &user, language).await?) +
+
+ +
+
+ + + + +
+ if let Some(refusal) = refusal { +

(refusal.message_in(language))

+ } + if let Some(token) = created { +
+

(t(language, Key::LinkCreated))

+
+

(t(language, Key::CopyLinkOnce))

+ +
+
+ } +
+
+

(t(language, Key::FoldersHeading))

+ (format!("{}", listing.folders.len())) +
+
+ if listing.folders.is_empty() { +

(t(language, Key::EmptyFolder))

+ } + for folder in listing.folders.iter() { +
+ (folder.name.clone()) +
+
+ + + + +
+ + + + +
+ + + +
+ } +
+
+
+
+

(t(language, Key::FilesHeading))

+ (format!("{}", listing.files.len())) +
+
+
+ + + (t(language, Key::DropFilesHere)) + +
+ for file in listing.files.iter() { +
+ if file.thumb_state == ThumbState::Ready { + + } else { + + } + (file.name.clone()) + (human_size(file.size_bytes)) +
+
+ + + + +
+ + + + +
+ + + +
+ } +
+
+
+
+ (crate::dropdown::dropdown_script(cx).await?) + (upload_script(cx).await?) + } +} + +/// The upload control's client half: files under 8 MiB ride the form's own +/// multipart post; files at or over it are split into the chunked protocol's +/// calls with a progress bar. +/// +/// The form wears `data-hard` so the soft-nav's multipart replay leaves it +/// alone — two uploaders racing the same bytes would double-insert, and the +/// progress the soft-nav draws knows nothing of chunks. Without script the +/// form posts plainly and the 303 lands back on the folder. +async fn upload_script(cx: &Cx) -> Result { + use topcoat::view::Unescaped; + const JS: &str = "\ + (function () { \ + if (window.__inUpload) { return; } \ + window.__inUpload = true; \ + var LIMIT = 8388608; \ + function bar(box, label) { \ + var wrap = document.createElement('div'); \ + wrap.className = 'upload-progress'; \ + var fill = document.createElement('div'); \ + fill.className = 'upload-progress-fill'; \ + wrap.appendChild(fill); \ + box.appendChild(window.__inAdded(wrap)); \ + if (label) { wrap.setAttribute('aria-label', label); } \ + return fill; \ + } \ + function fail(box, message) { \ + var note = document.createElement('p'); \ + note.className = 'field-error'; \ + note.textContent = message; \ + box.appendChild(window.__inAdded(note)); \ + } \ + async function startChunked(folder, name, size) { \ + var r = await fetch('/api/upload/start', { \ + method: 'POST', \ + headers: { 'content-type': 'application/json', accept: 'application/json' }, \ + body: JSON.stringify({ folder_id: folder || null, name: name, size_bytes: size }) \ + }); \ + var answer = await r.json(); \ + if (!answer.ok) { throw new Error(answer.err || 'start'); } \ + return answer.ok; \ + } \ + async function sendBig(file, folder, fill) { \ + var session = await startChunked(folder, file.name, file.size); \ + var index = 0; \ + for (var off = 0; off < file.size; off += LIMIT, index++) { \ + var piece = file.slice(off, Math.min(file.size, off + LIMIT)); \ + var r = await fetch('/api/upload/' + session.id + '/' + index, { \ + method: 'PUT', \ + headers: { 'content-type': 'application/octet-stream' }, \ + body: piece \ + }); \ + if (!r.ok) { throw new Error('chunk'); } \ + fill.style.width = Math.round(((off + piece.size) / file.size) * 100) + '%'; \ + } \ + var done = await fetch('/api/upload/' + session.id + '/finish', { method: 'POST' }); \ + var fin = await done.json(); \ + if (!fin.ok) { throw new Error((fin.err) || 'finish'); } \ + } \ + document.addEventListener('submit', function (e) { \ + var form = e.target; \ + if (!form || form.id !== 'upload-form') { return; } \ + e.preventDefault(); \ + var input = form.querySelector('.file-upload-input'); \ + var box = form.querySelector('.file-upload-box'); \ + var folder = form.querySelector('input[name=folder_id]').value; \ + var files = input && input.files ? Array.prototype.slice.call(input.files) : []; \ + if (!files.length) { return; } \ + if (form.__inBusy) { return; } \ + form.__inBusy = true; \ + if (input) { input.disabled = true; window.__inOwn(input, [], ['disabled']); } \ + var small = files.filter(function (f) { return f.size < LIMIT; }); \ + var big = files.filter(function (f) { return f.size >= LIMIT; }); \ + var failLabel = form.getAttribute('data-failed-label') || 'upload failed'; \ + var landing = window.location.href; \ + (async function () { \ + try { \ + if (small.length) { \ + var data = new FormData(); \ + data.append('folder_id', folder); \ + small.forEach(function (f) { data.append('file', f, f.name); }); \ + var fill = bar(box); \ + var r = await fetch(form.getAttribute('action'), { \ + method: 'POST', headers: { accept: 'text/html' }, body: data \ + }); \ + fill.style.width = '100%'; \ + landing = r.url || landing; \ + if (!r.ok) { fail(box, failLabel); } \ + } \ + for (var i = 0; i < big.length; i++) { \ + var fill2 = bar(box, big[i].name); \ + await sendBig(big[i], folder, fill2); \ + } \ + } catch (err) { fail(box, failLabel); } \ + input.value = ''; \ + form.__inBusy = false; \ + if (input) { input.disabled = false; } \ + if (window.__inGo) { window.__inGo(landing); } \ + else { window.location.href = landing; } \ + })(); \ + }); \ + })();"; + view! { cx => } +} + +#[derive(serde::Deserialize)] +struct CreateFolderForm { + #[serde(default)] + parent_id: String, + name: String, +} + +/// `POST /api/folder/create`: one folder under the open one, or the root. +#[route(POST "/api/folder/create")] +async fn create_folder(cx: &Cx, Form(input): Form) -> Redirect { + let user = match require_user(cx).await { + Ok(user) => user, + Err(refusal) => return redirect(cx, Some(refusal)), + }; + let store = app(cx).store.clone(); + let parent = if input.parent_id.is_empty() { + None + } else { + Some(input.parent_id.as_str()) + }; + if let Some(id) = parent { + match store.folder(id).await { + Ok(Some(folder)) if folder.owner_id == user.id && folder.deleted_at.is_none() => {} + _ => return redirect(cx, Some(Refusal::NotFound)), + } + } + match store.create_folder(&user.id, parent, &input.name).await { + Ok(_) => redirect(cx, None), + Err(error) => redirect(cx, Some(store_refusal(error))), + } +} + +#[derive(serde::Deserialize)] +struct FolderIdForm { + id: String, +} + +#[derive(serde::Deserialize)] +struct RenameFolderForm { + id: String, + name: String, +} + +#[derive(serde::Deserialize)] +struct MoveFolderForm { + id: String, + #[serde(default)] + parent_id: String, +} + +/// `POST /api/folder/rename`: a new label on an owned folder. +#[route(POST "/api/folder/rename")] +async fn rename_folder(cx: &Cx, Form(input): Form) -> Redirect { + let user = match require_user(cx).await { + Ok(user) => user, + Err(refusal) => return redirect(cx, Some(refusal)), + }; + let store = app(cx).store.clone(); + match store.folder(&input.id).await { + Ok(Some(folder)) if folder.owner_id == user.id && folder.deleted_at.is_none() => {} + _ => return redirect(cx, Some(Refusal::NotFound)), + } + match store.rename_folder(&input.id, &input.name).await { + Ok(_) => redirect(cx, None), + Err(error) => redirect(cx, Some(store_refusal(error))), + } +} + +/// `POST /api/folder/move`: an owned folder under another owned folder, or +/// the root. Into its own descendant is refused, not looped. +#[route(POST "/api/folder/move")] +async fn move_folder(cx: &Cx, Form(input): Form) -> Redirect { + let user = match require_user(cx).await { + Ok(user) => user, + Err(refusal) => return redirect(cx, Some(refusal)), + }; + let store = app(cx).store.clone(); + match store.folder(&input.id).await { + Ok(Some(folder)) if folder.owner_id == user.id && folder.deleted_at.is_none() => {} + _ => return redirect(cx, Some(Refusal::NotFound)), + } + let parent = if input.parent_id.is_empty() { + None + } else { + Some(input.parent_id.as_str()) + }; + if let Some(id) = parent { + match store.folder(id).await { + Ok(Some(folder)) if folder.owner_id == user.id && folder.deleted_at.is_none() => {} + _ => return redirect(cx, Some(Refusal::NotFound)), + } + } + match store.move_folder(&input.id, parent).await { + Ok(_) => redirect(cx, None), + Err(error) => redirect(cx, Some(store_refusal(error))), + } +} + +/// `POST /api/folder/delete`: trash an owned folder — the whole subtree wears +/// the same timestamp, and the bytes wait in the trash for the purge. +#[route(POST "/api/folder/delete")] +async fn delete_folder(cx: &Cx, Form(input): Form) -> Redirect { + let user = match require_user(cx).await { + Ok(user) => user, + Err(refusal) => return redirect(cx, Some(refusal)), + }; + let store = app(cx).store.clone(); + match store.folder(&input.id).await { + Ok(Some(folder)) if folder.owner_id == user.id && folder.deleted_at.is_none() => {} + _ => return redirect(cx, Some(Refusal::NotFound)), + } + match store.delete_folder(&input.id).await { + Ok(_) => redirect(cx, None), + Err(error) => redirect(cx, Some(store_refusal(error))), + } +} diff --git a/crates/in-web/src/dropdown.rs b/crates/in-web/src/dropdown.rs new file mode 100644 index 0000000..3bbfb0f --- /dev/null +++ b/crates/in-web/src/dropdown.rs @@ -0,0 +1,294 @@ +//! The house replacement for the native `` list, and only Chromium's +//! `::picker(select)` lets that popup be themed — Firefox/WebKit never see +//! it, so styling the native popup is not a real cross-browser option. +//! Instead [`dropdown_script`] progressively enhances any `select.status-select` +//! or `select.field-input` already on the page: the native element stays in +//! the DOM (hidden, so its `name`/value still post the same form field +//! unchanged) while a ` + + + } + + + if fresh.admin { +
+

(t(language, Key::AdminPanel))

+
+
+ for listed in &users { +
+ (listed.display_name.clone()) + (listed.email.clone()) + (format!("{} {} {}", human_bytes(listed.used_bytes), t(language, Key::QuotaOf), human_bytes(listed.quota_bytes))) + if listed.admin { + (t(language, Key::AdminBadge)) + } + if listed.disabled { + (t(language, Key::DisabledBadge)) + } +
+ + + + + if listed.id != fresh.id { +
+ + if listed.disabled { + + + } else { + + + } + + } +
+ } +
+
+
+ } + + } +} + +/// The just-minted token off the redirect's `?created=` pair, if present. +fn created_token(query: &str) -> Option { + query.split('&').find_map(|pair| { + let (name, value) = pair.split_once('=')?; + (name == "created" && !value.is_empty()).then(|| value.to_string()) + }) +} + +/// When the link stops opening, or never on its own. +fn expiry_line(language: crate::i18n::Lang, expires_at: Option) -> String { + match expires_at { + Some(at) => format!( + "{} {}", + t(language, Key::ExpiresLabel), + at.format(&time::format_description::well_known::Rfc3339) + .unwrap_or_else(|_| "?".to_string()) + ), + None => t(language, Key::NeverExpires).to_string(), + } +} diff --git a/crates/in-web/src/share.rs b/crates/in-web/src/share.rs new file mode 100644 index 0000000..4d6cbf3 --- /dev/null +++ b/crates/in-web/src/share.rs @@ -0,0 +1,776 @@ +//! Sharing: public links, per-user grants, and the shared-with-me page. +//! +//! `POST /api/share/link/create|revoke` mints and kills bearer links over a +//! file or folder (`can_download`, optional expiry in days; only the token +//! hash is stored). `POST /api/share/user/add|remove` grants and revokes +//! named users the same way. `GET /s/{token}` is public — no auth — +//! rendering the viewer page, the download only when `can_download` allows, +//! and the stored webp preview on `?thumb=1` regardless of the flag; a spent, +//! expired or revoked token answers the dead card, never a stack. +//! `GET /shared` lists what others shared with the reader. +//! +//! Every mutation answers the way `board.rs` in iz does: a 303 back to the +//! page the form was posted from, the refusal (if any) on the redirect's +//! query. The one exception is link creation, whose plaintext token exists +//! only at creation: the redirect carries it once as `?created=` so +//! a browser without script can copy it, and the drive and settings pages +//! render the copy-once banner off that pair. + +use in_core::hash_share_token; +use in_core::store::{ShareKind, Store, StoreError, User}; +use serde::Deserialize; +use time::OffsetDateTime; +use topcoat::Result; +use topcoat::context::Cx; +use topcoat::router::content::Form; +use topcoat::router::request::{headers as request_headers, uri}; +use topcoat::router::response::IntoResponse; +use topcoat::router::{HeaderName, StatusCode, header, page, path_param, route}; +use topcoat::view::view; + +use crate::i18n::{Key, Lang, lang, t}; +use crate::layout::{NavPage, topbar, wordmark}; +use crate::server::{Refusal, app, back_to, require_user}; + +path_param!(token); + +/// A refusal surfaced as a banner: the `?refusal=&on=` pair the +/// mutation redirects carry, rendered only when `on` names one of `calls`. +/// Shared by the trash and settings pages, which own no banner of their own. +pub(crate) async fn refusal_banner(cx: &Cx, language: Lang, calls: &[&str]) -> Result { + let query = uri(cx).query().unwrap_or(""); + let refusal = query_value(query, "refusal").and_then(|code| Refusal::from_code(&code)); + let on = query_value(query, "on").unwrap_or_default(); + let mine = calls.iter().any(|call| *call == on); + view! { + cx => + if mine { + if let Some(refusal) = refusal { + + } + } + } +} + +/// The value of one query pair, if present. +fn query_value(query: &str, key: &str) -> Option { + query.split('&').find_map(|pair| { + let (name, value) = pair.split_once('=')?; + (name == key).then(|| value.to_string()) + }) +} + +type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>; + +/// Back to the posting page, the refusal (if any) on the query. +fn redirect_back(cx: &Cx, nowhere: &str, call: &str, refusal: Option) -> Redirect { + let back = back_to(cx, nowhere); + let separator = if back.contains('?') { '&' } else { '?' }; + let location = match refusal { + Some(refusal) => format!("{back}{separator}refusal={}&on={call}", refusal.code()), + None => back, + }; + Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)])) +} + +/// The store's failure in the route's words. Cross-owner reads answer as +/// not-found — a 404, never a 403 — so a stranger cannot probe which ids +/// exist. +pub(crate) fn refusal_of(error: StoreError) -> Refusal { + match error { + StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound, + StoreError::NameTaken => Refusal::NameTaken, + StoreError::QuotaExceeded => Refusal::QuotaExceeded, + StoreError::AncestorTrashed => Refusal::AncestorTrashed, + _ => Refusal::Unavailable, + } +} + +/// `file` or `folder`, or nothing a route may act on. +fn parse_kind(raw: &str) -> Option { + match raw { + "file" => Some(ShareKind::File), + "folder" => Some(ShareKind::Folder), + _ => None, + } +} + +/// A checkbox-ish flag: absent means the control's default, present is true +/// unless it reads plainly false. +fn parse_flag(raw: Option<&str>, when_absent: bool) -> bool { + match raw { + None => when_absent, + Some(value) => !matches!( + value.trim().to_lowercase().as_str(), + "" | "0" | "false" | "no" | "off" + ), + } +} +/// The link's expiry off `expires_in_days`: absent or empty means no expiry, +/// anything else must name a positive whole number of days. A mistyped value +/// silently minting a never-expiring link would be the wrong default, so it +/// is refused instead. +fn parse_expiry(raw: Option<&str>) -> std::result::Result, Refusal> { + let Some(raw) = raw.map(str::trim).filter(|raw| !raw.is_empty()) else { + return Ok(None); + }; + let days: i64 = raw.parse().map_err(|_| Refusal::Forbidden)?; + if days <= 0 { + return Err(Refusal::Forbidden); + } + let seconds = days.checked_mul(86_400).ok_or(Refusal::Forbidden)?; + OffsetDateTime::now_utc() + .checked_add(time::Duration::seconds(seconds)) + .map(Some) + .ok_or(Refusal::Forbidden) +} + +/// The target the caller must own: present, untrashed, and theirs. Anything +/// else is not-found — a stranger learns nothing about whose it is. +async fn owned_target( + store: &dyn Store, + user: &User, + kind: ShareKind, + target_id: &str, +) -> std::result::Result<(), Refusal> { + let owned = match kind { + ShareKind::File => store + .file(target_id) + .await + .map_err(|_| Refusal::Unavailable)? + .is_some_and(|file| file.owner_id == user.id && file.deleted_at.is_none()), + ShareKind::Folder => store + .folder(target_id) + .await + .map_err(|_| Refusal::Unavailable)? + .is_some_and(|folder| folder.owner_id == user.id && folder.deleted_at.is_none()), + }; + if owned { Ok(()) } else { Err(Refusal::NotFound) } +} +/// The target the caller owns, trashed or not: unsharing a trashed target +/// still revokes the grant, and the grant row outlives the trash either way. +/// Anything else is not-found — a stranger learns nothing about whose it is. +async fn owned_target_for_unshare( + store: &dyn Store, + user: &User, + kind: ShareKind, + target_id: &str, +) -> std::result::Result<(), Refusal> { + let owned = match kind { + ShareKind::File => store + .file(target_id) + .await + .map_err(|_| Refusal::Unavailable)? + .is_some_and(|file| file.owner_id == user.id), + ShareKind::Folder => store + .folder(target_id) + .await + .map_err(|_| Refusal::Unavailable)? + .is_some_and(|folder| folder.owner_id == user.id), + }; + if owned { Ok(()) } else { Err(Refusal::NotFound) } +} + +#[derive(Deserialize)] +struct CreateLinkForm { + kind: String, + target_id: String, + #[serde(default)] + can_download: Option, + #[serde(default)] + expires_in_days: Option, +} + +/// Mints a bearer link. The token is shown once — in the redirect's +/// `?created=` pair, which the drive and settings pages render as the +/// copy-once banner — and never again; only its hash is stored. +#[route(POST "/api/share/link/create")] +async fn create_link(cx: &Cx, Form(input): Form) -> Redirect { + let user = match require_user(cx).await { + Ok(user) => user, + Err(refusal) => return redirect_back(cx, "/settings", "create", Some(refusal)), + }; + let Some(kind) = parse_kind(&input.kind) else { + return redirect_back(cx, "/settings", "create", Some(Refusal::NotFound)); + }; + if let Err(refusal) = owned_target(app(cx).store.as_ref(), &user, kind, &input.target_id).await + { + return redirect_back(cx, "/settings", "create", Some(refusal)); + } + let expires_at = match parse_expiry(input.expires_in_days.as_deref()) { + Ok(expires_at) => expires_at, + Err(refusal) => return redirect_back(cx, "/settings", "create", Some(refusal)), + }; + let created = app(cx) + .store + .create_share_link( + &user.id, + kind, + &input.target_id, + parse_flag(input.can_download.as_deref(), true), + expires_at, + ) + .await; + match created { + Ok(link) => { + let back = back_to(cx, "/settings"); + let separator = if back.contains('?') { '&' } else { '?' }; + let location = format!("{back}{separator}created={}", link.token); + Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)])) + } + Err(error) => redirect_back(cx, "/settings", "create", Some(refusal_of(error))), + } +} + +#[derive(Deserialize)] +struct RevokeLinkForm { + id: String, +} + +/// Kills a bearer link. Only its creator may: anyone else is answered as if +/// it never existed. Revoking twice is not an error. +#[route(POST "/api/share/link/revoke")] +async fn revoke_link(cx: &Cx, Form(input): Form) -> Redirect { + let user = match require_user(cx).await { + Ok(user) => user, + Err(refusal) => return redirect_back(cx, "/settings", "revoke", Some(refusal)), + }; + let store = app(cx).store; + let mine = store + .share_links(&user.id) + .await + .map_err(|_| Refusal::Unavailable); + let Ok(links) = mine else { + return redirect_back(cx, "/settings", "revoke", Some(Refusal::Unavailable)); + }; + if !links + .iter() + .any(|link| link.id == input.id && link.created_by == user.id) + { + return redirect_back(cx, "/settings", "revoke", Some(Refusal::NotFound)); + } + match store.revoke_share_link(&input.id).await { + Ok(()) => redirect_back(cx, "/settings", "revoke", None), + Err(error) => redirect_back(cx, "/settings", "revoke", Some(refusal_of(error))), + } +} + +/// Whether `at` is the link's target or sits under it: every step up must be +/// live, owned by the link's owner, and end at the target. A break anywhere +/// means the browse is outside the share. +async fn under_target(store: &dyn Store, owner_id: &str, target_id: &str, at: &str) -> bool { + let mut current = at.to_string(); + loop { + if current == target_id { + return true; + } + let Ok(Some(folder)) = store.folder(¤t).await else { + return false; + }; + if folder.owner_id != owner_id || folder.deleted_at.is_some() { + return false; + } + match folder.parent_id { + Some(parent) if parent != current => current = parent, + _ => return false, + } + } +} +#[derive(Deserialize)] +struct ShareUserForm { + kind: String, + target_id: String, + #[serde(default)] + email: String, + #[serde(default)] + can_download: Option, +} + +/// Shares one file or folder with one named person. The address is folded to +/// lowercase before lookup; an unknown address is not-found. +#[route(POST "/api/share/user/add")] +async fn add_share(cx: &Cx, Form(input): Form) -> Redirect { + let user = match require_user(cx).await { + Ok(user) => user, + Err(refusal) => return redirect_back(cx, "/settings", "add", Some(refusal)), + }; + let Some(kind) = parse_kind(&input.kind) else { + return redirect_back(cx, "/settings", "add", Some(Refusal::NotFound)); + }; + if let Err(refusal) = owned_target(app(cx).store.as_ref(), &user, kind, &input.target_id).await + { + return redirect_back(cx, "/settings", "add", Some(refusal)); + } + let store = app(cx).store; + let grantee = store + .user_by_email(&input.email.trim().to_lowercase()) + .await + .map_err(|_| Refusal::Unavailable); + let Ok(Some(grantee)) = grantee else { + return redirect_back(cx, "/settings", "add", Some(Refusal::NotFound)); + }; + match store + .add_share_user( + &user.id, + kind, + &input.target_id, + &grantee.id, + parse_flag(input.can_download.as_deref(), true), + ) + .await + { + Ok(()) => redirect_back(cx, "/settings", "add", None), + Err(error) => redirect_back(cx, "/settings", "add", Some(refusal_of(error))), + } +} + +/// Unshares. Removing what was never shared is not an error; only the +/// target's owner may unshare, trashed or not. +#[route(POST "/api/share/user/remove")] +async fn remove_share(cx: &Cx, Form(input): Form) -> Redirect { + let user = match require_user(cx).await { + Ok(user) => user, + Err(refusal) => return redirect_back(cx, "/settings", "remove", Some(refusal)), + }; + let Some(kind) = parse_kind(&input.kind) else { + return redirect_back(cx, "/settings", "remove", Some(Refusal::NotFound)); + }; + if let Err(refusal) = owned_target_for_unshare(app(cx).store.as_ref(), &user, kind, &input.target_id).await + { + return redirect_back(cx, "/settings", "remove", Some(refusal)); + } + let store = app(cx).store; + let grantee = store + .user_by_email(&input.email.trim().to_lowercase()) + .await + .map_err(|_| Refusal::Unavailable); + let Ok(Some(grantee)) = grantee else { + return redirect_back(cx, "/settings", "remove", Some(Refusal::NotFound)); + }; + match store + .remove_share_user(kind, &input.target_id, &grantee.id) + .await + { + Ok(()) => redirect_back(cx, "/settings", "remove", None), + Err(error) => redirect_back(cx, "/settings", "remove", Some(refusal_of(error))), + } +} + +/// The public viewer's query: which folder is browsed, which file is named, +/// whether the bytes (rather than the card) are wanted, and whether the +/// stored webp preview is wanted — the preview a view-only link grants. +struct SharedQuery { + folder: Option, + file: Option, + dl: bool, + thumb: bool, +} + +/// The query off the request's own URI. Unparseable pairs are ignored — +/// a hand-edited query browses nothing rather than failing the page. +fn shared_query(cx: &Cx) -> SharedQuery { + let query = uri(cx).query().unwrap_or(""); + SharedQuery { + folder: query_value(query, "folder"), + file: query_value(query, "file"), + dl: has_flag(query, "dl"), + thumb: has_flag(query, "thumb"), + } +} + +/// Whether the query names the bare flag, as `?dl` or `?dl=1`. +fn has_flag(query: &str, key: &str) -> bool { + query + .split('&') + .any(|pair| pair == key || pair.starts_with(&format!("{key}="))) +} + +/// The dead card: a spent, expired, revoked or never-real token, a trashed +/// target, or a download the link may not open. One answer for all of them — +/// a stranger learns nothing about which tokens exist. +async fn dead_link(cx: &Cx) -> Result { + let language = lang(cx); + view! { + cx => +
+ (wordmark(cx).await?) +

(Refusal::ShareRevoked.message_in(language))

+

(t(language, Key::BackToDrive))

+
+ } +} + +/// The public viewer. No auth: the token in the path is the whole +/// credential. A file target renders its card (and its bytes on `?dl=1` +/// when the link may download); a folder target renders the listing of the +/// browsed folder, downloads gated per file on the same flag. +#[route(GET "/s/{token}")] +async fn shared_link(cx: &Cx) -> topcoat::Result { + let token: &str = path_param::(cx); + let store = app(cx).store; + let now = OffsetDateTime::now_utc(); + let link = store + .resolve_share_link(&hash_share_token(token), now) + .await + .ok() + .flatten(); + let Some(link) = link else { + return dead_link(cx).await.into_response(cx); + }; + let query = shared_query(cx); + match link.kind { + ShareKind::File => { + let file = store + .file(&link.target_id) + .await + .map_err(|_| Refusal::Unavailable); + let Ok(Some(file)) = file else { + return dead_link(cx).await.into_response(cx); + }; + if file.deleted_at.is_some() { + return dead_link(cx).await.into_response(cx); + } + if query.dl { + return download_bytes(cx, store.as_ref(), &file.id, &file.name, &file.mime, link.can_download).await; + } + if query.thumb { + return public_thumb(cx, store.as_ref(), &file.id).await; + } + file_card(cx, &link, &file).await + } + ShareKind::Folder => { + let root = store + .folder(&link.target_id) + .await + .map_err(|_| Refusal::Unavailable); + let Ok(Some(root)) = root else { + return dead_link(cx).await.into_response(cx); + }; + if root.deleted_at.is_some() { + return dead_link(cx).await.into_response(cx); + } + let at = query.folder.as_deref().unwrap_or(&root.id).to_string(); + if !under_target(store.as_ref(), &root.owner_id, &root.id, &at).await { + return dead_link(cx).await.into_response(cx); + } + if query.dl { + let Some(file_id) = query.file.as_deref() else { + return dead_link(cx).await.into_response(cx); + }; + let file = store + .file(file_id) + .await + .map_err(|_| Refusal::Unavailable); + let Ok(Some(file)) = file else { + return dead_link(cx).await.into_response(cx); + }; + if file.deleted_at.is_some() + || file.owner_id != root.owner_id + || file.folder_id.as_deref() != Some(at.as_str()) + { + return dead_link(cx).await.into_response(cx); + } + return download_bytes(cx, store.as_ref(), &file.id, &file.name, &file.mime, link.can_download).await; + } + if query.thumb { + let Some(file_id) = query.file.as_deref() else { + return dead_link(cx).await.into_response(cx); + }; + let file = store + .file(file_id) + .await + .map_err(|_| Refusal::Unavailable); + let Ok(Some(file)) = file else { + return dead_link(cx).await.into_response(cx); + }; + if file.deleted_at.is_some() + || file.owner_id != root.owner_id + || file.folder_id.as_deref() != Some(at.as_str()) + { + return dead_link(cx).await.into_response(cx); + } + return public_thumb(cx, store.as_ref(), &file.id).await; + } + folder_card(cx, store.as_ref(), &link, &root, &at, token).await + } + } +} + +/// The bytes behind a public link. A view-only link answers the dead card +/// here — the same answer as a spent token — so the surface never says which +/// tokens exist. +async fn download_bytes( + cx: &Cx, + store: &dyn Store, + file_id: &str, + name: &str, + mime: &str, + can_download: bool, +) -> topcoat::Result { + use topcoat::router::response::IntoResponse; + use topcoat::router::{HeaderMap, HeaderValue}; + if !can_download { + return dead_link(cx).await.into_response(cx); + } + let bytes = store + .file_bytes(file_id) + .await + .map_err(|_| Refusal::Unavailable); + let Ok(Some(bytes)) = bytes else { + return dead_link(cx).await.into_response(cx); + }; + let mut headers = HeaderMap::new(); + if let Ok(value) = HeaderValue::from_str(mime) { + headers.insert(header::CONTENT_TYPE, value); + } + let disposition = format!("attachment; filename=\"{}\"", safe_name(name)); + if let Ok(value) = HeaderValue::from_str(&disposition) { + headers.insert(header::CONTENT_DISPOSITION, value); + } + headers.insert( + header::CACHE_CONTROL, + HeaderValue::from_static("private, no-cache"), + ); + Ok((StatusCode::OK, headers, bytes).into_response(cx)?) +} + +/// The stored webp preview behind a public link. Unlike the bytes, the +/// preview is what a view-only link grants, so this answers regardless of +/// `can_download` — and anything unservable is the dead card, like every +/// other answer on this surface. Headers twin the `files.rs` thumbnail route. +async fn public_thumb( + cx: &Cx, + store: &dyn Store, + file_id: &str, +) -> topcoat::Result { + use topcoat::router::response::IntoResponse; + use topcoat::router::{HeaderMap, HeaderValue}; + let Ok(Some(bytes)) = store.thumb_bytes(file_id).await else { + return dead_link(cx).await.into_response(cx); + }; + let etag = format!("\"{:x}\"", crate::files::fnv1a(&bytes)); + let mut headers = HeaderMap::new(); + headers.insert( + header::ETAG, + HeaderValue::from_str(&etag).unwrap_or(HeaderValue::from_static("\"0\"")), + ); + headers.insert( + header::CACHE_CONTROL, + HeaderValue::from_static("private, max-age=31536000, immutable"), + ); + headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("image/webp"), + ); + let if_none_match = request_headers(cx) + .get(header::IF_NONE_MATCH) + .and_then(|value| value.to_str().ok()); + if if_none_match == Some(etag.as_str()) { + return Ok((StatusCode::NOT_MODIFIED, headers, Vec::new()).into_response(cx)?); + } + Ok((StatusCode::OK, headers, bytes).into_response(cx)?) +} + +/// A filename safe for a header: quotes and backslashes stripped, never +/// empty. +fn safe_name(name: &str) -> String { + let cleaned: String = name + .chars() + .filter(|c| !c.is_control() && *c != '"' && *c != '\\') + .collect(); + if cleaned.is_empty() { + "file".to_string() + } else { + cleaned + } +} + +/// A shared file's card: its name, size and type, an image preview off the +/// public thumbnail route, and the download while the link allows it. +async fn file_card( + cx: &Cx, + link: &in_core::store::ShareLink, + file: &in_core::store::File, +) -> topcoat::Result { + let language = lang(cx); + let preview = file.mime.starts_with("image/"); + let token_path = current_path(cx); + view! { + cx => +
+ (wordmark(cx).await?) +

(file.name.clone())

+

(format!("{} · {}", file.mime.clone(), crate::settings::human_bytes(file.size_bytes)))

+ if preview { + (file.name.clone()) + } else { +

(t(language, Key::PreviewUnavailable))

+ } + if link.can_download { +

(t(language, Key::Download))

+ } else { +

(t(language, Key::ViewOnly))

+ } +
+ } + .into_response(cx) +} + +/// A shared folder's listing: subfolders then files, downloads gated on the +/// link's flag. Subfolders browse in place under the same token. +async fn folder_card( + cx: &Cx, + store: &dyn Store, + link: &in_core::store::ShareLink, + root: &in_core::store::Folder, + at: &str, + token: &str, +) -> topcoat::Result { + let language = lang(cx); + let here = store + .folder(at) + .await?; + let Some(here) = here else { + return dead_link(cx).await.into_response(cx); + }; + let listing = store + .list_children(&root.owner_id, Some(at)) + .await?; + let base = format!("/s/{token}"); + view! { + cx => +
+ (wordmark(cx).await?) +

(here.name.clone())

+
+

(t(language, Key::FoldersHeading))

+
+ if listing.folders.is_empty() { +

(t(language, Key::EmptyFolder))

+ } + for folder in &listing.folders { +

(folder.name.clone())

+ } +
+
+
+

(t(language, Key::FilesHeading))

+
+ if listing.files.is_empty() { +

(t(language, Key::EmptyFolder))

+ } + for file in &listing.files { +

+ (file.name.clone()) + (format!(" · {}", crate::settings::human_bytes(file.size_bytes))) + if link.can_download { + (t(language, Key::Download)) + } else { + (t(language, Key::ViewOnly)) + } +

+ } +
+
+
+ } + .into_response(cx) +} + +/// The request's own path, without its query: the download links the public +/// cards render point back at the same token. +fn current_path(cx: &Cx) -> String { + let path = uri(cx).path(); + if path.is_empty() { "/".to_string() } else { path.to_string() } +} + +/// Everything others shared with the reader, files and folders in their own +/// groups, newest grant first. The reader's own library never appears here. +#[page("/shared")] +async fn shared(cx: &Cx) -> Result { + let user = match require_user(cx).await { + Ok(user) => user, + Err(refusal) => { + let language = lang(cx); + return view! { + cx => +
+

(refusal.message_in(language))

+

(t(language, Key::BackToDrive))

+
+ }; + } + }; + let language = lang(cx); + let store = app(cx).store; + let items = store + .shares_for_user(&user.id) + .await?; + let mut owners: std::collections::HashMap = std::collections::HashMap::new(); + for item in &items { + if !owners.contains_key(&item.owner_id) { + let name = store + .user(&item.owner_id) + .await + .ok() + .flatten() + .map(|owner| owner.display_name) + .unwrap_or_default(); + owners.insert(item.owner_id.clone(), name); + } + } + view! { + cx => +
+ (topbar(cx, NavPage::Shared, &user, language).await?) +

(t(language, Key::SharedWithMe))

+ if items.is_empty() { +

(t(language, Key::NoSharedItems))

+ } +
+

(t(language, Key::FoldersHeading))

+
+ for item in items.iter().filter(|item| item.kind == ShareKind::Folder) { +

+ (item.name.clone()) + (owner_chip(item, &owners)) + (access_chip(language, item.can_download)) +

+ } +
+
+
+

(t(language, Key::FilesHeading))

+
+ for item in items.iter().filter(|item| item.kind == ShareKind::File) { +

+ (item.name.clone()) + (owner_chip(item, &owners)) + (access_chip(language, item.can_download)) +

+ } +
+
+
+ } +} + +/// `by `, when the owner's name is known. +fn owner_chip( + item: &in_core::store::SharedItem, + owners: &std::collections::HashMap, +) -> String { + match owners.get(&item.owner_id) { + Some(name) if !name.is_empty() => format!(" · {name}"), + _ => String::new(), + } +} + +/// What the grant opens: the download, or the view alone. +fn access_chip(language: Lang, can_download: bool) -> &'static str { + if can_download { + t(language, Key::CanDownload) + } else { + t(language, Key::ViewOnly) + } +} diff --git a/crates/in-web/src/trash.rs b/crates/in-web/src/trash.rs new file mode 100644 index 0000000..b0a75f2 --- /dev/null +++ b/crates/in-web/src/trash.rs @@ -0,0 +1,222 @@ +//! Trash: the soft-deleted shelf and its three mutations. +//! +//! `GET /trash` lists the reader's trashed files and folders. Trashed bytes +//! stay on disk and keep counting toward the quota until the purge. Folder +//! trash and restore cascade to descendants under one timestamp, and an item +//! whose ancestor is still trashed cannot be restored. +//! `POST /api/trash/restore|purge|empty` bring back, destroy one row (plus +//! its bytes), or destroy them all. Purge is the only delete that touches +//! the filesystem. Folder purge has no store method yet (hubbed to Main via +//! the orchestrator) and is refused until it lands. + +use in_core::store::{ShareKind, Store, User}; +use serde::Deserialize; +use topcoat::Result; +use topcoat::context::Cx; +use topcoat::router::content::Form; +use topcoat::router::{HeaderName, StatusCode, header, page, route}; +use topcoat::view::view; + +use crate::i18n::{Key, lang, t}; +use crate::layout::{NavPage, topbar}; +use crate::server::{Refusal, app, back_to, require_user}; +use crate::share::{refusal_banner, refusal_of}; + +/// The reader's own trashed row, or nothing a mutation may touch. +/// Cross-owner ids answer as not-found, never forbidden. +async fn trashed_row( + store: &dyn Store, + user: &User, + kind: ShareKind, + id: &str, +) -> std::result::Result<(), Refusal> { + let owned = match kind { + ShareKind::File => store + .file(id) + .await + .map_err(|_| Refusal::Unavailable)? + .is_some_and(|file| file.owner_id == user.id && file.deleted_at.is_some()), + ShareKind::Folder => store + .folder(id) + .await + .map_err(|_| Refusal::Unavailable)? + .is_some_and(|folder| folder.owner_id == user.id && folder.deleted_at.is_some()), + }; + if owned { Ok(()) } else { Err(Refusal::NotFound) } +} + +type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>; + +/// Back to the trash, the refusal (if any) on the query. +fn redirect_back(cx: &Cx, call: &str, refusal: Option) -> Redirect { + let back = back_to(cx, "/trash"); + let separator = if back.contains('?') { '&' } else { '?' }; + let location = match refusal { + Some(refusal) => format!("{back}{separator}refusal={}&on={call}", refusal.code()), + None => back, + }; + Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)])) +} + +#[derive(Deserialize)] +struct TrashTargetForm { + kind: String, + id: String, +} + +/// Brings one trashed row back. Refused while an ancestor folder is still +/// trashed (as forbidden — there is no code of its own yet), or while a +/// live sibling wears its name. +#[route(POST "/api/trash/restore")] +async fn restore(cx: &Cx, Form(input): Form) -> Redirect { + let user = match require_user(cx).await { + Ok(user) => user, + Err(refusal) => return redirect_back(cx, "restore", Some(refusal)), + }; + let kind = match input.kind.as_str() { + "file" => ShareKind::File, + "folder" => ShareKind::Folder, + _ => return redirect_back(cx, "restore", Some(Refusal::NotFound)), + }; + if let Err(refusal) = trashed_row(app(cx).store.as_ref(), &user, kind, &input.id).await { + return redirect_back(cx, "restore", Some(refusal)); + } + let store = app(cx).store; + let outcome = match kind { + ShareKind::File => store.restore_file(&input.id).await, + ShareKind::Folder => store.restore_folder(&input.id).await, + }; + match outcome { + Ok(()) => redirect_back(cx, "restore", None), + Err(error) => redirect_back(cx, "restore", Some(refusal_of(error))), + } +} + +/// Destroys one trashed file for good: the row goes and the bytes and +/// thumbnail follow. A live file is never purged — trash it first. Folder +/// purge waits on a store method (see the module docs) and is refused. +#[route(POST "/api/trash/purge")] +async fn purge(cx: &Cx, Form(input): Form) -> Redirect { + let user = match require_user(cx).await { + Ok(user) => user, + Err(refusal) => return redirect_back(cx, "purge", Some(refusal)), + }; + let kind = match input.kind.as_str() { + "file" => ShareKind::File, + "folder" => ShareKind::Folder, + _ => return redirect_back(cx, "purge", Some(Refusal::NotFound)), + }; + if let Err(refusal) = trashed_row(app(cx).store.as_ref(), &user, kind, &input.id).await { + return redirect_back(cx, "purge", Some(refusal)); + } + match kind { + ShareKind::File => match app(cx).store.purge_file(&input.id).await { + Ok(true) => redirect_back(cx, "purge", None), + Ok(false) => redirect_back(cx, "purge", Some(Refusal::NotFound)), + Err(error) => redirect_back(cx, "purge", Some(refusal_of(error))), + }, + ShareKind::Folder => match app(cx).store.purge_folder(&input.id).await { + Ok(_) => redirect_back(cx, "purge", None), + Err(error) => redirect_back(cx, "purge", Some(refusal_of(error))), + }, + } +} + +/// Destroys everything the reader trashed, files before folders. +#[route(POST "/api/trash/empty")] +async fn empty(cx: &Cx) -> Redirect { + let user = match require_user(cx).await { + Ok(user) => user, + Err(refusal) => return redirect_back(cx, "empty", Some(refusal)), + }; + match app(cx).store.empty_trash(&user.id).await { + Ok(_) => redirect_back(cx, "empty", None), + Err(error) => redirect_back(cx, "empty", Some(refusal_of(error))), + } +} + +/// The reader's trash: every trashed folder and file, newest trash first, +/// each row carrying its way back and its way gone, plus the button that +/// destroys them all. +#[page("/trash")] +async fn trash(cx: &Cx) -> Result { + let user = match require_user(cx).await { + Ok(user) => user, + Err(refusal) => { + let language = lang(cx); + return view! { + cx => +
+

(refusal.message_in(language))

+

(t(language, Key::BackToDrive))

+
+ }; + } + }; + let language = lang(cx); + let listing = app(cx) + .store + .list_trash(&user.id) + .await?; + view! { + cx => +
+ (topbar(cx, NavPage::Trash, &user, language).await?) +

(t(language, Key::Trash))

+ (refusal_banner(cx, language, &["restore", "purge", "empty"]).await?) + if listing.folders.is_empty() && listing.files.is_empty() { +

(t(language, Key::TrashEmpty))

+ } + if !listing.folders.is_empty() || !listing.files.is_empty() { +
+ + + } + if !listing.folders.is_empty() { +
+

(t(language, Key::FoldersHeading))

+
+ for folder in &listing.folders { +
+ (folder.name.clone()) +
+ + + + +
+ + + + +
+ } +
+
+ } + if !listing.files.is_empty() { +
+

(t(language, Key::FilesHeading))

+
+ for file in &listing.files { +
+ (file.name.clone()) + (crate::settings::human_bytes(file.size_bytes)) +
+ + + + +
+ + + + +
+ } +
+
+ } +
+ } +} diff --git a/crates/in-web/src/upload.rs b/crates/in-web/src/upload.rs new file mode 100644 index 0000000..9ebfa58 --- /dev/null +++ b/crates/in-web/src/upload.rs @@ -0,0 +1,165 @@ +//! The chunked-upload protocol. +//! +//! Four owner-only JSON calls, all UTF-8: `POST /api/upload/start` +//! `{folder_id, name, size_bytes}` answers `{id, chunk_size}` with the +//! server-fixed 8 MiB chunk size (`Refusal::QuotaExceeded` when the quota +//! says no); `PUT /api/upload/{id}/{index}` takes one raw chunk (16 MiB +//! cap, layered in `main.rs`); `POST /api/upload/{id}/finish` assembles the +//! staged chunks, sniffs the mime, moves the bytes to `files/` +//! and answers with the created file id; `POST /api/upload/{id}/abort` +//! drops the session and its staged bytes. Quota is enforced at start *and* +//! at finish. The UI picks this path at 8 MiB and over; below that it posts +//! straight to `POST /files`. +//! +//! Answers are `200` JSON throughout — `{ok: ...}` or `{err: }` — +//! because the caller is script, not a form: there is no page to redirect +//! back to, and the progress bar reads the refusal straight off the body. + +use in_core::store::StoreError; +use topcoat::Result; +use topcoat::context::Cx; +use topcoat::router::content::Json; +use topcoat::router::request::{Bytes, uri}; +use topcoat::router::{path_param, route}; + +use crate::server::{Refusal, app, require_user}; + +path_param!(id); + +/// What the script side reads: the value, or the refusal it failed with. +/// Serialises as `{"ok":...}` / `{"err":...}`. +type Answer = std::result::Result; + +/// A [`StoreError`] in the upload's own words. Another owner's session id +/// answers [`Refusal::NotFound`]: the id space is not theirs to probe. +fn store_refusal(error: StoreError) -> Refusal { + match error { + StoreError::QuotaExceeded => Refusal::QuotaExceeded, + StoreError::UploadExpired => Refusal::UploadExpired, + StoreError::BadChunk => Refusal::BadChunk, + StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound, + StoreError::NameTaken => Refusal::NameTaken, + _ => Refusal::Unavailable, + } +} + +/// The owned, active session the call names, or the refusal its answer +/// carries. Another owner's session is not found rather than forbidden. +async fn owned_session( + cx: &Cx, + id: &str, +) -> std::result::Result { + let user = require_user(cx).await?; + let store = app(cx).store.clone(); + match store.upload_session(id).await { + Ok(Some(session)) if session.owner_id == user.id => Ok(session), + Ok(_) => Err(Refusal::NotFound), + Err(_) => Err(Refusal::Unavailable), + } +} + +#[derive(serde::Deserialize)] +struct StartIn { + folder_id: Option, + name: String, + size_bytes: u64, +} + +#[derive(serde::Serialize)] +struct StartOut { + id: String, + chunk_size: u64, +} + +/// Opens an upload session after the quota pre-check: the declared total +/// must fit the remaining quota, or the browser learns before sending a +/// single chunk. +#[route(POST "/api/upload/start")] +async fn start(cx: &Cx, Json(input): Json) -> Result>> { + let user = match require_user(cx).await { + Ok(user) => user, + Err(refusal) => return Ok(Json(Err(refusal))), + }; + let store = app(cx).store.clone(); + let folder = input.folder_id.as_deref().filter(|id| !id.is_empty()); + if let Some(id) = folder { + match store.folder(id).await { + Ok(Some(row)) if row.owner_id == user.id && row.deleted_at.is_none() => {} + Ok(_) => return Ok(Json(Err(Refusal::NotFound))), + Err(_) => return Ok(Json(Err(Refusal::Unavailable))), + } + } + match store + .create_upload_session(&user.id, folder, &input.name, input.size_bytes) + .await + { + Ok(session) => Ok(Json(Ok(StartOut { + id: session.id, + chunk_size: session.chunk_size, + }))), + Err(error) => Ok(Json(Err(store_refusal(error)))), + } +} + +#[derive(serde::Serialize)] +struct ChunkOut { + received_bytes: u64, + size_bytes: u64, +} + +/// Stages one raw chunk. The store refuses a wrong-sized or out-of-range +/// piece with [`StoreError::BadChunk`] and an expired session with +/// [`StoreError::UploadExpired`]; this layer only gates the owner. +#[route(PUT "/api/upload/{id}/{index}")] +async fn chunk(cx: &Cx, body: Bytes) -> Result>> { + let id: &str = path_param::(cx); + let index: u64 = match uri(cx).path().rsplit('/').next().and_then(|raw| raw.parse().ok()) { + Some(index) => index, + None => return Ok(Json(Err(Refusal::BadChunk))), + }; + let session = match owned_session(cx, id).await { + Ok(session) => session, + Err(refusal) => return Ok(Json(Err(refusal))), + }; + let store = app(cx).store.clone(); + match store.record_chunk(&session.id, index, &body).await { + Ok(session) => Ok(Json(Ok(ChunkOut { + received_bytes: session.received_bytes, + size_bytes: session.size_bytes, + }))), + Err(error) => Ok(Json(Err(store_refusal(error)))), + } +} + +/// Assembles the staged chunks — rechecking the quota, sniffing the mime +/// off the bytes, attempting the thumbnail — and answers the created file +/// id. The chunks stay staged on refusal, so the browser may retry. +#[route(POST "/api/upload/{id}/finish")] +async fn finish(cx: &Cx) -> Result>> { + let id: &str = path_param::(cx); + let session = match owned_session(cx, id).await { + Ok(session) => session, + Err(refusal) => return Ok(Json(Err(refusal))), + }; + let store = app(cx).store.clone(); + match store.finish_upload(&session.id).await { + Ok(file) => Ok(Json(Ok(file.id))), + Err(error) => Ok(Json(Err(store_refusal(error)))), + } +} + +/// Aborts a session: the row says `aborted` and the staged chunks go. +/// Aborting twice — or aborting nothing — is not an error. +#[route(POST "/api/upload/{id}/abort")] +async fn abort(cx: &Cx) -> Result>> { + let id: &str = path_param::(cx); + let session = match owned_session(cx, id).await { + Ok(session) => session, + Err(refusal) => return Ok(Json(Err(refusal))), + }; + let store = app(cx).store.clone(); + match store.abort_upload(&session.id).await { + Ok(_) => Ok(Json(Ok(()))), + Err(error) => Ok(Json(Err(store_refusal(error)))), + } +} diff --git a/crates/in-web/tests/http.rs b/crates/in-web/tests/http.rs new file mode 100644 index 0000000..b69af62 --- /dev/null +++ b/crates/in-web/tests/http.rs @@ -0,0 +1,1898 @@ +//! The drive driven the way a browser drives it: real router, real store, +//! real session cookie, fake im. +//! +//! Auth in tests: the OIDC dance cannot run against a live im, so each test +//! spins a fake one — a bare TCP server answering `POST /introspect` — and +//! signs users in with `in_client::mint_session_cookie` (feature +//! `test-seam`). The token<->claims map is per-test, so one test's session +//! is meaningless to the next. +//! +//! New HTTP tests belong in this file rather than a new `tests/*.rs`: one +//! test binary links and runs once. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; + +use http::{HeaderValue, Request, StatusCode, header}; +use in_core::store::{ShareKind, Store, TursoStore}; +use in_core::{Config, OidcConfig}; +use in_web::server::App; +use topcoat::asset::{AssetBundle, RouterBuilderAssetExt}; +use topcoat::cookie::RouterBuilderCookieExt; +use topcoat::router::{Body, BodyLimit, Router, RouterBuilderDiscoverExt, to_bytes}; +use ulid::Ulid; + +/// The bundle `cargo build -p in-web` + `topcoat asset bundle --bin in-web` +/// write next to the crate's own `target/debug`, not next to the test +/// binary (which lives in `target/debug/deps`) — `AssetBundle::load` looks +/// beside `current_exe` and would miss it, so the path is given explicitly +/// instead. +fn asset_dir() -> PathBuf { + PathBuf::from(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../target/debug/assets" + )) +} + +/// A fake im: answers `POST /introspect` from its token map, `{"active": +/// false}` for anything it does not know. Bare TCP + hand-rolled HTTP/1.1 — +/// just enough for the client's form post. +struct FakeIm { + addr: std::net::SocketAddr, + tokens: Arc>>, +} + +impl FakeIm { + async fn spawn() -> Self { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let tokens: Arc>> = + Arc::new(Mutex::new(HashMap::new())); + let map = tokens.clone(); + tokio::spawn(async move { + loop { + let Ok((socket, _)) = listener.accept().await else { + return; + }; + let map = map.clone(); + tokio::spawn(async move { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let mut socket = socket; + let mut buf = vec![0u8; 8192]; + let mut req = Vec::new(); + // One request after another on the same connection: + // closing it after every answer races the client's + // pool, which may hand out the dead socket for the + // next introspection and read that as signed-out. + loop { + let body_start = loop { + let Ok(n) = socket.read(&mut buf).await else { + return; + }; + if n == 0 { + return; + } + req.extend_from_slice(&buf[..n]); + if let Some(end) = headers_end(&req) { + let head = String::from_utf8_lossy(&req[..end]).to_string(); + let len = content_length(&head); + if req.len() >= end + len { + break end; + } + } + if req.len() > 1_000_000 { + return; + } + }; + let head = String::from_utf8_lossy(&req[..body_start]).to_string(); + let first = head.lines().next().unwrap_or("").to_string(); + // The body may already hold the next pipelined + // request's first bytes; take exactly this one. + let len = content_length(&head); + let body: Vec = req[body_start..body_start + len].to_vec(); + req.drain(..body_start + len); + let answer = answer_for(&map, &first, &body); + let payload = serde_json::to_vec(&answer).unwrap(); + let response = format!( + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n", + payload.len() + ); + if socket.write_all(response.as_bytes()).await.is_err() { + return; + } + if socket.write_all(&payload).await.is_err() { + return; + } + } + }); + } + }); + Self { addr, tokens } + } + + fn url(&self) -> String { + format!("http://{}", self.addr) + } +} + +fn headers_end(req: &[u8]) -> Option { + req.windows(4) + .position(|w| w == b"\r\n\r\n") + .map(|pos| pos + 4) +} + +fn content_length(head: &str) -> usize { + head.lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + (name.trim().eq_ignore_ascii_case("content-length")) + .then(|| value.trim().parse().ok())? + }) + .unwrap_or(0) +} + +/// Percent-decoding, enough for the opaque tokens these tests mint. +fn decode(raw: &str) -> String { + let mut out = String::with_capacity(raw.len()); + let mut bytes = raw.as_bytes().iter(); + while let Some(&b) = bytes.next() { + if b == b'+' { + out.push(' '); + } else if b == b'%' { + let hi = bytes.next().copied().unwrap_or(b'0'); + let lo = bytes.next().copied().unwrap_or(b'0'); + let hex = |c: u8| (c as char).to_digit(16).unwrap_or(0) as u8; + out.push((hex(hi) * 16 + hex(lo)) as char); + } else { + out.push(b as char); + } + } + out +} + +fn answer_for( + map: &Arc>>, + request_line: &str, + body: &[u8], +) -> serde_json::Value { + let mut head = request_line.split_whitespace(); + let is_introspect = head.next() == Some("POST") && head.next() == Some(in_client::introspect_path()); + if !is_introspect { + return serde_json::json!({"active": false}); + } + let text = String::from_utf8_lossy(body).to_string(); + let token = text + .split('&') + .filter_map(|pair| pair.split_once('=')) + .find(|(name, _)| *name == "token") + .map(|(_, value)| decode(value)); + match token.and_then(|token| map.lock().unwrap().get(&token).cloned()) { + Some(claims) => claims, + None => serde_json::json!({"active": false}), + } +} + +/// A throwaway workspace: its own database file, its own fake im, its own +/// router. +struct TestApp { + dir: PathBuf, + router: Router, + store: Arc, + config: Config, + client: in_client::Config, + fake: FakeIm, + stop: tokio::sync::watch::Sender, +} + +impl TestApp { + async fn build() -> Self { + let dir = std::env::temp_dir().join(format!("in-http-{}", Ulid::new())); + std::fs::create_dir_all(&dir).unwrap(); + let db = dir.join("in.db"); + let storage = dir.join("storage"); + let store: Arc = Arc::new( + TursoStore::open(db.to_str().unwrap(), Some(storage.as_path())) + .await + .unwrap(), + ); + let fake = FakeIm::spawn().await; + let client = in_client::Config { + issuer: fake.url(), + client_id: "in-test".to_string(), + client_secret: "s3cr3t".to_string(), + redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(), + cookie_name: "in_session".to_string(), + cookie_key: [7u8; 32], + }; + let config = Config { + database: db.to_str().unwrap().to_string(), + storage, + listen: "127.0.0.1:7655".parse().unwrap(), + live_seconds: 300, + purge_after_days: 30, + default_quota_bytes: 10 * 1024 * 1024 * 1024, + oidc: OidcConfig { + issuer: fake.url(), + client_id: "in-test".to_string(), + client_secret: "s3cr3t".to_string(), + redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(), + }, + ignored: Vec::new(), + defaulted: false, + }; + let (stop, stopping) = tokio::sync::watch::channel(false); + let router = in_client::mount( + Router::builder() + .discover() + .layer(BodyLimit::max(16 * 1024 * 1024).at("/api/upload")) + .layer(BodyLimit::max(64 * 1024 * 1024).at("/files")) + .cookies() + .assets( + AssetBundle::load_dir(asset_dir()) + .expect("run `topcoat asset bundle` before the http suite"), + ), + client.clone(), + ) + .app_context(App { + store: store.clone(), + config: config.clone(), + shutdown: in_web::live::Shutdown(stopping), + }) + .app_context(in_web::live::LiveWindow(std::time::Duration::from_secs(10))) + .build(); + Self { + dir, + router, + store, + config, + client, + fake, + stop, + } + } + + /// Provisions the row and mints a session for it, returning the `Cookie` + /// header value to send. + async fn sign_in(&self, sub: &str, email: &str, name: &str) -> String { + let user = self + .store + .provision_user(sub, email, name, self.config.default_quota_bytes) + .await + .unwrap(); + let token = format!("tok-{}", Ulid::new()); + let exp = time::OffsetDateTime::now_utc() + time::Duration::hours(1); + self.fake.tokens.lock().unwrap().insert( + token.clone(), + serde_json::json!({ + "active": true, + "sub": user.oidc_sub, + "email": user.email, + "name": user.display_name, + "exp": exp.unix_timestamp(), + }), + ); + let value = in_client::mint_session_cookie(&self.client, &token, exp); + format!("in_session={value}") + } + + /// Posts a form the way a hydrated caller does: `Accept: + /// application/json`, no `Referer`. Every mutating `/api/*` route + /// answers `303 See Other` regardless — [`Router::handle`] never follows + /// a redirect, so the answer is read straight off this response. + async fn post(&self, path: &str, cookie: Option<&str>, form: &[(&str, &str)]) -> Answer { + let body = form + .iter() + .map(|(key, value)| format!("{}={}", encode(key), encode(value))) + .collect::>() + .join("&"); + let mut request = Request::builder() + .method("POST") + .uri(path) + .header(header::ACCEPT, "application/json") + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); + if let Some(cookie) = cookie { + request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap()); + } + let response = self + .router + .handle(request.body(Body::from(body)).unwrap()) + .await; + Answer::from_response(response).await + } + + /// Posts JSON the way the upload script does. + async fn post_json( + &self, + path: &str, + cookie: Option<&str>, + value: serde_json::Value, + ) -> Answer { + let mut request = Request::builder() + .method("POST") + .uri(path) + .header(header::ACCEPT, "application/json") + .header(header::CONTENT_TYPE, "application/json"); + if let Some(cookie) = cookie { + request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap()); + } + let response = self + .router + .handle(request.body(Body::from(value.to_string())).unwrap()) + .await; + Answer::from_response(response).await + } + + /// Puts raw bytes the way the upload script sends one chunk. + async fn put_bytes(&self, path: &str, cookie: Option<&str>, bytes: &[u8]) -> Answer { + let mut request = Request::builder() + .method("PUT") + .uri(path) + .header(header::ACCEPT, "application/json") + .header(header::CONTENT_TYPE, "application/octet-stream"); + if let Some(cookie) = cookie { + request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap()); + } + let response = self + .router + .handle(request.body(Body::from(bytes.to_vec())).unwrap()) + .await; + Answer::from_response(response).await + } + + /// Posts a multipart form the way the drive's upload control does, + /// hand-built rather than pulling in a client crate for it: the fields + /// first, in the order given, then one `file` part per file. + async fn post_multipart( + &self, + path: &str, + cookie: Option<&str>, + fields: &[(&str, &str)], + files: &[(&str, &str, &[u8])], + ) -> Answer { + const BOUNDARY: &str = "in-test-boundary"; + let mut body = Vec::new(); + for (name, value) in fields { + body.extend_from_slice( + format!( + "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n" + ) + .as_bytes(), + ); + } + for (filename, content_type, bytes) in files { + body.extend_from_slice( + format!( + "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\nContent-Type: {content_type}\r\n\r\n" + ) + .as_bytes(), + ); + body.extend_from_slice(bytes); + body.extend_from_slice(b"\r\n"); + } + body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes()); + + let mut request = Request::builder().method("POST").uri(path).header( + header::CONTENT_TYPE, + format!("multipart/form-data; boundary={BOUNDARY}"), + ); + if let Some(cookie) = cookie { + request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap()); + } + let response = self + .router + .handle(request.body(Body::from(body)).unwrap()) + .await; + Answer::from_response(response).await + } + + /// Gets a page or a download the way a browser does, raw bytes back + /// untouched — a download's body is not always UTF-8. + async fn get(&self, path: &str, cookie: Option<&str>) -> Raw { + self.get_with(path, cookie, None, None).await + } + + /// Like `get`, but with a `Range` header, for the partial-content path. + async fn get_with_range(&self, path: &str, cookie: Option<&str>, range: &str) -> Raw { + self.get_with(path, cookie, Some(range), None).await + } + + /// Like `get`, but with `If-None-Match`, for the thumbnail revalidate + /// path. + async fn get_with_if_none_match(&self, path: &str, cookie: Option<&str>, etag: &str) -> Raw { + self.get_with(path, cookie, None, Some(etag)).await + } + + async fn get_with( + &self, + path: &str, + cookie: Option<&str>, + range: Option<&str>, + if_none_match: Option<&str>, + ) -> Raw { + let mut request = Request::builder().method("GET").uri(path); + if let Some(cookie) = cookie { + request = request.header(header::COOKIE, HeaderValue::from_str(cookie).unwrap()); + } + if let Some(range) = range { + request = request.header(header::RANGE, range); + } + if let Some(if_none_match) = if_none_match { + request = request.header(header::IF_NONE_MATCH, if_none_match); + } + let response = self + .router + .handle(request.body(Body::empty()).unwrap()) + .await; + let status = response.status(); + let headers = response.headers().clone(); + let header = |name| { + headers + .get(name) + .and_then(|value| value.to_str().ok()) + .map(str::to_string) + }; + let bytes = to_bytes(response.into_body(), usize::MAX) + .await + .unwrap() + .to_vec(); + Raw { + status, + content_type: header(header::CONTENT_TYPE), + disposition: header(header::CONTENT_DISPOSITION), + content_range: header(header::CONTENT_RANGE), + accept_ranges: header(header::ACCEPT_RANGES), + cache_control: header(header::CACHE_CONTROL), + etag: header(header::ETAG), + location: header(header::LOCATION), + bytes, + } + } +} + +impl Drop for TestApp { + fn drop(&mut self) { + let _ = self.stop.send(true); + let _ = std::fs::remove_dir_all(&self.dir); + } +} +/// A mutating call's answer: always a 303, carrying the refusal (or its +/// absence) as JSON — the same body a hydrated caller reads. +struct Answer { + status: StatusCode, + body: String, + location: Option, +} + +impl Answer { + async fn from_response(response: topcoat::router::response::Response) -> Self { + let status = response.status(); + let location = response + .headers() + .get(header::LOCATION) + .and_then(|value| value.to_str().ok()) + .map(str::to_string); + let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + Answer { + status, + location, + body: String::from_utf8(bytes.to_vec()).unwrap(), + } + } + + fn json(&self) -> serde_json::Value { + serde_json::from_str(&self.body).unwrap() + } + + fn refused(&self, code: &str, call: &str) -> bool { + self.status == StatusCode::SEE_OTHER + && self + .location + .as_deref() + .is_some_and(|location| { + location.contains(&format!("refusal={code}")) && location.contains(&format!("on={call}")) + }) + } + + fn accepted(&self) -> bool { + self.status == StatusCode::SEE_OTHER + && self + .location + .as_deref() + .is_some_and(|location| !location.contains("refusal=")) + } +} + +/// A GET answer kept as raw bytes: a page's HTML or a download's file. +struct Raw { + status: StatusCode, + content_type: Option, + disposition: Option, + content_range: Option, + accept_ranges: Option, + cache_control: Option, + etag: Option, + location: Option, + bytes: Vec, +} + +impl Raw { + fn text(&self) -> String { + String::from_utf8(self.bytes.clone()).unwrap() + } +} + +/// Form encoding, enough for the names these tests send. +fn encode(raw: &str) -> String { + let mut out = String::with_capacity(raw.len()); + for byte in raw.bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + out.push(byte as char) + } + b' ' => out.push('+'), + other => out.push_str(&format!("%{other:02X}")), + } + } + out +} + +/// The 1x1 transparent PNG: the smallest thing the thumbnailer must accept. +fn tiny_png() -> Vec { + vec![ + 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, + 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, + 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, + 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, + 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82, + ] +} + +/// The newest live folder with this name under this parent, read straight +/// off the store. +async fn folder_id(app: &TestApp, owner: &str, parent: Option<&str>, name: &str) -> String { + app.store + .list_children(owner, parent) + .await + .unwrap() + .folders + .iter() + .find(|folder| folder.name == name) + .expect("folder was not created") + .id + .clone() +} +/// The token off a creation redirect's `?created=` pair. +fn created_token(location: &str) -> String { + let query = location.split_once('?').map(|(_, query)| query).unwrap_or(""); + query + .split('&') + .filter_map(|pair| pair.split_once('=')) + .find(|(name, _)| *name == "created") + .map(|(_, value)| value.to_string()) + .expect("creation set no token") +} + +async fn file_id(app: &TestApp, owner: &str, name: &str, bytes: &[u8]) -> String { + app.store + .insert_file(owner, None, name, bytes) + .await + .unwrap() + .id +} + +async fn owner_of(app: &TestApp, sub: &str) -> String { + app.store + .provision_user(sub, "x@y.z", "X", app.config.default_quota_bytes) + .await + .unwrap() + .id +} + +#[tokio::test] +async fn drive_redirects_without_session() { + let app = TestApp::build().await; + let page = app.get("/drive", None).await; + assert_eq!(page.status, StatusCode::SEE_OTHER); + assert_eq!(page.location.as_deref(), Some("/")); +} + +#[tokio::test] +async fn folder_crud_and_cycle_is_refused() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-crud", "crud@in.test", "Crud").await; + let user = app + .store + .user_by_oidc_sub("sub-crud") + .await + .unwrap() + .unwrap(); + + let answer = app + .post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "projects")]) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body); + assert_eq!(answer.body, "null", "creating was refused"); + + let projects = folder_id(&app, &user.id, None, "projects").await; + let answer = app + .post( + "/api/folder/create", + Some(&cookie), + &[("parent_id", &projects), ("name", "sub")], + ) + .await; + assert_eq!(answer.body, "null", "creating was refused"); + let sub = folder_id(&app, &user.id, Some(&projects), "sub").await; + + // Nesting `projects` inside its own descendant is refused, not looped. + let answer = app + .post( + "/api/folder/move", + Some(&cookie), + &[("id", &projects), ("parent_id", &sub)], + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + assert!( + answer.body.contains("Forbidden"), + "cycle was not refused: {}", + answer.body + ); + + // A legal move, a rename and a delete all land clean. + let answer = app + .post("/api/folder/move", Some(&cookie), &[("id", &sub), ("parent_id", "")]) + .await; + assert_eq!(answer.body, "null", "moving was refused: {}", answer.body); + let answer = app + .post( + "/api/folder/rename", + Some(&cookie), + &[("id", &sub), ("name", "moved")], + ) + .await; + assert_eq!(answer.body, "null", "renaming was refused: {}", answer.body); + let answer = app + .post("/api/folder/delete", Some(&cookie), &[("id", &sub)]) + .await; + assert_eq!(answer.body, "null", "deleting was refused: {}", answer.body); + + // The drive page names what is left. + let page = app.get("/drive", Some(&cookie)).await; + assert_eq!(page.status, StatusCode::OK); + assert!(page.text().contains("projects"), "drive hides the folder"); +} + +#[tokio::test] +async fn small_upload_round_trip() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-small", "small@in.test", "Small").await; + let user = app + .store + .user_by_oidc_sub("sub-small") + .await + .unwrap() + .unwrap(); + + let bytes = b"hello in"; + let answer = app + .post_multipart( + "/files", + Some(&cookie), + &[("folder_id", "")], + &[("hello.txt", "text/plain", bytes)], + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.location.unwrap_or_default()); + assert!( + !answer.location.as_deref().unwrap_or("").contains("refusal="), + "upload was refused: {}", + answer.location.unwrap_or_default() + ); + + let file = app + .store + .list_children(&user.id, None) + .await + .unwrap() + .files + .into_iter() + .find(|file| file.name == "hello.txt") + .expect("file was not stored"); + assert_eq!(file.mime, "text/plain"); + + let got = app.get(&format!("/file/{}", file.id), Some(&cookie)).await; + assert_eq!(got.status, StatusCode::OK); + assert_eq!(got.bytes, bytes); + assert_eq!(got.accept_ranges.as_deref(), Some("bytes")); + assert!( + got.cache_control.as_deref().unwrap_or("").contains("immutable"), + "missing immutable cache directive" + ); +} + +#[tokio::test] +async fn chunked_upload_round_trip() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-chunk", "chunk@in.test", "Chunk").await; + let user = app + .store + .user_by_oidc_sub("sub-chunk") + .await + .unwrap() + .unwrap(); + + // Two chunks: the 8 MiB server size plus a tail, so the finish assembles + // more than one staged piece. + let total = 8 * 1024 * 1024 + 100; + let mut bytes = Vec::with_capacity(total); + for i in 0..total { + bytes.push((i % 251) as u8); + } + + let answer = app + .post_json( + "/api/upload/start", + Some(&cookie), + serde_json::json!({"folder_id": null, "name": "big.bin", "size_bytes": total}), + ) + .await; + assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); + let started = answer.json(); + let session = started["Ok"]["id"].as_str().expect("start was refused").to_string(); + assert_eq!(started["Ok"]["chunk_size"].as_u64(), Some(8 * 1024 * 1024)); + + let answer = app + .put_bytes( + &format!("/api/upload/{session}/0"), + Some(&cookie), + &bytes[..8 * 1024 * 1024], + ) + .await; + assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); + assert_eq!(answer.json()["Ok"]["received_bytes"].as_u64(), Some(8 * 1024 * 1024)); + + let answer = app + .put_bytes(&format!("/api/upload/{session}/1"), Some(&cookie), &bytes[8 * 1024 * 1024..]) + .await; + assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); + assert_eq!(answer.json()["Ok"]["received_bytes"].as_u64(), Some(total as u64)); + + let answer = app + .post_json( + &format!("/api/upload/{session}/finish"), + Some(&cookie), + serde_json::json!({}), + ) + .await; + assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); + let file_id = answer.json()["Ok"].as_str().expect("finish was refused").to_string(); + + let got = app.get(&format!("/file/{file_id}"), Some(&cookie)).await; + assert_eq!(got.status, StatusCode::OK); + assert_eq!(got.bytes, bytes); + + let row = app.store.file(&file_id).await.unwrap().unwrap(); + assert_eq!(row.owner_id, user.id); +} + +#[tokio::test] +async fn range_request_serves_a_slice() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-range", "range@in.test", "Range").await; + let user = app + .store + .user_by_oidc_sub("sub-range") + .await + .unwrap() + .unwrap(); + + let bytes = b"hello in"; + app.post_multipart( + "/files", + Some(&cookie), + &[("folder_id", "")], + &[("hello.txt", "text/plain", bytes)], + ) + .await; + let file = app + .store + .list_children(&user.id, None) + .await + .unwrap() + .files + .into_iter() + .next() + .unwrap(); + + let slice = app + .get_with_range(&format!("/file/{}", file.id), Some(&cookie), "bytes=0-4") + .await; + assert_eq!(slice.status, StatusCode::PARTIAL_CONTENT); + assert_eq!(slice.bytes, b"hello"); + assert_eq!(slice.content_range.as_deref(), Some("bytes 0-4/8")); + + let past_end = app + .get_with_range(&format!("/file/{}", file.id), Some(&cookie), "bytes=99-") + .await; + assert_eq!(past_end.status, StatusCode::RANGE_NOT_SATISFIABLE); +} + +#[tokio::test] +async fn quota_is_refused_before_and_during_upload() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-quota", "quota@in.test", "Quota").await; + let user = app + .store + .user_by_oidc_sub("sub-quota") + .await + .unwrap() + .unwrap(); + app.store.set_user_quota(&user.id, 10).await.unwrap(); + + let answer = app + .post_json( + "/api/upload/start", + Some(&cookie), + serde_json::json!({"folder_id": null, "name": "too-big.bin", "size_bytes": 100}), + ) + .await; + assert_eq!(answer.status, StatusCode::OK, "{}", answer.body); + assert_eq!( + answer.json()["Err"].as_str(), + Some("QuotaExceeded"), + "start was not refused: {}", + answer.body + ); + + let answer = app + .post_multipart( + "/files", + Some(&cookie), + &[("folder_id", "")], + &[("twenty.txt", "text/plain", b"12345678901234567890")], + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + let location = answer.location.unwrap_or_default(); + assert!( + location.contains("quota-exceeded"), + "small upload was not refused: {location}" + ); +} + +#[tokio::test] +async fn thumbnail_is_served_after_image_upload() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-thumb", "thumb@in.test", "Thumb").await; + let user = app + .store + .user_by_oidc_sub("sub-thumb") + .await + .unwrap() + .unwrap(); + + let png = tiny_png(); + let answer = app + .post_multipart( + "/files", + Some(&cookie), + &[("folder_id", "")], + &[("dot.png", "image/png", &png)], + ) + .await; + assert!( + !answer.location.as_deref().unwrap_or("").contains("refusal="), + "image upload was refused: {}", + answer.location.unwrap_or_default() + ); + let file = app + .store + .list_children(&user.id, None) + .await + .unwrap() + .files + .into_iter() + .find(|file| file.name == "dot.png") + .expect("image was not stored"); + assert_eq!(file.mime, "image/png"); + + let thumb = app.get(&format!("/thumb/{}", file.id), Some(&cookie)).await; + assert_eq!(thumb.status, StatusCode::OK, "no thumbnail served"); + assert_eq!(thumb.content_type.as_deref(), Some("image/webp")); + assert_eq!(&thumb.bytes[0..4], b"RIFF"); + assert_eq!(&thumb.bytes[8..12], b"WEBP"); + + let etag = thumb.etag.clone().expect("no etag on the thumbnail"); + let cached = app + .get_with_if_none_match(&format!("/thumb/{}", file.id), Some(&cookie), &etag) + .await; + assert_eq!(cached.status, StatusCode::NOT_MODIFIED); +} + +#[tokio::test] +async fn cross_owner_answers_not_found() { + let app = TestApp::build().await; + let alice = app.sign_in("sub-alice", "alice@in.test", "Alice").await; + let alice_user = app.store.user_by_oidc_sub("sub-alice").await.unwrap().unwrap(); + let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await; + + app.post("/api/folder/create", Some(&alice), &[("parent_id", ""), ("name", "hers")]) + .await; + let hers = folder_id(&app, &alice_user.id, None, "hers").await; + app.post_multipart( + "/files", + Some(&alice), + &[("folder_id", "")], + &[("hers.txt", "text/plain", b"hers")], + ) + .await; + let file = app + .store + .list_children(&alice_user.id, None) + .await + .unwrap() + .files + .into_iter() + .next() + .unwrap(); + + let bytes = app.get(&format!("/file/{}", file.id), Some(&bob)).await; + assert_eq!(bytes.status, StatusCode::NOT_FOUND); + let thumb = app.get(&format!("/thumb/{}", file.id), Some(&bob)).await; + assert_eq!(thumb.status, StatusCode::NOT_FOUND); + let page = app.get(&format!("/drive?folder={hers}"), Some(&bob)).await; + assert_eq!(page.status, StatusCode::NOT_FOUND); + + let answer = app + .post("/api/folder/rename", Some(&bob), &[("id", &hers), ("name", "theirs")]) + .await; + assert!( + answer.body.contains("NotFound"), + "cross-owner write was not refused as not-found: {}", + answer.body + ); + let answer = app + .post("/api/file/delete", Some(&bob), &[("id", &file.id)]) + .await; + assert!( + answer.body.contains("NotFound"), + "cross-owner delete was not refused as not-found: {}", + answer.body + ); +} + +#[tokio::test] +async fn file_rename_move_and_delete() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-fops", "fops@in.test", "Fops").await; + let user = app.store.user_by_oidc_sub("sub-fops").await.unwrap().unwrap(); + + app.post("/api/folder/create", Some(&cookie), &[("parent_id", ""), ("name", "box")]) + .await; + let boxed = folder_id(&app, &user.id, None, "box").await; + app.post_multipart( + "/files", + Some(&cookie), + &[("folder_id", "")], + &[("note.txt", "text/plain", b"note")], + ) + .await; + let file = app + .store + .list_children(&user.id, None) + .await + .unwrap() + .files + .into_iter() + .next() + .unwrap(); + + let answer = app + .post("/api/file/rename", Some(&cookie), &[("id", &file.id), ("name", "renamed.txt")]) + .await; + assert_eq!(answer.body, "null", "renaming was refused: {}", answer.body); + let answer = app + .post("/api/file/move", Some(&cookie), &[("id", &file.id), ("folder_id", &boxed)]) + .await; + assert_eq!(answer.body, "null", "moving was refused: {}", answer.body); + let moved = app.store.file(&file.id).await.unwrap().unwrap(); + assert_eq!(moved.name, "renamed.txt"); + assert_eq!(moved.folder_id.as_deref(), Some(boxed.as_str())); + + let answer = app.post("/api/file/delete", Some(&cookie), &[("id", &file.id)]).await; + assert_eq!(answer.body, "null", "deleting was refused: {}", answer.body); + let trashed = app.store.file(&file.id).await.unwrap().unwrap(); + assert!(trashed.deleted_at.is_some(), "delete did not trash the file"); + // And the bytes answer 404 once trashed. + let gone = app.get(&format!("/file/{}", file.id), Some(&cookie)).await; + assert_eq!(gone.status, StatusCode::NOT_FOUND); +} + +#[tokio::test] +async fn upload_abort_and_bad_chunk() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-abort", "abort@in.test", "Abort").await; + + let answer = app + .post_json( + "/api/upload/start", + Some(&cookie), + serde_json::json!({"folder_id": null, "name": "never.bin", "size_bytes": 100}), + ) + .await; + let session = answer.json()["Ok"]["id"].as_str().unwrap().to_string(); + + // A short piece is a bad chunk, not a short file. + let answer = app.put_bytes(&format!("/api/upload/{session}/0"), Some(&cookie), b"short").await; + assert_eq!( + answer.json()["Err"].as_str(), + Some("BadChunk"), + "short chunk was not refused: {}", + answer.body + ); + + let answer = app + .post_json(&format!("/api/upload/{session}/abort"), Some(&cookie), serde_json::json!({})) + .await; + assert_eq!(answer.json()["Ok"], serde_json::Value::Null, "{}", answer.body); + + // The finish after the abort finds an expired session, with the chunks + // still staged for nothing. + let answer = app + .post_json(&format!("/api/upload/{session}/finish"), Some(&cookie), serde_json::json!({})) + .await; + assert_eq!( + answer.json()["Err"].as_str(), + Some("UploadExpired"), + "finish after abort was not refused: {}", + answer.body + ); +} + +#[tokio::test] +async fn forced_download_is_attachment() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-dl", "dl@in.test", "Dl").await; + let user = app.store.user_by_oidc_sub("sub-dl").await.unwrap().unwrap(); + + app.post_multipart( + "/files", + Some(&cookie), + &[("folder_id", "")], + &[("readme.txt", "text/plain", b"read me")], + ) + .await; + let file = app + .store + .list_children(&user.id, None) + .await + .unwrap() + .files + .into_iter() + .next() + .unwrap(); + + let inline = app.get(&format!("/file/{}", file.id), Some(&cookie)).await; + assert!( + inline.disposition.as_deref().unwrap_or("").starts_with("inline"), + "text should render inline: {:?}", + inline.disposition + ); + let forced = app.get(&format!("/file/{}?dl=1", file.id), Some(&cookie)).await; + assert_eq!(forced.status, StatusCode::OK); + assert!( + forced.disposition.as_deref().unwrap_or("").starts_with("attachment"), + "?dl=1 did not force attachment: {:?}", + forced.disposition + ); + assert_eq!(forced.bytes, b"read me"); +} + +// -- public links (merged from http_d2.rs; one binary per crate) ------------ + +#[tokio::test] +async fn link_create_public_view_revoke_gone() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let owner = owner_of(&app, "sub-admin").await; + let file = file_id(&app, &owner, "notes.txt", b"hello in").await; + + let answer = app + .post( + "/api/share/link/create", + Some(&admin), + &[ + ("kind", "file"), + ("target_id", &file), + ("can_download", "1"), + ], + ) + .await; + assert!(answer.accepted(), "create refused: {:?}", answer.location); + let token = created_token(answer.location.as_deref().unwrap()); + + // Public: no cookie, the card renders. + let page = app.get(&format!("/s/{token}"), None).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + assert!(page.text().contains("notes.txt"), "{}", page.text()); + + // Public download carries the bytes. + let bytes = app.get(&format!("/s/{token}?dl=1"), None).await; + assert_eq!(bytes.status, StatusCode::OK); + assert_eq!(bytes.bytes, b"hello in"); + + // Revoke: only the id travels; look it up straight off the store. + let id = app.store.share_links(&owner).await.unwrap()[0].id.clone(); + let answer = app + .post("/api/share/link/revoke", Some(&admin), &[("id", &id)]) + .await; + assert!(answer.accepted(), "revoke refused: {:?}", answer.location); + + let gone = app.get(&format!("/s/{token}"), None).await; + assert_eq!(gone.status, StatusCode::OK); + assert!( + gone.text().contains("no longer works"), + "revoked link showed: {}", + gone.text() + ); +} + +#[tokio::test] +async fn expired_link_is_dead() { + let app = TestApp::build().await; + let _ = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let owner = owner_of(&app, "sub-admin").await; + let file = file_id(&app, &owner, "old.txt", b"old").await; + let past = time::OffsetDateTime::now_utc() - time::Duration::days(1); + let created = app + .store + .create_share_link(&owner, ShareKind::File, &file, true, Some(past)) + .await + .unwrap(); + let page = app.get(&format!("/s/{}", created.token), None).await; + assert_eq!(page.status, StatusCode::OK); + assert!( + page.text().contains("no longer works"), + "expired link showed: {}", + page.text() + ); +} + +#[tokio::test] +async fn view_only_link_download_is_dead_card() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let owner = owner_of(&app, "sub-admin").await; + let file = file_id(&app, &owner, "secret.txt", b"eyes only").await; + let answer = app + .post( + "/api/share/link/create", + Some(&admin), + &[ + ("kind", "file"), + ("target_id", &file), + ("can_download", "0"), + ], + ) + .await; + assert!(answer.accepted(), "create refused: {:?}", answer.location); + let token = created_token(answer.location.as_deref().unwrap()); + + let page = app.get(&format!("/s/{token}"), None).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + assert!(page.text().contains("secret.txt"), "{}", page.text()); + + let blocked = app.get(&format!("/s/{token}?dl=1"), None).await; + assert_eq!(blocked.status, StatusCode::OK, "{}", blocked.text()); + assert!( + blocked.text().contains("no longer works"), + "view-only download showed: {}", + blocked.text() + ); +} + +#[tokio::test] +async fn folder_link_lists_and_serves_children() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let owner = owner_of(&app, "sub-admin").await; + let folder = app + .store + .create_folder(&owner, None, "shared") + .await + .unwrap(); + app.store + .insert_file(&owner, Some(&folder.id), "child.txt", b"child bytes") + .await + .unwrap(); + let answer = app + .post( + "/api/share/link/create", + Some(&admin), + &[ + ("kind", "folder"), + ("target_id", &folder.id), + ("can_download", "1"), + ], + ) + .await; + assert!(answer.accepted(), "create refused: {:?}", answer.location); + let token = created_token(answer.location.as_deref().unwrap()); + + let page = app.get(&format!("/s/{token}"), None).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + assert!(page.text().contains("child.txt"), "{}", page.text()); + + let child = app + .store + .list_children(&owner, Some(&folder.id)) + .await + .unwrap() + .files[0] + .id + .clone(); + let bytes = app + .get( + &format!("/s/{token}?folder={}&file={child}&dl=1", folder.id), + None, + ) + .await; + assert_eq!(bytes.status, StatusCode::OK, "{}", bytes.text()); + assert_eq!(bytes.bytes, b"child bytes"); +} + +#[tokio::test] +async fn cross_owner_link_create_is_not_found() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let _ = app.sign_in("sub-bob", "bob@in.test", "Bob").await; + let bob = owner_of(&app, "sub-bob").await; + let file = file_id(&app, &bob, "bobs.txt", b"bob").await; + // Ada names Bob's file: answered as not-found, never forbidden. + let answer = app + .post( + "/api/share/link/create", + Some(&admin), + &[("kind", "file"), ("target_id", &file), ("can_download", "1")], + ) + .await; + assert!(answer.refused("not-found", "create"), "{:?}", answer.location); +} + +// -- per-user shares -------------------------------------------------------- + +#[tokio::test] +async fn per_user_share_lands_in_shared_with_me() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await; + let cara = app.sign_in("sub-cara", "cara@in.test", "Cara").await; + let owner = owner_of(&app, "sub-admin").await; + let file = file_id(&app, &owner, "joint.txt", b"joint").await; + + let answer = app + .post( + "/api/share/user/add", + Some(&admin), + &[ + ("kind", "file"), + ("target_id", &file), + ("email", "BOB@in.test"), + ("can_download", "1"), + ], + ) + .await; + assert!(answer.accepted(), "add refused: {:?}", answer.location); + + let bobs = app.get("/shared", Some(&bob)).await; + assert_eq!(bobs.status, StatusCode::OK, "{}", bobs.text()); + assert!(bobs.text().contains("joint.txt"), "{}", bobs.text()); + + let caras = app.get("/shared", Some(&cara)).await; + assert_eq!(caras.status, StatusCode::OK, "{}", caras.text()); + assert!(!caras.text().contains("joint.txt"), "{}", caras.text()); + + // Unknown addresses are not-found, not a stack. + let answer = app + .post( + "/api/share/user/add", + Some(&admin), + &[ + ("kind", "file"), + ("target_id", &file), + ("email", "ghost@in.test"), + ("can_download", "1"), + ], + ) + .await; + assert!(answer.refused("not-found", "add"), "{:?}", answer.location); + + // Unshare and it leaves Bob's page. + let answer = app + .post( + "/api/share/user/remove", + Some(&admin), + &[ + ("kind", "file"), + ("target_id", &file), + ("email", "bob@in.test"), + ], + ) + .await; + assert!(answer.accepted(), "remove refused: {:?}", answer.location); + let bobs = app.get("/shared", Some(&bob)).await; + assert!(!bobs.text().contains("joint.txt"), "{}", bobs.text()); +} + +// -- trash ------------------------------------------------------------------ + +#[tokio::test] +async fn trash_restore_purge_empty_flows() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let owner = owner_of(&app, "sub-admin").await; + let one = file_id(&app, &owner, "one.txt", b"one").await; + let two = file_id(&app, &owner, "two.txt", b"two").await; + app.store.delete_file(&one).await.unwrap(); + app.store.delete_file(&two).await.unwrap(); + + let page = app.get("/trash", Some(&admin)).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + assert!(page.text().contains("one.txt"), "{}", page.text()); + assert!(page.text().contains("two.txt"), "{}", page.text()); + + // Restore one: it leaves the trash and keeps its bytes. + let answer = app + .post("/api/trash/restore", Some(&admin), &[("kind", "file"), ("id", &one)]) + .await; + assert!(answer.accepted(), "restore refused: {:?}", answer.location); + assert!( + app.store.file(&one).await.unwrap().unwrap().deleted_at.is_none() + ); + + // Purge the other: the row and its bytes go. + let answer = app + .post("/api/trash/purge", Some(&admin), &[("kind", "file"), ("id", &two)]) + .await; + assert!(answer.accepted(), "purge refused: {:?}", answer.location); + assert!(app.store.file(&two).await.unwrap().is_none()); + + // Empty takes the rest. + let three = file_id(&app, &owner, "three.txt", b"three").await; + app.store.delete_file(&three).await.unwrap(); + let answer = app.post("/api/trash/empty", Some(&admin), &[]).await; + assert!(answer.accepted(), "empty refused: {:?}", answer.location); + assert!( + app.store + .list_trash(&owner) + .await + .unwrap() + .files + .is_empty() + ); +} + +#[tokio::test] +async fn restore_under_trashed_ancestor_is_refused() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let owner = owner_of(&app, "sub-admin").await; + let folder = app + .store + .create_folder(&owner, None, "box") + .await + .unwrap(); + let file = app + .store + .insert_file(&owner, Some(&folder.id), "inbox.txt", b"in") + .await + .unwrap(); + app.store.delete_folder(&folder.id).await.unwrap(); + + let answer = app + .post( + "/api/trash/restore", + Some(&admin), + &[("kind", "file"), ("id", &file.id)], + ) + .await; + assert!( + answer.refused("ancestor-trashed", "restore"), + "{:?}", + answer.location + ); + + // The folder itself restores with its child. + let answer = app + .post( + "/api/trash/restore", + Some(&admin), + &[("kind", "folder"), ("id", &folder.id)], + ) + .await; + assert!(answer.accepted(), "restore refused: {:?}", answer.location); +} + +#[tokio::test] +async fn folder_purge_destroys_its_tree() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let owner = owner_of(&app, "sub-admin").await; + let folder = app + .store + .create_folder(&owner, None, "doomed") + .await + .unwrap(); + let file = app + .store + .insert_file(&owner, Some(&folder.id), "gone.txt", b"gone") + .await + .unwrap(); + app.store.delete_folder(&folder.id).await.unwrap(); + + let answer = app + .post( + "/api/trash/purge", + Some(&admin), + &[("kind", "folder"), ("id", &folder.id)], + ) + .await; + assert!(answer.accepted(), "purge refused: {:?}", answer.location); + assert!(app.store.folder(&folder.id).await.unwrap().is_none()); + assert!(app.store.file(&file.id).await.unwrap().is_none()); +} + +// -- search ----------------------------------------------------------------- + +#[tokio::test] +async fn search_scopes_to_owner_and_hides_trashed() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await; + let ada = owner_of(&app, "sub-admin").await; + let bob_id = owner_of(&app, "sub-bob").await; + let mine = file_id(&app, &ada, "quarterly report.txt", b"a").await; + let _ = file_id(&app, &bob_id, "quarterly notes.txt", b"b").await; + let buried = file_id(&app, &ada, "quarterly draft.txt", b"c").await; + app.store.delete_file(&buried).await.unwrap(); + + // Empty query is the prompt, not the whole drive. + let page = app.get("/search", Some(&admin)).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + assert!(!page.text().contains("quarterly report.txt"), "{}", page.text()); + + let page = app.get("/search?q=quarterly", Some(&admin)).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + assert!(page.text().contains("quarterly report.txt"), "{}", page.text()); + assert!(!page.text().contains("quarterly notes.txt"), "{}", page.text()); + assert!(!page.text().contains("quarterly draft.txt"), "{}", page.text()); + assert!(app.store.file(&mine).await.unwrap().is_some()); + + let page = app.get("/search?q=quarterly", Some(&bob)).await; + assert!(page.text().contains("quarterly notes.txt"), "{}", page.text()); + assert!(!page.text().contains("quarterly report.txt"), "{}", page.text()); +} + +// -- settings --------------------------------------------------------------- + +#[tokio::test] +async fn settings_quota_and_disable_guards() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await; + let bob_id = owner_of(&app, "sub-bob").await; + let admin_id = owner_of(&app, "sub-admin").await; + + let page = app.get("/settings", Some(&admin)).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + assert!(page.text().contains("ada@in.test"), "{}", page.text()); + + // Admin sets Bob's quota. + let answer = app + .post( + "/api/settings/quota", + Some(&admin), + &[("user_id", &bob_id), ("quota_bytes", "123456")], + ) + .await; + assert!(answer.accepted(), "quota refused: {:?}", answer.location); + assert_eq!(app.store.user(&bob_id).await.unwrap().unwrap().quota_bytes, 123456); + + // A non-admin is refused the same call. + let answer = app + .post( + "/api/settings/quota", + Some(&bob), + &[("user_id", &bob_id), ("quota_bytes", "999")], + ) + .await; + assert!(answer.refused("forbidden", "quota"), "{:?}", answer.location); + + // Disabling yourself is refused; disabling Bob signs him out. + let answer = app + .post( + "/api/settings/disable", + Some(&admin), + &[("user_id", &admin_id), ("disabled", "1")], + ) + .await; + assert!(answer.refused("forbidden", "disable"), "{:?}", answer.location); + + let answer = app + .post( + "/api/settings/disable", + Some(&admin), + &[("user_id", &bob_id), ("disabled", "1")], + ) + .await; + assert!(answer.accepted(), "disable refused: {:?}", answer.location); + let page = app.get("/settings", Some(&bob)).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + assert!( + !page.text().contains("bob@in.test"), + "disabled account still served: {}", + page.text() + ); +} + +#[tokio::test] +async fn signed_out_mutations_ask_to_sign_in() { + let app = TestApp::build().await; + for (path, call, form) in [ + ( + "/api/share/link/create", + "create", + &[("kind", "file"), ("target_id", "x"), ("can_download", "1")][..], + ), + ("/api/share/link/revoke", "revoke", &[("id", "x")][..]), + ( + "/api/share/user/add", + "add", + &[("kind", "file"), ("target_id", "x"), ("email", "a@b.c")][..], + ), + ( + "/api/trash/restore", + "restore", + &[("kind", "file"), ("id", "x")][..], + ), + ("/api/trash/empty", "empty", &[][..]), + ( + "/api/settings/quota", + "quota", + &[("user_id", "x"), ("quota_bytes", "1")][..], + ), + ] { + let answer = app.post(path, None, form).await; + assert!( + answer.refused("sign-in-first", call), + "{path}: {:?}", + answer.location + ); + } + // A never-real token is the dead card, not a stack. + let page = app.get("/s/never-real-token", None).await; + assert_eq!(page.status, StatusCode::OK); + assert!(page.text().contains("no longer works"), "{}", page.text()); +} + +#[tokio::test] +async fn empty_file_upload_round_trip() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-empty", "empty@in.test", "Empty").await; + let user = app + .store + .user_by_oidc_sub("sub-empty") + .await + .unwrap() + .unwrap(); + + let answer = app + .post_multipart( + "/files", + Some(&cookie), + &[("folder_id", "")], + &[("empty.txt", "text/plain", &[])], + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.location.clone().unwrap_or_default()); + assert!( + !answer.location.as_deref().unwrap_or("").contains("refusal="), + "empty upload was refused: {}", + answer.location.clone().unwrap_or_default() + ); + + let file = app + .store + .list_children(&user.id, None) + .await + .unwrap() + .files + .into_iter() + .find(|file| file.name == "empty.txt") + .expect("empty file was not stored"); + assert_eq!(file.size_bytes, 0); + + let got = app.get(&format!("/file/{}", file.id), Some(&cookie)).await; + assert_eq!(got.status, StatusCode::OK); + assert!(got.bytes.is_empty(), "expected 0 bytes, got {}", got.bytes.len()); +} + +// -- share review regressions (FullSilkworm) ------------------------------------ + +#[tokio::test] +async fn view_only_download_matches_dead_token() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let owner = owner_of(&app, "sub-admin").await; + let file = file_id(&app, &owner, "quiet.txt", b"quiet").await; + let answer = app + .post( + "/api/share/link/create", + Some(&admin), + &[ + ("kind", "file"), + ("target_id", &file), + ("can_download", "0"), + ], + ) + .await; + assert!(answer.accepted(), "create refused: {:?}", answer.location); + let token = created_token(answer.location.as_deref().unwrap()); + + // A view-only download attempt is the dead card — the same answer as a + // token that never existed, so the surface never says which tokens exist. + let blocked = app.get(&format!("/s/{token}?dl=1"), None).await; + let dead = app.get("/s/never-real-token", None).await; + assert_eq!(blocked.status, dead.status, "{}", blocked.text()); + assert_eq!(blocked.status, StatusCode::OK, "{}", blocked.text()); + assert!( + blocked.text().contains("no longer works"), + "view-only download showed: {}", + blocked.text() + ); + assert!( + dead.text().contains("no longer works"), + "dead token showed: {}", + dead.text() + ); +} + +#[tokio::test] +async fn malformed_expiry_is_forbidden() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let owner = owner_of(&app, "sub-admin").await; + let file = file_id(&app, &owner, "lease.txt", b"lease").await; + // Non-numeric, zero and negative values must not mint a link — and must + // never silently mint a never-expiring one. + for raw in ["not-a-number", "0", "-2", "1.5"] { + let answer = app + .post( + "/api/share/link/create", + Some(&admin), + &[ + ("kind", "file"), + ("target_id", &file), + ("can_download", "1"), + ("expires_in_days", raw), + ], + ) + .await; + assert!( + answer.refused("forbidden", "create"), + "{raw:?}: {:?}", + answer.location + ); + } + assert!( + app.store.share_links(&owner).await.unwrap().is_empty(), + "a refused mint left a link behind" + ); + // A positive value still mints an expiring link; an empty one still means + // no expiry. + let answer = app + .post( + "/api/share/link/create", + Some(&admin), + &[ + ("kind", "file"), + ("target_id", &file), + ("can_download", "1"), + ("expires_in_days", "30"), + ], + ) + .await; + assert!(answer.accepted(), "good expiry refused: {:?}", answer.location); + let links = app.store.share_links(&owner).await.unwrap(); + assert_eq!(links.len(), 1); + assert!( + links[0].expires_at.is_some(), + "a 30-day link carries no expiry" + ); + let answer = app + .post( + "/api/share/link/create", + Some(&admin), + &[ + ("kind", "file"), + ("target_id", &file), + ("can_download", "1"), + ("expires_in_days", ""), + ], + ) + .await; + assert!(answer.accepted(), "empty expiry refused: {:?}", answer.location); + let links = app.store.share_links(&owner).await.unwrap(); + assert_eq!(links.len(), 2); + assert!( + links.iter().any(|link| link.expires_at.is_none()), + "an empty expiry should mean no expiry" + ); +} + +#[tokio::test] +async fn unshare_trashed_target_still_revokes() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let bob = app.sign_in("sub-bob", "bob@in.test", "Bob").await; + let owner = owner_of(&app, "sub-admin").await; + let file = file_id(&app, &owner, "doomed.txt", b"doomed").await; + let answer = app + .post( + "/api/share/user/add", + Some(&admin), + &[ + ("kind", "file"), + ("target_id", &file), + ("email", "bob@in.test"), + ("can_download", "1"), + ], + ) + .await; + assert!(answer.accepted(), "add refused: {:?}", answer.location); + let bobs = app.get("/shared", Some(&bob)).await; + assert!(bobs.text().contains("doomed.txt"), "{}", bobs.text()); + + // Trash the target: unsharing must still go through for the owner. + app.store.delete_file(&file).await.unwrap(); + let answer = app + .post( + "/api/share/user/remove", + Some(&admin), + &[("kind", "file"), ("target_id", &file), ("email", "bob@in.test")], + ) + .await; + assert!(answer.accepted(), "remove refused: {:?}", answer.location); + // The grant row is really gone: restoring the file does not bring the + // share back to Bob's page. + app.store.restore_file(&file).await.unwrap(); + let bobs = app.get("/shared", Some(&bob)).await; + assert!(!bobs.text().contains("doomed.txt"), "{}", bobs.text()); +} + +#[tokio::test] +async fn view_only_public_thumb_serves_webp() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let owner = owner_of(&app, "sub-admin").await; + let png = tiny_png(); + let answer = app + .post_multipart( + "/files", + Some(&admin), + &[("folder_id", "")], + &[("dot.png", "image/png", &png)], + ) + .await; + assert!( + !answer.location.as_deref().unwrap_or("").contains("refusal="), + "image upload was refused: {}", + answer.location.unwrap_or_default() + ); + let file = app + .store + .list_children(&owner, None) + .await + .unwrap() + .files + .into_iter() + .find(|file| file.name == "dot.png") + .expect("image was not stored"); + let answer = app + .post( + "/api/share/link/create", + Some(&admin), + &[ + ("kind", "file"), + ("target_id", &file.id), + ("can_download", "0"), + ], + ) + .await; + assert!(answer.accepted(), "create refused: {:?}", answer.location); + let token = created_token(answer.location.as_deref().unwrap()); + // The card previews through the thumb route, never the raw bytes. + let page = app.get(&format!("/s/{token}"), None).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + assert!( + page.text().contains("?thumb=1"), + "card previews off nothing public: {}", + page.text() + ); + assert!( + !page.text().contains("?dl=1"), + "card must not point at the raw bytes: {}", + page.text() + ); + + // View-only still grants the 512px preview: webp bytes, etag revalidates. + let thumb = app.get(&format!("/s/{token}?thumb=1"), None).await; + assert_eq!(thumb.status, StatusCode::OK, "{}", thumb.text()); + assert_eq!(thumb.content_type.as_deref(), Some("image/webp")); + assert_eq!(&thumb.bytes[0..4], b"RIFF"); + assert_eq!(&thumb.bytes[8..12], b"WEBP"); + let etag = thumb.etag.clone().expect("no etag on the public thumbnail"); + let cached = app + .get_with_if_none_match(&format!("/s/{token}?thumb=1"), None, &etag) + .await; + assert_eq!(cached.status, StatusCode::NOT_MODIFIED); + + // The full bytes stay behind the download gate even so. + let blocked = app.get(&format!("/s/{token}?dl=1"), None).await; + assert_eq!(blocked.status, StatusCode::OK, "{}", blocked.text()); + assert!( + blocked.text().contains("no longer works"), + "view-only download showed: {}", + blocked.text() + ); + + // A dead token's thumb is the dead card, not a stack. + let dead = app.get("/s/never-real-token?thumb=1", None).await; + assert_eq!(dead.status, StatusCode::OK, "{}", dead.text()); + assert!( + dead.text().contains("no longer works"), + "dead thumb showed: {}", + dead.text() + ); +} + +#[tokio::test] +async fn a_refused_upload_carries_a_well_formed_query() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-dupe", "dupe@in.test", "Dupe").await; + + // One file in, then the same name again: the refusal redirect must join + // the feedback pairs with `?`, not `&` — a `/drive&refusal=...` Location + // is a different path entirely and 404s (observed live). + for _ in 0..2 { + app.post_multipart( + "/files", + Some(&cookie), + &[("folder_id", "")], + &[("same.txt", "text/plain", b"first or second")], + ) + .await; + } + let answer = app + .post_multipart( + "/files", + Some(&cookie), + &[("folder_id", "")], + &[("same.txt", "text/plain", b"third")], + ) + .await; + let location = answer.location.expect("no Location on the refusal"); + assert_eq!(answer.status, StatusCode::SEE_OTHER); + assert!( + location.starts_with("/drive?"), + "refusal Location was: {location}" + ); + assert!(location.contains("refusal=name-taken"), "{location}"); + + // And the browser that follows it lands on the drive page, not the 404. + let page = app.get(&location, Some(&cookie)).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + assert!(page.text().contains("already taken"), "{}", page.text()); +} diff --git a/public/.gitkeep b/public/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/style/_instrument.scss b/style/_instrument.scss new file mode 100644 index 0000000..3446050 --- /dev/null +++ b/style/_instrument.scss @@ -0,0 +1,283 @@ +// Instrument UI skin — dense, neutral-cool, chrome-quiet. Tokens live in +// main.scss; skin-specific overrides and component rules for +// [data-ui="instrument"] land here. +// +// Cascade note: this file is `@use`d at the TOP of main.scss, before every +// component rule, so any override must out-specify its base rule rather than +// rely on source order. Everything below sits inside the wrapper block, which +// adds one attribute selector (0,1,0) to every rule. + +[data-ui="instrument"] { + + // --- Instrument skin: chrome (topbar, nav) --------------------------------- + + // 44px chrome strip. + .topbar { + height: 44px; + } + + .filterbar { + height: 40px; + } + + // Active nav underlines in accent, not ink. + .topbar-nav-on { + box-shadow: inset 0 -2px 0 var(--accent); + } + + // Active detail tab underlines in accent, same idiom as the topbar nav. + .detail-tab-on { + box-shadow: inset 0 -2px 0 var(--accent); + } + + // --- Instrument skin: board (ruled columns) -------------------------------- + + // Columns are not floating wells; they are panels separated by hairline + // rules. Cards keep surface/1px border/radius-3/no-shadow — the instrument + // tokens already supply all four, so .card itself needs no override. + .board-columns { + gap: 0; + } + + .column { + background: transparent; + border-right: 1px solid var(--border); + + &:last-child { + border-right: none; + } + } + + // --- Instrument skin: chips (status LEDs) ---------------------------------- + + // Tint fills go away; a chip is its colored text plus a 6px LED square. + // Per-variant colors (.chip-overdue etc.) survive untouched — this rule + // never declares `color`. + .chip { + background: transparent; + font-family: var(--font-mono); + font-size: 10px; + font-weight: 500; + letter-spacing: 0.08em; + text-transform: uppercase; + + &::before { + content: ""; + width: 6px; + height: 6px; + margin-right: 6px; + flex: none; + background: currentColor; + } + } + + // --- Instrument skin: avatars (squares) ------------------------------------ + + // Circles become 18px squares; the 2px overlap ring is gone, so assignees + // butt closer. 2px is intentional (below the 3px radius token) — squares + // must not read as chips. + .avatar { + width: 18px; + height: 18px; + border-radius: 2px; + border: none; + } + + .avatar + .avatar { + margin-left: -4px; + } + + // The upload veil squares off with the avatar under it. + .avatar-upload::after { + border-radius: 2px; + } + + // Keep the empty-assignee slot's dashed outline, which the border: none + // above would otherwise silence. + .avatar-none { + border: 1px dashed var(--border-strong); + background: transparent; + } + + // --- Instrument skin: fields & controls ------------------------------------- + + // The primary action is an outlined target, not a filled one. + .primary { + background: transparent; + border: 1px solid var(--accent-border); + color: var(--accent); + + &:hover { + background: transparent; + border-color: var(--accent); + color: var(--accent); + } + } + + // Quiet stays outline-muted; only the fill drops so fields and buttons + // share one flat ground. + .quiet { + background: transparent; + } + + // --- Instrument skin: mono metadata idiom ----------------------------------- + + // Timestamps, card meta and member statuses join .field-label/.detail-label + // in tracked uppercase mono. (Emails stay sentence-case — .member-address + // keeps its mono but gains no uppercase; uppercase addresses hurt reading.) + .comment-when { + font-size: 10px; + letter-spacing: 0.08em; + text-transform: uppercase; + } + + .card-comments, + .card-deadline { + letter-spacing: 0.08em; + text-transform: uppercase; + } + + .member-status { + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.08em; + text-transform: uppercase; + } + + .member-you { + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.08em; + text-transform: uppercase; + border-radius: var(--radius-sm); + } + + // --- Instrument skin: density & spacing -------------------------------------- + + // (Deliberately sparse: density lives in the chrome heights, the gapless + // ruled columns and the square avatars above. Token values — control + // heights, radii, shadows — already carry the rest.) + + // --- Instrument skin: activity log ----------------------------------------- + + .log-row { + padding: 6px 2px; + } + + // --- Instrument skin: settings rail ----------------------------------------- + + .settings-sections { width: 200px; } + + .settings-section-link { + font-size: 13px; + letter-spacing: normal; + text-transform: none; + + &.active { + background: var(--row-hover); + box-shadow: inset 2px 0 0 var(--accent); + } + } + +} + +// -- task detail: 560px side panel over the board ---------------------------- +// The board stays live underneath; the panel docks right and dims the board +// through the scrim. The base `.modal-task` only fixes the frame — this rule +// moves it out of the centered flow and gives it the panel geometry. +[data-ui="instrument"] .modal-scrim:has(> .modal-task) { + background: color-mix(in srgb, var(--scrim) 65%, transparent); + justify-content: flex-end; + padding: 0; +} + +[data-ui="instrument"] .modal-task { + position: fixed; + top: 0; + right: 0; + bottom: 0; + width: 560px; + max-width: 100%; + max-height: none; + background: var(--surface); + border: none; + border-radius: 0; + box-shadow: var(--shadow-3); +} + +// Header: key + title left (stacked), Esc and the close cross right. The +// header's own state chip is suppressed — status lives in the body's field +// grid. The tab strip sits directly under it, so the header itself carries +// no bottom rule any more. +[data-ui="instrument"] .modal-task .detail-head { + align-items: flex-start; + gap: 12px; + padding: 14px 16px; +} + +[data-ui="instrument"] .detail-tabs { + padding: 0 16px; +} + +[data-ui="instrument"] .detail-state, +[data-ui="instrument"] .detail-board { + display: none; +} + +[data-ui="instrument"] .detail-body { + flex: 1; + min-height: 0; + overflow-y: auto; + padding: 20px; +} + +[data-ui="instrument"] .detail-title { + font-size: 20px; +} + +// The fields ride in the masthead, so they carry its inset themselves. +[data-ui="instrument"] .detail-fields { + gap: 10px; + padding: 0 16px 14px; + margin-top: 14px; +} + +// Blocks run down the panel body below the title; only the composer pins. +[data-ui="instrument"] .detail-block { + margin-top: 18px; +} + +// Pinned at the panel's foot, wearing the composer's rule and padding: the +// two are the same kind of thing, a bar the body scrolls beneath. +[data-ui="instrument"] .detail-foot { + padding: 14px 20px; + margin-top: 0; + border-top: 1px solid var(--border); +} + +// Composer is the last child of `.modal-task` (outside `.detail-body`), so on +// the flex panel it stays pinned while the body above scrolls. +[data-ui="instrument"] .comment-composer { + flex: none; + padding: 14px 20px; + border-top: 1px solid var(--border); +} +// -- mobile (narrow viewports) ----------------------------------------------- +// Geometry that the skin sets with [data-ui]-prefixed rules and that the +// shared mobile layer in main.scss cannot out-specify. +@media (max-width: 620px) { + // The rail is a strip; its width is a desktop's and its active rule runs + // under the section, not beside it. + [data-ui="instrument"] .settings-sections { width: auto; } + + [data-ui="instrument"] .settings-section-link.active { + background: none; + box-shadow: inset 0 -2px 0 var(--accent); + } + + // The filterbar wraps at this width; the skin's fixed 40px would clip it. + [data-ui="instrument"] .filterbar { height: auto; } + + // A phone carries no Escape key; the hint is chrome for a keyboard. + [data-ui="instrument"] .modal-task .detail-esc { display: none; } +} diff --git a/style/_ledger.scss b/style/_ledger.scss new file mode 100644 index 0000000..1343074 --- /dev/null +++ b/style/_ledger.scss @@ -0,0 +1,503 @@ +// Ledger UI skin — warm paper, hairline rules, serif display (Newsreader). +// Tokens live in main.scss; skin-specific overrides and component rules for +// [data-ui="ledger"] land here. + +// Every selector carries the [data-ui="ledger"] prefix (one nested block +// below). That attribute+class specificity outranks the same-name class +// rules in main.scss, so the order of the @use never matters. + +[data-ui="ledger"] { + // --- Ledger skin: typography ------------------------------------------------- + + // The display face carries named things: page/board/panel titles, task + // titles, people. Keys, dates, counts and labels stay IBM Plex Mono 10px + // uppercase — main.scss's metadata idiom is left alone, and so is the + // wordmark, which is the same lockup on both skins. + .auth-title, + .settings-title, + .detail-title, + .title-input, + .panel-title, + .column-name, + .card-title, + .member-name { + font-family: var(--font-display); + } + + .settings-title { font-size: 22px; } + .panel-title { font-size: 15px; } + .card-title { font-size: 16px; } + + // --- Ledger skin: rules & ornaments (no boxes) ------------------------------- + + // Panels and cards give up their chrome: the paper itself is the surface + // and a hairline separates entries. Section heads sit on a 2px ink rule. + .panel { + background: transparent; + border: none; + box-shadow: none; + } + + .panel-head { + border-bottom: 2px solid var(--rule-strong); + padding: 0 0 10px; + } + + .auth-card { + background: transparent; + border: none; + box-shadow: none; + padding: 0; + } + + .column { + background: transparent; + border-radius: 0; + } + + .column-empty { + background: transparent; + border-color: var(--border-soft); + } + + .column-head { + padding: 2px 4px 8px; + border-bottom: 2px solid var(--rule-strong); + } + + // A card is an entry in the ledger: no box, a hairline under it, and the + // hover darkens that rule instead of flooding a background. + .card { + background: transparent; + border: none; + border-bottom: 1px solid var(--border); + border-radius: 0; + box-shadow: none; + padding: 12px 2px 14px 2px; + transition: border-color var(--dur-fast) var(--ease); + + &:hover { + background: transparent; + border-bottom-color: var(--rule-strong); + } + } + + .card-done { + background: transparent; + + .card-title { text-decoration: line-through; } + } + + // Ledger entries stack into a continuous ruled column — no gaps between rows. + .column-cards { + gap: 0; + } + + .rule-row { + background: transparent; + border: none; + border-bottom: 1px solid var(--border); + border-radius: 0; + padding: 14px 2px; + + &-off { background: transparent; } + } + + .tag-row { + background: transparent; + border: none; + border-bottom: 1px solid var(--border); + border-radius: 0; + padding: 14px 2px; + } + + // Activity log reads as a ruled ledger column too: no boxes, the actor + // named in the display face like .member-name. + .log-row { + border-bottom: 1px solid var(--border); + } + + .log-actor { + font-family: var(--font-display); + } + + // --- Ledger skin: baseline header -------------------------------------------- + + .topbar { + background: transparent; + border-bottom: 1px solid var(--rule-strong); + } + + .topbar-nav-on { + border-bottom: 2px solid var(--rule-strong); + box-shadow: none; + } + + .detail-tab-on { + border-bottom: 2px solid var(--ink); + box-shadow: none; + } + + // --- Ledger skin: chips as inked text ---------------------------------------- + + .chip { + display: inline-flex; + align-items: baseline; + height: auto; + padding: 0; + background: transparent; + border: none; + border-bottom: 1px dotted currentColor; + border-radius: 0; + font-family: var(--font-mono); + font-size: 10px; + font-weight: 500; + letter-spacing: 0.08em; + text-transform: uppercase; + + // The tint fills and boxes go; the hue stays on as the ink color. + &-overdue, + &-blocked, + &-role, + &-admin, + &-connected, + &-off { background: transparent; } + + &-role, + &-admin { border: none; border-bottom: 1px dotted currentColor; } + + &-role, + &-admin, + &-connected, + &-off { text-transform: uppercase; } + } + + // --- Ledger skin: controls ----------------------------------------------------- + + // Outlined-ink controls; the primary action is set in solid ink with paper + // text, inverting cleanly in the dark set because both sides are tokens. + .primary { + background: var(--ink); + border-color: var(--ink); + color: var(--bg); + + &:hover { + background: var(--ink-soft); + border-color: var(--ink-soft); + color: var(--bg); + } + } + + .auth-submit, + .edit-save, + .comment-post { + background: var(--ink); + color: var(--bg); + } + + .auth-submit:hover, + .edit-save:hover, + .comment-post:hover { + background: var(--ink-soft); + } + + .quiet { + background: transparent; + border-color: var(--ink-soft); + + &:hover { + border-color: var(--ink); + color: var(--ink); + } + } + + .quiet-danger { + border-color: var(--danger); + + &:hover { + border-color: var(--danger); + background: transparent; + } + } + + .detail-delete { + background: transparent; + border-color: var(--danger); + } + + // Fields rule themselves onto the paper: transparent ground, ink outline. + .auth-input, + .field-input, + .title-input { + background: transparent; + border-color: var(--ink-soft); + + &:focus-visible { + background: transparent; + border-color: var(--ink); + } + + &:disabled { background: transparent; } + } + + .auth-locked, + .field-box, + .status-form { + background: transparent; + border-color: var(--ink-soft); + } + + // --- Ledger skin: toggles ------------------------------------------------------ + + // The switch becomes what a mark is on paper: an empty ink square when + // off, a filled one when on. The knob has no role here. + .rule-switch { + width: 14px; + height: 14px; + border: 1px solid var(--ink); + border-radius: 0; + background: transparent; + + .rule-switch-knob { display: none; } + } + + .rule-switch-on { background: var(--ink); } +} + +// -- task detail: its own page ------------------------------------------------ +// No chrome, no floating card: the modal opens as an opaque paper page. The +// scrim carries the paper ground and the invisible panning; the column is +// static content on top of it, so nothing inside ever scrolls or shows a +// scrollbar. +[data-ui="ledger"] .modal-scrim:has(> .modal-task) { + background: var(--bg); + justify-content: center; + // Neither top nor bottom padding: the sticky masthead and foot carry the + // page's margins in their own padding, so both sit flush on the pan + // surface's edges instead of floating with text showing past them. + padding: 0 40px; +} + +[data-ui="ledger"] .modal-task { + position: static; + width: 720px; + max-width: 100%; + max-height: none; + overflow: visible; + display: block; + background: transparent; + border: none; + border-radius: 0; + box-shadow: none; +} + +[data-ui="ledger"] .detail-body { + overflow: visible; +} + +// Meta row: key + state chip left, `<- Board` right. The panel chrome — Esc +// hint, close cross — and the body's status fieldbox (the chip already says +// it) are suppressed. +[data-ui="ledger"] .modal-task .detail-head { + align-items: center; + gap: 12px; + padding: 0; +} + +[data-ui="ledger"] .detail-tabs { + padding: 0; + margin-top: 14px; +} + +// The masthead holds at the top of the paper: the task names itself however +// far down the comments you are. +[data-ui="ledger"] .detail-mast { + position: sticky; + top: 0; + z-index: 2; + padding: 36px 0 6px; + background: var(--bg); +} + +[data-ui="ledger"] .modal-task .detail-esc, +[data-ui="ledger"] .modal-task .detail-close, +[data-ui="ledger"] .detail-body .detail-field-status { + display: none; +} + +// Dependency rows lose the card chrome - the page reads as ruled paper. +[data-ui="ledger"] .dep-row { + border: 0; + border-bottom: 1px solid var(--border); + border-radius: 0; + background: transparent; +} + +[data-ui="ledger"] .modal-task .detail-key { + font-size: 10px; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--ink); + text-decoration: underline dotted; + text-underline-offset: 3px; +} + +[data-ui="ledger"] .detail-state { + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +[data-ui="ledger"] .detail-state .field-box, +[data-ui="ledger"] .detail-state .status-form { + height: auto; + padding: 0; + background: transparent; + border: none; + font: inherit; + color: var(--ink); +} + +[data-ui="ledger"] .detail-state .status-select { + width: auto; + flex: none; + font: inherit; + text-transform: uppercase; +} + +[data-ui="ledger"] .detail-state .status-dot { + display: none; +} + +[data-ui="ledger"] .detail-board { + margin-left: auto; + font-size: 10px; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--ink); + background: transparent; + border: none; + height: auto; +} + +// Serif title over a heavy rule; the edit form gets the same rule so the +// title area holds still while editing. The title now lives in the header, +// stacked under the key, ahead of the tab strip. +[data-ui="ledger"] .detail-head .detail-title, +[data-ui="ledger"] .title-form { + padding-bottom: 10px; + border-bottom: 2px solid var(--ink); +} + +[data-ui="ledger"] .detail-title { + font-family: var(--font-serif, Georgia, serif); + font-size: 32px; + font-weight: 400; + line-height: 1.15; + letter-spacing: 0; +} + +[data-ui="ledger"] .title-input { + height: auto; + padding: 0; + border: none; + background: transparent; + font-family: var(--font-serif, Georgia, serif); + font-size: 32px; + font-weight: 400; +} + +// Hairline ruled rows instead of boxed controls. +[data-ui="ledger"] .detail-fields { + display: block; + padding: 0; + margin-top: 14px; + border-top: 1px solid var(--border); +} + +[data-ui="ledger"] .detail-field { + display: flex; + flex-direction: row; + align-items: baseline; + gap: 16px; + padding: 10px 0; + border-bottom: 1px solid var(--border); +} + +[data-ui="ledger"] .detail-field > .detail-label { + flex: none; + width: 130px; +} + +[data-ui="ledger"] .detail-field .field-box, +[data-ui="ledger"] .detail-field .status-form { + background: transparent; + border: none; + border-radius: 0; + padding: 0; + height: auto; +} + +[data-ui="ledger"] .detail-field .status-dot { + display: none; +} + +// Long-form sections run as prose on paper. +[data-ui="ledger"] .detail-block { + margin-top: 24px; +} + +[data-ui="ledger"] .comment-list { + border-top: 1px solid var(--border); +} + +// Composer sits in the flow at the end of the page — the body above is +// static, so it simply follows the sections. +// The page pans, but the way out must not pan with it. The foot and the +// composer hold at the bottom of the paper with the ground under them, so a +// description or a comment run of any length still ends within reach. +[data-ui="ledger"] .detail-foot, +[data-ui="ledger"] .comment-composer { + position: sticky; + bottom: 0; + margin-top: 24px; + padding: 16px 0 36px; + background: var(--bg); + border-top: 1px solid var(--border); +} + +// Settings rail: a narrower column, mono/uppercase stays, the active section +// marked with an ink rule rather than a fill. +[data-ui="ledger"] .settings-sections { + width: 170px; +} + +[data-ui="ledger"] .settings-section-link.active { + border-bottom: 2px solid var(--ink); +} +// -- mobile (narrow viewports) ----------------------------------------------- +// Geometry that the skin sets with [data-ui]-prefixed rules and that the +// shared mobile layer in main.scss cannot out-specify. +@media (max-width: 620px) { + // The paper page keeps its mast and foot flush; only the side margins give. + [data-ui="ledger"] .modal-scrim:has(> .modal-task) { padding: 0 12px; } + + [data-ui="ledger"] .detail-mast { padding: 20px 0 6px; } + + [data-ui="ledger"] .detail-title, + [data-ui="ledger"] .title-input { font-size: 24px; } + + // The labeled rows stack: no third of a phone holds label and value side + // by side. + [data-ui="ledger"] .detail-field { + flex-direction: column; + align-items: stretch; + gap: 4px; + } + + [data-ui="ledger"] .detail-field > .detail-label { width: auto; } + + // The rail is a strip; the 170px column is a desktop's. + [data-ui="ledger"] .settings-sections { width: auto; } +} diff --git a/style/main.scss b/style/main.scss new file mode 100644 index 0000000..770de7c --- /dev/null +++ b/style/main.scss @@ -0,0 +1,4297 @@ +// Design tokens — two design languages selected by : +// +// instrument dense, neutral-cool tool (the default; the bare :root in the +// first block doubles as its light set and as a fallback for any +// document that somehow reaches this stylesheet without data-ui) +// ledger warm paper, hairline rules, serif display face +// +// data-theme="dark" (settings.rs SaveProfileForm.theme) flips either language. +// Component rules below read only these custom properties; the per-UI skins +// (_instrument.scss, _ledger.scss) add overrides on top. +@use "instrument"; +@use "ledger"; + +// Instrument, light: warm-gray ground, quiet borders, shared accent family. +:root, +[data-ui="instrument"] { + color-scheme: light; + --bg: #f2f2f0; + --surface: #fbfbfa; + --border: #dcdcd8; + --border-strong: #d0d0cb; + --ink: #1a1b1d; + --muted: #6b7078; + --muted-soft: #6b7078; + --accent: #46557b; + --accent-tint: #eef0f5; + --accent-ink: #2f3c5c; + + --field-bg: #f5f5f3; + --surface-sunken: #e9e9e7; + --surface-muted: #f5f5f3; + --ink-soft: #3d4045; + --row-hover: #ececea; + --panel-sunken: #eeeeec; + --border-soft: #d3d3ce; + --scrim: rgba(26, 27, 29, 0.46); + + --danger: #a04a24; + --danger-tint: #f9ece4; + --danger-tint-soft: #fdf6f2; + --danger-tint-alt: #fbf1ec; + --danger-border: #e8c9b8; + --danger-border-soft: #eddcd3; + --danger-border-alt: #ecd0bf; + + --warn-ink: #7a5c1e; + --warn-tint: #f7f0dd; + --warn-tint-soft: #fdfaf1; + --warn-border: #e6d7ae; + + --positive: #5c7b46; + --positive-ink: #4a6636; + --positive-tint: #eef3e9; + --positive-border: #d3e0c6; + + --accent-strong: #5a6a94; + --accent-border: #d6dbe8; + --accent-border-strong: #d8dce6; + + --avatar-tone-1: #7b6846; + --avatar-tone-3: #7b4655; + --avatar-tone-4: #46707b; + + --violet-tint: #f1eaf7; + --violet-border: #ddc4ec; + --violet-ink: #6a3f82; + + --font-sans: system-ui, sans-serif; + --font-mono: 'IBM Plex Mono', ui-monospace, monospace; + --font-display: var(--font-sans); + + --control-h: 32px; + --control-h-lg: 40px; + --rule-strong: #d0d0cb; + + --radius: 3px; + --radius-sm: var(--radius); + --radius-md: 3px; + --radius-lg: 3px; + --topbar-height: 56px; + + --shadow-1: none; + --shadow-2: none; + --shadow-3: none; + + --dur-fast: 120ms; + --ease: ease-out; +} + +// Instrument, dark: near-black neutral-cool; tint fills go translucent and +// tint borders go alpha so the ground shows through. +[data-ui="instrument"][data-theme="dark"] { + color-scheme: dark; + --bg: #0d0e10; + --surface: #14161a; + --border: #23262c; + --border-strong: #2e323a; + --ink: #e6e4de; + --muted: #7d8590; + --muted-soft: #4a4f58; + --accent: #8ba1e8; + --accent-tint: rgba(139, 161, 232, 0.14); + --accent-ink: #b9c6ee; + + --field-bg: #101216; + --surface-sunken: #101216; + --surface-muted: #0f1013; + --ink-soft: #c9c7c0; + --row-hover: #1a1d22; + --panel-sunken: #101216; + --border-soft: #1f2226; + --scrim: rgba(0, 0, 0, 0.75); + + --danger: #e0906a; + --danger-tint: rgba(224, 144, 106, 0.13); + --danger-tint-soft: rgba(224, 144, 106, 0.07); + --danger-tint-alt: rgba(224, 144, 106, 0.05); + --danger-border: rgba(224, 144, 106, 0.45); + --danger-border-soft: rgba(224, 144, 106, 0.3); + --danger-border-alt: rgba(224, 144, 106, 0.35); + + --warn-ink: #d4b16a; + --warn-tint: rgba(212, 177, 106, 0.14); + --warn-tint-soft: rgba(212, 177, 106, 0.07); + --warn-border: rgba(212, 177, 106, 0.4); + + --positive: #9db98a; + --positive-ink: #b4cba3; + --positive-tint: rgba(157, 185, 138, 0.13); + --positive-border: rgba(157, 185, 138, 0.4); + + --accent-strong: #7e93d9; + --accent-border: #3a4152; + --accent-border-strong: #2b3b63; + + --avatar-tone-1: #937d58; + --avatar-tone-3: #96606e; + --avatar-tone-4: #5b93a1; + + --violet-tint: rgba(185, 138, 151, 0.14); + --violet-border: rgba(185, 138, 151, 0.4); + --violet-ink: #b98a97; + + --font-sans: system-ui, sans-serif; + --font-mono: 'IBM Plex Mono', ui-monospace, monospace; + --font-display: var(--font-sans); + + --control-h: 32px; + --control-h-lg: 40px; + --rule-strong: #2e323a; + + --radius: 3px; + --radius-sm: var(--radius); + --radius-md: 3px; + --radius-lg: 3px; + --topbar-height: 56px; + + --shadow-1: none; + --shadow-2: none; + --shadow-3: none; + + --dur-fast: 120ms; + --ease: ease-out; +} + +// Ledger, light: warm paper; hairline rules carry structure, ink carries +// emphasis. Tint trio stays on the proven warm palette. +[data-ui="ledger"] { + color-scheme: light; + --bg: #f6f1e6; + --surface: #f6f1e6; + --border: #ddd5c2; + --border-strong: #221f18; + --ink: #221f18; + --muted: #7a7466; + --muted-soft: #a39b88; + --accent: #46557b; + --accent-tint: #eef0f5; + --accent-ink: #2f3c5c; + + --field-bg: #f1ebdd; + --surface-sunken: #efe9da; + --surface-muted: #f2ecdf; + --ink-soft: #4a453a; + --row-hover: #efe9da; + --panel-sunken: #f1ebdd; + --border-soft: #cfc6b0; + --scrim: rgba(34, 31, 24, 0.46); + + --danger: #a04a24; + --danger-tint: #f9ece4; + --danger-tint-soft: #fdf6f2; + --danger-tint-alt: #fbf1ec; + --danger-border: #e8c9b8; + --danger-border-soft: #eddcd3; + --danger-border-alt: #ecd0bf; + + --warn-ink: #7a5c1e; + --warn-tint: #f7f0dd; + --warn-tint-soft: #fdfaf1; + --warn-border: #e6d7ae; + + --positive: #5c7b46; + --positive-ink: #4a6636; + --positive-tint: #eef3e9; + --positive-border: #d3e0c6; + + --accent-strong: #5a6a94; + --accent-border: #d6dbe8; + --accent-border-strong: #d8dce6; + + --avatar-tone-1: #7b6846; + --avatar-tone-3: #7b4655; + --avatar-tone-4: #46707b; + + --violet-tint: #f1eaf7; + --violet-border: #ddc4ec; + --violet-ink: #6a3f82; + + --font-sans: system-ui, sans-serif; + --font-mono: 'IBM Plex Mono', ui-monospace, monospace; + --font-display: 'Newsreader', Georgia, serif; + + --control-h: 32px; + --control-h-lg: 40px; + --rule-strong: #221f18; + + --radius: 2px; + --radius-sm: var(--radius); + --radius-md: 2px; + --radius-lg: 2px; + --topbar-height: 56px; + + --shadow-1: none; + --shadow-2: none; + --shadow-3: none; + + --dur-fast: 120ms; + --ease: ease-out; +} + +// Ledger, dark: dimmed paper ground; semantic hues lifted for contrast, tint +// fills translucent over the paper tone. +[data-ui="ledger"][data-theme="dark"] { + color-scheme: dark; + --bg: #171511; + --surface: #171511; + --border: #3a352a; + --border-strong: #e8e2d4; + --ink: #e8e2d4; + --muted: #97907f; + --muted-soft: #6e6757; + --accent: #9db0dd; + --accent-tint: rgba(157, 176, 221, 0.14); + --accent-ink: #c3cfee; + + --field-bg: #1c1915; + --surface-sunken: #14120e; + --surface-muted: #1c1915; + --ink-soft: #cfc8b6; + --row-hover: #201c16; + --panel-sunken: #1b1814; + --border-soft: #2e2a20; + --scrim: rgba(0, 0, 0, 0.75); + + --danger: #d28a5a; + --danger-tint: rgba(210, 138, 90, 0.13); + --danger-tint-soft: rgba(210, 138, 90, 0.07); + --danger-tint-alt: rgba(210, 138, 90, 0.05); + --danger-border: rgba(210, 138, 90, 0.45); + --danger-border-soft: rgba(210, 138, 90, 0.3); + --danger-border-alt: rgba(210, 138, 90, 0.35); + + --warn-ink: #d4b16a; + --warn-tint: rgba(212, 177, 106, 0.14); + --warn-tint-soft: rgba(212, 177, 106, 0.07); + --warn-border: rgba(212, 177, 106, 0.4); + + --positive: #a3bd8b; + --positive-ink: #b8cda4; + --positive-tint: rgba(163, 189, 139, 0.13); + --positive-border: rgba(163, 189, 139, 0.4); + + --accent-strong: #8497c9; + --accent-border: #3f4658; + --accent-border-strong: #2c3550; + + --avatar-tone-1: #937d58; + --avatar-tone-3: #96606e; + --avatar-tone-4: #5b93a1; + + --violet-tint: rgba(201, 163, 222, 0.14); + --violet-border: rgba(201, 163, 222, 0.4); + --violet-ink: #c9a3de; + + --font-sans: system-ui, sans-serif; + --font-mono: 'IBM Plex Mono', ui-monospace, monospace; + --font-display: 'Newsreader', Georgia, serif; + + --control-h: 32px; + --control-h-lg: 40px; + --rule-strong: #e8e2d4; + + --radius: 2px; + --radius-sm: var(--radius); + --radius-md: 2px; + --radius-lg: 2px; + --topbar-height: 56px; + + --shadow-1: none; + --shadow-2: none; + --shadow-3: none; + + --dur-fast: 120ms; + --ease: ease-out; +} + +* { box-sizing: border-box; } + +body { + margin: 0; + background: var(--bg); + color: var(--ink); + font-family: var(--font-sans); + font-size: 13px; +} + +// The board page owns the viewport: chrome and the occasional refusal line +// keep their natural height, the stage absorbs the rest, the document never +// scrolls. +body:has(.board-stage) { + // dvh follows the browser chrome phones raise and lower; vh is the fallback + // for engines without it. + height: 100vh; + height: 100dvh; + overflow: hidden; + display: flex; + flex-direction: column; + + > * { flex: none; } + > .board-stage { flex: 1; min-height: 0; } +} + +body:has(.settings-shell) { + height: 100vh; + height: 100dvh; + overflow: hidden; + display: flex; + flex-direction: column; + + > * { flex: none; } + > .settings-shell { flex: 1; min-height: 0; } +} + +// A profile is one column of its own; it pans inside itself like every other +// page here, and the document never grows a scrollbar. +body:has(.people-shell) { + height: 100vh; + height: 100dvh; + overflow: hidden; + display: flex; + flex-direction: column; + + > * { flex: none; } + > .people-shell { flex: 1; min-height: 0; } +} +// The account screens take the same lock: the card centers in what is left +// of the viewport, and a card taller than it (a landscape phone) pans inside +// the stage instead of growing the document. +body:has(.auth-stage) { + height: 100vh; + height: 100dvh; + overflow: hidden; + display: flex; + flex-direction: column; + + > * { flex: none; } + > .auth-stage { + flex: 1; + min-height: 0; + overflow-y: auto; + scrollbar-width: none; + + &::-webkit-scrollbar { display: none; } + } +} + +a { + color: var(--accent); + transition: color var(--dur-fast) var(--ease); + &:hover { color: var(--accent-ink); } +} + +.topbar { + height: var(--topbar-height); + background: var(--surface); + border-bottom: 1px solid var(--border); + display: flex; + align-items: center; + gap: 16px; + padding: 0 24px; +} + +// The brand lockup is the one thing the two skins do NOT restyle: same +// monogram, same face, same size in Instrument and Ledger, light and dark. +// The mark takes the ink from `currentColor` and the tittle from the accent, +// so it re-tints with the theme without a second drawing. +.wordmark { + display: flex; + align-items: center; + gap: 10px; + text-decoration: none; + color: inherit; + + &:hover { color: inherit; } + + &-mark { + flex: none; + display: block; + width: 24px; + height: 24px; + } + + // The word without the mark, on the sign-in and setup pages: nothing else + // in that chrome, so it can take the room the topbar version cannot. + &-lone &-text { + font-size: 18px; + letter-spacing: 0.01em; + } + + &-tittle { + fill: var(--accent); + } + + // Lower case, and not by taste: capitalised, the dotted `i` becomes `I` and + // the name reads as the English word. The tittle is the Turkish one, in the + // word as it is in the mark. + &-text { + font-family: var(--font-mono); + font-size: 15px; + font-weight: 500; + letter-spacing: 0.02em; + } +} + +.topbar-divider { + width: 1px; + height: 20px; + background: var(--border); +} + +.topbar-nav-links { + display: flex; + gap: 16px; + margin-left: auto; +} + +// The spacer's flex-grow eats the free space before auto margins see any, so +// inside the chrome the nav's auto margin does the pushing instead. +.topbar > .spacer { display: none; } + +.topbar-nav { + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); + text-decoration: none; + // A two-word label ("Mail rules") folds under pressure and reads as two + // stacked links; the nav gives up room some other way. + white-space: nowrap; + padding-bottom: 2px; + + &:hover { color: var(--ink); } + + &-on { + color: var(--ink); + box-shadow: inset 0 -2px 0 var(--ink); + } +} + +.scaffold-note { + margin: 24px; + padding: 20px 24px; + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + color: var(--muted); +} + +// --- Account screens (FirstLogin artboard) --------------------------------- + +.auth-stage { + min-height: calc(100vh - var(--topbar-height)); + display: flex; + align-items: center; + justify-content: center; + padding: 0 40px 40px; +} + +.auth-column { + width: 520px; + max-width: 100%; + display: flex; + flex-direction: column; + gap: 10px; +} + +.auth-card { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + padding: 28px 28px; + display: flex; + flex-direction: column; + gap: 18px; + box-shadow: var(--shadow-2); + + form { + display: flex; + flex-direction: column; + gap: 20px; + } +} + +.auth-head { + display: flex; + flex-direction: column; + gap: 6px; +} + +.auth-title { + font-size: 18px; + font-weight: 600; + letter-spacing: -0.01em; +} + +.auth-sub { + font-size: 13px; + color: var(--muted); + line-height: 1.5; +} + +.auth-field { + display: flex; + flex-direction: column; + gap: 6px; +} + +.auth-label { + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.08em; + color: var(--muted-soft); +} + +// The address an invited member signs in as: shown, never edited. +.auth-locked { + display: flex; + align-items: center; + gap: 8px; + height: 40px; + padding: 0 12px; + background: var(--panel-sunken); + border: 1px solid var(--border-strong); + border-radius: var(--radius); +} + +.auth-locked-value { + font-family: var(--font-mono); + font-size: 13px; + color: var(--muted); + flex-grow: 1; +} + +.auth-submit { + height: var(--control-h-lg); + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + background: var(--accent); + color: var(--surface); + border: 0; + border-radius: var(--radius); + cursor: pointer; + font-family: var(--font-sans); + + &:disabled { + opacity: 0.45; + cursor: default; + } +} + +.auth-submit-text { + font-size: 13px; + font-weight: 600; +} + +.auth-key { + font-family: var(--font-mono); + font-size: 10px; + background: var(--accent-strong); + border-radius: var(--radius-sm); + padding: 1px 4px; +} + +.auth-problem { + font-size: 13px; + color: var(--danger); + background: var(--danger-tint-alt); + border: 1px solid var(--danger-border-soft); + border-radius: var(--radius); + padding: 10px 12px; +} + +.auth-note { + font-size: 13px; + color: var(--muted); + background: var(--panel-sunken); + border: 1px solid var(--border-soft); + border-radius: var(--radius); + padding: 10px 12px; +} + +.auth-alt { + font-size: 12px; + color: var(--muted); + text-decoration: none; + align-self: center; + + &:hover { color: var(--accent-ink); } +} + +// -- the board (Main and EmptyBoard artboards) ------------------------------- + +.spacer { flex-grow: 1; } + +.user-menu { position: relative; } + +.user-menu-trigger { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 0; + background: none; + border: none; + font-family: inherit; + font-size: 13px; + color: var(--muted); + cursor: pointer; + transition: color var(--dur-fast) var(--ease); + + &:hover { color: var(--accent-ink); } +} + +.user-menu-panel { + position: absolute; + top: 100%; + right: 0; + z-index: 30; + width: 220px; + padding: 8px 0; + background: var(--surface); + border: 1px solid var(--border-strong); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-2); + visibility: hidden; + opacity: 0; + pointer-events: none; + transition: opacity var(--dur-fast) var(--ease), visibility var(--dur-fast) var(--ease); +} + +.user-menu:hover .user-menu-panel, +.user-menu:focus-within .user-menu-panel { + visibility: visible; + opacity: 1; + pointer-events: auto; +} +.user-menu.user-menu-esc .user-menu-panel { visibility: hidden; opacity: 0; pointer-events: none; } + +.user-menu-name { + padding: 4px 14px 0; + font-size: 13px; + font-weight: 600; +} + +.user-menu-email { + padding: 2px 14px 0; + font-size: 12px; + color: var(--muted); + word-break: break-all; +} + +.user-menu-role { + padding: 2px 14px 6px; + font-size: 12px; + color: var(--muted-soft); + text-transform: capitalize; +} + +.user-menu-item { + display: flex; + align-items: center; + width: 100%; + height: 32px; + padding: 0 14px; + border: none; + background: none; + font-family: inherit; + font-size: 13px; + color: var(--ink-soft); + text-decoration: none; + text-align: left; + cursor: pointer; + transition: background-color var(--dur-fast) var(--ease), color var(--dur-fast) var(--ease); + + &:hover { background: var(--row-hover); color: var(--ink); } +} + +.user-menu-item-form { display: block; } + +.filterbar { + min-height: 52px; + background: var(--surface); + border-bottom: 1px solid var(--border); + display: flex; + align-items: center; + flex-wrap: wrap; + row-gap: 8px; + gap: 14px; + padding: 8px 24px; +} + +.segmented { + display: flex; + align-items: center; + background: var(--panel-sunken); + border: 1px solid var(--border-strong); + border-radius: var(--radius); + padding: 2px; + gap: 2px; +} + +.chip { + display: flex; + align-items: center; + height: 24px; + padding: 0 10px; + border-radius: var(--radius); + font-size: 11px; + font-weight: 600; + + &-overdue { + background: var(--danger-tint); + color: var(--danger); + } + + &-blocked { + background: var(--warn-tint); + color: var(--warn-ink); + } + + &-role, + &-admin, + &-connected, + &-off { + text-transform: capitalize; + } + + &-role { background: var(--surface-sunken); border: 1px solid var(--border-strong); color: var(--ink-soft); } + &-admin { background: var(--panel-sunken); border: 1px solid var(--border-strong); color: var(--muted); } + &-connected { background: var(--positive-tint); color: var(--positive-ink); } + &-off { background: var(--warn-tint); color: var(--warn-ink); } +} + +.board-stage { + position: relative; + display: flex; + flex-direction: column; + flex: 1; + min-height: 0; + padding: 20px 24px 24px 24px; +} + +.board-columns { + flex: 1; + min-height: 0; + display: grid; + grid-template-columns: repeat(auto-fit, minmax(0, 1fr)); + gap: 16px; + align-items: stretch; +} + +.column { + background: var(--surface-sunken); + border-radius: var(--radius-lg); + padding: 12px; + display: flex; + flex-direction: column; + gap: 10px; + min-height: 120px; +} + +.column-head { + display: flex; + align-items: center; + gap: 8px; + padding: 2px 4px; +} + +.column-name { + font-size: 13px; + font-weight: 600; +} + +.column-count { + font-family: var(--font-mono); + font-size: 11px; + font-variant-numeric: tabular-nums; + color: var(--muted-soft); + background: var(--panel-sunken); + border-radius: var(--radius); + padding: 1px 6px; +} + +.column-cards { + display: flex; + flex-direction: column; + gap: 8px; + flex: 1; + min-height: 0; + overflow-y: auto; + scrollbar-width: none; + + &::-webkit-scrollbar { display: none; } +} + +.column-empty { + flex: 1; + display: flex; + align-items: center; + justify-content: center; + min-height: 60px; + border: 1px dashed var(--border-strong); + border-radius: var(--radius-md); + background: var(--surface-sunken); + font-size: 12px; + color: var(--muted-soft); +} + +.card { + // The card is an anchor so it has an address; it must not read as one. + display: block; + text-decoration: none; + color: inherit; + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-md); + padding: 10px 12px; + box-shadow: var(--shadow-1); + cursor: pointer; + transition: background-color var(--dur-fast) var(--ease), border-color var(--dur-fast) var(--ease); + + &:hover { + background: var(--row-hover); + border-color: var(--border-strong); + } +} + +/* Where a dragged card may land. Only columns it is not already in light up: + the card's own column is not a destination. */ +.column-drop { + outline: 1px dashed var(--border-strong); + outline-offset: 4px; + border-radius: var(--radius-md); + background: var(--accent-tint); +} + +.card-done { + background: var(--surface-muted); + box-shadow: none; + + .card-title { color: var(--muted); } +} + +.card-keys { + display: flex; + align-items: baseline; + gap: 6px; + font-family: var(--font-mono); + font-size: 10px; +} + +.card-key { color: var(--muted); } + +.card-blocks, +.card-blocked-by { color: var(--warn-ink); } + +.card-title { + font-size: 13px; + font-weight: 600; + line-height: 1.4; + margin-top: 4px; +} + +.card-foot { + display: flex; + align-items: center; + gap: 6px; + margin-top: 10px; + flex-wrap: wrap; +} + +.card-deadline { + display: flex; + align-items: center; + font-family: var(--font-mono); + font-size: 11px; + font-variant-numeric: tabular-nums; + color: var(--muted); + background: var(--surface-sunken); + border-radius: var(--radius-sm); + padding: 2px 6px; + + &-overdue { + color: var(--danger); + background: var(--danger-tint); + } + + &-none { + color: var(--muted-soft); + background: transparent; + padding-left: 0; + } +} + +.card-comments, +.card-subtasks { + font-family: var(--font-mono); + font-size: 11px; + color: var(--muted); +} + +.card-tag { + font-family: var(--font-mono); + font-size: 11px; + color: var(--muted); + background: var(--surface-sunken); + border-radius: var(--radius-sm); + padding: 2px 6px; +} + +/// Parts still open is the same warning the blocker chips carry: this card +/// cannot reach the done column yet. +.card-subtasks-open { color: var(--warn-ink); } + +.avatars { + display: flex; + align-items: center; + min-width: 0; + overflow: hidden; + + // The data-name tooltip pokes above the row; hovering drops the clip so it + // is not cut off by the overlap truncation. + &:has(.avatar:hover) { overflow: visible; } +} + +.avatar { + width: 22px; + height: 22px; + border-radius: 50%; + border: 2px solid var(--surface); + color: var(--surface); + font-family: var(--font-mono); + font-size: 10px; + display: flex; + align-items: center; + justify-content: center; + position: relative; + + & + & { margin-left: -8px; } + + &-none { + border: 1px dashed var(--border-strong); + background: transparent; + } + + // The modal asks for two other sizes: 18px inside an assignee chip, 28px + // beside a comment. The border is the board's overlap trick and has no job + // on a lone avatar, so these drop it. + // + // They are written as `.avatar.avatar-sm` on purpose: the Instrument skin + // sizes `.avatar` from a `[data-ui]` scope, which outweighs a lone class — + // a plain `.avatar-lg` lost to it, and every size modifier collapsed to + // 18px on that skin without anybody noticing. + &.avatar-sm { + width: 18px; + height: 18px; + border: none; + font-size: 10px; + } + + &.avatar-lg { + width: 28px; + height: 28px; + border: none; + font-size: 11px; + flex: none; + } + + // The profile page's own picture: the one place a face is the subject of + // the screen rather than a mark beside somebody's name. + &.avatar-xl { + width: 92px; + height: 92px; + border: none; + font-size: 30px; + font-weight: 500; + flex: none; + } + + // A bare avatar carries `data-name`; hovering raises a house tooltip in + // place of the native `title`. + &[data-name]:hover::after { + content: attr(data-name); + position: absolute; + bottom: calc(100% + 6px); + left: 50%; + transform: translateX(-50%); + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + padding: 3px 8px; + font-size: 11px; + color: var(--ink-soft); + box-shadow: var(--shadow-2); + white-space: nowrap; + z-index: 30; + pointer-events: none; + } + + &-tone-0 { background: var(--accent); } + &-tone-1 { background: var(--avatar-tone-1); } + &-tone-2 { background: var(--positive); } + &-tone-3 { background: var(--avatar-tone-3); } + &-tone-4 { background: var(--avatar-tone-4); } +} + +// A photo avatar is the same box with the picture where the tone fill was; +// size and shape ride the shared .avatar classes. +img.avatar { + object-fit: cover; + display: block; +} + +// The avatar leads the profile panel. Without a photo it is itself the +// upload control — the file input rides its `form` attribute to a hidden +// sibling form, so nothing nests inside the profile form. With one, the +// click opens the photo viewer and a Change button owns the picker instead. +.identity-row { + display: flex; + align-items: center; + gap: 14px; +} + +// The two faces of the profile picture box: the picker label and, once a +// photo exists, the viewer trigger. The person page's own card wears the +// trigger too — the box rules are shared, the size is not. +.avatar-upload, +.avatar-view { + position: relative; + flex: none; + cursor: pointer; + + // The name tooltip has no job on your own picture. + .avatar[data-name]:hover::after { content: none; } +} + +// The settings row's picture is 64px whatever size class the avatar wears; +// the person card's keeps its xl. +.identity-row .avatar-upload .avatar, +.identity-row .avatar-view .avatar { + width: 64px; + height: 64px; + font-size: 20px; +} + +// The trigger is the label's box with a button's chrome stripped. +.avatar-view { + appearance: none; + background: none; + border: none; + padding: 0; +} + +.avatar-upload { + // The upload affordance: a veil and a plus over the picture, on hover or + // keyboard focus only. + &::after { + content: "+"; + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + background: rgb(0 0 0 / 0.4); + border-radius: 50%; + color: #fff; + font-size: 24px; + font-weight: 300; + opacity: 0; + transition: opacity var(--dur-fast) var(--ease); + pointer-events: none; + } + + &:hover::after, + &:has(.file-upload-input:focus-visible)::after { opacity: 1; } +} + +// -- the card context menu --------------------------------------------------- +// +// A right-click opens this at the cursor; `card_menu_script` (board.rs) sets +// its position and the `card-menu-open` class, and a document click closes +// whichever one is open. The panel and its rows wear the same floating-list +// chrome as the assignee and link pickers (`.pop-panel`/`.pop-list`/`.pop-row`). + +.card-menu { + display: none; + position: fixed; + z-index: 25; + min-width: 160px; + + &-open { display: block; } +} + +.card-menu-move { position: relative; } + +.card-menu-submenu { + display: none; + position: absolute; + left: 100%; + top: 0; + margin-left: 4px; + min-width: 140px; +} + +.card-menu-move:hover > .card-menu-submenu, +.card-menu-move-trigger:focus + .card-menu-submenu { display: block; } + +.card-menu-danger { color: var(--danger); } + +// -- the task detail modal -------------------------------------------------- +// +// The modal is a view. Every region that can be changed is a `
` wearing +// the view's clothes: the read-only shape is a `
` itself: +// `display: flex` directly on a `` drops it out of the table's row/column +// model, which is what left this list's columns loose and its rows +// unevenly centered. +.member-name-row, +.member-account-row { + display: flex; + align-items: center; +} + +.member-name { font-weight: 600; } +.member-name-row { gap: 8px; } + +.member-you { + flex: none; + padding: 1px 8px; + border-radius: 999px; + background: var(--field-bg); + border: 1px solid var(--border-strong); + font-size: 11px; + font-weight: 500; + color: var(--muted); +} + +.member-address { + font-family: var(--font-mono); + font-size: 12px; + color: var(--muted); +} + +.member-account { color: var(--muted); } +.member-account-row { gap: 10px; } +.member-status { flex: none; white-space: nowrap; } + +.member-resend { display: inline-flex; flex: none; } + +.quiet { + display: inline-flex; + align-items: center; + height: var(--control-h); + padding: 0 10px; + background: var(--surface); + border: 1px solid var(--border-strong); + border-radius: var(--radius); + font-family: var(--font-sans); + font-size: 12px; + color: var(--ink-soft); + text-decoration: none; + cursor: pointer; + transition: border-color var(--dur-fast) var(--ease), color var(--dur-fast) var(--ease); + + &:hover { border-color: var(--accent); color: var(--accent); } +} + +// Danger modifier for a `.quiet` button — the "Delete" action in a rule row. +// Written `.quiet.quiet-danger` for the same reason the avatar sizes are: +// the skins style `.quiet` from a `[data-ui]` scope, which outweighs a lone +// modifier class — on the Ledger skin a delete button lost its red border, +// and its red text on hover, to a rule about ordinary quiet buttons. +.quiet.quiet-danger { + border-color: var(--danger-border); + color: var(--danger); + + &:hover { border-color: var(--danger); color: var(--danger); background: var(--surface-sunken); } +} + +// The chevron floats over the trigger's right end rather than sitting next +// to it in the flex row: the trigger then spans the whole box, so the box +// is clickable edge to edge. +.member-role { + position: relative; + padding: 0; + + > .glyph { position: absolute; right: 10px; pointer-events: none; color: var(--muted); } + .status-select { align-self: stretch; padding: 0 28px 0 10px; } +} + +.member-invite { + display: flex; + align-items: flex-end; + gap: 12px; + flex-wrap: wrap; +} + +.field-role { flex-grow: 0; width: 140px; } + +// One control height, matching `.primary`, for this row's fields, so the +// role select and the "Add member" button share one height and baseline. +.member-invite .field-input { height: var(--control-h); } + +// The link exists once. It is shown once, and said to be shown once. +.member-link { + display: flex; + flex-direction: column; + gap: 6px; + padding: 12px; + background: var(--accent-tint); + border: 1px solid var(--accent-border); + border-radius: var(--radius); +} + +.member-link-value { + font-family: var(--font-mono); + font-size: 12px; + color: var(--accent-ink); + word-break: break-all; +} + +// --- Mail rules (MailRules artboard) --------------------------------------- + +// Text only a screen reader needs: the switch says what it does in a word the +// eye reads from its position, and the ear cannot. +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + +.rules-quiet { + margin: 0; + font-size: 13px; + color: var(--muted); +} + +.rule-list { + display: flex; + flex-direction: column; + gap: 10px; +} + +.rule-row { + display: flex; + align-items: center; + gap: 14px; + padding: 16px; + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-md); + + // A rule that is switched off is still listed — the screen shows what + // exists, not what is live — and reads as the quieter of the two. + &-off { + background: var(--surface-muted); + opacity: 0.75; + } +} + +.rule-switch-form { display: flex; flex-shrink: 0; } + +.rule-switch { + width: 36px; + height: 20px; + padding: 0; + border: none; + border-radius: var(--radius-lg); + background: var(--border-soft); + position: relative; + cursor: pointer; + + &-knob { + position: absolute; + top: 2px; + left: 2px; + width: 16px; + height: 16px; + border-radius: 50%; + background: var(--surface); + } + + &-on { + background: var(--accent); + .rule-switch-knob { left: auto; right: 2px; } + } +} + +.rule-sentence { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8px; + flex-grow: 1; + min-width: 0; + font-size: 13px; + color: var(--ink-soft); +} + +// One chosen word inside the sentence: a column, a subject, an audience. +// Identity, not state — a neutral outline so the toned verdict chips below +// stand out next to it instead of blending in. +.rule-term { + display: inline-flex; + align-items: center; + padding: 3px 8px; + background: transparent; + border: 1px solid var(--border-strong); + border-radius: var(--radius-sm); + font-weight: 500; + color: var(--ink); +} + +.rule-row-off .rule-term { + border-color: var(--border-soft); + color: var(--muted-soft); +} + +// A verdict or a queue state, toned so the eye can sort a page of them +// without reading every word: sent/queued reads as the app's accent blue, +// failed/abandoned as its danger orange, held/pending as its warning amber, +// no recipients gets its own violet tone, and everything that is quietly +// not-a-failure (not matched, rule off) stays muted rather than competing +// for attention. +.rule-term-owed, +.rule-term-already_owed, +.rule-term-sent { + background: var(--accent-tint); + border-color: var(--accent-border); + color: var(--accent-ink); +} + +.rule-term-failed, +.rule-term-abandoned { + background: var(--danger-tint); + border-color: var(--danger-border-alt); + color: var(--danger); +} + +.rule-term-held, +.rule-term-pending { + background: var(--warn-tint); + border-color: var(--warn-border); + color: var(--warn-ink); +} + +.rule-term-not_matched, +.rule-term-disabled { + background: var(--surface-sunken); + border-color: var(--border-strong); + color: var(--muted); +} + +.rule-term-no_recipients { + background: var(--violet-tint); + border-color: var(--violet-border); + color: var(--violet-ink); +} + +.rule-term-task_gone { + background: var(--danger-tint-soft); + border-color: var(--danger-border-soft); + color: var(--danger); +} + +// One event and every rule's verdict on it, so the task and moment are said +// once instead of once per rule. +.decision-block { + display: flex; + flex-direction: column; + gap: 8px; + padding: 16px; + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-md); +} + +.decision-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.decision-title { + font-size: 13px; + font-weight: 600; + color: var(--ink-soft); +} + +.decision-verdicts { + display: flex; + flex-direction: column; + gap: 6px; +} + +.decision-verdict { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8px; + font-size: 13px; + color: var(--ink-soft); +} + +.rule-stamp { + flex-shrink: 0; + font-family: var(--font-mono); + font-size: 11px; + color: var(--muted-soft); +} + +// Activity log: a columnar register, not a card list — one line per event, +// time-first, ruled by hairlines instead of boxed rows. +.log-list { + display: flex; + flex-direction: column; +} + +.log-row { + display: flex; + align-items: baseline; + gap: 12px; + padding: 8px 2px; + border-bottom: 1px solid var(--border); +} + +.log-stamp { + flex-shrink: 0; + min-width: 110px; + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); +} + +.log-actor { + flex-shrink: 0; + font-size: 13px; + font-weight: 500; + color: var(--ink); +} + +.log-line { + flex: 1; + min-width: 0; + font-size: 13px; + color: var(--ink-soft); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +// The activity panel's filter row is the board's control row living inside a +// panel body: the page-bar chrome (min strip, own bottom rule, bar padding) +// is opted out of — the panel head rules the row, the body pads it. The +// two-class selector out-ranks both `.filterbar` bases, the +// narrow-viewport one included. +.filterbar.log-filterbar { + min-height: 0; + padding: 0; + background: none; + border-bottom: none; + flex-wrap: wrap; + gap: 10px; +} + +.log-range-dash { + align-self: center; + margin: 0 2px; + color: var(--muted); +} + +// The pager foot's read of where the rendered rows sit in the whole feed. +.log-count { + font-family: var(--font-mono); + font-size: 10px; + color: var(--muted); +} + +.log-title { + flex-shrink: 1; + min-width: 0; + font-size: 13px; + color: var(--muted); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.log-key { + flex: none; + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); +} + + +.rule-new { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-lg); +} + +.rule-new-open { + display: flex; + align-items: center; + height: var(--control-h); + padding: 0 16px; + font-size: 13px; + font-weight: 600; + color: var(--accent-ink); + cursor: pointer; + list-style: none; + + &::marker, &::-webkit-details-marker { display: none; } + &::before { content: '+'; margin-right: 8px; font-size: 13px; } +} + +.rule-new-body { + display: flex; + flex-direction: column; + gap: 20px; + padding: 0 16px 16px; + border-top: 1px solid var(--border); + padding-top: 16px; +} + +.rule-field { + display: flex; + flex-direction: column; + gap: 6px; +} + +.tag-list { + display: flex; + flex-direction: column; + gap: 10px; +} + +.tag-row { + display: flex; + align-items: center; + gap: 14px; + padding: 16px; + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-md); +} + +.tag-name { + flex-grow: 1; + min-width: 0; + font-size: 13px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +// How many cards are on the project, in the same chip the board counts its +// columns with. It is also the reason the delete control beside it is or is +// not there. +.tag-count { + flex: none; + font-family: var(--font-mono); + font-size: 11px; + font-variant-numeric: tabular-nums; + color: var(--muted-soft); + background: var(--panel-sunken); + border-radius: var(--radius); + padding: 1px 6px; +} + +.tag-new { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-lg); +} + +.tag-new-open { + display: flex; + align-items: center; + height: var(--control-h); + padding: 0 16px; + font-size: 13px; + font-weight: 600; + color: var(--accent-ink); + cursor: pointer; + list-style: none; + + &::marker, &::-webkit-details-marker { display: none; } + &::before { content: '+'; margin-right: 8px; font-size: 13px; } +} + +.tag-form { + display: flex; + flex-direction: column; + gap: 20px; + padding: 0 16px 16px; + border-top: 1px solid var(--border); + padding-top: 16px; +} + +.tag-field { + display: flex; + flex-direction: column; + gap: 6px; +} + +// --- Profile (a member's page) ---------------------------------------------- + +.people-shell { + width: 100%; + max-width: 860px; + margin: 0 auto; + padding: 24px 32px 40px; + display: flex; + flex-direction: column; + gap: 20px; + overflow-y: auto; + scrollbar-width: none; + + &::-webkit-scrollbar { display: none; } + > * { flex: none; } +} + +// A face or a name that leads to the person it names. The chrome stays the +// chrome — the link exists to be clicked, not to look like one. +.person-link { + display: inline-flex; + align-items: center; + gap: inherit; + color: inherit; + text-decoration: none; + min-width: 0; + + &:hover { text-decoration: underline; } +} + +.person-card { + overflow: hidden; +} + +// The head is the identity: a picture big enough to be a picture, the name, +// what the workspace calls this person, and — on your own page only — the way +// to the one screen that can change any of it. +.person-head { + display: flex; + align-items: center; + gap: 18px; + padding: 22px 22px 20px; +} + +.person-heading { + display: flex; + flex-direction: column; + gap: 8px; + min-width: 0; +} + +.person-name { + margin: 0; + font-family: var(--font-display); + font-size: 22px; + font-weight: 600; + line-height: 1.1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.person-marks { + display: flex; + align-items: center; + gap: 6px; +} + +.person-edit { + margin-left: auto; + flex: none; +} + +// Every fact sits in a named cell instead of floating as a line of text. The +// cells share the panel's own hairlines, so the block reads as one table +// rather than as paragraphs that happen to be near each other. +.person-fields { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); + margin: 0; + border-top: 1px solid var(--border); +} + +.person-field { + padding: 12px 22px 14px; + min-width: 0; + border-right: 1px solid var(--border); + + &:last-child { border-right: none; } + + dt { + font-size: 10px; + letter-spacing: 0.09em; + color: var(--muted); + } + + dd { + margin: 4px 0 0; + font-size: 13px; + color: var(--ink); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } +} + +.person-field dd.person-address { + font-family: var(--font-mono); + font-size: 12px; +} + +// The hover tooltip names a face that is standing beside its own name. +.person-head .avatar[data-name]:hover::after { content: none; } + +// Four counts, four boxes. The number leads and the label sits under it, so a +// column reads as one thing rather than as a word with a digit beside it. +.person-stats { + display: grid; + grid-template-columns: repeat(4, 1fr); + margin: 0; + + @media (max-width: 620px) { + grid-template-columns: repeat(2, 1fr); + + // Two by two: the rule runs between the columns and under the first + // row, not off the right edge of every cell. + .person-stat { + border-right: none; + border-bottom: 1px solid var(--border); + + &:nth-child(odd) { border-right: 1px solid var(--border); } + &:nth-child(n + 3) { border-bottom: none; } + } + } +} + +.person-stat { + padding: 16px 22px 18px; + border-right: 1px solid var(--border); + + &:last-child { border-right: none; } + + dd { + margin: 0; + font-family: var(--font-mono); + font-size: 26px; + font-weight: 500; + line-height: 1.1; + font-variant-numeric: tabular-nums; + } + + dt { + margin-top: 6px; + font-size: 10px; + letter-spacing: 0.09em; + text-transform: uppercase; + color: var(--muted); + } +} + +.person-feed { + list-style: none; + margin: 0; + padding: 0; +} + +.person-line { + display: flex; + align-items: baseline; + gap: 12px; + padding: 9px 18px; + border-top: 1px solid var(--border); + min-width: 0; + + &:first-child { border-top: none; } + &:hover { background: var(--surface-muted); } +} + +.person-verb { + flex: none; + width: 88px; + font-size: 11px; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--muted); +} + +.person-task { + display: flex; + align-items: baseline; + gap: 8px; + min-width: 0; + color: inherit; + text-decoration: none; + + &:hover .person-title { text-decoration: underline; } +} + +.person-key { + flex: none; + font-family: var(--font-mono); + font-size: 11px; + color: var(--muted); +} + +.person-title { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 13px; +} + +.person-day { + margin-left: auto; + flex: none; + white-space: nowrap; + color: var(--muted); + font-size: 12px; +} +// --- Mobile (narrow viewports) ---------------------------------------------- +// +// One breakpoint, at the same 620px the person stats already fold at. The +// document stays viewport-locked on every page (the body:has(...) rules +// above); what a narrow screen changes is geometry: chrome tightens, the +// settings rail becomes a strip, the board's columns pan sideways, and the +// regions that already pan keep panning. Nothing here may open a document +// scrollbar, and nothing here may grow explainer text. +@media (max-width: 620px) { + // -- chrome ---------------------------------------------------------------- + + .topbar { + gap: 10px; + padding: 0 12px; + } + + .topbar-nav-links { + gap: 12px; + // Five admin links outrun the narrowest phones; the strip pans under the + // finger the way every other overflow region here does, and the wordmark + // and avatar stay pinned at the edges. + min-width: 0; + overflow-x: auto; + scrollbar-width: none; + + &::-webkit-scrollbar { display: none; } + } + + // The avatar says who is signed in at this width; the name is the menu's. + .user-menu-trigger-name { display: none; } + + // The last squeeze, below the smallest common phone: the chrome gives up + // its air before the nav gives up legibility. + @media (max-width: 360px) { + .topbar { + gap: 8px; + padding: 0 8px; + } + + .topbar-nav-links { gap: 10px; } + } + + // -- board ----------------------------------------------------------------- + + .filterbar { + height: auto; + min-height: 44px; + flex-wrap: wrap; + row-gap: 8px; + padding: 8px 12px; + } + + // A rule floating alone at the head of a wrapped row says nothing. + .filterbar .topbar-divider { display: none; } + + .filterbar .primary, + .filterbar .chip { flex: none; } + + .board-stage { padding: 12px; } + + // The columns stop sharing one row and become a rail: each as wide as a + // card needs, the row panning sideways under the finger, silently. + .board-columns { + grid-template-columns: none; + grid-auto-flow: column; + grid-auto-columns: min(72vw, 280px); + overflow-x: auto; + scroll-snap-type: x proximity; + scrollbar-width: none; + + &::-webkit-scrollbar { display: none; } + } + + .column { scroll-snap-align: start; } + + // -- modals ---------------------------------------------------------------- + + .modal-scrim { padding: 16px; } + + .modal { max-height: calc(100dvh - 32px); } + + .new-task-row { flex-wrap: wrap; } + + .detail-head { padding: 16px 16px 0; } + + // Six tabs outrun a phone; the strip pans, the way a column of cards does. + .detail-tabs { + overflow-x: auto; + scrollbar-width: none; + + &::-webkit-scrollbar { display: none; } + } + + .detail-tab { white-space: nowrap; } + + .detail-crumb-title { max-width: 16ch; } + + .detail-fields { + grid-template-columns: minmax(0, 1fr); + padding: 14px 16px 0; + } + + .detail-block { padding: 16px 16px 0; } + + .detail-foot { padding: 14px 16px 16px; } + + // -- the settings shell: rail becomes a strip ------------------------------- + + .settings-shell { flex-direction: column; } + + .settings-sections { + width: auto; + flex-direction: row; + padding: 0 8px; + border-right: none; + border-bottom: 1px solid var(--border); + overflow-x: auto; + scrollbar-width: none; + + &::-webkit-scrollbar { display: none; } + } + + .settings-section-link { + flex: none; + padding: 12px 10px; + white-space: nowrap; + } + + .settings-stage { padding: 16px 16px 32px; } + + // The members register keeps its named columns and pans inside the panel + // rather than squeezing the role select out of the screen. + .table-pan { + overflow-x: auto; + scrollbar-width: none; + + &::-webkit-scrollbar { display: none; } + + .member-table { min-width: 560px; } + } + + .field-row { flex-wrap: wrap; } + + // -- people ----------------------------------------------------------------- + + .people-shell { padding: 16px 16px 32px; } + + .person-head { flex-wrap: wrap; } + + .person-fields { grid-template-columns: minmax(0, 1fr); } + + // Stacked cells rule underneath each other, not off their right edge. + .person-field { + border-right: none; + border-bottom: 1px solid var(--border); + + &:last-child { + border-right: none; + border-bottom: none; + } + } + + // -- account screens --------------------------------------------------------- + + .auth-stage { padding: 0 16px 24px; } +}