steid

@jamesgill /

steid/plans/progress.md
Markdown70.5 KBRendered·Source·Blame·History·Raw
1# Progress
2
3## This attempt (#3, Topcoat)
4
5598 tests. Active milestone in [current.md]current.md.
6
7### Section 1 wave — read-only browsing · done
8
9**Every read-side `git` process is now bounded at 20 s** (`GIT_TIMEOUT` in
10`git_query.rs`), and the child is `kill_on_drop` so a cancelled request takes git with
11it. Added before blame and grep arrived, because those are the first reads that can
12run long on a big repository, and five agents each adding their own bound would have
13produced five. `GitQueryError::is_timeout()` is how a page tells "asked too much"
14(render a state, offer less) from "git failed" (a 500). Tokio's `time` feature was
15enabled for it.
16
17**Syntax highlighting (merged 2026-09-05).** `syntect` with the pure-Rust `default-fancy`
18engine plus `two-face` (`syntect-fancy` feature) for the grammars the default set lacks —
19TOML, Dockerfile, TypeScript — at +0.59 MiB on the binary. Decisions worth keeping:
20
21- **Classes, never inline colours.** Output is `ClassStyle::SpacedPrefixed { prefix: "hl-" }`
22 and every colour is a `--syntax-*` token in `styles.css`, so the palette follows the
23 theme. `ClassedHTMLGenerator` cannot be used because its spans cross line boundaries
24 and the blob view is one table row per line; `highlight.rs` drives `ParseState` +
25 `ScopeStack` itself, carrying parse state across lines but closing and reopening the
26 markup at each line end.
27- **`hl-` classes are scope atoms, not positional**, so `.hl-function` alone would colour
28 every `meta.function` body. Single-atom selectors only for an atom that leads its scope;
29 the rest are compounds. Rule order in `styles.css` is load-bearing: `.hl-string` is
30 written after `.hl-punctuation` so a quote reads as its string, and the comment rule is
31 last.
32- **The trailing newline is dropped by character, not `trim_end`** — the `_newlines`
33 syntaxes need it fed in, and it comes back escaped inside the output, sometimes before a
34 closing span. Left in, every row renders double-spaced.
35- **Caps are 512 KiB and 10,000 lines**, both, because cost is per byte and per line.
36 Plain text is returned as `Plain` lines, not wrapped in colourless spans.
37- **~87 ms per 1,255-line file in release**, uncached, paid on every view; debug is ~8×
38 slower and not the number to plan against. If it matters: cache per blob object id.
39
40**Branches and tags pages (merged 2026-09-05).** `/branches` and `/tags`, one
41`for-each-ref` each, and the counts beside the switcher and in the sidebar are links.
42
43- **`%(HEAD)` is why the page is one process**: `for-each-ref` marks the default branch,
44 so nothing calls `symbolic-ref` on the happy path, and the compare link's base is read
45 from the pinned row.
46- **Keep empty fields when splitting `for-each-ref` output.** A lightweight tag's
47 `%(*objectname)` is empty; filtering empties shifts its date into the id slot. There is
48 a test for exactly this.
49- **Ordering is git's (`--sort=-committerdate`), pinning is the use case's.** The default
50 branch is a display decision, a stable partition in `list_branches`.
51- **A lightweight tag's `%(contents:subject)` is the commit's subject**, so it is read only
52 when `%(objecttype)` is `tag`. `annotated` is its own field because an annotated tag may
53 carry an empty message. The row shows the peeled `%(*objectname)` so the sha is browsable.
54- **"No tags yet" and "nothing pushed yet" are different sentences**; telling them apart
55 costs one `default_branch` call, only when the list is empty.
56- **`refs.rs::timed_out` is the first web-layer place that renders a timeout as a state**
57 rather than a 500. When a second page wants it, move it to `web::context`.
58
59**Archive download and code search (merged 2026-09-05).** `/archive/{rev}.tar.gz`
60and `.zip` streamed from `git archive`; `/search?q=&rev=` over `git grep -F`.
61
62- **`GitArchive` is a fourth narrow port, not a `GitQuery` method.** `GitQuery`'s contract
63 is capped bytes, collected; an archive is as large as the repository. It lives in
64 `infrastructure/git.rs` beside the protocol server and reuses `web::git::GitBody`, so
65 "one subprocess's stdout becomes a response body" is written once and used twice.
66- **The archive use case is two steps, which is what makes the `ETag` cheap.**
67 `archive_repo` authorizes and resolves into an `ArchiveTarget` nothing else can
68 construct; `open_archive` runs git. A conditional request is answered from step one,
69 so re-downloading a tag costs one `cat-file`. The `ETag` is the resolved commit.
70- **`git grep` is the one command whose exit status is an answer** (1 = no matches).
71 `run_within_allowing` takes an allowed-exit list and `NO_MATCHES` names the exception
72 at the call site, so the module's rule stays visible where it is broken.
73- **`git grep -z` is not optional**: a path may contain colons, so the colon-separated
74 form has no unambiguous reading. The parser walks NULs.
75- **`RepoPath` refuses a colon**, so `a:b.rs` is unsearchable as well as unbrowsable; the
76 parser drops those hits rather than link to a 404. Pinned by a test.
77- **A search timeout is a page state** (`Searched::TimedOut`), the first real consumer of
78 `GitQueryError::is_timeout`.
79- **Archive and search 404 a private repository for a stranger**, matching every other
80 read page rather than 0007's uniform 401, which exists so a git client can offer a
81 credential; a browser link gets no benefit from it.
82- `topcoat dev` in a worktree exited rather than restarting after some source edits and
83 had to be relaunched by hand. Possibly two instances sharing a `target/`. Watch it.
84
85**Commit page and compare view (merged 2026-09-05).** `/commits/{sha}`, `/compare`
86(form) and `/compare/{base}...{head}`, three-dot. Every sha in the log and the
87latest-commit bar links to the commit page.
88
89- **The counts and the patch come from one `git` process**: `diff-tree --numstat -p`
90 writes numstat *first*, so a patch too large to draw still lists every file with real
91 `+a −b`. A second `--numstat` call would be paid on every page for the rare oversized
92 one.
93- **`run_capped` reads through a pipe and kills the child** at `max_bytes + 1`; the exit
94 status is checked only when the cap was not hit, since a killed process says so.
95- **`run_allowing` bends the "non-zero exit is a fault" rule for exactly two commands**
96 whose codes git's manual promises as answers: `grep` (1 = matched nothing) and
97 `merge-base` (1 = no common ancestor, 128 = broken). Both arrived in the same wave with
98 their own copy; the merge kept one. A third caller needs the same scrutiny.
99- **Compare is three-dot** (merge-base to head): two-dot undoes everything base gained
100 since the branch left, a wall of deletions nobody made, and three-dot is what a pull
101 request needs. `...` is unambiguous because `RefName` refuses `..`.
102- **The patch parser tracks hunk line counts**, never matching `diff --git`/`+++`/`---`
103 prefixes anywhere: a patch *of a patch* contains those as content.
104- **Paths come from `---`/`+++`/`rename from`, not the `diff --git` header**, whose
105 `a/<old> b/<new>` has no defined split when names contain spaces. C-quoted names are
106 unquoted.
107- **The compare form GETs to `/compare?base=&head=` and 307s to the path form**, so the
108 shareable URL is always the path one and no JavaScript is needed.
109- **The file header is `sticky`, which is why the diff panel is not `overflow-hidden`**:
110 a hidden overflow makes an ancestor a scroll container and sticky sticks to nothing.
111
112**Blame (merged 2026-09-05).** `/blame/{rev}/-/{path}`, with `Code · Blame · Raw` in the
113file header of both views.
114
115- **The porcelain parser is pure, in `application/blame.rs`.** `git blame --porcelain`
116 writes a commit's header block only the *first* time the commit appears; later runs are
117 a bare sha line looked up from an accumulated map. A code line can look exactly like a
118 header line, and **the leading tab is the only thing that tells them apart**. Both are
119 pinned by tests. `parse_blame` never fails: an unrecognised record is skipped.
120- **`filename` is per commit, not per hunk**, carried on `BlameCommit`; that is what makes
121 the "moved from" marker work.
122- **The use case reads the blob before blaming**, so binary, too-large and not-there are
123 decided by the blob page's rules from the same cap. Blame's own output cannot tell: a
124 binary file blames into garbage rather than reporting itself. Costs one `cat-file`.
125- **The commit cell is one line tall, on purpose**: two lines and blame and blob disagree
126 about where line 400 is. Row height measured at 19.5px in both.
127- **The age tint is linear in time, not rank**, five steps between the file's oldest and
128 newest commit, as `color-mix` of the primary in plain CSS. A file whose history is
129 bunched shows only the end steps; rank quintiles would always look richer and lie about
130 the gaps. A file written in one commit takes the top step.
131- **Blame is 4 processes** (two `batch-check`s asking the same existence question, one
132 from the use case and one inside the adapter). A kept-alive `cat-file --batch`
133 collapses both — the same upgrade 0006 defers.
134- **Headless Chrome writes screenshots to files; the puppeteer MCP tool does not.**
135 `--headless --hide-scrollbars --window-size=W,H --screenshot=path URL`. And `topcoat
136 dev` sometimes keeps printing "no changes; application up to date" while serving the
137 previous binary; `pkill -f "topcoat dev"`, wait for the port, restart.
138
139**The integration pass (2026-09-05).** The five branches merged, run as one app against
140Steid's own history — 9 branches, 2 annotated tags, a public repository and a private
141one — and every link crossing a feature boundary followed in a browser, in dark and in
142light. **Nothing was broken at a seam**, which is the finding: five agents that could
143not see each other agreed on URL shapes because the shapes were written down in
144`ui.md` and in each other's handovers before the code was.
145
146- **A private repository 404s on all eleven read routes anonymously** — landing, log,
147 branches, tags, commit, search, tree, blame, raw, archive, compare. Every use case
148 takes an `Actor` and answers `Ok(None)`, and each page turns that into `not_found()`;
149 the uniformity is the architecture rule paying off rather than eleven separate
150 decisions.
151- **Two gaps found, both entry points rather than breaks.** The About sidebar's Download
152 links can only ever offer the default branch, because the sidebar renders on the one
153 repository page that has no `{rev}`. And blame renders its lines unhighlighted while
154 the blob highlights them, `highlight.rs` and `blame.rs` having shipped on separate
155 branches. Both are in [current.md]current.md.
156- **A wave needs a divergent branch to test compare with.** Every feature branch was an
157 ancestor of `main` after merging, so every branch row's Compare link correctly said
158 there was nothing to compare and exercised none of the diff. `git commit-tree` makes
159 one without a working tree.
160- **Follow-ups the handovers named, done here:** blame's revision switcher (`Switch`
161 gained a `Blame` arm), `web::context::timed_out` shared by three pages, `.jsx` aliased
162 onto JavaScript, `token.rs`'s phantom `bg-muted`, and the two exit-status comments
163 that each claimed to be the only one.
164
165**Released as 0.3.0 (2026-09-06)** — the first version carrying the section 1 wave.
166No migrations between 0.2.0 and 0.3.0, so the two binaries share a database and
167`deploy.sh`'s rollback is a real one. First Linux release build with `syntect` and
168`two-face`; both are pure Rust behind the fancy-regex features — the bullseye container
169build took ~2 minutes and needed no changes. Deployed 2026-09-06 12:07 UTC+1, health
170check passed first time. Probed live afterwards: landing, branches, tags, search, log,
171commit and compare all under 0.25 s; the 113 KB `git_query.rs` blob and its blame both
172~0.65 s (highlighting, uncached, on the Lightsail box); `archive/main.tar.gz` answers with
173the sha as `ETag`; an unknown repository 404s.
174
175### Wave 2 — git features · in progress
176
177**Rename, default branch, archived (merged 2026-09-06).** All on the settings page,
178which now reads as five sections.
179
180- **A rename moves the directory first, then writes the row**, compensating with a move
181 back if the save fails — the opposite order from delete, because a move is reversible
182 where a delete is not. `GitStorage::rename` refuses an occupied destination: with no
183 row naming it, whatever is there is an orphan, and adopting it hands someone else's
184 objects to this repository. **`fs::rename` silently replaces an empty directory on
185 Unix**, hence the explicit exists check.
186- **No redirect from an old name**, single tenant; the form names `git remote set-url`.
187 Revisit at Milestone 7.
188- **The default branch has no column.** git holds it in `HEAD`; a SQLite copy would be a
189 second answer that drifts. The write is `GitStorage::set_default_branch` (on the
190 storage port, since `GitQuery`'s contract is reading). **`symbolic-ref` accepts a
191 branch that does not exist**, which would make every page say "nothing pushed yet",
192 so the use case checks the name against `branches()` first — the same call that
193 renders the select, so one process for both.
194- **Archived is a column and not a third visibility.** It says "finished", not "hidden":
195 clone, browse, search and download keep working, and an archived private repository is
196 a real, tested state. The push refusal sits in `serve_git` *after* the `Role::Owner`
197 check, so only someone who could otherwise push ever learns a repository is archived.
198 `DomainError::Archived` is its own variant: the owner is refused too, and it is the
199 one refusal the person hitting it can lift. The 403 carries a `text/plain` body so
200 `git push` shows the sentence behind `remote:`.
201- **`update_repo` and `rename_repo` carry `archived` across explicitly**, because both
202 rebuild through `new()`, which resets it.
203- The `repositories` column-migration test in `sqlite.rs` applies a **list** of
204 migrations; every future column on that table belongs in it.
205
206**Issues (merged 2026-09-06).** Per-repository issues with comments, an Issues tab,
207and a number sequence pull requests will share.
208
209- **The sequence is its own table**, `repo_sequences (repo_id, next_number)`, not a
210 column on `repositories`: pull requests draw from it too, and allocating a number must
211 not write the row a push is contending for. **Allocation is one statement**
212 (`insert … on conflict do update … returning`), so SQLite's writer serialisation is
213 the whole concurrency story; `unique (repo_id, number)` makes it load-bearing.
214- **Comments sit behind the issue's port**, one trait for the aggregate, two tables — a
215 deliberate departure from a literal "every table gets a trait". Same-second comments
216 tie-break on **insertion order**, not id: ids are random UUIDs and an id tiebreak made
217 a conversation read backwards, caught by a flaky test.
218- **`markdown.rs` needed no change**: it writes every tag itself and never passes source
219 HTML through, so a `<script>` in an issue is inert text. That property is why
220 user-written markdown can render on the session cookie's origin at all. **Do not
221 reintroduce HTML passthrough.**
222- **Third instance of the page-name shadowing trap**: `#[page] async fn comment` would
223 have shadowed a loop variable; the handler is `add_comment`.
224- Author handles are resolved once per request (`Handles`); a deleted author renders as
225 "someone" rather than failing the page.
226
227**Import from a URL (merged 2026-09-06).** A second block on the new-repository page
228mirrors a public `https://` source in the background; the row exists immediately in an
229`importing` state. Verified against a real GitHub repository: 3,293 commits, 112 tags,
230`HEAD` following the source, an ordinary repository afterwards.
231
232- **`import_state` is nullable and `NULL` is an ordinary repository**, so a page that
233 forgets about importing gets the behaviour it had. `import_source` outlives the state:
234 provenance stays true and a retry needs it. State attaches via `with_import(...)` after
235 construction, like `pinned`, rather than widening `from_trusted`.
236- **The SSRF check is two halves and both are needed**: `ImportSource::new` refuses the
237 scheme, userinfo and literal non-public addresses; `DiskGitImport` resolves the host
238 and checks **every** address immediately before spawning git, because a public name
239 can resolve to loopback. A host with one public and one private answer is refused.
240- **`GitImport` is a fifth narrow port**, not a `GitStorage` method: a ten-minute
241 network transfer that only runs in the background, `kill_on_drop`,
242 `GIT_TERMINAL_PROMPT=0` — which is load-bearing, since without it a private or
243 mistyped source hangs git on a username prompt forever. With it, GitHub's 401 for a
244 missing path reads as "could not read Username", which `import::explain` translates.
245- **`import_repo` does not touch disk**; `git clone --mirror` creates the directory, so
246 the two-writes problem moves into `run_import`, which re-reads the row after the clone
247 because minutes have passed and the repository may have been deleted. The boot sweep
248 marks stuck `importing` rows failed; it is safe because it runs before anything is
249 spawned.
250- **A push during an import is `DomainError::Unavailable` → 409**, after the permission
251 check so a stranger learns nothing. Clones during an import are still served: git
252 either finds refs or it does not. The 409 sentence reaches the terminal as a `remote:`
253 line.
254- `tokio` gained `net` for `lookup_host`. No new crate.
255
256**Push events and webhooks (merged 2026-09-06).** One `push_event` per ref an
257authorized push moved; webhooks at `/settings/hooks` deliver a signed JSON POST with
258retries and a delivery log; `REMOTE_USER` reaches the reflog.
259
260- **Events are recorded from the application, not a `post-receive` script**: refs are
261 snapshotted before and after the receive-pack RPC and diffed. A hook script would need
262 installing on creation and on boot, syncing with the binary, and a channel back; it is
263 the right answer if per-push cost ever matters, and the only way to a `pre-receive`
264 refusal. **The recording hangs off the response body's EOF** (`GitBody::on_end`),
265 because `serve_git` returns while receive-pack still streams; a client that vanishes
266 mid-transfer records nothing.
267- **`REMOTE_USER` was inert until `core.logAllRefUpdates` was turned on** — `git init
268 --bare` leaves bare repos with no reflog. `init_bare` now sets it; **repositories
269 created before this keep no reflog and there is no migration** (`git config
270 core.logAllRefUpdates true` in each bare repo). The `(none)` in the reflog identity is
271 `REMOTE_ADDR`, which Topcoat 0.5 discards.
272- **A hook's secret is stored in the clear**, unlike a token: an HMAC needs the value,
273 and a leak forges a payload at one endpoint rather than acting as the owner.
274- **SSRF in two halves**: `WebhookUrl::new` refuses schemes, credentials, private and
275 link-local ranges and packed address spellings (`127.1`, `2130706433`); the sender
276 resolves and checks every answer before dialling. `from_trusted` does not re-run the
277 rule, so a tightened rule cannot hide a stored hook from the page where it is deleted.
278 **`import` and `webhook` each carry their own `is_public`**; the root re-exports
279 import's. Consolidate.
280- **`ureq`, not `reqwest`**: already in the tree via Topcoat with rustls, so a feature
281 flag rather than a second TLS stack; blocking, hence `spawn_blocking`.
282 `http_status_as_error(false)` because a 4xx is what the delivery row records. New
283 direct deps `hmac`, `serde_json`, `ureq` were all already compiled transitively.
284- **`X-Steid-Delivery` carries the push event's id**, the same on every attempt, since
285 deduplicating on it is the only reason a receiver reads it. Hooks are delivered to
286 concurrently, events sequentially per hook. The retry schedule is a parameter so tests
287 prove four attempts without waiting 2.5 minutes.
288- `GitQuery::ref_snapshot` covers all of `refs/` and reports an annotated tag's own object.
289
290### Milestone 0 — Skeleton · done
291
292Topcoat 0.5 app serving pages, `AppConfig` from `STEID_*` env, SQLite pool in app
293context. Split into a library plus a thin binary — the domain layer had no consumers
294yet and read as ~30 dead-code warnings in a bare binary, and it unlocks `tests/`.
295Topcoat's link-time page discovery works from a library; that was checked, not assumed.
296
297**Requires rustc ≥ 1.95.** On older toolchains `cargo add topcoat` silently resolves to
298an empty `topcoat v0.0.0` placeholder instead of failing.
299
300### Milestone 1 — Identity, thin · done
301
302**Domain.** Typed IDs, `Email`, `PasswordHash`, `OrgName`, `Organization`, `User`,
303`Membership`, `Role`, `Actor`, `Session`, `SetupToken`, `DomainError`. Value objects
304pair `new()` (validates) with `from_trusted()` (skips, for rows already validated).
305
306**Application.** `claim_instance`, `login`, `resolve_actor`, `record_session`,
307`end_session`, `sweep_expired`. `PasswordHasher` port with Argon2 and a stub.
308
309**Infrastructure.** Migrations for orgs, users, memberships, sessions. In-memory and
310SQLite implementations of every port. Root layout, `/setup`, `/login`, `/logout`, home,
311and `/api/me`.
312
313`describe_identity` is the first use case with two consumers — the home page and
314`/api/me` both read through it. Until that existed, "the application layer is
315transport-neutral" was an assertion with one caller behind it.
316
317**Verified in a browser and by curl:** wrong token refused with nothing written;
318correct token creates org + user + owner membership and signs the owner in; session
319authenticates; logout clears cookie and row; wrong password bounces; right one signs
320in; re-claiming a claimed instance is refused.
321
322#### Decisions worth remembering
323
324- **`Actor` is an enum with an explicit `Anonymous`**, not `Option<UserId>`. Attempt #2
325 used a placeholder `UserId("ssh-anonymous")` and it became a security hole. A variant
326 can't be forgotten the way a sentinel can.
327- **`login` verifies a dummy hash when no user matched.** Returning early on the
328 unknown-email path makes it measurably faster and leaks which addresses have
329 accounts. A test pins that the dummy stays parseable — if it stops being, `verify`
330 bails early and the defence dies silently.
331- **`SetupToken` compares in constant time.** An early-return comparison leaks how much
332 of the token is right, which recovers it a character at a time.
333- **The setup token is only in app context while unclaimed**, so a claimed instance has
334 nothing for a claim attempt to match.
335- **SQLite ignores foreign keys unless asked**, per connection. `foreign_keys(true)`
336 plus a test that a user pointing at a missing org is refused.
337- **`sqlx migrate add` stamps versions to the second** — three calls in one second
338 collide, leaving apply order ambiguous between tables that reference each other.
339- **An unparseable role surfaces as an error**, never as "no membership". The latter
340 silently downgrades an owner to no access.
341- **`Secure` session cookies over plain-HTTP localhost fail silently.** See
342 [runbook.md]runbook.md#steid_insecure_cookies--development-only. This one actually
343 bit, and it looked exactly like broken auth logic.
344
345### Milestone 2 — Profile page · done
346
347`/{handle}` is the real profile page: label, handle, bio, and the section frame for
348repositories, writing, and projects. Public, renders signed out, 404s on an unknown
349handle, and resolves regardless of casing. `/` forwards a signed-in owner to their own
350profile. `/api/users/{handle}` serves the same read model as JSON.
351
352URLs settled as root handles with grouped application routes
353([0004]decisions/0004-root-handles-grouped-routes.md), superseding
354[0003]decisions/0003-scoped-urls.md the same day. A twenty-word reserved list in
355`OrgName::new` keeps handles from shadowing routes.
356
357#### Decisions worth remembering
358
359- **`PublicProfile` has no email field, deliberately.** `Identity` does, and `/api/me`
360 returns it, because that endpoint describes the caller to themselves. Giving the type
361 that reaches the page nowhere to put an email makes the leak impossible rather than
362 merely avoided.
363- **`viewer_is_owner` is decided in the use case**, so the web form and `/api` cannot
364 disagree about who may edit. Tested for a signed-in stranger and a non-owner member —
365 "signed in" quietly becoming "allowed" is the usual failure.
366- **`Organization::update_profile` clears on blank input** rather than storing
367 whitespace, so cleared and never-set are one state and the page renders one case. A
368 rejected edit applies nothing.
369- **Bio length counts characters, not bytes.** A byte check would reject a bio of
370 accented text well under the limit.
371- **`path_param` is an attribute macro in 0.5**, not function-like. The vendored crate
372 is the authority for the pinned version, not the docs on `main`.
373- **Components are invoked bare inside `view!`**, and `if`/`match`/`for`/`let` are
374 native to the macro.
375- **`#[query_params]` needs `error = …`** to work with `?`; otherwise the error borrows
376 from `cx` and escapes the handler.
377- **Forms re-render on failure and redirect on success.** Redirecting after a
378 validation error throws away what was typed and hides the reason.
379- **Styling is Tailwind via Topcoat's build script**, with registry components copied
380 in rather than depended on ([0005]decisions/0005-tailwind-and-copied-components.md).
381 Components reference theme tokens, never raw colours.
382
383### Milestone 3 — Repo model · done
384
385Repositories exist as records and as bare repos on disk, and they appear on the
386profile. Domain, both persistence adapters, `GitStorage` with `DiskGitStorage` behind
387it, `create_repo` / `view_repo` / `list_repos`, the `/{handle}/repos/new` form and
388`/{handle}/repos/{name}` page, the profile's Repositories section, and
389`/api/users/{handle}/repos`. How git is invoked is recorded in
390[0006]decisions/0006-git-binary-behind-narrow-ports.md.
391
392**Verified in a browser and by curl:** the owner creates a repo through the form, a
393bare repo appears at `{data_dir}/{handle}/{name}.git`, and it lists on the profile; a
394private repo is absent for a signed-out visitor on both the page and `/api`; an unknown
395handle 404s rather than answering `[]`. `git clone` does not work yet — Milestone 4.
396
397#### Decisions worth remembering
398
399- **`git init` on an existing repository exits 0 and re-initialises in silence.**
400 Measured, not assumed. So `AlreadyExists` has to be our own `path.exists()` check —
401 there is no exit code to key off. Refusing rather than adopting matters because a
402 directory with no matching row is an orphan from a crashed create, and re-initialising
403 it would resurface a private repository's objects under a fresh record.
404- **`git init` creates missing parent directories itself**, so there is no
405 `create_dir_all` before it. This was in the plan and the probe removed it.
406- **`--template=` takes a new bare repo from 18 files to 2.** The default seeds sixteen
407 `.sample` hooks. Timed at 15.2ms against 13.1ms across 20 runs — so the ~2ms is not
408 the reason; Steid installs its own hooks later and the samples would be noise to work
409 around.
410- **`--initial-branch=main` is explicit** so the host's `init.defaultBranch` cannot
411 decide it. This machine's git already says `main`, which is precisely why a drift
412 would go unnoticed — hence the test.
413- **`GIT_CONFIG_GLOBAL` and `GIT_CONFIG_SYSTEM` are pointed at `/dev/null`**, and the
414 five `GIT_*` variables that redirect object storage are removed from the child
415 environment. `GIT_DIR` was checked and does *not* override an explicit path argument,
416 but `GIT_OBJECT_DIRECTORY` does redirect where objects land, and the failure is
417 silent — the repository just looks empty.
418- **One `run_git` owns the invocation.** With a single caller this looks premature; it
419 is a private function rather than a public abstraction for that reason. The point is
420 that Milestone 4's `http-backend` spawn cannot quietly disagree about isolation.
421- **`tokio::process` and `tokio::fs`, never the `std` equivalents.** `init_bare` is not
422 hot — ~13ms, once per repository — but `remove_dir_all` on a repo with real history
423 walks every loose object and would stall a runtime worker. The performance that
424 matters is Milestone 4's per-request spawn, not this.
425- **`tempfile` for test fixtures, not `target/`.** Parallel-safe by construction and
426 self-cleaning on panic. Debris under `target/` would be actively harmful here, since
427 `init_bare` refuses a path that already exists.
428- **Membership is resolved once per listing, not once per row.** Obvious in hindsight;
429 the shape that invites the mistake is filtering inside a loop that can `await`.
430- **One empty state serves "no repositories" and "none you may see".** A distinct
431 message for the second — or any count — leaks that private repositories exist and how
432 many. Tested, because it is the kind of thing a later "helpful" tweak would undo.
433- **`redirect()` is a 307, and 307 preserves the method.** Post/redirect/get needs a
434 303, or the browser re-POSTs the form to its redirect target. Milestone 2's settings
435 form shipped with this and nothing caught it — every test passed, because the tests
436 are on the use case and the bug is in the reply. Found by following the redirect with
437 curl. The fix is a `StatusCode::SEE_OTHER` plus a `Location` pair inside `view!`,
438 wrapped as `web::context::location`, because `see_other()` is a response type and
439 `#[page]` must return a view for the layout to wrap the failure re-render.
440 `RedirectError::new` is private, so a 303 cannot be built as an error, and the
441 error-to-response path only downcasts topcoat's own error types — a custom one
442 becomes a 500.
443- **`#[page]` returns a view; `#[route]` returns a response.** That is the whole reason
444 the redirect is spelled awkwardly: a form handler needs both a redirect and a
445 full-page re-render, and only the view path gets the layout.
446- **Boolean HTML attributes take an explicit value in `view!`** — `required=(true)`, not
447 bare `required`, which fails to parse. `false` omits the attribute entirely, so
448 `selected=(bool)` on an `<option>` is correct rather than rendering `selected="false"`.
449- **`topcoat ui add select` needs the `icon-iconify` feature and a staged icon set.**
450 The chevron comes from `feather`, staged in `build.rs`. No new crates, but the build
451 fails with a clear message until the set is staged.
452- **`is_org_owner` moved to `application/authz.rs`** on its second caller. Owner-ness
453 gates the profile edit, repo creation, and later PATs and push; two copies of an
454 authorization predicate drift, and the direction they drift is open.
455- **The compensating transaction is safe to do by path.** `remove` after a failed save
456 can only ever delete what `init_bare` just created, because the loser of a concurrent
457 create never gets past `init_bare`. Non-obvious enough that it is commented in the
458 code as well as here.
459- **Compensation is best-effort.** If the removal also fails, the caller still gets the
460 error that started it — an orphaned directory is the documented failure mode, and
461 replacing the real error with the cleanup's error would hide the cause.
462- **`InMemoryGitStorage` enforces `AlreadyExists` too.** A permissive fake would let
463 `create_repo` pass while the real adapter refused. The fake mirroring the rule is the
464 point of having two implementations.
465- **`/api` resolves the handle without loading a profile.** `handle_param` split out
466 of `profile_for` so the repo listing route 404s on `list_repos`' own `None`. Routing
467 it through the profile would have made that `None` unreachable and left the page and
468 `/api` disagreeing about what an empty portfolio means — the exact duplication
469 `architecture.md` says to watch for.
470- **The `/api` listing is a bare array, not an envelope.** Matches `/api/users/{handle}`
471 returning a bare object. Pagination later means a wrapper and a breaking change; taken
472 knowingly, since personal-first means a handful of repositories and there are no
473 consumers yet.
474- **`Repository::description` stays.** Added unrequested and flagged; kept on review
475 because this milestone's own "Done when" puts repositories on the profile, which
476 makes it a consumer inside the milestone rather than speculation. Worth noting the
477 window that closed: the repositories migration had not yet been applied to the dev
478 database, so removing the column would have been a free in-place edit rather than a
479 second migration.
480
481### Milestone 4a — Clone over HTTP · done
482
483`git clone` works against a public repository, for anyone, with no credentials.
484`GitProtocolServer` (CGI-shaped) with `GitHttpBackend` behind it, the `serve_git` use
485case, and three routes under `/{handle}/repos/{name}.git/`. Bodies stream both
486directions.
487
488**Verified against a real client**, not only by unit test: an anonymous `git clone` of a
489201-ref repository returns 201 commits and 203 refs with `HEAD` matching the origin, on
490protocol v2 and on v0; a private repository answers 404 to an anonymous clone but 200 to
491its owner's browser session; `git push` is refused with 403; and unknown repo, unknown
492handle, missing `service`, an unknown service, a missing `.git` suffix, and a
493dumb-protocol object path all answer 404 while the repository page still answers 200.
494
495`git http-backend`'s contract, probed against git 2.50.1 by driving the CGI from a
496throwaway server and cloning through it. Everything below is measured, not read.
497
498#### The contract
499
500- **`HTTP_CONTENT_ENCODING`, not `CONTENT_ENCODING`.** CGI gives only `Content-Type` and
501 `Content-Length` unprefixed names; every other request header is `HTTP_`-prefixed, and
502 `http-backend` looks for the prefixed one. **This is the finding that would have cost a
503 day.** With the wrong name, `http-backend` hands the still-compressed body to
504 `upload-pack`, which dies with `bad line length character` and the client reports
505 `fatal: expected 'packfile'` — nothing names gzip, or the environment, anywhere in the
506 failure. And it only happens once a repository has enough refs for the client to bother
507 compressing: a one-ref test repo passes.
508- **`HTTP_GIT_PROTOCOL`** carries `version=2` through to `upload-pack`. Clones verified
509 on v2 and on `protocol.version=0`, both 201 commits, both gzipped.
510- **`GIT_PROJECT_ROOT` plus `PATH_INFO`**, where `PATH_INFO` is the on-disk path relative
511 to the root. Steid's URL and its storage layout differ — `/{handle}/repos/{name}.git/…`
512 against `{data_dir}/{handle}/{name}.git` — so the adapter rewrites the middle segment
513 out. `GIT_PROJECT_ROOT` is the data directory.
514- **`GIT_HTTP_EXPORT_ALL=1` is required.** Without it every repository answers `Status:
515 404 Not Found` and `Repository not exported`, unless a `git-daemon-export-ok` marker
516 file sits in the bare repo (confirmed: dropping that file in re-enables it).
517- **Headers are CRLF-terminated and end at `\r\n\r\n`.** No bare-LF variant was
518 observed, but the adapter should accept one rather than hang.
519- **`Status:` appears only on failure.** Its absence means 200, and it must be
520 translated, not forwarded as a header.
521- **`http-backend` sets its own `Content-Type` and cache headers** — `Expires: Fri, 01
522 Jan 1980`, `Pragma: no-cache`, `Cache-Control: no-cache, max-age=0, must-revalidate`.
523 Steid forwards them rather than inventing its own.
524
525#### Decisions worth remembering
526
527- **`GIT_HTTP_EXPORT_ALL`, never `git-daemon-export-ok`.** The marker file is git's own
528 visibility mechanism and it looks tempting, but visibility lives in the `repositories`
529 table and the use case is what enforces it. A marker file would be a second source of
530 truth for the same question, free to drift from the first, and the drift direction is
531 "private repository still clonable". Steid decides; git is told to stop asking.
532- **`receive-pack` is refused by default** — `Status: 403 Forbidden`, `Service not
533 enabled: 'receive-pack'`, without any configuration. Convenient for 4a, but the routes
534 still refuse writes explicitly rather than leaning on it: a default that helpfully
535 changes is not an authorization decision.
536- **A non-zero exit can arrive after the headers are already out.** The gzip failure
537 exited 1 having emitted a complete, successful-looking header block. So the exit code
538 cannot gate the response — by the time it is known, the status is sent. It belongs in
539 the log.
540- **A missing repository is `Status: 404` with exit 0.** Failure is reported in the
541 CGI stream, not the exit code, and the two disagree in both directions.
542- **The router is the allowlist.** Only `info/refs`, `git-upload-pack` and
543 `git-receive-pack` are routed. Handed any other path, `http-backend` serves
544 dumb-protocol object files straight off disk — a read of a repository nothing
545 authorized. Verified: `/…​.git/objects/info/packs` answers 404.
546- **The endpoint is named by the route, not parsed from the path.** Three routes, three
547 literal `GitEndpoint` values, and `serve_git` rebuilds `path_info` from the validated
548 handle and name. The string that decides authorization and the string handed to git
549 are therefore the same string.
550- **Existence is settled before permission.** A push to a repository the actor cannot
551 see answers 404, not 403 — a 403 would confirm a private repository by that name
552 exists. Costs nothing to get right at the start and is invisible to test later.
553- **`BufReader` is what makes the header/body split safe.** The reader keeps whatever it
554 read past the blank line, so handing the reader itself back as the response body
555 carries the already-buffered first bytes of the pack with it. Parsing headers into a
556 separate buffer and then streaming the rest would silently drop them.
557- **The child's exit code cannot gate the response.** A protocol failure exits non-zero
558 *after* a complete, successful-looking header block has been written. By the time the
559 status is known it has been sent, so the exit code goes to the log and nowhere else.
560- **Stderr must be drained, not merely piped.** An unread pipe fills and blocks the
561 backend mid-transfer. It is read in the same task that reaps the child.
562- **`body_limit` does not exist** in `topcoat-router` 0.5.0 — the warning carried from
563 [0001]decisions/0001-git-over-http-not-ssh.md is stale. Bodies are read by the
564 handler with a caller-chosen limit via `to_bytes`, and the git routes take `Body`
565 unbuffered so no limit applies at all.
566- **`impl<B> IntoResponse for http::Response<B>`** means a handler can return its own
567 `http_body::Body` and Topcoat re-bodies it. That is what lets the pack stream without
568 a framework-specific body type.
569
570### Milestone 4b — Push and tokens · done
571
572`git push` works over HTTP for the owner, and a private repository is clonable by
573someone holding a token for it. `PersonalAccessToken` with both storage adapters,
574`issue_token` / `list_tokens` / `revoke_token` / `authenticate_token`, HTTP Basic on the
575git routes, and token management at `/{handle}/settings/tokens`. Decisions recorded in
576[0007]decisions/0007-tokens-over-http-basic.md.
577
578**Verified end to end**, issuing the token through the UI rather than seeding one:
579push of 201 refs to a public repo and to a private one; clone of the private repo
580returning 201 commits; anonymous clone of the public repo still open with no prompt;
581401 with `WWW-Authenticate: Basic` for a private repo, a **nonexistent** repo, an
582unknown handle and a push advertisement alike; a wrong token challenged rather than
583accepted; and after revoking, both clone and push answer 401 while the public repo stays
584open. The token is shown once and never again on reload, the revoke button disappears
585from the list, and the page is 403 for anyone else.
586
587#### Decisions worth remembering
588
589- **`http-backend` refuses `receive-pack` by default, and Steid authorizing the push is
590 not enough.** The symptom is a 403 that looks like Steid's own refusal but is git's:
591 `Service not enabled: 'receive-pack'`. It needs `-c http.receivepack=true` **before**
592 the subcommand. That flag is set from a `GitRequest` field the use case turns on only
593 after the authorization check passes, so git remains a second refusal behind Steid's
594 rather than being switched on wholesale — if the rules are ever wrong, git still says
595 no.
596- **The uniform 401 is what makes authenticated cloning possible at all.** A git client
597 offers a credential only after a 401, so the 4a behaviour of answering 404 for a
598 private repository made an authenticated private clone unreachable. Extending the 401
599 to repositories that do not exist is what keeps it from leaking which private names
600 are real.
601- **A bad credential falls through to anonymous rather than failing.** The caller then
602 gets the same challenge as someone who presented nothing and can try again, which is
603 also how a stale session cookie behaves.
604- **Basic accepts the token in the password field, or in the username with no password.**
605 Git puts it in the password; people paste it into the username. The alternative is an
606 authentication failure with nothing to explain it.
607- **Issuing a token deliberately does not redirect**, unlike every other form here. The
608 secret exists only in that response, and surviving a redirect would mean putting a live
609 credential in a URL — browser history, logs, referrers. Reloading issues a second
610 token, which is harmless and visible in the list.
611- **Revoking someone else's token is `NotFound`, not `Forbidden`.** That a token id
612 exists but belongs to another user is not a fact worth confirming.
613- **Tokens do not expire.** A credential pasted into a machine and forgotten is worth
614 less if it stops working silently; revocation is the control that matters.
615- **`in_memory.rs` keeps `mod tests` in the middle of the file**, like `sqlite.rs`.
616 Appending an implementation to the end lands it inside a later impl block.
617
618#### Measured, for Milestone 5
619
620Taken at the end of 4b, on a 201-commit repository, 50 runs averaged per command:
621
622| Command | Per call |
623|---|---|
624| `git rev-parse HEAD` | 11.2 ms |
625| `git ls-tree -l HEAD` | 11.7 ms |
626| `git cat-file -p HEAD:` | 11.6 ms |
627| `git log -20 --format=…` | 11.8 ms |
628| `git for-each-ref` | 14.4 ms |
629
630**The cost is starting git, not the query** — every command lands in the same band
631regardless of the work it does, matching the ~13ms `git init --bare` from Milestone 3.
632A three-call page is therefore ~35ms of pure overhead, and a per-file last-commit column
633at one call per entry would be ~230ms for twenty files. This is the input
634[0006]decisions/0006-git-binary-behind-narrow-ports.md asked for before reconsidering
635`gix` on the read path.
636
637### Milestone 5 — Repo browsing · done
638
639A repository is readable on the web: the file tree at a revision, a file's contents with
640line numbers, and the commit log. `ObjectId` / `RefName` / `RepoPath` / `EntryKind` /
641`TreeEntry` / `CommitSummary` in the domain, a `GitQuery` port with `DiskGitQuery` and an
642in-memory fake behind it, `browse_repo` and `repo_log` read models, and pages at
643`/{handle}/repos/{name}`, `/tree/{rev}`, `/tree/{rev}/-/{path}`, `/log` and `/log/{rev}`.
644The read-path decision and its upgrade ladder are in
645[0006]decisions/0006-git-binary-behind-narrow-ports.md#amendment--20260829-the-milestone-5-read-path.
646
647**Verified against Steid's own repository, hosted on Steid.** A freshly created repo
648shows push instructions; after pushing 57 commits the page lists the tree; directories
649descend and breadcrumb back; `src/domain/session.rs` renders with line numbers and
650correct HTML escaping; the log shows 50 commits with author and relative time. Unknown
651revision, unknown path, `../etc/passwd`, unknown repo and unknown handle all 404, clone
652still works, and a private repository answers 404 to an anonymous visitor on **every**
653browse route while its owner sees it.
654
655#### Decisions worth remembering
656
657- **`cat-file --batch-check` with the spec on stdin is the lookup primitive.** It exits
658 **0** and prints `<spec> missing` for anything unresolvable, which is what makes "not
659 found" a *value read off stdout* rather than an exit code to interpret. The rule the
660 adapter follows: **a non-zero exit is always an error; absence is a marker in the
661 output** (`missing`, `ambiguous`, `dangling`, `notdir`). The obvious alternatives are
662 worse — `rev-parse --verify --quiet` returns 1 for an unknown ref but 128 for a missing
663 repository, and `ls-tree` pointed at a blob is a `fatal:` for what is, to a visitor, a
664 404. Passing the spec on **stdin** also means no revision or path can ever be read as a
665 flag, whatever validation upstream does or stops doing.
666- **`git log` in a repository with no commits is a fatal error, not empty output**, hence
667 resolving the revision first. An extra fork, in exchange for not reading meaning out of
668 a localised stderr string.
669- **`%s` is git's *subject*, not the first line** — with no blank line in the message it
670 joins the whole first paragraph with spaces. The adapter takes `.lines().next()` rather
671 than trusting that.
672- **Negative `%ct` exists** in imported histories and would panic `UNIX_EPOCH + Duration`.
673- **A symlink is indistinguishable from a file in the object store** — both are blobs — so
674 `read_blob` returns a symlink's target path as its content. Deliberate; making it
675 `Ok(None)` would cost an extra `ls-tree` of the parent.
676- **The empty repository is a first-class state, not an error.** Steid creates
677 repositories empty and Milestone 4 made it easy to have one never pushed to, so
678 `default_branch` returning `None` means "no commits" and the page offers the three
679 commands to push rather than a broken listing.
680- **`%2F` in a revision segment survives routing.** Topcoat matches on the raw path and
681 percent-decodes after, so a slashed branch works as a single segment — which is what
682 makes the `/-/` separator sufficient without a ref lookup.
683- **Three agents worked in parallel on disjoint files**, with the port, the fake and a
684 non-panicking stub adapter written first so neither branch could break the other's
685 build. The stub answering "nothing there" rather than `todo!()` is what let the pages
686 be developed and run before the adapter existed.
687
688### Milestone 5b — Deployable by anyone · in progress
689
690Distributed as a binary plus its `assets/` directory, installed by one command, behind
691Caddy for automatic HTTPS. `release.sh`, `install.sh`, `deploy/`, a `README.md`, and the
692operability the service needs: `/healthz`, `STEID_SETUP_TOKEN`, and rate limiting.
693
694#### Topcoat findings, both load-bearing
695
696- **`topcoat::start()` already handles SIGTERM.** `serve()` calls `serve_until(…,
697 shutdown_signal())`, and that selects on Ctrl+C *and* SIGTERM on Unix: it stops
698 accepting, drops the listener so a replacement process can bind the port, and drains
699 in-flight requests up to `shutdown_timeout`. So systemd stop/restart does not cut a
700 clone mid-pack, and **no wiring was needed** — the work was finding this out rather
701 than building it.
702- **The peer socket address is not reachable from a handler.** `internal_serve` discards
703 it at accept time (`let (stream, _remote) = accepted?;`) and never puts it on the
704 request extensions; the context exposes only parts, method, uri, headers and
705 extensions. **Any IP-based decision in Steid is therefore header-based by necessity**,
706 not by choice, and closing that would take an upstream change.
707
708#### Decisions worth remembering
709
710- **The rate limiter keys on the *rightmost* `X-Forwarded-For` entry.** A proxy
711 *appends* the address it accepted from, so the last entry is the one the nearest proxy
712 wrote and the only one a client cannot forge. The leftmost — what "the real client IP"
713 usually means — is exactly the attacker-controlled one. Two proxy hops collapse clients
714 onto the inner proxy's address, which is stricter, so being wrong that way is safe.
715- **A global cap backs the per-key one**, because without a peer address a forged key
716 cannot be disproved. It turns key forgery from a total bypass into a modest speed-up.
717 The cost is that a flood can lock the login form for a minute — a recoverable denial
718 against an unrecoverable guessed password.
719- **The limiter's map is bounded.** An unbounded map keyed by attacker-controlled values
720 is itself the denial of service; at the cap it sweeps expired entries and otherwise
721 falls through to the global window, which is stricter rather than permissive.
722- **glibc on bullseye, not static musl.** musl failed on `ring` (Debian's `musl-gcc`
723 rejects `-m64`), but the decisive argument is that **musl buys a dependency-free binary
724 and Steid hard-requires `git` on PATH** — the portability is unusable. Bullseye pins the
725 glibc floor at 2.31, covering Debian 11+ and Ubuntu 20.04+; bookworm would need 2.36
726 and silently exclude Ubuntu 22.04.
727- **The runtime binary links a TLS stack it never uses.** `ring` ← `rustls` ← `ureq` ←
728 Topcoat's `icon-iconify`/`tailwind`, whose `ureq` downloads the Tailwind CLI *at build
729 time*. Those features are on the normal dependency as well as the build one, so the
730 crypto ships too. Moving them would shrink the binary and drop an unused dependency
731 from the attack surface. Not attempted; it is also what made the musl build fail where
732 it did.
733- **`STEID_SETUP_TOKEN` does not undermine [0002]decisions/0002-first-run-claim-not-config-bootstrap.md.**
734 What that ADR refused to put in configuration was the owner's *password* — long-lived,
735 goes stale, ends up in a repository. This is the one-time claim secret the operator was
736 already copying out of a log line. It is validated for strength, never printed, and
737 ignored entirely once claimed.
738
739### Gap-filling while 5b was blocked on DNS · done
740
741Built while the domain transfer was in flight, so none of it belongs to a milestone.
742Three things: repository settings, browse usability, and README rendering — the last of
743which is Milestone 6's markdown pipeline arriving early because a repository page needed
744it.
745
746#### Repository settings — a hole, not a feature
747
748Repositories were **create-only**. No edit, no delete, and therefore **no way to
749un-publish something published by accident**. Now: description and visibility are
750editable, and a repository can be deleted behind a type-the-name confirmation.
751
752- **Delete writes the row first, then the directory best-effort.** An orphaned directory
753 only blocks reusing that name and is already `create_repo`'s documented failure mode;
754 an orphaned row is a repository that lists on the profile and 404s when clicked. The
755 visible failure is the worse one, so the ordering avoids it.
756- **Two different refusals, deliberately.** A repository the actor may not *see* is
757 `NotFound` (a 403 would confirm a private repo by that name exists); one they can see
758 but do not own is `Forbidden`, matching `create_repo`, because the resource is public
759 anyway. The page collapses both to 404.
760- **Renaming is still impossible, now with a comment saying why.** The bare repo lives at
761 `{data_dir}/{handle}/{name}.git`, so a rename is a directory move that breaks every
762 existing clone — and doing the row half only breaks them silently.
763
764#### Markdown — raw HTML is structurally impossible, not merely disabled
765
766- **`pulldown-cmark` does not sanitise URLs.** Its `escape_href` only percent-escapes, so
767 `javascript:` would have survived into a rendered README. The renderer uses a scheme
768 **allowlist** (`http`, `https`, `mailto`, `ftp`, `ftps`, `tel`) and strips ASCII control
769 characters *before* the check as well as on output, because browsers strip them too and
770 `java&#9;script:` is otherwise a live bypass.
771- **Adding the crate with `default-features = false` turned off its `html` feature**, so
772 `push_html` does not exist in this build. The renderer therefore walks the event stream
773 and writes every tag itself. Forced rather than chosen, and better: the emittable tag
774 set is exactly what the writer spells out, so raw HTML cannot pass through by
775 construction. `Event::Html` is written as *text*, so `<script>` is visible and inert
776 rather than silently vanishing.
777- **Escaping goes through `topcoat::view::HtmlContext`**, the same escaper `view!` uses —
778 not a hand-rolled one.
779- **Smart punctuation is off**: it rewrites `--flag` to an en dash, quietly corrupting CLI
780 flags in README prose.
781- Relative *links* are rewritten into tree URLs; relative *images* are deliberately left
782 alone, because a tree URL serves a page and rewriting would swap a 404 for a broken
783 image. Pointing them at `/raw/` is the obvious follow-up now that route exists.
784
785#### Browse — the switcher and raw files
786
787- **`for-each-ref` asks only for `%(refname)`.** `%(objecttype)` is `commit` for both a
788 branch and a lightweight tag, so the *namespace* is the only thing that answers
789 branch-versus-tag.
790- **Raw files are served as `application/octet-stream`, always** — never the file's own
791 type and never guessed from an extension — with `nosniff`, `Content-Disposition:
792 attachment` and `default-src 'none'; sandbox`. A repository-supplied `.html` or `.svg`
793 served as its real type on this origin is stored XSS against the viewer's session.
794 `text/plain` was rejected because browsers render it and have been talked into sniffing
795 it as HTML. The filename is repository content arriving in a header, so it is reduced to
796 `[A-Za-z0-9._-]` against header injection.
797- **The switcher costs one more fork (~13ms) on tree and log pages**, measured
798 interleaved against `ls-tree` to cancel out load — same band, confirming again that the
799 fork is the cost. It is not called on the repository page or an empty repository.
800
801#### Verified
802
803Against a running instance with a deliberately hostile README: **zero real `<script>` or
804`<img>` tags in the output**, the markup present once as escaped inert text, the
805`javascript:` link stripped of its `href` while `https://example.com` survived, the table
806rendered, raw bytes SHA-256 identical with the headers above, the switcher listing a
807branch and a tag, and the Settings link visible to the owner and absent for anonymous.
808
809### The profile page, rebuilt · done
810
811Flat navigation, per [ui.md]ui.md#the-profile-page. Tabs instead of stacked sections,
812one lead item distinguished by weight and space rather than size, hairlines instead of
813boxes, and a `/{handle}/repos` index for the tab to point at.
814
815#### Decisions worth remembering
816
817- **Existing rows were stamped with the migration time, not left at 0.** A repository
818 pushed to for months would otherwise read "updated 56 years ago" on the very page the
819 column exists to order. Wrong by a bounded amount and self-correcting on the first
820 push, against wrong forever and looking broken.
821- **The single-pin invariant lives in the use case, not in a constraint.** The rule is
822 "pinning this unpins that", and a unique index can only *refuse*, never unpin. The two
823 writes are not one transaction; a crash between them leaves nothing pinned, which is
824 the harmless direction.
825- **`updated_at` is touched on the authorized write path**, before the protocol is
826 reached — so a clone never moves it and neither does a refused push. It records that a
827 push was *authorized*, not that it succeeded; waiting for the subprocess would be a
828 much larger change for a small gain. A failed touch is logged and does not fail the
829 push.
830- **The lead is picked out of the listing**, not fetched separately, so the lead and the
831 list cannot disagree about which repository is pinned.
832- **Ordering changed from name to recency**, and two existing tests had been passing by
833 accident: everything created inside one second tied and fell back to the alphabet.
834
835#### Two Topcoat traps, both silent
836
837- **`let profile = …` in a module with `#[page] async fn profile` is a unit-struct
838 pattern, not a binding.** The page's name is a unit struct in module scope. The error
839 points at neither the page nor the shadowing.
840- **Forgetting `topcoat asset bundle` after `cargo build` produces a broken-looking
841 page, not an error.** New utility classes are simply absent, so gaps collapse and type
842 falls back to browser defaults — it reads as a design mistake. Cost one confused
843 screenshot.
844
845### Security review before going public · done
846
847Attempted with three blind reviewer agents; all three died to the machine sleeping, so
848the review was done directly instead. **Findings were verified by attacking a running
849instance, not by reading comments** — the codebase argues confidently for its own
850safety and those arguments are exactly what needed testing.
851
852#### What held, demonstrated rather than assumed
853
854| Probe | Result |
855|---|---|
856| Private repo: page, tree, log, settings, raw, `/api` | 404 on every surface; `/api` does not leak the name |
857| `rev=--upload-pack=touch /tmp/pwned` and five other injections | 404, no execution |
858| Four path-traversal spellings incl. `%2e%2e` and `....//` | 404 |
859| Login brute force | 10 attempts then 429 |
860| Error bodies | bare "not found", nothing internal |
861| Raw `.html` and `.svg` from a repo | `octet-stream` + `nosniff` + `attachment` + sandbox CSP |
862| Filename `ev"il; drop.txt` in a header | sanitised to `ev_il__drop.txt`, no header injection |
863| `<script>` in a viewed file | escaped, zero live tags |
864
865**The production cookie is `__Host-session; HttpOnly; Secure; SameSite=Lax; Path=/`** —
866the strictest cookie form available, and it forbids a `Domain` attribute so a
867compromised subdomain cannot inject one.
868
869**A near-miss worth recording:** the first check appeared to show production serving
870`steid-dev-session` with no `Secure`. It was a testing error — **`dotenvy` reads `.env`
871from the working directory**, and running the binary from the repo root picked up the
872gitignored dev `.env`. Verify from a neutral directory, and note the same trap applies
873to the deployment: the systemd unit's `WorkingDirectory=/opt/steid` means a stray `.env`
874there would silently override the environment file.
875
876#### The one real finding: no security headers on HTML
877
878Fixed with a layer, deliberately a layer rather than a per-handler concern — a page
879added without them would simply not have them and nothing would fail.
880
881- **Steid renders no JavaScript at all**, not a script tag on any page, so
882 `default-src 'none'` is a policy the product can genuinely keep. That is far stricter
883 than a typical CSP and worth defending: if a feature ever needs script, weakening it
884 should be a deliberate decision.
885- `'unsafe-inline'` is granted for **styles only**, and only because Topcoat's icon
886 macro emits `style="vertical-align: -0.125em"`. A framework constraint, not a choice.
887- **`Referrer-Policy: no-referrer`**, not the usual `strict-origin-when-cross-origin`: a
888 private repository's URL contains its name, and a README may link anywhere, so a
889 referrer would hand that name to whatever the visitor clicked.
890- Headers are set with `entry().or_insert()`, never `insert()` — the raw endpoint's own
891 stricter `default-src 'none'; sandbox` must not be relaxed by a blanket overwrite.
892 Verified that it survives.
893
894#### Not covered, and why
895
896- **The member-but-not-owner path could not be demonstrated.** There is no registration,
897 so a second account cannot exist until Milestone 7. It is covered by use-case tests and
898 nothing else — re-verify for real the moment a second account is possible.
899- **No automated test asserts the headers.** There is no HTTP-level test harness in this
900 project, so a regression here would be silent. That is a gap, not a decision.
901- No dependency audit (`cargo audit` was not run), and no review of the deployment
902 scripts beyond the earlier container dry-run.
903
904### Deployed · jpgill.dev, 2026-09-04
905
906Steid runs on the public internet at **https://jpgill.dev**, on AWS Lightsail (Debian 13,
907x86_64, 1 GB), behind Caddy with a Let's Encrypt certificate, hosting its own source.
908Installed with `install.sh --tarball`, since the instance that will serve the releases is
909the one being installed.
910
911#### What the first real deployment taught
912
913- **A domain transfer moves the registrar, not the nameservers.** The transfer to Amazon
914 Registrar completed, the Route 53 zone held the right records, and every public resolver
915 returned nothing — because the `.dev` registry still delegated to the old provider's
916 nameservers. Diagnosed with `dig +trace`, which shows the delegation the world actually
917 follows rather than the zone you are looking at.
918- **The domain was `jpgill.dev`, not `jpgilldev.com`.** Inferred from an email address and
919 never confirmed, and by then it was baked into `install.sh`'s release URL and the
920 systemd unit. Ask what the domain is.
921- **`.dev` is HSTS-preloaded.** Browsers refuse plain HTTP with no click-through, so the
922 certificate is not optional — until Caddy has one the site is simply unreachable.
923- **The uniform 401 cost real time.** Pushing to a mistyped handle answered
924 `Authentication failed` rather than "no such repository", because
925 [0007]decisions/0007-tokens-over-http-basic.md deliberately makes an absent repository
926 indistinguishable from a private one. That trade was recorded as costing "a prompt on a
927 typo"; in practice it cost ten minutes and a confident wrong diagnosis, with someone
928 watching who knew the design. A stranger has nobody to ask.
929- **An upgrade silently discarded the operator's Caddyfile.** `install.sh` kept
930 `steid.env` across a re-run but rewrote the Caddyfile unconditionally, so a hand-added
931 `www` redirect vanished on the next upgrade and took the hostname with it. Now written
932 on first install only, with `--force-caddyfile` and `--www`. Found by testing the
933 upgrade path rather than waiting for it to happen.
934- **The upgrade path works and is verified**: claim, database, repositories, `steid.env`
935 and Caddyfile all survive `install.sh` re-run against a newer tarball.
936
937#### Renaming a handle, done by hand
938
939`current.md` recorded a rename as "a directory move, not a row update". That was exercised
940for real, renaming `jpgilldev` to `jamesgill` on the live instance: **one `UPDATE orgs SET
941name` and one `mv` of `{data_dir}/{handle}/`**. Everything else — users, repositories,
942tokens, sessions — keys off ids, so nothing else moved, and the account, password and
943access token all survived.
944
945So a rename feature is genuinely two writes. What makes it more than that is the
946consequence: every existing clone URL breaks, and there is no redirect from the old
947handle. That is the part to design, not the mechanics.
948
949### The shell: top bar and per-page widths · done (2026-09-05)
950
951The root layout gained a slim global top bar — wordmark to `/`, and either "Sign in"
952or `@handle` / Settings / Sign out — and stopped imposing a width. Pages now choose
953their own column via two components in `layout.rs`: `narrow` (48rem — profile, forms,
954settings) and `wide` (80rem — tree, blob, log, the repo page). Verified in the
955browser across visitor and owner states, including sign-out.
956
957#### Decisions worth remembering
958
959- **A slim bar plus contextual tabs, deliberately not an app shell.** The reasoning
960 lives in [ui.md]ui.md#the-shell; the short form is that Steid's first audience is
961 an anonymous reader of someone's site, and GitLab-style rail chrome tells that
962 visitor they've landed in an admin tool.
963- **A `#[layout]` may take `cx: &Cx`** alongside `slot` — both recognized by name, no
964 other parameters. Documented in the vendored `topcoat-router-macro` docs, not
965 obvious from the README example.
966- **The layout imposes no width; pages wrap themselves.** Same philosophy as request
967 helpers being functions: a page that forgets a container renders full-bleed, which
968 is immediately visible, rather than silently inheriting a wrong one.
969- **The top bar costs an identity lookup on every page render** (session hash plus a
970 user row). Fine over local SQLite; worth remembering if page queries are ever
971 counted.
972
973### The repository landing page · done (2026-09-05)
974
975`/{handle}/repos/{name}` became two columns — the file list and README on the left, an
976About sidebar on the right — and every repository page (tree, blob, log) picked up the
977same header and `Code` / `Commits` tab strip. New: a toolbar row carrying the revision
978switcher and branch/tag counts, a latest-commit bar, an About block with the
979description and detected licence, a facts list (commits, branches, tags, latest tag,
980pushed), and the clone URL moved into the sidebar.
981
982The layout and the map of where the next features slot in are in
983[ui.md]ui.md#the-repository-page. What is here is what the next session should not
984have to rediscover.
985
986**Verified** with the app running from a worktree on port 3100: this repository's own
987history pushed into it with two annotated tags and three branches, plus an empty
988repository and one with no README and no licence. Screenshots taken headless at 1280px
989and 800px, in both colour schemes, of the landing page, the empty and sparse states, a
990tree subpath, a blob and the log; the owner's view (with the Settings button) checked
991signed in. `cargo test` 467 passing, clippy clean.
992
993#### Decisions worth remembering
994
995- **The subprocess count was measured, not estimated.** A `git` shim on `PATH` logging
996 every invocation: **15 processes** for a repository with a README and a licence, **10**
997 without them, **1** for an empty one — up from 7. Worth repeating the trick; it took
998 two minutes and contradicted a careful hand-count.
999- **The description has exactly one home, and it is the sidebar.** Putting it in the
1000 header too makes the header tallest on the repositories with the most to say, which
1001 pushes the code below the fold on exactly the pages that deserve it least.
1002- **`repo_summary` takes the revision and the root listing the page already read.** A
1003 self-contained use case would have spent two more processes re-reading what the caller
1004 had in hand. The five calls it does make run under one `tokio::try_join!`.
1005- **`organise_refs` was split out of `list_refs`** so the landing page gets the counts
1006 and the switcher's list from one `for-each-ref`. Two places deciding ref order is two
1007 places to change it.
1008- **A `#[component]`'s name is a unit struct in module scope, and the copied-in
1009 components are in that scope too.** A parameter named `label` inside `repo.rs` does
1010 not bind — it parses as the `label` component's unit struct, and the error says
1011 "expected `str`, found `label`" without naming the component. The fix was renaming the
1012 parameter to `term`. This is the same trap `CLAUDE.md` records for pages; registry
1013 components widen it to every file that imports one.
1014- **`bg-muted` is not a token.** Three `<pre>` blocks have been rendering with no
1015 background since they were written, silently — the exact failure `ui.md` describes for
1016 Tailwind classes the build never ships. `bg-surface` is the token. Two were fixed here;
1017 `token.rs` still has one.
1018- **The clone URL wraps rather than scrolls.** In an 18rem column an `overflow-x-auto`
1019 URL looks like a truncated one, and the part hidden is the repository's own name.
1020- **Light mode was checked by flipping the layout's `class="dark"` and rebuilding**,
1021 because there is no toggle. Nothing was wrong on these pages. That is the cheapest way
1022 to check it until a toggle exists, and it is worth doing before each UI step rather
1023 than after several.
1024
1025---
1026
1027## Reference: what attempt #2 proved
1028
1029Not this repo's progress. This is a catalogue of what was built and **verified working**
1030in `steid-backup-2026-07-31`, so the rebuild can crib rather than rediscover.
1031
1032Final state: single crate, ~4,200 LOC, 60 passing tests, five milestones.
1033
1034### Identity
1035
1036Domain model (User, Organization, Membership, Actor, Role), `Email` and
1037`PasswordHash` value objects, typed IDs, `DomainError`, four repository ports with
1038in-memory and SQLite implementations each. `RegistrationPolicy` (Personal / Invite /
1039Open) driving which routes exist. Argon2 hashing behind a `PasswordHasher` port with a
1040stub for tests. Use cases: `bootstrap_owner`, `register_user`, `login`, `create_invite`.
1041Signed-cookie sessions via an `AuthUser` extractor.
1042
1043**Gotcha:** organizations must be saved before users — the FK runs that direction.
1044Both `bootstrap_owner` and `register_user` had to be fixed for this.
1045
1046### Repo model
1047
1048`Repository` entity, `RepoId`, `Visibility` (Public/Private), `RepoRepository` port,
1049migration `006_create_repositories.sql`. `create_repo` use case validates the name,
1050rejects duplicates, and initialises the bare repo on disk in the same call. Bare repos
1051live at `{data_dir}/{org}/{repo}.git`, `data_dir` defaulting to `./data`. Repos are
1052created empty, no initial commit, like GitHub.
1053
1054### Git over SSH
1055
1056`GitStorage` port (`init_bare`, `repo_path`) with `DiskGitStorage` shelling out to
1057`git init --bare`. `GitProtocolServer` port (`upload_pack`, `receive_pack`) with
1058`GitBinary` spawning `git upload-pack` / `git receive-pack` via
1059`tokio::process::Command` and pumping stdio with `tokio::io::copy`.
1060
1061`serve_clone` and `serve_push` use cases enforce visibility and actor checks **before
1062any protocol byte flows** — that ordering is the whole point of putting them in the
1063application layer.
1064
1065#### SSH channel bridging
1066
1067The fiddly part, and worth re-reading if SSH ever returns as a transport
1068(milestone 8+ — [0001]decisions/0001-git-over-http-not-ssh.md chose HTTP):
1069
1070- Store `Channel<Msg>` per `ChannelId` in the handler's map on `channel_open_session`
1071- On `exec_request`, take the channel, split it with `into_stream()` +
1072 `tokio::io::split`
1073- Take stderr via `make_writer_ext(Some(1))` **before** `into_stream()` — that call
1074 consumes the channel, so the order is not optional
1075- No `data()` or `channel_eof()` handlers needed once the streams are split
1076
1077An earlier iteration used mpsc channels, custom `ChannelReader`/`ChannelWriter`, and a
1078`spawn_blocking` thread. All of it was deleted and the result was simpler.
1079
1080### SSH key auth and authorization
1081
1082`SshKey { id, user_id, name, fingerprint, openssh }` + port, migration
1083`007_create_ssh_keys.sql` (`fingerprint` UNIQUE). Fingerprints are SHA256 via
1084`russh::keys::ssh_key::PublicKey::fingerprint(HashAlg::Sha256)`, stored as `SHA256:…`.
1085`add_ssh_key` parses the openssh blob, dedupes on fingerprint, and re-encodes to a
1086canonical form before storing.
1087
1088`auth_none` rejects. `auth_publickey` fingerprints the offered key, looks it up, and
1089on a match stores `user_id` on the handler; `exec_request` builds the real `Actor`
1090from it.
1091
1092Authorization rules as shipped:
1093
1094| Operation | Requirement |
1095|---|---|
1096| Clone, public repo | open |
1097| Clone, private repo | any membership in the repo's org |
1098| Push | `Role::Owner` membership in the repo's org |
1099
1100Web UI at `/{owner}/keys` — owner-only, lists fingerprints, accepts openssh via
1101textarea, revokes per-row.
1102
1103**Verified end-to-end:** clone with an unregistered key → `Permission denied` (exit
1104128); register via web UI → clone and push both succeed; second unregistered key →
1105rejected at auth; revoke via web UI → subsequent clone rejected at auth.
1106
1107### Security notes
1108
1109Attempt #2 ran with a **named, deliberate backdoor** between milestones: SSH accepted
1110any connection and passed a placeholder `Actor` (`UserId("ssh-anonymous")`), leaving
1111push open to anyone who could reach the port. It was recorded with an explicit
1112tightening point (`ssh.rs::exec_request`) and a closing milestone, and it did close.
1113
1114That practice is worth keeping. When this attempt opens a hole to make progress, name
1115it, name the line that closes it, and name the milestone.
1116
1117### Never built
1118
1119Repo browsing (tree/blob/log), HTTP smart protocol, personal access tokens, flash
1120messages, issues, PRs, blogs, pages, project showcases. Milestones 5–8 in
1121[ROADMAP.md]ROADMAP.md are all greenfield.