in
Clone
0 watching0 forksRust528.7 KiB9ffa9cdTahinli1 month ago28 commits
"in" (old_in) - complete feature inventory for a from-scratch rebuild
Source tree: /home/tahinli/Documents/Code/Rust/old_in (read-only inventory; nothing modified). Crates: crates/in-core (store, config, thumbs, live), crates/in-client (OIDC client to im), crates/in-web (HTTP app on topcoat 0.9.0). Method: every source file was read by a dedicated pass (turso_store.rs and tests were split), then cross-checked by grep. Items marked "(unverified)" were not confirmed against source.
1. Purpose
- "in" is a personal file drive: folders, file upload (small and chunked/resumable), download, preview, thumbnails, trash, share links, per-person shares, quotas.
- Sign-in is delegated to sibling app "im" (OIDC, PKCE, RS256 id_token, introspection per request). im also provides the user directory (full pass + live stream) and avatars.
- Storage is local disk (default) or Cloudflare R2 (S3 API) for final blobs; upload staging is always local.
- A machine "service API" (bearer keys) lets other family apps push, fetch and delete blobs against a per-service account and quota.
- Single binary, server-rendered HTML with small inline JS, SSE for live updates, SQLite-compatible Turso database.
2. User-facing features
Conventions: "owner" = the signed-in user who owns a row. Cross-owner access always answers 404 (never 403) on purpose. Mutations are HTML form POSTs that answer 303 back to the page with ?refusal=<code>&on=<call> on failure. JSON "API" routes answer HTTP 200 with {"ok": ...} or {"err": "<Name>"}. Unauthenticated page GETs redirect 303 to /.
2.1 Sign-in and session
- GET
/: signed-in browser gets 303 to/drive; signed-out gets the sign-in card (link to/auth/login). Store error renders a scaffold note. - GET
/auth/login: OIDC start. Sets flight cookiein_session_pkce(sealed JSON {verifier, state, nonce, next, exp}, Max-Age 600). 303 to{issuer}/authorize(response_type=code, scope "openid profile email", PKCE S256, 32-byte verifier, 16-byte state and nonce).nextaccepted only as a local absolute path. - GET
/auth/callback:?error=X->/?auth_error=X; missing code/state or flight cookie ->invalid_request; expired flight or state mismatch ->invalid_state; exchange failure ->exchange_failed. Success sets session cookie and redirects tonext. - GET
/auth/logout: clearsin_session, 303 to{issuer}/logout?back=<origin>/. (State-changing GET; logout CSRF possible, see oddities.) - Per request:
current_useropens the session cookie, checks local exp, then introspects with im every request. Only explicitactive:falseclears the cookie; transport errors read as signed out but keep the cookie. A disabled local account reads as signed out. First provisioned user becomes admin. - GET
/api/me: session probe. 204 signed in, 401 signed out (empty body), 500 on store failure. - GET
/whoami: appears in one place as a route; probably test-only (unverified).
2.2 Drive (browse, folders)
- GET
/drive(?folder=<id>,?q=,?sort=key:dir,?kind=all|folders|files,?edit=<id>,?share=kind:id,?move=kind:id,?created=<token>,?refusal=&on=).- Owner view of a folder:
current_folderrequires owned, live folder with no trashed ancestor; otherwise 404 (store errors also 404). If that fails,granted_foldertries a grant; grantee gets the read-onlydrive_sharedview. Otherwise 404. - Listing: subfolders first, then files, from
list_children. Row: chip, name, "Shared" chip (fromshared_target_ids, silent on error), size (files), created date, download count (files). Folder rows link/drive?folder=, file rows/view/<id>. - Row Options menu (details element): Rename (
?edit=), Share (?share=), Move (?move=), Delete (POST), Download (files,/file/<id>?dl=1). - Breadcrumb trail root-first, hidden in search and at root; errors silently truncate it.
- Sorting keys: name (default asc), uploaded (created_at), size, downloads. Bare key defaults: name asc, others desc. Unknown key = standing order. Folders sort by name for size/downloads. Ties broken by id. Sorting done in page layer.
- Kind filter
all|folders|files(unknown = all), applied after sort. - Filter bar: search box (
q), sort select and kind select (autosubmit), "+" menu (New folder; upload input#drive-upload-input). - Search mode (
qtrimmed, non-empty):store.search(user, q, 50)library-wide, folders and files separately, ignores current folder; caption "Search results"; NoResults empty state; no row options. - Empty states:
EmptyFolder(note a kind filter that hides everything also shows this),NoResults,SharedFolderEmptyfor grantees. - Rename-in-place when
?edit=<id>: inline form posting to/api/folder/renameor/api/file/rename, input maxlength 255, required. - Created-link panel
?created=<token>: one-time share URL{origin}/s/{token}with "copy once" note. - Refusal banner from
?refusal=for names create, rename, move, delete, upload (not share).
- Owner view of a folder:
- GET
/search: 303 to/drive?q=<raw q>(blank ->/drive). Onlyqforwarded. - Move picker
?move=kind:id: modal listing "Drive" root plus all owned live folders (depth-first, one list_children per folder, N+1). Folder target excludes its own subtree (display-path prefix match, a folder name containing " / " can confuse it). Each row is a POST form (/api/file/movewith folder_id, or/api/folder/movewith parent_id; blank = root). - Share modal
?share=kind:idrendered byshare.rs(see 2.7). - Grantee view
drive_shared: granted folder title, "Shared with you" + access chip (View only / May download), listing with sort and kind only (q/edit/share/move ignored), trail stops at granted root, no write affordances.
Folder mutations (all owner-only, POST, 303 back via back_to, refusal via redirect):
- POST
/api/folder/create(parent_id,name). Parent must be owned and live. Blank name -> quick-create "New folder" (postfixed by store) and redirect to/drive?folder=<parent>&edit=<newid>(sort/kind dropped). Name not trimmed when stored. - POST
/api/folder/rename(id,name). Owned+live folder. No server-side trim, emptiness or length check in this layer (HTML maxlength only); the store enforces names. - POST
/api/folder/move(id,parent_id). Owned+live folder and parent. Cycles/self-nesting -> storeCycle-> refusalForbidden. - POST
/api/folder/delete(id). Soft-trashes the subtree (store). Cross-owner / missing -> NotFound refusal. - store error mapping: QuotaExceeded -> QuotaExceeded; NotFound/CrossOwner -> NotFound; Cycle -> Forbidden; other -> Unavailable.
Name rules (store): labels only, path components stripped (../../etc stored as etc), control chars removed, empty -> "Untitled", max 255 chars (postfixed names truncate the stem so the total fits; the extension itself is not truncated). Collisions among live siblings get " (2)", " (3)"... inserted before the extension for files (report.txt -> report (2).txt; extension-less note -> note (2)), appended for folders (root (2)). Files and folders are separate namespaces. Name match is exact and case-sensitive (BINARY collation; "Zeta" sorts before "alpha").
2.3 Upload
Two paths, both owner-only.
A. Single-shot multipart (POST /files): fields folder_id (must precede file parts) and one or more file parts. Each part fully buffered in memory, then insert_file. Empty list = redirect with no refusal. Folder must be owned and live (else NotFound, redirect /drive). Stops at the first refusal; files already inserted stay; only that refusal is reported. Redirect 303 /drive?folder=<id> (+ &refusal=&on=upload). Body limit 2 GiB (main.rs). Parse errors return Unavailable before any insert. Blob puts happen inside the store's write transaction.
B. Chunked, resumable (JS in the drive page; threshold 8 MiB in JS LIMIT = 8388608; smaller files use A). Chunk size fixed at 8 MiB (CHUNK_SIZE = 8388608, server-fixed, returned by start). Chunk body limit 32 MiB (main.rs /api/upload).
- POST
/api/upload/startbody{folder_id?, name, size_bytes}->{id, chunk_size}. Folder must be owned, live. Quota pre-check against user quota minus other active sessions' declared sizes (staged_claim). Creates session rowstate=active,expires_at = now + 24h(UPLOAD_TTL_HOURS = 24), and staging dir. - GET
/api/upload/{id}->{id, chunk_size, size_bytes, name, folder_id, uploaded: [indexes]}. Works on expired sessions; lets the client skip staged chunks. Other owner / unknown ->{"err":"NotFound"}. - PUT
/api/upload/{id}/{index}raw body ->{received_bytes, size_bytes}. Index must be < chunk_count; byte length must equal the expected length (last chunk may be short) elseBadChunk; expired or not-active ->UploadExpired. Written atomically touploads/<id>/<index>.received_bytesis measured from disk, not incremented. - POST
/api/upload/{id}/finish->{ok: "<new file id>"}. Requires all chunks; assembles them in order to a temp file, checks total size; MIME sniffed from first 1 MiB (never the uploader's claim); thumbnail computed outside the transaction; then in one IMMEDIATE transaction: re-checks session active and unexpired, parent live, quota (excluding this session's own claim), name collision (postfix, never refused); adopts the temp tofiles/<id>, puts thumb, inserts row, marks sessiondone, refreshes usage; staging dir removed after commit. Chunks kept on refusal so the client can retry. Refusals: UploadExpired, NotFound, BadChunk, QuotaExceeded. - POST
/api/upload/{id}/abort->{ok: null}. Marks active session aborted and removes staging dir. Idempotent (unknown id answers{err:"not_found"}in one path, per upload.rs). - Client behaviour (JS in drive page): 3 attempts per chunk, backoff 1000*attempt ms; one session restart on UploadExpired; resume key in localStorage
in-upload:<folder>:<name>:<size>. - Expired sessions: boot sweep marks active sessions past
expires_atas aborted and deletes staging dirs (prune_expired_uploads); rows are kept as aborted.
Quota: used_bytes counts all live and trashed file bytes; checked at start, at finish and for service pushes. Staged sessions' declared sizes count against new uploads' headroom.
2.4 Download, preview, viewer
- GET
/file/{id}(?dl=1forces attachment; presence of the key counts, evendl=0).- Unauthenticated -> 303
/. Not visible (not owner and no grant, or trashed and not owner) -> 404. - Forced download needs
may_download(owner, or grant with can_download; trashed files are not downloadable). Otherwise 404. - Inline only if not forced and mime in: image/* (except image/heic), video/, audio/, application/pdf, text/plain; never image/svg+xml or text/html (forced to attachment).
- Content-Disposition:
inline|attachment; filename="<ascii-sanitised>"; filename*=UTF-8''<pct>; ASCII fallback maps non-[A-Za-z0-9._-] to_. - Content-Type = stored mime (not re-sniffed).
Accept-Ranges: bytes.Cache-Control: private, max-age=31536000, immutable. - Range: single
bytes=a-b,a-,-Nonly; multi-range, malformed, start>end,-0ignored (full 200). Start past end -> 416 withContent-Range: bytes */total. Valid -> 206 withContent-Range. - Streams via
file_stream(64 KiB frames per doc). - Download counter
download_countincremented only when forced, successful, and either no Range or range starts at 0.
- Unauthenticated -> 303
- GET
/thumb/{id}: webp thumbnail (image/webp), visible to the same audience as/file(trashed owner can still fetch). Not visible -> plain 404. ETag = quoted FNV-1a hex of bytes;If-None-Matchexact match -> 304;Cache-Control: private, max-age=31536000, immutable. - GET
/view/{id}: viewer page. Not visible -> framework 404. Shows entry chip, name, meta "mime · size", uploaded date, download count, details panel (size, uploaded, downloads). Back link: trashed ->/trash;?from=shared->/shared; else/drive. Download button only when may_download; "View only" note for non-owner without download.- Viewer kinds (
viewer_kind): Image (<img>, all viewers), Video and Audio (house media player, all viewers), PDF (<object>) and Text (<iframe sandbox="">) only with download grant, otherwise "preview unavailable"; everything else "preview unavailable". image/heic is download-only. - Media player: play, seek, volume, mute, speed 0.5-2, fullscreen (video); dead after media error or 5 s with readyState 0 and networkState 2.
- Context menu blocked over the viewer stage (viewer_guard_script).
- Viewer kinds (
2.5 Trash
- GET
/trash(?kind=all|folders|files,?q=case-insensitive substring on name,?sort=key:dirwith keys name, deleted (default, desc), uploaded, size; folders sort as size 0). Lists owner's trashed folders and files, each with a...menu: Restore and Delete forever. Trashed file rows link to/view/<id>(owner preview); trashed file chips use mime-class glyph (no thumbnail). Unauthenticated -> 200 message page (not a redirect). Empty-trash button shown only if the unfiltered list is non-empty. - Soft delete: files via POST
/api/file/delete(trash only, bytes kept, still count toward quota); folders via POST/api/folder/delete(subtree trashed with one shared timestamp). - POST
/api/trash/restore(kindfile|folder,id): row must be owner's and trashed. File restore: refused if an ancestor folder is trashed; name collision postfixed; no quota check (trashed bytes already counted). Folder restore cascades to descendants stamped with the same timestamp; individually trashed rows keep their earlier stamp; top folder name postfixed; refused if parent chain trashed. Refusals mapped viarefusal_of(AncestorTrashed -> refusalrestore/on). Redirect to/trash. - POST
/api/trash/purge(kind,id): permanent. File: removes rows (share_link and share_user rows for the file too) then best-effort blob deletes (files/<id>,thumbs/<id>). Folder: deepest-first row deletion of the trashed subtree, files and blobs. Sessions whose folder is purged get folder_id NULL (finish into root). Unknown or live rows: refused (NotFound for files on the route side; purge_file returns Ok(false) on live rows, purge_folder returns NotFound). - POST
/api/trash/empty: purges everything the owner trashed (storeempty_trash, guard re-checked under the write lock). - Auto purge:
purge_expired(now - purge_after_days)runs once at boot in the background (default 30 days).openitself never purges trash.
2.6 Search
- Drive search (see 2.2) and
/searchredirect. Storesearch(owner, q, limit): LIKE with escaped%,_,\(ESCAPE '\'), ASCII case-insensitive under SQLite defaults (unverified on Turso), limit clamped 1..=100 per list, no pagination. Owner scoped; trashed hidden.
2.7 Sharing
Per-person grants (share_user):
- Only the owner of a live target can add or list grants; only owner can remove (trashed targets allowed for removal).
- Grant has one flag:
can_download(view-only = false). Re-sharing upserts and can flip the flag. - Grantee by lowercased email from the im directory mirror; unknown address -> NotFound. Sharing with yourself is a silent Ok.
- POST
/api/share/user/add(form: kind, target_id, email list). Multi-address is not atomic: loop returns early on the first unknown address (earlier grants persist). - POST
/api/share/user/remove(kind, target_id, email). Removing a non-existent grant is not an error. - Share modal (rendered inside the drive page via
?share=, not a route): people picker from im directory (provision_userper directory member on each render, so the GET path writes), grants list with name, email, access chip and Remove form. Shows only the first live link and hides the create form while one exists (the API allows several). - GET
/shared: grants made to the reader (folders and files; dead or trashed targets silently dropped). Signed-out visitor gets a 200 message page. - Grantee access:
can_see(any live ancestor folder grant counts, most permissive wins) andcan_download.
Public share links (share_link):
- POST
/api/share/link/create(form: kind file|folder, target_id, can_download (absent = false; "", 0, false, no, off = false), expires_in_days (absent/blank = none; else positive integer, else Forbidden; no maximum; checked_mul by 86400), password (trimmed; blank = none)). Owner-only (CrossOwner/NotFound). 303 to/settings?section=linkswithcreated=<token>on success.- Token: 32 random bytes, base64url no padding (43 chars). Only SHA-256 (unsalted, base64url) is stored in
token_hash(unique). Plaintext also sealed (XChaCha20-Poly1305, app key) into settingshare_token:{link_id}so the owner can redisplay the URL; links created before sealing (or after key loss) show a masked value and a Remint action. - Origin:
base_urlsetting if set, else configpublic_origin()(listen address). Share URL{origin}/s/{token}.
- Token: 32 random bytes, base64url no padding (43 chars). Only SHA-256 (unsalted, base64url) is stored in
- POST
/api/share/link/revoke(form id): setsrevoked_at = COALESCE(revoked_at, now); owner only; idempotent. Deletes the sealed token setting. - POST
/api/share/link/remint(form id): creates a fresh link with the same kind/target/flags (carries expiry only if still in the future; an elapsed expiry becomes no expiry), revokes the old one. Known issues: remint does not check revoked/expired on the source; creates before revoking. - Expired links are not deleted; they stop resolving. Revoked/expired -> dead.
- Public page GET
/s/{token}(no session; the token is the credential). Priority:dl>media>thumb> card.- Dead or unknown token: 200 HTML "no longer works" card (never 404; same status and body for dead and view-only-download).
- Card: file card (name, mime, size; download only when can_download), or folder listing (folders then files by lowercase name; each file with thumbnail where ready). Folder browsing with
?folder=and?file=; each folder ancestor must be live and owned by link owner. ?dl=1: download bytes (attachment) only if can_download; else dead card. Counts toward the file's download_count (same counter as owner downloads; not per link; counts before serving).?media=1: inline video or audio regardless of can_download (range supported,Content-Disposition: inline,Cache-Control: private, no-cache).?thumb=1: webp thumbnail regardless of can_download (Cache-Control: private, max-age=31536000, immutable, FNV ETag).- Password-protected link: without the proof cookie, GET shows a password gate (no file name). POST
/s/{token}(form password) verifies with Argon2; success sets cookiein_link_<link_id>(value = base64url(SHA-256("token:phc")), Path=/s, HttpOnly, SameSite=Lax, Secure only if OIDC issuer is https, session cookie no Max-Age) and 303 to/s/{token}; failure 303 to/s/{token}?wrong=1with "Wrong password." The gate covers card, bytes, media and thumbs. - Downloads from links:
Content-Disposition: attachment; filename="<safe>"(quotes, backslashes, control chars removed; raw UTF-8, no filename*),Cache-Control: private, no-cache. - No view counter, no use limit, no lockout or rate limit on password guesses.
2.8 Quota
- Per-user
quota_bytes(default from configdefault_quota_bytes, 10 GiB) andused_bytes(sum of all file sizes owned, live and trashed; recomputed on each mutation). - Enforced on: folder create (none, folders are 0 bytes), upload start (pre-check), upload finish, file insert, service push. Restore and rename/move skip checks.
- Admin can set quota (see 2.9); lowering below usage is allowed and not enforced retroactively. Quota 0 accepted.
- Profile shows "used / quota" and a bar (
quota_percent, capped at 100; quota 0 shows 100).
2.9 Settings (GET /settings, ?section=profile|links|everyone|server|service, ?saved=, ?created=, ?shown=)
Rail: Profile and Links for everyone; Everyone, Server and Service for admins (non-admin requests for admin sections fall back to Profile). Reached from the user menu, not the topbar.
- Profile (all): display name and email (read-only, no profile edit route here), storage used bar, Connection card (OIDC issuer and client id, stream connected or reconnecting, age of last roster event and last full pass; secret never shown), preferences form.
- POST
/api/settings/preferences:uiin {instrument, ledger} (default instrument for new users; the migration default is ledger, see oddities),themein {light, dark} (new users default dark),languagein {en, tr} (default en). Unknown values refused (BadUi, BadTheme, BadLanguage). Success ->/settings?section=profile&saved=preferences.
- POST
- Links (all): lists the user's live links (skips revoked): target name, expiry (
Expires <RFC3339>or Never), May download / View only, copy-once URL (?created=), revoke form, remint for legacy links. - Everyone (admin): table of all users (name, admin and disabled chips, email, used/quota, forms).
- POST
/api/settings/quota(user_id, quota decimal, quota_unit MiB|GiB; 1 MiB = 1048576, 1 GiB = 1073741824). Refused for service accounts (ServiceQuota), BadLimit for negative/non-finite or unknown unit. Zero accepted. Amount rounded to 2 decimals (silent rounding on re-save). - POST
/api/settings/disable(user_id, disabled). Missingdisabledfield means DISABLE (dangerous default)."",0,false,no,off(case-insensitive) mean enable; anything else disables. Self-disable refused (Forbidden). Admins can disable other admins. Disabling and enabling both announce Revoked to that user's open tabs.
- POST
- Server (admin): effective origin display; POST
/api/settings/base_url(base_url): empty = fall back; non-empty must start http:// or https:// and must not end with/(Config::validate_base_url), else BadBaseUrl; stored in settingbase_url. - Service (admin): see section 3. POST
/api/settings/service_add(service from mintable list, name),/api/settings/service_rotate(service),/api/settings/service_revoke(service). Minted key shown once via?shown=<ticket>(ticket exchanged once, in-memory shelf, 10 min TTL, lost on restart). Rotate and revoke are one-click after expanding a details element (no confirm).
2.10 Admin-only controls outside settings
- Admin status comes from im's directory
adminflag (mirrored), or the first user at provisioning. - Disabled accounts are signed out on their next request.
- Family flyout (topbar app switcher) lists sibling services from im's family list with health dots (probes
{url}/healthz, 2 s timeout, 30 s cache).
2.11 Avatars
- GET
/avatar/{user_id}(session required; no session -> 401 empty body). Unknown id or store error -> 404 withCache-Control: private, max-age=300. - ETag
"p{photo_version}"(version from local row).?v=<photo_version>givesprivate, max-age=31536000, immutable; other requestsprivate, no-cache. ExactIf-None-Match-> 304 without contacting im. - Otherwise fetches photo bytes from im (
directory.photo(oidc_sub)), serves with im's content type (fallback octet-stream). No size limit, no server cache. - Topbar avatar: initials in one of five tones (hash of id mod 5) with the photo image overlaid; broken image hidden by JS.
2.12 Live updates
- GET
/api/live: Server-Sent Events, unnamed events (message), JSON data. Requires session (401 empty otherwise). One stream per tab; windowlive_seconds= 300 then the server closes and the browser reconnects. Keepalive interval is topcoat's default (unverified). Graceful shutdown ends streams immediately. - Frame:
{"topic":"<kind>","id":"<user id>","seq":N}where kind is library, trash, shares, profile, revoked, admin.seqis a process-global counter starting at 1 on each boot (not per user). {"topic":"resync"}on broadcast lag (stream stays open).{"topic":"revoked"}when the signed-in user's own account is revoked, then the stream ends.- Filter: own id always heard; Profile heard by everyone; Admin heard by admins only; Revoked only by the target; other users' Library/Trash/Shares dropped.
- Topics fired: Library(owner) on folder/file create, rename, move, delete, restore, purge, upload finish, record_download, service push/delete; Trash(owner) on trash, restore, purge, empty; Shares(owner) on share link and grant changes; Profile on preferences change and provisioning updates; Admin on quota, disable, provisioning; Revoked on disable/enable.
- Browser (JS
live_script): one EventSource per tab; resync and profile refresh everywhere;adminonly on Settings;sharesonly on Shared;trashonly on Trash;libraryelsewhere;revokedhard-redirects to/; on error probes/api/meand leaves on 401; morph refresh debounced 200 ms; 60 s tick refresh where[data-tick]exists.
2.13 Chrome, navigation, UI behaviour
- Topbar: monogram/wordmark "in", family app switcher, nav tabs Drive, Shared, Trash, user menu (name, email, admin badge, Profile link to
{issuer}/people/{sub}, Settings, Sign out). - Soft navigation: same-origin links and forms swap the body via fetch with field and focus restoration; multipart uploads via XHR with progress and cancel;
in:wireevent after swaps; build-skew triggers one reload per build. - Live search on drive search box (200 ms debounce).
- Custom dropdown replaces native selects (keyboard arrows, Enter, type-to-filter, search when >7 options).
- Notices: persistent toast stack (never auto-dismisses; dismiss button), mirrored in
window.__inNotices. - Escape key manager (priorities: dropdown 95, viewer and delete confirm 90, user menu 40 (dead), datepicker 20 (absent), row context menu 10 (absent)).
- Theme/skin:
data-theme="dark"anddata-ui(instrument default or ledger) from user prefs. No light/dark toggle outside settings. - Language:
<html lang>from i18n. - Overlays: viewer scrim, modal scrim (share, move, delete confirm via details), query keys scrubbed on close.
- Errors: 404 page inside the shell (catch-all
/{*path}and NotFound). No styled 403 or 500 page. - Health: GET
/healthzreturnsok <IN_BUILD_SHA>(sha from git at build time ordev), no DB check.
3. Machine service API (crates/in-web/src/service.rs)
Auth for all four routes: header Authorization: Bearer <token> (case-sensitive prefix, trimmed, non-empty). The token is hashed (SHA-256, base64url, unsalted) and looked up in service_key.token_hash. The cookie is never read. There is no config key or env var for service keys: admins mint them in Settings > Service (POST /api/settings/service_add, _rotate, _revoke). Token: 32 random bytes, base64url (43 chars), shown once. Disabled account counts as no key (note: service_account_by_token does not check disabled; the caller in server.rs does; unverified in the route path).
Missing or wrong key -> HTTP 401, body {"err":"Unauthorized"} on JSON routes, empty body on byte routes.
JSON routes answer HTTP 200 for both success and refusal.
| Method and path | Request | Success | Errors |
|---|---|---|---|
POST /api/service/files |
multipart/form-data: external_id (text, non-empty), name (text, non-empty), file (bytes). Unknown fields ignored. Body limit 512 MiB. |
200 {"ok":"<file id>"} |
401; missing or empty field: 200 {"err":"BadRequest"}; multipart read error: {"err":"Unavailable"}; quota: {"err":"QuotaExceeded"}; other store error: {"err":"Unavailable"} |
GET /api/service/file/{external_id} |
none | 200 raw bytes; Content-Disposition: attachment; filename="<name with non [A-Za-z0-9._-] -> _>"; Content-Type = stored mime (if parseable); Cache-Control: private, max-age=31536000, immutable |
401 empty body; unknown handle or any store error: 404 empty body |
DELETE /api/service/file/{external_id} |
none | 200 {"ok":true} (unknown handle also {"ok":true}) |
401; store error: {"err":"Unavailable"} |
GET /api/service/status |
none | 200 {"ok":true,"quota_bytes":N,"used_bytes":N} (u64) |
401; store error: {"err":"Unavailable"} |
Service pushes: writes replace in place when external_id already exists for that owner (same row id, new bytes, new name and mime, size charged as the difference); a re-push does not create a second row. Pushed files are hard-deleted (no trash) and get no thumbnail. Service pushes count toward user quota like any file.
Service accounts: one user row per service family, oidc_sub = "service:<service>", admin false, quota from family limit or default_quota_bytes. One key per service (unique index on service_key.service); minting a second key for a service that already has one fails with a Backend error (rotate instead). Re-mint after revoke reuses the account.
Family limits: apply_family_limits sets each service account quota from im's family list limit_bytes (house default when null). Abort on first store error (later accounts not updated) (see oddities).
3.1 Authentication with im
Config [oidc] (in config/in.toml): issuer, client_id, client_secret, optional redirect_uri (default http://<listen host>/auth/callback; unspecified bind maps to 127.0.0.1; port 80 omitted). Cookie name hard-coded in_session. Session cookie key = 32 bytes in in.key (created beside the DB, mode 0600), also used to seal share-token plaintext.
Login flow (in-client crate, mounted with in_client::mount):
/auth/login->{issuer}/authorizewith PKCE S256 (verifier 32 bytes), state and nonce (16 bytes each), scopeopenid profile email. Client id, state and nonce are not percent-encoded in the URL (safe in practice)./auth/callback-> POST{issuer}/tokenwith form:grant_type=authorization_code,code,redirect_uri,client_id,client_secret,code_verifier. Response must carryid_tokenand im'sapp_session(opaque token).- id_token validated: compact JWT, header alg RS256, kid required; JWKS from
GET {issuer}/jwks.jsoncached 3600 s and refetched on unknown kid; RSA PKCS#1 v1.5 SHA-256;iss= issuer;aud(string) = client_id;expin the future;nonce= flight nonce. The id_token identity is then ignored: the app_session is introspected and must return active:true or login is refused. - Session cookie
in_session: base64url(24-byte nonce || XChaCha20-Poly1305(JSON{"app_session":"...","exp":<unix>})). Attributes: HttpOnly, SameSite=Lax, Path=/, Max-Age 30 days, Secure only if the issuer scheme is https. - Per request:
POST {issuer}/introspect(form: token, client_id, client_secret). Missing or non-boolactive, transport failure or missing sub/email/name/exp reads as signed out but keeps the cookie. Optionalphoto_version(default 0). - Logout:
/auth/logoutclears the cookie and redirects to{issuer}/logout?back=<origin>/.
3.2 Family registration (heartbeat)
- Every 300 s (first pass at boot), if
base_urlis set:POST {issuer}/family/registerwith HTTP Basic (client_id:client_secret), JSON{"key":"in","name":"Files","url":"<base_url, trailing slash trimmed>","limit_bytes":null}. Any 2xx is success; otherwise logsim refused with <status>: <error>: <reason>. If base_url is empty it logs and skips registration. - Then
GET {issuer}/family(Basic auth) -> list of{key, name, url, limit_bytes?}; on non-2xx or bad body the last stored list is kept. Success: apply limits to service accounts, store the list JSON in settingfamily(read by topbar flyout and mintable dropdown).
3.3 Directory usage
- Client:
im_client::directory::DirectoryClient::new(issuer, client_id, client_secret)(Basic auth in the test fake). The im client crate is a git dependency (DizeyLab/im, pinned rev), not in this tree, so its endpoint paths below come from the test fake and are not verified against source. - Full pass:
GET {issuer}/directory; each member mirrored withprovision_user(sub, email, name, admin, photo_version, default_quota)andset_user_disabledif disabled differs. - Stream:
GET {issuer}/directory/live(eventsProfile(member)orRevoked{sub}); Revoked announces the local account so its tabs morph to sign-in. Each event updates the health atomics. - On stream end, a full pass runs again. Failures back off 1 s doubling to 30 s cap.
- Photos:
directory.photo(oidc_sub)via avatar route. - Local cache: sub, email, name, admin, disabled, photo_version, quota stored in the user table; not fetched per request.
3.4 mint example
crates/in-client/examples/mint.rs (feature test-seam): mint <in.key path> <app-session-token> [cookie-name=in_session] prints a sealed in_session cookie value valid against that key, expiring in 1 day. Dev helper for smoke runs against a fake im. A missing token argument panics instead of printing usage.
4. Data model
Database: Turso 0.8.0-pre.10 (SQLite-compatible), file database (config), WAL, PRAGMA foreign_keys = ON, busy timeout 5000 ms. Migrations 0001-0007 in crates/in-core/migrations/, concatenated as schema::schema_sql(). Fingerprint of sqlite_master compared at boot; mismatch triggers an automatic rebuild (see section 5.4).
Timestamps: RFC 3339 text (ISO-like). Ordering relies on lexicographic text comparison; stamp() does not normalise to UTC (caller-supplied expires_at could break ordering).
user
- id TEXT PK (ULID); oidc_sub TEXT NOT NULL, unique index (user_oidc_sub); email TEXT NOT NULL (lowercased); display_name TEXT NOT NULL
- admin INT NOT NULL DEFAULT 0; disabled INT NOT NULL DEFAULT 0
- quota_bytes INT NOT NULL; used_bytes INT NOT NULL DEFAULT 0 (recomputed from file sizes)
- created_at TEXT NOT NULL; last_seen_at TEXT
- 0002: ui TEXT NOT NULL DEFAULT 'ledger' (instrument or ledger skin)
- 0003: theme TEXT NOT NULL DEFAULT 'light' (light or dark); language TEXT NOT NULL DEFAULT 'en' (en or tr)
- 0006: photo_version INT NOT NULL DEFAULT 0 (avatar cache stamp)
folder
- id TEXT PK; owner_id TEXT NOT NULL FK user; parent_id TEXT FK folder (NULL = root); name TEXT NOT NULL (label only); created_at NOT NULL; deleted_at TEXT (trash stamp, NULL = live)
- index folder_by_parent(owner_id, parent_id). No DB uniqueness for live sibling names (application-level postfixing only).
file
- id TEXT PK; owner_id FK user; folder_id FK folder (NULL = root); name NOT NULL; mime NOT NULL (sniffed server-side); size_bytes INT NOT NULL
- thumb_state TEXT NOT NULL DEFAULT 'none' (none, pending, ready, failed); created_at NOT NULL; updated_at NOT NULL; deleted_at TEXT (trash)
- index file_by_folder(owner_id, folder_id)
- 0004: download_count INT NOT NULL DEFAULT 0
- 0007: external_id TEXT (service handle), partial unique index file_external_by_owner(owner_id, external_id) WHERE external_id IS NOT NULL
share_link
- id TEXT PK; token_hash TEXT NOT NULL, unique (share_link_token); kind TEXT NOT NULL ('file' or 'folder', no CHECK); target_id NOT NULL; created_by FK user; can_download INT NOT NULL DEFAULT 1; created_at NOT NULL; expires_at TEXT; revoked_at TEXT
- 0005: password_hash TEXT (Argon2id PHC string, NULL = no password)
share_user (per-person grants)
- kind TEXT; target_id TEXT; user_id TEXT FK user; can_download INT NOT NULL DEFAULT 1; created_at NOT NULL; PK(kind, target_id, user_id). No index on user_id (grantee lookups scan).
upload_session
- id TEXT PK; owner_id FK user; folder_id FK folder (nullable); name NOT NULL; size_bytes NOT NULL; chunk_size NOT NULL; received_bytes INT NOT NULL DEFAULT 0; state TEXT NOT NULL DEFAULT 'active' ('active', 'done', 'aborted'; no CHECK); created_at NOT NULL; expires_at NOT NULL
setting (0004)
- key TEXT PK; value TEXT NOT NULL. Instance key/value: base_url, family (JSON), share_token: (sealed plaintext token), others.
service_key (0007)
- token_hash TEXT PK (SHA-256 of bearer token); name NOT NULL; service NOT NULL; user_id FK user; created_at NOT NULL; unique index service_key_service(service) (one key per service)
Mismatches and notes:
- 0001_init.sql's CREATE TABLEs predate later ALTERs (they lack user.ui/theme/language/photo_version, file.download_count/external_id, share_link.password_hash) and omit setting and service_key. Its header claims all changes land in three places; this is not kept. The authoritative schema is the migrations applied in order.
- Reconcile backfill defaults disagree with migrations for old databases: map uses ui 'instrument' and theme 'dark' while 0002/0003 default ui 'ledger' and theme 'light'. Rebuilt and migrated DBs can differ in preferences.
- No CHECK constraints on enum-like columns; validation lives in parse functions.
- Trait-level types:
ThumbState(none/pending/ready/failed),UploadState(active/done/aborted),ShareKind(file/folder).
5. Blob storage design
5.1 Local tree (default)
Storage root = config storage path, default <database parent>/storage. Created at boot with mode 0700 (files/, thumbs/, uploads/). Boot also removes a legacy storage/previews directory unconditionally.
files/<file-id>: bytes, keyed by row id only (name never in path).thumbs/<file-id>: WebP thumbnail.uploads/<session-id>/<index>: staged chunks (decimal index); always local, even with R2.- Temp files:
putwrites<key>.<ulid>.tmpin the same directory, then renames (no fsync). Crash debris is reclaimed by the sweep. adopt(key, staged, expected_len): length check then rename into place (same filesystem required).getreturns None on NotFound;span(key, start, len)clamps to real length and streams 64 KiB frames;deleteidempotent;list_with_times(dir)lists files with mtime.
5.2 R2 (optional, config [storage.r2])
- Presence of the table selects R2. Required: account_id, bucket, key_file. Endpoint
https://<account_id>.r2.cloudflarestorage.com, region "auto", viaobject_storeAmazonS3. Plain HTTP is test-only. - Credentials: key_file is a plaintext two-line file (access key id, then secret). Read at boot by in-web main.rs; empty values refused. The app does not create it or enforce its mode.
- Keys identical to local:
files/<id>andthumbs/<id>. Uploads are never in the bucket. put: single PUT of the whole buffer (thumbnails, small inserts).adopt: streams the staged file as multipart upload with 8 MiB parts; only the last part may be short; a zero-byte file is one empty PUT; on error it aborts the multipart upload and keeps staging; on success unlinks staging.span: HEAD for size, clamp, then ranged GET (honest length from response). NotFound between HEAD and GET -> None.list_with_times("files"|"thumbs"): prefix list, mtime as unix seconds (used by the sweep).- Ordering contract (stated in both blob modules): bytes land at their key before the row commits; bytes are deleted only after the row is gone or can never name them. Exception: finish_upload adopts the file before committing; a failed commit leaves an orphan that the boot sweep reclaims once it is older than the watermark.
5.3 Upload staging
Chunks written atomically (temp + rename) to uploads/<session>/<n>. received_bytes is recomputed from disk. Finish assembles into files/<id>.<ulid>.tmp and adopts it. Session dirs are removed after commit, on abort, and on expiry by the sweep. Declared sizes of active sessions count against quota for new uploads (staged_claim).
5.4 Reconcile and rebuild (crates/in-core/src/store/reconcile.rs)
- CLI:
in reconcile [--dry-run] [--yes](in-web main.rs; exits after running). - Boot:
repair_if_staleruns before any long-lived handle opens the database. If the file exists, is non-empty and its sqlite_master fingerprint (normalised, comments and IF NOT EXISTS stripped) differs from the declared schema, reconcile runs with auto: true, then reopens and re-fingerprints; a mismatch refuses to start. - Rebuild steps: write
<db>.rebuilt, create declared schema, copy each table with explicit column maps (foreign keys off during copy), verify (FK check, integrity_check == ok, row counts per table; noteservice_keyis omitted from the count list), checkpoint WAL, rename original to<db>.backup-<UTC timestamp>(with -wal/-shm), rename rebuilt into place. Originals are never deleted. Blobs untouched. - Known hazards: swap window with no lock; manual reconcile against a running server copies without locking.
5.5 Boot sweep (turso_store.rs boot_sweeps, background after the port opens)
prune_expired_uploads(now): active sessions past expires_at -> aborted; staging dirs removed.sweep_orphan_files: under one IMMEDIATE transaction (write lock held for the whole pass):- id sets: all file ids; file ids with thumb_state='ready'; active upload_session ids.
- watermark = newest timestamp among file.created_at, file.updated_at, upload_session.created_at.
- For
files/andthumbs/: unknown objects with mtime <= watermark are deleted; newer ones are kept and logged; known ids missing on disk are logged only. Empty DB = nothing deleted. - For
uploads/: any directory not matching an active session is removed under the same watermark rule.
purge_expired(now - purge_after_days): trash older than the cutoff is purged (same background task, not inopen).
5.6 Content sniffing (crates/in-core/src/store/sniff.rs)
Pure function over bytes; result written to file.mime and drives thumbnail eligibility and serve disposition. The uploader's claim is never used.
- Magic numbers: PNG, JPEG, GIF, PDF, zip (PK\x03\x04), OLE2 (D0 CF 11 E0 ...), gzip, Matroska/EBML (1A 45 DF A3), WebP, WAV, FLAC, Ogg, MP3 (ID3, FF FB/F3/F2), ISO-BMFF ftyp brands: avif, heic/heix/hevc/heif/mif1/msf1, qt, generic mp4.
- Zip: substring scan picks xlsx (
xl/workbook.xml), ods (opendocument.spreadsheet), pptx (ppt/presentation.xml), else application/zip. - OLE2: "Workbook" in UTF-16 gives application/vnd.ms-excel, else application/x-ole-storage.
- Matroska: track walk; video/webm only when all tracks are VP8/VP9/AV1 or Vorbis/Opus; otherwise video/x-matroska; unparseable keeps video/webm.
- Fallback: valid UTF-8 (including empty) is text/plain; otherwise application/octet-stream.
- Sniff runs on insert, service insert and finish (first 1 MiB for finish).
5.7 Thumbnails (crates/in-core/src/thumbs.rs)
- Eligible (
thumbnailed(mime)): any image/* (including SVG and HEIC, which cannot decode; they fail), plus video/mp4, video/webm, video/quicktime, video/x-matroska. - Max edge 512 px, output WebP. Images:
imagecratethumbnail(512,512)then WebP encode, in-process. Source cap 64 MiB (THUMB_SOURCE_CAP); larger files get failed without decoding. No pixel cap or explicit decode timeout in thumbs.rs. - Video: external
ffmpegon PATH (checked once, cached). Seek 1 s (first frame for short clips),scale=512:512:force_original_aspect_ratio=decrease,-c:v libwebp, 10 s kill timeout per attempt, two attempts (worst case ~20 s). Output validated as RIFF....WEBP. Video bytes for the in-memory path are spilled tostd::env::temp_dir()asin-thumb-<pid>-<counter>.binwith default permissions and removed afterwards (plaintext spill; leaks on crash). - States: none (not attempted), pending, ready (blob at thumbs/), failed. Failures never retried.
- Serving:
thumb_bytesonly if state ready.
6. Configuration
Loading: Config::load() reads ./config/in.toml relative to the process working directory (fixed path; no env overrides; no CLI flag; no upward search). If absent, the file is written from development defaults and the process stops with "missing oidc.issuer" (first-run behaviour). A successful boot rewrites the file to append missing optional top-level keys (complete()), which can modify the file under a deployment. Parse errors exit 2. Relative paths resolve against the directory containing config/. Unknown keys are collected and logged.
| Key | Type | Code default | config/in.toml value | Rules |
|---|---|---|---|---|
database |
string | required | "in.db" |
empty -> Missing |
storage |
string path or [storage] table | <db parent>/storage |
"/home/tahinli/Documents/Code/Rust/in/storage" (absolute, points into a sibling tree Rust/in, not Rust/old_in) |
empty -> default |
listen |
SocketAddr | 127.0.0.1:7655 |
127.0.0.1:7655 |
hostnames rejected (Invalid) |
live_seconds |
u64 | 300 | 300 | 0 invalid |
purge_after_days |
u32 | 30 | 30 | no range check |
default_quota_bytes |
u64 | 10 GiB (10737418240) | 10737418240 | no range check; 0 accepted |
base_url |
string | none (use listen) | "" |
empty = None; must start http:// or https:// and not end with / |
[oidc] issuer |
string | required | "http://127.0.0.1:7650" |
empty -> Missing; scheme not enforced |
[oidc] client_id |
string | required | "01M21CE4Y692M537BJ7AAYE5RT" |
empty -> Missing |
[oidc] client_secret |
string | required | "dev-drive-secret-2026" (a live-looking secret committed to the repo) |
empty -> Missing |
[oidc] redirect_uri |
string | http://<listen host>[:port]/auth/callback |
commented out | not validated |
[storage.r2] account_id |
string | optional table | commented example | required if table present |
[storage.r2] bucket |
string | optional | commented example | required |
[storage.r2] key_file |
path | optional | commented example | required; 2-line plaintext key file |
Other fixed values: cookie name in_session; flight cookie in_session_pkce; link cookie in_link_<id>; session key file in.key beside the database (32 raw bytes, 0600 intended); family registration key in, name Files; FAMILY_SECONDS = 300; UPLOAD_TTL_HOURS = 24; CHUNK_SIZE = 8 MiB; THUMB_SOURCE_CAP = 64 MiB; broadcast channel capacity 256; busy timeout 5000 ms. Body limits: /api/upload 32 MiB, /api/service/files 512 MiB, /files 2 GiB (main.rs).
Secrets: oidc.client_secret is plaintext in config; R2 credentials are plaintext in key_file; the link sealing key is in.key. Config and OidcConfig derive Debug and contain the plaintext client_secret (leak risk through debug output).
Cargo: workspace resolver 3, edition 2024, GPL-3.0-or-later. Profiles: release (fat LTO, 1 codegen unit), dist (thin LTO, 16 units; used by deploy). Pins: turso =0.8.0-pre.10, im-client git rev, rsa 0.10.0-rc.18.
7. Security mechanisms
- Authentication: OIDC authorization code with PKCE S256, state and nonce checks, RS256 id_token signature check against JWKS, then app_session introspection with im on every request.
- Session cookie: XChaCha20-Poly1305 sealed with
in.key; HttpOnly; SameSite=Lax; Path=/; 30-day Max-Age; Secure only when the issuer is https (not the app's own scheme). - CSRF: no CSRF token anywhere in the codebase. The only mitigations are SameSite=Lax on cookies and a middleware that rewrites redirect Locations using the Referer (
back_to,carrying,same_origin) for form posts. Origin header is not examined. Logout is a GET. - Cross-owner: answered as 404 by design, never 403. Grantees: explicit
can_see/can_downloadchecks; trashed targets excluded. - Share tokens: 256-bit random, stored only as unsalted SHA-256; plaintext sealed separately for redisplay.
- Share passwords: Argon2id v0x13, m=19 MiB, t=2, p=1, random salt, PHC strings; verified in spawn_blocking; malformed hash verifies false. Unlock proof cookie: SHA-256("token:phc"), unkeyed, no expiry, no rotation. No rate limiting or lockout. Password trimmed at creation, not at unlock.
- Content-type handling: mime from sniffing (never uploader claim); inline disposition only for an allow-list; SVG and HTML forced to attachment;
text/plaininline allowed; PDF inline; viewer iframe sandbox="" for text. - Headers:
Cache-Controlset per response class (private, immutable for content keyed by id, no-cache for mutable, no-cache on HTML via global middlewarecache_directives). No CSP, no HSTS, no X-Content-Type-Options, no Referrer-Policy, no X-Robots-Tag anywhere in the code (framework defaults unverified). - Content-Disposition: attachment filenames sanitised (ASCII fallback plus filename* for normal downloads; quote/backslash/control stripped for share downloads).
- Size limits: body limits per route as above; per-user quota; per-file thumbnail cap 64 MiB; chunk size fixed at 8 MiB and validated per chunk; no per-file upload cap beyond quota and body limits.
- Service keys: bearer tokens, SHA-256 hashed at rest, one key per service, shown once via in-memory shelf (10 min TTL, lost on restart).
- Secrets at rest: client_secret and R2 key file in plaintext; key files created then restricted (brief default-permission window in some paths).
- Process: no tracing crate; logging is println/eprintln.
8. UI pages
/: sign-in card (wordmark, Sign in button, auth notes) for signed-out; redirects to drive for signed-in users. Title bug (see oddities)./drive: folder list with topbar, filter bar (search, sort, kind, "+" menu), column header, rows (folders then files), row options, breadcrumb trail, upload control and drop overlay, empty states, rename-in-place, created-link panel, move picker modal, share modal, refusal banner. Grantee variant: read-only shared folder./search: redirect only./view/{id}: file viewer with preview (image, video, audio, PDF, text as allowed), details panel, download button, back link./trash: trashed folders and files with filter, search, sort, per-row restore and purge menu, empty-trash button, countdown text./shared: grants made to you (folders and files), Shared topbar tab, message page when signed out./settings: sections Profile (identity, quota bar, preferences, connection card), Links (share links with copy-once URL, revoke, remint), Everyone (admin user table with quota and disable), Server (admin base URL), Service (admin keys: mint, rotate, revoke with one-time key display)./s/{token}: public share page: file card, folder listing with thumbnails, password gate, media player (?media=1), dead-link card, download only where allowed.- 404 page within the shell (catch-all). No 403 or 500 page.
- Overlays and dialogs: viewer scrim, modal scrim (share, move, delete confirm), notice toast stack, custom dropdown panels.
- Themes: instrument (default, dense) and ledger (serif, warm paper) skins; light and dark tokens. Styling sources: style/main.scss (5538 lines), style/_instrument.scss, style/_ledger.scss; compiled at build by grass into the stylesheet with fingerprint checked at boot.
- Many stylesheet blocks are dead (board, task detail, mail rules, profile, logs, datepicker families). See oddities.
9. Localization
- Two locales, inline in code:
Lang::En,Lang::Tr(crates/in-web/src/i18n.rs).Keyenum with 185 variants; both matches exhaustive with no fallback arm, so a missing translation is a compile error. No runtime fallback path, no interpolation, no plural rules. - Selection: signed-in user's stored
language(anything other than "tr" is English); signed-out or user lookup error: first tag ofAccept-Language(q-values ignored; primary subtag only); else English. No cookie, no query parameter. - Hard-coded labels not keyed: "English" and "Türkçe" in the language select; "MiB" and "GiB" in the quota unit select.
<html lang>from the code.
10. Health and operations
- GET
/healthz: 200, bodyok <IN_BUILD_SHA>; checks only that the HTTP server answers. Unauthenticated; publishes build commit. - Family health probes:
{url}/healthzwith 2 s timeout, accepts 2xx and body starting with "ok", body truncated to 64 chars, cached 30 s (for the topbar family flyout dots). - Directory health: atomics for stream connected, last event age, last full-pass age (shown on Settings Connection card).
- CLI:
in reconcile [--dry-run] [--yes]. - Startup order (main.rs): CLI check; config load and completion; asset bundle load and stylesheet fingerprint check (exit 2 on mismatch); storage tree creation; optional R2 client; store open (migrations, repair_if_stale; panics on failure); boot sweeps and trash purge in background; in.key load or create; OIDC client mount; directory sync task; family sync task; listener bind (panics on failure); graceful shutdown on SIGINT/SIGTERM (ends SSE streams).
- Deploy: GitHub Actions on push to main (see section 11).
11. Build, test and deploy
Build:
crates/in-web/build.rscompiles style/main.scss with grass intocrates/in-web/assets/main.css; emitsIN_STYLE_FINGERPRINT(sha256 of css) andIN_BUILD_SHA(env, default "dev"). rerun-if-changed covers only the three scss files.- Asset bundling in CI:
topcoat asset bundle --package in-web --profile dist --out stage/assets(topcoat-cli 0.9.0). - No i18n build step (i18n is hand-written Rust).
Deploy (.github/workflows/main.yml):
- Trigger: push to main only. Single job
deploy, runner ubuntu-24.04, concurrency groupdeploy(no cancel). Targetx86_64-unknown-linux-gnu, profiledist. - Steps: checkout; rustup stable (unpinned); rust-cache; cache topcoat-cli; write
.cargo/config.tomltarget line (appended, not committed); asset bundle; copy and strip binary; install SSH key from secrets; ssh-keyscan (no host pinning); upload tarball to~/in/current.new(subdir validated); swapcurrentandcurrent.previous; cleanconfig/*.bak*and*.pre-*; chmod config 0600; installdeploy/in.serviceto~/.config/systemd/user/; daemon-reload, enable, restart; poll/healthz30 times requiringok <sha>; rollback on failure; verify served stylesheet sha256 matches the staged asset;rm -rf ~/.ssh(no if: always()). - Secrets used by name: SSH_PRIVATE_KEY, SSH_HOST, SSH_USER. Nothing else.
- No cargo test, clippy or fmt step in CI.
Systemd unit deploy/in.service: systemd user unit, WorkingDirectory=%h/in, ExecStart=%h/in/current/in-web, Restart=on-failure, After=network-online.target, WantedBy=default.target. No Environment, no hardening, no RestartSec. Requires loginctl enable-linger once.
Tests (not run in CI):
- crates/in-web/tests/http.rs (about 6555 lines, roughly 100 #[test] attributes): fake im, real router and store. Covers drive CRUD, uploads (small, chunked, resume, abort, quota, postfix), downloads and ranges, thumbnails, previews, share links (create, public view, password, expiry, revoke, remint, legacy), per-person sharing, search, trash, settings guards, avatars, service API, live channel, me probe. Needs a prebuilt asset bundle at target/debug/assets.
- crates/in-core/tests/store.rs (about 2390 lines, 71 tests): schema and users, change feed, names and postfixing, files and thumbnails, trash and purge races, sharing, uploads, boot sweep, R2 via local s3s server (access key test-key), service accounts.
- Video tests skip when ffmpeg is absent.
Workspace: members in-core, in-client, in-web. .gitignore excludes target, dist, style/main.css, *.db, storage, .env, in.key, CLAUDE.md, assets, backups.
12. Oddities, bugs, half-finished work
Security:
config/in.tomlcontains a literal client_secret ("dev-drive-secret-2026") while its comment says the committed copy stays empty. Treat as exposed.ConfigandOidcConfigderive Debug with the plaintext secret.- No CSRF tokens; logout is a GET (logout CSRF); cross-site top-level navigation can sign the user out.
- Callback error reflection:
format!("/?auth_error={error}")after percent-decoding; decoded&or#can inject query parameters into the local redirect. settingsdisable: a POST with nodisabledfield disables the account; an empty string enables it. Admins can disable admins; only self-disable refused.- Quota form: service-account guard uses
unwrap_or(false), so a store error lets the quota write proceed against a service account. No check that user_id exists. - Share link password: unkeyed SHA-256 unlock proof with no expiry; no lockout; trim mismatch (create trims, unlock does not). Remint does not check revoked or expired on the source link and can turn an expired link into a permanent one; it also creates the new link before revoking the old, so a failed revoke leaves two live links with the new token never shown.
- Copy-once share URL travels in the
?created=query string (browser history, logs, Referer), unlike the shown= ticket design for service keys. - Share links: dead answers are all 200, so clients cannot tell dead from live by status. Thumbnails cached for a year even after revoke.
- Token in the URL path leaks via logs and Referer; no Referrer-Policy.
- Live stream and Revoked: set_user_disabled announces Revoked on enable as well as disable, so re-enabling kills open tabs.
- Cookie Secure flag follows issuer scheme, not the app's public origin.
- Family limits loop aborts on first store error; accounts left unchanged; a service dropping out of im's family silently falls back to default quota.
mintexample prints a usable session cookie to stdout.- Unverified: whether in-client module doc (promising refresh tokens and silent rotation) matches code. Code has no refresh token;
current_userintrospects every request. - Logout and callback: id_token identity ignored (only nonce checked).
- JWKS refetch:
?on RsaPublicKey::new aborts the whole refresh on one bad key. /api/service/filedownload: store errors collapse to 404.- Service pushes buffer the whole file in memory (512 MiB body limit).
- Service delete of an unknown handle returns
{"ok":true}. service_file_bytesis unused in routes.insert_service_filereplace path writes new bytes before commit; if the commit fails the row keeps the old size and name while bytes are replaced (data loss of the previous version).service_fileand insert ignoredeleted_at(service pushes can silently refill trashed rows).service_account_by_tokendoes not checkdisabled(caller responsibility).apply_service_limitcan set quota below used_bytes.- Service key re-mint for an existing service fails with a generic Backend error.
Data integrity and storage:
27. finish_upload and insert_file: blobs written inside the IMMEDIATE write transaction (I/O under the write lock); if a later step fails, the blobs are orphaned until the boot sweep.
28. record_chunk and abort_upload race: a chunk write can recreate the staging dir after abort; prune_expired_uploads lacks an AND state='active' guard.
29. create_upload_session quota check and insert are not in one transaction; directory create after commit can leave an active session with no dir.
30. Share create and grant add are vet-then-write without a transaction; a concurrent trash can leave a dangling grant.
31. delete_file does its UPDATE and refresh_usage as separate autocommit statements (used_bytes can drift on crash).
32. ancestor_trashed, depth_in and move_folder cycle walk have no cycle guard beyond the self-parent check.
33. select_expired and select_trash load all candidates with no LIMIT.
34. delete_folder_rows nulls folder_id on all upload sessions, including finished ones.
35. Name uniqueness is application-level only (no DB unique index); concurrent creates can collide. Name matching is case-sensitive.
36. Reconcile: backfill defaults for ui and theme disagree with migrations; verify omits service_key; swap window has no lock; manual run against a live server copies without locking and compares counts only.
37. Sweep holds the DB write lock across R2 listing and deletes (slow bucket stalls all writers).
38. Local blob operations use blocking std::fs inside async functions.
39. R2 adopt comment claims one part buffer resident; the code keeps about two.
40. LocalBlobs tmp naming uses with_extension (wrong for keys containing dots; harmless today).
41. Thumbnails: image/* includes SVG and HEIC which cannot decode (wasted attempts); no pixel cap in thumbs.rs; video temp spill to system temp dir as plaintext.
42. Sniff substring markers can misclassify plain zips containing those bytes; unrecognised formats (AVI, BMP, TIFF, 7z, rar, tar) fall to octet-stream or text.
43. Sniff doc links to a non-existent GENERIC_MIME_TYPES; fingerprint filter treats _ in LIKE as wildcard.
44. pending thumbnail state is never reset on boot after a crash (unverified).
45. Keys and config files are created with default permissions before being restricted (brief exposure).
46. Config boot rewrites config/in.toml; complete() can be suppressed by a same-named key in another table.
47. purge_file on a live file returns Ok(false); purge_folder on a live folder returns NotFound.
48. Trash purge deletes share rows for the purged file/folder (defensive, correct) but purge does not remove sealed token settings for those links (unverified).
49. Files restore and move/rename skip quota (correct under the model) but folder rename and move call refresh_usage needlessly.
50. Module docs in store and turso_store refer to a crates/in-core/migrations apply step and "0001_init.sql as the declared schema" (stale).
51. Dead store method: default Blobs::list is unused outside tests.
52. share_user has no index on user_id.
Web and UI:
53. Title bug: title_key_of("/") always returns SignIn even when / serves the drive to a signed-in browser.
54. escape_script (user menu Escape) is defined but never emitted; the user-menu Escape resolver is dead.
55. topcoat::dev::script() emitted unconditionally in <head> (verify whether dev-only).
56. Google Fonts loaded from a third-party CDN without SRI.
57. --font-serif referenced in the ledger skin but never defined; titles fall back to Georgia.
58. Large stylesheet dead-code: board, task detail, mail rules, profile, logs, datepicker, tag and auth families have no Rust counterpart (roughly 287 class names with no literal match; some may be format-built). Light and dark token blocks duplicated.
59. Drive search mode: "+" menu and upload still target the current folder, which is not the visible context.
60. Drive kind filter can show "empty folder" when content exists but is hidden by the filter.
61. Drive row Shared chip and folder-picker subtree filter by display path (names containing " / " can confuse it).
62. Redirect /search forwards raw q without decoding; here link drops q.
63. Folder/file breadcrumbs and picker swallow store errors silently.
64. Grantee drive page runs a wasted search before the grantee branch.
65. Share modal writes (provision_user per directory member) during a GET render.
66. Share modal and settings: one live link per target shown, though the API allows several.
67. / route: search link does not exist in the topbar (intentional per tests).
68. Upload progress and abort via XHR; refusal parsing relies on responseURL.
69. Stylistic: many mis-indented view! blocks and rustfmt drift in files.rs parse_range; garbled comments (e.g. "in never kept bytes" in reconcile header); doc comments glued together in layout.rs.
70. Layout catch-all /{*path} raises NotFound inside the shell (intended).
71. Unused or stale: /whoami route probably test-only; public/ directory contains only .gitkeep; config/im.toml is an im-side config (database im.db, listen 7650) not read by in-web and with none of in's keys.
72. Duplicate rules and dead CSS as described; !important once.
Test and CI gaps:
73. CI does not run tests, clippy or fmt; deploy only builds and health checks.
74. Video tests silently skip without ffmpeg.
75. Rollback on first deploy: rm -rf current then mv current.previous current fails under set -e when no previous release exists.
76. find config -name '*.bak*' -delete runs on every deploy (deletes operator backups).
77. ssh-keyscan without pinning; ~/.ssh cleanup not in if: always().
78. Deploy writes .cargo/config.toml with >> (accumulates on non-fresh checkout).
79. Systemd unit has no hardening and no RestartSec.
80. Dependencies pinned to pre-release versions (turso, rsa).
13. Rebuild checklist (what a faithful clone must cover)
- All routes in sections 2 and 3, with the exact status, redirect and JSON shapes above.
- Store semantics: owner scoping, trash cascade with shared timestamp, postfix naming, quota arithmetic, staged-claim accounting, deepest-first purge, sealed token storage, Argon2 PHC, SHA-256 token hashes, service key hashing.
- Blob layout
files/<id>,thumbs/<id>,uploads/<session>/<n>, same keys on R2, plus the boot sweep and watermark rule. - OIDC login with PKCE and id_token validation, per-request introspection, family heartbeat, directory mirror and stream, avatar proxy.
- SSE channel with the topic filter rules and the resync and revoked control frames.
- Config keys and defaults as in section 6;
/healthzbody format. - The sniffing allow-lists for inline disposition and the sniffed mime model.
- Decide explicitly whether to keep the oddities listed in section 12 (most are bugs, not features).