im
Clone
0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits
Code conventions
These rules are the same in im, in and iz (the file is copied into each repo). They are taken from
forge (~/Documents/Code/Rust/forge, see its docs/architecture.md), which is the reference
implementation: when a rule here is unclear, read how forge does it and do the same.
1. Workspace
- Edition 2024, resolver 3,
unsafe_code = "forbid"in[workspace.lints.rust], every member ends with[lints] workspace = trueandpublish = false. - Every dependency version lives in the root
[workspace.dependencies], added withcargo addat its latest release (never copied from another project). Members writefoo.workspace = true. - Topcoat 0.11 with
default-features = falseand an explicit feature list. Turso (latest stable) for the database. - Two crates per app:
<app>-core(domain types, store, migrations, config, secrets, auth primitives, pure logic; no HTTP) and<app>-web(the binary named<app>: Topcoat UI, HTTP APIs, background workers, CLI). Add a crate only for a real boundary. - Dev profile:
debug = "line-tables-only";opt-level = 3forargon2,sha2and the turso crates, each with a one-line reason. Release:lto = true,codegen-units = 1.
2. Boot
main.rs dispatches on positional words: no word or serve runs the server, admin <cmd> runs the CLI.
Config path: --config <path>, then <APP>_CONFIG, then config/<app>.toml. Exit 2 on usage errors, 1 on
failure.
serve order: load and validate config → create data_dir (0700) → load or create <app>.key (32 bytes, 0600,
O_EXCL) → open the store (pragmas, migrations) → layer stored UI overrides on the file config → spawn
workers → build the router → bind → serve until SIGTERM/Ctrl-C, with one stop flag shared by every listener and
worker.
Logging: tracing + tracing-subscriber (env-filter), stderr, default info, structured fields. Never log
tokens, passwords, cookies, or secrets.
3. Config
config/<app>.example.tomlis committed.config/<app>.tomlis gitignored. A missing file is created from the example (dev defaults) on first run.#[serde(deny_unknown_fields)]on every struct. OneConfig::validate()for cross-field rules, used at load and when a UI override is saved.- Secrets never live in the TOML. They are entered in the admin UI (sealed in the DB) or in a separate file readable only by the service user.
- Runtime settings: a
settingskey/value table with precedence UI override → file → built-in default, and each field markedLive,RestartorReadOnly(forgeserver_settings.rs).
4. Store
- One writer connection behind a tokio
Mutex, plus a pool of 4PRAGMA query_onlyreaders. Pure reads use a reader; writes, transactions and read-then-write sequences use the writer. - Pragmas on every connection:
journal_mode=WAL,synchronous=FULL,foreign_keys=ON, busy timeout 5 s. Read them back and log them at boot. - Migrations:
crates/<app>-core/migrations/NNNN_snake_name.sql, each starting with a comment that says what it does; listed instore/migrate.rsas(version, include_str!(...)); each applied in its own transaction with aschema_migrationsrow. Never edit an applied migration. - Ids are ULID text. Timestamps are UTC RFC 3339 with 9 fractional digits and
Z(fixed width, so text order is time order) fromtime.rs(now_stamp(),stamp_after(d)). Booleans areINTEGER0/1 with aCHECK. - Column lists are constants (
USER_COLS) next to theirmap_user(row); SQL uses?1, ?2; ownership goes in theWHERE(... WHERE id = ?1 AND owner_id = ?2). - Multi-statement writes:
unchecked_transaction()+ an async block returningResult+ onefinish(tx, outcome)helper that commits or rolls back. - Constraints live in the schema (
NOT NULL,CHECK,UNIQUE,REFERENCES ... ON DELETE ...), not only in Rust. - Backups:
snapshot_to(path)withVACUUM INTOon the writer, then checkpoint the copy so it is one self-contained file, then fsync.admin backup --out DIRwrites the snapshot, the blob tree (where the app has one), amanifest.jsonwith a sha256 per file and amanifest.mac: HMAC-SHA256 of the manifest bytes under a subkey of the instance key, which lives outside the backup. Verify and restore check the MAC first (constant time), then hashes,integrity_checkand contiguous migrations. Never copy a live DB file.
5. HTTP and pages
- Routes with
#[route(...)]/#[page(...)]and.discover(). Anything that must not be public is registered explicitly on a separate router. - Handler shape: (1) authenticate, (2) load and authorize, (3) build the view, (4) return it.
- Forms: every field
#[serde(default)]; every state-changing POST carries acsrffield checked in constant time before any side effect (require_csrf). Pre-session forms use the__Host-<app>_precsrfcookie (SameSite=Strict). Post/Redirect/Get with notices in the query string (?notice=...), not cookies. - Session cookie:
__Host-<app>_session, random 32 bytes base64url; the DB stores only its SHA-256. HttpOnly, Secure, SameSite=Lax, Path=/. safe_next()for every return path: one leading/, not//or/\, no control characters, ≤2048 bytes.- One security-headers layer on
/:X-Content-Type-Options: nosniff,X-Frame-Options: DENY,Referrer-Policy: same-origin,Strict-Transport-Securitywhen the base URL is https, andContent-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'. No inline scripts or styles anywhere; all JS is inassets/*.js. - Styled 404 page for
Accept: text/html; 404 for "missing" and for "exists but you may not see it". - Request bodies are capped per route (
BodyLimit); upload routes stream. - Assets (CSS compiled from
style/*.scsswithgrassinbuild.rs, JS, fonts) are embedded withinclude_str!/include_bytes!, served by routes withCache-Control: public, max-age=31536000, immutable, and linked with a content-hash query (/assets/main.css?v=<12 hex>). Fonts are self-hosted. Nothing is loaded from a third-party origin.
6. Auth primitives
- Passwords: argon2id (
Argon2::default()), PHC strings, always onspawn_blocking. Unknown accounts verify against a fixed dummy hash so timing does not reveal them. - Tokens: 32 random bytes, base64url; stored as hex SHA-256; compared with
subtle; shown once. - Throttle (in memory, sliding window, bounded key count): failed logins per account and per IP, failed second
factors per user; checked before any lookup;
429withRetry-After. - Secrets at rest:
seal/openwith XChaCha20-Poly1305,v1:+ base64(nonce || ciphertext). The instance key is never used directly: every use gets its own key, HMAC-SHA256(instance key, " - Client IP: the TCP peer unless it is in
trusted_proxies; thenX-Forwarded-Forright to left.
7. Authorization
One pure function per app, authz::authorize(actor, resource, role, action) -> Result<(), Denied>, with
Denied::{NotFound, Forbidden}. Every page, form handler, API route and live stream goes through it. It is
unit-tested as a truth table.
8. Live pages
LiveHubofwatch::Sender<u64>perTopic(an enum keyed by what a page is about). Writes calllive.bump(&topic)after commit.- A page that updates live renders
data-live="<stream url>". The stream route authenticates and authorizes first, thenstream_changes(cx, hub, topics, fingerprint): subscribe, read a fingerprint, and send a data-lessevent: changedonly when the fingerprint changes.retry: 1000, keep-alive every 30 s,X-Accel-Buffering: no. GET /-/aliveis held by every page (anonymous-safe). It drives the "server restarting" bar and carriesaccountevents (sign-out, preference change) for the viewer.assets/nav.js(one file, progressive enhancement): soft navigation for same-origin links and forms (data-hardopts out), keeps focus/scroll/typed input across swaps, opens one EventSource per distinctdata-liveURL, re-fetches the page onchanged, reconnects after 1/2/3 s, never re-sends a POST. Pages work without JS.
9. Errors
- One
thiserrorenum per crate:Io,Database,Migration,Config,Crypto,NotFound,Conflict(String),Forbidden(String),Invalid(String). InvalidandConflicttext is for the user (shown as an alert). Everything else is a 500 with a generic page and a logged cause.- Security-sensitive answers are identical for "unknown" and "wrong".
10. Audit
Append-only audit_log (id, at, actor_id, actor_kind, action, target_kind, target_id, ip, data JSON). Written
after the change commits; a failed audit write is logged and never fails the request. Never store secrets in
data. Admin page with filters and keyset paging. Rows older than the retention window are removed by the sweeper; nothing else deletes them.
11. i18n
English and Turkish. Lang::{En, Tr}; resolution: the user's stored language, else Accept-Language, else
English. Keys are enums per area with an exhaustive match on (key, lang), so a missing translation does not
compile. Every page, including sign-in, error and mail text, is translated. Sentences with values use small
format helpers, not concatenation in views.
12. Comments and naming
//!on every module: what it is, what it is not, the invariant it keeps.///on every public item and on every policy constant (with its unit and reason). Inline comments explain why, in full sentences.- No commented-out code. No
TODOwithout a line indocs/backlog.md.
13. Tests
Few and meaningful. Unit tests for pure logic that is easy to get wrong (authz truth table, token and CSRF
compare, safe_next, parsers, time math, quota math), store tests on a real temp database (tempfile) for
tricky queries and constraints, and one or two in-process router tests per security rule (CSRF refused,
hidden resource is 404, admin page refuses members). No snapshot tests, no browser tests, no mocks of the
database. Tests never write outside their temp dir.
14. Deploy
deploy/<app>.service: dedicated user, ProtectSystem=strict, ReadWritePaths= the data dir only,
ProtectHome=yes, PrivateTmp=yes, PrivateDevices=yes, NoNewPrivileges=yes, CapabilityBoundingSet=,
RestrictNamespaces=yes, RestrictSUIDSGID=yes, LockPersonality=yes, MemoryDenyWriteExecute=yes,
SystemCallArchitectures=native, SystemCallFilter=@system-service, UMask=0077, Restart=on-failure.
/healthz per contracts.md 4.1.
15. Git
Commit messages follow forge's style: gitmoji + type + description, for example
✨ feat: sign-in with TOTP and recovery codes, 🐛 fix: ..., ♻️ refactor: ..., 📝 docs: ....
No co-author or "generated with" lines.