im
Clone
https://git.tahinli.com/Tahinli/im.git
0 watching·0 forks·Rust·AGPL-3.0·542.8 KiB·b9f0726·Tahinli·27 days ago·34 commits
| 1 | # im: feature inventory (rebuild reference) |
| 2 | |
| 3 | Source: /home/tahinli/Documents/Code/Rust/old_im (read-only survey). Workspace crates: im-core (domain + storage, feature `server`), im-web (topcoat web app, binary `im-web`), im-client (app-side SDK). |
| 4 | |
| 5 | ## 1. Purpose summary |
| 6 | |
| 7 | 1. im is a self-hosted OpenID Connect identity provider (OIDC, RS256, PKCE S256) and account portal for a small family of sibling apps. |
| 8 | 2. Users sign in with email + Argon2id password, optional TOTP 2FA; they manage sessions, profile photo, preferences, password, and email change. |
| 9 | 3. Admins manage users (invite, disable, delete, sign-out-everywhere), OIDC clients, the sibling service registry, SMTP, policy settings, a filterable audit log, and service health. |
| 10 | 4. Sibling apps ("in" = Files, "iz" = Board) integrate via OIDC, mirror the member directory over HTTP + SSE, read profile photos, introspect app sessions, and register themselves in the family registry. |
| 11 | 5. Single binary, Turso (SQLite-compatible) storage, files beside the DB; backup/restore via `pack`/`unpack`; systemd user unit with GitHub Actions deploy. |
| 12 | |
| 13 | ## 2. User-facing features |
| 14 | |
| 15 | Routes are method + path as registered in `crates/im-web/src`. Pages return HTML; POST handlers redirect (303) with `?ok=` or `?error=` codes. |
| 16 | |
| 17 | ### 2.1 Landing and profile (`pages.rs`) |
| 18 | - `GET /` signed out: login card. Signed in: landing with sections via `?section=` = `profile` | `sessions` | `apps` | `preferences` | `password`. |
| 19 | - Profile card: photo or initial avatar, 2FA chip, admin chip, email, member since, link to public profile, "activate 2FA" link when off, admin panel link when admin. |
| 20 | - Stats card (`stats.rs`): sign_ins (all sessions ever), active_sessions (not revoked, not expired), connected_apps (distinct clients with live app sessions). |
| 21 | - Sessions section: list of sessions as `<details>` items; device label parsed from User-Agent (Edge, Firefox, Chromium, Chrome, Safari; iPhone, iPad, Android, Windows, macOS, ChromeOS, Linux); shows address, created, last seen; `POST /sessions/revoke` (`session`=token hash) revokes one owned session (cascades to refresh_tokens and app_sessions of that session). |
| 22 | - Apps section: connected apps (`list_connected_apps`) with revoke. |
| 23 | - Preferences: `POST /preferences`: theme `light|dark`; ui `instrument|ledger`; language `en|tr`; timezone from zone_options UTC-12..UTC+14 plus UTC (default `UTC+03:00`). Redirect `/?section=preferences`. |
| 24 | - Password: `POST /password` (current, password, password_confirm). Rules below. Revokes all other sessions, keeps current. Redirect `/?section=password&ok=password`. |
| 25 | |
| 26 | ### 2.2 Login and 2FA (`auth.rs`, `pages.rs`) |
| 27 | - `GET /login` (optional `back`, `error`, `ok`). `POST /login` (email, password, back). |
| 28 | - Rate limited per account (key = trimmed email); over limit → `/login?error=rate_limited`. |
| 29 | - Bad credentials (also unknown email, disabled user, same message) → `/login?error=bad_login&back=...`. |
| 30 | - Account with confirmed TOTP → sealed pending cookie `im_pending` (JSON {user, purpose "login", back, exp}, TTL 10 min or policy `pending_minutes`) → redirect `/login/totp`. |
| 31 | - Account without 2FA → session issued immediately (2FA is optional). |
| 32 | - `safe_back`: only local paths (or same-origin family URLs) accepted. |
| 33 | - `GET /login/totp`, `POST /login/totp` (code). Rate limit key `totp:{user}`. Bad → `/login/totp?error=bad_code`. Success → `im_session` cookie and redirect to back. Replay protection via `users.totp_last_step`. |
| 34 | - `POST /logout`: signs out everywhere (central session revoked; cookie cleared) → `/`. |
| 35 | - `GET /logout?back=`: RP-initiated logout; `back` must be local path or same origin as a family service; clears central session. |
| 36 | - `GET /api/me`: 204 when signed in, 401 otherwise (used by client JS). |
| 37 | |
| 38 | ### 2.3 2FA enrollment (`pages.rs`, `totp.rs`) |
| 39 | - `GET /enroll`: generates a 20-byte secret (stored sealed, `totp_confirmed = 0`), shows base32 secret grouped by 4, `otpauth://totp/im:{email}?secret=...&issuer=im`, QR as SVG (`qrcode` crate). Page strings are English-only. |
| 40 | - `POST /enroll` (code). Bad → `/enroll?error=bad_code`; good → `totp_confirmed = 1`, redirect `/?ok=enrolled`. |
| 41 | - No UI or route to disable TOTP once enrolled. Re-visiting `/enroll` after confirmation regenerates the secret (`set_totp` resets confirmed flag) — see oddities. |
| 42 | - Verification: HMAC-SHA1, 6 digits, 30 s step, +/-1 step drift. Secret 160-bit. |
| 43 | |
| 44 | ### 2.4 Invitations and account creation |
| 45 | - Invite creation: admin only (see 2.8). Invite token = 32 random bytes, base64url, stored as SHA-256 hex (`invites.token`). Expiry = policy `invite_days` (default 7). |
| 46 | - `GET /invite/{token}`: form with name, password, password_confirm; invalid/expired/accepted token shows error. |
| 47 | - `POST /invite` (token, name, password, password_confirm): creates user (transactional, marks invite accepted), auto-signs-in, redirect `/`. TOTP not forced. |
| 48 | - Invite refused if email already has an account. Multiple pending invites for one email are allowed. |
| 49 | - Mail: invite email in English only (`invite_mail`), link `{issuer}/invite/{token}`, mentions INVITE_DAYS. If no SMTP configured, dev mode prints the link to stdout; admin UI shows the link once. |
| 50 | |
| 51 | ### 2.5 Password reset (`pages.rs`, `accounts.rs`) |
| 52 | - `GET /forgot`; `POST /forgot` (email): always redirects `/forgot?ok=sent` (no enumeration). Rate limit key `forgot:{email}`. If account exists, creates reset link (retires previous unused links; expiry policy `reset_minutes`, default 60) and mails `{issuer}/reset/{token}` in the account's language. |
| 53 | - `GET /reset/{token}`; `POST /reset` (token, password, password_confirm): success → `/login?ok=reset`; errors → `/reset/{token}?error=...`. On success marks link used, sets hash, revokes all sessions, clears login failures. |
| 54 | |
| 55 | ### 2.6 Email change (two-sided confirmation) (`pages.rs`, `auth.rs`, `accounts.rs`) |
| 56 | - `POST /email_change` (email): validates address (trim, lowercase, contains @ and dotted domain; taken → error). Creates a pair of tokens (old-address token, new-address token) in `email_changes`, expiry ~ policy-driven. Mails both: "leaving" link to old address, "gaining" link to new address (`{issuer}/email/{token}`). |
| 57 | - If mail send fails, both confirmation links are returned in the redirect query `links=` (see security oddities). |
| 58 | - `GET /email/{token}` shows confirmation page (GET never mutates). `POST /email` (token) confirms that side. Results: `/login?ok=email_changed` when both sides confirmed; `/login?ok=email_half_confirmed` otherwise; errors. At completion the new address is re-checked for being taken. |
| 59 | - Pending state shown on profile via `pending_email_change`. |
| 60 | |
| 61 | ### 2.7 Profile photo (`photo.rs`) |
| 62 | - `POST /api/profile_photo` (multipart, field file): limit 5 MiB (`PHOTO_LIMIT_BYTES`); BodyLimit set to limit + 4096. Sniffs magic bytes: PNG, JPEG, GIF, WEBP, AVIF. Errors `/?error=no_file|photo_too_big|not_an_image|unavailable`; success `/?ok=photo_saved`. Stores file at `<storage>/photos/<user_id>`, row increments `photo_version`. |
| 63 | - `POST /api/delete_profile_photo` → `/?ok=photo_removed`. |
| 64 | - `GET /photo/{user_id}`: auth by session cookie OR HTTP Basic app credentials; otherwise 404. Unknown user or no photo → SVG initial tile. Headers: ETag `"p{version}"`; with `?v=` matching version: `private, max-age=31536000, immutable`; otherwise `private, no-cache`; 304 on If-None-Match. |
| 65 | |
| 66 | ### 2.8 Public profile (`people.rs`) |
| 67 | - `GET /people/{user_id}`: requires signed-in viewer; unknown id or signed out → router not-found. Shows name, email, member since, 2FA/admin chips, stats. Edit link only for self. |
| 68 | |
| 69 | ### 2.9 Admin panel (`admin.rs`) |
| 70 | - `GET /admin` (admin only; non-admin → 303 `/`). Sections via `?section=`: `users` (default), `services` (alias `clients`), `message`, `settings`, `logs`, `health`. A `mail` section exists but is only reached by redirects; the nav has no Mail tab (oddity). |
| 71 | - Admin role cannot be granted from the panel. Only CLI `promote`/`demote` or an invite with role admin. |
| 72 | - Users section: table with per-user session rows (device, address, created, last seen, revoke button), disable/enable, delete, sign out everywhere, per-user email edit fold. |
| 73 | - `POST /admin/invite` (email, role `member|admin`): mails invite or shows link once via `invited=`; logs `invite_created`. |
| 74 | - `POST /admin/uninvite` (invite=hash): removes pending invite; logs `invite_revoked`. |
| 75 | - `POST /admin/user_email` (user, email): direct rescue edit, no confirmation; logs `email_changed`. |
| 76 | - `POST /admin/delete` (user): deletes user (see 4 for what survives); logs `user_deleted`. |
| 77 | - `POST /admin/revoke` (user): sign out everywhere; logs `sessions_revoked`. |
| 78 | - `POST /admin/session_revoke` (user, session): one session; logs. |
| 79 | - `POST /admin/disable` and `POST /admin/enable` (user): disable revokes all sessions; `notify_profile` broadcast; logs `user_disabled`/`user_enabled`. |
| 80 | - Services section: `POST /admin/services_add` (key, name, url); `POST /admin/services_edit` (key, name, url, limit_amount, limit_unit `MiB|GiB`); `POST /admin/services_remove` (key; refuses owned rows; closes gap); `POST /admin/services_move` (key, dir `up|down`; swaps with neighbor). Keys: lowercase letters, digits, dashes. Name non-empty. URL http(s), no spaces. Edit: only name and storage limit may change for existing rows; URL change refused. |
| 81 | - Clients section (OIDC clients): `POST /admin/clients_add` (name, redirect_uris split by whitespace or comma); client secret shown once via show-once shelf (10 min one-time ticket in `shown=`). `POST /admin/clients_rotate` (client): new secret, shown once. `POST /admin/clients_revoke` (client): deletes client, its refresh tokens and app sessions (not central sessions). |
| 82 | - Settings section: `POST /admin/settings` (invite_days, session_days, max_sessions, pending_minutes, reset_minutes, login_attempts_per_hour). Values < 1 clamped to default. |
| 83 | - SMTP: `POST /admin/smtp` (host, port u16 default 587, username, password optional (blank keeps old), from_name, from); saves and re-probes in background. `POST /admin/smtp_test` sends test mail to admin's email. `POST /admin/smtp_check` runs connection probe (15 s timeout). Standing shown as NotConfigured / Unchecked / Connected / Refused, with recorded check time, latency, error. |
| 84 | - Message section: `POST /admin/message` (to = `everyone` (excludes admin) or user id; subject; body). Sends sequentially; aborts on first failure. |
| 85 | - Logs section: audit events table. Filters: kind, actor, from/to dates, dir (`newest|oldest`), q (substring). Default 50 rows per page (cookie `im_rows_logs`, clamp 5 to 200, fit-to-viewport script). Cursor paging `before` / `after` as `rfc3339~id`; position note `X-Y / Z`. |
| 86 | - Health section: table of services with `/healthz` result and latency. |
| 87 | |
| 88 | ### 2.10 Logout of sibling apps |
| 89 | - Apps call `GET /logout?back=` (see 2.2) to end the central session. |
| 90 | |
| 91 | ### 2.11 Family registry (cross-app, see 3.8/3.9) |
| 92 | - Services are listed in the admin panel and in the family flyout (signed-in chrome) with health dots. im's own row is excluded from the flyout. |
| 93 | |
| 94 | ## 3. Machine and API endpoints (cross-app contract) |
| 95 | |
| 96 | Base: `issuer` (config, default `http://127.0.0.1:7650`). Auth schemes: "Basic" = HTTP Basic `client_id:client_secret` checked against `oidc_clients` (secret stored as hash). "Bearer" = RS256 JWT from /token. |
| 97 | |
| 98 | ### 3.1 OIDC discovery and keys |
| 99 | - `GET /.well-known/openid-configuration` (no auth). JSON: `issuer`, `authorization_endpoint` `{issuer}/authorize`, `token_endpoint` `/token`, `userinfo_endpoint` `/userinfo`, `jwks_uri` `/jwks.json`, `response_types_supported` ["code"], `grant_types_supported` ["authorization_code","refresh_token"], `subject_types_supported` ["public"], `id_token_signing_alg_values_supported` ["RS256"], `scopes_supported` ["openid","profile","email"], `claims_supported` iss, sub, aud, exp, iat, nonce, email, name, `code_challenge_methods_supported` ["S256"]. No introspection_endpoint or end_session_endpoint listed. |
| 100 | - `GET /jwks.json` (no auth). `{"keys":[{"kty":"RSA","alg":"RS256","use":"sig","kid":...,"n":...,"e":...}]}`. kid = first 16 hex of SHA-256 of public DER. |
| 101 | |
| 102 | ### 3.2 Authorization code flow |
| 103 | - `GET /authorize` (no auth; needs central session). Query: `client_id`, `redirect_uri` (must exactly match a registered URI), `response_type=code`, `scope` (must include `openid`; only openid/profile/email), `code_challenge` (required), `code_challenge_method=S256`, `state`, `nonce`. |
| 104 | - No central session → 303 `/login?back=/authorize?...`. |
| 105 | - Bad client or redirect_uri → bare 400 "invalid request" (no redirect). |
| 106 | - Other errors → 302 to redirect_uri with `?error=` (`unsupported_response_type`, `invalid_scope`, `invalid_request`) and `state`. |
| 107 | - Success → 303 `redirect_uri?code=...&state=...`. Code: 32 random bytes, stored as hash, TTL 60 s, single use (peek then consume in immediate transaction). |
| 108 | - `POST /token` (form-encoded). Client auth: `client_secret_post` only (client_id and client_secret in body). |
| 109 | - `grant_type=authorization_code`: `code`, `redirect_uri`, `client_id`, `client_secret`, `code_verifier` (PKCE S256 check). Response JSON: |
| 110 | - `access_token`: RS256 JWT, claims iss, sub, aud=client_id, exp (now+900), iat, scope "openid profile email" (hardcoded). |
| 111 | - `id_token`: RS256 JWT, claims iss, sub, aud=client_id, exp, iat, email, name, nonce. |
| 112 | - `refresh_token`: opaque, 30 days (`REFRESH_DAYS`), stored hash; bound to central session_hash. |
| 113 | - `expires_in`: 900; `token_type`: "Bearer"; `app_session`: opaque app session token (30 days, non-OIDC, used by `/introspect`). |
| 114 | - `grant_type=refresh_token`: `refresh_token`, `client_id`, `client_secret`. Rotates: old revoked, new issued. No reuse detection (reuse does not revoke the chain). |
| 115 | - Errors: JSON `{"error": "invalid_request" | "invalid_client" | "invalid_grant" | "unsupported_grant_type"}` with 400 (401 for invalid_client). |
| 116 | - `GET /userinfo`: `Authorization: Bearer <JWT>`. Verifies signature, requires aud to be a registered client. Returns `{"sub","email","name"}`. Failure: 401 `invalid_token` with `WWW-Authenticate: Bearer`. |
| 117 | |
| 118 | ### 3.3 Introspection |
| 119 | - `POST /introspect` (form: `token`, `client_id`, `client_secret`). Token is an app_session (opaque). Response JSON: `{"active": true, "sub", "email", "name", "admin", "photo_version", "timezone", "exp"}` or `{"active": false}`. Active requires: client_id match, central session alive, user not disabled, app session not expired/revoked. Invalid client → 401 `{"error":"invalid_client"}`. |
| 120 | |
| 121 | ### 3.4 Directory (member mirror) |
| 122 | - `GET /directory` (Basic). JSON array of non-disabled members: `sub`, `email`, `name`, `admin`, `photo_version`, `timezone`, `disabled` (false). Invalid client → 401 `{"error":"invalid_client"}`. |
| 123 | - `GET /directory/live` (Basic). SSE. First frame: comment "directory live" and `retry: 5000`. Events: |
| 124 | - `event: profile`, data = member JSON (may carry `disabled: true`, although the full list excludes disabled members). |
| 125 | - `event: revoked`, data `{"sub": "<user id>"}`. |
| 126 | - Ticks are silent. Keep-alive comments. Stream window 50 minutes (`WINDOW`), then closes; client reconnects. |
| 127 | |
| 128 | ### 3.5 Profile photo |
| 129 | - `GET /photo/{user_id}` with Basic credentials (see 2.7). Used by sibling apps to show avatars. |
| 130 | |
| 131 | ### 3.6 Live SSE for browsers |
| 132 | - `GET /live` (session cookie; signed-in users). SSE, 50-min window, per-connection resolved session. |
| 133 | - `event: profile` data `{"kind":"profile","sub":"<user id>"}` for any member change (not filtered to the viewer). |
| 134 | - `event: revoked` (empty data) sent to matching user + session hash, or all sessions of a user. |
| 135 | - Tick → default message with data `{}`. |
| 136 | - Client JS (`live_script`): EventSource `/live`; on `revoked` navigates home; on error probes `/api/me`, on 401 navigates home. |
| 137 | |
| 138 | ### 3.7 Health |
| 139 | - `GET /healthz` (no auth): body `ok {IM_BUILD_SHA}` (build SHA from env, default `dev`). |
| 140 | - im itself probes each service's `{url}/healthz`: 2 s timeout, success status and body starting "ok". Shared reqwest client, 30 s cache (`CACHE_TTL`). |
| 141 | |
| 142 | ### 3.8 Family registry |
| 143 | - `GET /family` (Basic). JSON array ordered by position: `key`, `name`, `url`, `limit_bytes`. (`owner` and `client_id` are not serialized.) |
| 144 | - `POST /family/register` (Basic). JSON body `{key, name, url}`. Owner and client_id = authenticated client id. |
| 145 | - Success: returns the service JSON (200). |
| 146 | - 409 `{"error":"owned"}` if another client owns the key. |
| 147 | - 400 `{"error":"invalid","reason":...}` on validation failure. |
| 148 | - Claims unowned rows; refreshing own row updates url/owner/client_id; name stays admin's. |
| 149 | |
| 150 | ### 3.9 Local-process hints |
| 151 | - `IM_BUILD_SHA` env used in /healthz; `IM_*` env vars used by the im-client example only. |
| 152 | |
| 153 | ## 4. Data model |
| 154 | |
| 155 | Storage: Turso (single writer, one connection behind `tokio::sync::Mutex`, `BEGIN IMMEDIATE` transactions). Schema: SCHEMA const in `crates/im-core/src/store.rs`, plus guarded ALTERs in `Store::migrate`. No `migrations/` directory exists. Files beside DB: `storage/photos/<user_id>`, `im.key` (32-byte at-rest key, mode 0600). |
| 156 | |
| 157 | Tables: |
| 158 | - `users`: id (ULID PK), email (UNIQUE COLLATE NOCASE), name, password_hash (Argon2id PHC), totp_secret (BLOB, sealed), totp_confirmed (bool), totp_last_step (replay guard), admin (bool), disabled (bool), created_at, photo_mime, photo_version (int, cache key), theme (default `light`), language (default `en`), ui (default `instrument`), timezone (default `UTC+03:00`). |
| 159 | - `invites`: token (hash PK), email, invited_by (user id, nulled on inviter delete), admin (bool, role), created_at, expires_at, accepted_at. |
| 160 | - `sessions`: token_hash PK, user_id FK, created_at, expires_at, revoked_at, ip, agent (User-Agent), seen_at (throttled to 5 min). |
| 161 | - `oidc_clients`: client_id PK, name, secret_hash, redirect_uris (JSON text), created_at. |
| 162 | - `auth_codes`: code_hash PK, client_id, user_id, redirect_uri, nonce, code_challenge, session_hash, expires_at (60 s), consumed_at. |
| 163 | - `refresh_tokens`: token_hash PK, user_id, client_id, session_hash FK sessions, expires_at, revoked_at. |
| 164 | - `signing_keys`: kid PK, private_der_enc (PKCS#8, sealed), public_der, created_at, active (default 1; never set to 0 in code). |
| 165 | - `app_sessions`: token_hash PK, user_id, client_id, session_hash, created_at, expires_at, revoked_at. |
| 166 | - `events`: id (ULID PK), at, kind, actor, detail (audit log). |
| 167 | - `reset_links`: token (hash PK), user_id, created_at, expires_at, used_at. |
| 168 | - `email_changes`: old_token_hash PK, new_token_hash UNIQUE, user_id, old_email, new_email, created_at, expires_at, confirmed_old_at, confirmed_new_at, used_at. |
| 169 | - `login_attempts`: key, at; index on key+at (rolling 1 h window). |
| 170 | - `settings`: key PK, value. Policy keys (invite_days, session_days, max_sessions, pending_minutes, reset_minutes, login_attempts_per_hour), smtp_* keys (host, port, username, from, from_name, password sealed as `smtp_password`), smtp_check_at, smtp_check_ms, smtp_check_error. |
| 171 | - `services`: key PK, name, url, position, owner (client id; null if unowned), client_id, storage_limit_bytes. |
| 172 | |
| 173 | Migration ALTERs (`migrate`): users.photo_mime, photo_version, theme, language, ui, timezone, totp_last_step; services.client_id, storage_limit_bytes; sessions.ip, agent, seen_at. Services seed from config only when table is empty. |
| 174 | |
| 175 | Sealed values use the `v1:` envelope (see 6). |
| 176 | |
| 177 | ## 5. Config keys |
| 178 | |
| 179 | File: `config/im.toml` (also written with DEFAULTS by `Config::load()` if missing). Path resolution beside the binary's working dir (`%h/im` in deploy). |
| 180 | |
| 181 | | Key | Default | Notes | |
| 182 | |---|---|---| |
| 183 | | `database` | `im.db` | Turso DB path; key file and storage dir live beside it | |
| 184 | | `listen` | `127.0.0.1:7650` | bind address | |
| 185 | | `issuer` | `http://127.0.0.1:7650` | must be http(s); trailing slash trimmed; https makes cookies Secure | |
| 186 | | `[[services]]` | in/Files/`http://127.0.0.1:7655`, im/Account/`http://127.0.0.1:7650`, iz/Board/`http://127.0.0.1:7654` | first-boot seed only; key in/im/iz; url http(s) | |
| 187 | | `[smtp]` | commented example | host, port (587 default), username, from, from_name, password (password stored sealed in DB, not in TOML) | |
| 188 | |
| 189 | Policy defaults (admin-editable in `settings`; values < 1 clamp to default): |
| 190 | - `invite_days` 7 |
| 191 | - `session_days` 30 (DB expiry; the cookie MaxAge is a constant 30 days, see oddities) |
| 192 | - `max_sessions` 5 (oldest revoked when exceeded) |
| 193 | - `pending_minutes` 10 |
| 194 | - `reset_minutes` 60 |
| 195 | - `login_attempts_per_hour` 10 |
| 196 | |
| 197 | Constants: `MIN_PASSWORD_CHARS` 10; `SESSION_DAYS` 30; `CODE_SECONDS` 60; `TOKEN_SECONDS` 900; `REFRESH_DAYS` 30; `APP_SESSION_DAYS` 30; `PHOTO_LIMIT_BYTES` 5 MiB; live `WINDOW` 50 min; `CACHE_TTL` 30 s (health); health timeout 2 s; SMTP probe timeout 15 s; probe timeout for SMTP check; `DEFAULT_TIMEZONE` "UTC+03:00"; Argon2 m=19456 KiB, t=2, p=1; show-once secret TTL 10 min; photo max-age 31536000. |
| 198 | |
| 199 | Env: `IM_BUILD_SHA` (build-time, default `dev`); im-client example reads `IM_ISSUER`, `IM_CLIENT_ID`, `IM_CLIENT_SECRET`. |
| 200 | |
| 201 | CLI (`im-web` binary; no subcommand = serve): |
| 202 | - `invite <email> [--admin]`; `revoke <email>`; `promote <email>`; `demote <email>` |
| 203 | - `create-client <name> <redirect_uri...>`; `rotate-client <client_id>`; `revoke-client <client_id>` |
| 204 | - `pack [--root DIR] [--out FILE]`; `unpack FILE [--root DIR] [--force]` |
| 205 | |
| 206 | Serve startup: seed services when empty; `register_self` (im's own row claimed with owner "im" from issuer on each boot); sweep orphan photo files (deletes unknown files and `*.incoming-*` / `*.tmp`; reports rows missing files); create signing key if none; BodyLimit on `/api/profile_photo`; cookies; assets bundle; trusted proxies `nearest(1)`; graceful shutdown on SIGTERM/Ctrl+C. |
| 207 | |
| 208 | ## 6. Security mechanisms |
| 209 | |
| 210 | - Passwords: Argon2id (m=19456 KiB, t=2, p=1, v0x13), PHC strings. `dummy_verify` for unknown emails to equalize timing. Rules: min 10 chars; reject if it contains the email, local part, or name words (>= 3 chars, substring); change must differ from current; wrong current rejected. |
| 211 | - Tokens: 32 random bytes, base64url no pad; stored as SHA-256 hex. Compared with `subtle` (constant time) where applicable. |
| 212 | - Cookies: `im_session` (raw random token; HttpOnly, SameSite=Lax, Secure iff issuer is https, Path=/, Max-Age 30 days constant); `im_pending` (sealed JSON; 10 min). App cookie in im-client: sealed JSON, MaxAge 30 days. |
| 213 | - Sealing: XChaCha20-Poly1305, `v1:` envelope (base64 of 24-byte nonce || ciphertext), key = 32-byte `im.key` (mode 0600, created on first boot). |
| 214 | - Sealed at rest: TOTP secrets, signing private key (PKCS#8), SMTP password, pending cookie. |
| 215 | - JWT: RS256 (PKCS#1 v1.5 + SHA-256), hand-rolled `sign_jwt`; RSA-2048 key generated on first boot; no rotation mechanism. |
| 216 | - PKCE: S256 required on /authorize; verified at /token. |
| 217 | - Auth codes: single use, 60 s TTL, peek then consume in immediate transaction. |
| 218 | - Refresh: rotation on each use; old revoked; no reuse-detection chain revocation. |
| 219 | - Login rate limit: per-key rolling 1 h window, `login_attempts_per_hour` (default 10); keys: email (login), `totp:{user}`, `forgot:{email}`. Limits successful-login lockout by design (DoS possible). |
| 220 | - Session policy: `max_sessions` cap (oldest revoked); sessions revoked on disable, delete, password reset, password change (others), sign-out-everywhere; `seen_at` throttled to 5 min. |
| 221 | - Disabled users: refused at login, at session resolve, at introspection. |
| 222 | - Open redirects: `safe_back` allows local paths and same-origin family URLs only; redirect_uri exact match. |
| 223 | - Email confirmation: email change requires both old and new addresses to confirm; GET confirmation pages do not mutate. |
| 224 | - Forgot password: always same response (no enumeration). |
| 225 | - Show-once secrets: client secrets and invite links shown once via in-memory shelf (`SHOWN_SECRETS`, 10-minute TTL, one-time ticket). |
| 226 | - Basic auth for cross-app endpoints checks client_id:secret against `oidc_clients`. |
| 227 | - Trusted proxy: client label from `nearest(1)` proxy (X-Forwarded-For). |
| 228 | - Photo upload: magic-byte sniffing; 5 MiB limit; BodyLimit. |
| 229 | - Audit: events logged for admin and account actions; introspection deliberately not logged; `log` never fails the caller. |
| 230 | - Pack archives: 0600 mode; unpack refuses unsafe paths; manifest version must be 1; tightens .toml, .keys, .key to 0600. Pack archive contains plaintext `<key>.key` (not encrypted). |
| 231 | - Not present: CSP, HSTS, X-Frame-Options, CSRF tokens (relies on SameSite=Lax + same-origin forms). |
| 232 | |
| 233 | ## 7. im-client crate public API |
| 234 | |
| 235 | Crate: `crates/im-client` (features: `oidc` default on). Directory mirror always available. |
| 236 | |
| 237 | OIDC (`oidc` feature): |
| 238 | - `Config { issuer, client_id, client_secret, redirect_uri, cookie_name, cookie_key: [u8; 32] }`. |
| 239 | - `mount(builder, config)`: adds routes: |
| 240 | - `GET /auth/login?next=`: sets PKCE pair cookie `{cookie_name}_pkce` (10 min); redirects to `/authorize` (scope openid profile email). |
| 241 | - `GET /auth/callback`: state check; code exchange; id_token validation (JWKS cached 1 h, refetch on unknown kid; nonce check); introspection of app_session; sets app cookie. Errors redirect to `/?auth_error=...`. |
| 242 | - `GET /auth/logout`: clears app cookie only (does not end the central session). |
| 243 | - `current_user(cx) -> Option<User>` where `User { sub, email, name, admin, photo_version }`; introspects per request. |
| 244 | - App session cookie: sealed JSON `{app_session, exp}`, MaxAge 30 days. |
| 245 | - Refresh tokens are ignored by the client (app session lasts 30 days). |
| 246 | - `Error` enum: `Http`, `Refused`, `Token`. |
| 247 | |
| 248 | Directory mirror (`directory` module): |
| 249 | - `DirectoryClient::new(issuer, client_id, client_secret)`; methods `directory()` (full list), `photo(sub)` (bytes), `open_stream()` returning `DirectoryStream` with `next()` yielding `DirectoryEvent`. |
| 250 | - `DirectoryMember { sub, email, name, admin, photo_version, timezone (default "UTC+03:00"), disabled }`. |
| 251 | - `DirectoryEvent { Profile(DirectoryMember), Revoked { sub } }`. |
| 252 | - `spawn_sync(client, on_member, on_resync)`: full pass, then stream; backoff 1 s doubling to 30 s cap; `on_resync` after reconnect. |
| 253 | - Oddity: module doc comment has a truncated sentence about `open_stream` and events. |
| 254 | |
| 255 | Example: `crates/im-client/examples/demo.rs`: smoke-test app at redirect `http://127.0.0.1:7656/auth/callback`, env IM_ISSUER / IM_CLIENT_ID / IM_CLIENT_SECRET, fixed DEV_COOKIE_KEY [42; 32]; routes `/` and `/me`. |
| 256 | |
| 257 | ## 8. UI pages and style |
| 258 | |
| 259 | Pages (all server-rendered via topcoat `view!`): |
| 260 | - Signed out: `/` (login card), `/login`, `/login/totp`, `/invite/{token}`, `/forgot`, `/reset/{token}`, `/email/{token}`, `/enroll` (hardcoded English for these pages). |
| 261 | - Signed in: `/` landing (sections profile, sessions, apps, preferences, password), `/enroll`, `/people/{user_id}`, `/admin` (users, services, message, settings, logs, health; mail reached only via redirect). |
| 262 | - Errors shown via `error_text` and OK messages via `ok_text`; mapping in i18n.rs. Landing uses the user's language; `lang_of` returns English when signed out. |
| 263 | - Shell (`layout.rs` `shell`): `lang` attribute; `data-theme="dark"` only when user theme is dark; `data-ui` = instrument (default) or ledger. Google Fonts link loads IBM Plex Mono only (Newsreader used by ledger is not loaded; falls back to Georgia). |
| 264 | - Signed-in chrome: "im" mark with family flyout (sibling marks, health dots; CSS hover/focus). |
| 265 | - Avatar: photo or initial span; avatar viewer JS and XHR upload-progress JS (`avatar_script`). |
| 266 | - Soft navigation JS (`soft_nav_script`): fetch + DOM swap; `data-hard` opts out. |
| 267 | - Themed dropdown (`dropdown.rs`): replaces `select.auth-input`; search box when > 7 options or `data-search`; keyboard support; panel appended to body; only on signed-in pages. |
| 268 | - Logs fit-to-viewport script (`LOG_FIT_SCRIPT`), cookie `im_rows_logs`, clamp 5 to 200 rows, default 50. |
| 269 | - Session list: `<details>` modal cards; admin popovers use top-layer dialogs. |
| 270 | - Styles: `style/main.scss` and `style/_ledger.scss` compiled by `build.rs` (grass) to `crates/im-web/assets/main.css` (generated, 1304 lines, not in .gitignore). Tokens: --ink #1a1b1d, --accent #46557b, --font-sans system-ui, --font-mono IBM Plex Mono. Two data-ui languages (instrument: default; ledger: warm paper, serif display) plus dark variants. Responsive breakpoint at 720px. |
| 271 | - Assets served through topcoat `asset!("assets/main.css")` bundle. |
| 272 | |
| 273 | ## 9. Oddities, bugs, half-finished items |
| 274 | |
| 275 | Security: |
| 276 | - `/email_change` leaks both confirmation links in the redirect query (`links=`) when mail sending fails. |
| 277 | - Any registered OIDC client can call `/family/register` for an unowned key and URL; im then GETs `{url}/healthz` from signed-in pages (SSRF-like probe). |
| 278 | - Any valid client can claim unowned service rows. |
| 279 | - `/photo`, `/directory`, `/family` are accessible to any registered client (no per-client scoping). |
| 280 | - Live `profile` frames are broadcast to all signed-in users (not filtered per viewer). |
| 281 | - No CSP, HSTS, X-Frame-Options; no CSRF tokens (SameSite=Lax + same-origin forms only). |
| 282 | - Signing key never rotated (`active` never set to 0). |
| 283 | - Refresh token reuse does not revoke the chain. |
| 284 | - Access token `scope` hardcoded to "openid profile email". |
| 285 | - Login rate limit can lock out a legitimate user (per-account DoS). |
| 286 | - Admin user email edit (`/admin/user_email`) bypasses two-sided confirmation (intentional rescue but unguarded). |
| 287 | - Admin cannot disable TOTP for locked-out users; no UI to remove 2FA. |
| 288 | - `login` allows sign-in without 2FA (2FA is optional for everyone). |
| 289 | - `verify_login` receives untrimmed email while rate-limit key is trimmed (inconsistent). |
| 290 | |
| 291 | Functional / consistency: |
| 292 | - `SESSION_DAYS` const (30) vs policy `session_days`: cookie Max-Age is the constant while DB expiry uses policy. |
| 293 | - `delete_user` does not delete `reset_links`, `email_changes`, `auth_codes`, `events`, or the photo file (orphans). |
| 294 | - Duplicate pending invites for the same email are allowed. |
| 295 | - `set_smtp` with empty host removes smtp keys but NOT `smtp_password`. |
| 296 | - `NavMail` i18n key is unused; the admin mail section is unreachable from the nav. |
| 297 | - `connected_chip` TR and EN branches are identical (trivial). |
| 298 | - Unused `let _ = issuer;` in the enroll page (dead code). |
| 299 | - `/enroll` revisit regenerates the TOTP secret for already-confirmed users (`set_totp` resets `totp_confirmed = 0`), which could lock out a user who has not yet re-scanned. |
| 300 | - Login, TOTP, invite, enroll, forgot, reset, and email-confirm pages are English-only even for Turkish users. |
| 301 | - `invite_mail` English only. |
| 302 | - im-client module doc has a truncated sentence. |
| 303 | - `store.rs` `migrate` comment for services.client_id sits under the timezone ALTER (comment placement mismatch). |
| 304 | - `migrations/` directory absent; schema is in `store.rs`. |
| 305 | - Pack archive holds plaintext `*.key` (unencrypted at-rest key). |
| 306 | - `connected_chip` and some i18n keys duplicated; `kind_word` lacks labels for several audit kinds (forgot_limited, user_demoted, services_updated, email_changed, email_change_asked); raw kind strings shown instead. |
| 307 | - `main.css` is a generated artifact and is not git-ignored. |
| 308 | - Discovery document omits introspection and end-session endpoints even though they exist. |
| 309 | - Deploy: GitHub Actions `.github/workflows/main.yml` runs `cargo test --workspace`, bundles assets, deploys over SSH to `$HOME/im` with `current` / `current.new` / `current.previous` swap; systemd unit `deploy/im.service` (`ExecStart=%h/im/current/im-web`, Restart=on-failure, WantedBy=default.target); health-check and rollback loop; served-stylesheet hash check. |
| 310 | - Release profile: fat LTO, codegen-units=1; `dist` profile: thin LTO, codegen-units=16. |
| 311 | - Coverage gaps in this survey: admin logs/health markup and test modules were surveyed, not read line-by-line; i18n full key list not enumerated; `main.css` not read in detail. |