in
Clone
0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits
in architecture
in is the family's file drive: folders, uploads (resumable), previews and thumbnails, trash, sharing with
people and by link, quotas, and an object store that other family apps use through a machine API. Read
docs/contracts.md (cross-app API) and docs/conventions.md (how code is written) first.
Status: design for the rebuild. ~/Documents/Code/Rust/old_in is a feature reference only;
docs/reference/old-inventory.md lists its features (the parity checklist) and its defects (section 12 there),
which must not be carried over.
1. Goals
- Your files outlive the app. The blob tree is plain files named by id, and
admin exportwrites a normal directory tree (real folder and file names) that needs nointo read. - Feature parity with old in (inventory sections 2–3).
- Better than old in: CSRF everywhere, local sessions (no per-request call to
im), back-channel logout, machine API withimJWTs instead of minted bearer keys (contracts.md 5), streaming uploads everywhere (no whole-file buffering), fsync on every blob write, security headers, rate-limited share passwords, every page translated, real/healthz.
Not goals now (docs/backlog.md): file versioning, WebDAV, end-to-end encryption, desktop sync client,
office document editing.
2. Crates and modules
in/
crates/
in-core/ domain, store, migrations, config, secret, token, time, names, sniff, authz, quota math, blob trait + backends, thumbs
in-web/ binary `in`: pages, OIDC client, directory mirror, machine API, upload API, share pages, live, workers, CLI
in-core
error.rs,time.rs,config.rs,settings.rs,secret.rs,token.rs,password.rs(share passwords)names.rs: display-name rules (inventory 2.2 "Name rules": strip path components and control characters, empty → "Untitled", ≤255 chars bychar, collision postfix " (2)" before the extension for files, appended for folders; files and folders are separate namespaces; comparison is exact)sniff.rs: magic-number sniffing (inventory 5.6, plus SVG detection so SVG is never inline), never trusts the client's typeauthz.rs: section 6blob/:mod.rs(BlobStoretrait:put_stream,adopt_file,open_range,size,delete,list),local.rs(temp file + fsync + rename + dir fsync),s3.rs(object_storeS3 client for R2, Hetzner Object Storage or any S3 endpoint; multipart for large objects)thumbs.rs: images with theimagecrate (decode limits: 64 MiB source, 10000 px per side and 256 MiB decoded, 10 s onspawn_blocking), video throughffmpegwhen present (10 s kill, temp file indata_dir/tmpmode 0600), WebP output, max edge 512store/:users.rs(local mirror of members),sessions.rs,folders.rs,files.rs,trash.rs,shares.rs,links.rs,uploads.rs,services.rs(service namespaces and objects),audit.rs,settings.rs,snapshot.rs,migrate.rs
in-web
main.rs,boot.rs,state.rs,admin_cli.rs,auth.rs,throttle.rs,client_ip.rsoidc/(client: discovery cache, JWKS cache, login, callback, logout, back-channel endpoint, client-credentials token cache),directory.rs(mirror worker),family.rs(switcher list worker)api/objects.rs+api/machine_auth.rs(contracts.md 5),api/upload.rs(chunked upload JSON API)pages/(drive.rs,view.rs,trash.rs,shared.rs,share_dialog.rs,links.rs,settings.rs,admin.rs,public_share.rs,files.rs(byte serving),thumbs.rs,avatar.rs,not_found.rs)serve_bytes.rs: one function that serves a blob with Range, ETag, disposition and the byte-response headers (section 7) for every byte routeviews/,i18n/,live.rs,audit.rs,assets.rs, workers (sweeper.rs,thumbs_worker.rs,backup.rs)assets/nav.js,assets/drive.js(upload queue: chunking, resume, retry, progress, drop zone; context menus; dropdowns),assets/player.js(media player),assets/offline.html,assets/sw.js
3. Data model
members (mirror of im's directory, contracts.md 3; one row per person)
subTEXT PK,email,name,is_admin,disabled,locale,zoneinfo,picture_version,im_updated_at,first_seen_at,last_sign_in_atNULLthemeTEXT NOT NULL DEFAULT 'system' CHECK IN ('system','light','dark'),locale_overrideNULLquota_bytesINTEGER NOT NULL,used_bytesINTEGER NOT NULL DEFAULT 0 CHECK (used_bytes >= 0)
sessions: id PK, sub FK members CASCADE, token_hash UNIQUE, csrf_token, im_sid, created_at,
expires_at (≤12 h, contracts.md 2.4), last_seen_at, ip, user_agent. Index on im_sid and sub.
oidc_flights: none in the DB; the login flight (verifier, state, nonce, next) is a sealed
__Host-in_flight cookie, 10 minutes, SameSite=Lax (it must survive the redirect back from im).
seen_logout_jti: jti PK, expires_at (replay guard for back-channel logout tokens).
folders: id PK, owner FK members, parent_id NULL FK folders, name, created_at, updated_at,
trashed_at NULL, trash_root NULL (id of the folder whose trashing trashed this one; restore restores exactly
that set). Partial unique index (owner, parent_id, name) WHERE trashed_at IS NULL (parent NULL handled with
COALESCE(parent_id, '')), so postfixing is checked by the database.
files: id PK, owner FK members, folder_id NULL FK folders, name, mime (sniffed), size,
sha256, blob_key (files/<id[0..2]>/<id>), thumb_state CHECK IN ('none','pending','ready','failed','skip'),
download_count, created_at, updated_at, trashed_at NULL, trash_root NULL. Same partial unique index on
live names per folder.
grants (per-person shares): id PK, target_kind CHECK IN ('file','folder'), target_id, owner,
grantee FK members CASCADE, can_download 0/1, created_at; UNIQUE (target_kind, target_id, grantee);
index on grantee.
links (public share links): id PK, token_hash UNIQUE, token_sealed (so the owner can see the URL
again), target_kind, target_id, owner, can_download, password_hash NULL, expires_at NULL,
revoked_at NULL, created_at, last_used_at NULL, use_count.
uploads: id PK, owner, folder_id NULL, name, size, chunk_size, state CHECK IN
('active','done','aborted'), file_id NULL, created_at, expires_at (24 h).
services (namespaces for machine callers): key PK (the token's svc), quota_bytes, used_bytes,
created_at. Created on first authorised call with the default quota from settings.
objects: service FK services, external_id, size, sha256, content_type, name NULL, blob_key
(objects/<service>/<sha256 of the content>, shared by objects of one service with equal bytes; removed when the last one goes), created_at, updated_at; PK (service, external_id).
audit_log, settings: per conventions. The audit log is kept for AUDIT_RETENTION_DAYS (365 days,
in-core/src/store/audit.rs); the sweeper deletes older rows in batches of AUDIT_PURGE_BATCH (1000), each
batch its own statement, so no purge holds the writer lock for long.
Quota rule (one place, quota.rs): used_bytes = sum of size of the person's files, live and trashed, kept
up to date inside the same transaction as every insert, replace, purge; headroom for a new upload = quota −
used − sizes declared by the person's other active uploads. A nightly check recomputes and logs any drift.
Blob tree ([storage] backend = "local", root data_dir/blobs): files/<2 hex>/<id>, thumbs/<2 hex>/<id>.webp,
objects/<service>/<sha>, staging data_dir/uploads/<upload id>/<index> (always local). Ordering contract: bytes
are durable at their key before the row that names them commits; bytes are deleted only after the row is gone.
The sweeper removes unreferenced blobs older than 24 h.
4. Routes
4.1 Pages (session required unless noted)
| Path | What |
|---|---|
GET / |
signed out: sign-in card; signed in: redirect to /drive |
GET /drive, GET /drive/{folder_id} |
folder listing (inventory 2.2): sort, kind filter, search (?q=), breadcrumbs, row menus, rename in place, new folder, upload, drop zone, move dialog, share dialog |
POST /folders, /folders/{id}/rename, /folders/{id}/move, /folders/{id}/trash |
folder writes |
POST /files (multipart, streamed), /files/{id}/rename, /files/{id}/move, /files/{id}/trash |
file writes |
GET /view/{id} |
viewer page (image, video, audio, PDF, text; inventory 2.4) |
GET /file/{id} (?dl=1), GET /thumb/{id} |
bytes (section 7) |
GET /trash, POST /trash/restore, /trash/purge, /trash/empty |
trash |
GET /shared |
items shared with me |
POST /grants, /grants/{id}/update, /grants/{id}/remove |
per-person shares (grantee chosen from the members mirror) |
GET /links, POST /links, /links/{id}/revoke, /links/{id}/remint |
my share links |
GET/POST /s/{token} (anonymous) |
public share page, folder browsing, password gate, download, media, thumbs |
GET /settings + POST |
preferences (theme; language follows im unless overridden), storage usage |
GET /admin + POSTs (instance admin) |
people with quotas (set quota), services with quotas, default quotas, storage backend status, backup schedule, last success and attempt, the latest error and the stale warning, and POST /admin/backup (back up now), base URL, audit log, health |
GET /avatar/{sub} |
photo proxy with disk cache (contracts.md 3.2) |
GET /auth/login, /auth/callback, POST /auth/logout, POST /auth/backchannel-logout |
OIDC client |
GET /-/alive, live streams, /healthz, /assets/* |
4.2 JSON APIs
- Upload (session + CSRF header
X-CSRF-Token):POST /api/uploads{folder_id?, name, size}→{id, chunk_size};GET /api/uploads/{id}→ state with received chunk indexes;PUT /api/uploads/{id}/{index}(raw body, ≤ chunk size);POST /api/uploads/{id}/finish→{file_id};DELETE /api/uploads/{id}. Chunk size 8 MiB; files under 8 MiB may usePOST /files. - Objects for services: contracts.md 5.
5. Sign-in
Per contracts.md 2: /auth/login?next= builds the flight cookie and redirects to im; /auth/callback
validates state, exchanges the code (client_secret_basic), validates the ID token, upserts the member from its
claims (so a person can use in before the directory stream catches up), creates a local session (12 h), and
redirects to next. The client secret is read from the file named by client_secret_file (0600), never
from the TOML. A secret file, and every S3 credential file,
that group or world can read is refused at boot (secret::check_private). A member with disabled set cannot sign in
and has no sessions.
6. Authorization
authz::authorize(actor, target, grant, action):
actor:Anonymous,Member { sub, is_admin },Link { link }(a validated share-link visit),Service { key, scopes }.target: a file or folder with owner and trashed state, plus the effective grant (the most permissive grant on the item or any live ancestor folder) and, for links, whether the item is inside the linked folder.action:List,View(see name, preview inline),Download,Write(rename, move, upload into, trash),Restore,Share(a new grant or link),Revoke(change the level of an existing grant, or remove it),Purge,Administer.- Rules: owner may do everything on their items (trashed items: only
View,Download, restore,Purge, andRevoke, so access taken back stays gone after a restore; no new grant or link on a trashed item); grantee:ListandView,Downloadwhencan_download, never on trashed items; link visitor: the same as a grantee within the link's subtree; admin:Administeronly (an admin does not read other people's files); anything else isNotFound.
7. Byte serving (one function for every byte route)
- Single
Range(a-b,a-,-n), 206 / 416;ETag="<validator>", where the validator of a stored file issecret::validator(HMAC-SHA256 of the SHA-256 under a subkey of the instance key,filepurpose, 128 bits in hex; thumbnails use thethumbpurpose). The same bytes keep it, but a viewer cannot learn the hash or test whether a known file is stored. Object API answers keep"<sha256>"(contracts.md 5).If-None-Match→ 304, andIf-Rangecompares against the same validator. Per RFC 7233 3.1 aRangethat is malformed, reversed, or in another unit is ignored (200, whole file); only a valid range the file cannot satisfy gets 416 withContent-Range: bytes */<len>. Several ranges get 200, whole file. Content-Disposition:inlineonly for image/* (not SVG, not HEIC), video/, audio/, application/pdf, text/plain, and only when the action allowsViewanddlis not set; otherwiseattachment. Always bothfilename="<ascii fallback>"andfilename*=UTF-8''<percent-encoded>.- Every byte response:
X-Content-Type-Options: nosniff,X-Frame-Options: SAMEORIGIN,Content-Security-Policy: default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; sandbox; frame-ancestors 'self',Cross-Origin-Resource-Policy: same-origin.- PDFs get the same policy without
sandbox. Browser PDF viewers do not run inside a sandboxed document and stop working, so a PDF is served inline without it. It stays safe: the type is fixed toapplication/pdfwithnosniff, so it is never read as HTML, anddefault-src 'none'still blocks everything else.
- PDFs get the same policy without
Cache-Control: private, no-cacheon every byte response, member bytes and share-link bytes alike. Notimmutable: the same URL can return different bytes after an overwrite or a restore, and a grant change must be seen at once. The browser revalidates, and theETagturns that into a cheap304while the bytes are the same.- A full-body answer of a stored file is hashed against its row's SHA-256 while it streams. The check runs on the
frame that reaches the row's size, before that frame is sent: on a mismatch the body is cut short with no bad
bytes, and the key is logged for
in fsck --hash. A longer stream is refused the same way. Range answers are not checked (they are part of the file). - Streams from the blob store in 64 KiB frames; never buffers a whole file.
- The download counter counts a forced download that starts at byte 0, once per request.
8. Share links
- Token: 32 random bytes; DB stores the SHA-256 and a sealed copy for the owner to re-display.
- Options: can download, password (argon2id), expiry (1 hour to 1 year, or none).
- Password gate: POST checks the password (throttled per link: 100 failures / 15 min from all visitors together; and
per link and client address: 10 failures / 15 min) and sets a cookie
__Host-in_link_<id>= HMAC-SHA256(unlock subkey, link id || "|" || password_hash), where the unlock subkey is HMAC-SHA256(instance key, "in link unlock v1"), 12 h, so changing the password or remint invalidates old unlocks. - Dead links (revoked, expired, target trashed or purged, owner disabled) answer one identical "link no longer works" page. A disabled owner's links and grants stop working at once and are not deleted: enabling the owner again restores them.
- Remint creates the new link and revokes the old one in one transaction.
9. Workers
- directory: full fetch, then stream (contracts.md 3), resync on gap; applies member changes; on
disabledordeletedends the person's sessions. Backoff 1 s → 30 s. - family: fetches the switcher list every 5 minutes.
- thumbs: picks
pendingfiles, generates thumbnails one at a time (seethumbs_worker.rsfor why), with a 10 s limit per decode, marks ready/failed. A decode that outlives its limit keeps its slot until it returns. - sweeper (hourly): expired sessions, expired uploads, staging directories that no open upload names (24 h old,
which retries failed removals), seen JTIs, trash past
purge_after_days, audit rows past 365 days, unreferenced blobs older than 24 h, quota drift check (nightly). - backup (optional): snapshot + blob tree manifest, HMAC-SHA256 over the manifest (
manifest.mac, keyed fromin.key, checked before a restore parses anything), keep N, dead-man pings. The worker wakes every minute and runs when no attempt is recorded orbackup.last_attempt_atis at leastinterval_hoursold (backup::is_due). The attempt time is written before the run, so a restart neither starts a run nor resets the interval. The worker also runs when the admin page asks (BackupTrigger: one busy flag and aNotifythe worker waits on); at most one run is pending or running. After every run, scheduled or manual, the outcome is written tosettings(no migration):backup.last_attempt_atbefore the run,backup.last_success_aton success (and the error is cleared),backup.last_erroron failure (the first line of the error, control characters removed, at most 200 characters; never the ping URL). The admin Backups section shows the last success and the last attempt, an alert while the latest run failed, and a warning when backups are on and the last success is older than the limit:max(2 days, 2 × interval_hours)(backup::is_stale)./healthzdoes not show any of this.
10. Settings (UI > file > default)
default_quota_bytes (10 GiB), default_service_quota_bytes (10 GiB), purge_after_days (30),
max_upload_bytes (50 GiB), link_max_days (365), base_url, trusted_proxies; storage backend and its
credentials (S3 secret sealed) are Restart settings.
11. CLI
A bare in (or in serve) runs the server. Backups are written by the server's backup worker.
in restore --from SET replaces the database with a verified set (server stopped; needs the same in.key).
in export --member <sub|email> --out DIR writes a plain tree with real names (folders 0700, files 0600). in fsck [--hash] [--quarantine]
checks that every row has its blob and every blob has a row (sizes, and hashes with --hash); it changes nothing,
except that --quarantine moves orphan blobs over an hour old into data_dir/quarantine/ (never deletes).
in quota recompute recomputes used bytes.
12. Build order
- Scaffold (workspace, core basics, store + 0001, boot, healthz, assets, shell, nav.js, i18n, headers, 404).
- OIDC client, local sessions, back-channel logout, members mirror, avatar proxy, switcher.
- Blob stores (local, S3) and
serve_bytes. - Drive: folders, files, small uploads, rename, move, trash, restore, purge, search, sort, quota.
- Chunked upload API and
drive.js. - Viewer, thumbnails worker, media player.
- Grants, shared page, links, public share pages.
- Machine object API.
- Settings, admin, audit, live topics, sweeper, backup, export, fsck, deploy unit, README.