<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[BrightBot.co.uk]]></title><description><![CDATA[Smart Home Technology and Home Lab adventures]]></description><link>https://brightbot.co.uk/</link><image><url>https://brightbot.co.uk/favicon.png</url><title>BrightBot.co.uk</title><link>https://brightbot.co.uk/</link></image><generator>Ghost 2.9</generator><lastBuildDate>Sun, 22 Nov 2026 05:51:38 GMT</lastBuildDate><atom:link href="https://brightbot.co.uk/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[House-move inventory: Status, going? and a history - Part 11]]></title><description><![CDATA[~8 min read

A box has a status: packing, sealed, in transit, arrived, unpacked. That was in the very first design. What I hadn't predicted was how much a move is also a long series of decisions about things that aren't packed at all. This post is about the two extra fields that grew onto boxes, the history that records them, and a rule about dependent fields that I'd defend in a code review.


Two independent axes

Status is the physical lifecycle: packing → sealed → in_transit → arrived → unpa]]></description><link>https://brightbot.co.uk/status-going-and-history/</link><guid isPermaLink="false">Ghost__Post__6ae5babf1df6faba86556b6c</guid><category><![CDATA[Building Inventory System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sat, 21 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1630783204556-649cc187d778?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fGdvaW5nfGVufDB8fHx8MTc5MzUyNzcyMnww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1630783204556-649cc187d778?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fGdvaW5nfGVufDB8fHx8MTc5MzUyNzcyMnww&ixlib=rb-4.1.0&q=80&w=2000" alt="House-move inventory: Status, going? and a history - Part 11"/><p><em>~8 min read</em></p><p>A box has a status: packing, sealed, in transit, arrived, unpacked. That was in the very first design. What I hadn't predicted was how much a move is also a long series of <em>decisions</em> about things that aren't packed at all. This post is about the two extra fields that grew onto boxes, the history that records them, and a rule about dependent fields that I'd defend in a code review.</p><h2 id="two-independent-axes">Two independent axes</h2><p><strong>Status</strong> is the physical lifecycle: <code>packing</code> → <code>sealed</code> → <code>in_transit</code> → <code>arrived</code> → <code>unpacked</code>. It answers "where is this box?".</p><p><strong>Going?</strong> (<code>decision</code>, Phase 3.27) answers a different question: "is this box coming with us at all?". Its values are <code>definite</code>, <code>maybe</code> and <code>no</code>, defaulting to <code>definite</code>.</p><p>They are deliberately independent. A box can be sealed and fully packed while still <em>maybe</em> - the decision on whether it goes might wait on the size of the lorry. If I'd folded "maybe" into the status list I'd have needed a status for every combination. Two small enums beat one big one.</p><p>The UI gives each a pill: status with its own colours, and Going? as a traffic light - green definite, amber maybe, red no (<code>DecisionPill</code>). The box list shows both as columns and both are filters.</p><h2 id="a-field-that-only-exists-sometimes">A field that only exists sometimes</h2><p>When a box is <strong>not</strong> going, the next question is why. Is it being sold, or thrown away ("tipped")? Phase 3.36 added <code>sub_status</code> - <code>selling</code> or <code>tipping</code>.</p><p>The design question was where to put it. A flat <code>Box.reason</code> field would be meaningful for a "no" box and nonsense otherwise, and nothing would stop you setting it on a box that's definitely coming. The rules I settled on:</p><ul><li><code>sub_status</code> is nullable, and <strong>optional even when the decision is "no"</strong>. A box can sit at <code>no</code> with the reason still unset - the UI calls that "Undecided" - because forcing a choice at the moment you decide not to take something is annoying.</li><li><code>set_box_sub_status</code> <strong>rejects with a 422 unless <code>decision</code> is currently <code>no</code>.</strong></li><li>And in the other direction, <code>set_box_decision</code> <strong>clears <code>sub_status</code> back to null</strong> the instant the decision changes to anything else. In the same write, with no separate event.</li></ul><p>That last point is the one worth stealing. The invariant "a reason exists only while the answer is no" isn't enforced by a check somewhere that might get skipped; it's maintained by the only function that can break it. The history already records the <code>decision_changed</code> event, which explains the clearing, so there's no second entry to confuse things.</p><p>The same rule shows up in cloning. <code>clone_box</code> copies the source box's decision (a clone is "more of the same kind of box", so the call usually still applies) but resets <em>status</em> to <code>packing</code>.</p><h2 id="history-append-only">History, append-only</h2><p>I added the box history early (Phase 3.16) because "who moved the lamp box to the garage, and when?" is a surprisingly common question when two people pack.</p><p><code>box_events</code> is an <strong>append-only table</strong>: nothing is updated or deleted. Each row has the box, a timestamp and a <code>kind</code> - <code>created</code>, <code>cloned</code>, <code>renamed</code>, <code>moved</code>, <code>status_changed</code>, and later <code>decision_changed</code> and <code>sub_status_changed</code> - plus a detail string. The migration that added it back-filled a <code>created</code> entry for every existing box, so old boxes aren't history-less.</p><p>The service logs events as a side effect of the operation: renaming a box writes the rename and the event together. The box page shows a <strong>History</strong> timeline, auto-refreshing when the box changes, with a line per event. The clock injection from <a href="https://ghost.atathome.me/a-core-that-knows-nothing-about-http/">post 2</a> is what makes the ordering testable.</p><p>Adding a new kind later costs two things: a new value, and a line in the timeline renderer. Phases 3.27 and 3.36 each did exactly that.</p><h2 id="rolling-it-up">Rolling it up</h2><p>Once boxes have this much structure, the questions get more interesting, and the answers come from aggregation in the core:</p><ul><li><strong>Move by room</strong> (Phase 3.17): <code>summary_by_room()</code> returns box count, lines, items and value per room, with a totals footer and the fixed-rate note.</li><li><strong>Move by box</strong>: the original whole-move table.</li><li><strong>Missing French</strong> (post 8): a top-level view of what still needs translating.</li></ul><p>Aggregations are the exact thing that tends to creep into the transport layer ("I'll just add these up in the route"), and the architecture rule - no aggregation outside the core - means each of them is a method with a test instead of a loop in a handler.</p><h2 id="sorting-is-just-ui">Sorting is just UI</h2><p>A small coda: the box list got sortable columns on 27 October (<code>BoxList.tsx</code>). It's client-side - a <code>useMemo</code> over the fetched list, with a click-to-toggle direction. There's one rule I like: <strong>empty values always sort last, whichever direction you're sorting</strong>, so clicking "name" doesn't bury your named boxes under a wall of blanks. Not everything needs to touch the core; sorting a list that's already on the page is presentation.</p><p>Next: all of this feeds the filters on the room export - and the last feature I shipped, exporting every room at once.</p><hr><p>Previous: <a href="https://ghost.atathome.me/built-then-deleted-auth/">← Built, then deleted: authentication</a> · Next: <a href="https://ghost.atathome.me/filters-decisions-and-exporting-everything/">Filters, and exporting everything →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: Cash, and an audit trail - Part 18]]></title><description><![CDATA[~7 min read

Everything the app tracks so far lives somewhere with an API, or at least a login: banks through TrueLayer, Hargreaves Lansdown through its website, and loans typed in by hand as manual accounts. The one pot of money it couldn't see was the physical kind - the notes and coins in a wallet or a drawer. Four commits close that gap and then answer a question it raised: when a balance changes, why? This post covers the cash account type (add full cash tracking account type, reduce cash d]]></description><link>https://brightbot.co.uk/cash-and-an-audit-trail/</link><guid isPermaLink="false">Ghost__Post__6ad5db841df6faba86556a3f</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Fri, 20 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1544396821-4dd40b938ad3?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDEwfHxkb2N1bWVudGF0aW9ufGVufDB8fHx8MTc5MjY4MjE4M3ww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1544396821-4dd40b938ad3?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDEwfHxkb2N1bWVudGF0aW9ufGVufDB8fHx8MTc5MjY4MjE4M3ww&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: Cash, and an audit trail - Part 18"/><p><em>~7 min read</em></p><p>Everything the app tracks so far lives somewhere with an API, or at least a login: banks through TrueLayer, Hargreaves Lansdown through its website, and loans typed in by hand as manual accounts. The one pot of money it couldn't see was the physical kind - the notes and coins in a wallet or a drawer. Four commits close that gap and then answer a question it raised: when a balance changes, <em>why</em>? This post covers the cash account type (<code>add full cash tracking account type</code>, <code>reduce cash denominations</code>) and the audit trail that followed (<code>add account audit history</code>, <code>view history from home page</code>).</p><h2 id="a-balance-you-cant-type">A balance you can't type</h2><p>A cash account is a manual account with a flag, <code>is_cash</code>, and one rule: <strong>you never enter its balance</strong>. You tell it which notes and coins went in or out, and the balance is whatever that adds up to. A hand-typed £47.50 that doesn't match the wallet is exactly the drift the feature exists to prevent, so the API simply refuses it - a PATCH with a balance on a cash account is a 400 saying the balance "comes from its notes and coins - add or remove some".</p><p>Like <code>budgets.py</code> and <code>savings.py</code> before it, the logic is a module of pure functions, <code>cash.py</code>, with no database in sight. Amounts are whole pence throughout, so adding up a wallet never meets float rounding; the API converts to pounds only at the edge. The denominations are a small table, largest first, which is also the order the UI lists them in:</p><pre><code class="language-python">DENOMINATIONS = (
    (5000, "£50", "note"),
    (2000, "£20", "note"),
    (1000, "£10", "note"),
    (500, "£5", "note"),
    (200, "£2", "coin"),
    (100, "£1", "coin"),
    (50, "50p", "coin"),
)
</code></pre><p>That's the shorter list. The first version went all the way down to 1p, and the follow-up commit trimmed it to the denominations "worth counting": notes down to £5, coins down to 50p. Nobody tracks their coppers in an app, and a longer list is a longer form to fill in every time.</p><p>The one interesting function is <code>apply_changes</code>. It takes the current counts and a dict of signed changes - positive adds, negative removes - and returns the new counts, raising <code>ValueError</code> for an unknown denomination or for removing more than is held. "A wallet can't hold minus two tenners." It never modifies its input, which is what makes the storage side all-or-nothing: the new counts are fully computed and validated <em>before</em> anything is written, so a request that adds a £10 and removes two £20s from a wallet holding one £20 changes nothing at all. A test pins exactly that.</p><h2 id="storage-counts-in-one-table-the-balance-derived">Storage: counts in one table, the balance derived</h2><p>Counts live in their own table, <code>cash_holdings</code>, keyed <code>(account_id, pence)</code>. The comment on its schema states the invariant: the account's balance "is always derived from these, never entered by hand". <code>apply_cash_changes</code> writes the new counts and then calls the same <code>update_manual_account</code> every other manual balance change goes through, so the daily balance-history snapshot (<a href="https://ghost.atathome.me/periods-charts-and-a-phone-sized-ui/">post 13</a>) and everything that reads <code>list_accounts()</code> pick cash up for free. A cash account shows in the totals, on the Savings page and in the charts exactly like any other money-you-hold account, because as far as they're concerned it is one.</p><p>Two creation paths matter. A new cash account is forced to <code>kind='accounts'</code> (money you hold) with a balance of zero, whatever the request says - a test sends <code>balance: 999, kind: "cards"</code> and checks both are ignored. And an <em>existing</em> manual account can be converted with <code>convert-to-cash</code>: you enter what's actually in the wallet and its total <strong>replaces</strong> the old hand-typed balance. That's the one place a balance is overwritten rather than adjusted, so it's guarded: only accounts you hold money in can be converted (not a loan), an already-cash account can't be converted again, and an empty set of counts is rejected, since "the balance becomes their total" would silently zero the account.</p><p>On the page, a cash row gets a "Notes &amp; coins" button. The dialog lists every denomination with how many are held, an Add/Remove toggle, and a count box per row; when removing, each box's <code>max</code> is what's held. The API's GET returns <em>every</em> denomination with a count of zero for ones never held, so the UI never needs to know the list itself - the same instinct as the categories seeded in <a href="https://ghost.atathome.me/rule-based-categorisation/">post 12</a>.</p><h2 id="the-next-question-why-did-it-change">The next question: why did it change?</h2><p>Cash made an existing gap obvious. The balance-history chart records one point per account per <em>day</em>, which is right for a line on a graph and useless as a record. It can say a wallet went from £43 to £23; it can't say a £20 note was taken out, or when, or whether a figure moved because of a sync or because I edited it.</p><p>So the second piece is an audit trail, in a new table, <code>account_events</code>. It is deliberately separate from <code>account_balance_history</code>: that one upserts a single row per day so the chart stays tidy, this one appends a row per change and never merges. Each row has an account, a timestamp, the old and new balance, and a <code>kind</code> saying why it moved:</p><ul><li><code>created</code> - a manual account was added;</li><li><code>manual</code> - a hand-entered balance was edited;</li><li><code>cash</code> - notes and coins were added or removed, with the signed <code>{pence: count}</code> stored as JSON alongside;</li><li><code>sync</code> - a provider refresh found a different balance.</li></ul><p>A single function, <code>record_account_event</code>, is the only writer, and its one rule is in its docstring: write a row only if the balance <em>actually moved</em> (or it's the account's first sighting, <code>old_balance</code> NULL). That keeps the trail meaningful. Re-syncing an unchanged account every night would otherwise bury the interesting rows under hundreds of identical ones; so would saving a rename, which touches the account but not its balance. Both are tested.</p><h3 id="the-sync-path-needed-care">The sync path needed care</h3><p>The manual paths were easy because the old balance is one query away. Synced accounts were the awkward case, because <code>save_accounts</code> is a full refresh: per bank it <em>deletes</em> the cached rows and re-inserts them (<a href="https://ghost.atathome.me/balances-and-disconnecting-banks/">post 8</a>), so by the time it's looking at the new balance the old one has been deleted. The fix is a single read at the top of the function, before the DELETE, into a <code>{(bank, account_id): balance}</code> dict, and then a comparison per account afterwards. It's three lines, but it's the kind that goes wrong silently if someone later tidies the order. The comment above it says why it must stay where it is.</p><p>Cash events are recorded from <code>apply_cash_changes</code> via two extra keyword arguments on <code>update_manual_account</code> (<code>event_kind</code>, <code>cash_changes</code>), rather than by a second code path, so a change to a cash balance can't be logged without the balance actually changing, or the other way round. Zero-valued entries are dropped before storage, so an event only lists what really moved.</p><h2 id="reading-it-back">Reading it back</h2><p><code>GET /api/accounts/events?bank=…&amp;account_id=…</code> returns the trail newest first. Both identifiers are <strong>query parameters</strong>, not path segments: a bank name can contain anything, and a <code>/</code> or a space in a path segment is a routing problem waiting for the one bank that has one. The storage layer returns cash changes as <code>{pence: count}</code>; the route decorates each with the label and note-or-coin kind from the same <code>DENOMINATIONS</code> table, so the frontend renders "Added 2 × £20 notes" without carrying its own copy of the list.</p><p>The page itself, <code>/accounts/:bank/:accountId</code>, is an ordinary React Router detail view like the budget drill-downs (<a href="https://ghost.atathome.me/budgets/">post 15</a>): a back link, the account's name and balance, and a list of events. Each shows what happened, when, the new balance and the change in pounds, green for up and red for down. For a cash event the individual notes and coins appear beneath, pluralised properly ("1 × £20 note", "3 × £1 coins"). Reached from a History button on every row of the Accounts page and, in the last commit, from a "View history" button on each balance chart on the home page - the chart tells you <em>that</em> a balance moved and the button is one click to <em>why</em>.</p><h2 id="honest-about-the-gaps">Honest about the gaps</h2><p>Two limits are worth stating rather than hiding. First, there's <strong>no backfill</strong>: the table is created empty, so changes before it existed simply aren't there, and the page says so when an account has no events instead of showing a blank. Second, deleting a manual account deletes its trail - an audit log for something that no longer exists would be orphaned rows with no way to view them.</p><p>One mundane cost is worth recording too. A great many existing tests build their in-memory database table by table rather than through <code>connect()</code>, so adding a table that <code>save_accounts</code> and <code>update_manual_account</code> now write to broke dozens of them at once, all with <code>no such table: account_events</code>. The fix was mechanical - export the schema constant and create it in each fixture - but it's a reminder of what those hand-built fixtures cost: every new table is a sweep through the tests. It's an argument for a single <code>make_test_db()</code> helper, and a candidate for the next tidy-up.</p><h2 id="what-this-adds-up-to">What this adds up to</h2><p>The app now covers the whole picture: open-banking accounts, a brokerage with no API, hand-tracked debts, and a wallet. The audit trail makes the last two kinds trustworthy, since "I typed that" and "the wallet changed" are now recorded rather than remembered. And the shape of the solution echoes earlier posts: pure functions for the arithmetic, per-account state in tables keyed beside the account, and a rule written down at the one place that enforces it.</p><hr><p>Previous: <a href="https://ghost.atathome.me/making-the-nightly-sync-boring/">← Making the nightly sync boring</a> · Next: <a href="https://ghost.atathome.me/card-statements-and-due-dates/">Card statements and due dates →</a> · Back to <a href="https://ghost.atathome.me/tag/building-finance-system/">series index</a></p></hr>]]></content:encoded></item><item><title><![CDATA[House-move inventory: Built, then deleted: authentication - Part 10]]></title><description><![CDATA[~8 min read

For a two-person app, a login system sounds like overkill. I built one anyway, over about three weeks, and then removed all of it. This post is the history, and what the app trusts today.

(If you've read the finance-system series, its post 9 "Handing authentication to identity-system" covers the same destination reached from a different starting point.)


Built it

On 6 September, Phase 3.9 added per-user accounts and server-side sessions with Argon2 hashing, a POST /api/auth/login]]></description><link>https://brightbot.co.uk/built-then-deleted-auth/</link><guid isPermaLink="false">Ghost__Post__6ae5babe1df6faba86556b67</guid><category><![CDATA[Building Inventory System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Thu, 19 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1762330472502-83efbe1d4478?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDR8fGF1dGhlbnRpY2F0aW9ufGVufDB8fHx8MTc5MzUyNzc0N3ww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1762330472502-83efbe1d4478?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDR8fGF1dGhlbnRpY2F0aW9ufGVufDB8fHx8MTc5MzUyNzc0N3ww&ixlib=rb-4.1.0&q=80&w=2000" alt="House-move inventory: Built, then deleted: authentication - Part 10"/><p><em>~8 min read</em></p><p>For a two-person app, a login system sounds like overkill. I built one anyway, over about three weeks, and then removed all of it. This post is the history, and what the app trusts today.</p><p>(If you've read the finance-system series, its post 9 "Handing authentication to identity-system" covers the same destination reached from a different starting point.)</p><h2 id="built-it">Built it</h2><p>On 6 September, Phase 3.9 added per-user accounts and server-side sessions with Argon2 hashing, a <code>POST /api/auth/login</code> and a cookie guarding every route except <code>/health</code>. Two days later came opt-in two-factor auth: TOTP from an authenticator app, ten single-use recovery codes, a lockout after ten consecutive bad codes, a QR-code enrolment screen in Settings.</p><p>Then I extracted it. The auth code became its own package, <code>sessionkit</code>, first in-tree (Phase 3.23, with a test that fails CI if it ever imports <code>inventory</code> or FastAPI), then published to its own repo and installed from GitHub (3.24). That was a satisfying piece of engineering. It was also the moment I should have asked the obvious question.</p><h2 id="the-question-i-should-have-asked-sooner">The question I should have asked sooner</h2><p>Why does <em>this</em> app own accounts at all? I run other small tools at home. Each one that needed a login would carry its own user table, its own 2FA enrolment screen and its own password-change form, and a fix to how accounts work would have to be rolled out to every one of them. <code>sessionkit</code> made that rollout <em>possible</em>; it didn't make it unnecessary.</p><p>The alternative is a pattern nginx calls <code>auth_request</code>: one service, a separate project called <strong>identity-system</strong>, owns the accounts. nginx asks it about every request, and the app trusts the answer.</p><h2 id="what-the-app-does-now">What the app does now</h2><pre><code>Browser --&gt; nginx --auth_request--&gt; identity-system GET /verify
                                          |
                      200 + X-Auth-User-Id / -Email / -Name
                                          |
            nginx injects those headers, then forwards to this app
</code></pre><p>The entire authentication surface of the inventory app is one file, <code>api/identity.py</code>. It reads three headers. <code>X-Auth-User-Email</code> is the signal: if it's blank or missing the request got here without going through nginx, and the answer is <code>401</code>. There's no database lookup. <code>X-Auth-User-Name</code> falls back to the email, and <code>X-Auth-User-Id</code> may legitimately be empty - nothing in this schema references it any more.</p><p>For local development there's no proxy, so every route would 401. An explicit <code>INVENTORY_DEV_AUTH_BYPASS=1</code> fakes a fixed user instead. It's opt-in and named loudly, because a "convenient" default-on bypass is how real ones ship.</p><h2 id="the-rule-that-makes-it-safe">The rule that makes it safe</h2><p>Trusting request headers is only safe if clients cannot set them. The guarantee is in nginx: the <code>proxy_set_header</code> lines <strong>unconditionally overwrite</strong> all three <code>X-Auth-User-*</code> headers with what <code>/verify</code> returned, discarding anything a client sent under the same names. It's written into the project notes in bold:</p><blockquote>Any new nginx <code>location</code> that proxies to this backend must set all three headers too, or it is an authentication bypass.</blockquote><p>That is the kind of invariant I'd rather have in the docs <em>and</em> in a place a future me will trip over it, which is why it's in <code>CLAUDE.md</code>, <code>docs/auth.md</code> and a comment in the nginx file.</p><h2 id="it-was-done-in-careful-steps">It was done in careful steps</h2><p>The cutover went out as separate commits so each could be verified against the live container before the next:</p><ol><li><strong>TLS first.</strong> identity-system's session cookie is <code>Secure</code>, scoped to a shared cookie domain. A <code>Secure</code> cookie is silently dropped over plain HTTP, which turns a missing certificate into an infinite redirect loop. TLS was a prerequisite, not a nicety. (The nginx file in the repo now sits behind a TLS-terminating layer in front, and an interim <code>443</code> listener was removed.)</li><li><strong>Forward-auth</strong> in nginx.</li><li><strong>Drop the in-app auth.</strong></li></ol><p>The third step was the satisfying one: the <code>sessionkit</code> dependency, the <code>/api/auth/*</code> and <code>/api/users*</code> routes, <code>render/qr.py</code> and the <code>qrcode</code> dependency (used for nothing but the TOTP QR), the login and 2FA screens, the account CLI. In the SPA, <code>auth.tsx</code> and <code>App.tsx</code> lost their login wall entirely - an unauthenticated browser never receives the app in the first place, so a 401 anywhere just reloads the page, which re-triggers the proxy's check on the document request.</p><h2 id="the-tail-migration-14">The tail: migration 14</h2><p>Dropping the code left the <em>data</em>: three tables. Migration 14 drops <code>users</code>, <code>sessions</code> and <code>recovery_codes</code> (children first), and in doing so exposed the baseline-schema bug from <a href="https://ghost.atathome.me/schema-migrations-with-pragma-user-version/">post 6</a> - the baseline would have quietly recreated them on next start. Deleting a feature properly is a migration, a guard, and a docs change, not just <code>git rm</code>.</p><h2 id="what-id-say-about-the-detour">What I'd say about the detour</h2><p>Three weeks of auth work looks wasteful. It isn't quite: the realistic-fixture approach to migration 7 and the in-tree-first extraction are both things I'd reuse. But the lesson is cheap to state. <strong>Before building a capability inside an app, count how many apps will need it.</strong> If the answer is more than one, it's a service.</p><p>Next: the status, the "going?" decision, and the history that records them.</p><hr><p>Previous: <a href="https://ghost.atathome.me/slow-pdfs-as-background-jobs/">← Slow PDFs as background jobs</a> · Next: <a href="https://ghost.atathome.me/status-going-and-history/">Status, going? and a history →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: Making the nightly sync boring - Part 17]]></title><description><![CDATA[~9 min read

The goal of a nightly job is to be boring. Nothing about it should be worth reading about. By early October the sync was no longer a script I ran by hand (post 3) but a multi-user, multi-provider pipeline, and getting it to quiet took a run of unglamorous commits. This post gathers them, from systemd units to log retention to two small test fixes. If the earlier posts were about adding capabilities, this one is about the failure modes that appear once the capabilities are live.


Mo]]></description><link>https://brightbot.co.uk/making-the-nightly-sync-boring/</link><guid isPermaLink="false">Ghost__Post__6ad488cb1df6faba865569d0</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Wed, 18 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1505811210036-052144988918?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDIxfHxOaWdodHxlbnwwfHx8fDE3OTIzMTY3MTV8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1505811210036-052144988918?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDIxfHxOaWdodHxlbnwwfHx8fDE3OTIzMTY3MTV8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: Making the nightly sync boring - Part 17"/><p><em>~9 min read</em></p><p>The goal of a nightly job is to be boring. Nothing about it should be worth reading about. By early October the sync was no longer a script I ran by hand (<a href="https://ghost.atathome.me/first-prototype-cli-script/">post 3</a>) but a multi-user, multi-provider pipeline, and getting it to <em>quiet</em> took a run of unglamorous commits. This post gathers them, from systemd units to log retention to two small test fixes. If the earlier posts were about adding capabilities, this one is about the failure modes that appear once the capabilities are live.</p><h2 id="monzo-and-the-30-day-window">Monzo and the 30-day window</h2><p><a href="https://ghost.atathome.me/keeping-data-fresh/">Post 7</a> described <code>sca_exceeded</code>: some providers only allow transaction history to be pulled shortly after the user has authenticated. That's a particular problem for a job that asks for the last 90 days at 3am, when the last authentication was long ago. One commit (<code>fixing HL systemd units, fix subsequent monzo sync's limiting to 30 days</code> - the title also covers the Hargreaves Lansdown fix in <a href="https://ghost.atathome.me/hargreaves-lansdown/">post 14</a>) changes the window, and the reasoning is written into a comment above two constants:</p><pre><code class="language-python">INITIAL_SYNC_DAYS = 90
SUBSEQUENT_SYNC_DAYS = 30
</code></pre><p>A bank's <em>first</em> pull after linking (or re-linking) asks for the full 90 days, because that's also when a provider is most likely to grant deep history - "per their SCA exemption rules." Every later sync asks for 30, since "by then most history is already stored locally, and a narrower ask is less likely to run into a provider's 'shortly after authentication' restriction than repeating the full 90 every time would."</p><p>How does <code>fetch()</code> know which kind of sync this is? A <code>synced</code> flag in that bank's stored token entry. It's absent for a bank that has never completed a fetch, and - usefully - it's <em>also</em> absent after re-linking, because the callback overwrites the stored token wholesale. So re-linking to recover from a problem automatically triggers a deep pull, with no extra bookkeeping. Overwriting a record you want to reset is a perfectly good way to reset it.</p><h2 id="turning-an-error-string-into-data">Turning an error string into data</h2><p>Post 7 improved the log line for a failed request but left the error as a string. The same commit makes it structured. <code>get()</code> now raises a <code>TrueLayerAPIError</code>, a subclass of <code>requests.HTTPError</code> - so every existing <code>except requests.RequestException</code> still catches it - that carries TrueLayer's error <code>code</code> as a real attribute. The docstring says why: so callers "can branch on it structurally instead of substring-matching <code>str(exc)</code>."</p><p>And one caller does. When a transactions fetch fails with <code>sca_exceeded</code>, the connection is flagged <code>needs_reauth</code>:</p><pre><code class="language-python">if isinstance(exc, TrueLayerAPIError) and exc.code == "sca_exceeded":
    connection_entry["needs_reauth"] = True
</code></pre><p>This is deliberately separate from <code>consent_expires_at</code>. The comment is precise: the consent itself is "usually still valid for months, but this provider (Monzo, notably) still demands a fresh PSU authentication to pull transaction history", so the Accounts page flags it as its own state - or else it's "masked by an otherwise-healthy 'Expires in N days' badge." Two different problems, two different badges, the same fix for the user (re-link). The new column lands with the usual <code>PRAGMA table_info</code> guard, and <code>save_connections()</code> defaults a missing <code>needs_reauth</code> to <code>0</code> so old JSON files and test fixtures don't have to know about it.</p><h2 id="dont-fail-the-whole-unit-because-someone-has-nothing-to-sync">Don't fail the whole unit because someone has nothing to sync</h2><p>One <code>fix nightly sync</code> commit is two small edits that fix a real consequence of <a href="https://ghost.atathome.me/one-storage-tree-per-user/">post 10</a>. The nightly script loops over every user directory. A user who's been provisioned but hasn't yet linked a bank - or has unlinked their last one - makes <code>fetch()</code> raise <code>NoLinkedBanks</code>, which the CLI turned into <code>sys.exit(1)</code>: exactly the same exit code as a real failure. The unit would report failure every night over something perfectly expected.</p><p>The fix gives "nothing to do" its own code:</p><pre><code class="language-python"># CLI exit status for NoLinkedBanks - distinct from 1 (a real failure) so
# deploy/fetch-all-users.sh can skip an unlinked user without failing the
# whole nightly unit.
EXIT_NO_LINKED_BANKS = 3
</code></pre><p>and the shell script treats 3 as a skip (<code>continue</code>) rather than a failure. It's the same principle as <a href="https://ghost.atathome.me/keeping-data-fresh/">post 7</a>'s partial-failure reporting, one level up: a monitoring signal that cries wolf gets ignored, and then it's useless on the night it's right. Exit code 1 should mean something went wrong.</p><h2 id="logs-that-clean-up-after-themselves">Logs that clean up after themselves</h2><p>The <code>add nightly logging</code> commit addresses a problem that only shows after a few weeks: every sync writes a timestamped log file per user, and nothing ever deletes them. Retention is built into the sync itself rather than being a separate cleanup job. <code>prune_old_sync_logs()</code> runs right before a run opens its log file and deletes anything older than 30 days.</p><p>Two details are worth noting. Age is read from the <strong>timestamp encoded in the filename</strong>, not the file's modification time, because a backup, restore or copy can change an mtime; the name is the record. And the docs are candid about the tradeoff: because retention rides along with the sync, "a user whose syncs have stopped running keeps whatever was last written until they run again." That behaviour is acceptable, and it's stated rather than discovered.</p><p>The same commit exposes the logs in the browser: the Debug page from <a href="https://ghost.atathome.me/seeing-everything-in-one-place/">post 11</a> gains an "Account sync logs" section backed by <code>/api/debug/sync-logs</code>, sorted newest-first using that same filename timestamp - sorting by filename would always put <code>hargreaves_lansdown_...</code> ahead of <code>true_layer_...</code> regardless of which ran last. The log-file endpoint also uses the pattern from earlier: the requested name must match one that the directory listing itself returned, so no path is ever built from user input.</p><h2 id="one-module-run-two-ways">One module, run two ways</h2><p>A second commit called <code>fix nightly sync</code> moves the storage CLI out of <code>sqlite.py</code>'s <code>if __name__ == "__main__"</code> block and into <code>storage/__main__.py</code>. The module docstring has the reason, and it's a classic Python wrinkle: the <code>storage</code> package's <code>__init__</code> already imports <code>sqlite</code>, so running <code>python -m finance_system.storage.sqlite</code> re-executes a module that's already been imported, which triggers a <code>runpy</code> <code>RuntimeWarning</code>. Moving the entry point to <code>__main__.py</code> means <code>python -m finance_system.storage</code> runs exactly once. The two <code>fetch-*-all-users.sh</code> scripts from <a href="https://ghost.atathome.me/one-storage-tree-per-user/">post 10</a> and <a href="https://ghost.atathome.me/hargreaves-lansdown/">post 14</a> were updated to match, along with the docs - and the unit snippet in <a href="https://ghost.atathome.me/from-script-to-service/">post 4</a>, which that commit also touches.</p><h2 id="deploy-and-test-hygiene">Deploy and test hygiene</h2><p>Two last categories of "boring" work. One commit hardens the deploy script. It now sets <code>BatchMode=yes</code> so a broken SSH key fails immediately instead of hanging on a password prompt Jenkins can't answer, and it prints where the script and the SSH session each actually land, so a mis-set host alias that loops "the target" back to the CI agent shows up in the log rather than as a deploy that silently does nothing. It also fixes <code>remote-setup.sh</code> resolving the unit files relative to the working directory - which, over <code>ssh</code>, is the login shell's home directory, not the script's.</p><p>And two test fixes. The first is a good one. Some frontend tests used a fixed fixture date of <code>2026-09-01</code>, which stopped working when the real month rolled over, because the "this month so far" filter compares against the real clock. The fix uses today's date: the comment notes it's "always 'this month', so it's a safe default for every test that doesn't care about the exact date value." Tests that depend on the calendar rot on a schedule. The second updated a backend test's expectation after HL got a logo.</p><h2 id="what-boring-costs">What boring costs</h2><p>None of these is a feature, and few are visible. But the sync is the foundation under every page - budgets, savings and categories all read what it wrote - and it runs when nobody's looking. The pattern across all of them is the same: when something is <em>expected</em> (a user with no banks, a rolled-over month, a 30-day window), give it a name in the code, instead of letting it look like a failure.</p><hr><p>Previous: <a href="https://ghost.atathome.me/savings-projections/">← Savings projections</a> · Next: <a href="https://ghost.atathome.me/cash-and-an-audit-trail/">Cash, and an audit trail →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[House-move inventory: Slow PDFs as background jobs - Part 9]]></title><description><![CDATA[~8 min read

By the end of September the room PDF could do a lot: a summary page, every box's contents, each box's photo and each item's photo, then every invoice attachment merged on the end. It was also taking long enough that production started returning 504s - the reverse proxy gave up before the PDF finished.

This post is about the fix, and about a decision I'm glad I made: not putting it in the database.


First, the cheap fix (and why it wasn't enough)

The first reaction is to raise the]]></description><link>https://brightbot.co.uk/slow-pdfs-as-background-jobs/</link><guid isPermaLink="false">Ghost__Post__6ae5babd1df6faba86556b62</guid><category><![CDATA[Building Inventory System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Tue, 17 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1518729371765-043e54eb5674?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDR8fHNsb3d8ZW58MHx8fHwxNzkzNTI3NjY3fDA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1518729371765-043e54eb5674?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDR8fHNsb3d8ZW58MHx8fHwxNzkzNTI3NjY3fDA&ixlib=rb-4.1.0&q=80&w=2000" alt="House-move inventory: Slow PDFs as background jobs - Part 9"/><p><em>~8 min read</em></p><p>By the end of September the room PDF could do a lot: a summary page, every box's contents, each box's photo and each item's photo, then every invoice attachment merged on the end. It was also taking long enough that production started returning <strong>504s</strong> - the reverse proxy gave up before the PDF finished.</p><p>This post is about the fix, and about a decision I'm glad I made: not putting it in the database.</p><h2 id="first-the-cheap-fix-and-why-it-wasnt-enough">First, the cheap fix (and why it wasn't enough)</h2><p>The first reaction is to raise the timeout, and I did: <code>deploy/nginx-inventory-system.conf</code> got a <code>proxy_read_timeout</code> / <code>proxy_send_timeout</code> bump to ten minutes. But a request that holds a connection open for minutes is fragile in every way a phone user cares about: switch apps, lock the screen, lose signal, and the work is thrown away.</p><p>So the timeout stayed as defence in depth, and the real change was to stop building the PDF <em>inside the request</em>.</p><h2 id="queue-poll-fetch">Queue, poll, fetch</h2><p>Phase 3.33 turned the two slow exports - the room sheet, and the box sheet with <code>?invoices=true</code> - into background jobs:</p><ol><li><code>POST /pdf-jobs/rooms/{room_id}/sheet</code> takes the same query parameters as the synchronous endpoint and returns <code>202</code> with a <code>job_id</code> immediately.</li><li><code>GET /pdf-jobs/{job_id}</code> reports <code>pending</code>, <code>done</code> or <code>error</code>.</li><li><code>GET /pdf-jobs/{job_id}/file</code> serves the finished PDF.</li></ol><p>The fast exports (labels, a plain box sheet, a box sheet with just photos) stay synchronous. They didn't need it, and a <code>GET</code> that returns a PDF is the simplest possible thing for a link.</p><h2 id="pdfjobmanager-deliberately-small"><code>PdfJobManager</code>, deliberately small</h2><p>The implementation is <code>api/pdf_jobs.py</code>, and the module docstring is blunt about its limits:</p><blockquote>Jobs are process-local and unpersisted - restarting the API drops any in flight, which just means the caller clicks "Generate" again. There is deliberately no database table for this: it is ephemeral, short-lived state, not domain data.</blockquote><p>In detail: a <code>ThreadPoolExecutor</code> with two workers runs the render off the request thread. A job record is a small dataclass - id, status, filename, label, file id, error, timestamps - held in a dict behind a lock. The finished PDF isn't kept in memory; it's cached via a second <code>LocalFileStore</code>, the same opaque-id storage attachments already use, pointed at <code>$INVENTORY_PDF_CACHE_DIR</code> (default: a <code>pdf-cache/</code> sibling of the attachments directory).</p><p>Records and their files are swept 24 hours after creation, long enough for "grab that PDF again later today", and <code>create()</code> sweeps stale jobs before adding a new one, so there's no background janitor thread to get wrong.</p><p>Why not a table? A jobs table would have needed a migration, a repository method set, tests - and for what? If the process restarts mid-render, the right recovery is to click the button again. Persisting it would add machinery to preserve something nobody wants preserved. The <code>clock</code> is injectable here too, so the 24-hour sweep is tested by advancing a fake clock rather than waiting.</p><p>One honest limitation: with two workers and an in-memory registry this only works with <strong>one API process</strong>. For a single-container deploy, that's the deployment. If it ever scaled out, jobs would need to move somewhere shared.</p><h2 id="the-front-end-three-pieces">The front end: three pieces</h2><ul><li><strong><code>usePdfJob</code></strong>, a hook that starts the job and polls it.</li><li><code><strong>&lt;PdfJobLink&gt;</strong></code>, which replaces a plain <code>&lt;a&gt;</code> for these buttons. Idle it says "Generate…", pending it disables and polls, done it swaps in a real link (served from the cache, no regeneration) and opens it once automatically.</li><li><strong>The Exports page.</strong></li></ul><p>The Exports page exists because of a flaw I noticed immediately: click Generate, navigate away, and the job is invisible. There was nowhere to check on a slow export or find out why one failed. So each job carries a <strong>label</strong> built by the route handler (not the caller) - e.g. <code>Room sheet — Kitchen (sealed) + invoices</code> - and <code>GET /pdf-jobs</code> lists them newest first. The page shows label, status pill, created and expiry times, a "View ↗" link when done, or the error message, and polls every two seconds while anything is pending.</p><p>The label's modifiers are assembled from the request: <code>(sealed)</code> for a status filter, <code>(going: definite, maybe)</code> for a decision filter, <code>+ invoices</code>, <code>+ photos</code>. It's a small thing, but it's what lets you tell three Kitchen exports apart.</p><h2 id="errors-are-results">Errors are results</h2><p>Any exception inside the render is caught and recorded on the job (<code>job.status = "error"</code>, <code>job.error = str(exc)</code>), then reported through the poll endpoint like any other state. That sounds obvious, but it means a failure inside a background thread isn't swallowed - it appears on the Exports page with its message. <a href="https://ghost.atathome.me/filters-decisions-and-exporting-everything/">Post 12</a> leans on this: the all-rooms export raises a plain validation error when no box matches, and the job simply ends in <code>error</code> with that message.</p><p>Next: the post where I wrote a complete login system and then deleted it.</p><hr><p>Previous: <a href="https://ghost.atathome.me/sheets-labels-and-french/">← Sheets, labels and French</a> · Next: <a href="https://ghost.atathome.me/built-then-deleted-auth/">Built, then deleted: authentication →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: Savings projections - Part 16]]></title><description><![CDATA[~8 min read

Everything so far has looked backwards: what I spent, what I owe, what the balance was. The savings and projection commit and its follow-up (build on savings add anni date) look forward. The Savings page takes any savings account - synced or manual - and projects its balance twelve months out, given an interest rate and a monthly contribution. It's a small amount of maths, and nearly all of the interest is in making the assumptions explicit, so this post is mostly about those.


The]]></description><link>https://brightbot.co.uk/savings-projections/</link><guid isPermaLink="false">Ghost__Post__6ad488ca1df6faba865569cb</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Mon, 16 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1791569913610-f35abd1c63bd?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDIxfHxTYXZpbmdzJTIwcHJvamVjdGlvbnxlbnwwfHx8fDE3OTIzMTY3NDB8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1791569913610-f35abd1c63bd?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDIxfHxTYXZpbmdzJTIwcHJvamVjdGlvbnxlbnwwfHx8fDE3OTIzMTY3NDB8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: Savings projections - Part 16"/><p><em>~8 min read</em></p><p>Everything so far has looked backwards: what I spent, what I owe, what the balance was. The <code>savings and projection</code> commit and its follow-up (<code>build on savings add anni date</code>) look forward. The Savings page takes any savings account - synced or manual - and projects its balance twelve months out, given an interest rate and a monthly contribution. It's a small amount of maths, and nearly all of the interest is in making the <em>assumptions</em> explicit, so this post is mostly about those.</p><h2 id="the-model-in-a-docstring">The model, in a docstring</h2><p><code>savings.py</code> opens with the model, and it's worth reading before the code because it's honest about what it doesn't do. The projection is "gross (no tax) and deliberately simple". The rate is the account's gross <em>nominal</em> annual rate - "the figure banks quote alongside 'paid monthly' or 'paid yearly' - not the effective AER." The two payment frequencies behave differently:</p><ul><li><strong>Monthly</strong>: interest is credited each month at <code>rate/12</code> on the balance, so it compounds monthly. 5% paid monthly grows to about 5.12% over a year.</li><li><strong>Yearly</strong>: interest <em>accrues</em> at <code>rate/12</code> each month on the credited balance but isn't added until the anniversary, so it doesn't compound within the year. 5% paid yearly grows to exactly 5%.</li></ul><p>There's one more rule that matters, and it's the kind of thing that's easy to get subtly wrong: the monthly contribution lands "at the end of each month, after that month's interest, so it starts earning from the following month." Fixing the order of those two events in writing means the tests have a definite thing to check.</p><p>Like <code>categorization.py</code> and <code>budgets.py</code> before it, this is a module of pure functions - no database, no HTTP. <code>project()</code> takes a balance, rate, frequency, contribution and start date and returns the totals plus one point per month-end. That made it easy to test exhaustively, and it's why the API route that wraps it stays short.</p><h2 id="one-point-per-month-end">One point per month-end</h2><p>Each projected point is "what the account would show then: credited money plus any interest accrued but not yet paid out". For a yearly account that's a meaningful choice: between anniversaries, accrued interest is real money the bank owes you but it isn't in the balance yet. Showing credited-only would make the line sit flat and then jump; including accrued shows steady growth, and the totals (<code>interest_earned</code>, <code>contributions</code>, <code>end_balance</code>) are kept separately so the page can show each.</p><h2 id="settings-live-beside-the-account-not-in-it">Settings live beside the account, not in it</h2><p>Savings configuration is per-account metadata - a rate, a frequency, a contribution - and it follows the rule from <a href="https://ghost.atathome.me/seeing-everything-in-one-place/">post 11</a>: user-authored data doesn't go in tables a sync rewrites. It gets its own <code>savings_settings</code> table, keyed <code>(bank, account_id)</code> exactly like the alias table so that one table works for synced and manual accounts alike. Its comment states the lifecycle: "a row only exists once the user has set it up - no row means the account has no projection yet." An account without settings simply shows its balance; the projection appears when there's something to project.</p><p>The API's <code>GET /api/savings</code> returns every account with <code>kind='accounts'</code> (the non-debt ones), attaching a projection to those with settings, and <code>PUT /api/savings/{bank}/{account_id}</code> saves the settings. Cards are rejected with a 400, since a debt doesn't earn interest.</p><h2 id="the-anniversary-a-bug-in-the-first-version">The anniversary: a bug in the first version</h2><p>The first version of yearly interest paid out "12 months from now". That isn't how savings accounts work: interest is paid on the account's <em>anniversary</em>, whenever that happens to fall. A projection that credits it in the wrong month is wrong in every month of the chart.</p><p>The follow-up fixes it by asking for the anniversary date. The interesting detail is how little of it is used - only the <strong>month</strong> matters, since projection points are month-ends:</p><pre><code class="language-python">def _credits_interest(month_of_year, months_from_start, anniversary):
    if anniversary is None:
        return months_from_start % 12 == 0
    return month_of_year == anniversary.month
</code></pre><p>A test pins the behaviour with arithmetic you can check by hand: an account opened in March paying 12% yearly credits at the end of March 2027, the sixth point, with 1000 becoming 1060 credited, then six more months of simple interest accruing on top (£10.60 a month) for an end balance of 1123.60.</p><p>Three smaller details show how the change was threaded through:</p><ul><li><strong>Validation at the edge.</strong> The API now returns a 422 if frequency is <code>yearly</code> and there's no anniversary date - "Yearly interest needs the anniversary date it's paid on". The model has a sensible fallback (12 months from start), but a <em>user</em> choosing yearly is told to supply it.</li><li><strong>Clearing stale data.</strong> If an account is switched back to monthly, the stored anniversary is set to <code>None</code> - only yearly accounts have one, and keeping an ignored date around invites it being misread later.</li><li><strong>A migration that preserves behaviour.</strong> The column is added with the usual <code>PRAGMA table_info</code> guard, and rows saved before it existed read back <code>NULL</code>, "which keeps their old 12-months-from-today projection until the user sets a date." Old rows keep working exactly as before, without a backfill.</li></ul><p>The frontend keeps its form fields as strings, so half-typed input like <code>4.</code> doesn't get rewritten under the cursor, and only parses on save. It also formats the anniversary in UTC - a bare <code>YYYY-MM-DD</code> shifts by a day in timezones west of UTC if formatted in local time.</p><h2 id="a-chart-that-joins-the-past-to-the-future">A chart that joins the past to the future</h2><p>The page started as a list of cards, each with its own projection. A later commit added one chart for all of them, and the interesting decision is how it joins history to projection. Each account gets two series: a solid line of recorded balances from the <code>account_balance_history</code> table (<a href="https://ghost.atathome.me/periods-charts-and-a-phone-sized-ui/">post 13</a>), limited to the last six months, and a dashed line for the projection. The dashed series starts at <em>today's</em> balance - the same point the solid one ends on - so the two lines meet instead of leaving a gap. An account with no settings simply has no dashed line. Reference lines mark today and six months ahead, and the x axis is a real time scale rather than a category per point, so months with no snapshot don't get an evenly spaced slot of their own.</p><p>History is treated as a nice-to-have: if the request for it fails, the chart falls back to the balance now plus the projection, rather than the page showing an error.</p><h2 id="choosing-which-accounts-appear">Choosing which accounts appear</h2><p>Every account with <code>kind='accounts'</code> used to show up here, including a current account you'd never project. The Accounts page now has a "Show on Savings" checkbox per account, and the storage for it is a small table of accounts that are <em>hidden</em>, not a flag defaulting to shown:</p><pre><code class="language-python">SAVINGS_HIDDEN_SCHEMA = """
CREATE TABLE IF NOT EXISTS savings_hidden (
    bank TEXT NOT NULL,
    account_id TEXT NOT NULL,
    PRIMARY KEY (bank, account_id)
);
"""
</code></pre><p>The comment above it gives the reason: with a hidden-list, every savings account is visible until you opt it out, no row is needed for the default, and there is no migration for existing users. <code>PUT /api/savings/{bank}/{account_id}/visibility</code> inserts or deletes the row, hiding keeps the account's projection settings, and deleting a manual account clears its hidden row along with its settings. It's the same shape as the alias and settings tables: per-account state lives in a table keyed <code>(bank, account_id)</code>, beside the account rather than in it.</p><h2 id="tab-titles-and-other-small-ux">Tab titles, and other small UX</h2><p>The <code>UX improvements</code> commit is the least technical in the series but worth a mention. It replaces the Vite default <code>&lt;title&gt;frontend&lt;/title&gt;</code> with "Finance System", swaps the stock favicon for a small chart-line icon, and adds a <code>PageTitle</code> component that keeps <code>document.title</code> in step with the route: "Budgets · Finance System", or for a drill-down, "Groceries · Budgets · Finance System" - the most specific part first, so tabs stay readable when several are open at once. Its lookup table is keyed by the first path segment, so a new route "only needs a line here". It's a few dozen lines, and it's the commit that makes the app feel like a product rather than a localhost project.</p><hr><p>Previous: <a href="https://ghost.atathome.me/budgets/">← Budgets</a> · Next: <a href="https://ghost.atathome.me/making-the-nightly-sync-boring/">Making the nightly sync boring →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[House-move inventory: Sheets, labels and French - Part 8]]></title><description><![CDATA[~9 min read

The inventory only does its job if it leaves the screen. A sheet goes inside each box. A label goes on the outside. Customs gets a document, and since the move is to France, the document is in French. This post covers the rendering layer and the project's only outbound network call.


Pure formatting over domain objects

render/ holds three modules:

 * sheets.py - the plain-text contents sheet.
 * pdf.py - PDFs with reportlab: a box sheet, a room sheet, and /labels.pdf, A4 pages of]]></description><link>https://brightbot.co.uk/sheets-labels-and-french/</link><guid isPermaLink="false">Ghost__Post__6ae5babd1df6faba86556b5d</guid><category><![CDATA[Building Inventory System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sun, 15 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1783115259399-3a5a3e0e4592?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDZ8fHNwcmVhZHNoZWV0fGVufDB8fHx8MTc5MzUyNzY5M3ww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1783115259399-3a5a3e0e4592?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDZ8fHNwcmVhZHNoZWV0fGVufDB8fHx8MTc5MzUyNzY5M3ww&ixlib=rb-4.1.0&q=80&w=2000" alt="House-move inventory: Sheets, labels and French - Part 8"/><p><em>~9 min read</em></p><p>The inventory only does its job if it leaves the screen. A sheet goes inside each box. A label goes on the outside. Customs gets a document, and since the move is to France, the document is in French. This post covers the rendering layer and the project's only outbound network call.</p><h2 id="pure-formatting-over-domain-objects">Pure formatting over domain objects</h2><p><code>render/</code> holds three modules:</p><ul><li><code>sheets.py</code> - the plain-text contents sheet.</li><li><code>pdf.py</code> - PDFs with <code>reportlab</code>: a box sheet, a room sheet, and <code>/labels.pdf</code>, A4 pages of 2×2 A6 shipping labels.</li><li><code>i18n.py</code> - the translations.</li></ul><p>The rule that governs them: <strong>rendering is pure formatting over domain objects and never touches storage.</strong> <code>pdf.py</code> receives a <code>BoxContents</code> or <code>RoomSheet</code> and returns bytes. When a sheet needs an invoice, the <em>service</em> reads the file and hands <code>pdf.py</code> an <code>InvoiceDoc</code> carrying the bytes. This is the same layering as <a href="https://ghost.atathome.me/a-core-that-knows-nothing-about-http/">post 2</a>, applied to output, and it makes the renderers trivially testable: build a sheet in memory, render it, and inspect the result.</p><p>How do you test a PDF? With <code>pypdf</code>. The tests render a real file and extract its text to assert on - not "did <code>render</code> return bytes" but "does page 3 contain <code>KIT-02</code> and not <code>KIT-01</code>". Several features in the roadmap carry a note like "verified end to end, not just at the unit level" after that kind of check caught what a unit test of an intermediate function would have missed: a caption that exists in the data but lands on the wrong page.</p><h2 id="what-goes-on-a-sheet">What goes on a sheet</h2><p>A box sheet is the itemised contents: each line's name, quantity and a string of extras. Those extras come from one shared function, <code>item_extras</code>, used by the text sheet and every PDF variant - <code>[FRAGILE]</code>, <code>[FLAT-PACK]</code>, the value, <code>(bought 2024-03-02)</code>, an invoice count, and dimensions as <code>(W × H × D cm)</code> using only whichever of the three are set.</p><p>Phase 3.31 existed because dimensions and flat-pack had been stored and shown in the UI for a release but "never made it onto anything printed". The fix was two more tokens in that one shared function, and it appeared on the text sheet, the box PDF and the room PDF at once. One function that every format shares is how features arrive everywhere or nowhere, never in two places out of three.</p><p>A room sheet is a summary page - the box list with room-wide market and retail totals - followed by every box's contents. <code>show_going</code> adds each box's going-or-not decision to its line on the summary.</p><h2 id="labels">Labels</h2><p><code>/labels.pdf</code> prints four A6 labels per A4 page: the big box code, room and name, item and line counts, a FRAGILE mark, and an <code>Updated … · Printed …</code> footer. You can ask for one box, an explicit set (<code>?codes=KIT-01&amp;codes=KIT-03</code>), or filter by status, decision, room or search text. Labels are always code-ordered so the printed stack matches the order you'll pick the boxes up in. From a room page you can tick a few boxes and print only those labels.</p><h2 id="french-in-two-layers">French, in two layers</h2><p>There are two different things to translate, and conflating them was the design mistake to avoid.</p><p><strong>The chrome</strong> - headings, field labels, "Market value", box status words - is fixed text in <code>render/i18n.py</code>, with <code>en</code> and <code>fr</code> tables. Every print endpoint takes <code>?lang=en|fr</code>. That's just a lookup.</p><p><strong>The data</strong> - the names and notes you typed - is different. Items and boxes have optional <em>stored</em> <code>name_fr</code> and <code>notes_fr</code> fields, and <code>pick()</code> prefers them when printing in French and falls back to the original:</p><pre><code class="language-python">def pick(base, translated, lang):
    if lang != DEFAULT_LANGUAGE and translated:
        return translated
    return base
</code></pre><p>The key point is that <strong>data translation is opt-in and explicit.</strong> Nothing is translated implicitly at print time, so what's printed is exactly what's stored and reviewed. Missing translations are made visible instead: a warning on the box page, an <code>FR</code> column in lists, and a top-level view of everything still untranslated (<code>0</code> means ready for the French sheet).</p><h2 id="the-one-outbound-call">The one outbound call</h2><p>Typing French labels for several hundred items by hand is tedious, so there's a <strong>suggest</strong> button backed by <code>translate.py</code> and the Anthropic API. The design constraints are what make it acceptable:</p><ul><li><strong>Optional.</strong> Without an <code>ANTHROPIC_API_KEY</code>, the translate endpoints return <code>503</code> and the rest of the app is unaffected. It's the project's only outbound network call, and the code says so at the top of the module.</li><li><strong>Drafts only.</strong> <code>POST /items/{id}/translate</code> and <code>/boxes/{code}/translate</code> return suggestions. They are <strong>never persisted.</strong> You review one and PATCH it back into <code>name_fr</code> / <code>notes_fr</code> like any other edit.</li><li><strong>Terse, and checked.</strong> The system prompt frames it as short inventory labels for a customs declaration, to leave brand names, model numbers, sizes and units alone, and to answer with only a JSON array the same length and order as the input. The adapter parses that array and raises a domain error if the response isn't a list of strings.</li><li><strong>A Protocol again.</strong> <code>Translator</code> is injected into <code>InventoryService</code>, so tests use a fake and never hit the network.</li></ul><p>A machine suggestion that a person approves, on a document that goes to customs, is the right amount of automation. The model writes the first draft; a person signs it off.</p><p>Next: what happens when a PDF takes so long to build that the web server gives up on it.</p><hr><p>Previous: <a href="https://ghost.atathome.me/invoices-photos-and-heic/">← Invoices, photos and HEIC</a> · Next: <a href="https://ghost.atathome.me/slow-pdfs-as-background-jobs/">Slow PDFs as background jobs →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Jenkins shared library: Linting and unit testing the library - Part 4]]></title><description><![CDATA[~8 min read

A shared library is the one place where a mistake reaches every pipeline at once. A typo in syncBlog doesn't break one build, it breaks every project that calls it the next time they load the library. That makes it the code in my setup that most deserves a safety net, and so far it had none. This post adds two: CodeNarc for linting, and unit tests, both run by the library's own Jenkinsfile.


A Gradle build that only does tooling

The library itself needs no build. Jenkins loads it ]]></description><link>https://brightbot.co.uk/jenkins-shared-lib-linting-and-unit-testing/</link><guid isPermaLink="false">Ghost__Post__6aef1e8a1df6faba86556c54</guid><category><![CDATA[Building Jenkins Shared Library]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sat, 14 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1768055105012-4c53791b2877?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDN8fHRlc3Rpbmd8ZW58MHx8fHwxNzk0MjQwMDk4fDA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1768055105012-4c53791b2877?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDN8fHRlc3Rpbmd8ZW58MHx8fHwxNzk0MjQwMDk4fDA&ixlib=rb-4.1.0&q=80&w=2000" alt="Jenkins shared library: Linting and unit testing the library - Part 4"/><p><em>~8 min read</em></p><p>A shared library is the one place where a mistake reaches every pipeline at once. A typo in <code>syncBlog</code> doesn't break one build, it breaks every project that calls it the next time they load the library. That makes it the code in my setup that most deserves a safety net, and so far it had none. This post adds two: CodeNarc for linting, and unit tests, both run by the library's own Jenkinsfile.</p><h2 id="a-gradle-build-that-only-does-tooling">A Gradle build that only does tooling</h2><p>The library itself needs no build. Jenkins loads it straight from the repo layout (<code>vars/</code>, <code>src/</code>, <code>resources/</code>). But both CodeNarc and the test framework I wanted are JVM tools, and Gradle is the easiest way to run them, so the repo gets a <code>build.gradle</code> whose only job is tooling. Its one awkward part is that Jenkins' layout isn't Gradle's, so the source sets are pointed at it:</p><pre><code class="language-groovy">sourceSets {
    main { groovy { srcDirs = ['src'] } }
    vars { groovy { srcDirs = ['vars'] } }
    test { groovy { srcDirs = ['test'] } }
}
</code></pre><p><code>main</code> is the plain classes, which compile fine and go on the test classpath. <code>vars</code> exists purely so CodeNarc will scan it: the steps call pipeline methods like <code>sh</code> and <code>withCredentials</code> that don't exist on a normal compile classpath, so <code>compileVarsGroovy</code> is never expected to pass, and nothing runs it.</p><p>I committed the Gradle wrapper, so the only thing an agent needs is a JDK.</p><h2 id="codenarc">CodeNarc</h2><p>CodeNarc is the standard static analyser for Groovy, and it runs as a Gradle task (<code>./gradlew codenarcMain codenarcVars codenarcTest</code>). The part that takes thought is the rule set. The default is large, and the formatting rules in particular flag stylistic things the existing code does on purpose, like aligning the <code>=</code> in a run of <code>def</code> lines. For a first pass I picked the rule sets that find real problems and nothing else: <code>basic</code>, <code>braces</code>, <code>exceptions</code>, <code>imports</code> and <code>unused</code>. Formatting rules can come later, once I've decided what I actually want.</p><p>A linter that passes proves little until you've seen it fail, so I dropped a file into <code>vars/</code> with an unused variable and an empty <code>catch</code>. The build failed and pointed at the report, and the real files passed: six scanned, none with violations. Then it ran on the tests I wrote next and flagged them straight away, for putting <code>import static</code> lines after the normal imports. That was a two-minute fix, and the sort of thing that's nicer to learn from a tool than from a review comment.</p><h2 id="unit-testing-in-two-layers">Unit testing, in two layers</h2><p>There are two kinds of code here, and they want different tests.</p><p><strong>Classes in <code>src/</code></strong> (<code>Versioning</code>, <code>Defaults</code>) are plain Groovy, so they get ordinary JUnit tests with no Jenkins involved. <code>Versioning</code> is the more interesting one: it rejects anything that isn't <code>MAJOR.MINOR.PATCH</code>, leaves <code>main</code> and <code>master</code> as the bare version, and turns a branch like <code>feature/Add_Login</code> into <code>1.4.2-feature-add-login.9</code>. Those are exactly the edge cases that are tedious to check by running a pipeline and trivial to check in a test.</p><p><strong>Steps in <code>vars/</code></strong> can't be tested that way, because they call pipeline steps. This is what <a href="https://github.com/jenkinsci/JenkinsPipelineUnit">JenkinsPipelineUnit</a> is for: it loads a step as a script and lets you register mock implementations of the pipeline methods it calls. For <code>syncBlog</code>, the mocks record what happened:</p><pre><code class="language-groovy">helper.registerAllowedMethod('withCredentials', [List, Closure]) { List creds, Closure body -&gt;
    credentials = creds
    body()
}
helper.registerAllowedMethod('catchError', [Map, Closure]) { Map opts, Closure body -&gt;
    catchErrorArgs &lt;&lt; opts
    body()
}
helper.registerAllowedMethod('sh', [String]) { String script -&gt; scripts &lt;&lt; script }
</code></pre><p>and the tests assert on them. Both Ghost credentials are requested. The default version and repo come from <code>Defaults</code>, and a <code>version:</code> argument overrides the version. <code>--apply</code> appears before <code>--schedule --apply</code>, which is the ordering the step's comment says must never change. The stage is wrapped in <code>catchError</code> by default, and <code>soft: false</code> leaves it out. There are smaller tests for <code>sayHello</code> and <code>notifyBuild</code>, which also loads its template from <code>resources/</code>. I left out <code>standardPipeline</code>, because a declarative pipeline needs a different kind of test.</p><h2 id="three-things-that-werent-in-the-docs">Three things that weren't in the docs</h2><ul><li><strong>The obvious dependency is the wrong one.</strong> JenkinsPipelineUnit's Maven Central artifact stops at version 1.1, which targets Groovy 2.4.6. Current releases (I used 1.31) are published to the Jenkins repository, so <code>build.gradle</code> adds <code>https://repo.jenkins-ci.org/releases/</code> as a repository.</li><li><strong>Test against Groovy 2.4, because Jenkins does.</strong> Pipeline code on Jenkins runs on Groovy 2.4, so the tests do too, rather than the Groovy 4 Gradle itself uses. It ran fine on the JDK on my laptop.</li><li><strong>Gradle will quietly skip your tests.</strong> The steps and templates are loaded at runtime, not compiled, so Gradle didn't know they were inputs to the <code>test</code> task. After I edited a step, <code>./gradlew test</code> called itself up to date and ran nothing. I only noticed because I broke <code>syncBlog</code> on purpose to check the tests could fail, and they stayed green. The fix is two lines declaring <code>vars</code> and <code>resources</code> as inputs. With that in place, the same deliberate break fails exactly the two tests that should catch it: the one for ordering and the one for <code>soft: false</code>.</li></ul><h2 id="what-the-tests-cant-tell-you">What the tests can't tell you</h2><p>These tests check that a step calls the right things in the right order with the right arguments. They can't check that <code>uvx</code> accepts that command line, that the credentials exist in Jenkins, or that Jenkins accepts the stage at all. A step can pass every test and still fail on the first real run. Before tagging a release, I'll still point a throwaway pipeline at a branch with <code>@Library('bb-jenkins-shared-lib@my-branch') _</code>.</p><h2 id="in-the-jenkinsfile">In the Jenkinsfile</h2><p>The library's own pipeline now has <code>Lint</code> and <code>Test</code> stages before it publishes this blog. Both use the wrapper, <code>Lint</code> archives the CodeNarc reports and also publishes them with <code>publishHTML</code>, so each build gets a "CodeNarc" link in the job sidebar, and <code>Test</code> publishes the JUnit results. A library change that doesn't lint or doesn't pass its tests never reaches <code>main</code>'s <code>Sync blog</code> stage.</p><p>Two things on the Jenkins side make that report usable. The HTML Publisher plugin has to be installed, and Jenkins' default Content-Security-Policy strips the report's inline styles, so it renders as unstyled text until you relax it (for example <code>hudson.model.DirectoryBrowserSupport.CSP</code>). That setting applies to all of Jenkins, so it's a trade-off, not a free win.</p><hr><p>Previous: <a href="https://ghost.atathome.me/jenkins-shared-lib-shared-defaults-and-a-package-name/">← Shared defaults and a package name</a> · Back to <a href="https://ghost.atathome.me/tag/building-jenkins-shared-library/">series index</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Marketplace Listing Helper: Linking listings that already exist - Part 7]]></title><description><![CDATA[~5 min read

The extension was built to create listings, but plenty of my stock was already on Marketplace before the extension existed. Those items sat in the list as drafts, with nothing to say they were live: no "listed" date, no renew reminder, and a real risk of posting them twice. I wanted to say "this listing is that item".


What "link" means

Linking records the address of the Facebook listing on the item. That's all. It's a new column, fb_url, which exports with the CSV like any other.]]></description><link>https://brightbot.co.uk/listing-helper-linking-listings-that-already-exist/</link><guid isPermaLink="false">Ghost__Post__6ae71f9b1df6faba86556bfc</guid><category><![CDATA[Building Marketplace Listing Helper]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sat, 14 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1776062356815-d5e8312792a8?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDZ8fHRvZ2V0aGVyfGVufDB8fHx8MTc5MzUzMjI5NXww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1776062356815-d5e8312792a8?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDZ8fHRvZ2V0aGVyfGVufDB8fHx8MTc5MzUzMjI5NXww&ixlib=rb-4.1.0&q=80&w=2000" alt="Marketplace Listing Helper: Linking listings that already exist - Part 7"/><p><em>~5 min read</em></p><p>The extension was built to create listings, but plenty of my stock was already on Marketplace before the extension existed. Those items sat in the list as drafts, with nothing to say they were live: no "listed" date, no renew reminder, and a real risk of posting them twice. I wanted to say "this listing is that item".</p><h2 id="what-link-means">What "link" means</h2><p>Linking records the address of the Facebook listing on the item. That's all. It's a new column, <code>fb_url</code>, which exports with the CSV like any other.</p><p>I considered two ways to do it:</p><ul><li><strong>Bulk match.</strong> Read the titles on my "Your listings" page and propose matches against the list. It saves clicks, but it depends on the structure of a page that changes often, and scraping it is the kind of thing I'd rather build once the simple version has proved itself.</li><li><strong>Link from the listing page.</strong> Open the listing, press a button. This is what I built.</li></ul><h2 id="how-it-works">How it works</h2><p>On a <code>/marketplace/item/&lt;id&gt;</code> page the panel shows a "Link this Facebook listing" box with a dropdown of my items. The page's number comes straight from the path:</p><pre><code class="language-js">const itemIdFromPage = () =&gt; (location.pathname.match(/^\/marketplace\/item\/(\d+)/) || [])[1] || null;
</code></pre><p>To save a click, it suggests a likely item: the unlinked item whose title shares the most words with the page's <code>document.title</code>. If the page title doesn't contain the item name, no suggestion is made and I choose by hand. Pressing <strong>Link</strong>:</p><ul><li>stores <code>https://www.facebook.com/marketplace/item/&lt;id&gt;/</code> on the item;</li><li>sets the status to <code>listed</code>, unless it's already <code>sold</code>;</li><li>sets the listed date to today if there wasn't one.</li></ul><p>That last point is a limitation I'd rather state than hide: for a listing I posted weeks ago, today's date is wrong, and the renew reminder is counted from it. The manager makes it easy to correct.</p><h2 id="keeping-it-safe">Keeping it safe</h2><p>A few rules stop it doing something surprising:</p><ul><li>If the listing was already linked to a different item, that link <strong>moves</strong> to the one I chose, so a listing never belongs to two items.</li><li>If the item is already linked to a <em>different</em> listing, it asks before replacing it, and the other item's link is only cleared after I confirm.</li><li><strong>Unlink</strong> and a <em>Facebook listing URL</em> field in the editor undo or edit it by hand.</li><li>A blank <code>fb_url</code> in an imported CSV keeps the stored link, as with <code>status</code> and <code>listed</code> in part 3. Re-importing the sheet can't erase it.</li><li>Links are only drawn as clickable if they begin with <code>https://</code>, since the field is text I can paste into.</li></ul><p>Once linked, the panel shows "Open on Facebook ↗" under the selected item, and the manager table has a ↗ column.</p><h2 id="its-the-same-rule">It's the same rule</h2><p>Linking only <em>reads</em> the address bar. It doesn't click anything on the listing page, doesn't renew, and doesn't edit, so it sits comfortably inside the rule from part 1: the extension helps me keep track, and every action on Facebook is still mine.</p><h2 id="what-this-adds-up-to">What this adds up to</h2><p>The feature is small because I kept it to recording a fact (this listing is that item) rather than driving the page. Everything useful that follows, the Open link, the listed state, the renew reminder, comes from that one stored address. Bulk matching can come later if the list grows enough to need it.</p><hr><p>Previous: <a href="https://ghost.atathome.me/listing-helper-photos-that-dont-lag-or-vanish/">← Photos that don't lag or vanish</a> · Back to <a href="https://ghost.atathome.me/tag/building-marketplace-listing-helper/">series index</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: Budgets - Part 15]]></title><description><![CDATA[~9 min read

Categorised spending answers "where did it go?". A budget answers the more useful question, "am I on track?". This post covers the Budgets page, built across five commits between 1 and 5 October, and extended in mid-October with a 50/30/20 view and a richer category page. Nearly all of it reuses machinery from post 12, which is the point - the interesting new decision is about time, not categories.


A month, but whose month?

A budget needs a period, and the obvious period is the c]]></description><link>https://brightbot.co.uk/budgets/</link><guid isPermaLink="false">Ghost__Post__6ad488c91df6faba865569c6</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sat, 14 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1711606815631-38d32cdaec3e?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDR8fEJ1ZGdldHxlbnwwfHx8fDE3OTIzMTY3NzJ8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1711606815631-38d32cdaec3e?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDR8fEJ1ZGdldHxlbnwwfHx8fDE3OTIzMTY3NzJ8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: Budgets - Part 15"/><p><em>~9 min read</em></p><p>Categorised spending answers "where did it go?". A budget answers the more useful question, "am I on track?". This post covers the Budgets page, built across five commits between 1 and 5 October, and extended in mid-October with a 50/30/20 view and a richer category page. Nearly all of it reuses machinery from <a href="https://ghost.atathome.me/rule-based-categorisation/">post 12</a>, which is the point - the interesting new decision is about <em>time</em>, not categories.</p><h2 id="a-month-but-whose-month">A month, but whose month?</h2><p>A budget needs a period, and the obvious period is the calendar month. But <a href="https://ghost.atathome.me/periods-charts-and-a-phone-sized-ui/">post 13</a> already showed what calendar months do to this data, and more fundamentally, I don't get paid on the 1st. If money arrives on the 28th, "the month" that matters runs from one payday to the next. Spending on the 29th is the start of the <em>next</em> budget, not the tail of this one.</p><p>So the only setting the Budgets page needs is a <strong>pay day</strong>, stored in a single-row <code>user_settings</code> table (<code>id</code> is constrained to 1, defaulting to the 28th when no row exists). Each category also gets an optional <code>budget</code> amount via a new column on <code>categories</code>.</p><p>The pay-period maths is a small pure module, <code>budgets.py</code>, in the same spirit as <code>categorization.py</code> - logic with no database access. The one genuinely fiddly part is that not every month has a 28th, 29th, 30th or 31st:</p><pre><code class="language-python">def _clamp_to_month(year, month, day):
    """`day` as a real date in (year, month), pulled back to the last day of
    that month if it's shorter than `day` (e.g. pay_day=31 in a 30-day
    month, or in February)."""
    last_day_of_month = calendar.monthrange(year, month)[1]
    return date(year, month, min(day, last_day_of_month))
</code></pre><p><code>current_pay_period(pay_day, today)</code> returns a half-open <code>[start, end)</code> interval: <code>start</code> is the most recent occurrence of the pay day on or before today, <code>end</code> is the same calculation one month later, both clamped. A pay day of 31 therefore still resolves to a real date every month. The API validates <code>1 &lt;= pay_day &lt;= 31</code>, and the clamping function is what makes 31 a valid answer rather than a crash waiting for February.</p><p>Half-open intervals are worth noting. <code>period_end</code> is the <em>first day of the next period</em>, which makes <code>[start, end)</code> contiguous with the next one - no gap and no overlap. It also makes it a handy reference date, which the paging below uses.</p><h2 id="the-page-spend-against-budget">The page: spend against budget</h2><p>The first commit builds <code>GET /api/budgets</code>, which for the current pay period returns each non-transfer category with its budget and what's been spent. It follows the same recipe as the spending-by-category endpoint, and the docstring is explicit about the ordering: categorise the <em>full</em> history first (subscription detection needs it), and only then restrict to the period and drop transfers - "they're excluded from spending entirely, so they don't belong on a budget page either." Restricting before categorising would break the subscription heuristic, because a monthly charge only has one occurrence inside a single pay period.</p><p>Everything on the Budgets page is derived from these pieces already written - the categorisation pipeline, the transfer flag, the colour slots. A new feature built almost entirely from existing parts is the best evidence that earlier boundaries were drawn in the right places.</p><h2 id="drilling-in">Drilling in</h2><p>The next adds <code>GET /api/budgets/{category}</code>: one category's spending <strong>per day</strong> across the pay period, plus the matching transactions. The interesting function is <code>spending_by_day()</code>, whose docstring says it returns "one entry per day even when nothing was spent that day - so a bar chart built from this has no gaps in its x-axis." Zero-filling is a data-shaping decision best made on the server: the chart component stays a dumb renderer, and nothing downstream has to remember that a missing date means zero. Both endpoints derive their window from the same <code>current_pay_period()</code> call, so the overview and the drill-down can't disagree about which days count - the docstring says that's why the category rows link straight into it.</p><h2 id="paging-through-time">Paging through time</h2><p>A third lets the page move between periods. The mechanism is neat: both endpoints gained an optional <code>reference_date</code> query parameter, defaulting to today, and the frontend pages by passing <em>another period's start</em> as the reference. Going forward uses the current <code>period_end</code> (which, being exclusive, is the first day of the next period); going back uses the day before <code>period_start</code>. The page keeps the reference date in the URL's <code>?ref=</code> query string, so a period is a linkable, refresh-safe address. There's no "current page number" state to get out of sync with the data.</p><p>Another adds the comparison: each category also returns <code>previous_spent</code> - its spend in the pay period before - computed by running the same function on <code>start - 1 day</code>. The frontend turns that into a change arrow, and the colouring is the same lesson as post 5's stat tiles: for spending, down is good (green) and up is bad (red), regardless of the arrow's direction. A previous spend of exactly £0 renders no change at all, since "went from nothing" isn't a meaningful percentage - the code comment is candid that £0 is indistinguishable from "no data for that period".</p><h2 id="two-fixes-that-came-from-using-it">Two fixes that came from using it</h2><p>The last (<code>Improve budget window and card spending</code>) contains one display bug and one data bug, and the data bug is the more important.</p><p>The display bug: <code>period_end</code> is exclusive, so the "Tracking spending from X to Y" heading was off by a day - a period starting on the 28th was labelled as ending on the 28th of the next month, when its last day is the 27th. The fix is to display <code>dayBefore(period_end)</code>. Exclusive end dates are right for computation and wrong for humans, so convert at the display edge.</p><p>The data bug is from <a href="https://ghost.atathome.me/seeing-everything-in-one-place/">post 11</a>'s unfinished business. I'd normalised card <em>balances</em> to this app's sign convention, but card <em>transactions</em> had the same problem and I'd missed it: they arrive as positive magnitudes with a <code>transaction_type</code> saying which way the money moved. As the new docstring puts it, "without this, card spend looks like income and never reaches the spending totals or budgets." The fix:</p><pre><code class="language-python">def _signed_amount(txn, kind):
    amount = txn["amount"]
    if kind != "cards":
        return amount
    magnitude = abs(amount)
    return -magnitude if txn.get("transaction_type") == "DEBIT" else magnitude
</code></pre><p>The consequence is easy to see: a card purchase silently counted as income inflates "income" and understates spending, so a budget looks healthier than it is.</p><p>There's a second half that's easy to miss. Fixing the sign at fetch time doesn't fix the rows <em>already stored</em>, and <code>save_transactions()</code> uses <code>INSERT OR IGNORE</code>, which never touches existing rows. So the same commit adds a follow-up <code>UPDATE transactions SET amount = :amount ... WHERE amount != :amount</code>, whose comment says it "heals rows stored before card amounts were sign-normalised." A normalisation fix on a de-duplicating pipeline needs two parts: the corrected write path and a way to repair old data, because the de-dup that makes re-syncing safe also makes it a poor repair tool.</p><h2 id="income-and-the-503020-split">Income and the 50/30/20 split</h2><p>Per-category budgets answer "is groceries on track?" but not "is the whole shape of my spending sensible?". For that the page gained a 50/30/20 view: of take-home income, roughly 50% should go on needs, 30% on wants and 20% on savings.</p><p>The model is one new column. Each category has an optional <code>bucket</code> - <code>needs</code>, <code>wants</code>, <code>savings</code> or <code>income</code> - and the starter categories are seeded with sensible ones (Bills, Groceries and Transport are needs; Eating out, Shopping and Subscriptions are wants). Settings gained a bucket selector on the category forms. As with the earlier columns, existing databases get an <code>ALTER TABLE</code> behind the usual <code>PRAGMA table_info</code> guard.</p><p>The calculation is <code>split_50_30_20()</code> in <code>budgets.py</code>, another pure function, and its docstring holds the decisions:</p><ul><li><strong>A bucket beats the transfer flag.</strong> Moving money into a savings account is a transfer as far as the rest of the app is concerned and is excluded from spending. But for this view it <em>is</em> the savings. So the function is given the period's transactions with transfers still in, and a category's bucket takes priority over <code>is_transfer</code>. A transfer in a category with no bucket stays excluded, as everywhere else.</li><li><strong>Debits only for spending, credits only for income.</strong> A credit landing in a savings account mustn't cancel the debit that funded it, and income counts only credits in categories bucketed <code>income</code>. The targets are fixed shares of that income.</li><li><strong>Gaps stay visible.</strong> <code>unallocated</code> is income minus the three buckets (negative when overspent), and <code>unbucketed</code> is the other non-transfer spending, Uncategorised included, so categories you haven't assigned don't quietly skew the percentages.</li></ul><p>There's a small API wrinkle worth recording. A category can be given a bucket or have one cleared, so on an update <code>null</code> has to mean "clear it", while leaving the field out has to mean "don't touch it". The route checks <code>"bucket" in payload.model_fields_set</code> to tell the two apart, and the storage function uses a private <code>_UNSET</code> sentinel for the same reason - <code>None</code> can't mean both.</p><p>On the page, a donut shows the split and each bucket is a row with its percentage of income against its target. The colouring encodes the direction of each target: needs and wants are ceilings, savings is a floor, so being <em>over</em> is bad for the first two and good for the last. Each row expands to list its categories, and where a category has a budget it reads "£120 of £150 budget" in green or red, so the two views of the same month agree. The main spend-versus-budget list also prints each category's budget under its name.</p><h2 id="the-category-page-grown-up">The category page, grown up</h2><p>The drill-down from earlier started as a bar chart and a transaction list. It now opens with four stat tiles - total spend, budget used, last period's spend, and budget remaining - with the same "down is good" colouring as the rest of the page. To feed them, <code>GET /api/budgets/{category}</code> returns the category's <code>budget</code>, <code>spent</code> and <code>previous_spent</code>, the last computed by running the same period maths on <code>start - 1 day</code> as before. The transaction table gets a total row.</p><p>A second chart, "Spend per account", breaks the category down by where the money came from. <code>spending_by_account()</code> has a small wrinkle: transactions only carry their account's display <em>name</em>, so it matches against the account list on <code>(bank, name)</code> to recover the account's kind and alias, labels cards as "(card)", and falls back to the raw name if the account has since been removed.</p><p>Finally, the page can now move between periods itself instead of making you go back to the overview: Previous, Next and Current period buttons, driven by the same <code>?ref=</code> query parameter as the overview. Both pages needed the same <code>dayBefore()</code> helper, so it moved out into <code>period.ts</code> rather than being copied.</p><hr><p>Previous: <a href="https://ghost.atathome.me/hargreaves-lansdown/">← Hargreaves Lansdown, with no API</a> · Next: <a href="https://ghost.atathome.me/savings-projections/">Savings projections →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[House-move inventory: Invoices, photos and HEIC - Part 7]]></title><description><![CDATA[~8 min read

A list of items tells customs what. An invoice tells them how much, and that it's real. And a photo of the item, or of the box before it was packed, answers every "which sofa was that?" argument. Both are files, and files don't belong in a SQLite database. This post covers where they went, and one surprisingly fiddly format.


Bytes outside the DB

Attachment bytes live on disk, next to the database, in <db dir>/attachments/ (override with $INVENTORY_ATTACHMENTS_DIR). The database s]]></description><link>https://brightbot.co.uk/invoices-photos-and-heic/</link><guid isPermaLink="false">Ghost__Post__6ae5babc1df6faba86556b58</guid><category><![CDATA[Building Inventory System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Fri, 13 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1735825764478-674bb8df9d4a?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fGludm9pY2VzfGVufDB8fHx8MTc5MzUyNzc2Nnww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1735825764478-674bb8df9d4a?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fGludm9pY2VzfGVufDB8fHx8MTc5MzUyNzc2Nnww&ixlib=rb-4.1.0&q=80&w=2000" alt="House-move inventory: Invoices, photos and HEIC - Part 7"/><p><em>~8 min read</em></p><p>A list of items tells customs <em>what</em>. An invoice tells them <em>how much, and that it's real</em>. And a photo of the item, or of the box before it was packed, answers every "which sofa was that?" argument. Both are files, and files don't belong in a SQLite database. This post covers where they went, and one surprisingly fiddly format.</p><h2 id="bytes-outside-the-db">Bytes outside the DB</h2><p>Attachment bytes live on disk, next to the database, in <code>&lt;db dir&gt;/attachments/</code> (override with <code>$INVENTORY_ATTACHMENTS_DIR</code>). The database stores metadata - filename, content type, size - and the file is named by an opaque id.</p><p>The code reaches the disk through a <code>FileStore</code> protocol with a <code>LocalFileStore</code> implementation, injected into <code>InventoryService</code> - the same pattern as the repository and the clock. Tests use a temp directory; nothing in <code>core.py</code> knows about paths.</p><p>That protocol creates a few obligations, which are the sort of thing that's easy to forget, so they're written down:</p><ul><li><code>delete_box</code>, <code>remove_item</code> and <code>remove_attachment</code> <strong>must delete the files</strong>, not just the rows. Otherwise the attachments directory silently accumulates orphans.</li><li><code>clone_box</code> <strong>copies</strong> them, so a cloned box's invoices are independent.</li><li>Missing files are skipped, not fatal: if a file has gone from disk, the sheet that would have appended it just doesn't.</li></ul><p>Uploads are PDF or image, with a limit. <code>max_upload_mb</code> started life as an environment variable and became a persisted <em>setting</em> (1-100) editable on the Settings page, with the env var as its default.</p><h2 id="three-kinds-of-picture">Three kinds of picture</h2><p>It took three phases to learn that "an image of something" is several different concepts:</p><ol><li><strong>Attachments</strong> (Phase 3.14): documents on an item - invoices, receipts. A PDF or an image. Many per item.</li><li><strong>Box photo</strong> (3.29): one optional photo per box, taken <em>before it's packed</em> - what it looked like, where it lived. <code>box_id</code> is the primary key, so at most one; a re-upload replaces it and deletes the old file. Not copied by <code>clone_box</code>, because it's a photo of a specific physical box.</li><li><strong>Item photo</strong> (3.32): one optional photo per item - what it looks like, as distinct from an invoice. Same shape and replace rule. Unlike the box photo, this one <em>is</em> copied by <code>clone_box</code>, since it documents the kind of item.</li></ol><p>I'd originally treated item photos as "just an image attachment". It isn't: an attachment is evidence, a photo is identification, and they show up in different places on the printed output (invoices are appended, photos lead a section). Giving them separate tables meant each could have its own rules.</p><p>On the front end, the box photo's upload/thumbnail/modal/replace/remove logic was extracted into a generic <code>PhotoPanel</code> once the item version needed it, so <code>ItemPhotoPanel</code> is a ~20-line wrapper rather than a second copy. And the file input carries <code>capture="environment"</code>, so on a phone it can open the camera directly.</p><h2 id="the-iphone-problem">The iPhone problem</h2><p>Photos taken on an iPhone are HEIC by default. Most browsers can't display HEIC, and <code>reportlab</code> can't embed it in a PDF. Nobody can see the photo, and the print pipeline can't use it.</p><p>Commit <code>541669a</code> ("add full heic support", 28 October) fixed it at the door: <code>inventory/images.py</code> converts HEIC/HEIF to JPEG <strong>before it reaches the file store</strong>, for box photos, item photos and image attachments alike. The stored filename becomes <code>*.jpg</code>, the content type <code>image/jpeg</code>.</p><pre><code class="language-python">with Image.open(io.BytesIO(content)) as img:
    img = ImageOps.exif_transpose(img).convert("RGB")
    out = io.BytesIO()
    img.save(out, format="JPEG", quality=JPEG_QUALITY)
</code></pre><p>Two details are the point of the module:</p><ul><li><strong>Rotation.</strong> A HEIC file carries its orientation as metadata. The converted JPEG drops the container's rotation, so <code>ImageOps.exif_transpose</code> applies it to the <em>pixels</em> first. Skip that and every portrait photo comes out sideways.</li><li><strong>Failure is a validation error.</strong> An undecodable file is a corrupt upload, not a server fault. It raises the domain <code>ValidationError</code> and the user gets a 422 with "could not read the HEIC image".</li></ul><p>The decoder is <code>pillow-heif</code>, imported lazily inside the function so the project still works without it for anyone not uploading HEIC. Converting once on upload means everything downstream - browser display, PDF embedding, caching - only ever sees JPEG and PNG. That's a pattern worth stealing: <strong>normalise at the boundary, not at every consumer.</strong></p><h2 id="where-it-all-ends-up">Where it all ends up</h2><p>Photos and invoices exist so they can be printed. A box sheet can lead with the box's photo and its items' photos (<code>?photo=true</code>) and can append every invoice (<code>?invoices=true</code>) - PDFs spliced in as-is, images drawn onto a page, anything unreadable replaced by a placeholder page, so one bad file doesn't sink the whole export. That's the next post.</p><hr><p>Previous: <a href="https://ghost.atathome.me/schema-migrations-with-pragma-user-version/">← Schema migrations with PRAGMA user_version</a> · Next: <a href="https://ghost.atathome.me/sheets-labels-and-french/">Sheets, labels and French →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Jenkins shared library: Shared defaults and a package name - Part 3]]></title><description><![CDATA[~5 min read

The first version of syncBlog had its release tag written straight into the step: v0.2.0 as a default, the Ghost repository URL inside the shell snippet, and the two credential IDs as string literals. That works for one step. This post is about moving those values somewhere central, and about the package name I put them under.


Where to keep a shared value

I weighed three places:

 * The default in the step. Simplest. Bump it, tag the library, and every project that doesn't pass v]]></description><link>https://brightbot.co.uk/jenkins-shared-lib-shared-defaults-and-a-package-name/</link><guid isPermaLink="false">Ghost__Post__6aef1e8a1df6faba86556c4f</guid><category><![CDATA[Building Jenkins Shared Library]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Thu, 12 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1718477183524-9591e306286e?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fGNvbnN0YW50fGVufDB8fHx8MTc5NDI0MDA3M3ww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1718477183524-9591e306286e?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fGNvbnN0YW50fGVufDB8fHx8MTc5NDI0MDA3M3ww&ixlib=rb-4.1.0&q=80&w=2000" alt="Jenkins shared library: Shared defaults and a package name - Part 3"/><p><em>~5 min read</em></p><p>The first version of <code>syncBlog</code> had its release tag written straight into the step: <code>v0.2.0</code> as a default, the Ghost repository URL inside the shell snippet, and the two credential IDs as string literals. That works for one step. This post is about moving those values somewhere central, and about the package name I put them under.</p><h2 id="where-to-keep-a-shared-value">Where to keep a shared value</h2><p>I weighed three places:</p><ul><li><strong>The default in the step.</strong> Simplest. Bump it, tag the library, and every project that doesn't pass <code>version:</code> follows when it moves to the new tag. For one value used by one step, it's enough.</li><li><strong>A Jenkins global environment variable.</strong> Changes everything instantly, with no library release. But the value is no longer in Git, so a change can't be reviewed or rolled back, and a bad value breaks every build at once. That's the opposite of the pinning I've been careful about.</li><li><strong>A constants class in <code>src/</code>.</strong> More than the single value needs today, but it gives the next step somewhere to put its own shared values.</li></ul><p>I went with the class, because this library is groundwork for more steps, and a second step needing the same tool version or credential IDs is likely.</p><p>It lives in <code>src/</code>, not <code>vars/</code>, on purpose. Every file in <code>vars/</code> becomes a global variable and shows up in Jenkins' Pipeline Syntax page, so a file of constants there is clutter. In <code>src/</code> it's a plain class that steps import:</p><pre><code class="language-groovy">package uk.co.brightbot

class Defaults implements Serializable {
    static final String BLOG_SYNC_REPO    = 'https://github.com/atownsend247/ghost-blog-sync.git'
    static final String BLOG_SYNC_VERSION = 'v0.2.0'

    static final String GHOST_URL_CREDENTIAL       = 'ghost-url'
    static final String GHOST_ADMIN_KEY_CREDENTIAL = 'ghost-admin-key'
}
</code></pre><p>and <code>syncBlog</code> reads <code>args.version ?: Defaults.BLOG_SYNC_VERSION</code>. A project can still override the version per call. Bumping <code>blog-sync</code> for everyone is now one edit and one library tag.</p><h2 id="the-package-name">The package name</h2><p>The scaffold shipped with a placeholder package, <code>org.acme</code>, in <code>src/</code> and in <code>resources/</code>. Replacing it touches more places than I expected, because the name appears in three kinds of spot that all have to agree:</p><ul><li>the <strong>folder path</strong> under <code>src/</code> and <code>resources/</code>,</li><li>the <strong><code>package</code> line</strong> in each class (the folder must match it, or Groovy reports <code>unable to resolve class</code>),</li><li>every <strong><code>import</code></strong> and <strong><code>libraryResource('...')</code></strong> path that refers to it, plus the docs and examples.</li></ul><p>The convention for Java and Groovy packages is the reversed domain name. My domain is <code>brightbot.co.uk</code>, so the package is <code>uk.co.brightbot</code>, not <code>co.uk.brightbot</code> - I got that backwards on the first attempt and had to move the folders a second time. It's a cheap mistake to make and a tedious one to undo, and it's far cheaper to fix now than once other projects import from it.</p><h2 id="whats-next">What's next</h2><p>The pieces are in place: a step, a place for its defaults, and a real package name. What remains is to register the library in Jenkins, tag a first release, and switch the Jenkinsfiles over to <code>syncBlog()</code>.</p><hr><p>Previous: <a href="https://ghost.atathome.me/jenkins-shared-lib-extracting-the-sync-blog-stage/">← Extracting the Sync blog stage</a> · Next: <a href="https://ghost.atathome.me/jenkins-shared-lib-linting-and-unit-testing/">Linting and unit testing the library →</a> · Back to <a href="https://ghost.atathome.me/tag/building-jenkins-shared-library/">series index</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Marketplace Listing Helper: Photos that don't lag or vanish - Part 6]]></title><description><![CDATA[~8 min read

The manager's photo picker had two problems. Selecting photos in the edit form was slow, and every new session started with reloading the whole photos folder. Both come down to the same thing: phone photos are large, and a browser extension can't keep hold of files it was shown once. This post is how each was handled.


The lag

The edit form shows every photo in the folder as a small tile, and you click the ones that belong to the item, in order. Clicking was visibly slow. There we]]></description><link>https://brightbot.co.uk/listing-helper-photos-that-dont-lag-or-vanish/</link><guid isPermaLink="false">Ghost__Post__6ae71f9a1df6faba86556bf7</guid><category><![CDATA[Building Marketplace Listing Helper]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Thu, 12 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1485402073834-c95f3eac2fcd?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fHNsb3d8ZW58MHx8fHwxNzkzNTI3NjY3fDA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1485402073834-c95f3eac2fcd?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fHNsb3d8ZW58MHx8fHwxNzkzNTI3NjY3fDA&ixlib=rb-4.1.0&q=80&w=2000" alt="Marketplace Listing Helper: Photos that don't lag or vanish - Part 6"/><p><em>~8 min read</em></p><p>The manager's photo picker had two problems. Selecting photos in the edit form was slow, and every new session started with reloading the whole photos folder. Both come down to the same thing: phone photos are large, and a browser extension can't keep hold of files it was shown once. This post is how each was handled.</p><h2 id="the-lag">The lag</h2><p>The edit form shows every photo in the folder as a small tile, and you click the ones that belong to the item, in order. Clicking was visibly slow. There were two causes:</p><ol><li>Every click <strong>rebuilt the whole grid</strong>: all the tiles, all the images.</li><li>Each tile's image was the <strong>full-size photo</strong>, scaled down by CSS. A 12-megapixel JPEG must be fully decoded to be drawn at 80 pixels wide, and the grid did that for every photo, on every click.</li></ol><p>The fixes mirror the causes:</p><ul><li><strong>Build the grid once</strong>; a click now only toggles a class and a numbered badge on the tile that changed.</li><li><strong>Make real thumbnails.</strong> Each photo is decoded once with <code>createImageBitmap</code>, drawn to a 200px canvas, and kept as a small JPEG. A queue runs three at a time so it doesn't swamp the browser, and an <code>IntersectionObserver</code> means only tiles scrolled into view are processed.</li></ul><p>I haven't timed the before and after. The change removes the repeated full-size decoding, so it should be obvious, but "should be" is not a measurement.</p><h2 id="the-vanishing">The vanishing</h2><p>Chrome gives an extension a <code>File</code> object when you pick a folder, and it can't be saved: only the filename survives a refresh. So the list remembered <em>which</em> photos belonged to an item, and the photos themselves had to be picked again every session.</p><p>The way round it is to keep a copy of the image data inside the extension, which brought up a question: where? The browser's IndexedDB is the usual answer for blobs, and it doesn't work here. A content script's IndexedDB belongs to the page it runs on, so on Facebook it would be <code>facebook.com</code>'s storage, not the extension's, and the manager page couldn't see it. So photos go in <code>chrome.storage.local</code>, which both share, as data URLs. That needs the <code>unlimitedStorage</code> permission, because the default quota is only about 10 MB.</p><h2 id="what-gets-saved">What gets saved</h2><p>Saving every full-resolution photo as base64 would use a lot of space, so:</p><ul><li>photos over 2000px on the long side, or over 1.5 MB, are shrunk to a 2000px JPEG (quality 0.88);</li><li>smaller ones are saved untouched;</li><li>a 200px thumbnail is stored beside each.</li></ul><p>Roughly half a megabyte per photo. A folder is only processed for files that are new or have changed (matched on name, size and modified time), so reloading a folder after adding five photos saves five photos. There's a <strong>Clear saved photos</strong> button that frees the space and leaves the items and their pairings alone.</p><h2 id="placeholders">Placeholders</h2><p>Loading every saved photo into memory on every Facebook page would be wasteful, so the page only holds a placeholder for each (<code>{ name, type, saved: true }</code>). Thumbnails are fetched from storage as tiles scroll into view. The full image is rebuilt into a real <code>File</code> at the last moment, when you press Fill and it's attached to the upload box:</p><pre><code class="language-js">const bin = atob(b64), bytes = new Uint8Array(bin.length);
for (let i = 0; i &lt; bin.length; i++) bytes[i] = bin.charCodeAt(i);
return new File([bytes], name, { type });
</code></pre><p>It decodes the data URL by hand rather than using <code>fetch</code>, because a content script's requests can be subject to the host page's security policy.</p><h2 id="caveats">Caveats</h2><p>What gets attached to the listing is the <strong>resized copy</strong>, not the original. Photos Chrome can't decode, HEIC for instance, can't be saved; they're reported as such and still need loading each session. And nothing yet deletes the photos of items I've sold. That's a button, not a policy, for now.</p><p>I've also only checked this by reading and syntax-checking the code, not yet by running it against a real folder, so the first real run is the test.</p><h2 id="what-this-adds-up-to">What this adds up to</h2><p>The lag was two ordinary mistakes (rebuilding everything on every click, decoding more pixels than you display) and the persistence was a choice of <em>where</em> to store things, forced by what a content script's origin is. Neither needed anything exotic.</p><hr><p>Previous: <a href="https://ghost.atathome.me/listing-helper-a-full-page-manager-without-a-bundler/">← A full-page manager, without a bundler</a> · Next: <a href="https://ghost.atathome.me/listing-helper-linking-listings-that-already-exist/">Linking listings that already exist →</a> · Back to <a href="https://ghost.atathome.me/tag/building-marketplace-listing-helper/">series index</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: Hargreaves Lansdown, with no API - Part 14]]></title><description><![CDATA[~9 min read

The project's very first description listed a stretch goal: Hargreaves Lansdown, for the investment side of the picture. Post 8 assumed that meant a CSV import. It didn't turn out that way. This post covers the commits that made HL a real provider, and mostly it's about how an integration with no API, no OAuth and a real lockout risk changes the design you'd copy from TrueLayer.


What's different about HL

TrueLayer gave me an OAuth flow, a refresh token, and an API. Hargreaves Lan]]></description><link>https://brightbot.co.uk/hargreaves-lansdown/</link><guid isPermaLink="false">Ghost__Post__6ad488c91df6faba865569c1</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Thu, 12 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1651341050677-24dba59ce0fd?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fFN0b2Nrc3xlbnwwfHx8fDE3OTIzMTY4MzF8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1651341050677-24dba59ce0fd?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fFN0b2Nrc3xlbnwwfHx8fDE3OTIzMTY4MzF8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: Hargreaves Lansdown, with no API - Part 14"/><p><em>~9 min read</em></p><p>The project's very first description listed a stretch goal: Hargreaves Lansdown, for the investment side of the picture. <a href="https://ghost.atathome.me/balances-and-disconnecting-banks/">Post 8</a> assumed that meant a CSV import. It didn't turn out that way. This post covers the commits that made HL a real provider, and mostly it's about how an integration with no API, no OAuth and a real lockout risk changes the design you'd copy from TrueLayer.</p><h2 id="whats-different-about-hl">What's different about HL</h2><p>TrueLayer gave me an OAuth flow, a refresh token, and an API. Hargreaves Lansdown offers retail customers none of that. The provider module's docstring states the situation without ceremony: HL "has no public API for retail customers, so <code>hl_client</code> logs into the web portal directly." <code>hl_client</code> is a separate library (<code>atownsend247/hl-api-client-python</code>, per the docstring) that scrapes the portal; this app is its consumer.</p><p>That one fact reshapes everything:</p><ul><li><strong>There's no refresh token.</strong> Every sync submits the real username, password, date of birth and security number. (HL's login also locks the account after too many failed attempts, which the library documents.)</li><li><strong>So syncing must be cautious.</strong> HL can't just ride along on the nightly TrueLayer timer. It got its own, which started out weekly - <code>OnCalendar=Sun *-*-* 04:00:00</code> - on the reasoning that portfolio values "don't move on the timescale spending does", and that every run sends real credentials. It later went daily (<code>OnCalendar=*-*-* 04:00:00</code>), an hour after the TrueLayer run. The unit's comment still draws the line: daily is as often as this should go, and if the stored login stops working the fix is to correct it on the Accounts page promptly "rather than letting the timer keep retrying."</li><li><strong>There's no browser redirect for linking</strong>, so "link" can only mean "store what the user typed."</li></ul><h2 id="first-version-credentials-in-environment-variables">First version: credentials in environment variables</h2><p>The <code>enable HL API client</code> commit was the straightforward implementation. The credentials came from <code>HL_USERNAME</code>, <code>HL_PASSWORD</code>, <code>HL_BIRTHDAY</code> and <code>HL_SECURITY_NUMBER</code> in <code>.env</code>, consistent with the rule in <code>CLAUDE.md</code> that credentials come from environment variables only. <code>fetch()</code> logs in, lists accounts, then lists each account's holdings, and writes JSON for the storage layer to load - the same two-step shape as TrueLayer.</p><p>It added a <code>holdings</code> table (units, price, value, cost, gain in pounds and percent) and, importantly, changed how the <em>shared</em> tables get refreshed. Accounts, connections and holdings are all full-replace caches, and a blanket <code>DELETE FROM accounts</code> would let one provider's sync wipe the other's rows. So each save is scoped to the banks in its own batch:</p><pre><code class="language-python">banks = {a["bank"] for a in accounts}
if banks:
    placeholders = ", ".join("?" * len(banks))
    conn.execute(f"DELETE FROM accounts WHERE bank IN ({placeholders})", tuple(banks))
</code></pre><p>Each provider only ever passes its own accounts, so a TrueLayer sync can't touch HL's rows. It's an easy invariant to break by accident, and it only exists because a second provider arrived.</p><p>One more habit carried over from <a href="https://ghost.atathome.me/keeping-data-fresh/">post 7</a>: if one account's holdings page fails to parse, <code>fetch()</code> logs it and moves on, so the account's own valuation - already recorded - and every other account survive.</p><h2 id="second-version-credentials-move-into-the-app">Second version: credentials move into the app</h2><p>The environment-variable approach had a problem that only showed once there was more than one user (<a href="https://ghost.atathome.me/one-storage-tree-per-user/">post 10</a>): env vars are global, so they can only hold <em>one</em> person's HL login. The <code>migrate HL to user based</code> commit moves the credentials to a per-user file written through the Accounts page.</p><p>This is the one place the project deliberately breaks its own rule, and the rule changed in writing in the same commit. <code>CLAUDE.md</code> now says credentials come from environment variables only, "except Hargreaves Lansdown's: it has no OAuth token to exchange them for, so the real username/password/DOB/ security-number are entered once via the Accounts page and stored per-user in <code>storage/users/{user_id}/secrets/hl_credentials.json</code>" - and then adds that this is "not a drift from the rule above, a deliberate exception to it". I like that the exception is written down next to the rule rather than quietly practised. (It also adds that file to the list of things never to read.)</p><p>The file is treated as more sensitive than TrueLayer's token file, and the code says why:</p><pre><code class="language-python">os.chmod(path, 0o600)
</code></pre><p>The docstring: this file "holds a real password and full security number, materially more sensitive than truelayer.py's revocable refresh token (which tokens.json doesn't bother chmod-ing), so it's worth the extra hardening here." A refresh token can be revoked at the provider; a password can't be un-leaked.</p><p>The new link endpoint contains a decision I'd defend: it <strong>doesn't try to log in</strong>. It just stores what was typed. The docstring explains: "a typo'd password would otherwise cost an extra attempt against HL's lockout counter beyond the one 'Sync now' will trigger anyway." Validating eagerly feels like the responsible thing and is actually the riskier one, because the validation is itself a login attempt. Unlinking deletes the credentials file and the cached accounts and holdings, and, unlike TrueLayer's unlink, takes no "also delete data" option - HL has no transaction history here, only a current snapshot, which goes stale the moment the login is removed either way.</p><h2 id="making-the-scheduler-multi-user">Making the scheduler multi-user</h2><p>With credentials per user, the HL unit had the same problem the nightly one had. The first version of the service unit needed a <code>__HL_USER_ID__</code> placeholder substituted by hand, and its comment admitted it wasn't wired into <code>remote-setup.sh</code> yet. A later commit replaced that with <code>deploy/fetch-hl-all-users.sh</code>, mirroring <code>fetch-all-users.sh</code> with one important difference, spelled out in the script's header: unlike TrueLayer, where every provisioned user is expected to have a bank linked, "most provisioned users won't have HL linked, and <code>fetch()</code> would just raise <code>MissingCredentials</code> for them." So the script skips any user without a <code>hl_credentials.json</code> before even trying - which also means it never submits a login for someone who hasn't asked for one.</p><h2 id="small-things-that-got-done-along-the-way">Small things that got done along the way</h2><p>Another gives HL a logo, hardcoded as <code>provider_logo_url</code>, since a scraped portal has no connection metadata to take one from. And two dependency bumps are worth a line because of what they were for: both update <code>hl-client</code> so failures are diagnosable. The first surfaces the HTTP status and landed path in the "Unable to submit Stage" error; the second surfaces HL's own rejection reason on a failed login. When your only integration is a scraper of someone else's website, the quality of its error messages is the quality of your debugging.</p><h2 id="each-holding-becomes-an-account">Each holding becomes an account</h2><p>Holdings started life as a table of their own, hanging off each HL account. That recorded what I owned, but the balance-history charts from <a href="https://ghost.atathome.me/periods-charts-and-a-phone-sized-ui/">post 13</a> only knew about accounts, so there was no history per holding. A later change gave every holding a row in the <code>accounts</code> table as well, so it gets its own balance, its own history and its own chart for free, exactly like one of a TrueLayer bank's accounts.</p><p>The part worth getting right is the arithmetic. HL reports an account's <code>total_value</code>, which already includes every holding, so adding a row per holding would count the same money twice. <code>fetch()</code> therefore subtracts the holdings from the parent:</p><pre><code class="language-python">parent["balance"] = round(parent["balance"] - sum(float(stock.value) for stock in stocks), 2)
</code></pre><p>The parent row then holds only what's left - cash and anything pending - and the rows still sum to HL's total. The holding rows have an <code>account_id</code> of <code>{account_id}:{stock.id}</code>, a name like <code>Some Fund (ISA)</code>, and an <code>is_holding</code> flag. That flag exists because "how many accounts did we sync?" now has two answers, and both <code>fetch()</code> and the storage loader's counts skip holding rows, so the number reported back to the Accounts page is still the number of accounts HL actually has.</p><h2 id="the-pattern">The pattern</h2><p>If I were adding a third provider, the HL work is the better template than TrueLayer, because it's the less friendly case: write down how this provider authenticates and what that means for sync <em>frequency</em>; store its credentials with the sensitivity they deserve; don't spend a rate-limited login on validation; scope every shared-table refresh to the provider doing it; and skip, rather than fail, users who've never opted in.</p><hr><p>Previous: <a href="https://ghost.atathome.me/periods-charts-and-a-phone-sized-ui/">← Periods, charts, and a phone-sized UI</a> · Next: <a href="https://ghost.atathome.me/budgets/">Budgets →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[House-move inventory: Schema migrations with PRAGMA user_version - Part 6]]></title><description><![CDATA[~9 min read

For the first day of this project, changing the schema meant deleting the database. That is fine until the database contains a week of real packing. The fix was a migration system, which took about a hundred lines, and then over the following weeks it taught me three things I didn't expect.


The runner

SQLite has a spare integer in the file header, PRAGMA user_version, that the engine itself never uses. That's all the bookkeeping a forward-only migration runner needs. In storage/d]]></description><link>https://brightbot.co.uk/schema-migrations-with-pragma-user-version/</link><guid isPermaLink="false">Ghost__Post__6ae5babb1df6faba86556b53</guid><category><![CDATA[Building Inventory System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Wed, 11 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1667372459510-55b5e2087cd0?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDE3fHxkYXRhYmFzZXxlbnwwfHx8fDE3OTM1Mjc3ODN8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1667372459510-55b5e2087cd0?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDE3fHxkYXRhYmFzZXxlbnwwfHx8fDE3OTM1Mjc3ODN8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="House-move inventory: Schema migrations with PRAGMA user_version - Part 6"/><p><em>~9 min read</em></p><p>For the first day of this project, changing the schema meant deleting the database. That is fine until the database contains a week of real packing. The fix was a migration system, which took about a hundred lines, and then over the following weeks it taught me three things I didn't expect.</p><h2 id="the-runner">The runner</h2><p>SQLite has a spare integer in the file header, <code>PRAGMA user_version</code>, that the engine itself never uses. That's all the bookkeeping a forward-only migration runner needs. In <code>storage/db.py</code>:</p><ul><li><code>SCHEMA</code> is a <strong>frozen baseline</strong> - the tables as they were when migrations started. It never changes.</li><li><code>MIGRATIONS</code> is an append-only list of <code>(N, (SQL, ...))</code>, numbered from 1.</li><li><code>apply_migrations</code> runs every entry whose number exceeds <code>user_version</code>, each in its own transaction, and bumps <code>user_version</code> as part of that transaction:</li></ul><pre><code class="language-python">conn.execute("BEGIN")
try:
    for statement in statements:
        conn.execute(statement)
    conn.execute(f"PRAGMA user_version = {version}")
    conn.execute("COMMIT")
except Exception:
    conn.execute("ROLLBACK")
    raise
</code></pre><p>It also refuses two things: a migrations list with gaps (<code>RuntimeError</code>, "must be numbered 1, 2, 3, ... with no gaps") and a database whose <code>user_version</code> is <em>newer</em> than the code knows about. The second one matters on a deploy: if I ever roll the app back past a migration, I want a loud error rather than an old build quietly mis-reading a newer schema.</p><p>The first real migration was tiny - <code>items.purchased_on</code>, a nullable date - and the whole point was that opening an older <code>inventory.db</code> with a newer build now upgrades it in place and keeps the data.</p><h2 id="lesson-1-sqlites-alter-table-is-small">Lesson 1: SQLite's <code>ALTER TABLE</code> is small</h2><p>It can add a column and rename things. That's it. So the recipe has two forms:</p><ul><li><strong>Additive change:</strong> <code>ALTER TABLE ... ADD COLUMN</code>. Most migrations are this - retail value, French labels, box decision, sub-status, dimensions.</li><li><strong>Restructuring:</strong> create the new table, copy, drop the old, rename, all in one migration entry.</li><li><strong>Dropping a whole table</strong> isn't restructuring and gets a plain <code>DROP TABLE</code> - but children before parents, because every connection runs <code>PRAGMA foreign_keys = ON</code>.</li></ul><p>A test helper builds fake migrations as <code>db.MIGRATIONS + [(len+1, ...)]</code>, which is how the "no gaps" rule shows up in practice.</p><h2 id="lesson-2-some-migrations-are-data-migrations">Lesson 2: some migrations are data migrations</h2><p>Migration 7 was the interesting one. An auth library change made user ids opaque strings instead of sequential integers, which meant rebuilding <code>users</code>, <code>sessions</code> and <code>recovery_codes</code> with a <code>TEXT</code> id and <strong>remapping the foreign keys</strong> in the other two tables to match.</p><p>SQLite has no UUID function, so the migration generates a random UUID4 per existing account in pure SQL - <code>hex(randomblob(...))</code> assembled into the 8-4-4-4-12 shape, with the version and variant nibbles forced. That's the kind of code you shouldn't trust on inspection, so I didn't. A scratch script built a realistic fixture - two accounts, one with 2FA on, sessions for each, recovery codes for one - ran the migration, and checked that <code>PRAGMA foreign_key_check</code> was clean, that every session and recovery code pointed at the <em>right</em> new id, and that TOTP state survived. Those checks now live in <code>tests/storage/test_migrations.py</code>.</p><p>(Those tables are gone now - <a href="https://ghost.atathome.me/built-then-deleted-auth/">post 10</a> is about that - but the technique, "write the realistic-fixture test before trusting a data migration", is the keeper.)</p><h2 id="lesson-3-the-baseline-can-resurrect-things">Lesson 3: the baseline can resurrect things</h2><p>This is the one that would have bitten me in production. Migration 14 drops the <code>users</code>, <code>sessions</code> and <code>recovery_codes</code> tables, because authentication moved to identity-system. Easy enough. But <code>init_db</code> used to run the baseline <code>SCHEMA</code> on <strong>every</strong> process start, and that baseline still declares those tables - migrations 6 and 7 are written against them, so it has to. Since the baseline uses <code>CREATE TABLE IF NOT EXISTS</code>, the next restart after migration 14 would have cheerfully recreated all three, empty.</p><p>Nothing would have errored. The tables would just have reappeared, silently, and the "dropped for good" migration would not have been.</p><p>The fix is a sentinel check: apply the baseline only if the <code>boxes</code> table does not already exist.</p><pre><code class="language-python">def _baseline_applied(conn):
    return conn.execute(
        "SELECT 1 FROM sqlite_master WHERE type='table' AND name='boxes'"
    ).fetchone() is not None

def init_db(conn):
    if not _baseline_applied(conn):
        conn.executescript(SCHEMA)
    apply_migrations(conn)
</code></pre><p><code>boxes</code> is the right sentinel because it's in the baseline and no migration has ever dropped it. The project notes now carry a warning not to remove that guard "without re-adding some other way to keep migration 14 durable". Idempotent setup scripts are only idempotent for the schema as it was when you wrote them.</p><h2 id="backups-before-you-need-them">Backups before you need them</h2><p>Migrations pair with the DB tool (<code>python -m inventory.cli.db</code>): <code>status</code> shows applied and pending migrations (and rejects a database newer than the code), <code>migrate</code> applies them, and <code>backup</code> uses SQLite's online-backup API, so the copy is consistent even while the API is running. <code>restore</code> validates that the source is a SQLite file and not newer than the code, and clears stale <code>-wal</code>/<code>-shm</code> files. A backup that you've never restored is a hope, so the restore path got the same care as the backup.</p><p>Next: files that don't belong in the database - invoices, photos, and an iPhone format that nothing else can read.</p><hr><p>Previous: <a href="https://ghost.atathome.me/the-spa-small-pieces-no-ui-library/">← The SPA: small pieces, no UI library</a> · Next: <a href="https://ghost.atathome.me/invoices-photos-and-heic/">Invoices, photos and HEIC →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Jenkins shared library: Extracting the Sync blog stage - Part 2]]></title><description><![CDATA[~6 min read

With the scaffold in place, the first real candidate was obvious: the Sync blog stage that appears, near enough verbatim, in three Jenkinsfiles. This post is about what I moved into the library, what I deliberately left behind, and the two options I gave the new step.


What the stage does

Reading the three copies side by side, the work they do is the same:

 1. Take two Secret text credentials from Jenkins, ghost-url and ghost-admin-key.
 2. Run blog-sync --apply, which creates mi]]></description><link>https://brightbot.co.uk/jenkins-shared-lib-extracting-the-sync-blog-stage/</link><guid isPermaLink="false">Ghost__Post__6aef1e891df6faba86556c4a</guid><category><![CDATA[Building Jenkins Shared Library]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Tue, 10 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1730382624709-81e52dd294d4?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fGRldmVsb3BtZW50fGVufDB8fHx8MTc5NDIzOTk1M3ww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1730382624709-81e52dd294d4?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fGRldmVsb3BtZW50fGVufDB8fHx8MTc5NDIzOTk1M3ww&ixlib=rb-4.1.0&q=80&w=2000" alt="Jenkins shared library: Extracting the Sync blog stage - Part 2"/><p><em>~6 min read</em></p><p>With the scaffold in place, the first real candidate was obvious: the <code>Sync blog</code> stage that appears, near enough verbatim, in three Jenkinsfiles. This post is about what I moved into the library, what I deliberately left behind, and the two options I gave the new step.</p><h2 id="what-the-stage-does">What the stage does</h2><p>Reading the three copies side by side, the work they do is the same:</p><ol><li>Take two Secret text credentials from Jenkins, <code>ghost-url</code> and <code>ghost-admin-key</code>.</li><li>Run <code>blog-sync --apply</code>, which creates missing posts as drafts and updates changed ones without touching a post's published or draft status.</li><li>Run <code>blog-sync --schedule --apply</code>, which queues any posts still sitting as drafts, one every other day at 09:00 London time.</li></ol><p>The order matters: scheduling skips posts that aren't on Ghost yet, so the content sync has to come first. Jenkins runs <code>sh</code> with <code>set -e</code>, so if the sync fails, the schedule step never runs. The library step keeps that comment, because it's the sort of thing someone will otherwise "tidy" away.</p><p>The finance, inventory and identity copies also wrap everything in <code>catchError</code>, so a Ghost outage or a bad API key marks the stage UNSTABLE rather than failing the build. A blog problem shouldn't hold up shipping the app.</p><h2 id="what-stays-in-the-jenkinsfile">What stays in the Jenkinsfile</h2><p>The <code>when { branch 'main' }</code> guard stays where it is. <code>when</code> is a declarative pipeline directive that belongs to a <code>stage</code>, and a step in <code>vars/</code> can't carry one. So the stage keeps its name and its guard, and the body becomes one line:</p><pre><code class="language-groovy">stage('Sync blog') {
    when { branch 'main' }
    steps { syncBlog() }
}
</code></pre><p>The alternative was a step that declares the whole stage itself, but that would hide the guard from anyone reading the Jenkinsfile, and the Jenkinsfile is where you expect to see <em>when</em> something runs.</p><h2 id="two-options">Two options</h2><p>The step takes a map, which the library's own docs recommend for anything with more than one option, because callers get named parameters and new options can be added without breaking anyone.</p><ul><li><code><strong>version</strong></code> is the <code>blog-sync</code> release tag to run. Today all three projects pin the same one, so it has a default, and a project can still override it. Pinning matters for the same reason it did in the Jenkinsfiles: a change to <code>blog-sync</code> can't break a build until someone bumps the tag.</li><li><code><strong>soft</strong></code> defaults to <code>true</code>, which keeps the <code>catchError</code> behaviour the three copies have. Passing <code>soft: false</code> lets the sync fail the build.</li></ul><p><code>soft: false</code> exists because not every project is shaped like those three. <code>blog-sync</code>'s own pipeline has nothing to ship, so the blog is the whole pipeline, and a failed sync should turn the build red.</p><h2 id="what-i-didnt-take">What I didn't take</h2><p><code>blog-sync</code>'s own Jenkinsfile runs the tool from its checkout (<code>uv run blog-sync</code>) so that it always tests the code it's about to publish, where the other projects install a pinned release with <code>uvx</code>. The shared step only covers the pinned case, so I've left that Jenkinsfile alone rather than bending the step to fit one caller.</p><h2 id="not-switched-over-yet">Not switched over yet</h2><p>The step exists, but the three Jenkinsfiles still carry their own copies. Moving them is a separate change per repository, and it needs the library registered in Jenkins and tagged first; otherwise their builds would fail looking for a step that isn't there.</p><hr><p>Previous: <a href="https://ghost.atathome.me/jenkins-shared-lib-why-a-shared-library/">← Why a shared library</a> · Next: <a href="https://ghost.atathome.me/jenkins-shared-lib-shared-defaults-and-a-package-name/">Shared defaults and a package name →</a> · Back to <a href="https://ghost.atathome.me/tag/building-jenkins-shared-library/">series index</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Childcare calculator: Doing the top-up maths for sleep-deprived parents - Part 6]]></title><description><![CDATA[~4 min read

If you've ever tried to work out a payment while running on three hours of broken sleep, you'll know the feeling: you read the same number four times, and it still doesn't mean anything. Baby brain is real, and it doesn't only affect the person who gave birth. Sleep-deprived parents get things wrong in new and creative ways, and "how much do I need to pay into the childcare account?" is a surprisingly easy one to get wrong.


The problem

With Tax-Free Childcare, you don't pay the f]]></description><link>https://brightbot.co.uk/the-government-top-up/</link><guid isPermaLink="false">Ghost__Post__6ae8cd821df6faba86556c2e</guid><category><![CDATA[Building a Childcare Calculator]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Tue, 10 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1758598497429-6eb3895d5bfa?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDN8fHRpcmVkfGVufDB8fHx8MTc5NDI0MDAzNHww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1758598497429-6eb3895d5bfa?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDN8fHRpcmVkfGVufDB8fHx8MTc5NDI0MDAzNHww&ixlib=rb-4.1.0&q=80&w=2000" alt="Childcare calculator: Doing the top-up maths for sleep-deprived parents - Part 6"/><p><em>~4 min read</em></p><p>If you've ever tried to work out a payment while running on three hours of broken sleep, you'll know the feeling: you read the same number four times, and it still doesn't mean anything. Baby brain is real, and it doesn't only affect the person who gave birth. Sleep-deprived parents get things wrong in new and creative ways, and "how much do I need to pay into the childcare account?" is a surprisingly easy one to get wrong.</p><h2 id="the-problem">The problem</h2><p>With Tax-Free Childcare, you don't pay the full bill into the account. You deposit money and the government tops it up by 20% of what you put in. Put in £100 and the government adds £20, so there's £120 in the account.</p><p>The calculator already told you the monthly total, say £600. The natural, tired, wrong thought is: the government adds 20%, so I need to pay in 80% of that. Or perhaps: 20% of £600 is £120, so I need £480. It sounds right. It isn't.</p><p>The top-up is 20% of <strong>your deposit</strong>, not 20% of the total. The total is 120% of what you pay in. So for a £600 bill:</p><ul><li>Wrong: £600 − 20% of £600 = £480 deposited. The account then holds £480 + £96 = £576, which is £24 short.</li><li>Right: £600 ÷ 1.2 = £500 deposited, plus £100 from the government, which is £600.</li></ul><p>A £24 shortfall is exactly the kind of mistake that turns up weeks later as a payment that bounced, or a childminder politely asking about an invoice, at the point you have the least spare attention for it.</p><h2 id="the-fix">The fix</h2><p>Under the "Total to pay" figure, the calculator now shows two more lines:</p><ul><li><strong>You deposit</strong>: the amount to put into the account.</li><li><strong>Government top-up (20%)</strong>: what the government will add on top.</li></ul><p>The total stays exactly as it was. The new lines just answer the question you actually have when you open the page.</p><p>The maths is two lines:</p><pre><code class="language-js">// Government adds 20% of the deposit, so deposit = total / 1.2
const deposit = grand / 1.2;
document.getElementById('topupDeposit').textContent = fmtMoney(deposit);
document.getElementById('topupGov').textContent = fmtMoney(grand - deposit);
</code></pre><p>The top-up is calculated as <code>grand - deposit</code> rather than <code>deposit * 0.2</code>, so the two figures are always derived from the same total. Both are rounded for display, so a deposit of £500.00 and a top-up of £100.00 will always add back up to the total shown above them.</p><h2 id="why-it-belongs-in-the-calculator">Why it belongs in the calculator</h2><p>None of this is difficult. Dividing by 1.2 is hardly a feature. But the point of this tool has always been to remove arithmetic from a monthly chore, and this is the one piece of arithmetic that people tend to do in their head, at the wrong time of day, with the wrong formula. A tool that gets the total right and then leaves you to work out the deposit has only done half the job.</p><h2 id="what-id-do-next">What I'd do next</h2><ul><li><strong>Make the rate configurable.</strong> 20% is the current top-up rate. If it changes, it's currently one number in one place, but it's still hardcoded.</li><li><strong>Round the deposit up to the penny.</strong> The deposit is currently rounded to the nearest penny, which can leave the account a penny short in rare cases.</li></ul><hr><p>Previous: <a href="https://ghost.atathome.me/term-dates-and-persistence/">← Term dates, persistence, and small decisions</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Marketplace Listing Helper: A full-page manager, without a bundler - Part 5]]></title><description><![CDATA[~8 min read

Thirty-six items in a 330-pixel panel on the corner of a Facebook page is a poor place to load a batch. I wanted a proper page: a table of everything, editable in place, with import and export. This post is how that page was added without a build step, and without duplicating the code that already worked.


The page

An extension can ship ordinary HTML pages that open at chrome-extension://<id>/manager.html. They share chrome.storage.local with the content script, so the manager and]]></description><link>https://brightbot.co.uk/listing-helper-a-full-page-manager-without-a-bundler/</link><guid isPermaLink="false">Ghost__Post__6ae71f991df6faba86556bf2</guid><category><![CDATA[Building Marketplace Listing Helper]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Tue, 10 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1542626991-cbc4e32524cc?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDV8fG1hbmFnZXJ8ZW58MHx8fHwxNzkzNTMyMjQyfDA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1542626991-cbc4e32524cc?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDV8fG1hbmFnZXJ8ZW58MHx8fHwxNzkzNTMyMjQyfDA&ixlib=rb-4.1.0&q=80&w=2000" alt="Marketplace Listing Helper: A full-page manager, without a bundler - Part 5"/><p><em>~8 min read</em></p><p>Thirty-six items in a 330-pixel panel on the corner of a Facebook page is a poor place to load a batch. I wanted a proper page: a table of everything, editable in place, with import and export. This post is how that page was added without a build step, and without duplicating the code that already worked.</p><h2 id="the-page">The page</h2><p>An extension can ship ordinary HTML pages that open at <code>chrome-extension://&lt;id&gt;/manager.html</code>. They share <code>chrome.storage.local</code> with the content script, so the manager and the Facebook panel see the same list. The manager has a table with title, price, condition, category and status editable inline (saved on <code>change</code>, so typing isn't interrupted), a search box and a status filter, plus import, export and templates.</p><p>It needs a way to open. A toolbar click does it, through a small service worker whose only job is to open the page, or focus it if it's already open:</p><pre><code class="language-js">chrome.action.onClicked.addListener(openManager);
chrome.runtime.onMessage.addListener(msg =&gt; { if (msg &amp;&amp; msg.open === "manager") openManager(); });
</code></pre><p>The message handler is for the "Manager" button in the Facebook panel. A content script can't navigate a normal tab to a <code>chrome-extension://</code> URL itself, so it asks the worker. The worker does nothing on Facebook, has no timers and doesn't change the rule from part 1.</p><h2 id="sharing-code-with-no-bundler">Sharing code with no bundler</h2><p>All the logic lived in one 800-line content script, mixed up with Facebook-specific code. The manager needed the CSV handling, the column aliases, storage, photo pairing, and even the item editor and template modals. The usual answer is modules and a bundler. I wanted to keep "edit a file, press reload".</p><p>The trick is that classic scripts loaded one after another share a global scope. So the shared code moved into <code>shared.js</code>, which declares plain top-level functions and variables. The manifest loads it first:</p><pre><code class="language-json">"js": ["shared.js", "content.js"]
</code></pre><p>and <code>manager.html</code> loads it with a <code>&lt;script&gt;</code> tag before <code>manager.js</code>. No imports, no exports, no tooling. The cost is that shared names are globals, which is acceptable in a project this size and was the cheapest way to keep a single copy of the editor. The editor and template dialogs take a callback (<code>openEditor(row, cb)</code>) so each page decides what to redraw afterwards.</p><p>What stayed in <code>content.js</code> is only what belongs to Facebook: the panel, form filling, and Mark listed/sold.</p><h2 id="two-pages-one-list">Two pages, one list</h2><p>With both pages open, each holds its own copy of the list in memory. If the manager saved and the Facebook tab later saved its stale copy, it would overwrite the manager's work. So each page listens for storage changes and reloads when the <em>other</em> one writes.</p><p>The obvious implementation is wrong. Each page also receives the event for its own write, so you must ignore those, and the first idea (compare the new value to what's in memory) races if you save twice in quick succession: the first write's event arrives while memory already holds the second, looks "different", and reverts your own change. The fix is to mark writes instead of comparing them. Each page generates a random id once, stamps it onto what it writes, and ignores any change carrying its own stamp:</p><pre><code class="language-js">await chrome.storage.local.set({ [DATA_KEY]: { headers, rows, by: SESSION }, [META_KEY]: meta });
// ...
if (d &amp;&amp; d.by !== SESSION &amp;&amp; d.headers) { headers = d.headers; rows = d.rows || []; changed = true; }
</code></pre><p>A known limit: if the same item is edited in both places at once, the last save wins, and a reload triggered by the other page can close an open edit form.</p><h2 id="what-this-adds-up-to">What this adds up to</h2><p>The manager made loading a batch bearable, and refactoring for it left <code>content.js</code> smaller and more focused. The two decisions I'd keep are the plain shared script (the right size of solution for a project with no build step) and marking writes instead of comparing values, which turned an intermittent race into a non-issue.</p><hr><p>Previous: <a href="https://ghost.atathome.me/listing-helper-from-a-spreadsheet-to-listings/">← From a spreadsheet to listings</a> · Next: <a href="https://ghost.atathome.me/listing-helper-photos-that-dont-lag-or-vanish/">Photos that don't lag or vanish →</a> · Back to <a href="https://ghost.atathome.me/tag/building-marketplace-listing-helper/">series index</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: Periods, charts, and a phone-sized UI - Part 13]]></title><description><![CDATA[~9 min read

With real categories (post 12) the Home and Transactions pages finally had something worth slicing. This post covers the next batch of changes, mostly 30 September and 1 October: choosing a reporting window, charting balances over time, making the whole app usable on a phone, and a surprisingly instructive detour through deleting a transaction. The theme is that each change started as the obvious implementation and had to be corrected once it met real data.


Rolling windows instead]]></description><link>https://brightbot.co.uk/periods-charts-and-a-phone-sized-ui/</link><guid isPermaLink="false">Ghost__Post__6ad488c81df6faba865569bc</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Tue, 10 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1666875753105-c63a6f3bdc86?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fENoYXJ0c3xlbnwwfHx8fDE3OTIzMTY4NDl8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1666875753105-c63a6f3bdc86?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fENoYXJ0c3xlbnwwfHx8fDE3OTIzMTY4NDl8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: Periods, charts, and a phone-sized UI - Part 13"/><p><em>~9 min read</em></p><p>With real categories (<a href="https://ghost.atathome.me/rule-based-categorisation/">post 12</a>) the Home and Transactions pages finally had something worth slicing. This post covers the next batch of changes, mostly 30 September and 1 October: choosing a reporting window, charting balances over time, making the whole app usable on a phone, and a surprisingly instructive detour through deleting a transaction. The theme is that each change started as the obvious implementation and had to be corrected once it met real data.</p><h2 id="rolling-windows-instead-of-calendar-months">Rolling windows instead of calendar months</h2><p>Until now "this month" was literal: income and spending for the current calendar month against the previous one. The commit message for the user-configurable categories change (from <a href="https://ghost.atathome.me/rule-based-categorisation/">post 12</a>) records the problem - the chart "was only ever showing 1-2 categories because it was scoped to the current calendar month, and most already-categorised spending was dated in earlier months." Early in a month, a calendar view is nearly empty; late in one it's flattering. The month boundary, not my spending, was driving what I saw.</p><p>A follow-up replaced the framing with a "Last 30 / 60 / 90 days" selector on Home. The API change is the interesting part. Both <code>GET /api/transactions/summary</code> and <code>GET /api/categories/spending</code> now take a <code>days</code> parameter and compare the current window against the <strong>equal-length window immediately before it</strong>:</p><pre><code class="language-python">today = date.today()
end = today + timedelta(days=1)
start = today - timedelta(days=days - 1)
previous_end = start
previous_start = start - timedelta(days=days)
</code></pre><p>Two adjacent, equal-length windows is what makes the "vs previous N days" delta honest. Compare a 60-day window to a 30-day one and every delta would be a lie; derive both from the same <code>days</code> and the comparison is apples-to-apples whichever period is selected. The endpoint also rejects values outside an allowed set (<code>ALLOWED_SUMMARY_WINDOWS</code>) rather than accepting an arbitrary integer, which keeps the UI's three options and the API's validation from drifting apart. The same commit adds a matching date filter to the Transactions page (this month so far, last 60, last 90 days), and drops the separate always-90-days spending card that the categories change had added, since the selector now covers it.</p><h2 id="balance-history-the-chart-you-can-only-build-going-forward">Balance history: the chart you can only build going forward</h2><p>The <code>home page charts of account balances over time</code> commit adds a line chart per account. There's a catch built into the idea: nothing records historic balances. TrueLayer reports the <em>current</em> balance, so a history only exists if I start saving snapshots. So the commit adds an <code>account_balance_history</code> table, keyed on <code>(bank, account_id, date)</code>, written by <code>save_accounts()</code> on every sync and by the manual-account functions whenever a balance is set.</p><p>The write uses an upsert, so a second sync on the same day moves that day's point rather than piling up near-duplicates:</p><pre><code class="language-sql">INSERT INTO account_balance_history (bank, account_id, date, balance)
VALUES (:bank, :account_id, :date, :balance)
ON CONFLICT (bank, account_id, date) DO UPDATE SET balance = excluded.balance
</code></pre><p>The endpoint's docstring owns the limitation: "Builds up over time; there's no backfill for balances from before this existed." The UI says the same thing to the viewer - an account with fewer than two points shows "Not enough history yet - check back after the next sync" rather than an empty axis. A chart that can't exist yet should say so.</p><p>Two design choices are worth recording. The line colour follows the same good/bad split as everywhere else on the page - green for accounts, red for debts - rather than a per-account hue, because each chart is a single series: "there's no identity to encode, only the same credit/debt status shown everywhere else." And this is where <a href="https://ghost.atathome.me/building-the-frontend/">post 5</a>'s "no chart library" stance expired: for time-series with a tooltip and axes, hand-built <code>&lt;div&gt;</code> bars stopped being the cheaper option, so the commit adds <code>recharts</code>. The category bars stayed <code>&lt;div&gt;</code>s.</p><p>One unglamorous consequence: jsdom has no layout engine, so every element measures 0×0 and Recharts' <code>ResponsiveContainer</code> never reports a size - the charts would silently render nothing in every test. The commit adds a <code>ResizeObserver</code> stub to the test setup that fires once with a fixed size, and its comment explains exactly that, because the failure mode is a test that passes while asserting nothing.</p><p>A later change fixed how debt reads on these charts. A card's balance is stored negative (<a href="https://ghost.atathome.me/seeing-everything-in-one-place/">post 11</a>), so its line fell as the debt grew - which looks like good news. Debt accounts now plot the amount <em>owed</em>, so the line rises as the debt does, and the tooltip says "Owed" instead of "Balance". The account list and the charts also share one ordering - cash and savings first, then cards and other debt - using a stable sort, so each group keeps the order the API returned.</p><h2 id="filters-that-survive-a-trip-to-settings">Filters that survive a trip to Settings</h2><p>The <code>make transaction filters local storage</code> commit came from a small, real annoyance: add a rule in Settings, come back to Transactions, and the filters I'd set were gone. The fix stores them in <code>localStorage</code> - as <em>one</em> object rather than five keys, so the whole filter set restores atomically.</p><p>There's a subtle bug the commit's own comment records, and it's a good one. Transactions already had an effect that clears the account filter if it doesn't belong to the chosen bank. But a filter restored from storage is set <em>before</em> the transactions have loaded, so the list of valid accounts is momentarily empty and the restored filter looks invalid for one render - and gets wiped before the data it belongs to has arrived. The fix is to gate that cleanup on <code>loading</code>. Persisted state plus a "clean up stale state" effect is a classic way to lose data on first render; the cleanup has to know whether it's judging against real data or not-yet-loaded data. (All access is wrapped in <code>try/catch</code>, because storage can be unavailable in private browsing; the filters then just don't persist.)</p><h2 id="deleting-a-transaction-twice">Deleting a transaction, twice</h2><p>The <code>add hide transactions</code> commit added a way to remove a transaction - typically a duplicate, since the de-dup key from <a href="https://ghost.atathome.me/from-script-to-service/">post 4</a> only catches <em>exact</em> <code>(bank, id)</code> repeats, and a bank that sends the same payment twice under different ids gets through. The first version simply deleted the row, and its docstring made a claim: "A later sync's INSERT OR IGNORE won't resurrect it unless the bank re-sends that same <code>(bank, id)</code> pair."</p><p>That claim has the bug in it. The nightly sync <em>does</em> re-fetch a window of recent history, and <code>INSERT OR IGNORE</code> only skips a row if it's already there. Delete the row and the next sync dutifully puts it back. The right fix, <code>soft delete transactions</code>, is to <strong>keep the row but mark it</strong>:</p><pre><code class="language-python">conn.execute(
    "UPDATE transactions SET is_deleted = 1, deleted_at = ? WHERE bank = ? AND id = ? AND is_deleted = 0",
    (datetime.now().isoformat(), bank, txn_id),
)
</code></pre><p>The row stays, so the primary key still exists, so <code>INSERT OR IGNORE</code> still skips it - the de-dup mechanism now protects the deletion instead of undoing it. <code>list_transactions()</code> filters <code>WHERE t.is_deleted = 0</code>, so categorisation, the summary and the frontend all treat it as gone. Two columns were added with the usual <code>PRAGMA table_info</code> guard, and pre-existing rows default to not-deleted. The earlier docstring was rewritten to describe what the code actually does.</p><h2 id="a-phone-sized-ui">A phone-sized UI</h2><p>The same commit made the whole app usable on a phone: a global <code>box-sizing</code> reset, responsive nav, cards, filters and forms below 640px, and a horizontally scrollable wrapper around the Transactions table rather than squeezing every column into unreadable wrapped text. The most useful part was how it was found: by looking at real mobile screenshots, which turned up two bugs no desktop review would have - a negative total splitting its minus sign onto its own line, and Edit/Remove button pairs wrapping independently and stranding "Remove" alone on a row. Both are the kind of thing you only find by actually looking.</p><p>A second pass, after using it on a real phone, was CSS only, and mostly about fingers rather than layout:</p><ul><li>Inputs and selects are 16px, because iOS Safari zooms the whole page in when a smaller field gets focus.</li><li>Buttons, nav links and inputs have a 44px minimum touch target, and checkboxes and colour swatches are bigger.</li><li>Inline edit forms put every control on its own full-width line, with the buttons sharing the last one.</li><li>A tall modal - the bank picker, or a form with the keyboard open - scrolls inside itself (<code>max-height: calc(100dvh - 2rem)</code>) instead of running off the bottom of the screen.</li></ul><hr><p>Previous: <a href="https://ghost.atathome.me/rule-based-categorisation/">← Rule-based categorisation</a> · Next: <a href="https://ghost.atathome.me/hargreaves-lansdown/">Hargreaves Lansdown, with no API →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[House-move inventory: The SPA: small pieces, no UI library - Part 5]]></title><description><![CDATA[~8 min read

The web app is how we actually use this: standing in a half-packed bedroom with a phone, typing "duvet" into a box. That use case set the design priorities more than any architecture diagram did - fast entry, big touch targets, and nothing that needs a laptop.

It's a React + Vite + TypeScript single-page app in web/. No server-side rendering, no shared code with the Python side. It talks to the API over JSON and that's all.


Three conventions that carry the weight

1. One file tal]]></description><link>https://brightbot.co.uk/the-spa-small-pieces-no-ui-library/</link><guid isPermaLink="false">Ghost__Post__6ae5babb1df6faba86556b4e</guid><category><![CDATA[Building Inventory System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Mon, 09 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1610986603166-f78428624e76?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDV8fGZyb250ZW5kfGVufDB8fHx8MTc5MzUyNzU2MXww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1610986603166-f78428624e76?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDV8fGZyb250ZW5kfGVufDB8fHx8MTc5MzUyNzU2MXww&ixlib=rb-4.1.0&q=80&w=2000" alt="House-move inventory: The SPA: small pieces, no UI library - Part 5"/><p><em>~8 min read</em></p><p>The web app is how we actually use this: standing in a half-packed bedroom with a phone, typing "duvet" into a box. That use case set the design priorities more than any architecture diagram did - fast entry, big touch targets, and nothing that needs a laptop.</p><p>It's a React + Vite + TypeScript single-page app in <code>web/</code>. No server-side rendering, no shared code with the Python side. It talks to the API over JSON and that's all.</p><h2 id="three-conventions-that-carry-the-weight">Three conventions that carry the weight</h2><p><strong>1. One file talks HTTP.</strong> <code>web/src/api.ts</code> is the only module that calls <code>fetch</code>. It's a typed client: every endpoint is a method, every response type is declared next to it, and money stays a string. When an API field changes, the TypeScript compiler (<code>npm run build</code> runs <code>tsc --noEmit</code>) points at every affected screen.</p><p><strong>2. One hook for fetching.</strong> <code>useAsync(fn, deps)</code> returns <code>{data, loading, error, reload}</code>. That's the whole data layer - no global store, no caching library. A page that changes something calls <code>reload()</code>. It's crude, and for a two-user app it is exactly enough.</p><p><strong>3. Dialogs are a native <code>&lt;dialog&gt;</code>.</strong> The <code>&lt;Modal&gt;</code> component wraps <code>showModal()</code> - Esc, backdrop and focus trapping come from the browser, with no dependency. The one wrinkle is jsdom, which doesn't implement the modal methods, so <code>src/test/setup.ts</code> carries a tiny shim. There was also a subtle React bug: StrictMode double-invokes mount effects (<code>showModal</code> → cleanup <code>close</code> → <code>showModal</code>), and the <code>close</code> event from that cleanup would bubble up and unmount the modal on open. A <code>programmatic</code> ref suppresses the event when <em>we</em> are the ones closing it.</p><h2 id="fast-entry-versus-complete-entry">Fast entry versus complete entry</h2><p>The most-used control is the add-item row on a box: a name, a quantity and an <strong>Add</strong> button. It posts just <code>{name, quantity}</code>. Everything else about an item - values, purchase date, dimensions, fragile, flat-pack - is optional, and a <strong>More fields…</strong> button opens the full <code>&lt;ItemForm&gt;</code> in a modal, pre-filled with whatever you'd already typed.</p><p>That split came from using it. The first version put every field inline in the table row, which made the items table wider than a phone and the inline editor overflow its container. Phase 3.21 pulled the form into a modal, shared between <strong>Edit</strong> (per row) and <strong>New item</strong>, and left the read row clean.</p><h2 id="phones-properly">Phones, properly</h2><p>Phase 3.28 was the mobile pass, and it's a list of small things that each mattered:</p><ul><li>Every <code>table.grid</code> sits in a <code>.table-scroll</code> wrapper (<code>overflow-x: auto</code>), so a wide table scrolls <em>inside its panel</em> instead of breaking the page.</li><li>The <code>.row</code> pattern (heading plus actions, used on nearly every panel header) wraps below 640px.</li><li>Form inputs go to 16px on small screens. At the 15px body default, iOS Safari zooms the whole page when you focus a field. This is the classic one, and the fix is a single CSS rule.</li><li>Small action buttons got bigger touch targets.</li><li>The photo input has <code>capture="environment"</code>, which hints a phone browser to open the camera straight away (post 7).</li></ul><p>The note I wrote against the phase says "no component or data changes - CSS plus wrapping <code>&lt;div className="table-scroll"&gt;</code>". Most mobile work is like that.</p><h2 id="theme-without-a-flash">Theme without a flash</h2><p>Dark mode is three-way (System / Light / Dark) in the top bar, persisted to <code>localStorage</code> and applied via <code>data-theme</code> on <code>&lt;html&gt;</code>. A small inline script sets the attribute before first paint so the page never flashes the wrong theme. The CSS defines tokens on <code>:root</code> for light, and redefines them in two places for dark - the <code>prefers-color-scheme</code> media query guarded by <code>:root:not([data-theme="light"])</code>, and an explicit <code>[data-theme="dark"]</code> - so "System" and a forced choice both work.</p><p>Later the toggle moved into Settings to declutter the top bar.</p><h2 id="testing-the-front-end">Testing the front end</h2><p>Phase 3.12 added Vitest, Testing Library and jsdom, with test files next to the code. Coverage thresholds live in <code>vite.config.ts</code> and ratchet up; at the start, product code was only ~43% covered, and every phase since has had to hold the floor. The project now has 170-odd web tests and the CI job posts a per-file coverage table on pull requests.</p><p>One lesson from a dependency sweep (Phase 3.25, every package to its latest major in stages, so a failure points at a specific pair): an assertion that "always passed" was racing an effect, and React 19's timing finally exposed it. It's now wrapped in its own <code>waitFor</code>. If a test passes by timing luck, a framework upgrade will find it for you.</p><p>Next: the part of this project that's most likely to hurt you at 11pm - changing a database schema that already has data in it.</p><hr><p>Previous: <a href="https://ghost.atathome.me/a-rest-api-whose-docs-cant-go-stale/">← A REST API whose docs can't go stale</a> · Next: <a href="https://ghost.atathome.me/schema-migrations-with-pragma-user-version/">Schema migrations with PRAGMA user_version →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Jenkins shared library: Why a shared library - Part 1]]></title><description><![CDATA[~5 min read

Most of my projects have a Jenkinsfile, and over time they've started to look alike. The finance system, the inventory system and the identity system each carry their own copy of a Sync blog stage - the one that publishes the project's blog/*.md posts to Ghost. The three copies are the same block of Groovy: a when { branch 'main' } guard, a catchError that marks the stage UNSTABLE instead of failing the build, two Ghost credentials, and a small shell function that runs the blog-sync]]></description><link>https://brightbot.co.uk/jenkins-shared-lib-why-a-shared-library/</link><guid isPermaLink="false">Ghost__Post__6aef1e881df6faba86556c43</guid><category><![CDATA[Building Jenkins Shared Library]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sun, 08 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1693917000983-3b48d0deff74?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDh8fGF1dG9tYXRpbmd8ZW58MHx8fHwxNzk0MjM5OTgyfDA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1693917000983-3b48d0deff74?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDh8fGF1dG9tYXRpbmd8ZW58MHx8fHwxNzk0MjM5OTgyfDA&ixlib=rb-4.1.0&q=80&w=2000" alt="Jenkins shared library: Why a shared library - Part 1"/><p><em>~5 min read</em></p><p>Most of my projects have a Jenkinsfile, and over time they've started to look alike. The finance system, the inventory system and the identity system each carry their own copy of a <code>Sync blog</code> stage - the one that publishes the project's <code>blog/*.md</code> posts to Ghost. The three copies are the same block of Groovy: a <code>when { branch 'main' }</code> guard, a <code>catchError</code> that marks the stage UNSTABLE instead of failing the build, two Ghost credentials, and a small shell function that runs the <code>blog-sync</code> tool at a pinned release tag, first to sync content and then to schedule it.</p><p>Copying a stage into a new project is quick. The cost shows up later. When I bump the pinned <code>blog-sync</code> version, that's one edit per repository, and it's easy to miss one. When I fix a mistake in the shell snippet, the same applies. The copies drift, and nothing tells me they have.</p><p>A Jenkins shared library is the standard answer: a separate Git repository that Jenkins loads into every pipeline that asks for it, so shared logic lives in one place and the Jenkinsfiles shrink to a call.</p><h2 id="the-three-folders">The three folders</h2><p>A library has a fixed layout, and each folder has one job:</p><p>| Folder | What goes there | How it's used | |---|---|---| | <code>vars/</code> | Steps and whole-pipeline templates | Called directly: <code>sayHello()</code> | | <code>src/</code> | Groovy classes and helpers | <code>import</code> them | | <code>resources/</code> | Templates and scripts bundled with the library | <code>libraryResource('...')</code> |</p><p>The file name in <code>vars/</code> is the step name, so <code>vars/syncBlog.groovy</code> becomes <code>syncBlog(...)</code> in a Jenkinsfile. Classes in <code>src/</code> follow normal Groovy package rules: the folder path must match the <code>package</code> line. Files in <code>resources/</code> are read as strings.</p><h2 id="starting-from-a-scaffold">Starting from a scaffold</h2><p>I didn't start with the blog stage. The first commit after the docs was a small scaffold with one working example of each folder, so that I'd be extending something I'd seen run rather than something I'd only read about:</p><ul><li><code>sayHello</code>, the simplest possible step.</li><li><code>standardPipeline</code>, a whole declarative pipeline (checkout, build, test) configured by a map, so a team's Jenkinsfile can be three lines.</li><li><code>notifyBuild</code>, a step that combines a class from <code>src/</code> with a template from <code>resources/</code>.</li></ul><p>Two things in the docs I wrote alongside it are worth repeating here, because they're the ones that bite later:</p><ul><li><strong>Release discipline.</strong> A project that loads the library from <code>main</code> gets every change immediately, which is exactly what you don't want for a change to something every pipeline uses. The answer is to tag releases and let important pipelines pin a version: <code>@Library('bb-jenkins-shared-lib@v1.0.0') _</code>.</li><li><strong>Classes in <code>src/</code> must be <code>Serializable</code>.</strong> Pipelines pause and resume by serialising their state, and an object that can't be serialised across a step fails with <code>NotSerializableException</code>.</li></ul><h2 id="whats-next">What's next</h2><p>The scaffold works, but its examples are placeholders. The next post replaces one with the real thing: pulling the <code>Sync blog</code> stage out of the Jenkinsfiles and into the library.</p><hr><p>Next: <a href="https://ghost.atathome.me/jenkins-shared-lib-extracting-the-sync-blog-stage/">Extracting the Sync blog stage →</a> · Back to <a href="https://ghost.atathome.me/tag/building-jenkins-shared-library/">series index</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Marketplace Listing Helper: From a spreadsheet to listings - Part 4]]></title><description><![CDATA[~6 min read

With the importer working, I fed it the real thing: a spreadsheet of Warhammer stock called warhammer-items.csv. It did not import cleanly, and the reasons are a good tour of what "my data" looks like next to what a tool expects.


What the sheet looked like

Nine columns: Item, Brand, Range, Faction, Status, Quantity, Retail, Avg eBay Sold, Market vs Retail (£). It was a stock-take, not a set of listings. Three things stood in the way.

 1. No price column. The importer looks for p]]></description><link>https://brightbot.co.uk/listing-helper-from-a-spreadsheet-to-listings/</link><guid isPermaLink="false">Ghost__Post__6ae71f981df6faba86556bed</guid><category><![CDATA[Building Marketplace Listing Helper]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sun, 08 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1586448681913-2fc1b29c5cca?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDIxfHxzcHJlYWRzaGVldHxlbnwwfHx8fDE3OTM1Mjc2OTN8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1586448681913-2fc1b29c5cca?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDIxfHxzcHJlYWRzaGVldHxlbnwwfHx8fDE3OTM1Mjc2OTN8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Marketplace Listing Helper: From a spreadsheet to listings - Part 4"/><p><em>~6 min read</em></p><p>With the importer working, I fed it the real thing: a spreadsheet of Warhammer stock called <code>warhammer-items.csv</code>. It did not import cleanly, and the reasons are a good tour of what "my data" looks like next to what a tool expects.</p><h2 id="what-the-sheet-looked-like">What the sheet looked like</h2><p>Nine columns: <code>Item, Brand, Range, Faction, Status, Quantity, Retail, Avg eBay Sold, Market vs Retail (£)</code>. It was a stock-take, not a set of listings. Three things stood in the way.</p><ol><li><strong>No price column.</strong> The importer looks for <code>price</code>, <code>asking price</code>, <code>£</code> or <code>price (£)</code>. My sheet had <code>Avg eBay Sold</code> and <code>Retail</code>. Every item would have imported with a blank price.</li><li><strong><code>Status</code> meant something else.</strong> In the sheet it was <code>Built</code> or <code>BNIB</code> (brand new in box). In the extension, <code>status</code> is <code>draft</code>, <code>listed</code> or <code>sold</code>, and the renew logic reads it. Importing as-is would have put model condition where listing state belongs.</li><li><strong>Junk rows.</strong> Thirteen blank rows, then a totals row (<code>£940.00</code>, <code>£950.00</code>, <code>-£154.00</code>) that would have imported as an item.</li></ol><p><code>Item</code> was the one column that already worked: it's an alias for the title.</p><h2 id="a-conversion-script-not-a-looser-importer">A conversion script, not a looser importer</h2><p>I could have taught the importer to guess. I didn't, for the same reason as in part 3: the extension's fields have fixed meanings, and a guess that is wrong 5% of the time silently corrupts a list. Instead a short one-off script reshapes the sheet into the extension's columns and leaves the importer strict:</p><p>| Extension field | Built from | |---|---| | <code>id</code> | generated, 1 to 36, so photo auto-pairing by <code>&lt;id&gt;-*.jpg</code> works | | <code>title</code> | brand + item, quantity if more than 1, then range and faction | | <code>price</code> | <code>Avg eBay Sold</code> with the <code>£</code> removed, used as-is | | <code>condition</code> | <code>BNIB</code> becomes "New", <code>Built</code> becomes "Used - Good" | | <code>description</code> | generated: brand, range, faction, "Brand new in box" or "Built, not painted", quantity | | <code>category</code> | "Toys &amp; Games" | | <code>status</code> | <code>draft</code> |</p><p>The original <code>Status</code> is kept as a <code>Build state</code> column rather than discarded, along with <code>Quantity</code>, <code>Brand</code>, <code>Range</code>, <code>Faction</code> and <code>Retail</code>, because the importer carries unknown columns through. Rows with no item name (the blank rows and the totals row) are skipped, which leaves 36 items.</p><h2 id="titles">Titles</h2><p>Titles were the part I changed my mind about. The first pass gave <code>Warhammer Ushabti x4</code>. But a buyer searching Marketplace for "Tomb Kings" would never find that, and range and faction are exactly what people search for. So the title now reads <code>Warhammer Ushabti x4 - Pre-Sigmar 6th Tomb Kings</code>, and <code>Warhammer Hammerhead - 40k Tau</code>. Where the range and faction are the same word (40k and 40k) it isn't repeated. The longest title is 83 characters, under Facebook's limit of 100, and the script truncates at 100 as a backstop.</p><p>Two small rules were forced by the data: quantities like <code>1 &amp; 6</code> go into the title as <code>x1 &amp; 6</code> rather than being parsed, and a quantity of 1 is left out.</p><h2 id="prices">Prices</h2><p>I took the average eBay sold price as the asking price, as-is, as a first pass. A few items sell for more than retail, such as Settra and the Casket of Souls, so those are worth a second look by hand. Three rows had no status in the sheet at all, so they have no condition, and the editor is the place to set them.</p><h2 id="a-warning-i-wrote-down">A warning I wrote down</h2><p>Because the importer matches rows by <code>id</code> and lets CSV values win, <strong>re-importing a regenerated file overwrites any edits made in the extension</strong> to those items. Changing the title format and regenerating is fine if nothing has been edited yet; once it has, it's safer to patch the few fields that changed than to re-import everything.</p><p>I checked the round trip in Node: import the file, export it, import that, and the output is byte-for-byte identical. That says the CSV code is stable. It does not say anything about how it behaves in Chrome, which I'll be checking by hand.</p><h2 id="what-this-adds-up-to">What this adds up to</h2><p>Converting the sheet outside the tool kept the tool simple and honest. The extension's fields keep their meanings, the odd cases (quantities, missing statuses, a totals row) are handled in a script I can read and re-run, and the original columns survive.</p><hr><p>Previous: <a href="https://ghost.atathome.me/listing-helper-a-list-that-lives-in-the-browser/">← A list that lives in the browser</a> · Next: <a href="https://ghost.atathome.me/listing-helper-a-full-page-manager-without-a-bundler/">A full-page manager, without a bundler →</a> · Back to <a href="https://ghost.atathome.me/tag/building-marketplace-listing-helper/">series index</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Childcare calculator: Term dates, persistence, and small decisions - Part 5]]></title><description><![CDATA[~8 min read

The last stretch of work was less about the core maths and more about making the tool something you'd actually keep using: handling term-time-only funding, remembering your setup, and a handful of small decisions that were easy to get subtly wrong.


Term-time-only funding

Some funded hours only apply during school term. In the holidays you still book the childminder and still pay, but nothing is free. The calculator needed a way to say "these days are eligible, these aren't".

I c]]></description><link>https://brightbot.co.uk/term-dates-and-persistence/</link><guid isPermaLink="false">Ghost__Post__6ae473091df6faba86556b05</guid><category><![CDATA[Building a Childcare Calculator]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sun, 08 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1542587227-8802646daa56?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDh8fHNjaG9vbCUyMHRlcm18ZW58MHx8fHwxNzkzMzU2NzU3fDA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1542587227-8802646daa56?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDh8fHNjaG9vbCUyMHRlcm18ZW58MHx8fHwxNzkzMzU2NzU3fDA&ixlib=rb-4.1.0&q=80&w=2000" alt="Childcare calculator: Term dates, persistence, and small decisions - Part 5"/><p><em>~8 min read</em></p><p>The last stretch of work was less about the core maths and more about making the tool something you'd actually keep using: handling term-time-only funding, remembering your setup, and a handful of small decisions that were easy to get subtly wrong.</p><h2 id="term-time-only-funding">Term-time-only funding</h2><p>Some funded hours only apply during school term. In the holidays you still book the childminder and still pay, but nothing is free. The calculator needed a way to say "these days are eligible, these aren't".</p><p>I chose to let the user enter their <strong>own term date ranges</strong> instead of hardcoding term dates. Term dates differ by council, school and year, and any list I shipped would be wrong for someone. It's the same trade as the bank holidays, except here the data belongs to the user, so it lives in state:</p><pre><code class="language-js">// term dates: { start: 'YYYY-MM-DD', end: 'YYYY-MM-DD' }[]; days outside all ranges
// are still booked &amp; charged in full, just not eligible for free hours
let termRanges = [];
function isInTerm(iso) { return termRanges.some(r =&gt; iso &gt;= r.start &amp;&amp; iso &lt;= r.end); }
</code></pre><p>Comparing ISO date strings with <code>&gt;=</code> works because <code>YYYY-MM-DD</code> sorts lexicographically in date order. No <code>Date</code> objects, no timezone surprises.</p><p>An out-of-term day is <strong>removed from the free-hours pool entirely</strong>, not given a reduced allowance. It's still booked and still charged in full, and it doesn't count towards the week's hours when working out how many free hours to hand out. Otherwise a week with two term days and three holiday days would still try to spend a full week's allowance across all five.</p><h2 id="two-guards-against-surprising-the-user">Two guards against surprising the user</h2><p><strong>The toggle does nothing until there's a range.</strong> With term-time-only turned on and no ranges entered, every day is technically out of term, which would silently zero out all free hours the moment someone ticked the box. So the calculation only restricts when at least one range exists:</p><pre><code class="language-js">const termTimeOnly = termTimeOnlyEl.checked &amp;&amp; termRanges.length &gt; 0;
</code></pre><p>The empty state says so on screen too: "No term dates added yet — free hours won't apply anywhere until you add at least one range."</p><p><strong>Term dates aren't applied outside the selected month.</strong> Part 4 filled in the adjacent-month days of a partial week using the normal schedule. For those days, the code deliberately doesn't check term dates, and says why:</p><pre><code class="language-js">// term dates are deliberately NOT checked here: a term range the user entered
// for this month may simply not yet extend into the adjacent month, and that
// shouldn't be read as "this day is a school holiday"
</code></pre><p>If you've entered September's term and look at September, the Monday and Tuesday from late August aren't covered by any range. Treating them as holidays would quietly cut the first week's funded hours. Bank holidays and tapped exclusions are real facts about a date; absence from a list the user has partly filled in isn't. It's the kind of decision that doesn't show up in a feature list but decides whether the numbers can be trusted.</p><h2 id="remembering-the-setup">Remembering the setup</h2><p>Entering two childminders, five days of hours, rates, a free-hours figure and a set of term dates every visit is a lot of friction for a monthly tool. The fix is <code>localStorage</code>, with no server involved, so the privacy story from <a href="https://ghost.atathome.me/why-a-static-page/">Part 1</a> is unchanged.</p><p>The decision I'm happiest with is what <em>not</em> to save. The selected month and any tapped exclusions are deliberately left out:</p><pre><code class="language-js">// ... The selected month and any tapped calendar exclusions are
// deliberately NOT persisted, so you always land on the current month with a clean slate.
</code></pre><p>Setup is stable across months, but "I ticked the 12th as a sick day" is true for one month in one session. Saving it would make next month's total mysteriously wrong. Opening the page should show the current month with your usual setup.</p><p>There are two other details. Storage can fail, since private browsing, disabled storage and full quotas all throw, so both directions are wrapped in <code>try</code>/<code>catch</code> and fail silently into the defaults:</p><pre><code class="language-js">try {
  localStorage.setItem(STORAGE_KEY, JSON.stringify({ childminders, schedule, termRanges, /* ... */ }));
} catch (e) {
  // private browsing / storage disabled / quota exceeded -- just don't persist
}
</code></pre><p>And loading doesn't trust what it finds. Each field is checked before it's used: the childminder count must be 1 to 4, the schedule must have exactly five entries, term ranges must have string <code>start</code> and <code>end</code>. Anything that doesn't fit is ignored and the default stays. The key is versioned (<code>childcare-calculator-state-v1</code>), so if the shape of the state changes one day, old data can be recognised or discarded rather than misread.</p><p>Saving is hooked in once, not per handler: <code>calculate()</code> runs after every change, so it calls <code>saveState()</code> at the end, and no individual handler has to remember to persist. On startup, <code>loadState()</code> runs before the first <code>refreshAll()</code>, so the page renders from the restored setup.</p><h2 id="small-things">Small things</h2><ul><li><strong>Bank holidays can be turned off.</strong> Some providers charge on bank holidays, so there's a toggle, on by default, that treats them as normal booked days. The note under the calendar changes to say whether they were excluded or still charged.</li><li><strong>Tap a day to exclude it.</strong> The calendar cell is the control, not a separate form. Tapping again brings it back. This was the original reason for not using a spreadsheet.</li><li><strong>A donation link.</strong> A Buy Me a Coffee badge in the README. A free tool that saves a few people some arithmetic every month can afford a small ask.</li></ul><h2 id="what-id-do-next">What I'd do next</h2><ul><li><strong>Move bank holidays out of <code>app.js</code>.</strong> They run out at the end of 2027, and extending a hardcoded set is a chore someone will forget.</li><li><strong>Make <code>calculate()</code> pure.</strong> It currently reads the DOM, does the maths and writes the DOM. Splitting it into "compute a result" and "render a result" would let me test the partial-week cases properly.</li><li><strong>Scotland and Northern Ireland.</strong> The holiday list is England and Wales only.</li><li><strong>Handle more than five days.</strong> Weekend and evening care is ignored entirely.</li></ul><p>The project is a good argument for starting small. Three files, no dependencies, and every feature in this series was a function and a bit of DOM. The hard parts were never the framework. They were what a "week" means at the edge of a month, and who gets the free hours.</p><hr><p>Previous: <a href="https://ghost.atathome.me/weeks-and-partial-weeks/">← Spreading hours across the week</a> · Next: <a href="https://ghost.atathome.me/the-government-top-up/">Doing the top-up maths →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: Rule-based categorisation - Part 12]]></title><description><![CDATA[~10 min read

The category column has been in the transactions table since post 4. For two weeks of commits it held nothing, and the Home page's "Spending by category" chart ran on a constant called SPEND_BY_CATEGORY (post 5). This is the post where that finally became real. It's the biggest single feature in the project so far - the first commit alone is a large one - and most of the interesting decisions are about what not to store.


The shape: three sources, one precedence order

I wanted to]]></description><link>https://brightbot.co.uk/rule-based-categorisation/</link><guid isPermaLink="false">Ghost__Post__6ad488c81df6faba865569b7</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sun, 08 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1429743305873-d4065c15f93e?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDV8fFBhdGhzfGVufDB8fHx8MTc5MjMxNjkyOHww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1429743305873-d4065c15f93e?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDV8fFBhdGhzfGVufDB8fHx8MTc5MjMxNjkyOHww&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: Rule-based categorisation - Part 12"/><p><em>~10 min read</em></p><p>The <code>category</code> column has been in the transactions table since <a href="https://ghost.atathome.me/from-script-to-service/">post 4</a>. For two weeks of commits it held nothing, and the Home page's "Spending by category" chart ran on a constant called <code>SPEND_BY_CATEGORY</code> (<a href="https://ghost.atathome.me/building-the-frontend/">post 5</a>). This is the post where that finally became real. It's the biggest single feature in the project so far - the first commit alone is a large one - and most of the interesting decisions are about what <em>not</em> to store.</p><h2 id="the-shape-three-sources-one-precedence-order">The shape: three sources, one precedence order</h2><p>I wanted to avoid two failure modes. A pure rules system means writing a rule for every Netflix-shaped thing. A pure automatic system means being stuck when it guesses wrong. So a transaction's category comes from three places, in strict order of authority:</p><ol><li><strong>A manual override</strong> on that transaction.</li><li><strong>A keyword rule</strong> I've written.</li><li><strong>A detected subscription</strong> (a heuristic, below).</li><li>Otherwise, <code>Uncategorised</code>.</li></ol><p>That's the whole of <code>resolve_category()</code>:</p><pre><code class="language-python">def resolve_category(transaction, rules, subscription_keys):
    if transaction.get("category"):
        return transaction["category"]
    rule_match = match_rule(transaction, rules)
    if rule_match:
        return rule_match
    if (transaction["bank"], transaction["id"]) in subscription_keys:
        return "Subscriptions"
    return UNCATEGORISED
</code></pre><p>The ordering has a nice property: the heuristic is a <em>fallback</em>, never a verdict. If it wrongly calls something a subscription, I write a rule and the rule wins.</p><h2 id="rules-a-substring-match-and-no-priority-field">Rules: a substring match, and no priority field</h2><p>A rule is a keyword and a category. It matches if the keyword appears, case-insensitively, in the transaction's merchant or description. When several rules match, the <strong>longest keyword wins</strong>, with ties broken by which rule was created first:</p><pre><code class="language-python">best = min(matches, key=lambda rule: (-len(rule["keyword"]), rule["created_at"]))
</code></pre><p>The reasoning is in the docstring: "more specific beats generic (a <code>TESCO EXPRESS</code> rule outranks <code>TESCO</code> for the same transaction)". And the payoff of computing priority from keyword length, rather than storing a priority number, is a sentence I enjoyed writing in the commit message: it avoids "needing a rule-reordering UI". There's no priority to drag around, because specificity <em>is</em> the priority.</p><h2 id="subscriptions-a-heuristic-with-numbers-i-can-defend">Subscriptions: a heuristic with numbers I can defend</h2><p>The subscription detector groups debits by <code>(bank, account, merchant, amount)</code> and flags a group when it has at least three occurrences, each 21-40 days after the last. Every threshold has a reason written next to it:</p><ul><li><strong>Three occurrences</strong> is "the smallest count that's both a meaningful repeat signal and actually reachable" inside the 90-day sync window; two same-amount debits to one merchant is easy to hit by coincidence.</li><li><strong>21-40 days</strong> covers calendar-month variation (28-31 days) plus a few days of direct-debit drift, "without also catching fortnightly or quarterly charges".</li></ul><p>Note the dependency: those numbers are sized around the sync window. (The window later shrank to 30 days for routine syncs - see <a href="https://ghost.atathome.me/making-the-nightly-sync-boring/">post 17</a> - but detection runs over everything stored in the database, which accumulates beyond any single fetch, so it isn't limited by it.)</p><h2 id="never-store-the-answer">Never store the answer</h2><p>The most consequential decision: <strong>categories are computed on every request and never persisted</strong>, except the manual override, which has to be. The commit message gives the reasoning: a personal-scale SQLite database "is cheap enough to recompute over on every request, and it means editing a rule reclassifies existing history immediately with no backfill step."</p><p>I got to confirm that directly in the smoke test, and it's worth quoting because it shows what the design buys: add a "tesco" rule in Settings, and TESCO's row flips from <code>Uncategorised</code> to <code>Groceries</code> with no resync, while Netflix charges - three occurrences, 28-30 days apart - were already showing as <code>Subscriptions</code> before any rule existed. A stored category would have needed a migration for every rule edit. Computing it means a rule change is instant and reversible.</p><p>The cost is that the API has to hand the frontend both values. <code>apply_categories()</code> returns the resolved <code>category</code> and also keeps the raw stored value as <code>category_override</code>, because the UI has to tell "auto-resolved to Bills" apart from "explicitly set to Bills" when it draws the override dropdown.</p><h2 id="categories-become-user-data">Categories become user data</h2><p>The first version had a fixed set of six categories in a Python tuple. A later commit (<code>Make categories user-configurable...</code>) replaced it with a per-user <code>categories</code> table, seeded once with the original six and their colours so existing data didn't change. Two consequences are worth noting.</p><p><strong>Renaming cascades.</strong> Rules and overrides store the category as a plain <em>string</em>, not a foreign key, so renaming "Eating out" has to rewrite every rule and every override that used the old name. A string key was the simple choice, and the cascade is the price.</p><p><strong>Colour follows identity, not rank.</strong> The chart colours come from the validated palette in post 5, which I'd checked for colour-blind distinguishability. The rule I stuck to is that a category's colour comes from a stored <em>slot</em>, not its position in a sorted list - otherwise "Groceries" would change colour whenever it overtook "Bills". Adding categories meant extending the palette beyond the original five hues, and I re-ran the validator script against the app's real surface colours, in light and dark, rather than eyeballing new ones. Slots 1-7 are assignable and slot 8 is reserved for <code>Uncategorised</code>. A later change removed the hard ceiling: once all seven validated colours are taken, a category can use a custom colour from a picker instead, with <code>color_slot</code> and <code>custom_color</code> kept mutually exclusive.</p><h2 id="transfers-arent-spending">Transfers aren't spending</h2><p>Another change fixed a distortion I'd otherwise have lived with. Moving £500 from current to savings isn't income on one side and spending on the other, but a naive sum treats it as exactly that. The fix is an <code>is_transfer</code> flag on a category: transactions that resolve to a flagged category stay fully visible and filterable on the Transactions page, but drop out of the income/outgoings summary and every spending-by-category view. Because that exclusion depends on <em>resolved</em> categories - which come from rules and overrides - it can't be done in raw SQL, so the SQL <code>monthly_summary</code> from <a href="https://ghost.atathome.me/keeping-data-fresh/">post 7</a> was replaced by a Python <code>summarize()</code> that runs after categorisation.</p><h2 id="the-ui-that-makes-rules-cheap-to-write">The UI that makes rules cheap to write</h2><p>A rule system only works if adding a rule is nearly free. Three small UI changes did that:</p><ul><li>Each row on the Transactions page has a category dropdown for the manual override, and a later commit added a category <em>filter</em> built from the categories actually present in the current results - so <code>Uncategorised</code> is filterable, and a category nothing resolves to doesn't clutter the list.</li><li>Rules in Settings are nested under their category, so it's obvious which categories have no rules yet.</li><li>The <code>add quick add rule</code> commit puts a <code>+</code> beside each transaction's category that opens a modal with the keyword pre-filled from the merchant and the category pre-selected. After saving, the page refetches, because the new rule may re-categorise other rows. A follow-up (<code>enable modal for categories</code>) moved the category add/edit forms in Settings into a modal too.</li></ul><h2 id="two-bugs-worth-owning">Two bugs worth owning</h2><p>Another commit fixed a small one that's a common trap: <code>GET /api/categories</code> was returning <code>is_transfer</code> and <code>is_manual</code> as SQLite's raw <code>0</code>/<code>1</code> instead of JSON booleans, because that route had no <code>response_model</code> to coerce them. A response model isn't only documentation - it's the layer that turns a database's idea of a boolean into the API's.</p><p>The same commit added a "Hide Uncategorised" toggle to the Home spending cards, for the common case where the unsorted remainder dwarfs everything you've categorised and flattens the chart.</p><hr><p>Previous: <a href="https://ghost.atathome.me/seeing-everything-in-one-place/">← Seeing everything in one place</a> · Next: <a href="https://ghost.atathome.me/periods-charts-and-a-phone-sized-ui/">Periods, charts, and a phone-sized UI →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[House-move inventory: A REST API whose docs can't go stale - Part 4]]></title><description><![CDATA[~7 min read

With the core in place (post 2), the REST API was the easy bit. FastAPI handlers are about six lines each. The interesting problem, and the one that took more commits than the endpoints themselves, was keeping the documentation true.


The thin layer

inventory.api maps HTTP to service calls:

 * Pydantic request and response models in api/schemas.py, distinct from the core's dataclasses, so the wire format can evolve without touching the domain. Request bodies are extra="forbid": a]]></description><link>https://brightbot.co.uk/a-rest-api-whose-docs-cant-go-stale/</link><guid isPermaLink="false">Ghost__Post__6ae5baba1df6faba86556b49</guid><category><![CDATA[Building Inventory System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sat, 07 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1623282033815-40b05d96c903?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fEFQSXxlbnwwfHx8fDE3OTM1MjQyODd8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1623282033815-40b05d96c903?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fEFQSXxlbnwwfHx8fDE3OTM1MjQyODd8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="House-move inventory: A REST API whose docs can't go stale - Part 4"/><p><em>~7 min read</em></p><p>With the core in place (<a href="https://ghost.atathome.me/a-core-that-knows-nothing-about-http/">post 2</a>), the REST API was the easy bit. FastAPI handlers are about six lines each. The interesting problem, and the one that took more commits than the endpoints themselves, was keeping the <em>documentation</em> true.</p><h2 id="the-thin-layer">The thin layer</h2><p><code>inventory.api</code> maps HTTP to service calls:</p><ul><li>Pydantic request and response models in <code>api/schemas.py</code>, <strong>distinct from the core's dataclasses</strong>, so the wire format can evolve without touching the domain. Request bodies are <code>extra="forbid"</code>: an unknown field is a 422, not silently ignored.</li><li>Domain errors become 404 / 409 / 422 through one mapping.</li><li>Serializers in <code>api/serializers.py</code> do the <code>str(Decimal)</code> conversion, so the money rule from <a href="https://ghost.atathome.me/money-and-an-approximate-euro/">post 3</a> lives in one place.</li><li>Everything lives under <code>/api</code>, except <code>/health</code>, which is the only public route.</li></ul><p>A plain-text contents sheet (<code>GET /boxes/{code}/sheet</code>) came along in Phase 2 as a bonus. It was meant to be the first printable thing; the PDF version (<a href="https://ghost.atathome.me/sheets-labels-and-french/">post 8</a>) came later.</p><h2 id="three-kinds-of-documentation-one-source">Three kinds of documentation, one source</h2><p>FastAPI generates an OpenAPI schema for free, and <code>/docs</code> (Swagger UI) is useful out of the box. But a generated schema is only as good as what you feed it, so Phase 3.22 was about feeding it properly:</p><ul><li>an expanded top-level description,</li><li><code>_OPENAPI_TAGS</code> - one sentence per resource group,</li><li>a <code>summary=</code> and a short docstring on every route,</li><li><code>examples</code> on the create request bodies.</li></ul><p>Then a small script, <code>scripts/dump_openapi.py</code>, writes the schema to <code>docs/openapi.json</code> <strong>without starting a server</strong>. The file is committed, so API changes show up in code review as a diff of the contract. <code>hatch run docs-api</code> also builds a self-contained three-panel HTML reference with <code>@redocly/cli</code>, and <code>/redoc</code> serves the same thing live.</p><h2 id="making-staleness-a-build-failure">Making staleness a build failure</h2><p>Generating a file doesn't help if nobody regenerates it. Two guards close that gap:</p><ol><li><strong>A pre-commit hook</strong> (<code>.githooks/pre-commit</code>, opt-in with <code>git config core.hooksPath .githooks</code>) regenerates <code>docs/openapi.json</code> when you commit.</li><li><strong>A CI job</strong> called <em>api docs</em> regenerates it and fails if the committed copy differs. It <strong>never pushes</strong> - it only fails. That asymmetry is deliberate: a bot silently committing to your branch is a surprise; a red check with a one-line fix (<code>hatch run openapi</code>) is not.</li></ol><p>I've watched this catch me every time I touch a route and forget. The first time was within a day of adding it, which is the best argument for it.</p><p>CI also builds the HTML reference on every run and keeps it as an <code>api-docs</code> artifact. There's a GitHub Pages publish job in <code>ci.yml</code>, commented out - Pages on a private repo needs a paid plan, so for now the artifact is the published form.</p><h2 id="prose-docs-are-the-other-half">Prose docs are the other half</h2><p>The OpenAPI file is the contract, but <code>docs/api.md</code> holds the <em>explanations</em>: what <code>?invoices=true</code> appends, what each filter means, which endpoints are synchronous and which are jobs. The project rule is to keep it in sync with the code, and it's checked by the dullest mechanism possible - I read the diff and ask "did the doc table change?".</p><p>This post's own example is the last feature I shipped. The all-rooms export (<a href="https://ghost.atathome.me/filters-decisions-and-exporting-everything/">post 12</a>) touched one route and one table row in <code>api.md</code>. It's a good test of whether the habit holds: if documenting a feature feels heavy, the feature is probably too big.</p><h2 id="what-id-do-differently">What I'd do differently</h2><p>Pagination: there isn't any. Every list endpoint returns everything. For two people and a few hundred boxes that is the correct amount of engineering; the docs say "no pagination" in so many words so nobody is surprised. If the box count ever reached the tens of thousands I'd revisit it - until then, the absence is a feature.</p><p>Next: the web app that sits on top of it.</p><hr><p>Previous: <a href="https://ghost.atathome.me/money-and-an-approximate-euro/">← Money, currencies and an approximate euro</a> · Next: <a href="https://ghost.atathome.me/the-spa-small-pieces-no-ui-library/">The SPA: small pieces, no UI library →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Marketplace Listing Helper: A list that lives in the browser - Part 3]]></title><description><![CDATA[~7 min read

The extension needs to remember what I'm selling. With no server allowed, the list has to live in the browser, and it has to move to and from a spreadsheet, because that is where I keep my stock. This post is the data model, and the small decisions that keep a CSV and a browser store from fighting each other.


Where it lives

Everything is in chrome.storage.local, under two keys:

 * mlh_data is { headers, rows }: the column names in order, and one object per item.
 * mlh_meta hold]]></description><link>https://brightbot.co.uk/listing-helper-a-list-that-lives-in-the-browser/</link><guid isPermaLink="false">Ghost__Post__6ae71f971df6faba86556be8</guid><category><![CDATA[Building Marketplace Listing Helper]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Fri, 06 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1730382625230-3756013c515c?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fGV4dGVuc2lvbnxlbnwwfHx8fDE3OTM1MzIxOTJ8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1730382625230-3756013c515c?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fGV4dGVuc2lvbnxlbnwwfHx8fDE3OTM1MzIxOTJ8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Marketplace Listing Helper: A list that lives in the browser - Part 3"/><p><em>~7 min read</em></p><p>The extension needs to remember what I'm selling. With no server allowed, the list has to live in the browser, and it has to move to and from a spreadsheet, because that is where I keep my stock. This post is the data model, and the small decisions that keep a CSV and a browser store from fighting each other.</p><h2 id="where-it-lives">Where it lives</h2><p>Everything is in <code>chrome.storage.local</code>, under two keys:</p><ul><li><code>mlh_data</code> is <code>{ headers, rows }</code>: the column names in order, and one object per item.</li><li><code>mlh_meta</code> holds the housekeeping: a count of changes since the last export, when the last export was, the name of the footer template, and the description templates.</li></ul><p>Rows are keyed by the <strong>header names from my own sheet</strong>, not by fixed field names. If my spreadsheet calls a column <code>Asking price</code>, that is what's stored and what's exported. The extension adapts to the sheet instead of the other way round.</p><h2 id="loose-column-matching">Loose column matching</h2><p>That flexibility needs a lookup layer. Code never writes <code>row["title"]</code>. It asks for the logical field <code>title</code>, and <code>headerFor()</code> finds whichever column matches, ignoring case:</p><pre><code class="language-js">const ALIASES = {
  id:    ["id", "sku", "ref", "item id"],
  title: ["title", "name", "item", "item name"],
  price: ["price", "asking price", "£", "price (£)"],
  // ... category, condition, description, photos, status, listed
};
</code></pre><p>Reads and writes go through <code>get(row, "price")</code> and <code>set(row, "price", v)</code>, which also add a column if the sheet doesn't have one yet. It's a few lines, and it means a sheet can use <code>Name</code> or <code>Item</code> or <code>Title</code> and everything still works.</p><h2 id="merging-not-replacing">Merging, not replacing</h2><p>Importing a CSV <em>merges</em> by row key: the <code>id</code>, falling back to the title. CSV values win, with one exception that matters a lot: a blank <code>status</code> or <code>listed</code> in the CSV keeps what the extension already has.</p><p>That exception exists because the two sides know different things. My sheet knows prices and descriptions. The extension knows which items I've marked as listed, and when. Without the rule, re-importing my sheet would wipe every "listed" date and lose track of what needs renewing. With it, I can re-import any time. Columns the extension doesn't know about are carried through untouched and exported again, so nothing in the sheet is lost.</p><p>Status is one of <code>draft</code>, <code>listed</code> or <code>sold</code>. "Mark listed" stamps today's date, and an item listed seven or more days ago is flagged as due a renew (I do the renewing myself, per the rules from part 1).</p><h2 id="a-list-that-lives-in-one-browser-needs-a-backup-nag">A list that lives in one browser needs a backup nag</h2><p>Data in extension storage disappears if the extension is removed or the site data is cleared. So the panel nudges me: after five unexported changes, or any change when it's been a week since the last export, a banner asks me to export a backup. Exporting resets the counter and records the date. It's a tiny feature that is the difference between "the list is safe" and "the list is safe until I tidy my browser".</p><h2 id="photos-are-filenames">Photos are filenames</h2><p>The list stores photo <em>filenames</em>, joined with <code>;</code>, in order, with the first as the cover. A browser extension can't hold on to a file handle between sessions, so at this point I had to reload the photos folder each session. Part 6 is the story of removing that limit.</p><p>Pairing photos to items is mostly automatic. Name them <code>12-1.jpg</code>, <code>12_front.jpg</code> or <code>12.jpg</code> for item 12, or start the filename with the item's title, and the pairing function matches them. Naming photos as I take them makes pairing a single click.</p><h2 id="what-this-adds-up-to">What this adds up to</h2><p>Storing the list was easy. The work was in the seams: loose column names so a real sheet imports, a merge that respects what each side knows, and a backup reminder because the store is private to one browser profile. Each of those is a few lines, and each prevents one specific way of quietly losing data.</p><hr><p>Previous: <a href="https://ghost.atathome.me/listing-helper-filling-in-facebooks-form/">← Filling in Facebook's form</a> · Next: <a href="https://ghost.atathome.me/listing-helper-from-a-spreadsheet-to-listings/">From a spreadsheet to listings →</a> · Back to <a href="https://ghost.atathome.me/tag/building-marketplace-listing-helper/">series index</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Central login service: A two-step login wizard - Part 8]]></title><description><![CDATA[~12 min read

Part 7 closed with "that's the story to date". It wasn't quite. The login page still had one awkward detail from the very first version: a single form with three fields, the last of them labelled "2FA code (only if you have it enabled)". Everyone, including people who have never turned on two-factor, saw a box asking about something that didn't apply to them.

This post turns that form into a small wizard. Step one asks for an email and password. Step two, a code from your authenti]]></description><link>https://brightbot.co.uk/identity-system-a-two-step-login-wizard/</link><guid isPermaLink="false">Ghost__Post__6ae478ed1df6faba86556b2b</guid><category><![CDATA[Building Identity System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Fri, 06 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1551269901-5c5e14c25df7?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fFdpemFyZHxlbnwwfHx8fDE3OTMzODczMTF8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1551269901-5c5e14c25df7?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fFdpemFyZHxlbnwwfHx8fDE3OTMzODczMTF8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Central login service: A two-step login wizard - Part 8"/><p><em>~12 min read</em></p><p>Part 7 closed with "that's the story to date". It wasn't quite. The login page still had one awkward detail from the very first version: a single form with three fields, the last of them labelled <strong>"2FA code (only if you have it enabled)"</strong>. Everyone, including people who have never turned on two-factor, saw a box asking about something that didn't apply to them.</p><p>This post turns that form into a small wizard. Step one asks for an email and password. Step two, a code from your authenticator app, appears only if your account has two-factor on. It's a small change, but the interesting part is the constraint underneath it, because the obvious design doesn't work.</p><h2 id="the-obvious-design-and-why-it-doesnt-work">The obvious design, and why it doesn't work</h2><p>The natural way to build this is a pre-flight check: when someone types their email, ask the server "does this account have 2FA?" and show the code field if so. That's two requests, and the first one is the problem.</p><p>An endpoint that answers "does <code>alex@example.com</code> have 2FA enabled?" before anyone has proved who they are tells a stranger two things: that the account exists, and how well protected it is. That's account enumeration with a bonus. The login endpoint is careful to answer a wrong email and a wrong password identically (<code>incorrect email or password</code>), and a pre-flight check would undo that on purpose.</p><p>So the question can only be asked <em>after</em> the password has been verified. That points at the login call itself, and there I hit the second constraint.</p><h2 id="what-sessionkit-gives-me">What sessionkit gives me</h2><p><code>AuthService.login(email, password, otp=None)</code> does everything in one go:</p><ol><li>Look up the user and verify the password. Failure raises <code>AuthenticationError</code>.</li><li>If the user has confirmed TOTP, check the second factor. A missing code raises <code>OtpRequired</code>; a wrong one raises <code>OtpInvalid</code>.</li><li>Only then create the session and return the token.</li></ol><p>There's no "password verified, code pending" state, and no half-logged-in token to carry from step one to step two. By the rule from Part 1, I shouldn't reimplement password checking in the route handler to get one: rules live in the library.</p><p>That turns out to be fine, because step 2 of <code>login</code> has a useful property. If the password is right and the code is missing, the call fails with <code>OtpRequired</code> <em>before any session exists</em>. So the server can learn "right password, needs a code" for free, and the only thing to fix is how it says so.</p><h2 id="making-the-signal-machine-readable">Making the signal machine-readable</h2><p>Before this change, a password-only login for a 2FA user returned a <code>401</code> with the message <code>enter the 6-digit code from your authenticator app</code>. A client could tell it apart from a wrong password only by matching on that text, which is brittle. A wrong password is also a <code>401</code>, and so is a locked account.</p><p>The fix is a flag in the response body:</p><pre><code class="language-python">try:
    result = auth.login(
        payload.get("email", ""),
        payload.get("password", ""),
        otp=payload.get("otp") or None,
    )
except OtpRequired as exc:
    # The password was right but this account has 2FA on: no session
    # was created. The flag lets the login wizard move to its code
    # step without matching on the message text.
    return JSONResponse(
        status_code=401, content={"detail": str(exc), "otp_required": True}
    )
</code></pre><p>The status is still <code>401</code> and <code>detail</code> is still there, so everything that already calls <code>/api/login</code> keeps working. The flag appears only on this one case. A wrong password has no <code>otp_required</code>, and neither does a wrong code (which stays a <code>422</code>, as <code>OtpInvalid</code> always has; see the <code>_ERROR_STATUS</code> note in Part 3).</p><p>One thing this does leak, and it's worth being plain about it: anyone who knows the correct password for an account can now learn that it has 2FA. That's acceptable. Someone with the password could learn it by getting the "enter your code" message before, and they've already cleared the harder bar.</p><h2 id="the-wizard">The wizard</h2><p>On the frontend, <code>ApiError</code> gained a <code>body</code> so a caller can read more than the message:</p><pre><code class="language-ts">export class ApiError extends Error {
  status: number
  body: Record&lt;string, unknown&gt;

  constructor(status: number, message: string, body: Record&lt;string, unknown&gt; = {}) {
    super(message)
    this.status = status
    this.body = body
  }
}
</code></pre><p><code>Login.tsx</code> then holds a <code>step</code> of <code>'credentials'</code> or <code>'otp'</code>. Step one posts <code>{ email, password, rd }</code>. There are three outcomes:</p><ul><li><strong>Success</strong> (no 2FA on the account): navigate to the server's <code>redirect_to</code>, as before.</li><li><strong><code>otp_required</code></strong>: switch to the code step. No error banner, because nothing went wrong.</li><li><strong>Anything else</strong>: show the message and stay on step one.</li></ul><pre><code class="language-tsx">} catch (err) {
  if (step === 'credentials' &amp;&amp; err instanceof ApiError &amp;&amp; err.body.otp_required === true) {
    setStep('otp')
    setSubmitting(false)
    return
  }
  setError(err instanceof ApiError ? err.message : 'Something went wrong')
  setSubmitting(false)
}
</code></pre><p>Step two shows only the code field, with <code>autoComplete="one-time-code"</code> so phones can offer the code from a text message or password manager, and a line saying a recovery code works too. It posts <code>{ email, password, otp, rd }</code>. A wrong code shows its error and stays put so the user can retry. A <strong>Back</strong> button returns to step one and clears the code and any error.</p><h3 id="the-password-has-to-stay-in-memory">The password has to stay in memory</h3><p>Because the server keeps no pending state, step two must send the password again. It lives in the component's React state between the steps and goes nowhere else: not <code>localStorage</code>, not the URL. When the page navigates away or reloads, it's gone, and the user starts at step one. That's a small cost for not building a server-side "pending login" store that the library doesn't have.</p><h3 id="the-redirect-rule-didnt-move">The redirect rule didn't move</h3><p>The open-redirect guard from Part 1 is untouched. Both steps send the raw <code>rd</code>, the server decides whether it's trusted, and the browser navigates to whatever <code>redirect_to</code> comes back, never to <code>?rd=</code> directly. A two-step flow is exactly where it would be easy to let step two "remember" the <code>rd</code> itself and skip that check, so a test keeps both honest.</p><h2 id="tests">Tests</h2><p>On the backend, the existing 2FA test grew three assertions. A password-only login gets <code>otp_required: true</code> and no cookie; a wrong code gets a <code>422</code> without the flag; a valid code logs in. The wrong-password test now checks the flag is absent.</p><p>On the frontend there are three new cases:</p><ol><li>A user without 2FA signs in from step one and the code field never appears.</li><li>A 2FA user reaches step two with no error showing, enters a wrong code (error, still on step two), then a right one, and the final request contains the email, password <em>and</em> code.</li><li><strong>Back</strong> returns to the password form and the code field is gone.</li></ol><h2 id="what-id-still-change">What I'd still change</h2><p><strong>A real pending-login state, in the library.</strong> Re-sending the password works but it's a second password check and a second round of Argon2. If sessionkit grew a "password verified" token with a short lifetime, the second step wouldn't need the password at all. It belongs there, with a release, not here.</p><p><strong>Rate limiting on the password step.</strong> The lockout protects the six-digit code, but nothing slows down guessing at step one. That gap has been documented since Part 1, and the wizard doesn't change it.</p><hr><p>That's the login page doing what its label always claimed. The code field is now there only for the people it's for.</p><p>Previous: <a href="https://ghost.atathome.me/identity-system-polish-and-creating-users-from-the-browser/">← Polish, and creating users from the browser</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Childcare calculator: Spreading hours across the week, and the partial-week problem - Part 4]]></title><description><![CDATA[~9 min read

Splitting free hours gives each childminder a weekly allocation. This post is about turning that into the day-by-day numbers on the calendar, adding a weekly breakdown, and fixing the most interesting bug in the project: a month rarely starts on a Monday.


Free hours are weekly, the calendar is daily

The first version applied each week's free hours chronologically: Monday's hours were free until the allowance ran out, then the rest were paid. The totals were right, but the calenda]]></description><link>https://brightbot.co.uk/weeks-and-partial-weeks/</link><guid isPermaLink="false">Ghost__Post__6ae473081df6faba86556b00</guid><category><![CDATA[Building a Childcare Calculator]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Fri, 06 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1692699203646-bbc19c8c8c22?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fHNwbGl0JTIwd2Vla3xlbnwwfHx8fDE3OTMzNTY3MzB8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1692699203646-bbc19c8c8c22?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fHNwbGl0JTIwd2Vla3xlbnwwfHx8fDE3OTMzNTY3MzB8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Childcare calculator: Spreading hours across the week, and the partial-week problem - Part 4"/><p><em>~9 min read</em></p><p><a href="https://ghost.atathome.me/splitting-free-hours/">Splitting free hours</a> gives each childminder a weekly allocation. This post is about turning that into the day-by-day numbers on the calendar, adding a weekly breakdown, and fixing the most interesting bug in the project: a month rarely starts on a Monday.</p><h2 id="free-hours-are-weekly-the-calendar-is-daily">Free hours are weekly, the calendar is daily</h2><p>The first version applied each week's free hours <strong>chronologically</strong>: Monday's hours were free until the allowance ran out, then the rest were paid. The totals were right, but the calendar looked odd. With 21.5 free hours spread over four 8.5-hour days, you'd see Monday and Tuesday fully free, Wednesday partly free and Thursday fully paid.</p><p>That's arithmetically fine and useless for a sanity check. You can't glance at the calendar and tell whether the figures look right. I changed it to spread free hours as evenly as possible across the days, in half-hour units, and the same example now reads 5, 5.5, 5.5, 5.5.</p><h2 id="spreadeven"><code>spreadEven</code></h2><p>The function takes a total and a cap for each day, and works in two passes.</p><p>First, a water-filling loop: give every open day an equal share, and if a day hits its cap, close it and share what's left among the rest. That handles days with different lengths.</p><p>Second, rounding. Real childminders bill in sensible units, and 5.375 hours on a calendar cell is noise, so shares are rounded <strong>down</strong> to half-hour units. Rounding down loses a little, so the leftover units get handed back one at a time:</p><pre><code class="language-js">// hand out the leftover half-hour units one at a time, round-robin from the last
// day backwards, so no single day soaks up the whole remainder
let leftoverUnits = Math.round((total - roundedSum) / unit);
let i = count - 1;
let attempts = 0;
while (leftoverUnits &gt; 0 &amp;&amp; attempts &lt; count * 1000) {
  if (share[i] + unit &lt;= capArr[i] + 1e-9) {
    share[i] += unit;
    leftoverUnits--;
  }
  i = (i - 1 + count) % count;
  attempts++;
}
</code></pre><p>Working through 21.5 over four 8.5-hour days: an equal share is 5.375, which rounds down to 5 each, totalling 20. That leaves 1.5 hours, or three units, which go to Thursday, Wednesday and Tuesday in that order. Result: <code>[5, 5.5, 5.5, 5.5]</code>, which sums to 21.5.</p><p>Why start from the <em>last</em> day? It's a small judgement call: if one day has to be a half-hour lighter, I'd rather it was Monday than Friday, and it gives a stable result. The <code>attempts</code> guard is the same belt-and-braces idea as before: the loop cannot run forever even if the caps leave no room.</p><h2 id="a-weekly-breakdown">A weekly breakdown</h2><p>While I was in there, the page gained a <strong>weekly breakdown</strong> (funded hours, and shortly after, unfunded hours and cost for each week), shown after the calendar. Weeks are grouped by their Monday, so a month that spans five calendar weeks shows five, labelled "Week 1" to "Week 5" with the date range each covers, like "15–19 Sep".</p><p>The unfunded-hours row came in a follow-up commit because I realised the breakdown showed what you <em>didn't</em> pay for and left you to subtract to see what you did. One more row, three more lines of code.</p><h2 id="the-partial-week-bug">The partial-week bug</h2><p>Here's the case that broke the model. Suppose a month starts on a Wednesday. The first calendar week in that month has only Wednesday to Friday: three days.</p><p>The calculation grouped booked days by week and gave each week <code>min(free hours per week, hours booked that week)</code> free hours. With three 8.5-hour days that's 25.5 booked hours, which is under a 30-hour allowance. <strong>The entire first week came out free.</strong></p><p>But it isn't really a three-day week. It's a <em>standard</em> week where Monday and Tuesday happen to belong to last month. The funded entitlement is weekly, so for the other half of that week the child was in care and the free hours were being used up on Monday and Tuesday in the <em>previous</em> month's calculation. The month-boundary week was getting a whole fresh allowance for a fraction of the days. My commit message put it as "3 days is 30 hours": the tool was treating a three-day stub as if it earned the full 30.</p><h2 id="the-fix-fill-in-the-rest-of-the-week">The fix: fill in the rest of the week</h2><p>The correct model is that a week is a week, no matter which month's page you're looking at. So for each week touched by the month, the calculation builds the <strong>full Monday-to-Friday list</strong>, using the real day records for days inside the month and the normal weekly schedule for days outside it:</p><pre><code class="language-js">for (let offset = 0; offset &lt; 5; offset++) {
  const d = new Date(monday);
  d.setDate(monday.getDate() + offset);
  if (d.getFullYear() === year &amp;&amp; d.getMonth() === monthIndex) {
    // a real day in this month
    ...
  } else {
    // a day in the adjacent month: use the normal scheduled day
    const entry = schedule[offset];
    const dIso = isoDate(d.getFullYear(), d.getMonth(), d.getDate());
    const skip = (excludeHolidays &amp;&amp; BANK_HOLIDAYS.has(dIso)) || excludedDates.has(dIso);
    if (entry &amp;&amp; entry.cm &gt;= 0 &amp;&amp; entry.cm &lt; n &amp;&amp; entry.hours &gt; 0 &amp;&amp; !skip) {
      fullDays.push({ cm: entry.cm, hours: entry.hours, rec: null });
    }
  }
}
</code></pre><p>Those full-week days feed <code>splitFree</code> and <code>spreadEven</code>, so the weekly allocation is worked out on the whole week. Then only the days that are actually in the selected month get shown and charged: records for adjacent-month days have <code>rec: null</code> and are skipped when results are written back.</p><p>The adjacent month's own page works out its days independently, with the same full-week logic, so a week split across two months ends up with one allowance shared between them rather than doubled.</p><p>Bank holidays and tapped exclusions still apply to the out-of-month days, since those are real. Term dates are a different story, and that's a design decision worth its own post.</p><h2 id="testing-this-without-a-test-suite">Testing this without a test suite</h2><p>There's no test framework, and the cases that matter are the boundaries: months starting on each weekday, months ending mid-week, and months where the first or last week contains a bank holiday. The month picker makes those quick to eyeball by flipping through months and watching the weekly breakdown, but that's manual. If this grows, a <code>calculate()</code> that returns data instead of writing to the DOM would be the first refactor, since it would make these cases testable.</p><hr><p>Previous: <a href="https://ghost.atathome.me/splitting-free-hours/">← Splitting free hours</a> · Next: <a href="https://ghost.atathome.me/term-dates-and-persistence/">Term dates, persistence, and small decisions →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: Seeing everything in one place - Part 11]]></title><description><![CDATA[~9 min read

By post 8 the app could pull balances and transactions from every linked bank. What it couldn't do was make that data legible - or hold the parts of my financial picture that no bank API will ever give me, like a car loan. This post is a run of smaller commits, spread over 28-29 September, that were each about the same thing: making the Accounts and Home pages answer "what do I actually have, and what do I owe?" without squinting.

It's less a single design story than five related f]]></description><link>https://brightbot.co.uk/seeing-everything-in-one-place/</link><guid isPermaLink="false">Ghost__Post__6ad488c71df6faba865569b2</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Fri, 06 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1453728013993-6d66e9c9123a?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fFZpZXd8ZW58MHx8fHwxNzkyMzE3MTkwfDA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1453728013993-6d66e9c9123a?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fFZpZXd8ZW58MHx8fHwxNzkyMzE3MTkwfDA&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: Seeing everything in one place - Part 11"/><p><em>~9 min read</em></p><p>By <a href="https://ghost.atathome.me/balances-and-disconnecting-banks/">post 8</a> the app could pull balances and transactions from every linked bank. What it couldn't do was make that data <em>legible</em> - or hold the parts of my financial picture that no bank API will ever give me, like a car loan. This post is a run of smaller commits, spread over 28-29 September, that were each about the same thing: making the Accounts and Home pages answer "what do I actually have, and what do I owe?" without squinting.</p><p>It's less a single design story than five related fixes, ordered roughly by how much they taught me.</p><h2 id="aliases-names-the-bank-chose-arent-names-id-choose">Aliases: names the bank chose aren't names I'd choose</h2><p>Banks label accounts however their own systems do. The <code>add account alias</code> commit lets me rename any account on the Accounts page, and the interesting part is <em>where the alias is stored</em>:</p><pre><code class="language-python">ACCOUNT_ALIASES_SCHEMA = """
CREATE TABLE IF NOT EXISTS account_aliases (
    bank TEXT NOT NULL,
    account_id TEXT NOT NULL,
    alias TEXT NOT NULL,
    PRIMARY KEY (bank, account_id)
);
"""
</code></pre><p>A separate table, not an <code>alias</code> column on <code>accounts</code>. The docstring says why: it "survives <code>save_accounts()</code>'s full-refresh-on-every-sync". The <code>accounts</code> table is a cache that gets deleted and rewritten on every sync, because balances change; anything I typed by hand into that table would be wiped the next night. The rule I took from it: <strong>user-authored data never lives in a table the sync owns.</strong> That same rule comes back for manual accounts below, and for categories in <a href="https://ghost.atathome.me/rule-based-categorisation/">post 12</a>.</p><p>There's one awkward join. Transactions only carry an account's <em>display name</em>, not its <code>account_id</code>, so showing an alias next to a transaction means joining through <code>accounts</code> on <code>(bank, name)</code> - the weaker key - rather than <code>(bank, account_id)</code>. The code has a comment owning that compromise.</p><h2 id="a-debug-page-because-i-kept-wanting-to-look-inside">A debug page, because I kept wanting to look inside</h2><p>The <code>add debug data page</code> commit added a page that lists every raw table and dumps it, and later the raw JSON files that fetches cache under <code>storage/inbound/</code>. When data looks wrong in a dashboard, the first question is always "is it wrong in the database, or wrong in how I'm showing it?", and without this I answered that by opening <code>sqlite3</code> on the server.</p><p>Two small bits of care are worth recording because the page reads arbitrary-looking input:</p><ul><li><code>dump_table()</code> has to interpolate a table name into SQL (SQLite can't bind an identifier as a parameter), so it checks the name against the <code>TABLES</code> tuple first. The docstring is blunt that this check "is the only thing standing between it and arbitrary SQL."</li><li>The file endpoints never build a path from the request. The requested filename must match a name that <code>iterdir()</code> itself returned, so <code>../</code> or odd encodings can't reach outside the cache directory.</li></ul><p>(It was later split into global and per-user sections - see <a href="https://ghost.atathome.me/one-storage-tree-per-user/">post 10</a> - and gained a sync-log viewer in <a href="https://ghost.atathome.me/making-the-nightly-sync-boring/">post 17</a>.)</p><h2 id="accounts-versus-cards-and-logos">Accounts versus cards, and logos</h2><p>A later commit added a "Credit card" badge to the Accounts page, so the two kinds of thing are distinguishable at a glance - the <code>kind</code> field had existed since the very first fetch, it just wasn't shown. Another added provider logos: TrueLayer's connection metadata includes a <code>logo_uri</code>, so <code>fetch()</code> captures it and stores it as <code>provider_logo_url</code> on each account. Same deal as the schema changes before it: a <code>PRAGMA table_info</code> check adds the column to an existing table, which is safe because <code>accounts</code> is a full-refresh cache with nothing to migrate.</p><h2 id="synced-n-ago-the-data-was-already-there">"Synced N ago": the data was already there</h2><p>One small commit is a good reminder to check what you already store. The <code>connections</code> table had carried an <code>updated_at</code> timestamp since the sync started writing it; it just wasn't rendered. The commit adds a relative "Synced 3 hours ago" note beside each bank's account count. A stale sync is the most common reason a number looks wrong, and until then the app gave no hint of it. The commit message also records how it was verified: seeding a scratch storage tree and driving the real dev servers with Playwright, with auth headers faked via route interception since there's no login page any more.</p><h2 id="the-sign-of-a-debt">The sign of a debt</h2><p>This is the one with an actual bug in it. In <a href="https://ghost.atathome.me/balances-and-disconnecting-banks/">post 8</a> I excluded cards from the Total balance because a card's balance is money <em>owed</em>. But TrueLayer reports that figure as a <strong>positive</strong> number, while this app's convention everywhere else is the same as a transaction: negative means money out. The <code>Fix card balance sign...</code> commit fixes it at the source:</p><blockquote>TrueLayer reports a card's "current" balance as a positive amount owed; fetch() now negates it for kind == "cards" so it matches this app's own convention (negative = debt, same sense as a negative transaction amount) instead of looking like money held. "available" (remaining credit) is untouched - it isn't debt.</blockquote><p>The detail I like is the last sentence: <code>available</code> is <em>remaining credit</em>, a positive amount you can still spend, not a debt, so it keeps its sign. Only the field that actually means debt flips. The same commit adds an "Account balances" section to Home, listing every account and card - cards in red, other accounts in green - and the verification note spells out the check: a card renders as <code>-£250.00</code> in red, a current account as <code>£1,234.56</code> in green, and Total balance still excludes the card.</p><p>(There's a sequel. Card <em>transactions</em> have the same problem - they arrive as positive magnitudes with a <code>transaction_type</code> saying which way the money went - and it took until a later commit to normalise those. See <a href="https://ghost.atathome.me/budgets/">post 15</a>.)</p><h2 id="things-the-bank-cant-tell-you-manual-accounts">Things the bank can't tell you: manual accounts</h2><p>Another commit adds the other half of the picture: a loan, say, or anything not reachable through open banking. It also adds totals to the Home page: a "total credit" (the sum of real accounts) and a "total debt" (the sum of everything else - cards, and now manual accounts).</p><p>A manual account is a name and a balance you maintain from a "Manual accounts" card on the Accounts page. The storage decision follows the rule from the alias section: it gets its own <code>manual_accounts</code> table rather than a column on <code>accounts</code>, because <code>accounts</code> is wiped on every sync and a manual account "has no sync source, so it can never live there." To avoid a parallel code path everywhere, <code>list_accounts()</code> <code>UNION ALL</code>s the two tables, so manual accounts flow through every existing consumer - the list, the alias endpoint, the debug view - without each learning about them. The UI generalises the colour split from <code>kind === 'cards'</code> to <code>kind !== 'accounts'</code>, so the red-for-debt styling covers them with no special case.</p><p>The balance is entered as a positive "amount owed" and stored negated, the same convention as a synced card. That was the first version. A follow-up, later the same day, made the account type selectable - debt, or savings/credit - after noticing "previously every manual account was hardcoded as debt." It also fixed a bug found in the process: switching an account's kind without re-entering its balance left the balance with the wrong sign. If you store a sign, changing the thing that determines the sign has to re-store the number.</p><h2 id="what-these-have-in-common">What these have in common</h2><p>None of these is large; the sign fix is one line of arithmetic. But taken together they're the difference between a dashboard that holds data and one you can trust at a glance. Two rules fell out that I've kept applying: <strong>keep user-authored data out of tables a sync rewrites</strong>, and <strong>pick one sign convention and normalise at the boundary where data enters.</strong></p><hr><p>Previous: <a href="https://ghost.atathome.me/one-storage-tree-per-user/">← One storage tree per user</a> · Next: <a href="https://ghost.atathome.me/rule-based-categorisation/">Rule-based categorisation →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[House-move inventory: Money, currencies and an approximate euro - Part 3]]></title><description><![CDATA[~7 min read

Every item in the inventory can have a value, and values are the part of this project where a quiet bug does the most harm: the number ends up on a customs declaration and in an insurance conversation. So the money rules were written down before the first item was added, and they have barely changed since.


The rules

From CLAUDE.md:

 * Money is Decimal end to end, and a string on the wire ("45.00"). Never float - the service actively rejects one.
 * New items default to GBP.
 * V]]></description><link>https://brightbot.co.uk/money-and-an-approximate-euro/</link><guid isPermaLink="false">Ghost__Post__6ae5bab91df6faba86556b44</guid><category><![CDATA[Building Inventory System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Thu, 05 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1777061421355-ca7ebbbe3fc3?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDN8fEN1cnJlbmN5fGVufDB8fHx8MTc5MzUyMzkyOXww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1777061421355-ca7ebbbe3fc3?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDN8fEN1cnJlbmN5fGVufDB8fHx8MTc5MzUyMzkyOXww&ixlib=rb-4.1.0&q=80&w=2000" alt="House-move inventory: Money, currencies and an approximate euro - Part 3"/><p><em>~7 min read</em></p><p>Every item in the inventory can have a value, and values are the part of this project where a quiet bug does the most harm: the number ends up on a customs declaration and in an insurance conversation. So the money rules were written down before the first item was added, and they have barely changed since.</p><h2 id="the-rules">The rules</h2><p>From <code>CLAUDE.md</code>:</p><ul><li><strong>Money is <code>Decimal</code> end to end, and a string on the wire</strong> (<code>"45.00"</code>). Never <code>float</code> - the service actively rejects one.</li><li>New items default to <strong>GBP</strong>.</li><li><code>ValueSummary.approx_eur</code> is <strong>display-only</strong>, computed from a configurable, fixed <code>gbp_to_eur_rate</code> setting.</li></ul><p>The string-on-the-wire rule is the one people trip over. JSON numbers are floats in most clients, and <code>0.1 + 0.2</code> is not <code>0.3</code> in a float. If the API returned <code>45.00</code> as a number, the browser would parse it as a double and every total computed client-side would inherit that. Returning <code>"45.00"</code> and keeping it a string in the React client (<code>web/src/api.ts</code> never turns money into a number) means the only place arithmetic happens is Python's <code>Decimal</code>.</p><h2 id="totals-that-refuse-to-lie">Totals that refuse to lie</h2><p>The interesting function is <code>_summarise_value</code> in <code>core.py</code>. A box (or a room, or the whole move) is a list of items, each with a quantity and an optional value in some currency. What should its total be?</p><p>The naive answer is <code>sum(value * quantity)</code>. That is wrong in two ways, and the function handles both by returning a small structure instead of a number:</p><pre><code class="language-python">valued = [i for i in items if key(i) is not None]
unvalued = len(items) - len(valued)
if not valued:
    return ValueSummary(total=None, mixed_currency=False, ...)
currencies = {i.currency for i in valued}
if len(currencies) &gt; 1:
    return ValueSummary(total=None, mixed_currency=True, ...)
</code></pre><ol><li><strong>No values yet is not zero.</strong> A box of books nobody has priced is "unknown", not "£0". <code>total</code> is <code>None</code>, and the UI shows something different for "nothing priced" than for a genuine zero.</li><li><strong>Mixed currencies are reported, not summed.</strong> If one item is £10 and another €10, any number I show is a lie. <code>mixed_currency=True</code> with <code>total=None</code> tells the UI to say so. Values are recorded in their original currency; the summary refuses to add across them.</li></ol><p>It also keeps <code>valued_lines</code> and <code>unvalued_lines</code>, so a total can honestly say "£1,240.00 across 31 priced lines, 4 not yet priced".</p><h2 id="why-the-euro-is-approximate">Why the euro is "approximate"</h2><p>The move is to France, so the French paperwork wants euros. The tempting design is a live exchange-rate lookup. I decided against it:</p><ul><li>It would add a <strong>second outbound network dependency</strong> (the only one today is optional French translation, post 8). The whole app is meant to run on a box in the house with no external calls it can't live without.</li><li>A live rate makes totals <strong>move between page loads</strong>. A declaration that changes when you refresh it is hard to reason about.</li><li>The numbers are estimates anyway. Nobody is hedging currency risk on a second-hand sofa.</li></ul><p>So <code>gbp_to_eur_rate</code> is a plain setting (default <code>1.17</code>) editable on the Settings page, and <code>approx_eur</code> restates a <em>single-currency GBP</em> total at that rate. It appears as an <code>≈ EUR</code> column on the whole-move list and on the printed sheet. The tilde is deliberate: it tells you it's display-only. If I want the rate to reflect the day, I change one number; if I want a fixed rate for the whole declaration, it stays put.</p><h2 id="market-value-and-retail-value">Market value and retail value</h2><p>Later (Phase 3.18) I added a second optional amount per item. The <strong>market value</strong> is what it's worth now - what you'd put on insurance. The <strong>retail / invoice value</strong> is what you paid, which is what an invoice attachment (post 7) actually backs up. Both share the item's currency and go through the <em>same</em> <code>_summarise_value</code>, just with a different <code>key</code> function:</p><pre><code class="language-python">retail_value=_summarise_value(all_items, gbp_to_eur=rate, key=lambda i: i.retail_value)
</code></pre><p>That one parameter is why the second total cost almost nothing to add, and why it follows exactly the same "unknown is not zero, mixed is not summed" rules. The whole-move summaries stay market-value only; retail value appears where you'd use it, on a box or room sheet.</p><h2 id="the-cost-of-defaults">The cost of defaults</h2><p>One footnote. Changing a domain default is more expensive than it looks. Moving new items to GBP was a one-line change, but several tests assert exact currency and amount strings, which is why the project notes say to grep <code>tests/</code> for the old value first. Defaults leak into assertions; that's a reason to keep few of them.</p><p>Next: putting a REST API on top, and making its documentation impossible to let rot.</p><hr><p>Previous: <a href="https://ghost.atathome.me/a-core-that-knows-nothing-about-http/">← A core that knows nothing about HTTP</a> · Next: <a href="https://ghost.atathome.me/a-rest-api-whose-docs-cant-go-stale/">A REST API whose docs can't go stale →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Marketplace Listing Helper: Filling in Facebook's form - Part 2]]></title><description><![CDATA[~7 min read

Filling in a form sounds like the easy half of the job. It's the half that breaks. Facebook's Create listing form is built from generated markup with no stable ids, its inputs are controlled by React, and its dropdowns are custom widgets. This post is about how the extension copes, and about the one rule that keeps it honest when it can't.


Finding a field without an id

There's nothing like #title to select. What is stable is the text a person reads, so findField() looks fields up]]></description><link>https://brightbot.co.uk/listing-helper-filling-in-facebooks-form/</link><guid isPermaLink="false">Ghost__Post__6ae71f961df6faba86556be3</guid><category><![CDATA[Building Marketplace Listing Helper]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Wed, 04 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1772588627342-5ec373e236d8?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDEyfHxmb3JtfGVufDB8fHx8MTc5MzUzMjE2Nnww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1772588627342-5ec373e236d8?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDEyfHxmb3JtfGVufDB8fHx8MTc5MzUzMjE2Nnww&ixlib=rb-4.1.0&q=80&w=2000" alt="Marketplace Listing Helper: Filling in Facebook's form - Part 2"/><p><em>~7 min read</em></p><p>Filling in a form sounds like the easy half of the job. It's the half that breaks. Facebook's Create listing form is built from generated markup with no stable ids, its inputs are controlled by React, and its dropdowns are custom widgets. This post is about how the extension copes, and about the one rule that keeps it honest when it can't.</p><h2 id="finding-a-field-without-an-id">Finding a field without an id</h2><p>There's nothing like <code>#title</code> to select. What is stable is the text a person reads, so <code>findField()</code> looks fields up by their visible label, falling back to an <code>aria-label</code>:</p><pre><code class="language-js">function findField(labelText) {
  const want = labelText.toLowerCase();
  for (const lab of document.querySelectorAll("label")) {
    if (lab.closest("#mlh-panel, #mlh-modal")) continue;
    const t = (lab.innerText || "").trim().toLowerCase();
    if (t === want || t.startsWith(want)) { /* return the input, or the combobox */ }
  }
  const aria = document.querySelector(`[aria-label="${labelText}" i]`);
  // ...
}
</code></pre><p>Two small details matter. It skips anything inside the extension's own panel and modal (<code>#mlh-panel, #mlh-modal</code>), otherwise the panel's own "Title" label could be found first. And it matches with <code>startsWith</code>, because Facebook sometimes adds a hint after the label text.</p><p>This is the part of the project most likely to break, and CLAUDE.md says so in as many words: Facebook's markup changes often, so expect to adjust <code>findField()</code>.</p><h2 id="typing-into-a-react-input">Typing into a React input</h2><p>Setting <code>input.value = "..."</code> doesn't work on a React-controlled input. React tracks the value itself and ignores a change it didn't make, so the box looks filled, then the form behaves as if it's empty. The fix is to call the browser's <em>native</em> value setter, bypassing React's wrapper, and then fire the events React listens for:</p><pre><code class="language-js">function setNativeValue(el, value) {
  const proto = el.tagName === "TEXTAREA" ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
  const setter = Object.getOwnPropertyDescriptor(proto, "value").set;
  el.focus();
  setter.call(el, value);
  el.dispatchEvent(new Event("input", { bubbles: true }));
  el.dispatchEvent(new Event("change", { bubbles: true }));
  el.blur();
}
</code></pre><p>The textarea and input prototypes have separate setters, hence the check. It's a well-known trick, and it's what makes title, price and description actually register.</p><h2 id="dropdowns">Dropdowns</h2><p>Category and Condition aren't <code>&lt;select&gt;</code> elements. You click them and a list appears. So <code>pickDropdown()</code> clicks the control, waits 600ms for the list to render, then looks for anything that looks like an option and clicks the one whose text matches, trying an exact match first and then a "contains":</p><pre><code class="language-js">const opts = [...document.querySelectorAll(
  '[role="option"], [role="menuitemradio"], [role="radio"], [role="listbox"] [role="button"]')];
const match = opts.find(o =&gt; text(o) === want) || opts.find(o =&gt; text(o).includes(want));
</code></pre><p>If nothing matches (my category name differs from Facebook's, say) it presses Escape to close the list and reports <code>pick manually</code> instead of guessing.</p><h2 id="photos">Photos</h2><p>The upload box is a normal <code>&lt;input type="file"&gt;</code>, and a script can assign files to one by building a <code>DataTransfer</code> and firing a <code>change</code> event:</p><pre><code class="language-js">const dt = new DataTransfer();
files.forEach(f =&gt; dt.items.add(f));
input.files = dt.files;
input.dispatchEvent(new Event("change", { bubbles: true }));
</code></pre><p>Photos are attached first, then the script waits 800ms before touching the other fields, because the upload area re-renders the form.</p><h2 id="the-report">The report</h2><p>Every fill ends with a per-field table in the panel: Photos, Title, Price, Category, Condition, Description, each marked <code>ok</code>, <code>not found</code>, <code>pick manually</code>, and so on. This is the rule I care most about in the whole file. A filler that silently half-works is worse than no filler, because I'd publish a listing believing it was complete. The report keeps that honest, and it's the reason the "I press Publish" rule is safe: I always know exactly what to check by hand.</p><p>There's one more thing that happens at fill time. A <strong>footer template</strong> (my "collection and payment" paragraph, say) is appended to the description when filling, but never saved into the item. Change the footer later and every unlisted item picks it up.</p><h2 id="what-this-adds-up-to">What this adds up to</h2><p>Reliable form filling here isn't about clever code. It's about picking the least fragile hook for each kind of control (visible label text, native setters, role-based options), failing visibly when a hook stops working, and keeping all of it in a couple of small functions so the inevitable repair is quick.</p><hr><p>Previous: <a href="https://ghost.atathome.me/listing-helper-a-helper-that-never-presses-publish/">← A helper that never presses Publish</a> · Next: <a href="https://ghost.atathome.me/listing-helper-a-list-that-lives-in-the-browser/">A list that lives in the browser →</a> · Back to <a href="https://ghost.atathome.me/tag/building-marketplace-listing-helper/">series index</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Childcare calculator: Splitting free hours across childminders - Part 3]]></title><description><![CDATA[~8 min read

The part of this calculator that actually needed thinking about is free hours. A funded entitlement is a number of hours per week, and it isn't tied to a particular childminder. If you use two childminders at different rates, you choose where those free hours land, and the choice changes the monthly bill quite a lot. This post is about the four strategies and the one rule that keeps them honest.


Why it matters

Take the default setup in the app: Childminder A at £5.50/hr for four ]]></description><link>https://brightbot.co.uk/splitting-free-hours/</link><guid isPermaLink="false">Ghost__Post__6ae473081df6faba86556afb</guid><category><![CDATA[Building a Childcare Calculator]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Wed, 04 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1547908068-b3c55fdda5be?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDN8fGZyZWUlMjBob3Vyc3xlbnwwfHx8fDE3OTMzNTY3MDh8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1547908068-b3c55fdda5be?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDN8fGZyZWUlMjBob3Vyc3xlbnwwfHx8fDE3OTMzNTY3MDh8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Childcare calculator: Splitting free hours across childminders - Part 3"/><p><em>~8 min read</em></p><p>The part of this calculator that actually needed thinking about is free hours. A funded entitlement is a number of hours per week, and it isn't tied to a particular childminder. If you use two childminders at different rates, you choose where those free hours land, and the choice changes the monthly bill quite a lot. This post is about the four strategies and the one rule that keeps them honest.</p><h2 id="why-it-matters">Why it matters</h2><p>Take the default setup in the app: Childminder A at £5.50/hr for four days of 8.5 hours (34 hours), Childminder B at £7.50/hr for one day of 8.5 hours. That's 42.5 booked hours in a week. Say 30 are funded. The same 30 free hours produce three different weekly bills:</p><p>| Strategy | A free / paid | B free / paid | Weekly cost | |---|---|---|---| | Expensive first | 21.5 / 12.5 | 8.5 / 0 | £68.75 | | Proportional | 24 / 10 | 6 / 2.5 | £73.75 | | Cheaper first | 30 / 4 | 0 / 8.5 | £85.75 |</p><p>A free hour is worth whatever the rate is, so spending free hours on the expensive childminder first saves the most. The gap between the best and worst here is £17 a week, which is over £70 a month. That's why the strategy is a dropdown and not something the code decides for you.</p><p>(Whether your childcare provider lets you split funding this way is a separate question that depends on your arrangement and local authority. The calculator just does the arithmetic for whichever rule you choose.)</p><h2 id="the-four-strategies">The four strategies</h2><p>All four live in one function, <code>splitFree(weekHours, freeForWeek)</code>, which takes the hours booked with each childminder this week and the total free hours to hand out, and returns an array of allocations.</p><p><strong>Proportional</strong> is the simplest: each childminder gets a share of the free hours matching their share of the booked hours.</p><pre><code class="language-js">if (strategy === 'proportional') {
  for (let i = 0; i &lt; n; i++) alloc[i] = freeForWeek * (weekHours[i] / weekTotal);
  return alloc;
}
</code></pre><p><strong>Expensive first</strong> and <strong>cheaper first</strong> share a branch. Sort the childminders by rate, then fill each one up to their booked hours before moving to the next:</p><pre><code class="language-js">const order = childminders.map((_, i) =&gt; i).sort((a, b) =&gt;
  strategy === 'expensive-first' ? rates[b] - rates[a] : rates[a] - rates[b]);
let remaining = freeForWeek;
for (const i of order) {
  const take = Math.min(remaining, weekHours[i]);
  alloc[i] = take;
  remaining -= take;
  if (remaining &lt;= 0) break;
}
</code></pre><p>The <code>Math.min(remaining, weekHours[i])</code> is the important part, and it's the rule mentioned above: <strong>nobody is allocated more free hours than they were booked for.</strong> You can't use 30 free hours at a childminder you only see for 8.5.</p><h2 id="custom-split-and-the-leftover-problem">Custom split, and the leftover problem</h2><p>The fourth strategy, <strong>custom</strong>, came in with multiple childminders. Each one gets a slider, and the sliders are <em>relative weights</em>: 50/50, 70/30 and 7/3 mean the same thing, and they don't need to add up to 100.</p><p>The catch is the cap. Suppose the weights say "split evenly" but one childminder is booked for 6 hours and the other for 36, with 30 hours to give. An even split would hand 15 to someone who only works 6. The surplus has nowhere to go, so it needs to pass to whoever still has room.</p><p>The implementation loops. On each pass it shares what's left among the childminders who still have unfunded booked hours, in proportion to their weights, clamped to their remaining capacity. Whatever couldn't be placed goes round again:</p><pre><code class="language-js">let remaining = freeForWeek;
let guard = 0;
while (remaining &gt; 1e-9 &amp;&amp; guard++ &lt; 25) {
  const elig = [];
  let eligW = 0;
  for (let i = 0; i &lt; n; i++) {
    if (alloc[i] &lt; weekHours[i] - 1e-9) { elig.push(i); eligW += pcts[i]; }
  }
  if (!elig.length) break;
  let used = 0;
  for (const i of elig) {
    const want = (eligW &gt; 0) ? remaining * (pcts[i] / eligW) : remaining / elig.length;
    const take = Math.min(want, weekHours[i] - alloc[i]);
    alloc[i] += take;
    used += take;
  }
  remaining -= used;
  if (used &lt;= 1e-9) break;
}
</code></pre><p>Two defensive details in there are worth calling out. The <code>1e-9</code> tolerance avoids floating-point dust (a childminder who's "full" by 0.0000000001 still counting as eligible). The <code>guard</code> counter and the <code>used &lt;= 1e-9</code> break are a belt-and-braces way of making sure a bad input can never turn into an infinite loop in someone's browser tab. If every weight is zero, the <code>eligW &gt; 0</code> check falls back to an even split between the eligible childminders rather than dividing by zero.</p><h2 id="a-preview-so-sliders-arent-blind">A preview, so sliders aren't blind</h2><p>Dragging a weight slider and seeing nothing change would be a poor experience, because the real effect only shows up in the monthly breakdown further down the page. So the custom-split card shows the result of the split on a <strong>standard week</strong>, computed from the weekly schedule alone, ignoring holidays, exclusions and the actual month:</p><pre><code class="language-js">const standardWeekHours = new Array(n).fill(0);
schedule.forEach(entry =&gt; {
  if (entry.cm != null &amp;&amp; entry.cm &gt;= 0 &amp;&amp; entry.cm &lt; n &amp;&amp; entry.hours &gt; 0) {
    standardWeekHours[entry.cm] += entry.hours;
  }
});
const standardFreeForWeek = Math.min(freeHoursPerWeek, standardWeekTotal);
const standardAlloc = splitFree(standardWeekHours, standardFreeForWeek);
</code></pre><p>It reuses <code>splitFree</code>, so the preview and the real calculation can't drift apart. That's a pattern I kept coming back to: when two parts of the UI need to agree, make them call the same function.</p><h2 id="next">Next</h2><p><code>splitFree</code> answers "how many free hours does each childminder get this week?". It says nothing about <em>which days</em> those hours fall on, and that turned out to matter for the calendar. <a href="https://ghost.atathome.me/weeks-and-partial-weeks/">The next post</a> covers that, and a bug about weeks that start or end mid-month.</p><hr><p>Previous: <a href="https://ghost.atathome.me/from-two-childminders-to-four/">← From two childminders to four</a> · Next: <a href="https://ghost.atathome.me/weeks-and-partial-weeks/">Spreading hours across the week →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Central login service: Polish, and creating users from the browser - Part 7]]></title><description><![CDATA[~22 min read

The last two commits to date are the least dramatic and, in a way, the most revealing about what a project looks like once the hard problems are solved. One (feat: make UI look nicer) is almost entirely CSS. The other (feat: adding new user) fills the last hole in the admin story: until now, the only way to create an account was to SSH into the container and run a command-line tool.

This final part covers both, and then steps back to take stock of the whole series: what the finish]]></description><link>https://brightbot.co.uk/identity-system-polish-and-creating-users-from-the-browser/</link><guid isPermaLink="false">Ghost__Post__6ada2fa81df6faba86556a96</guid><category><![CDATA[Building Identity System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Wed, 04 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1668903678359-e810dd966016?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fGNyZWF0ZSUyMHVzZXJ8ZW58MHx8fHwxNzkyNjg0MTk2fDA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1668903678359-e810dd966016?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fGNyZWF0ZSUyMHVzZXJ8ZW58MHx8fHwxNzkyNjg0MTk2fDA&ixlib=rb-4.1.0&q=80&w=2000" alt="Central login service: Polish, and creating users from the browser - Part 7"/><p><em>~22 min read</em></p><p>The last two commits to date are the least dramatic and, in a way, the most revealing about what a project looks like once the hard problems are solved. One (<code>feat: make UI look nicer</code>) is almost entirely CSS. The other (<code>feat: adding new user</code>) fills the last hole in the admin story: until now, the only way to create an account was to SSH into the container and run a command-line tool.</p><p>This final part covers both, and then steps back to take stock of the whole series: what the finished service looks like, which of its gaps are deliberate, and what I'd do differently.</p><h2 id="making-it-look-like-someone-cared">Making it look like someone cared</h2><p>By this point the frontend worked, and it looked like what it was: a set of unstyled forms with a few rules from the first afternoon. The earlier CSS was about a hundred lines, with colours written as literals (<code>#ddd</code>, <code>#b00020</code>) at the point of use. The polish commit replaces it with roughly 490 lines, and the thing worth explaining isn't any one rule. It's the structure.</p><h3 id="design-tokens-first">Design tokens first</h3><p>The file starts with a block of CSS custom properties:</p><pre><code class="language-css">:root {
  color-scheme: light dark;
  --bg: #f6f7f9;
  --surface: #ffffff;
  --text: #1c1f24;
  --muted: #5f6672;
  --border: #dde1e7;
  --accent: #2456d6;
  --accent-text: #ffffff;
  --accent-hover: #1d48b5;
  --danger: #b3261e;
  --danger-bg: #fdecea;
  --warn-bg: #fff8e1;
  --warn-border: #d9a400;
  --focus: rgba(36, 86, 214, 0.35);
  --radius: 0.6rem;
  --shadow: 0 1px 2px rgba(16, 24, 40, 0.06), 0 1px 3px rgba(16, 24, 40, 0.08);
  font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
  line-height: 1.5;
}
</code></pre><p>Every rule after that refers to a token (<code>var(--surface)</code>, <code>var(--border)</code>), never a literal colour. The benefit is that <em>themes become a matter of redefining a dozen variables</em>, and the rest of the stylesheet doesn't change. Names describe roles (<code>--surface</code>, <code>--muted</code>, <code>--danger-bg</code>) rather than appearances (<code>--light-grey</code>), which is what lets the same name mean a different colour in a different theme.</p><p>The font stack is <code>system-ui</code> first. That means the OS's own UI font, with no web-font download, no layout shift while it loads, and a result that looks native on whichever device the page is opened on. For an internal tool that's the right default, and it's also why the page has no external dependencies at all: no CDN, nothing to be blocked by a content-security policy or to go down.</p><h3 id="dark-mode-with-an-escape-hatch">Dark mode, with an escape hatch</h3><p>The dark theme redefines the same variable names:</p><pre><code class="language-css">@media (prefers-color-scheme: dark) {
  :root:not([data-theme='light']) {
    --bg: #0f1216;
    --surface: #171b21;
    --text: #e6e9ef;
    --muted: #9aa3b2;
    --border: #2a303a;
    --accent: #6e93f7;
    --accent-text: #0f1216;
    ...
  }
}

:root[data-theme='dark'] {
  --bg: #0f1216;
  ...
}
</code></pre><p>There are two selectors, which looks redundant until you work out what each is for:</p><ol><li>The <code>@media (prefers-color-scheme: dark)</code> block follows the <strong>operating system's</strong> setting, but <em>unless</em> the page has been explicitly pinned to light (<code>:not([data-theme='light'])</code>). Default behaviour is "do what the user's device says".</li><li>The <code>:root[data-theme='dark']</code> block forces dark <strong>regardless</strong> of the OS setting, for a future theme toggle (or a screenshot tool) to set an attribute.</li></ol><p>So three states are supported with no JavaScript: follow the system (no attribute), force light, force dark. Nothing in the app sets that attribute today, so the forced modes are currently unused: they're there so a toggle (or a screenshot tool) would be a one-line change rather than a stylesheet rewrite. That's mildly speculative, and the cost is a duplicated block of variables.</p><p>The dark palette isn't the light one inverted. A few things differ on purpose:</p><ul><li>The accent colour is <strong>lighter</strong> in dark mode (<code>#6e93f7</code> rather than <code>#2456d6</code>), because a saturated mid-blue that reads well on white can look muddy against near-black.</li><li><code>--accent-text</code> flips from white to the dark background colour, so text on a primary button stays legible against the lighter accent.</li><li>The error colour inverts its roles: in light mode it's a dark red on a pale pink (<code>#b3261e</code> on <code>#fdecea</code>), and in dark mode a pale pink on a dark red (<code>#f2b8b5</code> on <code>#3a1716</code>). Same meaning, readable in both.</li><li>The shadow is darker and tighter. A soft grey drop shadow disappears on a dark background.</li></ul><p>The commit doesn't include a contrast audit of these pairs. For an internal tool that's tolerable; for anything public I'd check them against the WCAG thresholds first.</p><h3 id="buttons-one-primary-the-rest-quiet">Buttons: one primary, the rest quiet</h3><p>The base <code>.btn</code> is a neutral bordered button. A second class, <code>.btn-primary</code>, is the filled accent colour, and the commit's small TSX changes are all of the same kind: adding <code>btn-primary</code> to the one button on each form that is <em>the thing the user is here to do</em> (Sign in, Save, Register client), and <code>btn-danger</code> to the two Delete buttons.</p><pre><code class="language-css">/* Primary action on a form: the one thing the user is here to do. */
.btn-primary {
  background: var(--accent);
  border-color: var(--accent);
  color: var(--accent-text);
}
</code></pre><p>That comment is also a design rule. If every button is loud, none is. The Edit and Rotate buttons inside the admin tables stay neutral (with a compact variant, <code>table .btn</code>, so they don't bloat the rows), while Delete gets <code>.btn-danger</code>: red text, and a red border and pale-red fill on hover.</p><p>Interaction states get real attention, since they're what separates "styled" from "usable":</p><pre><code class="language-css">.btn:focus-visible {
  outline: none;
  box-shadow: 0 0 0 3px var(--focus);
}

.btn:disabled {
  opacity: 0.55;
  cursor: not-allowed;
}
</code></pre><p><code>:focus-visible</code> shows the ring for keyboard navigation but not for mouse clicks, so the focus indicator isn't ugly for pointer users and isn't missing for keyboard users. Removing the default <code>outline</code> is only acceptable <em>because</em> it's replaced with something at least as visible; deleting focus styles without a replacement is a classic accessibility regression. The disabled style matters here more than usual because the forms disable their submit button while a request is in flight, which doubles as protection against a double-click creating two of something.</p><h3 id="details-that-earn-their-keep">Details that earn their keep</h3><p>A few smaller rules show the intent:</p><pre><code class="language-css">.secret-banner {
  background: var(--warn-bg);
  border: 1px solid var(--warn-border);
  border-radius: var(--radius);
  padding: 0.9rem 1.1rem;
  margin: 1.25rem 0;
  word-break: break-all;
}
</code></pre><p>That's the banner from Part 6 that displays a freshly generated client secret. It gets its own <strong>warning colours</strong>, distinct from error red and from normal content, because it carries a message the user must act on <em>now</em> ("copy this, it won't be shown again"). <code>word-break: break-all</code> is there because a 43-character URL-safe secret has no natural break points and would otherwise push the layout sideways on a phone.</p><pre><code class="language-css">@media (max-width: 40rem) {
  .app-header { padding: 0.6rem 1rem; }
  .app-main { margin-top: 1.25rem; padding: 0 1rem; }
}
</code></pre><p>The responsive handling is deliberately small: the header's flex row is allowed to wrap (<code>flex-wrap: wrap</code>), the content column has a <code>max-width</code> and fluid padding, and wide admin tables scroll <em>inside themselves</em> rather than forcing the whole page to scroll horizontally. The apps directory uses <code>grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr))</code>, which produces as many equal columns as fit and reflows to a single column on a phone without a single media query.</p><p>The header also got a small touch of identity: a gradient square in front of the wordmark, drawn with a <code>::before</code> pseudo-element, so it's decoration with no extra image or markup.</p><p>The commit touches five files, adding 430 lines and removing 54. Four of them are one-class changes to TSX (the <code>btn-primary</code> and <code>btn-danger</code> additions); the component logic didn't change, because the styling lives where it should.</p><h2 id="the-last-gap-creating-people">The last gap: creating people</h2><p>Back to the substantive change. The <code>README</code> of this project has said since the very first commit that there's <strong>no self-registration</strong>. That's deliberate: a public signup form on a personal login service is attack surface for no benefit. Accounts were created with the library's command-line tool, run on the server against the same database file.</p><p>That worked, and it had one painful property: adding a family member's account meant a shell session on the container. Now that apps, clients and users are all visible in the admin pages, "everything except creating a user" being a command-line job looked odd.</p><h3 id="the-route">The route</h3><pre><code class="language-python">@app.post("/api/admin/users", status_code=201)
def admin_create_user(payload: dict, _admin: User = Depends(require_admin)):
    user = auth.create_user(
        payload.get("email", ""), payload.get("password", ""), name=payload.get("name") or None
    )
    return _admin_user_json(user)
</code></pre><p>Four lines, and it's a good demonstration of the discipline from Part 1. The route does <strong>no validation of its own</strong>: no email-format regex, no password-length check, no duplicate lookup. All of that is <code>AuthService.create_user</code>'s job. It raises <code>ValidationError</code> for a malformed email or a short password and <code>DuplicateUser</code> for an address already in use, and both are already in the central status table, so they surface as <code>422</code> and <code>409</code> with no new code. The same rules apply whether an account is created from the CLI or from this page, because it's literally the same function.</p><p>Two small things in that route are worth noticing:</p><ul><li><code>name=payload.get("name") or None</code> turns an empty string into <code>None</code>, so a blank name field in the form means "use the default" and not "set the name to the empty string". The default, as the test shows, is the local part of the email.</li><li>The response is <code>201 Created</code> with the new user's admin view (no password material, naturally). And the earlier inline list comprehension that built the admin user dictionary was pulled out into <code>_admin_user_json</code>, because there were now two places that return it.</li></ul><p>The list route changed in a way I like: a helper used in two places is what you extract when the <em>second</em> use appears, not when you predict it.</p><h3 id="the-test-suite-for-it">The test suite for it</h3><p>Five tests cover the behaviour, and the interesting ones are the ones that check the account is actually usable:</p><pre><code class="language-python">def test_admin_can_create_a_user(client, auth):
    _login(client, auth, email="admin@example.com", password="password123", name="Admin")

    resp = client.post(
        "/api/admin/users",
        json={"email": "new@example.com", "password": "password123", "name": "New Person"},
    )
    assert resp.status_code == 201
    ...
    # The new account can actually sign in with the password the admin set.
    other = client.__class__(client.app, base_url=client.base_url)
    login = other.post("/api/login", json={"email": "new@example.com", "password": "password123"})
    assert login.status_code == 200
</code></pre><p>The last three lines build a <strong>second, separate test client</strong>. The first one holds the admin's session cookie, and reusing it would make a "login" that proves nothing about the new account. A fresh client with an empty cookie jar has to authenticate from scratch. It's the sort of detail that distinguishes a test that checks the response from a test that checks the outcome.</p><p>The other tests nail down the edges: the name defaulting from the email, <code>401</code> when signed out and <code>403</code> for a non-admin, <code>409</code> for a duplicate email, <code>422</code> for a too-short password. Together they assert that the route is gated the same way as every other admin route, and that the library's validation rules propagate through unchanged.</p><h3 id="the-form">The form</h3><p>On the frontend, the Users page gained an "Add a user" section under the table: email, an optional name, password, confirm password.</p><pre><code class="language-tsx">const handleSubmit = async (e: FormEvent) =&gt; {
  e.preventDefault()
  setFormError(null)
  if (form.password !== form.confirmPassword) {
    setFormError('Passwords do not match')
    return
  }
  setSubmitting(true)
  try {
    // There's no self-registration endpoint, deliberately (see CLAUDE.md) -
    // this is the admin-only equivalent of `sessionkit add`, not a signup
    // form. Validation (email format, password strength) lives in
    // AuthService.create_user, same as everywhere else.
    await api.post('/api/admin/users', {
      email: form.email,
      password: form.password,
      name: form.name || undefined,
    })
    setForm(EMPTY_FORM)
    await onUserCreated()
  } catch (err) {
    setFormError(errorMessage(err))
  } finally {
    setSubmitting(false)
  }
}
</code></pre><p>Some decisions packed in here:</p><p><strong>The confirm-password check happens only in the browser</strong>, and the API doesn't receive the confirmation at all. That's the right division of labour: the "did you mistype it?" check is a usability feature that protects against typos, not a security control, so it belongs where the typing happens. The server's rules are the real ones. The test confirms the shape, asserting that a mismatch stops submission <em>without ever calling the API</em>.</p><p><strong><code>try/catch/finally</code>.</strong> <code>finally</code> resets <code>submitting</code> whatever happens, so a failed request never leaves the button permanently disabled. Without it, one rejected duplicate email would require a page reload to try again.</p><p><strong>The server's own error message is displayed.</strong> <code>errorMessage(err)</code> unwraps the <code>ApiError</code>, so the admin sees the library's wording for a weak password or a duplicate rather than a generic failure. Another consequence of keeping the validation in one place: the UI never has to translate or duplicate the rules.</p><p><strong>On success the form resets and the list reloads</strong> via the <code>refresh</code> function from <code>useAdminList</code>. The new user appears in the table with "never" as their last login, which is a quick confirmation that the right thing happened.</p><p>The page also gained an empty state: a "No users yet." message instead of a table with a header and no rows. The kind of detail that only matters on a first run, which is exactly when a project makes its first impression.</p><h3 id="what-the-admin-doesnt-get">What the admin doesn't get</h3><p>The README is careful about the limits of this feature, and the honest summary is worth repeating:</p><ul><li><strong>The admin chooses the initial password and hands it over.</strong> There's no emailed invitation, no "reset on first login", and no generated secret (unlike OIDC clients, where the secret is only ever needed by a machine). For a household, with me and the person standing in the same room, that's acceptable. For anything larger it would be the next thing to build.</li><li><strong>Nothing else about an existing account is editable here.</strong> Renaming, re-emailing, deleting, resetting a password or switching off a lost authenticator's two-factor still require the command-line tool. The project notes list that explicitly so I don't assume the page does more than it does.</li><li><strong>There's no self-service password change in the frontend yet</strong>, though the backend route exists (it has since the first commit). That's a gap in the account page rather than in the API.</li></ul><h2 id="where-the-series-ends-up">Where the series ends up</h2><p>The finished service, as of the latest commit, is:</p><ul><li><strong>A forward-auth endpoint</strong> (<code>GET /verify</code>) that any app behind my nginx can use to learn who's asking, with the session cookie shared across a parent domain.</li><li><strong>A login page</strong> that is the only place a password is typed, with TOTP two-factor and a carefully guarded post-login redirect.</li><li><strong>An OpenID Connect provider</strong> for software that can't sit behind the proxy, with PKCE verified when offered, hashed client secrets and a persistent signing key.</li><li><strong>A hub</strong>: a public apps directory at <code>/</code>, an account page at <code>/account</code>, and, for administrators, pages to manage users, apps and OIDC clients, all editable live.</li><li><strong>A deploy pipeline</strong> that tests with <code>uv</code> and <code>npm</code>, builds the frontend, and ships to a Debian container with an <code>rsync</code> and a re-templated systemd unit and nginx config.</li></ul><p>All of it landed in under two weeks of commits, from the first on 28 September to the latest on 7 October.</p><h3 id="what-id-do-differently">What I'd do differently</h3><p><strong>Test with a real relying party earlier.</strong> Part 5's four problems were all invisible to tests I wrote myself. A throwaway real client at the start of the OIDC work would have turned an afternoon of surprises into a few minutes.</p><p><strong>Make the deploy smoke-test itself.</strong> A <code>curl</code> to <code>/verify</code> expecting a <code>401</code> after each deploy would have caught the stale-virtualenv bug immediately, and it's about three lines of shell.</p><p><strong>Install with <code>uv</code> on the container</strong>, so that what the tests ran against is what runs in production, rather than leaving the lockfile as a statement about CI only.</p><p><strong>Add an audit log.</strong> The admin pages can now create users, register clients that receive authorisation codes, and change where those codes are sent. Nothing records who did what or when.</p><h3 id="what-id-keep">What I'd keep</h3><p><strong>The rule that rules live in the library.</strong> Every time I was tempted to add a check to a route handler, the answer was "that's <code>AuthService</code>'s job", and it kept the service thin enough to hold in my head.</p><p><strong>Writing the gaps down.</strong> Every deliberate omission (no CSRF token, no authorisation model, the <code>POST /password</code> gap, in-memory authorisation codes) is documented where the next change will trip over it. About half of the later work in this series was a documented gap being closed on purpose.</p><p><strong>Fail-closed defaults.</strong> An empty admin list means no admins. An empty cookie domain trusts no redirects. A missing file means "nothing to import". When a setting is absent, the safe behaviour is also the default behaviour.</p><p><strong>Treating shared URLs as contracts.</strong> The frozen legacy paths from Part 3 meant I could rebuild the whole frontend without breaking a single app that relied on the service.</p><p><strong>Small comments that say <em>why</em>.</strong> Nearly every non-obvious decision in the codebase has a comment that explains the reasoning or the failure it came from. They're why I could write seven posts about this project from the repository alone.</p><hr><p>That's the story to date. The service sits quietly at the front of the house, and mostly what it does is answer "who is this?" for each request without anyone noticing. Which, for an identity service, is the best compliment I can think of.</p><p>Previous: <a href="https://ghost.atathome.me/identity-system-moving-configuration-into-the-database/">← Moving configuration into the database</a> Next: <a href="https://ghost.atathome.me/identity-system-a-two-step-login-wizard/">A two-step login wizard →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: One storage tree per user - Part 10]]></title><description><![CDATA[~8 min read

Once identity-system was putting a user id on every request, one assumption baked into the app from post 4 became visibly wrong. Everything - the SQLite database, the OAuth refresh tokens, the fetched JSON - lived in one shared storage/ directory, because there had only ever been one person. The moment a second account could log in, they'd see the first account's banks.

This post is about how I fixed that, and why I picked the less clever of two obvious designs. It's three commits ]]></description><link>https://brightbot.co.uk/one-storage-tree-per-user/</link><guid isPermaLink="false">Ghost__Post__6ad488c61df6faba865569ad</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Wed, 04 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1765502318157-61d9bb6579e0?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDl8fFN0b3JhZ2V8ZW58MHx8fHwxNzkyMzE3MTQxfDA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1765502318157-61d9bb6579e0?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDl8fFN0b3JhZ2V8ZW58MHx8fHwxNzkyMzE3MTQxfDA&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: One storage tree per user - Part 10"/><p><em>~8 min read</em></p><p>Once <a href="https://ghost.atathome.me/handing-auth-to-identity-system/">identity-system</a> was putting a user id on every request, one assumption baked into the app from <a href="https://ghost.atathome.me/from-script-to-service/">post 4</a> became visibly wrong. Everything - the SQLite database, the OAuth refresh tokens, the fetched JSON - lived in one shared <code>storage/</code> directory, because there had only ever been one person. The moment a second account could log in, they'd see the first account's banks.</p><p>This post is about how I fixed that, and why I picked the less clever of two obvious designs. It's three commits of real work and two small fixes after them.</p><h2 id="two-ways-to-isolate-users">Two ways to isolate users</h2><p>The textbook answer is a <code>user_id</code> column on every table, with every query filtered by it. It's compact and it's what most tutorials show. Its failure mode is the problem: forget one <code>WHERE user_id = ?</code> - in a new endpoint, or a rarely-run report - and the app doesn't crash, it quietly returns someone else's data.</p><p>The alternative is <strong>physical isolation</strong>: each user gets their own directory tree and their own SQLite file, and the code resolves paths from the user id:</p><pre><code>storage/
  providers.db                  &lt;- shared reference data (the bank list)
  logs/
  users/
    {user_id}/
      db/finance.db
      secrets/tokens.json
      inbound/transactions.json, accounts.json, connections.json, ...
</code></pre><p>The failure mode here is a <em>wrong path</em>, and a wrong path is loud: a missing file, an empty database, a failing test. The commit message for the main change puts it in one line - "a wrong path is a loud, obvious bug, where a forgotten WHERE clause is a silent cross-user data leak" - and that was the whole decision. For a tool holding people's bank data, I'll take the design whose mistakes announce themselves.</p><h2 id="step-one-pull-out-the-one-thing-that-isnt-per-user">Step one: pull out the one thing that isn't per-user</h2><p>A design like this has an immediate wrinkle: some data isn't per-user. TrueLayer's list of supported banks is shared reference data, fetched at server startup (<code>_refresh_providers()</code> in <code>main.py</code>) before any request - and so before any user - exists. It can't live in a per-user database.</p><p>So I split it out first, as a pure refactor with no behaviour change: <code>connect()</code> stopped touching the <code>providers</code> table, and a new <code>connect_providers()</code> owns a separate <code>providers.db</code>. Doing this as its own commit was a deliberate sequencing choice - the commit message calls it "step 1" of a plan. If the split broke something, I'd find out with the per-user change not yet in the picture. The one deploy-time side effect was documented in the message: the old <code>providers</code> rows inside <code>finance.db</code> become orphaned, harmlessly, because startup refetches the list into the new file.</p><h2 id="step-two-paths-become-functions-of-a-user">Step two: paths become functions of a user</h2><p>Then the main change. Every path that used to be a fixed property on <code>Settings</code> became a method that takes a user id:</p><pre><code class="language-python">def user_dir(self, user_id: str) -&gt; Path:
    return self.storage_dir / "users" / user_id

def db_path(self, user_id: str) -&gt; Path:
    return self.user_dir(user_id) / "db" / "finance.db"

def tokens_path(self, user_id: str) -&gt; Path:
    return self.user_dir(user_id) / "secrets" / "tokens.json"
</code></pre><p>Turning properties into methods is a small type-level trick with a big effect: you can no longer ask for "the database path" without saying whose. Every call site that used the old properties fails until it supplies a user.</p><p>The request path follows from that. <code>get_db()</code> now depends on <code>current_user()</code>, so each request opens <em>that user's</em> SQLite file:</p><pre><code class="language-python">def get_db(user: AuthenticatedUser = Depends(current_user)):
    conn = storage.connect(get_settings().db_path(user.id))
    ...
</code></pre><p>And <code>current_user()</code> got stricter. Before, <code>id</code> defaulted to an empty string; now <code>AuthenticatedUser.id</code> has no default, and a request with an email header but no id is rejected. The reasoning is in a code comment: the id selects which user's files a request can read, "so a response that somehow carried an email but no id must not fall through to some default." An empty user id would otherwise resolve to <code>storage/users/</code> itself.</p><p>The same commit also added an identity check to the TrueLayer <code>/callback</code> route, which hadn't had one. It had worked anyway, because the browser round-trip is gated by nginx like any other page - but with per-user token files, the route now needs to know whose token file to write.</p><p>The commit's confidence rests on one test, <code>test_data_isolation.py</code>. Its docstring says what it's for: it's "the one test that proves that property actually holds through the real dependency chain - <code>get_db</code> is deliberately NOT overridden here." Only the <em>identity</em> is faked (a <code>current_user</code> override that returns user A or user B); everything downstream, including which SQLite file gets opened, is the real code. It seeds a transaction and an account alias into user A's database, then asserts that user A sees them and user B gets an empty list. A test that stubbed out <code>get_db</code> as well would pass no matter how the paths were wired.</p><h2 id="the-nightly-job-has-to-find-everyone">The nightly job has to find everyone</h2><p>The old systemd unit ran one hardcoded fetch. With data per user, it had to iterate. <code>deploy/fetch-all-users.sh</code> discovers users by listing <code>storage/users/*/</code>:</p><pre><code class="language-bash">for user_dir in "${USERS_DIR}"/*/; do
    user_id="$(basename "${user_dir}")"
    echo "=== Fetching for user '${user_id}' ==="
    .venv/bin/python -m finance_system.providers.truelayer fetch "${user_id}"
    fetch_status=$?
    if [[ ${fetch_status} -ne 0 ]]; then
        echo "fetch failed for '${user_id}' (exit ${fetch_status}) - skipping its SQLite load" &gt;&amp;2
        status=1
        continue
    fi
    .venv/bin/python -m finance_system.storage.sqlite "${user_id}" || status=1
done

exit "${status}"
</code></pre><p>Two properties are worth noting. A new user is picked up automatically - no edit to the script or the unit - because "who's a user" is just "who has a directory". And one user's failure doesn't stop the rest: it records <code>status=1</code>, skips that user's load step, and carries on, then exits non-zero at the end so systemd still reports the run as failed. That's the same "keep going, but don't hide it" posture <code>fetch()</code> already takes per bank. (The script has since been adjusted twice - a distinct exit code for "no banks linked", and the storage module's new entry point - both in <a href="https://ghost.atathome.me/making-the-nightly-sync-boring/">post 17</a>.)</p><h2 id="moving-the-existing-data-once">Moving the existing data, once</h2><p>There was one real user's data in the old flat layout, and the new code would look for it under <code>storage/users/{id}/</code> - leaving it, in the commit's words, "simply invisible - not deleted, just not where the app is now looking." <code>deploy/migrate-to-per-user-storage.sh</code> moves it. The script is cautious in the ways a one-off script touching live data should be:</p><ul><li>It takes the target user id as a required argument, and tells you where to find it (<code>GET /api/auth/me</code>, while logged in as the account that should own the data).</li><li>It <strong>refuses to run</strong> if the destination directory already exists, rather than merging into it.</li><li>It <code>mv</code>s rather than copies, so the header comment says to back up <code>storage/</code> first.</li><li>It's explicitly not wired into any deploy: "run by hand on the server in the same deploy window as this change, not something to automate or run unattended against live data."</li></ul><p>The follow-ups were mundane in the way deploy scripts usually are. One of them (<code>fix remote setup user</code>) set the service user to <code>root</code> in <code>remote-setup.sh</code> to match the units from earlier, and another (<code>fix migrate script</code>) replaced the script's relative <code>cd</code> with an absolute <code>cd /opt/finance-system</code>, since it's only ever run on that one server.</p><h2 id="making-the-split-visible">Making the split visible</h2><p>The Debug page from the next post lists raw database tables. A last commit updated it to show the new reality: one "Global data" section (the shared <code>providers</code> table) and one "Your data" section (everything in that user's own file), as two instances of the same component filtering one API response - no backend change needed.</p><p>The per-user tree is also what made some later features simple. Hargreaves Lansdown credentials (<a href="https://ghost.atathome.me/hargreaves-lansdown/">post 14</a>) live under <code>secrets/</code> in the same tree, and per-user sync logs (<a href="https://ghost.atathome.me/making-the-nightly-sync-boring/">post 17</a>) sit under <code>logs/providers/{user_id}/</code>. Both just fell out of "everything about a user lives under one directory".</p><hr><p>Previous: <a href="https://ghost.atathome.me/handing-auth-to-identity-system/">← Handing authentication to identity-system</a> · Next: <a href="https://ghost.atathome.me/seeing-everything-in-one-place/">Seeing everything in one place →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[House-move inventory: A core that knows nothing about HTTP - Part 2]]></title><description><![CDATA[~8 min read

Post 1 described rooms, boxes and items. This post is about where the rules about them live, because that decision has paid for itself more often than any other in the project.

The rule is one sentence in CLAUDE.md: inventory domain logic lives only in inventory.core. The API and the CLIs are thin translation layers - no rules, no validation logic, no aggregation. If a behaviour matters (quantity must be at least 1, a box that isn't going can have a reason, clones copy their source]]></description><link>https://brightbot.co.uk/a-core-that-knows-nothing-about-http/</link><guid isPermaLink="false">Ghost__Post__6ae5bab81df6faba86556b3f</guid><category><![CDATA[Building Inventory System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Tue, 03 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1776062356815-d5e8312792a8?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDN8fFJlc3BvbnNpYmlsaXR5JTIwfGVufDB8fHx8MTc5MzUyMzkwMnww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1776062356815-d5e8312792a8?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDN8fFJlc3BvbnNpYmlsaXR5JTIwfGVufDB8fHx8MTc5MzUyMzkwMnww&ixlib=rb-4.1.0&q=80&w=2000" alt="House-move inventory: A core that knows nothing about HTTP - Part 2"/><p><em>~8 min read</em></p><p><a href="https://ghost.atathome.me/why-a-spreadsheet-wasnt-enough/">Post 1</a> described rooms, boxes and items. This post is about where the <em>rules</em> about them live, because that decision has paid for itself more often than any other in the project.</p><p>The rule is one sentence in <code>CLAUDE.md</code>: <strong>inventory domain logic lives only in <code>inventory.core</code>.</strong> The API and the CLIs are thin translation layers - no rules, no validation logic, no aggregation. If a behaviour matters (quantity must be at least 1, a box that isn't going can have a reason, clones copy their source's decision but reset to "packing"), it's in <code>core.py</code>, and there's exactly one place to read it.</p><h2 id="talking-to-storage-through-a-protocol">Talking to storage through a Protocol</h2><p><code>core.py</code> never imports <code>sqlite3</code>. It talks to storage through a <code>Repository</code> protocol in <code>repository.py</code>:</p><pre><code class="language-python">class Repository(Protocol):
    def get_box_by_code(self, code: str) -&gt; Box | None: ...
    def list_boxes(...) -&gt; list[Box]: ...
    def add_item(self, item: Item) -&gt; Item: ...
    ...
</code></pre><p><code>SqliteRepository</code> implements it, and it is <em>persistence only</em> - no business rules sneak in there either. <code>factory.py</code> is the one place that wires the two together (<code>open_service()</code>, <code>open_api_service()</code>), so nothing else needs to know which storage is in use.</p><p>Why bother with a Protocol for a project with a single database? Three reasons that all turned out to be real:</p><ul><li><strong>Tests can use anything.</strong> Core tests run against a temp-file database through the same wiring as production.</li><li><strong>It keeps me honest.</strong> If I catch myself wanting to put an <code>if</code> in a SQL query, the Protocol is the thing that makes me notice I'm leaking a rule into the wrong layer.</li><li><strong>It documents the surface.</strong> The list of repository methods is a precise inventory of what the domain needs from storage.</li></ul><h2 id="time-is-a-dependency-too">Time is a dependency too</h2><p>The other injectable is the clock. <code>InventoryService</code> takes a <code>clock</code> callable, and the services use <code>self._clock()</code>, never <code>datetime.now()</code>. Timestamps are always timezone-aware UTC, and tests pass a <code>FakeClock</code> they can advance:</p><pre><code class="language-python">now = self._clock()
box = self._repo.add_box(Box(code=code, room=resolved.name, ..., created_at=now))
</code></pre><p>This looks fussy until you write the box-history feature (post 11), where the tests need to assert that "renamed" happened <em>after</em> "created". With a real clock that's a sleep or a flaky comparison; with a fake one it's an assertion.</p><h2 id="errors-are-domain-errors">Errors are domain errors</h2><p><code>errors.py</code> holds a small hierarchy - <code>DuplicateBoxCode</code>, <code>ValidationError</code>, <code>TranslationUnavailable</code>, and so on. The core raises them; it has no idea what an HTTP status is. The API layer owns a single mapping from error class to status code (validation errors become 422, "not found" 404, duplicates 409). That is the entire contract between the layers, and it means a new error type needs one line in one dict.</p><h2 id="what-thin-actually-means-in-the-api">What "thin" actually means in the API</h2><p>A route handler in <code>app.py</code> does three things: take validated input, call one service method, shape the output. Here's the core of the all-rooms export from post 12, minus its options:</p><pre><code class="language-python">sheets = svc.all_room_sheets(status=status, decision=decision)
</code></pre><p>The aggregation - "every room with at least one matching box" - is a method on the service, not a loop in the route. The loop that <em>is</em> in the route (rendering each room's sheet and merging the PDFs) is formatting, which the architecture rules allow: <code>render/</code> is "pure formatting over domain objects - no storage access".</p><p>The test for whether a layer is thin: could I add a CLI that does the same job by calling the same service methods, and get identical behaviour for free? Here the answer is yes, which is exactly what the planned thin inventory CLI relies on.</p><h2 id="the-cost">The cost</h2><p>It is more files and more indirection than a single <code>app.py</code> with SQL in the handlers, and for the first day it felt like ceremony. The payoff arrived in the first week of using it for real. Changing a default (the currency moved from "whatever you typed" to GBP) meant editing one function, and the failing tests told me exactly which assertions had hard-coded the old value - which is why <code>CLAUDE.md</code> now carries the reminder to <code>grep tests/</code> for the old value whenever a domain default changes.</p><p>By the numbers: when the REST API landed (Phase 2) the whole project had 57 tests. It has nearly 400 backend tests now, and the layering is the reason I trust adding to it.</p><p>Next: the money rules, and why the euro figure is deliberately a bit embarrassing.</p><hr><p>Previous: <a href="https://ghost.atathome.me/why-a-spreadsheet-wasnt-enough/">← Why a spreadsheet wasn't enough</a> · Next: <a href="https://ghost.atathome.me/money-and-an-approximate-euro/">Money, currencies and an approximate euro →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Marketplace Listing Helper: A helper that never presses Publish - Part 1]]></title><description><![CDATA[~6 min read

I had a few dozen things to sell, mostly Warhammer models, and a spreadsheet describing them. Facebook Marketplace wanted each one typed into a form, one at a time: title, price, category, condition, description, photos. None of it is hard. All of it is repetitive, and repetition is exactly what a computer should be doing for me. So I started building a Chrome extension to do the typing, and the first decision was about what it must not do.


The rule everything else hangs off

The ]]></description><link>https://brightbot.co.uk/listing-helper-a-helper-that-never-presses-publish/</link><guid isPermaLink="false">Ghost__Post__6ae71f951df6faba86556bdc</guid><category><![CDATA[Building Marketplace Listing Helper]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Mon, 02 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1576562331281-d09e46af9854?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDd8fG1hcmtldHxlbnwwfHx8fDE3OTM1MzIxNDh8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1576562331281-d09e46af9854?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDd8fG1hcmtldHxlbnwwfHx8fDE3OTM1MzIxNDh8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Marketplace Listing Helper: A helper that never presses Publish - Part 1"/><p><em>~6 min read</em></p><p>I had a few dozen things to sell, mostly Warhammer models, and a spreadsheet describing them. Facebook Marketplace wanted each one typed into a form, one at a time: title, price, category, condition, description, photos. None of it is hard. All of it is repetitive, and repetition is exactly what a computer should be doing for me. So I started building a Chrome extension to do the typing, and the first decision was about what it must <em>not</em> do.</p><h2 id="the-rule-everything-else-hangs-off">The rule everything else hangs off</h2><p>The extension fills the form in. <strong>I</strong> press Next and Publish. It never clicks either, and it never touches Renew, Delete or messaging on Facebook either.</p><p>It would be technically easy to go further. A script that fills the form, clicks Publish and moves to the next item is only a few more lines. But that is automation of my Facebook account, and I'd rather not give Facebook a reason to flag it. Having a human press Publish on every listing keeps the extension in the role of a very fast typist. It also means I check every listing before it goes live, which for a seller is no bad thing: the form is where you notice a wrong price or a missing photo.</p><p>That became the first section of the project's <code>CLAUDE.md</code>, as a hard rule not to be changed without my asking:</p><ul><li>never automate Next, Publish, Renew, Delete or messaging on Facebook;</li><li>no background posting, scheduled actions or headless browsing;</li><li>no remote servers or third-party APIs, so all data stays in the browser and in local CSV files;</li><li>selling and delisting on other platforms is out of scope, so "Mark sold" in the extension is all that's needed.</li></ul><p>Writing the rules down first has paid off since. When a feature idea comes up (auto-renew, auto-replying to messages) the answer is already on file.</p><h2 id="the-shape-of-the-extension">The shape of the extension</h2><p>It's a Manifest V3 extension with a deliberately small footprint: one content script that runs on <code>https://www.facebook.com/*</code>, and the <code>storage</code> permission. There is no build step and no dependencies. It's plain JavaScript that loads straight from the folder with Chrome's "Load unpacked", so editing a file and pressing reload is the whole development loop.</p><p>The content script adds a small panel (about 330px wide) in the bottom-right corner of Marketplace pages. Two details were worth getting right early.</p><p><strong>Facebook is a single-page app.</strong> Navigating from the feed to Marketplace doesn't reload the page, so a content script that checks the URL once at load would show the panel on the wrong pages, or never. Instead the script polls the path once a second and adds or removes the panel:</p><pre><code class="language-js">function sync() {
  const on = location.pathname.startsWith("/marketplace");
  if (on &amp;&amp; !panel.isConnected) document.body.appendChild(panel);
  if (!on &amp;&amp; panel.isConnected) { panel.remove(); document.getElementById("mlh-backdrop")?.remove(); }
}
</code></pre><p>A one-second poll isn't elegant, but it's cheap and it doesn't depend on any of Facebook's internal events, which change without warning.</p><p><strong>The script must only run once.</strong> Content scripts can be injected more than once, and a second copy would add a second panel. Everything is wrapped in an IIFE that bails out if a flag is already set:</p><pre><code class="language-js">(() =&gt; {
  if (window.__mlhLoaded) return;
  window.__mlhLoaded = true;
  // ...
})();
</code></pre><h2 id="what-the-panel-does">What the panel does</h2><p>The first version could do five things: keep a list of items, import and export that list as CSV, pair photos with items, fill the form, and record what had been listed. The rest of the series is those pieces in turn: the form filling (the fragile part) is next, then the data model, then the work of getting a real spreadsheet in.</p><h2 id="what-this-adds-up-to">What this adds up to</h2><p>The interesting part of this first step was not code. It was deciding that the tool would stop one click short of the finish line, and writing that down so that it holds. Everything that follows (the fragile form filling, the honest per-field report, the "pick manually" fallbacks) follows from that one choice: the tool does the typing, and tells me plainly what it couldn't do, because I'm the one who presses Publish.</p><hr><p>Next: <a href="https://ghost.atathome.me/listing-helper-filling-in-facebooks-form/">Filling in Facebook's form →</a> · Back to <a href="https://ghost.atathome.me/tag/building-marketplace-listing-helper/">series index</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Childcare calculator: From two childminders to four - Part 2]]></title><description><![CDATA[~7 min read

Last time the calculator had exactly two childminders, written into the markup as "A" and "B". That matched my own situation, but it's a poor assumption for a tool other people might use. This post covers the commit that replaced it with one to four childminders, and what that did to the code.


The assumption was everywhere

Two childminders sounds like a small thing to hardcode. In the first version it showed up in:

 * the markup, as two pairs of name and rate inputs
 * the sched]]></description><link>https://brightbot.co.uk/from-two-childminders-to-four/</link><guid isPermaLink="false">Ghost__Post__6ae473071df6faba86556af6</guid><category><![CDATA[Building a Childcare Calculator]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Mon, 02 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1537655780520-1e392ead81f2?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fGNoaWxkbWluZGVyfGVufDB8fHx8MTc5MzM1NjY4N3ww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1537655780520-1e392ead81f2?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fGNoaWxkbWluZGVyfGVufDB8fHx8MTc5MzM1NjY4N3ww&ixlib=rb-4.1.0&q=80&w=2000" alt="Childcare calculator: From two childminders to four - Part 2"/><p><em>~7 min read</em></p><p><a href="https://ghost.atathome.me/why-a-static-page/">Last time</a> the calculator had exactly two childminders, written into the markup as "A" and "B". That matched my own situation, but it's a poor assumption for a tool other people might use. This post covers the commit that replaced it with one to four childminders, and what that did to the code.</p><h2 id="the-assumption-was-everywhere">The assumption was everywhere</h2><p>Two childminders sounds like a small thing to hardcode. In the first version it showed up in:</p><ul><li>the markup, as two pairs of name and rate inputs</li><li>the schedule dropdowns, as options with values <code>'A'</code> and <code>'B'</code></li><li>the weekly totals, as <code>{ A: hours, B: hours }</code></li><li>the cost calculation and the summary cards</li><li>the colours</li></ul><p>Making the number variable meant touching all of it. The commit was +358/-223 lines, which is a lot for what looks like "add an Add button".</p><h2 id="one-array-as-the-source-of-truth">One array as the source of truth</h2><p>The core change was moving from named fields to an array:</p><pre><code class="language-js">// each childminder: { name, rate, pct }  (pct = relative weight for the custom split)
let childminders = [
  { name: 'Childminder A', rate: 5.50, pct: 50 },
  { name: 'Childminder B', rate: 7.50, pct: 50 }
];

// schedule[0..4] = Mon..Fri, { cm: &lt;childminder index&gt; | -1 for none, hours: &lt;number&gt; }
</code></pre><p>A schedule entry's <code>cm</code> changed from the string <code>'A'</code> to an <strong>index</strong> into that array, with <code>-1</code> meaning "nobody that day". Weekly hours went from <code>{ A, B }</code> to a numeric array with one slot per childminder, and every loop over "both childminders" became a loop over <code>n</code>.</p><p>An index is simple, but it has a catch.</p><h2 id="removing-someone-shifts-everyone-after-them">Removing someone shifts everyone after them</h2><p>If three childminders exist and you remove the first, the old second is now index 0. Any schedule day pointing at index 1 would suddenly point at the wrong person, or at nobody. So removal has to repoint the schedule:</p><pre><code class="language-js">function removeChildminder(idx) {
  if (childminders.length &lt;= MIN_CM) return;
  childminders.splice(idx, 1);
  // repoint the weekly schedule: dropped -&gt; none, later indices shift down one
  schedule.forEach(entry =&gt; {
    if (entry.cm === idx) entry.cm = -1;
    else if (entry.cm &gt; idx) entry.cm -= 1;
  });
  refreshAll();
}
</code></pre><p>Days that belonged to the removed childminder become unscheduled, and days that belonged to anyone later get decremented. It's four lines, and it's the bug I'd most expect to ship with a naive "just splice the array" version.</p><p>Using stable IDs instead of indices would avoid the shifting. I didn't, because the list is capped at four and the repointing is easy to read and test by hand. For a bigger list I'd switch.</p><h2 id="rebuild-the-dom-from-state">Rebuild the DOM from state</h2><p>With a variable number of cards, hand-written HTML stops working. The page now rebuilds the childminder cards, the schedule dropdowns, the custom-split sliders and the legend from the arrays, through a set of <code>render*</code> functions that <code>refreshAll()</code> calls in turn.</p><p>That created a problem with typing. If every keystroke in a name field rebuilt the cards, the input would lose focus after each character. The fix is a comment in the code and a deliberate split in the event handler:</p><pre><code class="language-js">if (e.target.classList.contains('cmName')) {
  childminders[idx].name = e.target.value;
  // the name shows in several places; refresh those but NOT the cards (would drop focus)
  renderSchedule();
  renderManualRows();
  renderLegend();
  calculate();
}
</code></pre><p>The name appears in the schedule dropdowns, the sliders and the legend, so those get re-rendered. The card holding the input being typed in does not. Rate changes only need <code>calculate()</code>, since a rate appears nowhere but the maths.</p><p>Events are also <strong>delegated</strong> onto the container elements (<code>cmListEl</code>, <code>schedBodyEl</code>, <code>manualRowsEl</code>). The containers survive re-renders and their children don't, so listeners attached to the children would be thrown away every time.</p><h2 id="colours">Colours</h2><p>Each childminder needs a colour that carries through the calendar, the legend and the summary cards. <code>styles.css</code> defines a four-slot palette (<code>cm-c0</code> to <code>cm-c3</code>), and <code>cmClass(i)</code> maps an index to a class:</p><pre><code class="language-js">const MAX_CM = 4;         // colours cm-c0..cm-c3 are defined in styles.css
const PALETTE_SIZE = 4;
function cmClass(i) { return 'cm-c' + (i % PALETTE_SIZE); }
</code></pre><p>The cap of four is really a palette limit. A fifth childminder would need a fifth distinguishable colour, and four was already enough for any realistic case. Having one constant refer to the other in a comment keeps the next person from raising the limit without adding a colour.</p><h2 id="what-got-easier">What got easier</h2><p>Not much got easier for the user, but one thing did for me: once the childminders were data, adding a feature that applies to all of them stopped needing special cases. That mattered a lot for the next problem, which is that free hours are shared between the childminders, and <em>how</em> they're shared changes the bill. <a href="https://ghost.atathome.me/splitting-free-hours/">That's next.</a></p><hr><p>Previous: <a href="https://ghost.atathome.me/why-a-static-page/">← Why a static page</a> · Next: <a href="https://ghost.atathome.me/splitting-free-hours/">Splitting free hours →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Central login service: Moving configuration into the database - Part 6]]></title><description><![CDATA[~25 min read

By the end of Part 5, the service was doing real work: apps behind the proxy used it for forward-auth, and Jenkins signed in through it with OpenID Connect. What it wasn't was pleasant to operate, and the reason was the same in both of its configurable parts.

There were two pieces of configuration that changed over time:

 * The apps directory: the cards on the landing page, held in apps.json.
 * The OIDC client registry: the relying parties allowed to sign users in, held in oidc_]]></description><link>https://brightbot.co.uk/identity-system-moving-configuration-into-the-database/</link><guid isPermaLink="false">Ghost__Post__6ada2fa71df6faba86556a91</guid><category><![CDATA[Building Identity System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Mon, 02 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1544383835-bda2bc66a55d?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDE2fHxkYXRhYmFzZXxlbnwwfHx8fDE3OTI2ODQxNzB8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1544383835-bda2bc66a55d?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDE2fHxkYXRhYmFzZXxlbnwwfHx8fDE3OTI2ODQxNzB8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Central login service: Moving configuration into the database - Part 6"/><p><em>~25 min read</em></p><p>By the end of <a href="https://ghost.atathome.me/identity-system-making-jenkins-sign-in/">Part 5</a>, the service was doing real work: apps behind the proxy used it for forward-auth, and Jenkins signed in through it with OpenID Connect. What it wasn't was <em>pleasant to operate</em>, and the reason was the same in both of its configurable parts.</p><p>There were two pieces of configuration that changed over time:</p><ul><li><strong>The apps directory</strong>: the cards on the landing page, held in <code>apps.json</code>.</li><li><strong>The OIDC client registry</strong>: the relying parties allowed to sign users in, held in <code>oidc_clients.json</code>.</li></ul><p>Both were files read once at startup. To add an app to the landing page I edited a JSON file, committed it, waited for Jenkins to build and deploy, and the service restarted to pick it up. One of the commits in the history is literally <code>feat: add extra applications</code>, a two-entry change to <code>apps.json</code> that cost a full pipeline run. To register a new OIDC client I had to compute an Argon2 hash by hand in a Python one-liner, paste it into a file on the server, and restart.</p><p>This part is about replacing both files with a small SQLite-backed registry managed from admin pages in the UI. The commit is <code>feat: enable application/oidc control from within admin center</code>, 28 files and about 1,600 lines. Most of those lines are unremarkable CRUD, so I'll skip the typing and concentrate on the design decisions that weren't obvious: where the data lives, how the migration from files works without duplicating anything, how a secret can be shown once, and how a live-editable security setting interacts with the code that reads it.</p><h2 id="why-a-database-and-why-this-database">Why a database, and why <em>this</em> database</h2><p>The question "files or database?" is really "who edits this, and how often?". A <code>.env</code> file holds settings an operator picks once per deployment. A list of apps and a list of clients are <em>content</em>: they change as the household's software changes, and the person changing them is me in a browser, not me over SSH.</p><p>There was a second, less obvious argument for the database, which comes from Part 2. Everything stateful on the container has to live in <code>data/</code> or the next deploy's <code>rsync --delete</code> removes it. Part 4 had already stretched that rule to cover the OIDC signing key, and the client registry file had briefly needed its own special-case handling in <code>deploy.sh</code>. If configuration lives in the <strong>same SQLite file as the accounts</strong>, it inherits the existing protection for free, and the number of things that can be accidentally deleted by a deploy goes <em>down</em>.</p><p>That's the choice the new module makes, and its docstring states it directly:</p><blockquote>Lives in the same db file as sessionkit's own tables, as sibling tables on its own connection... That puts it under the same <code>data/</code> protection the rest of this service's state already relies on... so an admin's edits survive every deploy.</blockquote><p>Three tables, all small:</p><pre><code class="language-python">_SCHEMA = """
CREATE TABLE IF NOT EXISTS apps (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    name        TEXT NOT NULL,
    url         TEXT NOT NULL,
    description TEXT NOT NULL DEFAULT ''
);

CREATE TABLE IF NOT EXISTS oidc_clients (
    client_id          TEXT PRIMARY KEY,
    client_secret_hash TEXT NOT NULL,
    redirect_uris      TEXT NOT NULL,
    allowed_scopes     TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS identity_meta (
    key   TEXT PRIMARY KEY,
    value TEXT NOT NULL
);
"""
</code></pre><p>A few choices in there:</p><ul><li><strong><code>IF NOT EXISTS</code> everywhere.</strong> The registry runs the schema script on every construction. It's the whole "migration system": there's one version of the schema, and creating it is idempotent. When a column needs to change, that's the moment to introduce real migrations, and not before.</li><li><strong><code>apps</code> has an integer surrogate <code>id</code></strong>, while <code>oidc_clients</code> uses <code>client_id</code> itself as the primary key. An app has no natural unique key (two apps could share a name, and a URL might change), so the admin UI needs a stable handle to say "edit this one". A client already <em>has</em> a unique, human-chosen, immutable identifier, so inventing another would be redundant.</li><li><strong>Lists stored as JSON text.</strong> <code>redirect_uris</code> and <code>allowed_scopes</code> are JSON arrays in a <code>TEXT</code> column, written sorted. The registry only ever reads and writes whole client records and never queries "which clients allow this URI", so a join table would be structure for its own sake. Sorting makes the stored value deterministic.</li><li><strong><code>identity_meta</code></strong>, a generic key-value table, exists for one purpose that I'll get to in the migration section.</li></ul><h3 id="its-own-connection-its-own-lock">Its own connection, its own lock</h3><p>The registry doesn't reuse sessionkit's store object. It gets a <em>second connection to the same file</em>:</p><pre><code class="language-python">registry = ConfigRegistry(connect(settings.db_path, check_same_thread=False))
</code></pre><p>and serialises access with its own lock, in the same style as the library's store:</p><pre><code class="language-python">def list_apps(self) -&gt; list[dict]:
    with self._lock:
        rows = self._conn.execute(
            "SELECT id, name, url, description FROM apps ORDER BY id"
        ).fetchall()
    return [dict(row) for row in rows]
</code></pre><p>Since FastAPI runs synchronous routes on a thread pool, and a SQLite connection isn't safe for concurrent use, every method takes the lock before touching the connection. It's the simplest correct answer, and it's consistent with the single-writer posture the project documents everywhere: this is one instance of one small service.</p><p>Two connections to the same SQLite file means SQLite's own file locking arbitrates between them, which is fine at this scale; writers briefly block each other. It also keeps the registry fully decoupled from the library: no reaching into private attributes of the store to borrow its connection, and no risk that a library upgrade changes something I was quietly depending on.</p><h2 id="the-api-surface">The API surface</h2><p>The registry's methods map one-to-one to routes, all guarded by the same dependency. In Part 3 the admin users route did its own <code>is_admin</code> check inline. With five more admin routes arriving, that check was extracted:</p><pre><code class="language-python">def require_admin(user: User = Depends(current_user)) -&gt; User:
    if not settings.is_admin(user.email):
        raise HTTPException(status_code=403, detail="forbidden")
    return user
</code></pre><p>and every admin route declares it as a dependency:</p><pre><code class="language-python">@app.get("/api/admin/apps")
def admin_list_apps(_admin: User = Depends(require_admin)):
    return registry.list_apps()
</code></pre><p>The leading underscore on <code>_admin</code> signals that the value is unused, and the dependency is there purely for its side effect of rejecting the request. That's a small thing, but a dependency is the <em>right</em> mechanism: it's declared in the function signature where you can't miss it, it composes with <code>current_user</code> (so unauthenticated requests get <code>401</code> and authenticated non-admins get <code>403</code>, from one place), and it's hard to forget when copying a route.</p><p>"Hard to forget" is important, because forgetting is the failure mode here. A missing guard on one admin route silently exposes it to everyone. The test file guards against that with a table of every admin route:</p><pre><code class="language-python">ADMIN_ROUTES = [
    ("get", "/api/admin/apps", None),
    ("post", "/api/admin/apps", {...}),
    ("put", "/api/admin/apps/1", {...}),
    ("delete", "/api/admin/apps/1", None),
    ("get", "/api/admin/oidc-clients", None),
    ("post", "/api/admin/oidc-clients", {...}),
    ("put", "/api/admin/oidc-clients/x", {...}),
    ("post", "/api/admin/oidc-clients/x/rotate-secret", None),
    ("delete", "/api/admin/oidc-clients/x", None),
]

def test_every_admin_config_route_requires_login(client):
    for method, path, body in ADMIN_ROUTES:
        assert _call(client, method, path, body).status_code == 401, (method, path)

def test_every_admin_config_route_rejects_non_admins(client, auth):
    _non_admin(client, auth)
    for method, path, body in ADMIN_ROUTES:
        assert _call(client, method, path, body).status_code == 403, (method, path)
</code></pre><p>One loop, two tests, all nine routes. The <code>(method, path)</code> tuple as the assertion message means a failure names the exact route that's open. It's the sort of test that costs ten minutes to write and protects against the one mistake most likely to be made in the next dozen commits. It does have a weakness I'll acknowledge: it only covers routes <em>in the list</em>. A tenth route added without being appended to <code>ADMIN_ROUTES</code> wouldn't be tested. Tests catch forgotten guards only if they're also not forgotten.</p><h2 id="validation-at-the-edge">Validation at the edge</h2><p>Previously a malformed apps file or client file was the operator's problem. Now arbitrary strings arrive over HTTP, and some of them end up somewhere security-sensitive. The request bodies are declared as Pydantic models with explicit constraints:</p><pre><code class="language-python"># Same rules the public apps directory and the OIDC redirect_uri exact-match
# depend on - a plain absolute http(s) URL, no whitespace. Deliberately not
# pydantic's HttpUrl: that normalises the value (adds a trailing slash to a
# bare origin), and the redirect_uri check is an exact string match.
_HttpUrl = Annotated[str, StringConstraints(pattern=r"^https?://\S+$", max_length=2000)]
_OidcScope = Literal["openid", "email", "profile"]

class AppIn(BaseModel):
    name: str = Field(min_length=1, max_length=200)
    url: _HttpUrl
    description: str = Field(default="", max_length=1000)

class OidcClientIn(BaseModel):
    client_id: Annotated[str, StringConstraints(pattern=r"^[A-Za-z0-9._-]{1,200}$")]
    redirect_uris: list[_HttpUrl] = Field(min_length=1)
    allowed_scopes: list[_OidcScope] = Field(default_factory=lambda: ["openid"], min_length=1)
</code></pre><p>The comment about <code>HttpUrl</code> is worth dwelling on, because it's an interaction between two pieces of code that don't know about each other. Pydantic's built-in <code>HttpUrl</code> type is the obvious choice for "a URL". But it <em>normalises</em> what it parses: <code>https://example.com</code> becomes <code>https://example.com/</code>. Part 4's <code>/authorize</code> compares the supplied <code>redirect_uri</code> against the stored set with an exact string match, and an OIDC client sends whatever it was configured with. If the registry silently added a trailing slash on save, the stored value would no longer equal what the relying party sends, and every login would fail with "unknown client_id or redirect_uri" for a reason that's invisible in the admin UI. So the validator is a plain regular expression on a plain string: it checks the shape and leaves the value alone.</p><p>The regex <code>^https?://\S+$</code> does three jobs. It requires an <code>http</code> or <code>https</code> scheme, which rejects <code>javascript:alert(1)</code> (an apps-directory link is rendered as an <code>&lt;a href&gt;</code>, so this is a stored-XSS vector, not a nicety), a bare hostname like <code>finance.example.com</code>, and anything with whitespace. The test enumerates exactly those:</p><pre><code class="language-python">for bad in ["javascript:alert(1)", "finance.example.com", "https://", "https://a b.example.com"]:
    resp = client.post("/api/admin/apps", json={"name": "X", "url": bad})
    assert resp.status_code == 422, bad
</code></pre><p>Other notes on this block:</p><ul><li><code>allowed_scopes</code> is a <code>Literal</code> of the three known scopes, so a typo or an invented scope like <code>admin</code> is a <code>422</code> rather than a stored value that does nothing.</li><li><code>client_id</code> is restricted to a conservative character set: letters, digits, <code>.</code>, <code>_</code>, <code>-</code>. It ends up in URL paths (<code>/api/admin/oidc-clients/{client_id}</code>) and in the <code>aud</code> claim of tokens, so keeping it boring prevents encoding surprises in both.</li><li>There's a separate <code>OidcClientUpdate</code> model without <code>client_id</code>. A client's identifier is immutable once created, so the update shape simply can't carry one, and the UI disables the field while editing.</li><li>Creating a client with an ID that already exists returns <code>409 Conflict</code>, via the registry's <code>add_oidc_client</code> returning <code>False</code> on a SQLite <code>IntegrityError</code> rather than raising.</li></ul><h2 id="showing-a-secret-exactly-once">Showing a secret exactly once</h2><p>Creating a client means handing a secret to the administrator, who pastes it into the relying party. Previously the administrator invented the secret, hashed it by hand, and so already knew it. Now the <strong>server generates it</strong>:</p><pre><code class="language-python">def generate_client_secret() -&gt; str:
    """A fresh random client secret, generated server-side so the admin
    never has to pick (or hand-hash) one."""
    return secrets.token_urlsafe(32)
</code></pre><p>That's 256 bits from the OS's cryptographic source, and the URL-safe alphabet (letters, digits, <code>-</code> and <code>_</code>) deliberately sidesteps the <code>+/=</code> characters that caused Part 5's Basic-auth trouble. (The fix in Part 5 means such characters are handled correctly anyway, but a generated secret that avoids them removes a whole class of copy-paste and encoding problems for whatever relying party is on the other end.)</p><p>The create route hashes it, stores the hash, and returns the plaintext in the response, once:</p><pre><code class="language-python">@app.post("/api/admin/oidc-clients", status_code=201)
def admin_add_oidc_client(payload: OidcClientIn, _admin: User = Depends(require_admin)):
    secret = generate_client_secret()
    client = OidcClient(
        client_id=payload.client_id,
        client_secret_hash=hash_client_secret(secret),
        redirect_uris=frozenset(payload.redirect_uris),
        allowed_scopes=frozenset(payload.allowed_scopes),
    )
    if not registry.add_oidc_client(client):
        raise HTTPException(status_code=409, detail="client_id already registered")
    # The one and only time the plaintext secret leaves the server.
    return {**_oidc_client_json(client), "client_secret": secret}
</code></pre><p>Every other representation of a client goes through one serialiser that never includes a secret or a hash:</p><pre><code class="language-python">def _oidc_client_json(client: OidcClient) -&gt; dict:
    # Never the hash - and the plaintext secret only ever appears in the
    # create/rotate responses, once.
    return {
        "client_id": client.client_id,
        "redirect_uris": sorted(client.redirect_uris),
        "allowed_scopes": sorted(client.allowed_scopes),
    }
</code></pre><p>The test asserts both halves of the contract: the create response contains a secret of at least 32 characters, and <em>no listing ever contains either <code>client_secret</code> or <code>client_secret_hash</code></em>. It also reaches into the registry to check the stored hash differs from the plaintext and that <code>verify_client_secret</code> accepts the real secret. The end-to-end test then uses the freshly created client to complete a full authorisation-code flow, which proves the generated, hashed secret actually works against the token endpoint, the test that catches an "I hashed it differently from how I verify it" bug.</p><h3 id="the-consequence-lost-means-rotated">The consequence: lost means rotated</h3><p>If a secret is only ever shown once and only its hash is stored, a lost secret can't be recovered. Nobody, including me with database access, can read it back. The remedy is <strong>rotation</strong>:</p><pre><code class="language-python">@app.post("/api/admin/oidc-clients/{client_id}/rotate-secret")
def admin_rotate_oidc_client_secret(client_id: str, _admin: User = Depends(require_admin)):
    secret = generate_client_secret()
    if not registry.set_oidc_client_secret_hash(client_id, hash_client_secret(secret)):
        raise HTTPException(status_code=404, detail="client not found")
    return {"client_id": client_id, "client_secret": secret}
</code></pre><p>New secret, new hash, old hash overwritten, so <strong>the old secret stops working immediately</strong>. The UI's confirm dialog says exactly that ("Rotate the secret for jenkins? The old one stops working immediately"), because rotating while the relying party is still configured with the old secret breaks its logins until someone updates it. The test checks both directions: the new secret verifies and the old one doesn't.</p><p>On the frontend, the plaintext is held in a piece of component state and rendered in a banner with "Copy it now. It won't be shown again - only a hash is kept." and a Dismiss button. It's never written to storage and never logged. Starting an edit clears it; reloading the page loses it. That is the intended behaviour: the page is a courier, not a vault.</p><h2 id="live-reads-making-a-security-setting-editable">Live reads: making a security setting editable</h2><p>Before this change, the OIDC router received a plain dictionary of clients, built once at startup. That can't work any more: a client registered in the UI has to be usable immediately, and a client deleted in the UI has to stop being usable immediately. So the router's parameter changed from data to a <strong>function</strong>:</p><pre><code class="language-python">def create_oidc_router(
    *,
    auth: AuthService,
    settings: Settings,
    lookup_client: Callable[[str], OidcClient | None],
    signing_key: rsa.RSAPrivateKey,
    ...
</code></pre><p>and every use site changed from <code>clients.get(client_id)</code> to <code>lookup_client(client_id)</code>, wired up in <code>create_app</code> as <code>registry.get_oidc_client</code>. The OIDC module doesn't know a database exists; it asks a callable. That keeps <code>oidc.py</code> free of any storage dependency, and it's why the existing OIDC tests needed almost no changes.</p><p>Reading from the database on every authorise and token call costs a tiny indexed lookup on a table with a handful of rows, which is irrelevant next to the Argon2 hash that follows it on the token path. The benefit is that revocation is genuinely immediate, which two tests check:</p><pre><code class="language-python">def test_update_changes_redirect_uris_and_scopes_live(client, auth, oidc_clients):
    ...
    # The old redirect_uri is no longer registered, so /authorize refuses it
    # outright - no restart needed.
    assert old.status_code == 400

def test_delete_client_stops_it_authorizing(client, auth, oidc_clients):
    assert client.delete("/api/admin/oidc-clients/jenkins").status_code == 204
    ...
    assert resp.status_code == 400
</code></pre><p>I think "can I revoke this <em>right now</em>?" is one of the questions to ask of any authentication-adjacent configuration. A static file loaded at boot answers "after the next deploy". A live lookup answers "yes".</p><h2 id="the-migration-files-in-exactly-once">The migration: files in, exactly once</h2><p>The service already had real data in the two JSON files on a running machine. Replacing them with tables without migrating would mean re-entering everything by hand, and a migration that runs <em>twice</em> would duplicate every row. The design needs a one-shot import with a durable "I've done it" flag, and that's what <code>identity_meta</code> is for.</p><pre><code class="language-python">def legacy_import_done(self) -&gt; bool:
    with self._lock:
        row = self._conn.execute(
            "SELECT 1 FROM identity_meta WHERE key = ?", (_LEGACY_IMPORT_KEY,)
        ).fetchone()
    return row is not None

def import_legacy(self, apps: list[dict], clients: list[OidcClient]) -&gt; None:
    """Seeds the tables from the old static files and sets the import
    flag, all in one transaction - a crash partway through leaves the
    flag unset, so the next startup retries the whole import cleanly."""
    with self._lock, self._conn:
        for entry in apps:
            self._conn.execute(
                "INSERT INTO apps (name, url, description) VALUES (?, ?, ?)",
                (entry["name"], entry["url"], entry.get("description", "")),
            )
        for client in clients:
            self._conn.execute("INSERT INTO oidc_clients ...", _client_to_row(client))
        self._conn.execute(
            "INSERT INTO identity_meta (key, value) VALUES (?, 'true')",
            (_LEGACY_IMPORT_KEY,),
        )
</code></pre><p>The load-bearing detail is <code>with self._lock, self._conn:</code>. Using a SQLite connection as a context manager wraps the block in a transaction: commit on success, rollback on an exception. The rows and the flag are written in the <em>same transaction</em>, so there are only two possible end states: all of it happened, or none of it did. A crash halfway through the import leaves no flag and no rows, and the next startup tries again from clean. Without the transaction, a crash after inserting the apps but before setting the flag would cause the next boot to re-insert them, giving duplicates.</p><p>Hashes carry across untouched. The OIDC clients' <code>client_secret_hash</code> values from the old file are inserted as they are, which means every registered relying party keeps working with its existing secret through the migration. Nothing has to be rotated and nobody has to re-enter anything.</p><h3 id="a-subtle-trap-in-the-startup-code">A subtle trap in the startup code</h3><p>The startup logic in <code>main.py</code> has a guard that took some thought:</p><pre><code class="language-python"># Only mark the import done if there was something to import - otherwise a
# box that starts without either file would have its flag set, and a file
# copied in afterwards would silently never be imported.
legacy_files_present = any(
    Path(p).is_file() for p in (settings.apps_path, settings.oidc_clients_path)
)
if legacy_files_present and not registry.legacy_import_done():
    registry.import_legacy(
        load_apps(settings.apps_path),
        list(load_oidc_clients(settings.oidc_clients_path).values()),
    )
</code></pre><p>Consider the simplest version: "if the flag isn't set, import and set it". On a brand new box with neither file, that sets the flag after importing <em>nothing</em>. If someone later drops an <code>apps.json</code> in place expecting it to be picked up, the flag says the import already happened and the file is silently ignored. Gating on "at least one file exists" means the flag only gets set once there was actually something to migrate. The loaders themselves treat a missing file as "nothing to import".</p><p>There's a flip side that this guard doesn't cover. If only <em>one</em> of the two files exists, the import runs for both with the missing one contributing nothing, and the flag is set; a later-arriving second file is then ignored. It's a narrow case, and closing it would take two independent flags. For a one-time migration of a single household's config that's a reasonable thing to leave alone, but it is a gap.</p><p>The project notes record the operational consequence, in terms I'd want to read after a long gap: <strong>editing <code>apps.json</code> or <code>oidc_clients.json</code> on a live box now does nothing, and the way to "fix" that is never to re-run the import, because a re-import would duplicate rows.</strong> The admin pages are the source of truth. And the committed <code>apps.json</code> stays in the repository as the seed for a fresh install, with the loaders retained solely for that purpose.</p><p>The deploy script's header got a matching rewrite. Where it used to explain how the JSON files are protected from <code>--delete</code>, it now says neither needs protecting: after the import the database is the source of truth, and a missing file just means there's nothing to import. Deleting a whole paragraph of special-case reasoning from a script is a very satisfying outcome of a design change.</p><h2 id="admin-navigation-showing-only-what-you-can-use">Admin navigation: showing only what you can use</h2><p>There are now three admin pages: Users, Apps directory, OIDC clients. The nav bar should only show those links to admins. But the frontend doesn't know who's an admin: it knows the user's name and email from <code>/me</code>. The answer is to put the verdict in the response:</p><pre><code class="language-python">def _user_json(user: User) -&gt; dict:
    # is_admin is only here so the frontend can decide which admin pages
    # to show - every admin route still enforces it server-side.
    return {
        "id": user.id,
        "email": user.email,
        "name": user.name,
        "totp_enabled": user.totp_enabled,
        "is_admin": settings.is_admin(user.email),
    }
</code></pre><p>and the nav conditionally renders:</p><pre><code class="language-tsx">{user.is_admin &amp;&amp; (
  &lt;&gt;
    &lt;NavLink to="/admin"&gt;Users&lt;/NavLink&gt;{' '}
    &lt;NavLink to="/admin/apps"&gt;Apps directory&lt;/NavLink&gt;{' '}
    &lt;NavLink to="/admin/oidc-clients"&gt;OIDC clients&lt;/NavLink&gt;{' '}
  &lt;/&gt;
)}
</code></pre><p>The comment on <code>is_admin</code> states the security model plainly: this flag is for <strong>presentation</strong>, not <strong>enforcement</strong>. Hiding a link isn't access control; anyone can type the URL. That's why every admin route is independently guarded, why the pages still handle <code>401</code> and <code>403</code> themselves, and why the test suite asserts every route rejects non-admins. The nav change is a courtesy so that non-admins don't see links that would just say "Forbidden".</p><h2 id="three-admin-pages-one-hook">Three admin pages, one hook</h2><p>The three pages (users, apps, clients) all do the same dance: load a list, map <code>401</code> to a redirect and <code>403</code> to a message, show a table and a form, refresh after a mutation. Instead of copying it a third time, the logic became a hook, <code>useAdminList</code>:</p><pre><code class="language-ts">export function useAdminList&lt;T&gt;(path: string) {
  const [items, setItems] = useState&lt;T[]&gt;([])
  const [status, setStatus] = useState&lt;AdminStatus&gt;('loading')

  const refresh = useCallback(async () =&gt; {
    try {
      setItems(await api.get&lt;T[]&gt;(path))
      setStatus('ok')
    } catch (err) {
      if (err instanceof ApiError &amp;&amp; err.status === 401) setStatus('unauthenticated')
      else if (err instanceof ApiError &amp;&amp; err.status === 403) setStatus('forbidden')
      else setStatus('error')
    }
  }, [path])

  useEffect(() =&gt; {
    refresh()
  }, [refresh])

  return { items, status, refresh }
}
</code></pre><p>Returning <code>refresh</code> is what lets a page re-query after a successful create, update or delete, so the table reflects the server's truth rather than a locally patched copy. That choice costs one extra request per mutation and removes a whole category of "UI drifted from reality" bugs. The API wrapper grew <code>put</code> and <code>delete</code> methods, nginx got two more exact-match <code>location =</code> lines for <code>/admin/apps</code> and <code>/admin/oidc-clients</code> (forget those and a refresh on either page returns <code>404</code>), and the frontend tests grew by about 250 lines.</p><h2 id="what-id-flag">What I'd flag</h2><p>A few honest notes on what this does and doesn't do:</p><ul><li><strong>The admin pages are now a powerful surface.</strong> Anyone on the admin allowlist can register an OIDC client with any redirect URI they like, and the system will happily issue authorisation codes to it. There's no consent screen, and I've been explicit about that trust model. It's also exactly why the allowlist is a static <code>.env</code> value that only I can change, not something editable in the same UI.</li><li><strong>There's no audit trail.</strong> Nothing records who changed what. For a household of one administrator, I accepted that; for anything bigger it would be the first thing to add.</li><li><strong>Deleting a client doesn't revoke tokens already issued</strong>, because tokens are self-contained signed JWTs with a five-minute lifetime. The window is short, but it exists.</li><li><strong>Losing the database now loses more.</strong> Accounts, apps and client credentials all live in <code>auth.db</code>. That concentrates risk in one file, which is the same file that already needed backing up.</li></ul><p>What I got in exchange is the ability to add an app or a relying party from the browser with no deploy and no restart: the same job that used to cost a commit, a pipeline run and a restart.</p><p>The service now does most of what I wanted. Two things were still missing: a way to create a <em>person</em> without a command line, and a user interface that looked like it belonged to a finished product. The final part covers both.</p><hr><p>Previous: <a href="https://ghost.atathome.me/identity-system-making-jenkins-sign-in/">← Making Jenkins sign in</a> · Next: <a href="https://ghost.atathome.me/identity-system-polish-and-creating-users-from-the-browser/">Polish, and creating users from the browser →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: Handing authentication to identity-system - Part 9]]></title><description><![CDATA[~8 min read

Post 6 ended with a login system I was reasonably pleased with: Argon2id passwords, opaque server-side sessions, TOTP two-factor with recovery codes, a password-change form that borrowed login() to verify the current password. It had also, by the end of that post, hit two gaps in the library underneath it - no way to update a user's name or email, and no built-in current-password check - that I'd worked around rather than fixed.

The next day I deleted all of it. This post is about ]]></description><link>https://brightbot.co.uk/handing-auth-to-identity-system/</link><guid isPermaLink="false">Ghost__Post__6ad488c51df6faba865569a8</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Mon, 02 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1667453466805-75bbf36e8707?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fEF1dGhlbnRpY2F0aW9ufGVufDB8fHx8MTc5MjMxNzAwN3ww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1667453466805-75bbf36e8707?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fEF1dGhlbnRpY2F0aW9ufGVufDB8fHx8MTc5MjMxNzAwN3ww&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: Handing authentication to identity-system - Part 9"/><p><em>~8 min read</em></p><p><a href="https://ghost.atathome.me/auth-2fa-and-settings/">Post 6</a> ended with a login system I was reasonably pleased with: Argon2id passwords, opaque server-side sessions, TOTP two-factor with recovery codes, a password-change form that borrowed <code>login()</code> to verify the current password. It had also, by the end of that post, hit two gaps in the library underneath it - no way to update a user's name or email, and no built-in current-password check - that I'd worked around rather than fixed.</p><p>The next day I deleted all of it. This post is about why that was the right call, and what replaced it: a pair of commits that moved authentication out of this app entirely.</p><h2 id="the-real-problem-wasnt-the-code-it-was-the-count">The real problem wasn't the code, it was the count</h2><p>Everything in post 6 was a sensible way to run authentication for <em>one application</em>. But this isn't the only thing I run at home. Each small tool that needed a login would have had to carry its own copy of the same machinery - its own user table, its own 2FA enrolment screen, its own password-change form - and I'd be the only person who'd ever remember how each one differed. The gaps from post 6 were a preview of that: any fix to how accounts work would have to be made once in a library and then rolled out to every app that embedded it.</p><p>The alternative is the pattern nginx calls <code>auth_request</code>: put a single service in front of every app, let it own accounts, and have the app trust whatever identity that service vouches for. That service is a separate project I called <code>identity-system</code>. This app's job shrinks from "authenticate users" to "believe the headers nginx hands me, and make sure those headers can't be forged."</p><h2 id="step-one-put-the-gate-in-front-keep-the-old-door-open">Step one: put the gate in front, keep the old door open</h2><p>The first commit (<code>Gate the app behind identity-system's forward-auth</code>), only touched two files: <code>deploy/nginx.conf</code> and <code>src/finance_system/auth.py</code>. It was deliberately additive - the old cookie login kept working so I could verify the new path without locking myself out.</p><p>In nginx, every request is first checked against identity-system:</p><pre><code class="language-nginx"># Internal-only: reached via auth_request below, never hit directly.
location = /_verify {
    internal;
    proxy_pass http://192.168.71.29/verify;
    proxy_set_header Host identity.atathome.me;
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
    proxy_set_header X-Original-URI $request_uri;
}

location /api/ {
    auth_request /_verify;
    auth_request_set $auth_user_id $upstream_http_x_auth_user_id;
    auth_request_set $auth_user_email $upstream_http_x_auth_user_email;
    auth_request_set $auth_user_name $upstream_http_x_auth_user_name;

    error_page 401 = @api_unauthorized;

    proxy_pass http://127.0.0.1:8000;
    proxy_set_header X-Auth-User-Id $auth_user_id;
    proxy_set_header X-Auth-User-Email $auth_user_email;
    proxy_set_header X-Auth-User-Name $auth_user_name;
}
</code></pre><p>Two details in there matter more than the rest. First, the <code>proxy_set_header</code> lines <em>overwrite</em> the <code>X-Auth-User-*</code> headers unconditionally. If a client sends its own <code>X-Auth-User-Email: someone-else@example.com</code>, nginx replaces it with whatever identity-system actually returned - a forwarded-header scheme is only as trustworthy as that overwrite. Second, the two failure modes are different on purpose. An API call that fails the check gets a bare <code>401</code> with a JSON body, because the frontend's <code>fetch()</code> calls expect JSON. A page load that fails gets a <code>302</code> to identity-system's <code>/login</code> with a <code>rd=</code> parameter carrying the URL to come back to, because that's a human in a browser.</p><p>On the Python side, <code>current_user()</code> learned to prefer those headers and fall back to the cookie session when they weren't there - which is what kept local development and the existing <code>/api/auth/*</code> routes alive in the interim.</p><h2 id="step-two-remove-everything-thats-now-redundant">Step two: remove everything that's now redundant</h2><p>With the gate verified, the second commit (<code>Retire local login/2FA/password now that identity-system fronts auth</code>) did the satisfying part. The diffstat tells it: 22 files, 94 insertions, 897 deletions.</p><p>On the backend, <code>current_user()</code> became purely header-based:</p><pre><code class="language-python">def current_user(request: Request) -&gt; AuthenticatedUser:
    email = request.headers.get("x-auth-user-email")
    user_id = request.headers.get("x-auth-user-id")
    if not email or not user_id:
        raise AuthenticationError()
    return AuthenticatedUser(
        id=user_id,
        email=email,
        name=request.headers.get("x-auth-user-name") or email,
    )
</code></pre><p>A missing header means the app was reached directly, bypassing nginx, and gets a 401 - there's deliberately no fallback to a default user. (That second <code>user_id</code> check arrived a few commits later, for reasons that make more sense in <a href="https://ghost.atathome.me/one-storage-tree-per-user/">post 10</a>.) <code>/api/auth/*</code> shrank to a single <code>/me</code> endpoint that just reflects the forwarded identity back to the frontend. <code>sessionkit</code> came out of <code>pyproject.toml</code> and <code>uv.lock</code> entirely, along with the exception handlers and schemas that existed only to translate its errors.</p><p>On the frontend, <code>LoginForm</code>, <code>PasswordSettings</code> and <code>TwoFactorSettings</code> were deleted outright, along with their tests. The Settings page now just points at identity-system for account management. Two behaviours changed in ways worth noting:</p><ul><li><strong>An unauthenticated response sends the browser to identity-system.</strong> If <code>/api/auth/me</code> fails, <code>App.tsx</code> redirects to identity-system's <code>/login</code> with the current URL as <code>rd</code>. In production that shouldn't ever fire, since nginx would already have redirected the page load - it's a backstop for the case where nginx's check was somehow bypassed.</li><li><strong>Logging out is a form POST, not a <code>fetch()</code>.</strong> identity-system's session cookie lives on its own origin, and its <code>POST /logout</code> responds with a redirect to its login page. A <code>fetch()</code> can't follow a cross-origin redirect usefully, so logout creates a real <code>&lt;form method="POST"&gt;</code>, points it at identity-system, and submits it - a top-level navigation, which can.</li></ul><h2 id="what-this-cost-and-what-it-bought">What this cost, and what it bought</h2><p>The honest cost is local development. There's no login page to click through any more, and neither the FastAPI dev server nor Vite sits behind nginx, so every request 401s by default. <code>docs/development.md</code> now says so plainly: for backend work, send the headers yourself with <code>curl</code>; for the full frontend, run identity-system alongside with the same <code>auth_request</code> wiring. A later commit's message mentions driving the app with Playwright "auth headers faked via route interception, since there's no login page anymore" - that's what working this way actually looks like.</p><p>What it bought was the deletion of roughly 800 lines whose only job was to be a second, worse copy of something that now exists once. Password hashing, session lifetime, two-factor enrolment and recovery codes are one service's problem, fixed in one place. This app is left with a rule short enough to state in a sentence: <em>the identity on the request is whatever nginx says it is, and everything else keys off the user id.</em></p><p>That last clause turned out to matter more than I expected. Once the app knew who was asking, there was a better question to ask about where each person's data lives.</p><hr><p>Previous: <a href="https://ghost.atathome.me/balances-and-disconnecting-banks/">← Account balances and disconnecting banks</a> · Next: <a href="https://ghost.atathome.me/one-storage-tree-per-user/">One storage tree per user →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[House-move inventory: Why a spreadsheet wasn't enough - Part 1]]></title><description><![CDATA[~7 min read

We're moving from the UK to France, and the removals company, the French customs form and my own sanity all want the same thing: a list of what is in every box. Not a rough list. Which box is the kettle in? Did every box that left the house actually arrive? What's the declared value of the kitchen? Which boxes are we not taking after all?

The obvious tool is a spreadsheet, and I started with one. This post is about why I stopped, what I built instead, and the few decisions in the f]]></description><link>https://brightbot.co.uk/why-a-spreadsheet-wasnt-enough/</link><guid isPermaLink="false">Ghost__Post__6ae5bab71df6faba86556b38</guid><category><![CDATA[Building Inventory System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sun, 01 Nov 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1698917414969-feade59e3343?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDR8fEhvdXNlJTIwbW92ZXxlbnwwfHx8fDE3OTM1MjM4NDV8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1698917414969-feade59e3343?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDR8fEhvdXNlJTIwbW92ZXxlbnwwfHx8fDE3OTM1MjM4NDV8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="House-move inventory: Why a spreadsheet wasn't enough - Part 1"/><p><em>~7 min read</em></p><p>We're moving from the UK to France, and the removals company, the French customs form and my own sanity all want the same thing: a list of what is in every box. Not a rough list. Which box is the kettle in? Did every box that left the house actually arrive? What's the declared value of the kitchen? Which boxes are we <em>not</em> taking after all?</p><p>The obvious tool is a spreadsheet, and I started with one. This post is about why I stopped, what I built instead, and the few decisions in the first commits that shaped everything after.</p><h2 id="where-the-spreadsheet-broke">Where the spreadsheet broke</h2><p>A spreadsheet is a fine answer to "list the things". It is a poor answer to the questions that actually come up during a move:</p><ul><li><strong>A box has a life.</strong> It is packed, sealed, in transit, arrived, unpacked. Tracking that per row of items means repeating the status on every line, or keeping a second sheet in sync by hand.</li><li><strong>Two people edit at once.</strong> Both of us are packing, in different rooms, often from phones.</li><li><strong>The output matters as much as the data.</strong> A box needs a contents sheet to tape inside it and a label for the outside. Customs wants invoices attached to the expensive things. None of that is a spreadsheet's job.</li><li><strong>Money.</strong> Everything is bought in pounds, the French paperwork wants euros, and a total that silently adds £ and € together is worse than no total.</li></ul><p>So: a small web app. Not a general asset-management system - the overview doc says it plainly, "it only needs to survive one move. Favour simplicity over completeness" - but one that models the move properly.</p><h2 id="the-shape-of-the-data">The shape of the data</h2><p>Three levels, and the hierarchy is the whole idea:</p><pre><code>room  -&gt;  box  -&gt;  item
Kitchen   KIT-01   Frying pan x1, £25.00
</code></pre><p>A <strong>room</strong> owns a short prefix (<code>KIT</code>, <code>BED</code>, ...). A <strong>box</strong> belongs to a room and gets a human-readable code, <code>PREFIX-NN</code>: <code>KIT-01</code>, <code>KIT-02</code>. An <strong>item</strong> belongs to a box and has a name, a quantity, an optional value and some notes.</p><p>The codes matter more than they look. A box code gets written on the side of a cardboard box with a marker, read out over the phone and typed into a search field, so it has to be short, unambiguous and stable. Generating the next one is deliberately simple - take the highest number already used for that prefix and add one:</p><pre><code class="language-python">def _next_seq(self, prefix: str) -&gt; int:
    highest = 0
    for existing in self._repo.list_box_codes_with_prefix(prefix):
        _, _, tail = existing.partition("-")
        if tail.isdigit():
            highest = max(highest, int(tail))
    return highest + 1
</code></pre><p>Two small behaviours fall out of that. An unknown room name typed into the new-box form <em>registers</em> the room (with a heuristic prefix) rather than failing, so the list of managed rooms always reflects what boxes actually use. And a box's code follows its room's prefix at creation time - a later post covers what happens when you change a prefix afterwards.</p><h2 id="decisions-made-on-day-one">Decisions made on day one</h2><p>The first commits (5 September: "Add docs", "Add initial inventory service", "add api interface pre-refactor") were mostly writing, not coding. The docs came first, and three decisions in them stuck:</p><ol><li><strong>Layers, kept loosely coupled.</strong> A Python core with all the domain logic, a thin FastAPI layer over it, a React single-page app over that, and (eventually) a thin CLI beside the API. Each can be tested on its own. The <a href="https://ghost.atathome.me/a-core-that-knows-nothing-about-http/">next post</a> is about this.</li><li><strong>SQLite, one file, no cloud.</strong> Two people, one move. A single SQLite file that I can back up by copying removes an entire category of operational work. The costs - one writer at a time, schema changes need care - turned out to be real but manageable, and later posts cover both.</li><li><strong>Money is <code>Decimal</code>, never <code>float</code>.</strong> Decided before any item existed. Retrofitting this is the sort of thing that goes wrong quietly.</li></ol><p>I also wrote an explicit <strong>out of scope</strong> list: multiple users and concurrent editing, photos, barcode scanning, currency conversion. It is a mildly embarrassing list to read back, because several of those items shipped within weeks - photos on boxes and items, EUR conversion, and (through someone else's login) multiple users. What the list was really for was getting a usable first version out, and for that it worked: by the end of the first day there was a service that could create boxes, add items, change status, search across boxes and total a box's value.</p><h2 id="what-usable-meant">What "usable" meant</h2><p>The roadmap I wrote for myself had a rule: <em>each phase should leave something usable</em>. Phase 1 was the core and storage. Phase 2 was the REST API. Phase 3 was the web UI. Then a long tail of numbered phases - 3.5 managed rooms, 3.6 GBP default and EUR conversion, 3.7 clone box, and so on up to 3.37 - each one a small thing I wanted while actually using it. That tail is the real history of the project, and the rest of this series follows it roughly in order.</p><p>If you're building something for a one-off event, the lesson I'd pull out of this is boring but true: model the <em>lifecycle</em> of the thing (a box moves through states), not just its contents, and decide early what your identifiers look like, because everything ends up keyed on them.</p><p>Next: how the code is organised so that the rules live in exactly one place.</p><hr><p>Next: <a href="https://ghost.atathome.me/a-core-that-knows-nothing-about-http/">A core that knows nothing about HTTP →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Childcare calculator: Why a static page, and why not a spreadsheet - Part 1]]></title><description><![CDATA[~6 min read

Childcare costs are one of those bills that look simple until you try to predict them. A childminder charges an hourly rate. You book some days. The government funds some of the hours. Bank holidays don't count. And somehow the number on the invoice is never the number you guessed.

I wanted a way to type in my setup and see the month's cost, day by day, before the invoice arrived. This post is about the first decision: what to build it with, and what the first version actually did.]]></description><link>https://brightbot.co.uk/why-a-static-page/</link><guid isPermaLink="false">Ghost__Post__6ae473061df6faba86556aef</guid><category><![CDATA[Building a Childcare Calculator]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sat, 31 Oct 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1578349035260-9f3d4042f1f7?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fGNoaWxkY2FyZXxlbnwwfHx8fDE3OTMzNTY2NTd8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1578349035260-9f3d4042f1f7?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fGNoaWxkY2FyZXxlbnwwfHx8fDE3OTMzNTY2NTd8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Childcare calculator: Why a static page, and why not a spreadsheet - Part 1"/><p><em>~6 min read</em></p><p>Childcare costs are one of those bills that look simple until you try to predict them. A childminder charges an hourly rate. You book some days. The government funds some of the hours. Bank holidays don't count. And somehow the number on the invoice is never the number you guessed.</p><p>I wanted a way to type in my setup and see the month's cost, day by day, before the invoice arrived. This post is about the first decision: what to build it with, and what the first version actually did.</p><h2 id="why-not-a-spreadsheet">Why not a spreadsheet?</h2><p>A spreadsheet was the obvious first answer, and It's what most people reach for. It stops working well when you want to do three things:</p><ul><li><strong>Show a calendar.</strong> A grid of days with the childminder, hours and cost on each one is the natural way to sanity-check a month. Spreadsheets can fake it, badly.</li><li><strong>Tap a day to remove it.</strong> Sick days and days off are the main reason a real invoice differs from the plan. I wanted to click a day and watch the total change.</li><li><strong>Hand it to someone else.</strong> A link anyone can open on a phone beats "here's my spreadsheet, don't touch the formulas".</li></ul><p>None of that is hard in a web page, and all of it is awkward in a spreadsheet.</p><h2 id="three-files-and-no-build-step">Three files and no build step</h2><p>The whole project is <code>index.html</code>, <code>styles.css</code> and <code>app.js</code>. No framework, no bundler, no <code>package.json</code>, no backend. I'm a fan of this for a tool this size, and there's a privacy argument too: the inputs are rates and a weekly schedule for your child, and I'd rather that never left the browser. With no server there's nothing to leak and nothing to keep running.</p><p>The cost of that choice is that the state has to live somewhere, and the DOM makes a poor place for it. Even the first version kept the data separate from the markup:</p><pre><code class="language-js">const excludedDates = new Set(); // ISO date strings the user has tapped to exclude

const defaultSchedule = [
  { cm: 'A', hours: 8.5 },
  { cm: 'A', hours: 8.5 },
  { cm: 'A', hours: 8.5 },
  { cm: 'A', hours: 8.5 },
  { cm: 'B', hours: 8.5 }
];
</code></pre><p>A schedule is five entries (Monday to Friday), each with a childminder and a number of hours. Excluded days are a set of ISO date strings. Everything on the page is derived from those two things plus a few inputs, and <code>calculate()</code> re-derives the lot on every change. For a page this small, recomputing everything on every keystroke is cheap and means there's no "update the right bit" logic to get wrong.</p><h2 id="the-first-versions-model">The first version's model</h2><p>The initial commit already had the shape the calculator still has:</p><ol><li>Walk every day of the selected month.</li><li>Skip weekends. Skip bank holidays if the toggle is on.</li><li>Look up that weekday in the weekly schedule.</li><li>Group the surviving days into weeks, keyed by the Monday of that week.</li><li>Apply the free-hours allowance per week, then price what's left.</li></ol><p>Bank holidays are a hardcoded set of <code>YYYY-MM-DD</code> strings for England and Wales:</p><pre><code class="language-js">const BANK_HOLIDAYS = new Set([
  '2025-01-01','2025-04-18','2025-04-21', /* ... */
  '2027-12-27','2027-12-28'
]);
</code></pre><p>That's a deliberate shortcut. There's no API call and no dependency, and the cost is that someone has to extend the list by hand every couple of years. The README says so, with a link to the official dates. I'd rather have an honest manual step than a network request that can fail.</p><h2 id="publishing-it">Publishing it</h2><p>A tool nobody can open is a tool nobody uses, so the next few commits were about reach rather than features: a GitHub Actions workflow that deploys to GitHub Pages on every push to <code>main</code>, a status badge, a link to the live site in the README, and and a fix for dropdown styling. Because there's no build step, the workflow is just "upload the folder".</p><p>That's the whole appeal of the approach. Pushing a commit is deploying, and the deployed thing is exactly the files in the repo.</p><h2 id="what-this-version-couldnt-do">What this version couldn't do</h2><p>It had two childminders hardcoded as "A" and "B", with the names and rates as two fixed pairs of inputs. That's fine until you have one childminder, or three. <a href="https://ghost.atathome.me/from-two-childminders-to-four/">The next post</a> is about removing that assumption, which touched almost every function in the file.</p><hr><p>Next: <a href="https://ghost.atathome.me/from-two-childminders-to-four/">From two childminders to four →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Central login service: Making Jenkins sign in - Part 5]]></title><description><![CDATA[~20 min read

Part 4 ended with an OpenID Connect provider that passed its test suite, covered the whole Authorization Code flow, required PKCE, hashed its client secrets, and was, by the specification as I'd read it, correct.

Then I pointed Jenkins at it, and the next half hour produced three commits with titles like fix jenkins login, fixing the fix further and Adding preffered username. This part is about those three commits. They're short (the three of them touch well under a hundred lines ]]></description><link>https://brightbot.co.uk/identity-system-making-jenkins-sign-in/</link><guid isPermaLink="false">Ghost__Post__6ada2fa61df6faba86556a8c</guid><category><![CDATA[Building Identity System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sat, 31 Oct 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1651235732694-0d057ace2f30?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fGF1dGhlbnRpY2F0aW9ufGVufDB8fHx8MTc5MjY4NDE0OXww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1651235732694-0d057ace2f30?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fGF1dGhlbnRpY2F0aW9ufGVufDB8fHx8MTc5MjY4NDE0OXww&ixlib=rb-4.1.0&q=80&w=2000" alt="Central login service: Making Jenkins sign in - Part 5"/><p><em>~20 min read</em></p><p><a href="https://ghost.atathome.me/identity-system-becoming-an-openid-connect-provider/">Part 4</a> ended with an OpenID Connect provider that passed its test suite, covered the whole Authorization Code flow, required PKCE, hashed its client secrets, and was, by the specification as I'd read it, correct.</p><p>Then I pointed Jenkins at it, and the next half hour produced three commits with titles like <code>fix jenkins login</code>, <code>fixing the fix further</code> and <code>Adding preffered username</code>. This part is about those three commits. They're short (the three of them touch well under a hundred lines of production code between them), but they are the most educational part of the whole project, because each one is a place where "correct according to the spec" and "works with the software on the other end" came apart.</p><p>I think the pattern matters more than the individual bugs, so I'll go through each one as a small case study: the symptom, what I wrongly assumed, the actual cause, and the fix.</p><h2 id="setting-the-scene">Setting the scene</h2><p>Jenkins' OpenID Connect plugin lets you replace its security realm (the thing that answers "who is this person?") with an external provider. You give it a client ID and secret, and a discovery URL, and in principle it configures itself: it fetches <code>/.well-known/openid-configuration</code>, learns the endpoints, and runs the Authorization Code flow.</p><p>The setup, in the README I wrote, is three bullet points:</p><ul><li>Client ID / Client Secret: the values registered with the identity service.</li><li>Configuration mode: automatic, using the discovery URL.</li><li>Scopes: <code>openid email profile</code>.</li></ul><p>Authorisation <em>inside</em> Jenkins (who may build what, who is an administrator) stays with Jenkins' own role-based strategy, in line with the rule from Part 1 that this service answers "who is this", never "what may they do".</p><p>The discovery fetch worked. The redirect to my login page worked. I signed in. And then Jenkins showed an error.</p><h2 id="problem-1-could-not-extract-credentials-from-request">Problem 1: "Could not extract credentials from request"</h2><p>The message Jenkins displayed was a generic credentials-extraction failure. It said nothing about OAuth, nothing about PKCE, nothing about which request had failed or why. That's a classic shape for this kind of integration bug: the <em>relying party's</em> error message describes what it was trying to do, not what the server did wrong.</p><p>When you're the identity provider and the client is a black box, the debugging method is to reason from the protocol. What do I know about what Jenkins sent me?</p><p>My <code>/authorize</code> endpoint, as written in Part 4, had this check:</p><pre><code class="language-python">code_challenge = params.get("code_challenge", "")
if params.get("code_challenge_method", "") != "S256" or not code_challenge:
    return error_redirect("invalid_request", "PKCE (code_challenge_method=S256) is required")
</code></pre><p>and a matching one at <code>/token</code>, where <code>code_verifier</code> was a required form field:</p><pre><code class="language-python">code_verifier: str = Form(...),
</code></pre><p>Jenkins' OIDC plugin, in the configuration I was using, doesn't send PKCE parameters unless they are explicitly enabled. So the authorise request had no <code>code_challenge</code>, my endpoint dutifully redirected back with an <code>invalid_request</code> error, and the plugin, which was expecting a <code>code</code> and got an <code>error</code>, reported the only thing it understood: it couldn't extract what it needed from the response.</p><p>There was a second, subtler failure behind it. Even if the authorise step had succeeded, <code>code_verifier: str = Form(...)</code> marks the field as required at the <em>framework</em> level. FastAPI validates the request body before my handler ever runs, so a token request without <code>code_verifier</code> would be rejected with a framework-generated <code>422 Unprocessable Entity</code> carrying FastAPI's own validation-error JSON, which is not an OAuth error at all. That's why the module docstring I wrote afterwards says the failure surfaced as a generic error "because the request never reached our own error handling".</p><p>That second point is worth sitting with, because it's a general trap. <strong>When your web framework validates required fields declaratively, requests that violate them never reach your code, so your carefully designed protocol-shaped errors are bypassed.</strong> An OAuth client expects <code>{"error": "invalid_request", ...}</code>; it gets a different shape, and it can't make sense of it. For a standards-based endpoint, the framework's validation layer is part of your public contract.</p><h3 id="was-i-wrong-to-require-pkce">Was I wrong to require PKCE?</h3><p>This deserves an honest answer, because "I removed a security feature to make a client work" is exactly the sort of sentence that should make you suspicious.</p><p>PKCE exists to protect <strong>public clients</strong>: applications that can't keep a secret, like a mobile app or a browser-only single-page app. If an attacker intercepts the authorisation code from the redirect, a public client has nothing else standing between that code and a token, so PKCE adds the missing proof.</p><p>Every client registered with this service is a <strong>confidential client</strong>. It has a client secret that it must present at the token endpoint, and an intercepted code is useless without that secret. So for these clients, PKCE is defence in depth rather than the only defence. Requiring it unconditionally was strictness that blocked a legitimate relying party without protecting anything the secret wasn't already protecting.</p><p>What I did instead was make it <strong>verified when present, optional when absent</strong>:</p><pre><code class="language-python"># PKCE is verified when a client uses it, but not required: it
# exists to protect *public* clients that can't hold a secret, and
# every client registered here is confidential ...
code_challenge = params.get("code_challenge") or None
code_challenge_method = params.get("code_challenge_method") or None
if code_challenge is not None and code_challenge_method != "S256":
    return error_redirect("invalid_request", "only code_challenge_method=S256 is supported")
</code></pre><p>and at the token endpoint:</p><pre><code class="language-python">code_verifier: str | None = Form(None),
...
# Only verified if /authorize actually received a code_challenge
if entry.code_challenge is not None:
    if not code_verifier or not _verify_pkce(entry.code_challenge, code_verifier):
        return JSONResponse(
            status_code=400,
            content={"error": "invalid_grant", "error_description": "PKCE verification failed"},
        )
</code></pre><p>The stored challenge is now <code>str | None</code> on the code record. The logic is:</p><ul><li>If the client sent a challenge at authorise time, then at token time it <strong>must</strong> produce a matching verifier. Skipping the verifier when a challenge exists would be a downgrade attack, so <code>not code_verifier</code> is treated as a failure, not as "nothing to check".</li><li>If the client sent no challenge, there's nothing to verify, and the client's secret is the proof.</li><li>If the client sent a challenge using any method other than <code>S256</code> (such as <code>plain</code>, which sends the verifier unhashed and so protects almost nothing), it's rejected rather than silently accepted. Only the strong method is supported.</li></ul><p>The conditions are tight enough that I'm comfortable with the trade, and it's one I have documented as a deliberate posture, with the reasoning, in the module docstring, the README and the project notes. But I'll also say plainly that it is a loosening. If this service ever registered a public client, a client with no way to hold a secret, then this setting would be wrong for it, and PKCE would need to be required <em>per client</em> rather than not at all. That's a future problem that the data model (a client record with scopes and redirect URIs) would accommodate easily.</p><h3 id="the-tests-that-changed">The tests that changed</h3><p>The tests tell the story. The old test <code>test_authorize_rejects_missing_pkce</code> was replaced with <code>test_authorize_rejects_code_challenge_with_unsupported_method</code>, which asserts the new, narrower rule. A new test, <code>test_full_round_trip_without_pkce</code>, runs the whole flow with no challenge and no verifier, and its comment is the reason the test exists: "an RP not sending it (e.g. Jenkins' OIDC plugin without PKCE enabled) must still be able to complete the flow."</p><p>The helpers also got an option. <code>_authorize</code> grew a <code>use_pkce=True</code> parameter, and <code>_token_request</code> made <code>verifier</code> optional, so every existing test kept exercising the PKCE path by default while the new one opted out. That's the cheap way to widen a test suite: add a switch with a default that preserves old behaviour, rather than rewriting every test.</p><h2 id="problem-2-a-registry-file-that-crashed-the-whole-service">Problem 2: a registry file that crashed the whole service</h2><p>While in there, the same commit made a defensive change that had nothing to do with OIDC protocol rules and everything to do with operating the thing.</p><p>At this point, clients were registered by hand in a JSON file. The loader did this:</p><pre><code class="language-python">entries = json.loads(text)
return {
    entry["client_id"]: OidcClient(
        client_id=entry["client_id"],
        ...
    )
    for entry in entries
}
</code></pre><p>Registering a single client, the natural way to write the file is a single JSON object:</p><pre><code class="language-json">{
  "client_id": "jenkins",
  "client_secret_hash": "...",
  ...
}
</code></pre><p>That parses as perfectly valid JSON. It's also wrong, because the loader expects a <em>list</em> of clients. Iterating over a dict yields its <strong>keys</strong>, which are strings, so <code>entry["client_id"]</code> becomes <code>"client_id"["client_id"]</code>, which raises <code>TypeError: string indices must be integers</code>. The message points at an indexing expression, not at the file, and it happens during module import, because <code>main.py</code> loads the registry at startup.</p><p>The consequence is what makes it worth a fix: the loader was called unconditionally at startup, so a typo in an <em>OIDC client file</em> took down the <strong>entire service</strong>, login page, <code>/verify</code> and every app behind the proxy included. A mistake in an optional feature's configuration had a blast radius covering the core feature.</p><p>The fix is a type check with an error message written for the person who'll read it at 2 a.m.:</p><pre><code class="language-python">entries = json.loads(text)
if not isinstance(entries, list):
    raise ValueError(
        f"{path} must be a JSON array of client objects (even for a single "
        f"client) - see oidc_clients.json.example. Got a top-level "
        f"{type(entries).__name__} instead."
    )
</code></pre><p>It still fails at startup, which I think is right: a malformed registry is a configuration error you want to find immediately rather than discover when a login mysteriously doesn't work. But now the failure says what's wrong and where to look. The principle I took from it is that <strong>validation errors in hand-edited files should name the file, the rule and the fix.</strong> (This particular loader was later demoted from "how clients are configured" to "one-time legacy import", as Part 6 describes, which quietly removes the whole category of mistake. But the habit applies to every hand-edited file.)</p><h2 id="problem-3-the-secret-that-never-matched">Problem 3: the secret that never matched</h2><p>The registry fix went in and the PKCE change went in and, in the logs, sign-in got further. Jenkins now got a code, and called my token endpoint. And my token endpoint said <code>401 invalid_client</code>.</p><p>This is the maddening kind of authentication bug: the secret configured in Jenkins was supposed to be the one hashed into the registry, and hashing and verification worked fine in the tests. And yet verification failed against a real client.</p><p>The difference between the tests and Jenkins was the <em>transport</em>. My tests sent <code>client_id</code> and <code>client_secret</code> as ordinary form fields (the <code>client_secret_post</code> method). Jenkins used HTTP Basic authentication (<code>client_secret_basic</code>), which is the default in most OIDC clients and which my discovery document had advertised. In the first version, my code handled it like this:</p><pre><code class="language-python">auth_header = request.headers.get("authorization", "")
if auth_header.lower().startswith("basic "):
    try:
        decoded = base64.b64decode(auth_header[len("basic "):]).decode()
        client_id, client_secret = decoded.split(":", 1)
    except Exception:
        return JSONResponse(status_code=401, content={"error": "invalid_client"})
</code></pre><p>That's the textbook HTTP Basic decode: base64-decode, split on the first colon. It's what you'd write for any other API. And for OAuth2 it is subtly wrong.</p><h3 id="rfc-6749-appendix-b">RFC 6749, Appendix B</h3><p>The OAuth2 specification says that when a client uses Basic authentication, the client ID and secret are first encoded with the <code>application/x-www-form-urlencoded</code> algorithm (the same encoding as form fields, where a space becomes <code>+</code> and special characters become <code>%XX</code>), <em>and then</em> joined with a colon and base64-encoded.</p><p>Which means the receiving side must do two decodes: base64, then URL-decoding of each half. Skipping the second step is harmless when a secret is made of plain letters and digits, because they pass through URL-encoding unchanged. It breaks on any character that the encoding changes: <code>+</code>, <code>/</code>, <code>=</code>, <code>%</code>, space, and others.</p><p>Now consider how a strong secret is typically produced: something like <code>openssl rand -base64 32</code>, and base64 output <strong>is made of letters, digits, <code>+</code>, <code>/</code> and <code>=</code></strong>. So almost any strong, machine-generated secret contains characters that the client dutifully percent-encoded before sending, and that my server compared in encoded form: <code>abc%2Bdef</code> against the stored hash of <code>abc+def</code>. They could never match. The weaker and more boring the secret, the better it worked, which is an unpleasant property for a security feature.</p><p>The fix is two lines, and a comment that cites the section:</p><pre><code class="language-python">raw_id, raw_secret = decoded.split(":", 1)
# RFC 6749 Appendix B: client_id/client_secret are
# application/x-www-form-urlencoded *before* Basic-encoding
# - skipping this decode step meant any secret containing
# +, /, =, % (i.e. almost anything generated with
# `openssl rand -base64 ...`) never matched, because we'd
# be comparing the still-percent-encoded string.
client_id, client_secret = unquote_plus(raw_id), unquote_plus(raw_secret)
</code></pre><p><code>unquote_plus</code> is the right function here, as opposed to <code>unquote</code>: it also turns <code>+</code> back into a space, which is what the form-urlencoded algorithm specifies. (A secret that originally contained a literal <code>+</code> arrives as <code>%2B</code> and decodes to <code>+</code>; one that contained a space arrives as <code>+</code> and decodes to a space.)</p><h3 id="the-test-that-would-have-caught-it">The test that would have caught it</h3><p>The regression test is a good example of testing at the right level. It deliberately builds its own app with a client whose secret is <code>tricky+secret/with=chars</code>, encodes it the way a spec-compliant client would, and sends it as a Basic header:</p><pre><code class="language-python">secret = "tricky+secret/with=chars"
...
basic = base64.b64encode(f"jenkins:{quote_plus(secret)}".encode()).decode()
resp = http_client.post(
    "/api/oidc/token",
    data={"grant_type": "authorization_code", "code": code, "redirect_uri": REDIRECT_URI},
    headers={"Authorization": f"Basic {basic}"},
)
assert resp.status_code == 200
</code></pre><p>Look at how it differs from the original tests. The original secret in the shared fixture was a plain string, and the original requests used form fields. Neither of those exercised the encoding path. <strong>My tests were passing because they were testing the easy case.</strong> The fix wasn't only code; it was recognising that the test data was too friendly, and that realistic test data (here, a secret full of the awkward characters real secrets contain) is part of the test's value.</p><p>There's a related lesson in the code I did <em>not</em> change. The <code>client_secret_post</code> path, where the secret is a form field, doesn't need decoding, because the web framework has already decoded the form. Two ways of presenting the same credential, two different encoding rules. That's an argument for supporting only one if you control both ends, but I don't control Jenkins's end.</p><h2 id="problem-4-no-username">Problem 4: no username</h2><p>The last commit of the series is the shortest, and it's about a claim, not a bug. Signing in worked. Jenkins got its tokens, verified the signature, and read my claims. What it didn't have was a <em>username</em>: a short, human-friendly name to display and key its own internal user records on.</p><p>OpenID Connect has a standard claim for this, <code>preferred_username</code>, in the <code>profile</code> scope. The library underneath me has no separate username field. A user is an email, a name and an ID, so I had to produce one. The natural stand-in is the part of the email before the <code>@</code>:</p><pre><code class="language-python">if "profile" in scopes:
    claims["name"] = name
    # sessionkit's User has no separate username field - the email
    # local part is the natural stand-in. Per the OIDC spec this claim
    # is explicitly a display hint, not a stable/unique identifier
    # (that's `sub`), so it doesn't need to be unique across domains.
    claims["preferred_username"] = email.split("@", 1)[0]
</code></pre><p>Three small follow-through edits make it a complete feature rather than a patch: <code>claims_supported</code> in the discovery document gains <code>"preferred_username"</code>, so a client that reads the document knows it's available; the userinfo endpoint's allow-list of claims to pass through gains it too; and the README's endpoint table is updated.</p><p>The caveat in the comment is the important engineering judgement. A local part is <em>not</em> unique: <code>alex@example.com</code> and <code>alex@example.org</code> would both produce <code>alex</code>. That's acceptable here for two reasons: the spec says <code>preferred_username</code> is a display hint and <strong>not</strong> an identifier (that's the job of <code>sub</code>, which is the account's real ID), and every account on this service is one I created. But a relying party that decided to key its own user table on this claim would be building on sand, and I'd tell anyone integrating against the service not to.</p><p>Both new assertions went into the existing end-to-end test as two extra lines, one on the decoded ID token and one on the userinfo response, rather than a new test: the claim's behaviour is a property of the flow, so it's tested in the flow.</p><h2 id="what-id-take-from-the-afternoon">What I'd take from the afternoon</h2><p>Four problems across three commits, and the common thread isn't that I'd misread the specification. On PKCE, I'd read it correctly and applied it more strictly than the world does. On Basic auth, I'd <em>skipped</em> a section. On the registry I'd written a loader for the file I intended to write rather than the file I might write. On the claim, I'd built the protocol and forgotten that clients are people's expectations in code.</p><p>A few things generalise:</p><p><strong>Build the first integration test against the real client early.</strong> Everything in Part 4's test suite was written by me, simulating a relying party as I understood relying parties. The tests encoded my assumptions, so they couldn't contradict them. A real client is the only thing that can. If I did it again I'd stand up a throwaway Jenkins (or any real OIDC client) before writing the second half of the endpoints.</p><p><strong>Prefer being liberal in what you accept when the extra strictness buys nothing.</strong> The PKCE decision wasn't "security versus convenience"; it was recognising that the strict version defended against an attacker who was already stopped by the client secret. Strict checks that defend nothing are just compatibility bugs.</p><p><strong>Framework validation is part of your protocol surface.</strong> A required form field that a real client omits will produce the framework's error, not yours, and the client may not understand it.</p><p><strong>Make test data hostile.</strong> Secrets with <code>+/=</code>, emails with plus-addressing, names with accents, URLs with query strings. Realistic awkwardness is where the bugs live.</p><p><strong>Write down <em>why</em>, in the file, at the moment you learn it.</strong> Each of these fixes carries a comment explaining the symptom ("surfacing there as a generic 'Could not extract credentials from request'"), so the next person to be tempted to tighten PKCE again (including me, in a year) hits the explanation first.</p><p>With Jenkins signing in through the same accounts as everything else, the identity service did what I'd built it to do. What it still couldn't do was be <em>configured</em> without me editing files over SSH: adding an app to the landing page, or registering a new OIDC client, meant touching JSON on the server and restarting. That's the subject of the next part.</p><hr><p>Previous: <a href="https://ghost.atathome.me/identity-system-becoming-an-openid-connect-provider/">← Becoming an OpenID Connect provider</a> · Next: <a href="https://ghost.atathome.me/identity-system-moving-configuration-into-the-database/">Moving configuration into the database →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: Account balances and disconnecting banks cleanly - Part 8]]></title><description><![CDATA[~10 min read

The next two pieces of this project both came from the same question: does the app actually reflect the full state of my accounts, in both directions - what's currently in them, and which ones I've actually chosen to keep connected. This post covers pulling real balances into the dashboard, and building a way to disconnect a bank that doesn't leave stale data lying around pretending to be current.


Balances were already paid for

TrueLayer's Data API has balance endpoints - /data/]]></description><link>https://brightbot.co.uk/balances-and-disconnecting-banks/</link><guid isPermaLink="false">Ghost__Post__6ad488c51df6faba865569a3</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sat, 31 Oct 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1616803140344-6682afb13cda?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fEJhbmslMjBsaW5rfGVufDB8fHx8MTc5MjMxNzMzMXww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1616803140344-6682afb13cda?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fEJhbmslMjBsaW5rfGVufDB8fHx8MTc5MjMxNzMzMXww&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: Account balances and disconnecting banks cleanly - Part 8"/><p><em>~10 min read</em></p><p>The next two pieces of this project both came from the same question: does the app actually reflect the full state of my accounts, in both directions - what's currently in them, and which ones I've actually chosen to keep connected. This post covers pulling real balances into the dashboard, and building a way to disconnect a bank that doesn't leave stale data lying around pretending to be current.</p><h2 id="balances-were-already-paid-for">Balances were already paid for</h2><p>TrueLayer's Data API has balance endpoints - <code>/data/v1/accounts/{id}/balance</code> and the card equivalent, <code>/data/v1/cards/{id}/balance</code> - returning <code>current</code>, <code>available</code>, and <code>currency</code> for a given account or card. The convenient part: the scope needed for this, <code>balance</code>, had been in the OAuth scope string since <a href="https://ghost.atathome.me/developer-access-and-app-setup/">the very first app setup post</a>, added early specifically on the reasoning that re-consenting later is annoying and the cost of asking upfront is low. That bet paid off in exactly the way it was supposed to - every already-linked bank already had permission granted, and adding balance data to the sync meant one more API call per account, not a re-linking flow for every bank I'd already connected.</p><p>The balance pull sits in the same per-account loop the transactions pull lives in, and deliberately doesn't share a failure path with it:</p><pre><code class="language-python">try:
    balance = fetch_balance(access, kind, account_id, logger=logger)
except requests.RequestException as exc:
    logger.warning(f"{label} / {name}: could not fetch balance - {exc}", exc_info=True)
    balance = None
</code></pre><p>A failed balance fetch just means that account's balance shows as unknown this run - it doesn't touch whether that account's <em>transactions</em> get pulled. Given the resilience work from the <a href="https://ghost.atathome.me/keeping-data-fresh/">previous post</a> was entirely about not letting one kind of failure take down unrelated data, it would have undermined that to let a balance-specific problem silently cost me transaction history too.</p><h2 id="nested-accounts-and-what-total-should-mean">Nested accounts, and what "total" should mean</h2><p>Each bank on the Accounts page now expands to show its individual accounts and cards as child rows, each with its own balance - not just "Monzo: linked," but "Monzo: Current Account £1,161.20, Savings Pot £3,500.00." That part was mechanical once the data existed: group by bank, render a nested list.</p><p>The more interesting decision was what the Home page's <strong>Total balance</strong> stat tile should actually sum. Naively, every linked account and card's <code>current</code> balance, added together. But a credit card's <code>current</code> balance represents money you <em>owe</em>, not money you <em>have</em> - summing it straight into a "total balance" figure alongside actual cash accounts would inflate the number in a way that's actively misleading about how much money you actually have access to. The fix was filtering the sum to accounts, not cards:</p><pre><code class="language-python">totalBalance = accounts
  .filter(a =&gt; a.kind === 'accounts' &amp;&amp; a.balance !== null)
  .reduce((sum, a) =&gt; sum + a.balance, 0)
</code></pre><p>Card balances are still fully visible, just itemised per-account rather than folded into a headline number that would misrepresent them.</p><p>(A correction on what this commit left behind: it kept TrueLayer's card balance as reported - a <em>positive</em> number meaning "amount owed" - and just excluded cards from the total. That worked for the headline figure but left the data in two different sign conventions, a card at <code>+£250</code> next to transactions where spending is negative. a later fix negated card balances on the way in so debt is negative everywhere; see <a href="https://ghost.atathome.me/seeing-everything-in-one-place/">post 11</a>.) It's a small distinction, but it's the difference between a dashboard number that means something and one that technically sums correctly while telling you something false.</p><h2 id="disconnecting-a-bank-and-what-disconnect-should-actually-do">Disconnecting a bank, and what "disconnect" should actually do</h2><p>Every bank that's ever been linked stayed linked, permanently, until this point - there was no way to remove one short of editing the token file by hand. Adding an "Unlink" action meant deciding what it actually deletes, and the honest answer is: two different things, only one of which should happen automatically.</p><p><strong>The connection itself</strong> - the stored refresh token, the cached consent status, the cached account/balance snapshot - is unambiguous. The moment you unlink a bank, all of that is stale by definition; there's no version of "unlink but keep the cached data around" that makes sense, because nothing will ever refresh it again. That part happens unconditionally.</p><p><strong>The transaction history</strong> that bank already contributed is a different question entirely. Maybe you're unlinking because you closed the account and never want to see it again. Maybe you're unlinking a card temporarily and want your spending history intact when you relink it later. Those are different intents, and defaulting to either one silently would be wrong for the other case. So it's a choice, made explicit in a confirmation modal:</p><pre><code class="language-tsx">&lt;label className="modal-checkbox"&gt;
  &lt;input type="checkbox" checked={deleteData} onChange={...} /&gt;
  Also delete all synced transactions for this bank
&lt;/label&gt;
</code></pre><p>Unchecked by default - the reversible, lower-consequence option - with deleting history requiring a deliberate extra click rather than being the path of least resistance. The API mirrors that split exactly:</p><pre><code class="language-python">storage.delete_connection(conn, label)
storage.delete_accounts_for_bank(conn, label)

deleted_transactions = storage.delete_transactions_for_bank(conn, label) if delete_data else 0
</code></pre><p>The first two lines always run - the stale cache goes regardless. The transaction delete is the one line gated on what the checkbox actually said.</p><h2 id="confirming-a-destructive-action-needs-its-own-care-even-in-a-modal">Confirming a destructive action needs its own care, even in a modal</h2><p>The unlink confirmation isn't just a <code>window.confirm()</code> - browser-native confirm dialogs can't hold a checkbox, and the delete-data choice is exactly the kind of decision that shouldn't be a second, separate prompt stacked after the first. So it's a proper modal component: a backdrop, a centred card asking "Unlink {bank}?", the checkbox, and two buttons whose labelling turned out to matter more than I expected. Both the row's trigger button and the modal's confirm button initially just said "Unlink," which looked fine visually - one small ghost button next to the bank, one bold red button in the modal - right up until a test tried to click "the button labelled Unlink" after the modal was already open and found two of them. That's a real signal, not just a testing inconvenience: if an accessibility tool or a screen reader can't disambiguate the two buttons by label either, a sighted user skimming quickly is in the same position. The fix was renaming the modal's confirm button to "Unlink bank" - distinct, still obviously the same action, and now unambiguous to a test and to anyone not looking closely at which one is red.</p><p>Testing the confirm flow itself needed one deliberate trick: asserting a loading state exists at all requires <em>not</em> letting the mocked request resolve immediately, or there's no window in which "Unlinking…" is ever actually on screen for a test to catch. A manually-resolved promise - call the component's handler, assert the disabled loading state, <em>then</em> resolve the promise and assert the final state - is the same pattern the sync button's tests used in the previous post, and by this point in the project it had become the default way to test anything with a pending network request in the middle of it, rather than something rediscovered each time.</p><h2 id="a-schema-change-that-had-to-not-break-the-running-system">A schema change that had to not break the running system</h2><p>Adding the balance table meant a new column (<code>account_count</code>, tracked separately, added around the same time) on a table - <code>connections</code> - that already existed on my running deployment from earlier work. <code>CREATE TABLE IF NOT EXISTS</code> doesn't add columns to a table that's already there; it only handles the case where the table doesn't exist yet at all. Deploying that change without accounting for it would have meant the <em>next</em> nightly sync on the real server crashing with <code>no such column</code>, discovered at 3am with nobody watching.</p><pre><code class="language-python">existing_columns = {row["name"] for row in conn.execute("PRAGMA table_info(connections)")}
if "account_count" not in existing_columns:
    conn.execute("ALTER TABLE connections ADD COLUMN account_count INTEGER")
</code></pre><p>A few lines, checked on every connection open, and safe to leave in permanently - once the column exists, the check is a no-op. It's not a general migration framework, and it doesn't need to be one for a single-table, single-user app; it just needs to not break the thing that's already running the moment new code reaches it.</p><h2 id="what-wasnt-built-yet">What wasn't built yet</h2><p>Worth closing honestly rather than implying this was finished, because it wasn't. <code>category</code> had sat unused in the transactions schema since the very first SQLite migration back in post four - the intent from day one was rule-based categorisation (grocery-store descriptions become "Groceries," recurring same-amount debits become "Subscriptions," and so on), and it was still just a <code>NULL</code> column. The Home page's "spending by category" chart was still demo data for exactly that reason. And the storage layer was deliberately built provider-agnostic from post four onward - a <code>providers/</code> package with <code>truelayer.py</code> as the only module in it - specifically so a second source could be added without redesigning anything underneath it. Hargreaves Lansdown, for investment accounts, was the one I kept meaning to get to.</p><p>Both turned out to be the next things built, though not quite as planned. Categorisation became <a href="https://ghost.atathome.me/rule-based-categorisation/">post 12</a>. Hargreaves Lansdown didn't end up a CSV import at all - it became a scraper-backed provider with its own credential handling, in <a href="https://ghost.atathome.me/hargreaves-lansdown/">post 14</a>.</p><h2 id="looking-back-at-the-first-arc">Looking back at the first arc</h2><p>Eight posts ago this was two competing evaluation scripts, deciding whether signing my own JWTs with a private key was worth the trouble compared to a plain OAuth flow with a sandbox to test against. By this point it was a FastAPI backend with SQLite storage, session-based auth with optional 2FA (which, as it happens, was about to be deleted), a multi-page React frontend with a design system, a nightly sync job that survives individual accounts having bad days, real dashboard numbers backed by actual SQL, and a way to walk any of it back cleanly if a bank connection isn't wanted anymore.</p><p>None of the individual steps were large. What made it hold together was mostly resisting the urge to skip the boring parts - the sandbox before the real bank, the de-dup key before real usage exposed the wrong one, the migration guard before the schema change reached the running server. Every one of those was the unglamorous choice at the time.</p><p>That was the end of the first arc, and the series continues from here: the app was about to stop owning its own logins, get a storage tree per user, learn to categorise, and grow budgets and savings projections on top.</p><hr><p>Previous: <a href="https://ghost.atathome.me/keeping-data-fresh/">← Keeping data fresh</a> · Next: <a href="https://ghost.atathome.me/handing-auth-to-identity-system/">Handing authentication to identity-system →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Building a 4-Zone Irrigation Controller with ESPHome - Part 2]]></title><description><![CDATA[ESPHome Configuration

Here’s a sample YAML config for a 4-zone irrigation controller:

esphome:
  name: esphome-web-806180
  friendly_name: ESPHome Garden Irrigation Controller
  min_version: 2025.5.0
  name_add_mac_suffix: false

esp32:
  board: esp32dev
  framework:
    type: esp-idf

# Enable logging
logger:

# Enable Home Assistant API
# Enable Home Assistant API
api:

# Allow Over-The-Air updates
ota:
- platform: esphome

text_sensor:
  - platform: version
    name: "ESPHome Version"
    h]]></description><link>https://brightbot.co.uk/building-a-4-zone-irrigation-controller-with-esphome-part-2/</link><guid isPermaLink="false">Ghost__Post__68e1819b64bc86d5eba40150</guid><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Fri, 30 Oct 2026 10:40:01 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1743742566156-f1745850281a?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDV8fGlycmlnYXRpb258ZW58MHx8fHwxNzkzMzU2Nzg3fDA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<h2 id="esphome-configuration">ESPHome Configuration</h2><img src="https://images.unsplash.com/photo-1743742566156-f1745850281a?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDV8fGlycmlnYXRpb258ZW58MHx8fHwxNzkzMzU2Nzg3fDA&ixlib=rb-4.1.0&q=80&w=2000" alt="Building a 4-Zone Irrigation Controller with ESPHome - Part 2"/><p>Here’s a sample YAML config for a 4-zone irrigation controller:</p><pre><code class="language-yaml">esphome:
  name: esphome-web-806180
  friendly_name: ESPHome Garden Irrigation Controller
  min_version: 2025.5.0
  name_add_mac_suffix: false

esp32:
  board: esp32dev
  framework:
    type: esp-idf

# Enable logging
logger:

# Enable Home Assistant API
# Enable Home Assistant API
api:

# Allow Over-The-Air updates
ota:
- platform: esphome

text_sensor:
  - platform: version
    name: "ESPHome Version"
    hide_timestamp: true

wifi:
  ap: {}

globals:
  - id: selected_index
    type: int
    restore_value: no
    initial_value: '0'

one_wire:
  - platform: gpio
    pin: GPIO16

i2c:
  sda: GPIO23
  scl: GPIO22

binary_sensor:
  - platform: gpio
    pin:
      number: GPIO0
      mode:
        input: true
        pullup: true
      inverted: true
    id: mode_button
    on_press:
      then:
        - select.next: run_mode
light:
  - platform: status_led
    name: run_led
    id: run_led
    pin: GPIO15

sensor:
  - platform: internal_temperature
    name: "Internal Temperature"
    id: ic_temp
  - platform: dallas_temp
    name: "Temperature"
    id: outside_temp

select:
  - platform: template
    name: "mode"
    id: run_mode
    options:
      - "OFF"
      - "AUTO"
      - "MANUAL"
    initial_option: "OFF"
    optimistic: true
  - platform: template
    name: "run_state"
    id: run_state
    options:
      - "READY"
      - "RUNNING"
    initial_option: "READY"
    optimistic: true
    on_value:
      then:
        - if:
            condition:
              lambda: 'return id(run_state).state == "RUNNING";'
            then:
              - light.turn_on: run_led
            else:
              - light.turn_off: run_led




switch:
  - platform: gpio
    pin: GPIO5
    name: "Irrigation Zone 1"
    inverted: true
    interlock: &amp;interlock_group [zone_1, zone_2, zone_3, zone_4]
    id: zone_1
    on_turn_on:
      then:
        - select.set_index:
            id: run_state
            index: 1
    on_turn_off: 
      then:
        - select.set_index:
            id: run_state
            index: 0
  - platform: gpio
    pin: GPIO18
    name: "Irrigation Zone 2"
    inverted: true
    interlock: *interlock_group
    id: zone_2
    on_turn_on:
      then:
        - select.set_index:
            id: run_state
            index: 1
    on_turn_off: 
      then:
        - select.set_index:
            id: run_state
            index: 0
  - platform: gpio
    pin: GPIO19
    name: "Irrigation Zone 3"
    inverted: true
    interlock: *interlock_group
    id: zone_3
    on_turn_on:
      then:
        - select.set_index:
            id: run_state
            index: 1
    on_turn_off: 
      then:
        - select.set_index:
            id: run_state
            index: 0
  - platform: gpio
    pin: GPIO21
    name: "Irrigation Zone 4"
    inverted: true
    interlock: *interlock_group
    id: zone_4
    on_turn_on:
      then:
        - select.set_index:
            id: run_state
            index: 1
    on_turn_off: 
      then:
        - select.set_index:
            id: run_state
            index: 0

time:
  - platform: homeassistant
    id: homeassistant_time

font:
  - file: "https://github.com/IdreesInc/Monocraft/releases/download/v3.0/Monocraft.ttf"
    id: web_font_title
    size: 16
  - file: "https://github.com/IdreesInc/Monocraft/releases/download/v3.0/Monocraft.ttf"
    id: web_font_time
    size: 10
  - file: "https://github.com/IdreesInc/Monocraft/releases/download/v3.0/Monocraft.ttf"
    id: web_font_text
    size: 9
    
display:
  - platform: ssd1306_i2c
    model: "SSD1306 128x64"
    address: 0x3C
    lambda: |-
      it.printf(0, 0, id(web_font_title), "%s", id(run_state).state.c_str());
      it.strftime(it.get_width(), 0, id(web_font_time), TextAlign::TOP_RIGHT, "%H:%M", id(homeassistant_time).now());
      it.printf(0, 16, id(web_font_text), "Zne1: %s", id(zone_1).state ? "ON" : "OFF");
      it.printf(it.get_width(), 16, id(web_font_text), TextAlign::TOP_RIGHT, "Zne2: %s", id(zone_2).state ? "ON" : "OFF");
      it.printf(0, 25, id(web_font_text), "Zne3: %s", id(zone_3).state ? "ON" : "OFF");
      it.printf(it.get_width(), 25, id(web_font_text), TextAlign::TOP_RIGHT, "Zne4: %s", id(zone_4).state ? "ON" : "OFF");
      it.printf(0, 34, id(web_font_text), "Mode: %s", id(run_mode).state.c_str());
      it.printf(0, 53, id(web_font_text), "Out:%.1f°C", id(outside_temp).state);
      it.printf(it.get_width(), 52, id(web_font_text), TextAlign::TOP_RIGHT, "IC:%.1f°C", id(ic_temp).state);</code></pre><p>Upload this config via ESPHome, and you’ll see four switches in Home Assistant — one for each irrigation zone.</p><hr><h2 id="adding-automations">Adding Automations</h2><p>While you can toggle zones manually, automation makes irrigation shine. Examples:</p><ul><li><strong>Time-based schedule</strong>: Run Zone 1 for 10 minutes every morning at 6 AM.</li><li><strong>Weather-aware watering</strong>: Skip irrigation if rain is forecast.</li><li><strong>Soil-moisture integration</strong>: Only water if soil is below a threshold.</li></ul><p>Example Home Assistant automation (YAML):</p><pre><code class="language-yaml">alias: Irrigation Morning Run
trigger:
  - platform: time
    at: "06:00:00"
action:
  - service: switch.turn_on
    target:
      entity_id: switch.zone_1
  - delay: "00:10:00"
  - service: switch.turn_off
    target:
      entity_id: switch.zone_1
  - service: switch.turn_on
    target:
      entity_id: switch.zone_2
  - delay: "00:10:00"
  - service: switch.turn_off
    target:
      entity_id: switch.zone_2
  # repeat for zones 3 &amp; 4
</code></pre><hr><h2 id="benefits-of-diy-irrigation-controller">Benefits of DIY Irrigation Controller</h2><ul><li><strong>Flexible</strong> – Adjust zones and schedules without proprietary controllers.</li><li><strong>Smart</strong> – Integrates with sensors, weather APIs, and voice assistants.</li><li><strong>Affordable</strong> – Uses inexpensive ESP hardware and relays.</li><li><strong>Fun</strong> – A practical project that improves your home and teaches you electronics.</li></ul><hr><h2 id="conclusion">Conclusion</h2><p>With <strong>ESPHome</strong> and a simple 4-channel relay, you can build a smart irrigation controller that rivals commercial products — but with much more flexibility. Once set up, your garden or lawn can be watered automatically, intelligently, and efficiently.</p><p>This project is a great example of how home automation can move beyond lights and switches to something tangible, useful, and rewarding.</p></hr></hr></hr>]]></content:encoded></item><item><title><![CDATA[Central login service: Becoming an OpenID Connect provider - Part 4]]></title><description><![CDATA[~28 min read

Everything so far assumed one thing: that the app I'm protecting can sit behind my reverse proxy. The proxy asks the login service "is this request allowed?", the answer arrives as a status code and a few headers, and the app never has to know how any of it happened.

Then I wanted Jenkins to use the same accounts. Jenkins can't play that game. It isn't a little app I wrote; it has its own idea of users, sessions and security realms, and it ships with a plugin that wants to speak O]]></description><link>https://brightbot.co.uk/identity-system-becoming-an-openid-connect-provider/</link><guid isPermaLink="false">Ghost__Post__6ada2fa51df6faba86556a87</guid><category><![CDATA[Building Identity System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Thu, 29 Oct 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1762330472502-83efbe1d4478?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDIxfHxsb2dpbnxlbnwwfHx8fDE3OTI2ODQxMTJ8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1762330472502-83efbe1d4478?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDIxfHxsb2dpbnxlbnwwfHx8fDE3OTI2ODQxMTJ8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Central login service: Becoming an OpenID Connect provider - Part 4"/><p><em>~28 min read</em></p><p>Everything so far assumed one thing: that the app I'm protecting can sit behind my reverse proxy. The proxy asks the login service "is this request allowed?", the answer arrives as a status code and a few headers, and the app never has to know how any of it happened.</p><p>Then I wanted Jenkins to use the same accounts. Jenkins can't play that game. It isn't a little app I wrote; it has its own idea of users, sessions and security realms, and it ships with a plugin that wants to speak <strong>OpenID Connect</strong> to an identity provider. The forward-auth trick doesn't help, because there's nothing for the proxy to "vouch" to: Jenkins insists on running a login flow of its own.</p><p>So the central login service had to learn a second protocol. This part is about that: what OAuth2 and OIDC actually are, the roughly 350 lines of <code>oidc.py</code> that implement the minimum I needed, the security decisions embedded in it, and the deployment consequences of holding a signing key. The work landed in the commit <code>feat: Enable oidc endpoints and functionality</code>, with its follow-up deployment fixes.</p><h2 id="oauth2-and-oidc-in-plain-terms">OAuth2 and OIDC in plain terms</h2><p>Three parties are involved in the flow I implemented, called the <strong>Authorization Code</strong> flow:</p><ul><li>The <strong>user</strong>, sitting at a browser.</li><li>The <strong>relying party</strong> (RP), the app that wants to know who the user is. Here, Jenkins. In OAuth2 terminology this is the <em>client</em>.</li><li>The <strong>identity provider</strong> (IdP), the thing that actually authenticates the user. Here, <code>identity-system</code>.</li></ul><p>The shape of the exchange is:</p><pre><code>1. Browser at Jenkins ──▶ "Sign in" ──▶ Jenkins redirects the browser to
   idp/authorize?client_id=...&amp;redirect_uri=...&amp;scope=openid email profile&amp;state=...

2. IdP checks who the browser is (session cookie). Not signed in? Show the
   login page, then come back to step 2.

3. IdP redirects the browser back to the RP's redirect_uri with a short-lived,
   one-time `code` (and the `state` it was given).

4. RP's *server* (not the browser) calls idp/token with the code and its own
   client secret ──▶ gets back an ID token (a signed JWT saying who the user is)
   and an access token.

5. RP verifies the ID token's signature using the IdP's public keys, reads
   the user's email and name from it, and logs the user in locally.
</code></pre><p>The reason for the two-step dance (a code through the browser, then a token over a direct server-to-server call) is that the <em>browser is the untrusted part</em>. The code is useless without the client secret, which only the RP's server holds, so someone who intercepts the redirect can't use it.</p><p><strong>OAuth2</strong> is the framework for delegating access. <strong>OpenID Connect</strong> is a thin layer on top that adds the part OAuth2 deliberately leaves out: a standard way to say <em>who the user is</em>. In practice that adds: the <code>openid</code> scope, the <strong>ID token</strong> (a JWT with identity claims in it), a <strong>discovery document</strong> so clients can configure themselves, and a <strong>userinfo</strong> endpoint.</p><p>I implemented the smallest slice of this that real software accepts: five endpoints.</p><p>| Endpoint | What it's for | |---|---| | <code>GET /.well-known/openid-configuration</code> | Discovery: tells a client where everything else is | | <code>GET /api/oidc/jwks.json</code> | The public key(s) clients use to verify tokens | | <code>GET /api/oidc/authorize</code> | Step 1 to 3 above | | <code>POST /api/oidc/token</code> | Step 4: code for tokens | | <code>GET /api/oidc/userinfo</code> | Fetch the user's claims with an access token |</p><p>All of it lives in one module, <code>oidc.py</code>, exposed as a FastAPI <code>APIRouter</code> that <code>create_app</code> mounts. Notice the path of the first one: <code>/.well-known/...</code> is fixed by the specification, so it's the one deliberate exception to the "anything new goes under <code>/api/</code>" rule from Part 3.</p><h2 id="what-minimal-means-here">What "minimal" means here</h2><p>The docstring at the top of <code>oidc.py</code> is the most important part of the file, because it records what I decided <em>not</em> to build:</p><ul><li><strong>No consent screen.</strong> Any registered client is auto-approved for a signed-in user. A public identity provider must ask "Allow Jenkins to see your email?" because it can't trust the clients. Mine can: every client is something <em>I</em> registered, so the consent prompt would be ceremony. The trust posture is "the people who can register a client are already trusted", the same posture as the admin allowlist.</li><li><strong>No self-service client registration.</strong> Clients are added by an administrator. (At this point that meant editing a file by hand; Part 6 gives it a UI.)</li><li><strong>No refresh tokens.</strong> When a relying party's session lapses, it re-runs the flow in the browser, which is invisible if the user still has a live session here.</li><li><strong>Authorization codes in memory only.</strong> I'll defend this one at length below.</li><li><strong>One signing key, no rotation.</strong> Rotate by replacing the file and restarting. A single long-lived key is the right amount of complexity for a handful of internal relying parties.</li></ul><p>Each "no" is also a smaller attack surface and fewer moving parts to get wrong. If any of them stops being true (a second household, an app I don't control), that's the point to reach for an off-the-shelf identity provider rather than extending this one.</p><h2 id="the-signing-key">The signing key</h2><p>ID tokens are <strong>signed JWTs</strong>. A relying party must be able to confirm that a token really came from my service and wasn't forged, and it does so with a public key published at the JWKS endpoint. That means the service needs an RSA keypair, and it provisions one for itself on first run:</p><pre><code class="language-python">def load_or_create_signing_key(path: str) -&gt; rsa.RSAPrivateKey:
    p = Path(path)
    if p.exists():
        return serialization.load_pem_private_key(p.read_bytes(), password=None)
    key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
    pem = key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption(),
    )
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_bytes(pem)
    p.chmod(0o600)
    return key
</code></pre><p>"Provision on first run" is the same posture the underlying library takes with its own database: you shouldn't need a setup step to get a working service. A few things in this function are worth a second look.</p><p><strong>The key is generated on the server and never leaves it.</strong> There's no key ceremony and nobody ever handles the private key.</p><p><strong><code>chmod(0o600)</code>.</strong> Owner read/write only. A private signing key readable by other users on the machine is a credential leak waiting for a bad day.</p><p><strong><code>write_bytes</code> then <code>chmod</code>, rather than creating the file restricted from the start.</strong> There's a window, short but real, in which the file exists with default permissions. Opening with <code>os.open(..., 0o600)</code> would close it. On a container where the only account is the service's own it doesn't matter, but it's the sort of thing I'd fix in a shared environment, and I'd rather say so than pretend it's airtight.</p><p><strong>The key has no passphrase</strong> (<code>NoEncryption</code>). A passphrase would need to live somewhere the service can read at startup, which just relocates the secret. File permissions and the container boundary are doing that job.</p><p>The JWKS endpoint publishes only the public half:</p><pre><code class="language-python">@router.get("/api/oidc/jwks.json")
def jwks():
    jwk = json.loads(RSAAlgorithm.to_jwk(signing_key.public_key()))
    jwk.update({"kid": kid, "alg": "RS256", "use": "sig"})
    return {"keys": [jwk]}
</code></pre><p>and there's a test whose entire job is to assert <code>"d" not in keys[0]</code>, because <code>d</code> is the private exponent in a JWK and leaking it would be catastrophic. A test that checks for an <em>absence</em> is cheap insurance for a mistake you only get to make once.</p><h3 id="a-key-id-that-survives-restarts">A key ID that survives restarts</h3><p>Each JWT carries a <code>kid</code> header so a client knows which key in the JWKS verified it. That ID is derived from the key itself rather than generated randomly:</p><pre><code class="language-python">def _kid_for(public_key: rsa.RSAPublicKey) -&gt; str:
    numbers = public_key.public_numbers()
    raw = f"{numbers.n}:{numbers.e}".encode()
    return hashlib.sha256(raw).hexdigest()[:16]
</code></pre><p>A hash of the public numbers is stable for as long as the key file is. If the <code>kid</code> were random per start, every restart would give tokens a different identifier and a client that cached the JWKS would see tokens it couldn't match. Deriving it from the key makes the identifier a pure function of the thing it identifies.</p><h2 id="authorization-codes-one-time-short-lived-in-memory">Authorization codes: one-time, short-lived, in memory</h2><p>When a signed-in user is sent back to the relying party, they carry a <code>code</code>. The code is just a lookup key into a server-side table:</p><pre><code class="language-python">@dataclass(frozen=True)
class _AuthCode:
    client_id: str
    redirect_uri: str
    user_id: str
    email: str
    name: str
    scope: str
    nonce: str | None
    code_challenge: str
    expires_at: float


class AuthorizationCodeStore:
    def __init__(self, ttl_seconds: int = _AUTH_CODE_TTL_SECONDS) -&gt; None:
        self._ttl = ttl_seconds
        self._codes: dict[str, _AuthCode] = {}

    def create(self, **fields) -&gt; str:
        self._sweep()
        code = secrets.token_urlsafe(32)
        self._codes[code] = _AuthCode(expires_at=time.time() + self._ttl, **fields)
        return code

    def consume(self, code: str) -&gt; _AuthCode | None:
        self._sweep()
        entry = self._codes.pop(code, None)
        if entry is None or entry.expires_at &lt; time.time():
            return None
        return entry
</code></pre><p>Properties worth naming:</p><ul><li><strong>Unguessable.</strong> <code>secrets.token_urlsafe(32)</code> is 256 bits from the operating system's cryptographic generator. No sequential IDs, no <code>random</code>.</li><li><strong>Single use, by construction.</strong> <code>consume</code> uses <code>dict.pop</code>, which returns the value <em>and removes it</em> in one step. There is no code path where a code can be read twice, which is exactly what the spec requires; a test confirms a second exchange of the same code returns <code>invalid_grant</code>.</li><li><strong>Short-lived.</strong> Sixty seconds. The legitimate use is "the browser follows a redirect and the RP's server makes a call", which takes milliseconds. A long lifetime only helps an attacker.</li><li><strong>It snapshots the user's details.</strong> Email and name are copied into the code entry at authorise time instead of being looked up again at the token endpoint. The library's <code>AuthService</code> has no "get user by id" method, only a lookup by email, and for a code that lives sixty seconds, a stale snapshot is a non-issue.</li></ul><p>The <code>_sweep()</code> calls prune expired entries on every operation. There's no background thread or scheduler; the table is small and the cleanup is amortised into requests that are already happening.</p><h3 id="why-in-memory-and-why-thats-a-deliberate-trade">Why in memory, and why that's a deliberate trade</h3><p>A restart loses any code that's mid-flight. The user's browser lands on the relying party with a code that no longer exists, the RP shows a login error, the user clicks sign in again. The window for this to matter is the sixty seconds around a restart.</p><p>The alternative is a database table, and the module docstring spells out why I didn't: the whole service is already committed to a single-instance posture (a single SQLite file), so the "multiple instances share codes" benefit of a database doesn't apply, and persisting them adds a write on the login path plus a cleanup job. The project notes carry a warning to future-me: <em>do not "fix" the restart behaviour by reaching for a table without re-reading that reasoning first.</em> It's a simplicity and availability trade tied to a larger architectural decision, not an oversight.</p><h2 id="authorize-the-interesting-endpoint"><code>/authorize</code>: the interesting endpoint</h2><p>This is where most of the security-relevant decisions live, and the ORDER of checks matters as much as the checks.</p><pre><code class="language-python">@router.get("/api/oidc/authorize")
def authorize(request: Request):
    params = request.query_params
    client_id = params.get("client_id", "")
    redirect_uri = params.get("redirect_uri", "")
    state = params.get("state", "")

    client = clients.get(client_id)
    if client is None or redirect_uri not in client.redirect_uris:
        # redirect_uri isn't verified yet - never redirect an
        # unverified URI, that's the whole point of registering them.
        raise HTTPException(status_code=400, detail="unknown client_id or redirect_uri")
</code></pre><p><strong>First, validate who's asking and where the answer will go.</strong> If the <code>client_id</code> is unknown, or the <code>redirect_uri</code> isn't one the client registered, the response is a plain <code>400</code> shown to the user. It must <em>not</em> be a redirect to the supplied URI with an error attached, because at this point the URI is untrusted: redirecting to it would turn the endpoint into an open redirect (the same class of bug as <code>?rd=</code> in Part 1). Everything after this check can safely redirect errors back, because the destination has been proven to be one the administrator approved.</p><p>The comparison is <code>redirect_uri not in client.redirect_uris</code>: an <strong>exact string match</strong> against a set. That's stricter than the <code>?rd=</code> check, which allows any subdomain of the cookie domain, and the strictness is intentional, and written into the project notes as a rule: <em>don't reuse <code>is_trusted_redirect</code> here.</em> A domain-suffix match would let anyone who can stand up a page anywhere under the domain receive another relying party's authorization code. For <code>?rd=</code> the worst case is "a user lands on another of my pages"; for an authorization code the worst case is "someone else logs in as the user". Same shape of check, very different stakes, so a different rule.</p><p>Then come the protocol checks, which <em>do</em> redirect with an OAuth-style error:</p><pre><code class="language-python">def error_redirect(error: str, description: str) -&gt; RedirectResponse:
    query = urlencode({"error": error, "error_description": description, "state": state})
    return RedirectResponse(url=f"{redirect_uri}?{query}", status_code=302)

if params.get("response_type", "") != "code":
    return error_redirect("unsupported_response_type", "only 'code' is supported")

requested_scopes = set(params.get("scope", "").split())
if "openid" not in requested_scopes:
    return error_redirect("invalid_scope", "'openid' scope is required")
if not requested_scopes &lt;= client.allowed_scopes:
    return error_redirect("invalid_scope", "scope not allowed for this client")
</code></pre><p>Two details. The <code>&lt;=</code> is set inclusion: every requested scope must be one the client is permitted. A client registered for only <code>openid</code> can't ask for <code>email</code> and get it. And errors carry <code>state</code> back, because the spec requires the RP to be able to match a response to the request it started.</p><p>Only then does it look at who the <em>user</em> is:</p><pre><code class="language-python">token = request.cookies.get(settings.cookie_name)
try:
    user = auth.user_for_token(token)
except AuthenticationError:
    rd = f"{request.url.path}?{request.url.query}"
    return RedirectResponse(url=f"/login?{urlencode({'rd': rd})}", status_code=302)
</code></pre><p>If there's no valid session, the user is sent to the login page with <code>rd</code> set to <em>this exact authorize request</em>, path and query string. After login, the frontend (following the server's <code>redirect_to</code>, remember) comes straight back to <code>/api/oidc/authorize</code> with the same parameters, now with a cookie. The existing login machinery handles it with no OIDC-specific code at all. A test asserts that the redirect starts with <code>/login?rd=%2Fapi%2Foidc%2Fauthorize</code>, which is the path URL-encoded into the <code>rd</code> parameter.</p><p>That reuse is the payoff of building <code>rd</code> as a generic "come back here" mechanism in Part 1. And it's still safe: the <code>rd</code> here is a <em>relative path</em>, which <code>is_trusted_redirect</code> accepts.</p><p>With a session, the code is minted and the browser is sent back:</p><pre><code class="language-python">code = code_store.create(
    client_id=client_id,
    redirect_uri=redirect_uri,
    user_id=user.id or "",
    email=user.email,
    name=user.name,
    scope=" ".join(sorted(requested_scopes)),
    nonce=params.get("nonce"),
    code_challenge=code_challenge,
)
query = urlencode({"code": code, "state": state})
return RedirectResponse(url=f"{redirect_uri}?{query}", status_code=302)
</code></pre><h3 id="pkce">PKCE</h3><p>The first version <em>required</em> <strong>PKCE</strong> (Proof Key for Code Exchange, pronounced "pixie"). PKCE closes a hole in the code flow for apps that can't keep a secret, like mobile apps and single-page apps. The client invents a random string (the <code>code_verifier</code>), sends only its SHA-256 hash (the <code>code_challenge</code>) at authorise time, and sends the original string at token time. The server checks that the verifier hashes to the challenge it saw earlier. An attacker who steals the code in transit doesn't have the verifier, so can't redeem it.</p><pre><code class="language-python">def _verify_pkce(code_challenge: str, code_verifier: str) -&gt; bool:
    digest = hashlib.sha256(code_verifier.encode()).digest()
    expected = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
    return secrets.compare_digest(expected, code_challenge)
</code></pre><p>The base64 here is the URL-safe variant with the <code>=</code> padding stripped, per the spec (RFC 7636). Getting that detail wrong produces a mismatch that looks exactly like a wrong verifier. And <code>secrets.compare_digest</code> does a constant-time comparison, so the check doesn't leak how many leading characters were right through response timing. For a value that's about to be compared to a secret, that's the right habit even when the practical risk is small.</p><p>I made PKCE mandatory because "secure by default" felt right, and the next part is the story of how that default met Jenkins.</p><h2 id="token-exchanging-a-code-for-tokens"><code>/token</code>: exchanging a code for tokens</h2><p>The token endpoint runs on a direct server-to-server call, and it authenticates the <em>client</em>:</p><pre><code class="language-python">client = clients.get(client_id or "")
if client is None or not client_secret or not verify_client_secret(client, client_secret):
    return JSONResponse(status_code=401, content={"error": "invalid_client"})
</code></pre><p>Client secrets are stored <strong>hashed</strong>, using the same Argon2 hasher the library uses for user passwords. I reused it deliberately instead of adding a second hashing scheme:</p><pre><code class="language-python">def hash_client_secret(secret: str) -&gt; str:
    return Argon2Hasher().hash(secret)

def verify_client_secret(client: OidcClient, secret: str) -&gt; bool:
    return Argon2Hasher().verify(client.client_secret_hash, secret)
</code></pre><p>The effect is that a leaked copy of the client registry exposes no more plaintext secrets than a leaked user database would expose plaintext passwords. The registry file is also treated like <code>.env</code>: gitignored (with a committed <code>.example</code> template), and kept out of the repository entirely.</p><p>With the client authenticated, the code is consumed and cross-checked:</p><pre><code class="language-python">entry = code_store.consume(code)
if entry is None or entry.client_id != client_id or entry.redirect_uri != redirect_uri:
    return JSONResponse(status_code=400, content={"error": "invalid_grant"})

if not _verify_pkce(entry.code_challenge, code_verifier):
    return JSONResponse(status_code=400, content={...})
</code></pre><p>The <code>client_id</code> and <code>redirect_uri</code> must match what the code was issued for. Without that, a client could redeem a code that was issued to a <em>different</em> client. Note the code is consumed (removed) <em>before</em> the PKCE check, so a failed attempt burns the code, and an attacker gets exactly one guess.</p><p>Then come the tokens:</p><pre><code class="language-python">claims = {
    "sub": entry.user_id,
    "aud": client_id,
    **_claims_for_scope(entry.scope, email=entry.email, name=entry.name),
}
id_token_claims = dict(claims)
if entry.nonce:
    id_token_claims["nonce"] = entry.nonce
id_token_claims["auth_time"] = int(time.time())
</code></pre><p><code>sub</code> is the <strong>subject</strong>: a stable, unique identifier for the user. I use the account's ID, never the email, because emails can be changed (Part 3 added exactly that feature) and a relying party that keyed accounts on email would see a renamed user as a brand new one. <code>aud</code> is the audience, the client the token was issued <em>for</em>. The <code>nonce</code>, if the client sent one at authorise time, is echoed back so the client can bind the token to its own session and detect replay.</p><p>Claims are gated by scope:</p><pre><code class="language-python">def _claims_for_scope(scope: str, *, email: str, name: str) -&gt; dict:
    claims: dict = {}
    scopes = set(scope.split())
    if "email" in scopes:
        claims["email"] = email
        claims["email_verified"] = True
    if "profile" in scopes:
        claims["name"] = name
    return claims
</code></pre><p>A client that only asked for <code>openid</code> gets just <code>sub</code>. One that asked for <code>email</code> gets the address. (<code>email_verified</code> is hard-coded to <code>True</code>. That's only defensible because accounts are created by an administrator rather than self-registered, so there's no unverified address to flag; it would be wrong the day signup opened up.)</p><p>Both the ID token and the access token are RS256 JWTs signed by the same key, five minutes of life each, carrying the same scope-gated claims:</p><pre><code class="language-python">def _issue_jwt(*, issuer, signing_key, kid, ttl_seconds, claims) -&gt; str:
    now = int(time.time())
    payload = {"iss": issuer, "iat": now, "exp": now + ttl_seconds, **claims}
    return jwt.encode(payload, signing_key, algorithm="RS256", headers={"kid": kid})
</code></pre><p>Making the access token a self-contained JWT means <code>/userinfo</code> never needs a token database: it verifies a signature and returns the claims inside.</p><pre><code class="language-python">claims = jwt.decode(
    token, signing_key.public_key(), algorithms=["RS256"],
    options={"verify_aud": False},
)
</code></pre><p>Notice <code>algorithms=["RS256"]</code>, an explicit allow-list. JWT libraries historically had a class of vulnerability where a token claiming <code>alg: none</code> or switching to a symmetric algorithm was accepted because the verifier trusted the token's own header. Pinning the algorithm on the verifying side closes it. <code>verify_aud</code> is off here because userinfo doesn't know which client is calling and the signature already proves the token is ours.</p><h2 id="discovery">Discovery</h2><p>The discovery document is what lets an administrator paste one URL into Jenkins and be done:</p><pre><code class="language-python">return {
    "issuer": issuer,
    "authorization_endpoint": f"{issuer}/api/oidc/authorize",
    "token_endpoint": f"{issuer}/api/oidc/token",
    "userinfo_endpoint": f"{issuer}/api/oidc/userinfo",
    "jwks_uri": f"{issuer}/api/oidc/jwks.json",
    "response_types_supported": ["code"],
    "subject_types_supported": ["public"],
    "id_token_signing_alg_values_supported": ["RS256"],
    "scopes_supported": ["openid", "email", "profile"],
    "token_endpoint_auth_methods_supported": ["client_secret_basic", "client_secret_post"],
    "code_challenge_methods_supported": ["S256"],
    "claims_supported": ["sub", "email", "email_verified", "name"],
}
</code></pre><p>The <code>issuer</code> comes from a <em>new</em> setting, and here a mistake I'd planned for from the start earns its keep. Part 1 introduced <code>issuer</code> as the label shown in an authenticator app. This is a different concept that needs a different name. The OIDC issuer is the service's real, externally reachable origin, with no trailing slash, and every URL in the document and the <code>iss</code> claim in every token is built from it. If the two settings were one, changing the label would break every token. So there's <code>IDENTITY_SYSTEM_OIDC_ISSUER_URL</code>, with a comment in <code>.env.example</code> and a note in the project docs saying "not the same thing".</p><p>An issuer mismatch is the classic reason an OIDC integration fails with an unhelpful message: the client fetches the discovery document, sees an <code>issuer</code> that doesn't match the URL it fetched it from, and (correctly) refuses to continue.</p><h2 id="the-test-suite">The test suite</h2><p><code>test_oidc.py</code> is about 220 lines and reads as a checklist of the properties above. The helper at the heart of it plays the part of a relying party:</p><pre><code class="language-python">def _pkce_pair():
    verifier = base64.urlsafe_b64encode(os.urandom(32)).rstrip(b"=").decode()
    challenge = (
        base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
    )
    return verifier, challenge
</code></pre><p>and the main test drives the entire flow end to end: sign in, authorise, take the code out of the redirect <code>Location</code>, exchange it, decode the ID token, call userinfo with the access token, and compare. Around it sit the negative cases:</p><ul><li>unknown client and non-matching <code>redirect_uri</code> both get a <code>400</code>, not a redirect;</li><li>missing <code>openid</code> scope, or a scope the client isn't allowed, get an <code>invalid_scope</code> redirect;</li><li>a code can't be reused;</li><li>an expired code is rejected, tested by monkeypatching <code>time.time</code> forward an hour rather than sleeping for sixty seconds;</li><li>a wrong PKCE verifier and a wrong client secret are rejected, with <code>invalid_grant</code> and <code>invalid_client</code> respectively;</li><li>userinfo rejects a missing or garbage bearer token.</li></ul><p>The test fixture for the registered client returns the <strong>plaintext</strong> secret alongside registering its hash. That's necessary (a test driving the token endpoint needs the real secret) and illustrates the property from the other side: only the hash is stored, so the plaintext has to be handed out at creation.</p><h2 id="operating-a-signing-key">Operating a signing key</h2><p>Holding a private key changes the deployment story, and it's the part of this commit I'm most glad I thought about before shipping.</p><p>The key lives in a file, <code>data/oidc_signing_key.pem</code> by default. And Part 2 told you what <code>rsync --delete</code> does to files outside <code>data/</code>. If the key file ended up anywhere else, the next deploy would delete it, and on the next start the service would <em>helpfully generate a brand new one</em>. Nothing would error. But every relying party caches the public key from the old JWKS, so every token the new key signs would fail verification until each RP re-fetched the key set. SSO would silently break for everything at once.</p><p>So the same defences that protect the database were extended to the key:</p><ul><li><code>.env.example</code> documents the path with a stern note.</li><li><code>remote-setup.sh</code> got a second check next to the database one, warning loudly if <code>IDENTITY_SYSTEM_OIDC_SIGNING_KEY_PATH</code> isn't inside <code>data/</code>.</li><li>There's no <code>*.pem</code>-style catch-all exclude in <code>deploy.sh</code>, and I deliberately didn't add one, as it would hide the problem rather than surface it. <code>data/</code> is the only thing protecting the key, and the project notes say so.</li></ul><p>The client registry, a JSON file holding hashed secrets, was initially handled the other way: gitignored, excluded from rsync by name. That held up for about 90 minutes. By the time the follow-up commits arrived (<code>feat: sync dpeloy updated</code>, typo preserved), it had moved into <code>data/</code> too, with a comment explaining why a name-based exclude was the wrong tool: <code>apps.json</code> sits right next to it and <em>must</em> sync, so excluding by file name was fragile, whereas "everything stateful lives in <code>data/</code>" is one rule that covers all of it.</p><p>The deploy-time surprise from Part 2, where <code>pip install</code> skipped reinstalling because the version string hadn't changed, also surfaced here. The OIDC routes returned <code>404</code> after a green deploy because the virtual environment was still running the pre-OIDC code. That was the bug the <code>--force-reinstall</code> flag fixed.</p><h2 id="what-this-part-changed">What this part changed</h2><p>Before this commit the service had one way in: a cookie and a header. After it, it has two, sharing the same accounts, sessions and login page. A request to <code>/api/oidc/authorize</code> without a cookie is bounced through the same <code>/login</code> form as everything else, and the same <code>rd</code> mechanism brings it back.</p><p>The decisions I'd call out as load-bearing:</p><ol><li><strong>Validate the redirect URI before ever redirecting to it</strong>, and match it exactly.</li><li><strong>Codes are unguessable, single-use and short-lived</strong>, enforced by data structure, not by discipline.</li><li><strong>Client secrets are hashed</strong>, the same way passwords are.</li><li><strong>The signing key is stateful data</strong>, and gets the same protection as the database.</li><li><strong>Pin the JWT algorithm</strong> on the verifying side.</li></ol><p>What I hadn't planned for was how much of the work was still ahead once the code compiled and the tests passed, because real software doesn't always implement the specification the way you read it. The next part is about the afternoon I spent teaching a deliberately strict identity provider to get along with Jenkins.</p><hr><p>Previous: <a href="https://ghost.atathome.me/identity-system-an-admin-page-and-a-proper-frontend/">← An admin page and a proper frontend</a> · Next: <a href="https://ghost.atathome.me/identity-system-making-jenkins-sign-in/">Making Jenkins sign in →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: Keeping data fresh: manual sync, resilience, and real stats - Part 7]]></title><description><![CDATA[~10 min read

Everything up to this point assumed the nightly sync just works. It mostly does - right up until one bank connection has a problem, at which point the version of fetch() I'd had since the very first CLI prototype turned "one bank's data is temporarily unavailable" into "nobody's data updates tonight." This post is about the sync loop growing up: a manual trigger for when 3am is too long to wait, failure isolation so one bad connection can't take the rest down with it, error message]]></description><link>https://brightbot.co.uk/keeping-data-fresh/</link><guid isPermaLink="false">Ghost__Post__6ad488c41df6faba8655699e</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Thu, 29 Oct 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1526628953301-3e589a6a8b74?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDd8fFN0YXRzfGVufDB8fHx8MTc5MjMxNzIxNnww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1526628953301-3e589a6a8b74?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDd8fFN0YXRzfGVufDB8fHx8MTc5MjMxNzIxNnww&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: Keeping data fresh: manual sync, resilience, and real stats - Part 7"/><p><em>~10 min read</em></p><p>Everything up to this point assumed the nightly sync just works. It mostly does - right up until one bank connection has a problem, at which point the version of <code>fetch()</code> I'd had since the very first CLI prototype turned "one bank's data is temporarily unavailable" into "nobody's data updates tonight." This post is about the sync loop growing up: a manual trigger for when 3am is too long to wait, failure isolation so one bad connection can't take the rest down with it, error messages that actually say what went wrong, and turning the dashboard's stat tiles from hardcoded placeholder numbers into real SQL.</p><h2 id="a-button-not-just-a-timer">A button, not just a timer</h2><p>The nightly systemd timer covers "keep data current," but not "I just linked a new bank and want to see its transactions right now" or "I suspect something's stale and want to check." Adding a manual <strong>Sync now</strong> button to the Accounts page meant the same <code>fetch()</code> function the timer calls needed to be safely callable from an HTTP request instead of only from a CLI process that's allowed to just exit.</p><p>That surfaced an actual bug immediately. The original <code>fetch()</code> bailed out with <code>sys.exit(1)</code> when no banks were linked - completely fine for a script, where <code>sys.exit</code> just ends the process. Called from inside a FastAPI route handler, <code>sys.exit</code> raises <code>SystemExit</code>, which isn't a normal <code>Exception</code> - it's the same exception class Python uses to actually terminate the interpreter, and it's not reliably something a web framework's error handling will catch cleanly. The fix was a proper exception the API layer could catch on purpose:</p><pre><code class="language-python">class NoLinkedBanks(Exception):
    """Raised by fetch() when no banks are linked yet - callers (the CLI,
    the manual-sync API route) decide how to surface that."""
</code></pre><p>The CLI's <code>__main__</code> block catches it and calls <code>sys.exit(1)</code> itself, at the actual process boundary where that's the correct behaviour. The API route catches it and returns a 400 with a message the frontend can show. Same underlying condition, two completely different "this is how a caller should be told about it" - which is really the whole argument for not baking process-termination into a function you also want to call as a library.</p><h2 id="one-banks-problem-shouldnt-be-every-banks-problem">One bank's problem shouldn't be every bank's problem</h2><p>The bigger issue only showed up once I actually watched <code>fetch()</code> fail against real data: it looped over every linked bank, and any single <code>requests.HTTPError</code> - a bank whose consent had lapsed, an account TrueLayer returned a 403 for - propagated straight out of the whole function. Three linked banks, one having a bad day, and <em>none</em> of them got new transactions that run. That's a much worse failure mode than "this one bank is stale" - it makes reliable data quietly depend on the least reliable connection you have.</p><p>The fix was pushing <code>try</code>/<code>except</code> down to the smallest unit that can fail independently - token refresh, listing accounts, and each account's own transaction pull - and collecting failures instead of raising past them:</p><pre><code class="language-python">for kind, account_id, name in sources:
    try:
        txns = get(access, f"/{kind}/{account_id}/transactions", date_range, logger=logger)
    except requests.RequestException as exc:
        logger.error(f"{label} / {name}: could not fetch transactions - {exc}", exc_info=True)
        errors.append({"bank": label, "account": name, "error": f"could not fetch transactions ({exc})"})
        continue
    ...
</code></pre><p><code>continue</code> instead of letting the exception bubble is the entire fix. One account failing means that account doesn't get new transactions this run - and every other account, on every other bank, still does. <code>fetch()</code> now returns a summary including whatever went wrong (<code>{"transactions": N, "connections": N, "errors": [...]}</code>), and the manual sync endpoint surfaces those as warnings alongside an otherwise-successful result, rather than the whole request just failing with one opaque error.</p><h2 id="knowing-why-not-just-that-something-failed">Knowing <em>why</em>, not just <em>that</em>, something failed</h2><p>The error messages I was logging before this were nearly useless for actually diagnosing anything: <code>"403 Client Error: Forbidden for url: ...transactions"</code> and nothing else. TrueLayer's actual error body carries a specific code that explains what's going on - <code>access_denied</code> (consent's expired or been revoked, needs re-linking) versus <code>sca_exceeded</code> (some providers only allow pulling transaction history for a short window right after the user authenticates, and a 90-day pull outside that window gets rejected even with an otherwise-valid token) - and <code>raise_for_status()</code> throws that information away before I ever saw it.</p><pre><code class="language-python">if not resp.ok:
    # TrueLayer's error body carries a code (e.g. access_denied,
    # sca_exceeded) that the status alone doesn't - log it before
    # raise_for_status() reduces it to just "403 Client Error: ...".
    logger.error(f"TrueLayer {resp.status_code} on {path}: {resp.text}")
resp.raise_for_status()
</code></pre><p>One line, logged before the exception gets raised. (A few days later the detail stopped being log-only: a follow-up turned it into a real <code>TrueLayerAPIError</code> carrying the error <code>code</code>, so the UI could tell a revoked consent from <code>sca_exceeded</code> - that's in <a href="https://ghost.atathome.me/making-the-nightly-sync-boring/">post 17</a>.) It's a small change with an outsized effect on how it feels to operate this thing - the difference between "something's wrong with Monzo, no idea what" and "this specific account's consent expired, it needs re-linking" is the difference between a mystery and a two-minute fix.</p><h2 id="surfacing-partial-failure-without-crying-wolf">Surfacing partial failure without crying wolf</h2><p>Getting the backend to isolate failures was only half the problem - the sync button also had to <em>show</em> a partial failure honestly, without either hiding it or treating it as catastrophic. A sync where two banks updated fine and one hit a <code>sca_exceeded</code> error isn't a failed sync; it's a mostly-successful one with a specific, actionable warning attached, and the UI needed to say exactly that:</p><pre><code class="language-tsx">setSyncMessage(
  `Synced ${result.transactions_inserted} new transaction(s) across ${result.banks_synced} bank(s).`,
)
setSyncWarnings(result.errors)
</code></pre><p>A green success line for what worked, sitting directly above an amber warning list for what didn't, in the same result - not a single pass/fail toast that would have to pick one or the other and misrepresent whichever it didn't pick. The button itself walks through three states while this happens (<code>Sync now</code> → <code>Syncing…</code> → back to <code>Sync now</code>), each one covered by a test that stubs a slow-resolving promise and asserts the button's disabled and relabelled for exactly the right window - a small thing, but "did the button actually enter its loading state" turned out to be an easy regression to introduce silently while refactoring the surrounding component, and cheap to catch with a test that just waits on a manually controlled promise before letting it resolve.</p><h2 id="a-de-dup-key-that-could-move-under-me">A de-dup key that could move under me</h2><p>Separately, and worth a short mention here because it's the same class of lesson - <em>read what the vendor's docs actually promise, not just what the field looks like it means</em> - I'd been de-duplicating transactions on TrueLayer's <code>transaction_id</code> since the very first prototype. Their docs describe that field as one that <strong>may change between requests</strong>, and recommend <code>normalised_provider_transaction_id</code> instead as the one that's stable. My primary key relied on exactly the property TrueLayer explicitly doesn't guarantee. The fix was a one-line change with a fallback for providers that don't return the normalised field:</p><pre><code class="language-python">"id": t.get("normalised_provider_transaction_id", t["transaction_id"]),
</code></pre><p>Nothing had gone wrong yet when I made this change - which is exactly why it was worth making before it did.</p><h2 id="real-numbers-instead-of-placeholders">Real numbers instead of placeholders</h2><p>The Home page's stat tiles started as hardcoded demo values, which was fine for getting the layout right but obviously not the point. Income and spending "this month" turned into an actual SQL aggregate over the transactions table:</p><pre><code class="language-sql">SELECT
    COALESCE(SUM(CASE WHEN amount &gt; 0 THEN amount END), 0) AS income,
    COALESCE(SUM(CASE WHEN amount &lt; 0 THEN -amount END), 0) AS outgoings
FROM transactions
WHERE date &gt;= :start AND date &lt; :end
</code></pre><p>Run once for the current calendar month and once for the previous one, and the difference between the two gives the stat tiles their "up/down vs last month" delta - the same query, just two different date ranges, rather than two different code paths. (Calendar months didn't last: once categorisation meant totals had to exclude transfers, a later commit replaced this SQL with a Python <code>summarize()</code> that runs after categorisation, and another swapped calendar months for rolling 30/60/90-day windows. See <a href="https://ghost.atathome.me/rule-based-categorisation/">post 12</a> and <a href="https://ghost.atathome.me/periods-charts-and-a-phone-sized-ui/">post 13</a>.) Consent expiry got the same treatment on the Accounts page: TrueLayer's <code>/me</code> endpoint returns <code>consent_expires_at</code> for a connection, cached alongside everything else, and rendered as "Expires in N days" or a harder "Needs re-linking" once it's past.</p><h2 id="picking-thresholds-for-the-expiry-badge">Picking thresholds for the expiry badge</h2><p>The consent expiry badge needed actual thresholds, not just a raw date, because "expires 2026-11-14" on its own doesn't tell me whether that's something to act on today or something to ignore for two months. I settled on three states: comfortably far away (no badge, nothing to see), inside fourteen days (an amber "Expires in N days"), and past expiry (a red "Needs re-linking"). Fourteen days came from wanting enough lead time to actually notice and act before a sync silently starts failing for that bank - shorter than that and there's a real chance I don't look at the Accounts page in the window between "worth mentioning" and "already broken." It's a judgement call, not a number TrueLayer prescribes, and one I'd tighten if a re-link ever turned out to need more notice in practice than two weeks gives.</p><h2 id="what-fresh-actually-means-now">What "fresh" actually means now</h2><p>None of this changed what data the app pulls - it's the same TrueLayer calls as the very first prototype. What changed is what happens when one piece of that data has a bad day: it used to mean nothing updated and you found out from a stale dashboard; now it means everything <em>else</em> still updates, the one thing that failed says specifically why, and you can trigger a re-check whenever you want instead of waiting for 3am. That's the actual bar for "keeping data fresh" on a tool you're meant to trust every morning.</p><p>The last piece was making that trust more complete: showing what's actually in each account, not just what's been spent from it - and giving myself a clean way to disconnect a bank once I stopped needing it.</p><hr><p>Previous: <a href="https://ghost.atathome.me/auth-2fa-and-settings/">← Auth, two-factor, and account settings</a> · Next: <a href="https://ghost.atathome.me/balances-and-disconnecting-banks/">Account balances and disconnecting banks →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Central login service: An admin page and a proper frontend - Part 3]]></title><description><![CDATA[~25 min read

By the end of Part 2 the login service was deployed and doing its job, and its entire user interface was one HTML form built from a Python string. That was fine for a service whose only visible surface was "type your password". It stopped being fine within a day, because I immediately wanted three things the form couldn't give me:

 1. A way to see who has an account and when they last signed in.
 2. A landing page listing the apps that sit behind the login, so the service is somew]]></description><link>https://brightbot.co.uk/identity-system-an-admin-page-and-a-proper-frontend/</link><guid isPermaLink="false">Ghost__Post__6ada2fa41df6faba86556a82</guid><category><![CDATA[Building Identity System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Tue, 27 Oct 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1667372393086-9d4001d51cf1?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fGZyb250ZW5kfGVufDB8fHx8MTc5MjY4NDA3MHww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1667372393086-9d4001d51cf1?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fGZyb250ZW5kfGVufDB8fHx8MTc5MjY4NDA3MHww&ixlib=rb-4.1.0&q=80&w=2000" alt="Central login service: An admin page and a proper frontend - Part 3"/><p><em>~25 min read</em></p><p>By the end of <a href="https://ghost.atathome.me/identity-system-shipping-it-jenkins-uv-and-a-container/">Part 2</a> the login service was deployed and doing its job, and its entire user interface was one HTML form built from a Python string. That was fine for a service whose only visible surface was "type your password". It stopped being fine within a day, because I immediately wanted three things the form couldn't give me:</p><ol><li>A way to see <strong>who has an account</strong> and when they last signed in.</li><li>A landing page listing <strong>the apps</strong> that sit behind the login, so the service is somewhere you <em>go</em>, not just somewhere you get bounced through.</li><li>An <strong>account page</strong> where a signed-in person can change their own name and email.</li></ol><p>This part covers how I got those, including the part where I built the first one the quick way, then threw the approach away roughly half an hour later. The commits involved are <code>feat: add admin interface</code>, <code>feat: adding better frontend</code> and <code>feat: add ability to update user data</code>.</p><h2 id="step-one-the-quick-admin-page">Step one: the quick admin page</h2><p>The first attempt followed the grain of what already existed. The login page was an inline HTML template, so the admin page would be one too:</p><pre><code class="language-python">@app.get("/admin", response_class=HTMLResponse)
def admin_users(request: Request):
    try:
        user = current_user(request)
    except AuthenticationError:
        return RedirectResponse(url="/login?rd=/admin", status_code=303)
    if not settings.is_admin(user.email):
        return HTMLResponse("Forbidden", status_code=403)
    return render_admin_users(auth.list_users())
</code></pre><p>There are two ideas in it worth keeping, because they survive into the final design.</p><p><strong>A static admin allowlist.</strong> The library has no roles, so "who is an admin?" had to be answered somewhere. I picked the dumbest mechanism that could work: an environment variable.</p><pre><code class="language-python">admin_emails=frozenset(
    email.strip().lower()
    for email in _env("ADMIN_EMAILS", "").split(",")
    if email.strip()
),

def is_admin(self, email: str) -&gt; bool:
    return email.strip().lower() in self.admin_emails
</code></pre><p>Comma-separated, case-insensitive, empty by default, meaning <em>nobody can reach the admin pages until the variable is set</em>. That default fails closed. There's no in-app management of the list: to change who's an admin you edit <code>.env</code> and restart. The project's notes are blunt that this is a deliberate choice rather than a stopgap: "no in-app management, edit <code>.env</code> and restart to change who's on it". Stored roles would be the proper answer, but they'd be a new rule, and new rules belong in the library.</p><p>It does mean this service now has a tiny authorisation concept of its own, which sits awkwardly with Part 1's "authentication, not authorisation". The note in the code is honest about it: the admin page is <em>this service's own page</em>, not a downstream app's, so it makes its own call.</p><p><strong>Redirect on 401, 403 on not-admin.</strong> A human browsing to <code>/admin</code> while signed out should be sent to sign in and then brought back, so a missing session becomes a <code>303</code> to <code>/login?rd=/admin</code>. A signed-in non-admin should get a refusal. The distinction between "I don't know who you are" and "I know who you are, and no" matters for usability and for not leaking information, and it's the distinction the later design keeps even though it moves who does the redirecting.</p><p>The page itself was an HTML table in a template with every value passed through <code>html.escape</code>. The columns were email, name, created, last login and whether two-factor is on. The tests followed the pattern from Part 1: not logged in gets redirected, logged in but not on the list gets <code>403</code>, and an admin sees all the users, including a "never" in the last-login column for an account that has never signed in.</p><p>It worked. And it made the next problem obvious.</p><h2 id="why-the-inline-html-had-to-go">Why the inline HTML had to go</h2><p>An inline HTML template is a fine way to build exactly one form. By the time I had two (login and the user list), the cracks were showing:</p><ul><li>All the styling was a <code>&lt;style&gt;</code> block in a Python string, duplicated per template.</li><li>Every interactive behaviour would need hand-written JavaScript in a string too, with no tests and no tooling.</li><li>The things I actually wanted next (an apps directory, an account editor, and eventually forms for creating users) are <em>applications</em>, with state, validation and error handling, not documents.</li></ul><p>The other apps in my fleet already use Vite + React + TypeScript, with Vitest for tests and <code>oxlint</code> for linting, so the decision wasn't much of a decision. The consequential question was the <em>shape of the split</em>: what does the Python side become when it no longer renders pages?</p><p>The answer, written at the top of <code>app.py</code> after the change: <strong>a pure JSON API, with no server-rendered HTML at all.</strong> Every page, <code>/</code>, <code>/login</code>, <code>/admin</code> and <code>/account</code>, is a client-side route that nginx serves from the built frontend.</p><p>That's a clean line to draw, and it's worth drawing. It means the backend's tests never assert on HTML, the frontend's tests never need a real backend, and the contract between them is a handful of JSON endpoints that I can reason about independently.</p><h2 id="reshaping-the-api">Reshaping the API</h2><p>Moving to a JSON API changed three routes, and one of those changes had a constraint I need to explain.</p><h3 id="login-becomes-post-apilogin">Login becomes <code>POST /api/login</code></h3><p>The old login handler accepted a form post and replied with a <code>303</code> redirect. A single-page app wants the opposite: send JSON, get JSON back, decide what to do next. The new route:</p><pre><code class="language-python">@app.post("/api/login")
def api_login(payload: dict):
    result = auth.login(
        payload.get("email", ""),
        payload.get("password", ""),
        otp=payload.get("otp") or None,
    )
    target = (
        payload.get("rd", "")
        if settings.is_trusted_redirect(payload.get("rd", ""))
        else "/account"
    )
    response = JSONResponse(
        {"user": _user_json(result.user), "redirect_to": target}
    )
    _set_session_cookie(response, result.token)
    return response
</code></pre><p>Notice what disappeared: the <code>try/except AuthError</code> that used to re-render the form. With no HTML to re-render, a failed login can just raise and let the central error table produce a JSON <code>401</code>, which is exactly the "every route is a plain JSON route, no exceptions" simplification I was after. The <code>OtpInvalid</code> entry from Part 1 now matters for this route too, since a wrong two-factor code at login is one of the ways it can fail.</p><p>The part I care most about is <code>redirect_to</code>. The open-redirect defence from Part 1 (<code>is_trusted_redirect</code>) is still applied <em>on the server</em>, and the server hands the verdict back as a field. The frontend's rule is then simple and absolute:</p><blockquote><strong>Navigate to <code>redirect_to</code>. Never navigate to the raw <code>?rd=</code> from the URL.</strong></blockquote><p>If the browser code ever grabbed <code>rd</code> straight from the query string and used it, the server-side validation would be decoration. So the component does this:</p><pre><code class="language-tsx">const result = await api.post&lt;LoginResponse&gt;('/api/login', { email, password, otp, rd })
// redirect_to is computed server-side (Settings.is_trusted_redirect) -
// navigate to that, never to the raw ?rd= itself, or the
// open-redirect guard is for nothing (see CLAUDE.md).
window.location.assign(result.redirect_to)
</code></pre><p>And the test for it is written to fail if someone breaks the rule. It renders the login form with a <em>malicious</em> <code>rd</code>, mocks the server replying with a safe <code>redirect_to</code> of <code>/account</code>, and asserts the browser was sent to <code>/account</code>:</p><pre><code class="language-tsx">renderLogin('https://evil.example.net/phish')
...
await waitFor(() =&gt; expect(assign).toHaveBeenCalledWith('/account'))
</code></pre><p>Testing a security property by <em>attacking your own component</em> is a good habit. A test that only checked the happy path would pass just as happily if the component ignored <code>redirect_to</code> entirely.</p><h3 id="the-admin-list-becomes-get-apiadminusers">The admin list becomes <code>GET /api/admin/users</code></h3><p>Same logic. The route returns JSON, gets its authentication from <code>Depends(current_user)</code>, and checks the allowlist itself:</p><pre><code class="language-python">@app.get("/api/admin/users")
def admin_users(user: User = Depends(current_user)):
    if not settings.is_admin(user.email):
        raise HTTPException(status_code=403, detail="forbidden")
    return [ { "id": u.id, "email": u.email, ... } for u in auth.list_users() ]
</code></pre><p>A comment explains the asymmetry that tripped me up briefly: <code>is_admin</code> isn't a library exception, it's this service's own bespoke check, so there's no <code>AuthError</code> subclass to put in the status table. It's a plain <code>HTTPException</code>.</p><p>What the route no longer does is redirect. A JSON endpoint has no business returning a <code>303</code> to an HTML page; it returns <code>401</code> or <code>403</code> and the frontend decides what to show. That decision moved to the page component, which I'll get to shortly.</p><h3 id="a-new-public-endpoint-get-apiapps">A new public endpoint: <code>GET /api/apps</code></h3><p>The landing page lists the apps behind the login. Where does that list come from? For this iteration the answer was the simplest possible thing: a JSON file in the repository, loaded once at startup.</p><pre><code class="language-json">[
  {
    "name": "Finance",
    "url": "https://finance.example.com",
    "description": "Accounts, transactions, and budgeting."
  },
  ...
]
</code></pre><pre><code class="language-python">def load_apps(path: str) -&gt; list[dict]:
    try:
        text = Path(path).read_text()
    except FileNotFoundError:
        return []
    return json.loads(text)
</code></pre><p>A missing file returns an empty list rather than raising, so a fresh checkout with no apps configured simply renders an empty directory. The route that serves it is deliberately unauthenticated:</p><pre><code class="language-python">@app.get("/api/apps")
def list_apps():
    # Public, deliberately unauthenticated - the apps directory (this
    # service's own default landing page) is meant to be visible
    # whether or not the visitor is signed in.
    return apps
</code></pre><p>That is a choice with consequences. Anyone who can reach the service can read the list of app names and URLs. For a personal setup those are names I'd happily publish (each app is behind the login anyway), but it's the sort of decision to make consciously, not by default. It is also why the descriptions are written as a one-line "what it does" rather than anything operational.</p><p>Editing the list means editing the file and restarting. That was fine for a first cut. Part 6 is about why it didn't stay that way.</p><h3 id="the-constraint-some-paths-cant-move">The constraint: some paths can't move</h3><p>While I was reshaping routes, I hit a rule I had to write into the project notes. Four things, <code>POST /logout</code>, <code>GET /verify</code>, <code>GET /me</code>, and the profile, password and two-factor routes, are <strong>frozen</strong>. Their bare paths and their shapes can't change.</p><p>The reason is that other things already depend on them. Other apps' nginx configs call <code>/verify</code> by that exact path. My finance app's already-deployed frontend hardcodes the identity service's origin and calls <code>/me</code> and the account routes. If I'd tidied everything into an <code>/api/</code> namespace for consistency, I'd have broken every app behind the login in one deploy.</p><p>So the rule became: <em>anything new goes under <code>/api/</code>; anything that existed before this point stays where it is.</em> The result is a slightly untidy namespace, with bare legacy paths alongside <code>/api/*</code>, but it's untidy in a way that's documented, and the alternative was a coordinated multi-repository change for no functional gain. The Vite dev-server config even carries a comment about it:</p><pre><code class="language-ts">// Dev-server-only proxy to the backend on :8000 (production nginx does the
// equivalent split - see deploy/nginx-identity-system.conf). Longer than a
// typical single '/api' entry because most of this backend's routes are
// still bare paths (/verify, /logout, /me, ...) rather than namespaced -
// see CLAUDE.md on why those can't move.
server: {
  proxy: {
    '/api': 'http://localhost:8000',
    '/verify': 'http://localhost:8000',
    '/logout': 'http://localhost:8000',
    '/me': 'http://localhost:8000',
    '/profile': 'http://localhost:8000',
    '/password': 'http://localhost:8000',
    '/2fa': 'http://localhost:8000',
  },
},
</code></pre><p>This is a general piece of API-design advice dressed as a config file: <strong>the first time something is depended on by another system, its URL becomes a public contract</strong>, however private it felt when you wrote it.</p><h2 id="the-frontend">The frontend</h2><h3 id="structure">Structure</h3><p>The app is small enough to describe in one list:</p><ul><li><code>App.tsx</code>: the shell. Fetches <code>GET /me</code> once, renders the nav and the router.</li><li><code>Apps.tsx</code>: the landing page (<code>/</code>).</li><li><code>Login.tsx</code>: the sign-in form (<code>/login</code>).</li><li><code>Account.tsx</code>: the signed-in user's own details (<code>/account</code>).</li><li><code>Admin.tsx</code>: the user list (<code>/admin</code>).</li><li><code>api.ts</code>: one shared <code>fetch</code> wrapper.</li><li><code>NavBar.tsx</code>, <code>types.ts</code>, <code>index.css</code>.</li></ul><p>The toolchain matches the rest of the fleet: React 19, <code>react-router-dom</code>, Vite, TypeScript, <code>oxlint</code>, and Vitest with Testing Library, with the Node version pinned in a <code>.node-version</code> file.</p><h3 id="one-fetch-wrapper">One fetch wrapper</h3><p>Every page talks to the backend through one small module:</p><pre><code class="language-ts">export class ApiError extends Error {
  status: number
  constructor(status: number, message: string) {
    super(message)
    this.status = status
  }
}

async function request&lt;T&gt;(path: string, init?: RequestInit): Promise&lt;T&gt; {
  const res = await fetch(path, {
    ...init,
    credentials: 'same-origin',
    headers: { 'Content-Type': 'application/json', ...init?.headers },
  })
  if (!res.ok) {
    let detail = res.statusText
    try {
      const body = await res.json()
      if (body?.detail) detail = body.detail
    } catch {
      // no JSON body - keep the status text
    }
    throw new ApiError(res.status, detail)
  }
  if (res.status === 204) return undefined as T
  return (await res.json()) as T
}
</code></pre><p>Three small design points. Errors are a typed <code>ApiError</code> carrying the HTTP status, so callers can branch on <code>401</code> vs <code>403</code> without parsing message strings. The backend consistently returns <code>{"detail": ...}</code> for failures (that's what the central error handler produces), and the wrapper surfaces <code>detail</code> as the error message, which means a form can display the server's own words (like "incorrect email or password") without any per-form translation. And <code>204 No Content</code> is special-cased, since calling <code>.json()</code> on an empty body throws; the profile update route returns exactly that.</p><p><code>credentials: 'same-origin'</code> is the line that makes the whole thing work with a cookie: nothing in the frontend carries a token. The browser attaches the session cookie to each request, and the server decides who's asking.</p><h3 id="the-shell-has-to-tolerate-being-signed-out">The shell has to tolerate being signed out</h3><p>A downstream app's frontend treats a <code>401</code> from <code>/me</code> as fatal. If you're not signed in, nothing works, so it redirects to login. This app can't do that, because its landing page is public. The shell therefore does something unusual:</p><pre><code class="language-tsx">const [user, setUser] = useState&lt;User | null&gt;(null)
// Unlike a downstream app's own frontend (which requires auth for
// everything and treats a 401 from GET /me as fatal), this app has to
// render the Apps page whether or not the visitor is signed in - so a
// 401 here is just "not logged in", not an error.
const [checkedAuth, setCheckedAuth] = useState(false)

useEffect(() =&gt; {
  api
    .get&lt;User&gt;('/me')
    .then(setUser)
    .catch(() =&gt; setUser(null))
    .finally(() =&gt; setCheckedAuth(true))
}, [])
</code></pre><p>Two pieces of state, not one. <code>user</code> is <code>null</code> for "signed out", but the first render also has <code>user === null</code> before the request finishes. Without <code>checkedAuth</code> the nav would flash "Sign in" at a signed-in user for a moment on every page load, or worse, the account page would redirect them to login before <code>/me</code> had answered. The <code>if (!checkedAuth) return &lt;p&gt;Loading...&lt;/p&gt;</code> guard waits for the first answer.</p><h3 id="logging-out-is-a-form-post-not-a-fetch">Logging out is a form post, not a <code>fetch</code></h3><pre><code class="language-tsx">const handleLogout = () =&gt; {
  // A real top-level form submission, not fetch() - POST /logout
  // redirects to /login, which fetch() can't turn into a page navigation.
  const form = document.createElement('form')
  form.method = 'POST'
  form.action = '/logout'
  document.body.appendChild(form)
  form.submit()
}
</code></pre><p><code>POST /logout</code> is one of the frozen legacy routes, and it replies with a <code>303</code> redirect to <code>/login</code>. A <code>fetch()</code> call would follow that redirect internally and hand the JavaScript a login-page response body, leaving the browser sitting on whatever page it was on. A real form submission is a top-level navigation, so the browser follows the redirect and <em>lands</em> on the login page. It's four lines of DOM code that exist purely to avoid rewriting a route I wasn't allowed to change. (A later finance-side frontend does the same thing for the same reason, with its form pointing at this service.)</p><h3 id="page-level-handling-of-401-and-403">Page-level handling of 401 and 403</h3><p>Back to the question the JSON admin route left open: if the API no longer redirects, who does? The page does, by mapping the response onto a small state machine:</p><pre><code class="language-tsx">type Status = 'loading' | 'ok' | 'unauthenticated' | 'forbidden' | 'error'

.catch((err: unknown) =&gt; {
  if (err instanceof ApiError &amp;&amp; err.status === 401) setStatus('unauthenticated')
  else if (err instanceof ApiError &amp;&amp; err.status === 403) setStatus('forbidden')
  else setStatus('error')
})

...
if (status === 'unauthenticated') return &lt;Navigate to="/login?rd=/admin" replace /&gt;
if (status === 'forbidden') {
  return &lt;p className="error"&gt;Forbidden - your account isn't on the admin allowlist.&lt;/p&gt;
}
</code></pre><p>The first version of this lived inside the <code>Admin</code> component. As more admin pages arrived it was lifted into a reusable hook, <code>useAdminList</code>, which Part 6 leans on heavily. The behaviour is identical: signed out goes to login with a return path, signed in but not allowed gets a message, anything else gets a generic error. Using <code>&lt;Navigate ... replace /&gt;</code> rather than pushing a new history entry means the back button doesn't strand the user on a page that immediately redirects them again.</p><h3 id="the-apps-page">The apps page</h3><p>The landing page is a grid of cards, each one a plain <code>&lt;a&gt;</code>:</p><pre><code class="language-tsx">// Plain &lt;a&gt;, not react-router's &lt;Link&gt; - these point at other
// origins entirely. A logged-out click bounces through that
// app's own forward-auth back to /login?rd=&lt;that app&gt; ...
&lt;a key={app.url} className="app-card" href={app.url}&gt;
  &lt;strong&gt;{app.name}&lt;/strong&gt;
  &lt;p&gt;{app.description}&lt;/p&gt;
&lt;/a&gt;
</code></pre><p>The comment records something I like about the design. The apps page doesn't need to know whether you're signed in. A click on an app link goes to that app; if you're signed out, the <em>app's own</em> forward-auth sends you to <code>/login?rd=&lt;that app&gt;</code>; you sign in; you land back on the app. The directory is just links, and the single sign-on machinery from Part 1 does all the work.</p><h2 id="serving-it-nginx-and-the-proxy-by-default-decision">Serving it: nginx and the proxy-by-default decision</h2><p>In production there's no Node server. <code>vite build</code> produces static files in <code>frontend/dist/</code>, and nginx serves them. The interesting question is <em>which requests</em> get static files and which get proxied to Python.</p><p>A single-page app has client-side routes: <code>/login</code>, <code>/admin</code> and <code>/account</code> don't exist as files; the browser asks nginx for them and nginx must hand back <code>index.html</code> so React Router can take over. The natural config is to list those routes explicitly:</p><pre><code class="language-nginx">root __BACKEND_DIR__/frontend/dist;

location = / { try_files /index.html =404; }
location = /login { try_files /index.html =404; }
location = /admin { try_files /index.html =404; }
location = /account { try_files /index.html =404; }

location /assets/ {
    try_files $uri =404;
    expires 1y;
    add_header Cache-Control "public, immutable";
}

location / {
    proxy_pass http://127.0.0.1:8000;
    ...
}
</code></pre><p>The <code>location =</code> form is an <em>exact match</em>, which is why each page route is its own line. The <code>/assets/</code> block serves Vite's hashed bundle files with a year-long <code>immutable</code> cache header, which is safe because the filenames contain a content hash, so a new build produces new names. And the last block is the part I want to draw attention to.</p><p><strong>The default is to proxy, not to serve static files.</strong> The usual SPA config does the opposite: serve <code>index.html</code> for anything not matching a file. I didn't do that because this backend has a long tail of bare legacy paths (<code>/verify</code>, <code>/logout</code>, <code>/me</code>, <code>/profile</code>, <code>/password</code>, <code>/2fa/*</code>) that other systems hardcode. With proxy-by-default, a new backend route just works without nginx needing to know about it. The cost is that every new <em>frontend</em> page route needs a matching <code>location =</code> line, and forgetting one means a browser refresh on that page returns a <code>404</code>, as the router only handles in-app navigation. The project notes carry that as a standing reminder.</p><h2 id="jenkins-gets-a-second-stage">Jenkins gets a second stage</h2><p>The pipeline needed a frontend build, and the Test stage became two parallel branches:</p><pre><code class="language-groovy">stage('Test') {
    parallel {
        stage('Backend') { ... uv sync --locked --extra dev; uv run pytest ... }
        stage('Frontend') {
            steps {
                dir('frontend') {
                    sh '''
                        mkdir -p ../reports
                        npm ci
                        npm run lint
                        npm test -- --reporter=junit --outputFile=../reports/junit-frontend.xml
                        npm run build
                    '''
                }
            }
        }
    }
}
</code></pre><p><code>npm ci</code> (as opposed to <code>npm install</code>) installs exactly what the lockfile says and fails if it disagrees, which is the same philosophy as <code>uv sync --locked</code>. Lint, test and build run in that order so the cheapest checks fail first. The Node version doesn't come from a Jenkins-managed tool installation. The environment block puts the <code>nodenv</code> shims on <code>PATH</code>, and the version is dispatched from <code>frontend/.node-version</code>, so CI and local development use the same Node.</p><p>The <code>frontend/dist/</code> the build produces is then simply part of the checkout that <code>deploy.sh</code> rsyncs to the container. It isn't excluded from the sweep, so a new build's output replaces the old one, with <code>--delete</code> removing stale hashed files. Both test branches publish JUnit results, so a failure points at a specific test rather than a console log.</p><h2 id="letting-people-edit-their-own-account">Letting people edit their own account</h2><p>The last commit in this part gives the account page something to do. It had been read-only; now it has two forms.</p><pre><code class="language-tsx">const handleNameSubmit = async (e: FormEvent) =&gt; {
  e.preventDefault()
  setNameStatus('saving')
  setNameError(null)
  try {
    await api.patch('/profile', { name })
    await refreshUser()
    setNameStatus('idle')
  } catch (err) {
    setNameError(err instanceof ApiError ? err.message : 'Something went wrong')
    setNameStatus('error')
  }
}
</code></pre><p>There are two forms rather than one because the backend treats the two fields differently, and the UI shouldn't pretend otherwise. Changing your <strong>display name</strong> needs nothing but a session. Changing your <strong>email</strong> requires your <strong>current password</strong>, because email is the thing a password-reset flow or an account takeover would target. The email form therefore has a password field the name form doesn't, with a comment pointing at why.</p><p>Two things in that component are worth pulling out.</p><p><strong>Re-fetch instead of trusting the response.</strong> <code>PATCH /profile</code> returns <code>204 No Content</code> (Part 1 explained why: there's no get-by-id to return the refreshed record from). So after each successful save the form calls <code>/me</code> again and pushes the result up to the shell. That way the name in the nav bar updates immediately and the <code>User</code> the whole app holds is the server's version, not the client's guess.</p><p><strong>Hooks before the early return.</strong> Near the top of the component:</p><pre><code class="language-tsx">// Hooks can't run conditionally, so these are declared before the
// !user redirect below - `user` is only ever null for the one render
// before that redirect takes effect.
const [name, setName] = useState(user?.name ?? '')
...
if (!user) return &lt;Navigate to="/login?rd=/account" replace /&gt;
</code></pre><p>React requires hooks to be called in the same order on every render, which rules out calling <code>useState</code> after a conditional <code>return</code>. So every piece of state is declared first, seeded defensively from <code>user?.name ?? ''</code>, and only then does the component bail out for a signed-out visitor. It looks fussy, and it is precisely the sort of rule a linter catches and a human forgets.</p><p>The same commit also had to change <code>App.tsx</code> so the shell passes down an <code>onUserUpdated</code> callback and the API wrapper grew a <code>patch</code> method alongside <code>get</code> and <code>post</code>. The commit stat reads 185 lines added and 24 removed across four files, roughly half of it test code covering both forms and their error states.</p><p>Password and two-factor management are still missing from this page. The text on the page says so ("More account management... is coming here later"), and it was a conscious stopping point. Those routes exist on the backend; they need UI.</p><h2 id="what-this-part-changed">What this part changed</h2><p>Counting in files, the story is: one commit adds a server-rendered admin page; the next deletes all server-rendered HTML, adds 44 files and a few thousand lines (the bulk being <code>package-lock.json</code>, tests and CSS), and turns Python into a JSON API; the third gives the account page real forms.</p><p>Counting in lessons, it's shorter:</p><ol><li><strong>Don't defend a sunk cost.</strong> The inline-HTML admin page took a short time and was wrong for where the project was going. Replacing it quickly cost less than living with it.</li><li><strong>Draw the line between API and UI early, and draw it hard.</strong> "No HTML in Python" is a rule I can check in code review by grepping for it.</li><li><strong>Treat URLs other systems use as a contract.</strong> The frozen legacy paths are the reason the migration was safe, and the reason the namespace is a little untidy.</li><li><strong>Test security properties adversarially.</strong> The login test feeds in a hostile <code>rd</code>, which is the case that matters.</li></ol><p>With a frontend in place, the service can finally do something it couldn't when it was only a login form: be part of someone else's login flow. The next part is about teaching it to speak OpenID Connect.</p><hr><p>Previous: <a href="https://ghost.atathome.me/identity-system-shipping-it-jenkins-uv-and-a-container/">← Shipping it</a> · Next: <a href="https://ghost.atathome.me/identity-system-becoming-an-openid-connect-provider/">Becoming an OpenID Connect provider →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: Auth, two-factor, and account settings - Part 6]]></title><description><![CDATA[~10 min read

Status: superseded. Everything described below was built, shipped and then deleted within about two days. On 28 September, two commits moved login, passwords and two-factor out of this app entirely and into a separate identity-system service that nginx consults before any request reaches the app. The post stays because the design reasoning (and the gaps it ran into) are the reason that move happened - the full story is in post 9.

This is a single-user app sitting in front of real ]]></description><link>https://brightbot.co.uk/auth-2fa-and-settings/</link><guid isPermaLink="false">Ghost__Post__6ad488c31df6faba86556999</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Tue, 27 Oct 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1633265486064-086b219458ec?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fFBhc3N3b3Jkc3xlbnwwfHx8fDE3OTIzMTczMDh8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1633265486064-086b219458ec?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fFBhc3N3b3Jkc3xlbnwwfHx8fDE3OTIzMTczMDh8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: Auth, two-factor, and account settings - Part 6"/><p><em>~10 min read</em></p><blockquote><strong>Status: superseded.</strong> Everything described below was built, shipped and then deleted within about two days. On 28 September, two commits moved login, passwords and two-factor out of this app entirely and into a separate <code>identity-system</code> service that nginx consults before any request reaches the app. The post stays because the design reasoning (and the gaps it ran into) are the reason that move happened - the full story is in <a href="https://ghost.atathome.me/handing-auth-to-identity-system/">post 9</a>.</blockquote><p>This is a single-user app sitting in front of real bank transaction data, which makes "how does login work" a question worth taking seriously even though there's only ever going to be one account. I didn't want to hand-roll password hashing or session management for a side project - that's exactly the kind of code where a subtle mistake sits quietly wrong for months - so authentication here is handled by a small library I wrote separately, <code>sessionkit</code>, rather than inline in this app. This post is about the parts that actually touch this project: wiring it in, building two-factor authentication on top of it, and one genuinely awkward gap I had to design around when I split account settings into sections.</p><h2 id="what-sessionkit-provides">What sessionkit provides</h2><p><code>sessionkit</code>'s <code>AuthService</code> covers the basics you'd expect: create a user with Argon2id-hashed passwords, log in and get back an opaque session token, validate a token back to a user, log out. On top of that, opt-in TOTP two-factor authentication - enroll, confirm with a code from an authenticator app, disable, regenerate recovery codes - plus session invalidation when it matters (disabling 2FA, changing a password).</p><p>Wiring it into FastAPI is a dependency and a cookie:</p><pre><code class="language-python">SESSION_COOKIE = "session_token"

def current_user(request: Request, auth: AuthService = Depends(get_auth_service)) -&gt; User:
    return auth.user_for_token(request.cookies.get(SESSION_COOKIE))
</code></pre><p>Every authenticated route takes <code>user=Depends(current_user)</code>. An invalid or missing token raises an error that a global FastAPI exception handler turns into a 401 - no route has to remember to check auth itself, it's structural.</p><h2 id="why-argon2id-and-why-a-cookie-instead-of-a-jwt">Why Argon2id, and why a cookie instead of a JWT</h2><p>Two choices sit underneath everything above that are easy to gloss past but worth stating deliberately, because both were decisions rather than defaults.</p><p><strong>Password hashing</strong> uses Argon2id specifically, not bcrypt and not a hand-rolled PBKDF2 call. Argon2id is the current OWASP recommendation for password storage - it's memory-hard, which makes it meaningfully more resistant to GPU-accelerated cracking attempts than bcrypt if a password database ever did leak, and "memory-hard" was a property worth having even for a database with exactly one row in its users table. The actual hashing call is one line via <code>sessionkit</code>; the decision that mattered was picking a library that defaults to a modern algorithm rather than one that defaults to whatever was best practice a decade ago and never revisited.</p><p><strong>Sessions are opaque server-side tokens in an <code>httponly</code> cookie, not a JWT.</strong> A JWT would let the API validate a request without a database lookup - the whole appeal of JWTs is statelessness - but that statelessness is exactly what makes revocation hard: an issued JWT is valid until it expires, full stop, unless you build a denylist, at which point you've recreated server-side session state anyway just to get revocation back. Password changes and 2FA disables in this app need to invalidate sessions <em>immediately</em>, not "whenever the token happens to expire," so an opaque token backed by a real, deletable row in a sessions table was the right trade from the start - one extra database lookup per authenticated request, in exchange for revocation that actually revokes something the moment it's asked to.</p><h2 id="two-factor-the-parts-worth-calling-out">Two-factor, the parts worth calling out</h2><p>The TOTP flow is standard - enroll gets you a secret and a <code>otpauth://</code> URI to put in an authenticator app, confirm proves you actually set it up correctly by requiring a valid code before it's turned on, and from then on login requires that code too:</p><pre><code class="language-python">@router.post("/2fa/enroll", response_model=TotpEnrollmentOut)
def enroll_totp(user=Depends(current_user), auth: AuthService = Depends(get_auth_service)):
    enrollment = auth.start_totp_enrollment(user.id)
    return TotpEnrollmentOut(secret=enrollment.secret, uri=enrollment.uri)
</code></pre><p>The one design choice worth flagging: enrolling doesn't invalidate your current session, but a fresh <code>login</code> call afterward requires the OTP. That's deliberate - you're mid-setup, still authenticated, looking at a QR code; forcing a re-login at that exact moment would be actively hostile UX. The requirement only bites the <em>next</em> time you authenticate from scratch, which is exactly when it should.</p><h2 id="recovery-codes-and-the-one-time-display-problem">Recovery codes, and the one-time-display problem</h2><p>Confirming TOTP enrollment returns a batch of recovery codes - one-use backup codes for getting back in if I lose my phone or the authenticator app gets uninstalled. These get shown exactly once, in the response to the confirm call, and never again:</p><pre><code class="language-python">@router.post("/2fa/confirm")
def confirm_totp(payload: ConfirmTotpRequest, user=Depends(current_user), auth=Depends(get_auth_service)):
    recovery_codes = auth.confirm_totp(user.id, payload.otp)
    return {"recovery_codes": recovery_codes}
</code></pre><p><code>sessionkit</code> stores only hashes of these codes, the same way it stores password hashes - never the codes themselves - which means there's no "view your recovery codes again" feature to build even if I wanted one, because the plaintext genuinely doesn't exist anywhere after that one response. The frontend's job here is entirely about not squandering that single moment: the confirm screen shows the codes in a fixed-width list with a clear "save these somewhere safe, you won't see them again" warning, and nothing else on that screen competes for attention. Get this UX wrong - bury the codes below the fold, let the success state auto-dismiss after a few seconds - and the result is a support burden of exactly one user, me, locked out with no way back in except deleting the 2FA enrollment from the database by hand.</p><h2 id="splitting-settings-into-sections-and-hitting-a-real-gap">Splitting settings into sections, and hitting a real gap</h2><p>The settings page originally had two-factor controls bolted onto the Home page dashboard, which made no sense once Home became a proper stats page - security settings don't belong wedged between spending charts. Splitting it into a real Settings page with three sections - <strong>User account</strong>, <strong>Password</strong>, <strong>Two-factor authentication</strong> - seemed straightforward, right up until I went to build the first one.</p><p><code>sessionkit</code>'s <code>User</code> model has exactly five fields: <code>email</code>, <code>name</code>, <code>id</code>, <code>created_at</code>, <code>totp_enabled</code>. There is no <code>update_user</code> method anywhere in the library - not on <code>AuthService</code>, not on the underlying store protocol. Name and email get set once, at account creation, and that's it. I own the library, so I could add that capability - but that's a change to a separate package with its own version to bump, not something to reach for mid-way through a settings page in a different repo. I'd also, briefly, considered writing directly to <code>sessionkit</code>'s SQLite table from this app instead - which would have worked, right up until the next time I changed that table's schema in the library and silently broke it from the outside without either project's tests catching it. Reaching around a library's own storage layer like that trades a real, contained problem (no update method) for a much worse one (an undocumented, unversioned coupling between two codebases that only I would ever remember exists).</p><p>So: the <strong>User account</strong> section is read-only. Name and email, displayed, not editable, with a short comment in the code explaining why rather than a silently missing feature someone might "fix" without knowing the constraint. Honest and unglamorous, and a much better trade than either of the alternatives.</p><h2 id="changing-a-password-correctly-with-a-gap-of-its-own">Changing a password, correctly, with a gap of its own</h2><p><code>set_password</code> exists and works, but has an interesting asymmetry compared to the rest of the library:</p><pre><code class="language-python">def set_password(self, user_id: str, password: str) -&gt; None:
</code></pre><p>No <code>current_password</code> parameter. Compare that to <code>disable_totp</code>, which takes one and checks it internally before disabling anything. For password changes there's no equivalent built-in check - call <code>set_password</code> with a valid <code>user_id</code> and it just changes the password, full stop. That's a reasonable design for a library that assumes callers already know what they're doing (an admin CLI, say), but a "change password" form on a settings page absolutely should confirm you know the <em>current</em> password first - protection against someone getting to your unlocked laptop, not against someone who's already got your password.</p><p>Rather than reach into the library's private internals to add that check myself, I reused the one thing already public and already does exactly that verification: <code>login()</code>.</p><pre><code class="language-python">@router.post("/password")
def change_password(
    payload: ChangePasswordRequest,
    response: Response,
    user=Depends(current_user),
    auth: AuthService = Depends(get_auth_service),
):
    # set_password() has no built-in current-password check - login() is
    # reused here to verify it, which also gets 2FA-aware handling for
    # free. The session login() creates is never handed to the client.
    try:
        auth.login(user.email, payload.current_password, payload.otp)
    except OtpRequired:
        return JSONResponse(status_code=401, content={"otp_required": True})
    except AuthenticationError:
        return JSONResponse(status_code=401, content={"detail": "Current password is incorrect"})

    auth.set_password(user.id, payload.new_password)
    response.delete_cookie(SESSION_COOKIE)
    return {"status": "ok"}
</code></pre><p>Calling <code>login()</code> and just discarding the session it issues is a slightly unusual pattern, but it buys two things for free: proper current-password verification using code that's already tested, and 2FA-aware handling for accounts that have it enabled - if you've got TOTP on, this form now requires a code too, exactly like logging in would, without writing any of that logic myself.</p><p>The other consequence is one I had to design the <em>frontend</em> around, not just the backend: <code>set_password</code> invalidates every session for that user, including the one that just made this very request. Change your password and you're logged out - not as a bug, as correct behaviour, but the settings page needs to know that a "successful" password change response actually means "now show the login screen," not "now show a success toast and keep going."</p><h2 id="the-shape-this-settled-into">The shape this settled into</h2><p>Three sections, three different levels of "how much can this actually do": account details you can see but not edit, a password you can change with proper verification (and a session that ends the moment you do), and 2FA that's fully self-service. None of that needed inventing new infrastructure - it needed being honest about what the underlying library actually supports, and building around the gap instead of papering over it with something fragile.</p><p>Auth handles who's allowed to see the data. Next post is about the data itself getting stale, and what "keeping it fresh" actually took once a sync could fail halfway through.</p><hr><p>Previous: <a href="https://ghost.atathome.me/building-the-frontend/">← Building the frontend</a> · Next: <a href="https://ghost.atathome.me/keeping-data-fresh/">Keeping data fresh →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Central login service: Shipping it - Jenkins, uv and a Debian container - Part 2]]></title><description><![CDATA[~25 min read

Part 1 ended with a login service that passed its tests and ran on my laptop. That's the easy half. A login service that isn't reachable from the other machines in the house isn't a login service, and "reachable" brought a pile of small decisions and an unglamorous run of commits with messages like ci: add uv.lock, fix python missmatch and fix deploy script.

This post is about all of that: the deployment target, the Jenkins pipeline, moving the build to uv, the rsync --delete that]]></description><link>https://brightbot.co.uk/identity-system-shipping-it-jenkins-uv-and-a-container/</link><guid isPermaLink="false">Ghost__Post__6ada2fa31df6faba86556a7d</guid><category><![CDATA[Building Identity System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sun, 25 Oct 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1762163516269-3c143e04175c?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDN8fHNlcnZlcnxlbnwwfHx8fDE3OTI2ODQwNTV8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1762163516269-3c143e04175c?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDN8fHNlcnZlcnxlbnwwfHx8fDE3OTI2ODQwNTV8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Central login service: Shipping it - Jenkins, uv and a Debian container - Part 2"/><p><em>~25 min read</em></p><p><a href="https://ghost.atathome.me/identity-system-why-a-central-login-service/">Part 1</a> ended with a login service that passed its tests and ran on my laptop. That's the easy half. A login service that isn't reachable from the other machines in the house isn't a login service, and "reachable" brought a pile of small decisions and an unglamorous run of commits with messages like <code>ci: add uv.lock</code>, <code>fix python missmatch</code> and <code>fix deploy script</code>.</p><p>This post is about all of that: the deployment target, the Jenkins pipeline, moving the build to <code>uv</code>, the <code>rsync --delete</code> that nearly ate my accounts database, and a deploy bug where the new code was copied across and then silently never ran. None of it is clever. All of it is the sort of thing that eats time the first time you meet it, so I'd rather write it down.</p><h2 id="the-shape-of-the-deployment">The shape of the deployment</h2><p>Everything I self-host runs in small Proxmox LXC containers, one service to a container where practical. <code>identity-system</code> gets a Debian 13 ("trixie") container with:</p><ul><li>the Python backend running under <code>systemd</code>, listening on a local port;</li><li><code>nginx</code> in front of it, terminating the public hostname;</li><li>the application checked out under <code>/opt/identity-system</code>, with a virtual environment alongside it.</li></ul><p>There is deliberately no Docker image. The container <em>is</em> the isolation boundary, and layering another one on top would add a build step, a registry or a local image cache, and a second place for things to go wrong, in return for isolation I already have. The repository's <code>deploy/</code> directory holds exactly four files:</p><pre><code>deploy/
  deploy.sh                    # runs on the Jenkins agent
  remote-setup.sh              # runs on the container, over SSH
  identity-system-api.service  # systemd unit template
  nginx-identity-system.conf   # nginx site template
</code></pre><p>The flow is: Jenkins builds and tests, then <code>deploy.sh</code> copies the checkout to the container with <code>rsync</code> and runs <code>remote-setup.sh</code> there. There's no artifact registry, no image, no orchestrator. I'm describing the simplest thing that could possibly work, and for a one-instance home service it's enough.</p><h2 id="the-jenkinsfile-and-how-it-got-to-uv">The Jenkinsfile, and how it got to <code>uv</code></h2><p>The first Jenkinsfile was copied from the pipeline of an older project, and its first draft of the Test stage did what most Python CI does: create a virtual environment, <code>pip install -e ".[dev]"</code>, run <code>pytest</code>.</p><pre><code class="language-groovy">stage('Test') {
    steps {
        sh '''
            python3 -m venv .venv
            .venv/bin/pip install --no-cache-dir -e ".[dev]"
            mkdir -p reports
            .venv/bin/pytest --junitxml=reports/junit.xml
        '''
    }
}
</code></pre><p>That works until the Python on the CI agent isn't the Python you think it is. This project requires Python 3.13 (it says so in <code>requires-python</code>), and I'd bumped to 3.13 deliberately in a <code>feat: upgrade to python 3.13</code> commit that added a <code>.python-version</code> file. The CI agent's system Python was something older.</p><h3 id="failing-loudly-instead-of-testing-the-wrong-thing">Failing loudly instead of testing the wrong thing</h3><p>My first response was a guard in the Jenkinsfile:</p><pre><code class="language-groovy">python_version="$(python3 -c 'import platform; print(platform.python_version())')"
case "$python_version" in
    3.13.*) ;;
    *) echo "Jenkins agent python3 is $python_version, not 3.13.x" &gt;&amp;2; exit 1 ;;
esac
</code></pre><p>The idea is sound and I still like it as a principle: if an assumption about the environment matters, check it and fail with a message that names the problem, rather than quietly testing against the wrong interpreter and getting confusing results (or worse, passing). A matching check went into <code>remote-setup.sh</code> for the production side, because the deploy target relies on Debian trixie's <em>system</em> <code>python3</code> being 3.13:</p><pre><code class="language-bash">PYTHON_VERSION="$(python3 -c 'import platform; print(platform.python_version())')"
if [[ "${PYTHON_VERSION}" != 3.13.* ]]; then
    echo "System python3 is ${PYTHON_VERSION}, not 3.13.x - this script" &gt;&amp;2
    echo "assumes a Debian 13 (trixie) target where python3 is already" &gt;&amp;2
    echo "3.13. Install python3.13 yourself first (or move to trixie)." &gt;&amp;2
    exit 1
fi
</code></pre><p>The very next commit, <code>fix python missmatch</code>, changed <code>python3</code> to <code>python</code> in the Jenkins check, because on that agent the <code>python3</code> binary and the <code>python</code> the rest of the toolchain used weren't the same interpreter. I then replaced the whole approach about half an hour later, which brings me to <code>uv</code>.</p><h3 id="letting-uv-own-the-toolchain">Letting uv own the toolchain</h3><p>Other projects in my fleet already use <a href="https://docs.astral.sh/uv/">uv</a>, and the thing that makes it a good fit for CI is that it can <em>download the right Python itself</em>. If the agent doesn't have 3.13, <code>uv</code> fetches it, based on <code>.python-version</code> and <code>requires-python</code>. That makes my hand-rolled version check redundant, so the commit <code>ci: convert to UV</code> deleted it:</p><pre><code class="language-groovy">stage('Install uv') {
    steps {
        sh 'curl -LsSf https://astral.sh/uv/install.sh | sh'
    }
}
...
stage('Test') {
    steps {
        sh '''
            mkdir -p reports
            uv sync --locked --extra dev
            uv run pytest --junitxml=reports/junit.xml
        '''
    }
}
</code></pre><p>Three details here are easy to get wrong:</p><p><strong>Bootstrapping uv inline.</strong> Rather than assuming the agent has it installed, the pipeline has an <code>Install uv</code> stage that runs the official installer. The environment block adds <code>${env.HOME}/.local/bin</code> to <code>PATH</code> so the freshly installed binary is found by later stages. It's a few seconds per build in exchange for not having a pre-requisite on the agent that I'd forget about until the agent was rebuilt.</p><p><strong><code>--locked</code>.</strong> <code>uv sync --locked</code> fails if <code>pyproject.toml</code> and <code>uv.lock</code> have drifted apart, instead of quietly re-resolving dependencies. That's the entire point of a lockfile in CI: the build tests exactly what you committed. The companion commit <code>ci: add uv.lock</code> came right after the conversion commit, with the message "CI would fail without it": the Jenkinsfile was asking for a strict lockfile that hadn't been committed yet.</p><p><strong><code>--extra dev</code>.</strong> In the uv-native sibling projects, the test dependencies live in a <code>[dependency-groups]</code> table, which a bare <code>uv sync</code> picks up by default. Here they're a plain <code>[project.optional-dependencies]</code> extra, because I wanted the README's <code>pip install -e ".[dev]"</code> to keep working for anyone not using uv. The trade-off is that <code>uv sync</code> doesn't install an extra unless you ask for it, so the pipeline spells out <code>--extra dev</code>. Omitting it produces a perfectly healthy-looking sync followed by <code>pytest</code> not being installed.</p><p>The Jenkinsfile's own header comment records one more asymmetry that I'd otherwise forget: <code>remote-setup.sh</code> still installs the backend with plain <code>pip</code> into a plain virtual environment on the container, not with <code>uv</code>. So <code>uv.lock</code> pins what <strong>CI tests against</strong>, not what's <strong>deployed</strong>. That's a real gap between "tested" and "shipped", and I chose to leave it as is for now because the deploy-time install resolves the same pinned <code>sessionkit</code> tag, and because switching the container to <code>uv</code> would mean one more tool to install and keep current there. It's the sort of thing worth writing in a comment so a future reader doesn't assume the lockfile is the whole story.</p><h3 id="a-multibranch-pipeline-and-a-guarded-deploy">A Multibranch pipeline and a guarded Deploy</h3><p>The pipeline is configured as a Multibranch Pipeline job, so <code>env.BRANCH_NAME</code> is populated and the Deploy stage can be guarded:</p><pre><code class="language-groovy">stage('Deploy') {
    when {
        branch 'main'
    }
    steps {
        sh 'chmod +x deploy/deploy.sh &amp;&amp; ./deploy/deploy.sh'
    }
}
</code></pre><p>Feature branches run Test and stop. Only <code>main</code> deploys. Two options in the <code>options {}</code> block are worth keeping on every pipeline:</p><pre><code class="language-groovy">options {
    timestamps()
    disableConcurrentBuilds()
    buildDiscarder(logRotator(numToKeepStr: '20'))
}
</code></pre><p><code>disableConcurrentBuilds()</code> matters more than it looks, because two overlapping deploys of the same service would race on the same directory. And the post section runs <code>cleanWs()</code> in an <code>always</code> block so the workspace, which now contains a checkout and a virtual environment, doesn't pile up on the agent.</p><p>The deploy target itself is a handful of environment variables:</p><pre><code class="language-groovy">environment {
    PATH = "${env.HOME}/.local/bin:${env.PATH}"

    DEPLOY_HOST        = '&lt;container address&gt;'
    DEPLOY_USER        = 'root'
    BACKEND_DIR        = '/opt/identity-system'
    BACKEND_SERVICE    = 'identity-system-api'
}
</code></pre><p>One of the earliest commits (<code>feat: fix identity IP</code>) is entirely a single changed address on that host line. The pipeline was copied from a neighbouring project, and a copied pipeline carries its old target with it. If a deploy "succeeds" but nothing changes, check where it went before anything else.</p><p>There's no Jenkins credential involved in the deploy: the agent is assumed to already have working SSH key access to the container. That's a one-time setup the scripts can't do for you, and <code>deploy.sh</code>'s header says so in plain words. I prefer that to a credential plugin for a single home network, but it does mean the agent's SSH key is the keys to the kingdom, and I treat it accordingly.</p><h2 id="deploysh-the-rsync-that-wants-to-delete-things"><code>deploy.sh</code>: the rsync that wants to delete things</h2><p><code>deploy.sh</code> runs on the <em>agent</em>, not the container. It does three things: make sure <code>rsync</code> exists on the target, push the checkout, and run the remote setup script.</p><pre><code class="language-bash">rsync -az --delete \
    -e "ssh ${SSH_OPTS[*]}" \
    --exclude '.git/' \
    --exclude '.venv/' \
    --exclude '__pycache__/' \
    --exclude '.pytest_cache/' \
    --exclude 'reports/' \
    --exclude 'data/' \
    --exclude '.env' \
    "${REPO_ROOT}/" "${SSH_TARGET}:${BACKEND_DIR}/"
</code></pre><p><code>--delete</code> makes the destination match the source exactly: anything on the container under <code>/opt/identity-system</code> that isn't in the checkout gets removed. That's the right behaviour for source code (a file I deleted from the repo shouldn't linger and keep being imported), and it's <em>exactly</em> the wrong behaviour for anything the running service creates. The service creates two kinds of thing:</p><ol><li>The SQLite database containing every account, session and two-factor secret.</li><li>Its <code>.env</code>, which holds the deployment's real configuration and which is intentionally never in the repository.</li></ol><p>Hence the two excludes that matter, <code>data/</code> and <code>.env</code>. The design is that the database lives in <code>/opt/identity-system/data/auth.db</code>, the <code>data/</code> directory is excluded from the sweep, and so the database survives every deploy.</p><p>Notice the <code>set -euo pipefail</code> at the top of the script. With <code>-e</code> a failing <code>rsync</code> aborts the deploy rather than continuing on to restart a half-updated service; <code>-u</code> makes an unset variable an error (the script also uses <code>: "${DEPLOY_HOST:?DEPLOY_HOST must be set}"</code> for each required variable, which gives a readable message naming exactly which one is missing); <code>pipefail</code> makes failures inside pipelines count.</p><h3 id="the-trap-a-default-that-deletes-your-database">The trap: a default that deletes your database</h3><p>Here is the trap behind the innocuously titled <code>fix deploy script</code> commit.</p><p><code>data/</code> is only protected if the database actually <em>lives</em> in <code>data/</code>. And the <code>.env.example</code> I'd written for local development says:</p><pre><code>IDENTITY_SYSTEM_DB=./auth.db
</code></pre><p>That's a sensible local default: a file in the current directory. But the systemd unit sets <code>WorkingDirectory=/opt/identity-system</code>, so on the container that relative path resolves to <code>/opt/identity-system/auth.db</code>, which is <strong>outside <code>data/</code></strong>. If I'd copied <code>.env.example</code> to the container unedited, the service would have happily created its database in the one place the next deploy's <code>rsync --delete</code> treats as garbage. Everything would work perfectly until the second deploy, at which point every account would vanish.</p><p>It's a nasty class of bug because there's no error at any point. It takes a deploy <em>succeeding</em> to destroy the data.</p><p>The fix was belt and braces, applied in three places:</p><p><strong>1. Say so in <code>.env.example</code>.</strong> The comment above the variable now states that when deployed it MUST be an absolute path inside <code>data/</code>, and explains precisely why.</p><p><strong>2. A second safety net in rsync.</strong></p><pre><code class="language-bash">    --exclude '*.db' \
    --exclude '*.db-*' \
</code></pre><p>Those patterns match a SQLite file anywhere in the tree (and its <code>-wal</code> and <code>-shm</code> sidecar files), so even a database in the wrong place is spared. This is a deliberate overlap: if the first protection is defeated by a typo, the second catches it.</p><p><strong>3. A check in <code>remote-setup.sh</code> that warns loudly.</strong></p><pre><code class="language-bash">db_path="$(grep -E '^IDENTITY_SYSTEM_DB=' "${BACKEND_DIR}/.env" | tail -1 | cut -d= -f2-)"
if [[ -n "${db_path}" &amp;&amp; "${db_path}" != "${BACKEND_DIR}/data/"* ]]; then
    echo "WARNING: IDENTITY_SYSTEM_DB in ${BACKEND_DIR}/.env is '${db_path}'," &gt;&amp;2
    echo "not inside ${BACKEND_DIR}/data/ - deploy.sh's rsync --delete will" &gt;&amp;2
    echo "wipe it on the next deploy (only data/, .env, *.db and *.db-* are" &gt;&amp;2
    echo "excluded from that sweep). Move the db file into ${BACKEND_DIR}/data/," &gt;&amp;2
    echo "point IDENTITY_SYSTEM_DB at it there, and restart ${SERVICE_NAME}." &gt;&amp;2
fi
</code></pre><p>It reads the variable out of the deployed <code>.env</code> with <code>grep</code> and <code>tail -1</code> (last assignment wins, as it would if the file were sourced), strips the name with <code>cut -d= -f2-</code>, and compares against the expected prefix. Two details: <code>cut -f2-</code> rather than <code>-f2</code> so a value containing an <code>=</code> isn't truncated, and the whole check is only a <em>warning</em>. It deliberately doesn't abort, because the service might legitimately be mid-migration and a hard failure here would block a deploy that fixes it.</p><p>The project notes carry a line telling any future version of me not to remove that check. Checks like this look like noise right up until the day they matter.</p><h2 id="remote-setupsh-idempotent-by-construction"><code>remote-setup.sh</code>: idempotent by construction</h2><p>The script that runs on the container is written so that running it twice does the same thing as running it once. That matters because it runs on <strong>every deploy</strong>, not just the first. Walking through it:</p><pre><code class="language-bash">echo "Installing required packages (${REQUIRED_PACKAGES[*]})..."
apt-get update
apt-get install -y --no-install-recommends "${REQUIRED_PACKAGES[@]}"
</code></pre><p><code>apt-get install</code> of something already installed is a no-op, and <code>--no-install-recommends</code> keeps the container lean. The package list is <code>python3-venv python3-pip nginx curl rsync</code>.</p><pre><code class="language-bash">if ! id -u "${SERVICE_USER}" &gt;/dev/null 2&gt;&amp;1; then
    useradd --system --no-create-home --shell /usr/sbin/nologin "${SERVICE_USER}"
fi
</code></pre><p>The "create the user if it doesn't exist" guard is the idiom for idempotence: test, then act. The same pattern appears when linking the nginx site:</p><pre><code class="language-bash">if [[ ! -e "/etc/nginx/sites-enabled/identity-system" ]]; then
    ln -s "/etc/nginx/sites-available/identity-system" "/etc/nginx/sites-enabled/identity-system"
fi
</code></pre><p>The venv is built only if missing (<code>if [[ ! -d "${BACKEND_DIR}/.venv" ]]</code>) and then the package is installed into it. Then the unit and nginx config are installed. Notice how:</p><pre><code class="language-bash">sed "s|__BACKEND_DIR__|${BACKEND_DIR}|g" "${SCRIPT_DIR}/${SERVICE_NAME}.service" \
    | install -m 644 /dev/stdin "/etc/systemd/system/${SERVICE_NAME}.service"
</code></pre><p>The unit file in the repository contains a literal placeholder, <code>__BACKEND_DIR__</code>, and <code>sed</code> substitutes the real path as it's installed (using <code>|</code> as the sed delimiter because the replacement contains slashes). <code>install -m 644 /dev/stdin</code> writes the result with the right permissions in one step. The same trick is used for the nginx config. Keeping templates in the repository and substituting at install time means there's exactly one place to edit them. A comment at the top of the nginx file says as much, because the other way to lose an afternoon is hand-editing the file on the container (for instance, letting <code>certbot</code> modify it in place) and having the next deploy cheerfully overwrite your change.</p><p>Finally:</p><pre><code class="language-bash">systemctl daemon-reload
systemctl enable --now "${SERVICE_NAME}"
systemctl restart "${SERVICE_NAME}"

nginx -t
systemctl reload nginx
</code></pre><p><code>daemon-reload</code> makes systemd re-read the unit; <code>enable --now</code> is a no-op if it's already enabled and running; <code>restart</code> ensures new code is loaded; <code>nginx -t</code> <strong>tests the configuration before reloading</strong>, so a typo in the config aborts the script (thanks to <code>set -e</code>) instead of taking the proxy down.</p><h3 id="the-unit-file">The unit file</h3><pre><code class="language-ini">[Service]
Type=simple
User=identity-system
Group=identity-system
WorkingDirectory=__BACKEND_DIR__
EnvironmentFile=__BACKEND_DIR__/.env
ExecStart=__BACKEND_DIR__/.venv/bin/uvicorn identity_system.main:app --host 127.0.0.1 --port 8000
Restart=on-failure
RestartSec=2
</code></pre><p><code>EnvironmentFile</code> is how the service gets its configuration without it ever being in the repository. <code>Restart=on-failure</code> with a two-second delay means a crash comes back on its own without hammering a hard failure in a tight loop. And <code>--host 127.0.0.1</code> binds only to the loopback interface, so the application port isn't reachable except via nginx on the same machine.</p><p>Note <code>User=identity-system</code>. The service runs as a dedicated, unprivileged system account, not root. It only ever needs to read and write its own database and signing key under <code>data/</code>, so that is all it is given: if the process is ever compromised, the attacker is confined to what that one user can touch rather than owning the container. For the one service in the house that holds everyone's credentials, this matters more than for most.</p><p>The account is created by <code>remote-setup.sh</code> (the <code>useradd --system --no-create-home --shell /usr/sbin/nologin</code> call shown earlier: no home directory and no login shell, so nobody can sign in as it), and the same script makes sure it owns what it must write to:</p><pre><code class="language-bash">SERVICE_USER="identity-system"
...
chown -R "${SERVICE_USER}:${SERVICE_USER}" "${BACKEND_DIR}/data"
chown -R "${SERVICE_USER}:${SERVICE_USER}" "${BACKEND_DIR}/.venv"
</code></pre><p>The <code>data/</code> directory is the one place the service writes, and the virtual environment is chowned so the process can read its own installed packages (the deploy itself still runs as root over SSH, which is why those <code>chown</code> calls have to be explicit after each install). The application code in <code>/opt/identity-system</code> stays root-owned and read-only to the service, so a compromised process can't rewrite the code it's running from.</p><p>One permissions trap to watch for is that the <code>.env</code> file is read by systemd <em>before</em> it drops privileges (<code>EnvironmentFile</code> is loaded by the service manager, not the process), so it can stay root-owned with mode <code>600</code> and the service still gets its settings, without the unprivileged account being able to read the file itself.</p><h2 id="the-nginx-config">The nginx config</h2><p>The first nginx config is short enough to quote entirely:</p><pre><code class="language-nginx">server {
    listen 80;
    listen [::]:80;
    server_name sso.example.com;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
</code></pre><p>It listens on port 80 for IPv4 and IPv6, matches the hostname, and proxies everything to the Python app, passing the original <code>Host</code> and client address along. (In this series I use <code>sso.example.com</code> as the public name; the real one is a different hostname on a private domain, and one of the commits, <code>feat: enable correct server name</code>, is just the swap from the placeholder to the real name.)</p><p>TLS is not terminated in this file. In my setup that happens one layer further out, but the comment in the file is firm that this needs HTTPS in front of it before it's treated as more than a starting point, because the session cookie is <code>Secure</code> by default and every downstream app's forward-auth hook assumes the login service is reachable over HTTPS. Running a login page over plain HTTP isn't a configuration to leave in place.</p><h2 id="the-deploy-that-ran-the-old-code">The deploy that ran the old code</h2><p>The last bug in this post belongs chronologically to the OIDC work in a later part, but it's a deploy bug, so it goes here. It's the most instructive one.</p><p>After shipping a large new feature, the new routes returned <code>404</code>. The deploy had succeeded: Jenkins was green, <code>rsync</code> had copied the new source, the setup script had run, and the service had restarted. And the <em>old</em> code was still serving requests.</p><p>The culprit was this line in <code>remote-setup.sh</code>:</p><pre><code class="language-bash">"${BACKEND_DIR}/.venv/bin/pip" install --no-cache-dir "${BACKEND_DIR}"
</code></pre><p>That installs the project from a local directory. <code>pip</code> reads the version out of the project metadata, sees that version of <code>identity-system</code> is already installed in the venv, concludes there is nothing to do, and skips the install. The source on disk was new, but the <em>installed copy</em> inside the virtual environment (the thing <code>uvicorn</code> actually imports) was the previous build. The package version is bumped by hand, so it hadn't changed.</p><p>The fix is one flag:</p><pre><code class="language-bash">"${BACKEND_DIR}/.venv/bin/pip" install --no-cache-dir --force-reinstall "${BACKEND_DIR}"
</code></pre><p><code>--force-reinstall</code> makes <code>pip</code> reinstall regardless of the version it finds. It's a bit heavy-handed, as it also reinstalls dependencies, but it removes a whole category of "I deployed it and nothing changed" from the table. The commit message called it out, and the comment in the script says it "bit the OIDC rollout for real (routes 404'd post-deploy because the venv was still serving the pre-OIDC build)".</p><p>The general lesson is about where the truth lives. When a deploy and a runtime disagree, the first question isn't "what did I deploy?" but "what is the process <em>actually</em> running?". Here those were two different directories that looked like one.</p><h2 id="what-the-pipeline-looks-like-now">What the pipeline looks like now</h2><p>Put together, a push to <code>main</code> does this:</p><ol><li><strong>Prereq / Install uv / Checkout</strong>: confirm the Node version manager is set up (the frontend arrives in the next part), bootstrap <code>uv</code>, check out the branch.</li><li><strong>Test</strong>: <code>uv sync --locked --extra dev</code> then <code>pytest</code>, with the JUnit XML published so Jenkins shows per-test results.</li><li><strong>Deploy</strong> (main only): <code>rsync</code> the checkout to the container, then run <code>remote-setup.sh</code> there, which installs packages, rebuilds the install, re-templates the systemd and nginx files, restarts the service, tests and reloads nginx.</li></ol><p>The two things I'd change if I did it again are small: install with <code>uv</code> on the container so what's tested is what's shipped; and add a post-deploy smoke test, a <code>curl</code> of <code>/verify</code> expecting a <code>401</code>, so "deployed but broken" fails the build rather than being discovered by whichever app I next try to open. The second would have caught the stale-venv problem within seconds.</p><p>What I wouldn't change is the habit this part is really about: every time something went wrong, the fix was paired with a note, either a comment at the failure site, a startup warning, or a line in the project notes. Most of the traps in this post are the sort that stay invisible until you hit them. Writing them down where the next change will see them is cheap.</p><p>The service is now live and reachable, which exposes the next limitation: its only interface is a small inline-HTML login page, and I wanted somewhere to see who had accounts. The next part replaces the HTML with a real frontend.</p><hr><p>Previous: <a href="https://ghost.atathome.me/identity-system-why-a-central-login-service/">← One place to type a password</a> · Next: <a href="https://ghost.atathome.me/identity-system-an-admin-page-and-a-proper-frontend/">An admin page and a proper frontend →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: Building the frontend: React, routing, and a design system - Part 5]]></title><description><![CDATA[~10 min read

For a while, the frontend was one component: log in, see a table of transactions, link a bank from a text input. That was fine for checking the backend actually worked, but it wasn't a tool I wanted to open every day. This post covers turning that single page into a proper multi-page app - Home, Accounts, Transactions, Settings - with real navigation and a design system underneath it, instead of default browser styling on a scattering of <div>s. It's the work of one commit (Add rou]]></description><link>https://brightbot.co.uk/building-the-frontend/</link><guid isPermaLink="false">Ghost__Post__6ad488c31df6faba86556994</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sun, 25 Oct 2026 09:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1467232004584-a241de8bcf5d?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fFdlYnNpdGV8ZW58MHx8fHwxNzkyMzE3MTE0fDA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1467232004584-a241de8bcf5d?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fFdlYnNpdGV8ZW58MHx8fHwxNzkyMzE3MTE0fDA&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: Building the frontend: React, routing, and a design system - Part 5"/><p><em>~10 min read</em></p><p>For a while, the frontend was one component: log in, see a table of transactions, link a bank from a text input. That was fine for checking the backend actually worked, but it wasn't a tool I wanted to open every day. This post covers turning that single page into a proper multi-page app - Home, Accounts, Transactions, Settings - with real navigation and a design system underneath it, instead of default browser styling on a scattering of <code>&lt;div&gt;</code>s. It's the work of one commit (<code>Add routed pages (Home, Accounts, Transactions, Settings) with a new design system</code>), with a couple of details that only landed in the commits right after it flagged as such below - most importantly, the Home page's numbers at this point were hardcoded demo values.</p><h2 id="why-routing-first">Why routing first</h2><p>The single-page version had grown a login gate, a bank-linking form, a 2FA settings block, and a transactions table all stacked vertically on one screen. Every feature added made that page longer and the mental model fuzzier - "where do I go to link a bank" was a scroll position, not a place. Before touching any visual design, the first change was structural: <code>react-router-dom</code>, four real routes, and a persistent nav bar.</p><pre><code class="language-tsx">&lt;BrowserRouter&gt;
  &lt;NavBar user={user} onLogout={handleLogout} /&gt;
  &lt;main className="app-main"&gt;
    &lt;Routes&gt;
      &lt;Route path="/" element={&lt;Home /&gt;} /&gt;
      &lt;Route path="/accounts" element={&lt;Accounts /&gt;} /&gt;
      &lt;Route path="/transactions" element={&lt;Transactions /&gt;} /&gt;
      &lt;Route path="/settings" element={&lt;Settings user={user} onLogout={handleLogout} /&gt;} /&gt;
      &lt;Route path="*" element={&lt;Navigate to="/" replace /&gt;} /&gt;
    &lt;/Routes&gt;
  &lt;/main&gt;
&lt;/BrowserRouter&gt;
</code></pre><p>Each page fetches only what it needs - <code>Transactions</code> doesn't fetch provider metadata, <code>Accounts</code> doesn't fetch transaction summaries - which sounds obvious in hindsight but wasn't true of the single-page version, where everything loaded on mount whether the page ended up using it or not. Splitting by route made "what data does this screen actually need" a question with an obvious answer for the first time.</p><h2 id="a-design-system-means-picking-defaults-once">A design system means picking defaults once</h2><p>"Design system" is a big phrase for what this actually was: a handful of CSS custom properties, defined once, referenced everywhere, so that "what colour is a card border" or "how much padding does a button get" was a decision made a single time instead of re-litigated in every component.</p><pre><code class="language-css">:root {
  --surface: #fcfcfb;
  --surface-page: #f9f9f7;
  --text-primary: #0b0b0b;
  --text-secondary: #52514e;
  --border: rgba(11, 11, 11, 0.1);
  --accent: #2a78d6;
  --success: #006300;
  --danger: #d03b3b;
  --radius: 10px;
  --shadow: 0 1px 2px rgba(11, 11, 11, 0.06), 0 1px 3px rgba(11, 11, 11, 0.08);
}

@media (prefers-color-scheme: dark) {
  :root {
    --surface: #1a1a19;
    --surface-page: #0d0d0d;
    --text-primary: #ffffff;
    /* ...matching dark values for every token above */
  }
}
</code></pre><p>Every card, button, and input references these tokens rather than a literal colour, so dark mode is a second <code>@media</code> block defining the same token names against a dark surface - not a parallel set of dark-mode class names sprinkled through every component. <code>prefers-color-scheme</code> picks it up automatically from the OS; I've never had to add a manual toggle, and haven't needed one for a single-user tool I mostly look at on my own devices.</p><p>A <code>.card</code> class, a <code>.btn</code>/<code>.btn-primary</code>/<code>.btn-danger</code> set, and a handful of layout primitives (<code>.stat-grid</code>, <code>.account-list</code>, <code>.modal-backdrop</code>) cover essentially the entire visual surface of the app. New features almost never need new CSS from scratch - the unlink confirmation modal added later reused the existing <code>.card</code> shadow and border-radius tokens and just needed a backdrop and a couple of layout rules on top.</p><h2 id="choosing-chart-colours-properly-not-by-eye">Choosing chart colours properly, not by eye</h2><p>The one place this app does anything chart-like is the "spending by category" breakdown on the Home page - a horizontal bar per category. It'd be easy to grab five colours that look nice together and move on, but colour choice for data visualisation has a right-and-wrong dimension that's easy to get wrong without checking: some colour pairs are genuinely hard to tell apart for colourblind readers, and it's not something you can reliably eyeball.</p><p>I used a validated categorical palette - eight hues, ordered specifically so that <em>adjacent</em> colours in that order clear a minimum perceptual distance under colour-vision-deficiency simulation, not just to normal vision:</p><pre><code class="language-css">--series-1: #2a78d6; /* blue */
--series-2: #eb6834; /* orange */
--series-3: #1baf7a; /* aqua */
--series-4: #eda100; /* yellow */
--series-5: #e87ba4; /* magenta */
</code></pre><p>For five categories that's comfortably inside the "safe to distinguish" range for this ordering. (At this commit those five categories were a <code>SPEND_BY_CATEGORY</code> constant in <code>Home.tsx</code>, under a "Demo data shown below" banner - the chart was real, the numbers weren't. It stayed that way until <a href="https://ghost.atathome.me/rule-based-categorisation/">categorisation</a> gave it something to chart, at which point the palette had to grow past five hues.) Each bar also gets a direct text label (<code>Bills</code>, <code>Groceries</code>, ...) rather than relying on a separate colour-key legend - with only five categories and each one labelled right next to its bar, a legend would just be duplicating information already on screen.</p><h2 id="testing-components-without-a-browser">Testing components without a browser</h2><p>Every page and most components got a Vitest + Testing Library test alongside it, and the pattern that made this worth doing rather than skipping was keeping the fetch mocking cheap. A typical test stubs <code>global.fetch</code> to return canned JSON for whatever endpoint the component under test calls, renders it, and asserts on what a user would actually see - text on screen, a button's disabled state, an option in a dropdown - rather than reaching into component internals:</p><pre><code class="language-tsx">function stubFetch(summary: unknown, accounts: unknown = []) {
  vi.stubGlobal('fetch', vi.fn(async (input) =&gt; {
    const url = input.toString()
    const body = url.includes('/accounts') ? accounts : summary
    return { ok: true, json: async () =&gt; body } as Response
  }))
}
</code></pre><p>That one helper, varied slightly per test file, covered loading states (never resolve the promise, assert on a placeholder), success states (resolve with realistic data, assert on the rendered numbers), and error states (resolve with <code>ok: false</code>, assert an error message appears) without needing a real backend running or a heavier end-to-end test tool. The delta-polarity logic mentioned below got exactly this treatment once the tiles showed real numbers (<code>Home.test.tsx</code> arrived shortly after): a test asserting spending-up renders red and income-up renders green, which is the kind of thing that's easy to silently invert while refactoring and would otherwise only get noticed by happening to have both numbers move in the same direction on the same day.</p><h2 id="stat-tiles-and-getting-good-and-bad-the-right-way-round">Stat tiles, and getting "good" and "bad" the right way round</h2><p>The Home page's headline numbers - total balance, income this month, spending this month, accounts linked - are stat tiles: a label, a value, and optionally a delta against last month with an up or down arrow. The subtlety here isn't the visual design, it's that <strong>"up" doesn't always mean "good."</strong> Income going up is good, shown in green. Spending going up is <em>bad</em> - it should be red, even though the number is also going up.</p><pre><code class="language-tsx">const isGood = stat.invertDelta ? stat.delta &lt;= 0 : stat.delta &gt;= 0
</code></pre><p>I'll be honest that the first version of this got it wrong: in the first version the demo tiles coloured any positive delta green and any negative one red (<code>stat.delta &gt;= 0 ? 'is-up' : 'is-down'</code>), which made the demo's <em>falling</em> spending look bad. The <code>invertDelta</code> flag arrived in a follow-up commit, when the tiles started showing real numbers and the mistake would have started to matter.</p><p><code>invertDelta</code> flips which direction of change reads as good for a given stat, decoupling the arrow's direction (which always matches the actual sign of the change) from the colour (which reflects whether that change is welcome). Missing this is an easy mistake to make and an easy one to not notice you've made - a dashboard that shows increased spending in the same reassuring green as increased income will <em>look</em> fine and just be quietly wrong every time you glance at it.</p><h2 id="the-login-screen-is-the-one-page-that-had-to-feel-trustworthy">The login screen is the one page that had to feel trustworthy</h2><p>Every other page in the app assumes you're already in. The login screen is the one place a first impression is actually doing work - it's the first thing anyone sees, including me, every single day - and it's the one page where "looks like a real product, not a half-finished side project" felt like it mattered rather than being pure vanity. That mostly came down to restraint rather than extra effort: a centred card on a plain background, the same <code>--surface</code>/<code>--border</code>/<code>--shadow</code> tokens every other card in the app uses (so it doesn't look like a different app bolted onto the front of this one), one clear call-to-action button, and inline validation errors that use the same <code>--danger</code> red as everywhere else rather than a generic browser alert. None of that is a special "login page" design system - it's the same tokens from the rest of the app, applied to a page with dramatically less on it, which turned out to be the entire trick. A login screen doesn't need more visual polish than the rest of the app; it needs the <em>same</em> polish, with nothing else competing for attention on the page.</p><p>(That screen lasted about a day. A later commit deleted <code>LoginForm</code> when authentication moved to a separate service - see <a href="https://ghost.atathome.me/handing-auth-to-identity-system/">post 9</a>. The design lesson held; the page didn't survive.)</p><h2 id="what-stayed-simple-on-purpose">What stayed simple on purpose</h2><p>A few things I deliberately didn't reach for:</p><ul><li><strong>No component library.</strong> No Material UI, no Chakra, no Tailwind. Plain CSS with custom properties covers everything this app needs, and there's no dependency to keep updated for styling alone.</li><li><strong>No client-side state management library.</strong> Every page fetches its own data with <code>useEffect</code> and <code>fetch</code>, holds it in <code>useState</code>, and that's the entire state story. Nothing here needs Redux or a query cache - the data volumes are small (one user, a handful of accounts) and most pages only need their own data once per visit.</li><li><strong>No chart library.</strong> The one chart is bars built from <code>&lt;div&gt;</code>s with <code>width</code> percentages. Pulling in a charting library for one component would have been more dependency than the feature warranted. (That held until the Home page needed balances plotted over time: I added <code>recharts</code> for the line charts, and left the category bars as <code>&lt;div&gt;</code>s. See <a href="https://ghost.atathome.me/periods-charts-and-a-phone-sized-ui/">post 13</a>.)</li></ul><p>None of that is a permanent stance - if this grows more charts or more cross-page shared state, those defaults would be worth revisiting. But "plain React, plain CSS, fetch-on-mount" turned out to cover a genuinely useful multi-page personal finance app without needing any of it, which was worth confirming before reaching for heavier tools by default.</p><p>Routing and styling got the app somewhere pleasant to look at. What it didn't have yet was a login screen worth trusting with real bank data, or any way to turn on two-factor authentication - that's next.</p><hr><p>Previous: <a href="https://ghost.atathome.me/from-script-to-service/">← From script to service</a> · Next: <a href="https://ghost.atathome.me/auth-2fa-and-settings/">Auth, two-factor, and account settings →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Central login service: One place to type a password - Part 1]]></title><description><![CDATA[~25 min read

Every small tool I build for myself eventually needs a login. A finance tracker, an invoicing app, a dashboard for something plugged in to the wall. The first time, I wrote the whole thing inline: a user table, Argon2 hashing, sessions, a password-change form, two-factor enrolment with recovery codes. It worked, it was even fairly pleasant, and then I looked at the second app on my list and realised I was about to write all of it again.

This series is about the project I built ins]]></description><link>https://brightbot.co.uk/identity-system-why-a-central-login-service/</link><guid isPermaLink="false">Ghost__Post__6ada2fa11df6faba86556a76</guid><category><![CDATA[Building Identity System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Fri, 23 Oct 2026 08:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1763974952384-d61fabe8ea76?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDZ8fHNwb2tlfGVufDB8fHx8MTc5MjY4NDAzN3ww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1763974952384-d61fabe8ea76?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDZ8fHNwb2tlfGVufDB8fHx8MTc5MjY4NDAzN3ww&ixlib=rb-4.1.0&q=80&w=2000" alt="Central login service: One place to type a password - Part 1"/><p><em>~25 min read</em></p><p>Every small tool I build for myself eventually needs a login. A finance tracker, an invoicing app, a dashboard for something plugged in to the wall. The first time, I wrote the whole thing inline: a user table, Argon2 hashing, sessions, a password-change form, two-factor enrolment with recovery codes. It worked, it was even fairly pleasant, and then I looked at the second app on my list and realised I was about to write all of it again.</p><p>This series is about the project I built instead: a small central login service that sits in front of everything else, and is the only place a browser ever types a password. This first post covers the idea, the first working version, and the decisions in it that turned out to matter. Later posts cover deploying it, giving it a proper frontend, teaching it to speak OpenID Connect, and moving its configuration out of files and into a database.</p><p>I'll show real code throughout. Where I describe a mistake, it's one that is visible in the repository's history, not a tidied-up version of events.</p><h2 id="the-problem-with-just-add-a-login">The problem with "just add a login"</h2><p>Authentication is the sort of feature that feels finished the moment it works. You hash the password, you set a cookie, you check the cookie. Done.</p><p>Except it's never one feature. A realistic list for even a hobby-grade login:</p><ul><li>Passwords hashed with a modern, slow algorithm and a per-user salt.</li><li>Opaque, revocable server-side sessions with an expiry.</li><li>Optional TOTP two-factor, which means enrolment, a QR code, confirmation that the user's authenticator actually works, recovery codes for when their phone doesn't, and a lockout so the six-digit code can't simply be guessed.</li><li>Changing your name, your email and your password, each with different rules about whether you need to prove who you are first.</li><li>Somebody to create the accounts in the first place.</li></ul><p>That's a lot of surface area to carry in an app whose actual job is to show me my bank balances. Worse, it's surface area I'd be carrying <em>per app</em>. When I fix a subtle issue in one copy (say, that changing a password should revoke other sessions), the other copies don't hear about it. Within a year I'd have four slightly different login systems, each one the only copy that knew a particular lesson.</p><p>So the question became: can one service own all of that, and every other app simply believe it?</p><h2 id="the-forward-auth-pattern">The forward-auth pattern</h2><p>Reverse proxies have a feature for exactly this. nginx calls it <code>auth_request</code>; Traefik calls it <code>ForwardAuth</code>; the idea is identical. Before the proxy forwards a request to a protected app, it makes a small subrequest to an authentication service and asks one question: <em>is this request allowed?</em></p><ul><li>If the auth service answers <code>200</code>, the proxy forwards the original request to the app. The <code>200</code> response can carry headers (who the user is), and the proxy copies those onto the forwarded request.</li><li>If it answers <code>401</code>, the proxy doesn't forward anything. Typically it redirects the browser to the auth service's login page instead.</li></ul><p>Drawn out, with three moving parts:</p><pre><code> browser ──▶ reverse proxy ──▶ protected app (app1.example.com, app2...)
                 │
                 │ auth_request / ForwardAuth
                 ▼
          identity-system  (sso.example.com)
             /verify   -&gt; 200 + X-Auth-User-* headers, or 401
             /login    -&gt; the only place a human types a password
</code></pre><p>The protected app never sees a password, never sets a session cookie, and never needs a user table. It reads a header that says who the proxy vouched for, and it believes it, because the only way a request reaches the app is through the proxy. (That belief is only safe if the proxy overwrites those headers unconditionally, so a client can't just send its own. I'll come back to that in the wiring section.)</p><p>The session cookie lives on the <em>parent domain</em>, say <code>.example.com</code>, so the browser sends it to <code>sso.example.com</code>, <code>app1.example.com</code> and <code>app2.example.com</code> alike. Sign in once at the login service and every app behind the proxy can see you.</p><p>The service is called <code>identity-system</code>, and its entire first-version contract fits in two sentences. <code>GET /verify</code> takes the cookie and answers yes or no. <code>/login</code> is where a human proves who they are.</p><h2 id="standing-on-a-library-not-rebuilding-one">Standing on a library, not rebuilding one</h2><p>I didn't write the hard parts here. They already existed in a library of mine called <a href="https://github.com/atownsend247/bb-py-sessionkit">sessionkit</a>: an <code>AuthService</code> that owns the rules (password hashing with Argon2, session lifetime, TOTP and its lockout, email and password validation) over an <code>AuthStore</code> that owns persistence. It ships a SQLite-backed store, and a small CLI for provisioning accounts.</p><p>That split shaped the whole project, and it's worth stating as a rule because it kept me honest for the rest of the build:</p><blockquote>A route handler's job is HTTP concerns only: reading the cookie, mapping errors to status codes. Every actual <em>rule</em> lives in <code>AuthService</code>.</blockquote><p>If I ever find myself wanting to add a rule here (a new password policy, a new account field), that's a sign it belongs in the library, with a release and a version bump, not in this service. That rule ended up written into the project's <code>CLAUDE.md</code> almost verbatim, and it shows in the dependency itself:</p><pre><code class="language-toml">dependencies = [
    "fastapi&gt;=0.110",
    "uvicorn[standard]&gt;=0.30",
    "python-multipart&gt;=0.0.9",
    "sessionkit @ git+https://github.com/atownsend247/bb-py-sessionkit.git@v0.3.0",
]

[tool.hatch.metadata]
# sessionkit isn't on PyPI - it's a direct git+https reference, which
# hatchling refuses to package unless this is explicitly opted into.
allow-direct-references = true
</code></pre><p>Two details there are worth a sentence each. The dependency is a <em>pinned git tag</em>, not a branch, because a direct git reference has no <code>&gt;=</code> range syntax and a tag is the only way to get a reproducible install and a deliberate, visible bump. And <code>allow-direct-references</code> is required for the build backend to accept that form of dependency at all; without it the build fails with an error that doesn't obviously point at the cause.</p><h2 id="the-first-version-of-the-app">The first version of the app</h2><p>The whole first commit is about 1,200 lines including tests, deployment scripts and docs, but the application itself is one file of roughly 180 lines. I'll walk through the interesting parts in the order a request would meet them.</p><h3 id="building-the-app-from-parts">Building the app from parts</h3><pre><code class="language-python">def create_app(auth: AuthService, settings: Settings) -&gt; FastAPI:
    app = FastAPI(title="identity-system")
    ...
</code></pre><p><code>create_app</code> takes an already-built <code>AuthService</code> and a <code>Settings</code> object instead of constructing them itself. This is the standard dependency-injection move, but the payoff here is concrete: the tests can hand it an <code>AuthService</code> over an in-memory SQLite database, so no test ever touches a real file. The only module that reads environment variables or opens a real database is <code>main.py</code>, a rule that held for the whole project.</p><h3 id="turning-library-errors-into-http-status-codes">Turning library errors into HTTP status codes</h3><p><code>AuthService</code> signals problems by raising exceptions that all descend from <code>AuthError</code>. The app has one table mapping those to HTTP statuses:</p><pre><code class="language-python">_ERROR_STATUS: dict[type[AuthError], int] = {
    AuthenticationError: 401,
    OtpInvalid: 422,
    UserNotFound: 404,
    DuplicateUser: 409,
    ValidationError: 422,
}


async def _handle_auth_error(_request: Request, exc: AuthError) -&gt; JSONResponse:
    status = next((s for t, s in _ERROR_STATUS.items() if isinstance(exc, t)), 400)
    return JSONResponse(status_code=status, content={"detail": str(exc)})

for exc_type in _ERROR_STATUS:
    app.add_exception_handler(exc_type, _handle_auth_error)
</code></pre><p>Each route can then just call the service and let exceptions propagate. There's no <code>try/except</code> in the handlers for the ordinary failure cases, which keeps them short and, more importantly, keeps the status-code policy in one place.</p><p>There's a trap in that table. Look at <code>OtpInvalid</code>. The other two-factor errors (<code>OtpRequired</code>, <code>OtpLocked</code>) are subclasses of <code>AuthenticationError</code>, so the <code>AuthenticationError: 401</code> entry covers them via the <code>isinstance</code> check. <code>OtpInvalid</code> is a direct <code>AuthError</code> subclass instead. It needs its own entry, or a wrong two-factor code falls through the handler registration entirely and the user gets a bare <code>500 Internal Server Error</code> instead of a polite <code>422</code>.</p><p>It's an easy thing to forget because nothing about the happy path exercises it. I now keep this in the project notes as an explicit rule: <em>every <code>AuthError</code> subclass that can reach a route needs an entry</em>. It reappears later in the series, when a new login route has the same exposure.</p><p>Why a list lookup with <code>isinstance</code> rather than a dictionary <code>.get(type(exc))</code>? Because of subclassing: <code>OtpRequired</code> isn't in the table, but it is an <code>AuthenticationError</code>, and an exact-type lookup would miss it. Order matters too (first match wins), which is why the generic parent classes can sit in the table without swallowing more specific ones, as long as the specific ones are listed first.</p><h3 id="the-session-cookie">The session cookie</h3><p>Sessions are opaque tokens: random strings with no meaning on their own, looked up server-side by <code>AuthService.user_for_token</code>. That has a useful property that signed tokens like JWTs don't: logging out, or changing your password, genuinely invalidates the session, because the server forgets it.</p><p>The cookie is set in one helper so every login path gets identical flags:</p><pre><code class="language-python">def _set_session_cookie(response: Response, token: str) -&gt; None:
    response.set_cookie(
        settings.cookie_name,
        token,
        max_age=settings.session_days * 86400,
        path="/",
        domain=settings.cookie_domain or None,
        httponly=True,
        secure=settings.cookie_secure,
        samesite="lax",
    )
</code></pre><p>Each flag earns its place:</p><ul><li><code>httponly=True</code>: JavaScript can't read the cookie, so a cross-site scripting bug can't trivially steal the session.</li><li><code>secure</code>: the browser only sends it over HTTPS. This defaults to <strong>on</strong>, and the setting to turn it off is named so it's clearly for local development. (A <code>Secure</code> cookie over plain <code>http://localhost</code> is silently never sent back, which makes for a baffling first ten minutes if you don't know.)</li><li><code>samesite="lax"</code>: the cookie isn't sent on cross-site POSTs, which blunts the most common request-forgery attacks without breaking ordinary link navigation, and link navigation is exactly what a login redirect is.</li><li><code>domain</code>: the parent domain, so every subdomain shares one session. This is what makes single sign-on across apps work at all.</li></ul><p><code>samesite=lax</code> is a mitigation, not a complete answer to cross-site request forgery, and there's no anti-CSRF token on the login route. I'll return to that under "known gaps"; it's deliberate and written down, not an oversight.</p><h3 id="the-login-route-and-the-open-redirect-problem">The login route, and the open-redirect problem</h3><p>A forward-auth flow needs the login page to send you <em>back</em> to where you came from. The proxy redirects an unauthenticated browser to something like:</p><pre><code>https://sso.example.com/login?rd=https://app1.example.com/some/page
</code></pre><p>and after a successful login, the service redirects to the <code>rd</code> value. Which is a textbook open redirect: if the service blindly honours <code>rd</code>, then <code>/login?rd=https://evil.example/phish</code> is a <em>genuine login link on a genuine domain</em> that drops the user on an attacker's site right after they've typed their real password. That's a strong phishing primitive, handed over for free.</p><p>The defence is a single method on <code>Settings</code>, and I treat it as one of the project's load-bearing walls:</p><pre><code class="language-python">def is_trusted_redirect(self, target: str) -&gt; bool:
    if not target or target.startswith("//"):
        return False
    parsed = urlsplit(target)
    if not parsed.scheme and not parsed.netloc:
        return target.startswith("/")
    if parsed.scheme not in ("http", "https"):
        return False
    host = parsed.hostname or ""
    domain = self.cookie_domain.lstrip(".")
    return bool(domain) and (host == domain or host.endswith("." + domain))
</code></pre><p>Walk through what each branch rejects or accepts:</p><ul><li><strong>Empty, or starting with <code>//</code>.</strong> A protocol-relative URL like <code>//evil.example/x</code> has no scheme, and some browsers treat it as an absolute URL on a different host. It would otherwise look like a "relative path" to a naive check, so it's rejected explicitly before anything else.</li><li><strong>No scheme and no host.</strong> A genuinely relative path. It's accepted only if it starts with <code>/</code>, so a bare word like <code>evil.example/x</code> (which a browser would treat as relative to the current page) is not accepted as a trusted destination.</li><li><strong>A scheme that isn't <code>http</code> or <code>https</code>.</strong> <code>javascript:</code>, <code>data:</code>, <code>file:</code> and friends are all rejected.</li><li><strong>An absolute URL.</strong> The host must be exactly the cookie domain or a true subdomain of it. Note the <code>"." +</code> in <code>endswith</code>: without it, <code>evilexample.com</code> would match a domain of <code>example.com</code>. The dot makes it <code>.example.com</code>, which <code>evilexample.com</code> doesn't end with.</li><li><strong>An empty cookie domain</strong> (<code>bool(domain) and ...</code>) means no absolute redirect is ever trusted, so a misconfigured deployment fails closed.</li></ul><p>The login handler then picks its destination like this: use <code>rd</code> if it passes the check, otherwise fall back to a safe default. The tests pin down the two outcomes that matter end to end, a login with a trusted <code>rd</code> lands there, and a login with <code>https://evil.example.net/phish</code> quietly falls back to the default page. I'd like to say every branch above has its own unit test; in truth the function is covered through those two routes, and each branch exists because it corresponds to a way open-redirect checks are commonly bypassed in other people's software, not because a test of mine caught it.</p><p>One more thing about the cookie domain: it does <em>double duty</em>. It's the <code>Domain=</code> attribute on the session cookie <strong>and</strong> the allow-list for redirects. That's convenient, since the set of hosts that should receive your cookie is precisely the set of hosts that are safe to send you back to, but it does mean those two concepts can't be configured separately. For this project that's a feature.</p><h3 id="verify-the-endpoint-everything-depends-on"><code>/verify</code>: the endpoint everything depends on</h3><pre><code class="language-python">@app.get("/verify")
def verify(request: Request) -&gt; Response:
    try:
        user = auth.user_for_token(_token(request))
    except AuthenticationError:
        return Response(status_code=401)
    return Response(
        status_code=200,
        headers={
            "X-Auth-User-Id": user.id or "",
            "X-Auth-User-Email": user.email,
            "X-Auth-User-Name": user.name,
        },
    )
</code></pre><p>It returns no body either way. The proxy calls this on <em>every request to every protected app</em>, so it has to be cheap, and the only information the caller wants is the status code and the headers. It's one of the few routes that catches its own <code>AuthenticationError</code> rather than leaning on the central error table, because the response it wants for failure (an empty <code>401</code>) is not the JSON error body the table would produce.</p><p>There's a companion route, <code>GET /me</code>, which does the same check and returns the identity as JSON. That's for the case where a <em>frontend</em> wants to know who's signed in. Browsers can't read the headers the proxy injects, so <code>/me</code> lets a single-page app ask the same question directly.</p><h3 id="profile-password-and-two-factor">Profile, password and two-factor</h3><p>The remaining routes are almost embarrassingly thin, which was the point:</p><pre><code class="language-python">@app.patch("/profile")
def update_profile(payload: dict, user: User = Depends(current_user)):
    if "name" in payload:
        auth.set_name(user.id, payload["name"])
    if "email" in payload:
        auth.set_email(
            user.id, payload["email"], current_password=payload.get("current_password")
        )
    return Response(status_code=204)

@app.post("/password")
def change_password(payload: dict, user: User = Depends(current_user)):
    auth.set_password(user.id, payload.get("new_password", ""))
    return Response(status_code=204)

@app.post("/2fa/setup")
def setup_2fa(user: User = Depends(current_user)):
    enrol = auth.start_totp_enrollment(user.id)
    return {"secret": enrol.secret, "otpauth_uri": enrol.uri}

@app.post("/2fa/confirm")
def confirm_2fa(payload: dict, user: User = Depends(current_user)):
    codes = auth.confirm_totp(user.id, payload.get("otp", ""))
    return {"recovery_codes": codes}
</code></pre><p>Every one is: authenticate with <code>Depends(current_user)</code>, call exactly one <code>AuthService</code> method, return. The validation (what makes a password acceptable, what makes an email valid) isn't here at all. A bad value raises a <code>ValidationError</code> inside the library, and the central table turns it into a <code>422</code>.</p><p>Two comments in the real code explain behaviours that aren't obvious from the shape:</p><ol><li><code>PATCH /profile</code> returns <code>204</code> with no body. The service has no "look up a user by id" method to return the refreshed record from, only <code>find_user(email)</code> and <code>list_users()</code>. Rather than guess at the new state, the route returns nothing and the client re-fetches <code>/me</code>.</li><li><code>POST /password</code> does <strong>not</strong> re-check the caller's current password. Changing an email requires <code>current_password</code>, and so does disabling two-factor, but the library's <code>set_password</code> takes no such argument. The session cookie is the only proof of identity the route asks for. That is a real gap in a service people might one day put somewhere a stolen cookie is a realistic threat. The fix isn't to bolt a check on here (there's no private hook to reach into); it's to add the argument to the library first. Until then it's documented, loudly, in two places.</li></ol><p>I'll flag one more property of that password route, because it surprised me when I first read the library's behaviour: changing a password revokes <em>every</em> session on the account, including the one making the request. So a successful password change immediately signs the user out everywhere. That's the safe behaviour, but any frontend has to expect to be thrown back to the login page afterwards.</p><h2 id="configuration-kept-boring">Configuration, kept boring</h2><p><code>Settings</code> is a frozen dataclass populated from environment variables with a common prefix:</p><pre><code class="language-python">_PREFIX = "IDENTITY_SYSTEM_"

def _env(name: str, default: str) -&gt; str:
    return os.environ.get(_PREFIX + name, default)

@dataclass(frozen=True)
class Settings:
    db_path: str
    cookie_domain: str
    cookie_secure: bool
    session_days: int
    issuer: str
    ...
</code></pre><p>There's no settings framework. The module's own docstring says why: "small enough that a settings framework would be more ceremony than it saves." That stayed true for the whole series, though the number of fields grew from five to about ten.</p><p>A small thing worth copying: <code>issuer</code> here is <strong>only</strong> the label that shows up in a user's authenticator app next to their code. It sounds like it should be the service's public URL. It is not. Later, when the service grows an OpenID Connect side that genuinely needs an issuer URL, that gets a completely separate setting, and the project's notes carry a warning not to conflate them. Two settings with confusingly similar names are an accident waiting to happen, and "documented in the file that defines them" turned out to be a reasonable mitigation.</p><p><code>.env.example</code> documents each variable with the <em>why</em> rather than just the default, which paid off repeatedly when I came back to the project after a gap.</p><h2 id="mainpy-the-one-place-that-touches-the-world"><code>main.py</code>: the one place that touches the world</h2><pre><code class="language-python">settings = Settings.from_env()
store = SqliteAuthStore.open(settings.db_path)
auth = AuthService(store, session_days=settings.session_days, issuer=settings.issuer)

app = create_app(auth, settings)
</code></pre><p>Four lines of real work. This is the entrypoint (<code>uvicorn identity_system.main:app</code>), and it's the only module allowed to read the environment or open a database file.</p><p>There's a threading subtlety hiding behind <code>SqliteAuthStore.open</code>. FastAPI runs synchronous route handlers on a thread pool, so one SQLite connection gets used from several threads. SQLite's Python binding refuses that by default (<code>check_same_thread</code>), so the store opens its connection with that check turned off and serialises access internally with its own lock. The practical rule from the library's guidance is: open <strong>one</strong> store, once, at import time, and share it. Opening a store per request would work but would be both slower and pointless.</p><p>This is also where the honest limitation lives. A single SQLite file with an internal lock is a perfectly good answer for one instance of one small service. It is not an answer to "scale out to several instances", and the notes say so: if that day ever comes, the answer is a different <code>AuthStore</code> implementation over Postgres (a structural change to storage, with no change to anything above it), not clever tricks with the SQLite file.</p><h2 id="the-tests">The tests</h2><p>Because <code>create_app</code> takes its collaborators, the test setup is tiny:</p><pre><code class="language-python">@pytest.fixture
def store():
    conn = connect(":memory:", check_same_thread=False)
    try:
        yield SqliteAuthStore(conn)
    finally:
        conn.close()

@pytest.fixture
def client(auth, settings) -&gt; TestClient:
    app = create_app(auth, settings)
    # The session cookie is scoped to settings.cookie_domain (.example.com);
    # TestClient's default host ("testserver") doesn't match that domain, so
    # its cookie jar would silently drop the cookie between requests unless
    # the client's own host is a subdomain of it.
    return TestClient(app, base_url="http://sso.example.com")
</code></pre><p>That comment is the single most expensive lesson in the test suite. My first instinct was to use <code>TestClient</code> with its default <code>testserver</code> host. The login test would succeed, the <em>next</em> request would come back as <code>401</code>, and the cookie would be right there in the response headers. The reason is that the cookie is scoped to <code>.example.com</code>, and a cookie jar quite correctly refuses to send a <code>.example.com</code> cookie to a host called <code>testserver</code>. The fix is just to give the test client a host under the domain. No code is wrong; the test's world was.</p><p>The tests themselves read like a specification of the contract:</p><pre><code class="language-python">def test_verify_without_cookie_is_401(client): ...
def test_verify_with_garbage_cookie_is_401(client): ...

def test_verify_with_valid_session_returns_identity_headers(client, auth):
    user = auth.create_user("alex@example.com", "password123", name="Alex")
    client.post("/login", data={"email": "alex@example.com", "password": "password123"})

    resp = client.get("/verify")
    assert resp.status_code == 200
    assert resp.headers["x-auth-user-id"] == user.id
    assert resp.headers["x-auth-user-email"] == "alex@example.com"
    assert resp.headers["x-auth-user-name"] == "Alex"
</code></pre><p>There are separate files for login/logout, profile, two-factor and the forward-auth contract. The garbage-cookie test is cheap and earns its keep: it pins down that a forged or stale token produces a clean <code>401</code>, never an exception.</p><h2 id="wiring-a-proxy-up-to-it">Wiring a proxy up to it</h2><p>The README ships examples for both proxies I might use. The nginx one is the reference:</p><pre><code class="language-nginx">location = /_verify {
    internal;
    proxy_pass http://identity-system/verify;
    proxy_set_header X-Original-URI $request_uri;
}

location / {
    auth_request /_verify;
    auth_request_set $user_email $upstream_http_x_auth_user_email;
    proxy_set_header X-Auth-User-Email $user_email;

    error_page 401 = @login_redirect;
    proxy_pass http://your-app;
}

location @login_redirect {
    return 302 https://sso.example.com/login?rd=$scheme://$http_host$request_uri;
}
</code></pre><p>Reading it top to bottom:</p><ul><li><code>/_verify</code> is <code>internal</code>, meaning clients can't request it directly; it only exists to be the target of <code>auth_request</code>.</li><li><code>auth_request /_verify</code> runs before the real proxying. <code>auth_request_set</code> captures a header from the verify response into a variable, and <code>proxy_set_header</code> writes it onto the forwarded request.</li><li>A <code>401</code> from the verify call is caught by <code>error_page</code> and turned into a <code>302</code> to the login page, with the original URL in <code>rd</code>.</li></ul><p>And here's the part that makes the whole scheme trustworthy: <code>proxy_set_header</code> <strong>overwrites</strong> the header unconditionally. If a client sends <code>X-Auth-User-Email: someone-else@example.com</code> itself, nginx replaces it with whatever the verify call actually said (or an empty value). A forwarded-header identity scheme is exactly as secure as that overwrite, and the app behind it must also be unreachable except through the proxy, or the whole thing is decorative.</p><p>The Traefik example uses <code>forwardauth.authResponseHeaders</code> to name the headers to copy across, with a note that Traefik's redirect-on-401 behaviour is less tidy than nginx's <code>error_page</code> trick and needs wiring per its own docs. My own apps sit behind nginx, so that example is documentation rather than something I've exercised, and the README is careful to say so.</p><h2 id="what-i-deliberately-didnt-build">What I deliberately didn't build</h2><p>The README has a "Known gaps" section, and I'd defend every item as a choice:</p><ul><li><strong>No self-registration.</strong> There is no public signup form. Accounts are provisioned by the library's CLI against the same database file (<code>sessionkit --db ./auth.db add you@example.com</code>; note <code>--db</code> is a top-level argument and goes <em>before</em> the subcommand). For a personal service whose users are me and a few people I trust, an open signup endpoint is attack surface with no upside. A later post adds an admin-only way to do it from the web, which is a different thing.</li><li><strong>No CSRF token on login.</strong> <code>SameSite=Lax</code> covers the common cross-site POST case but isn't a complete answer. Same stance the library takes on login rate-limiting: an explicit, documented gap.</li><li><strong>Authentication, not authorisation.</strong> <code>/verify</code> answers "who is this?", not "may they do X in this app?". The library has no roles or scopes, so each downstream app owns its own authorisation decisions based on the identity it receives. This will matter again when I need an admin page of the service's own.</li><li><strong>One SQLite file.</strong> As discussed, fine for one instance.</li></ul><p>Writing these down in the first commit was one of the better habits of this project. Half of the later work is a gap being closed on purpose, not a bug being found.</p><h2 id="where-this-leaves-us">Where this leaves us</h2><p>At the end of the first commit there's a working central login service: about 180 lines of app, a settings module, an inline-HTML login page, four test files, and a README that explains how to put a proxy in front of it. Any app behind nginx can now stop thinking about passwords.</p><p>It also has an obvious problem, which is that it isn't deployed anywhere. The next post is about getting it onto a real container, and the surprisingly large number of small things that went wrong between "it passes its tests" and "it's actually running".</p><hr><p>Next: <a href="https://ghost.atathome.me/identity-system-shipping-it-jenkins-uv-and-a-container/">Shipping it: Jenkins, uv and a Debian container →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: From script to service - Part 4]]></title><description><![CDATA[~10 min read

The CLI prototype proved the OAuth flow worked. It also had a very short list of things it fundamentally couldn't do: run anywhere but my laptop, keep transaction history instead of overwriting it, or be looked at by anything other than cat transactions.json. This post covers the two commits that fixed all three: init: basic backend/frontend, which turned the script into a FastAPI package with SQLite storage and typed settings, and Add TrueLayer web linking, provider/storage packag]]></description><link>https://brightbot.co.uk/from-script-to-service/</link><guid isPermaLink="false">Ghost__Post__6ad488c21df6faba8655698f</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Fri, 23 Oct 2026 08:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1605152276897-4f618f831968?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fFNlcnZpY2V8ZW58MHx8fHwxNzkyMzE2NjYzfDA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1605152276897-4f618f831968?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fFNlcnZpY2V8ZW58MHx8fHwxNzkyMzE2NjYzfDA&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: From script to service - Part 4"/><p><em>~10 min read</em></p><p>The <a href="https://ghost.atathome.me/first-prototype-cli-script/">CLI prototype</a> proved the OAuth flow worked. It also had a very short list of things it fundamentally couldn't do: run anywhere but my laptop, keep transaction history instead of overwriting it, or be looked at by anything other than <code>cat transactions.json</code>. This post covers the two commits that fixed all three: <code>init: basic backend/frontend</code>, which turned the script into a FastAPI package with SQLite storage and typed settings, and <code>Add TrueLayer web linking, provider/storage packages, deploy configs, and docs</code>, which moved linking into the API and added a real deployment target. Together they're a real storage layer, a real API, and somewhere to run it - plus a short tail of CI and deploy fixes that only showed up once it ran somewhere other than my laptop.</p><h2 id="splitting-one-script-into-two-packages">Splitting one script into two packages</h2><p>The prototype was a single file that did OAuth, token storage, and the TrueLayer HTTP calls all in one place. The first move was mechanical but important: split it into a <code>providers/</code> package (one module per data source - <code>truelayer.py</code> today, a Hargreaves Lansdown CSV importer as a stretch goal) and a <code>storage/</code> package (currently just SQLite, but scoped so it doesn't have to stay that way). Neither package knows about the other's internals. <code>providers/truelayer.py</code> produces a flat list of transaction dicts; <code>storage/sqlite.py</code> doesn't care whether those dicts came from TrueLayer, a CSV file, or something else entirely.</p><p>This is the kind of restructuring that's easy to skip when you're the only user and the only one who'll ever read the code - but it paid for itself almost immediately, because it's exactly the boundary that later let me add providers list caching, connection metadata, and account balances as their own concerns without every change rippling through unrelated code.</p><h2 id="a-database-and-the-one-line-that-makes-re-running-safe">A database, and the one line that makes re-running safe</h2><p>The prototype's <code>fetch</code> overwrote <code>transactions.json</code> on every run. That's fine once; it's actively wrong for something meant to run nightly, because transactions inside the <code>days=90</code> window would get re-fetched every time and you'd lose anything older than the window on each overwrite. SQLite fixed this (it arrived in the first backend commit as a flat <code>storage.py</code>, and only became the <code>storage/</code> package in the later split), and the entire fix is one line in the schema and one clause in the insert:</p><pre><code class="language-sql">CREATE TABLE IF NOT EXISTS transactions (
    bank TEXT NOT NULL,
    id TEXT NOT NULL,
    account TEXT,
    date TEXT NOT NULL,
    description TEXT,
    merchant TEXT,
    amount REAL NOT NULL,
    currency TEXT,
    bank_category TEXT,
    category TEXT,
    PRIMARY KEY (bank, id)
);
</code></pre><pre><code class="language-python">def save_transactions(conn, transactions):
    before = conn.total_changes
    conn.executemany(
        """
        INSERT OR IGNORE INTO transactions
            (bank, id, account, date, description, merchant, amount, currency, bank_category)
        VALUES
            (:bank, :id, :account, :date, :description, :merchant, :amount, :currency, :bank_category)
        """,
        transactions,
    )
    conn.commit()
    inserted = conn.total_changes - before
    return inserted, len(transactions) - inserted
</code></pre><p><code>PRIMARY KEY (bank, id)</code> plus <code>INSERT OR IGNORE</code> means running the same 90-day fetch every night is completely safe: transactions already in the database are silently skipped, only genuinely new ones get inserted, and I get an <code>(inserted, skipped)</code> count back for free to log. No transaction gets duplicated, and none of the fetch logic needs to know or care that it's re-fetching data it already has. <code>category</code> sits in the schema unused at this point - a placeholder for rule-based categorisation I hadn't built yet, but wanted room for without a migration later.</p><p>(The key itself never changed, but what I put <em>in</em> it did: TrueLayer documents its <code>transaction_id</code> field as one that <em>can change between requests</em> - not the guarantee you want from a de-dup key - so a later commit switched the <code>id</code> column over to <code>normalised_provider_transaction_id</code>. That's covered in <a href="https://ghost.atathome.me/keeping-data-fresh/">post 7</a>.)</p><h2 id="from-a-local-callback-server-to-real-api-endpoints">From a local callback server to real API endpoints</h2><p>This was the change that actually mattered most for turning a script into a service. The prototype's <code>wait_for_code()</code> - a <code>BaseHTTPRequestHandler</code> that opens, catches one redirect, and closes - only works because a human is sitting at a browser on the same machine the script is running on. That assumption breaks the moment you want this running unattended on a server somewhere.</p><p>The fix was to stop treating "link a bank" as something the script does and start treating it as something the <strong>API</strong> does, with the browser redirecting to a real, always-listening route instead of a server the script spins up and tears down for one request:</p><pre><code class="language-python">router = APIRouter(prefix="/api/providers/truelayer")


@router.get("/link")
def link(label: str):
    return RedirectResponse(truelayer.build_auth_url(state=label))


@router.get("/callback")
def callback(code: str | None = None, state: str | None = None, error: str | None = None):
    if error:
        return HTMLResponse(f"Linking failed: {error}", status_code=400)

    tokens = truelayer.token_request({
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": truelayer.REDIRECT_URI,
    })

    all_tokens = truelayer.load_tokens()
    all_tokens[state] = {"refresh_token": tokens["refresh_token"]}
    truelayer.save_tokens(all_tokens)

    return HTMLResponse(f"Linked '{state}'. You can close this tab.")


@router.get("/banks")
def list_banks():
    return {"banks": list(truelayer.load_tokens().keys())}
</code></pre><p>The <code>label</code> from the prototype's command-line argument became TrueLayer's OAuth <code>state</code> parameter instead - the one field in an OAuth redirect that's opaque to the provider and round-trips back to you unchanged, which makes it the natural place to carry "which of my accounts is this" through a redirect I don't otherwise control the shape of. <code>/link</code> redirects straight to TrueLayer's hosted consent page; <code>/callback</code> is where the browser lands after the user approves (or doesn't), and it's a real, permanent route - not a server that exists for one request and vanishes.</p><p>This meant linking a bank now worked from any browser, pointed at any deployment of the app - including a headless server with no display and no way to run <code>webbrowser.open()</code> at all. A tiny React component (<code>LinkedBanks.tsx</code> at this point, later renamed) replaced typing a bank name on a command line: pick a label, hit a button, get redirected to the bank, get redirected back.</p><h2 id="configuration-that-fails-loudly">Configuration that fails loudly</h2><p>One thing that changed shape entirely in this move (the settings class itself landed in the first backend commit, and the linking commit extended it) was how the app got its settings. The prototype read straight from <code>os.environ</code> wherever it needed a value - <code>os.environ["TL_CLIENT_ID"]</code> sitting inline in whatever function happened to need it first. That's fine when there's one entrypoint and one developer who already knows what's required. It stops being fine the moment there's a FastAPI app, a CLI fetch command, and a systemd unit all potentially starting up with a slightly different environment underneath them - a typo in a unit file's <code>Environment=</code> line, or a <code>.env</code> that didn't get copied to the deploy target, should fail on startup with a clear message, not three requests into serving traffic.</p><p>The fix was centralising configuration into one <code>pydantic-settings</code> class, read once and cached:</p><pre><code class="language-python">class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_file=".env", extra="ignore")

    tl_client_id: str
    tl_client_secret: str
    tl_is_sandbox: bool = True
    storage_dir: Path = Path("storage")
    public_base_url: str = "http://localhost:8000"

    @property
    def db_path(self) -&gt; Path:
        return self.storage_dir / "db" / "finance.db"

@lru_cache
def get_settings() -&gt; Settings:
    return Settings()
</code></pre><p>Every required field with no default - <code>tl_client_id</code>, <code>tl_client_secret</code> - raises a validation error the instant <code>Settings()</code> is constructed, which happens at import time, before the API has bound to a port or the fetch command has made a single HTTP request. Missing configuration now fails at the very first possible moment, with a message naming exactly which field is missing, instead of surfacing as a confusing downstream error the first time that particular code path happens to run.</p><h2 id="nightly-unattended-via-systemd">Nightly, unattended, via systemd</h2><p>With linking handled by the API and re-running <code>fetch</code> made safe by the de-dup key, the last piece was making <code>fetch</code> itself run without me remembering to. Two systemd units:</p><pre><code class="language-ini"># finance-system-fetch.timer
[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
</code></pre><pre><code class="language-ini"># finance-system-fetch.service
[Service]
Type=oneshot
User=finance-system
WorkingDirectory=/opt/finance-system
ExecStart=/opt/finance-system/.venv/bin/python -m finance_system.providers.truelayer fetch
ExecStart=/opt/finance-system/.venv/bin/python -m finance_system.storage.sqlite
</code></pre><p>(Two things in that unit didn't survive contact with the real server: a later commit (<code>Fix remote users</code>) switched <code>User=</code> to <code>root</code> on both units, and the second <code>ExecStart</code> later moved to <code>python -m finance_system.storage</code> - see <a href="https://ghost.atathome.me/making-the-nightly-sync-boring/">post 17</a>. The whole unit was eventually replaced by a script that loops over every user, which is <a href="https://ghost.atathome.me/one-storage-tree-per-user/">post 10</a>.)</p><p><code>Type=oneshot</code> with two <code>ExecStart</code> lines runs them in sequence: pull fresh transactions to JSON, then load that JSON into SQLite - the prototype's <code>fetch</code> plus the new storage module, now on a timer instead of by hand. <code>Persistent=true</code> on the timer means if the machine was off at 3am, the missed run fires as soon as it's back up, rather than silently skipping a day. And the service unit's comment is worth keeping verbatim, because it states a constraint that's easy to forget once linking moved into the API: <strong>this unit only refreshes already-linked banks</strong> - linking a new one is still an interactive, browser-based step, and always will be, because OAuth consent fundamentally needs a human looking at a screen. Nightly <code>fetch</code> can never be the thing that links your first bank; it can only keep already-linked ones current.</p><h2 id="why-systemd-not-cron">Why systemd, not cron</h2><p>Worth a short note since it's the kind of decision that's easy to make on autopilot: a nightly job is the textbook cron use case, and I considered it for about as long as it took to remember what debugging a failed cron job actually feels like. Systemd timers won for three concrete reasons, all of which mattered in practice, not just in theory. <code>Persistent=true</code> means a run missed while the machine was off or asleep fires as soon as it's back, which cron doesn't do at all - a laptop or a small home server isn't guaranteed to be up at 3am every single night, and I didn't want "missed the exact minute" to mean "missed the whole day." Logs go to the journal automatically (<code>journalctl -u finance-system-fetch</code>), searchable and timestamped, rather than needing me to redirect output to a log file by hand and remember to rotate it. And a <code>.timer</code>/<code>.service</code> pair is two declarative files I can read top to bottom and understand completely, rather than a crontab line whose syntax I have to look up fresh every time I need to change the schedule. None of that is exotic - it's just systemd being the better-fitted tool once you actually compare them on a target that already runs systemd anyway, which the deploy target here (a Proxmox LXC container) does.</p><h2 id="shipping-it-jenkins-rsync-and-the-first-things-a-real-server-broke">Shipping it: Jenkins, rsync, and the first things a real server broke</h2><p>A service nobody can deploy is still a script. The day after that second commit there was a run of small commits - <code>feat: fixup jenkinsfile</code>, <code>Fixing pre-requs</code>, <code>ci: fixing tests in jenkins</code>, <code>ci: fix deploy script</code> - that built the pipeline the rest of the project ships through. The <code>Jenkinsfile</code> is a multibranch pipeline with five ideas worth recording:</p><ul><li><strong>Tests run in parallel, and fail loudly on drift.</strong> The backend stage runs <code>uv sync --locked</code> (it errors if <code>pyproject.toml</code> and <code>uv.lock</code> disagree, rather than quietly re-resolving) then <code>pytest</code> with coverage; the frontend stage runs <code>npm ci</code>, <code>npm test</code> and <code>npm run build</code>. Both publish JUnit XML.</li><li><strong>Only <code>main</code> deploys.</strong> The Deploy stage is guarded by <code>when { branch 'main' }</code>, so a feature branch gets tested but never touches the server.</li><li><strong>The agent is pinned like local dev is.</strong> Node comes from <code>nodenv</code> and <code>frontend/.node-version</code> rather than a Jenkins tool installation, so CI and my laptop resolve the same version - which matters, because a Node that's too old breaks the Vite bundler with a native-binding error rather than a clear version message. <code>uv</code> is bootstrapped inline.</li><li><strong>Fail-loud settings need fake values in CI.</strong> The <code>Settings</code> class above raises at import time if <code>TL_CLIENT_ID</code>/<code>TL_CLIENT_SECRET</code> are missing, and a clean checkout has no <code>.env</code>, so the pipeline sets obviously fake values in the backend stage's environment. The tests mock every real TrueLayer call, so nothing ever uses them - the cost of "fail on startup" is that CI has to say so explicitly.</li><li><strong>Deploy is <code>rsync</code>, not a registry.</strong> <code>deploy/deploy.sh</code> rsyncs the checkout to <code>/opt/finance-system</code> on the LXC container, then runs <code>deploy/remote-setup.sh</code> there to install the systemd units and nginx config. <code>.env</code> and <code>/storage/</code> are excluded from the <code>--delete</code> sweep so a deploy can't wipe credentials or data (a later fix added the <code>.env</code> exclusion and anchored the <code>storage/</code> one to the repo root).</li></ul><p>The first real server then did what real servers do. One fix (<code>fix sqlite</code>) added <code>check_same_thread=False</code> to the connection: FastAPI runs sync dependencies and route handlers in a worker thread pool, so the connection opened in a request's dependency isn't guaranteed to be used on the same thread, and SQLite's default refuses that. It's safe here because every request opens and closes its own connection, and the commit ships a regression test that uses a connection from another thread. Another commit moved <code>/health</code> to <code>/api/health</code> so nginx's single <code>/api/</code> proxy rule covers it. A third commit cached TrueLayer's bank list at startup so the link-a-bank dropdown doesn't call out on every page load. None of these is interesting alone; together they're the reminder that "works locally" and "runs on a server" are different claims.</p><h2 id="what-service-actually-meant-here">What "service" actually meant here</h2><p>None of this was a big-system rewrite. It was: separate the code that talks to TrueLayer from the code that talks to SQLite; replace a script's temporary local server with the API's own permanent routes; make re-running the fetch idempotent with one primary key and one SQL clause; and hand the whole thing to systemd instead of my own memory of "did I run this recently." Small, individually boring changes. But they're the difference between "a script I run when I remember to" and "a thing that just has correct data in it every morning," which is the actual bar for a personal finance tool to be worth using.</p><p>What didn't exist yet, after this commit, was anywhere to <em>look</em> at that data beyond <code>sqlite3 finance.db</code>. That's next: turning the placeholder frontend into an actual multi-page app.</p><hr><p>Previous: <a href="https://ghost.atathome.me/first-prototype-cli-script/">← The first prototype</a> · Next: <a href="https://ghost.atathome.me/building-the-frontend/">Building the frontend →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Blog automation: Markdown to Ghost on every merge - Part 1]]></title><description><![CDATA[~9 min read

Every project I build gets a blog series. The finance system has nineteen posts, the identity system has seven, and each one is a markdown file that sits in the repo next to the code it describes. That part is easy to love: the posts are diffable, they live in git, and I can write them in the same editor as the code. The part I got tired of was the other half - copying each post into Ghost, fixing the links by hand, setting a publish date, and then doing it all over again when I cor]]></description><link>https://brightbot.co.uk/blog-sync-markdown-to-ghost-on-every-merge/</link><guid isPermaLink="false">Ghost__Post__6ada6a761df6faba86556abe</guid><category><![CDATA[Building Blog Sync]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Thu, 22 Oct 2026 20:00:19 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1600267204091-5c1ab8b10c02?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDI2fHxkb2N1bWVudGF0aW9ufGVufDB8fHx8MTc5MjY4MjE4M3ww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1600267204091-5c1ab8b10c02?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDI2fHxkb2N1bWVudGF0aW9ufGVufDB8fHx8MTc5MjY4MjE4M3ww&ixlib=rb-4.1.0&q=80&w=2000" alt="Blog automation: Markdown to Ghost on every merge - Part 1"/><p><em>~9 min read</em></p><p>Every project I build gets a blog series. The <a href="https://github.com/atownsend247/finance-system">finance system</a> has nineteen posts, the identity system has seven, and each one is a markdown file that sits in the repo next to the code it describes. That part is easy to love: the posts are diffable, they live in git, and I can write them in the same editor as the code. The part I got tired of was the other half - copying each post into Ghost, fixing the links by hand, setting a publish date, and then doing it all over again when I corrected a typo.</p><p>This post is about the tool that removed that half: <code>blog-sync</code>. A merge to <code>main</code> now creates the post on Ghost as a draft, keeps it up to date when I edit it, and queues it to go live a couple of days later. It started life as a script inside finance-system and became a shared package once a second project wanted the same thing, so most of what follows is about the decisions that made it safe to run on every single build.</p><h2 id="the-shape-of-the-problem">The shape of the problem</h2><p>The requirements were short, and each one ruled something out:</p><ul><li><strong>Markdown is the source of truth.</strong> Ghost is where posts are <em>published</em>, not where they're written. If I edit a post in the repo, Ghost should follow.</li><li><strong>Safe to run every build.</strong> I didn't want a "did the blog change?" condition in the Jenkinsfile. If running it twice is harmless, I can run it always.</li><li><strong>Never surprise a reader.</strong> A sync must not publish, unpublish or delete anything on its own.</li><li><strong>Never block a deploy.</strong> The blog is the least important thing a pipeline does. If Ghost is down, the app should still ship.</li></ul><p>Almost every design choice below is one of those four, applied.</p><h2 id="one-folder-one-small-config-file">One folder, one small config file</h2><p>A project's series is a folder of files named <code>NN-slug.md</code>, plus a <code>blog.toml</code>:</p><pre><code>blog/
├── blog.toml
├── 01-why-i-built-it.md
├── 02-first-prototype.md
└── README.md          # series index, not a post
</code></pre><pre><code class="language-toml">tag = "Building Finance System"
</code></pre><p>The number is the series order, the rest is the slug, and the first line of the file is the <code># Title</code>. Anything that doesn't match the <code>NN-name.md</code> pattern - the README, notes, images - is quietly ignored, so the folder can hold what it likes. The tag is the one required setting: every post in the series gets it, which gives each series its own tag page on the blog. Unknown keys in <code>blog.toml</code> are an error, so a typo fails loudly instead of doing nothing.</p><h2 id="making-re-running-safe-hash-the-thing-you-sent">Making re-running safe: hash the thing you sent</h2><p>The core loop is simple. For each post, ask Ghost for the post with that slug:</p><p>| Situation | Action | |---|---| | No post with that slug | create it as a <strong>draft</strong>, tagged with the series tag | | Exists, content changed | update it in place, status left alone | | Exists, content identical | skip |</p><p>The interesting question is "content changed". You can't compare what Ghost returns with what you sent, because Ghost re-renders HTML it receives - the bytes that come back are never the bytes that went in. So the tool doesn't try. It renders the markdown, hashes the title plus the HTML, and stores the first 16 characters of the SHA-256 on the post itself, as a comment in its code injection header:</p><pre><code class="language-python">def content_hash(title, html):
    return hashlib.sha256(f"{title}\n{html}".encode()).hexdigest()[:16]
</code></pre><p>Next run it renders again and compares hashes. Same hash and the right tag means <code>[unchanged]</code> and no write at all, so a build where I changed nothing makes one read request per post and nothing else. A useful side effect: the hash only covers the <em>rendered</em> content, and HTML comments are stripped before rendering. That means the hidden comments I use to note which commits a post covers - or the banner records, which I'll get to - can change freely without ever causing a re-publish.</p><p>Updating is careful about what it touches. It sends Ghost the post's <code>updated_at</code> so a concurrent edit in the editor produces an error rather than a silent overwrite, and it only adds the series tag when it's missing, so tags I added by hand survive.</p><h2 id="the-things-it-refuses-to-do">The things it refuses to do</h2><p>This is the list I'm most glad I wrote down before writing any code:</p><ul><li>It <strong>never changes a post's status.</strong> New posts are drafts. A published post stays published through any number of edits, and a draft stays a draft.</li><li>It <strong>never deletes anything.</strong> Remove a markdown file and the Ghost post stays.</li><li>It <strong>never sends banner images</strong>, and never removes tags I added by hand.</li></ul><p>Each is a trade of convenience for safety. Not deleting means a renamed post can leave an orphan behind that I tidy up manually. That's a small, visible, recoverable cost; the alternative is a pipeline that can delete published posts if I fat-finger a filename. And every mode is a <strong>dry run unless <code>--apply</code> is passed</strong>, so <code>blog-sync</code> on its own just prints what it would do. With no credentials set at all it simply lists the posts it found, which makes it a handy way to check a new series is wired up correctly before anything touches Ghost.</p><h2 id="links-and-where-the-banners-live">Links, and where the banners live</h2><p>Posts link to each other with ordinary relative markdown, which works in the repo and on GitHub:</p><pre><code class="language-markdown">Previous: [← The first prototype](02-first-prototype.md)
</code></pre><p>On the way to Ghost, the tool rewrites those links using the slug map it already has: <code>03-storage.md</code> becomes <code>/storage/</code>, anchors included, and a link to <code>README.md</code> becomes the series' tag page. A link to some other <code>.md</code> file is left alone, and the run prints <code>UNRESOLVED LINKS</code> against that post, so a typo shows up in the build output instead of as a 404 on the live site.</p><p>Banner images go the other way. I pick a feature image in Ghost's editor - it has the Unsplash picker built in, and that's genuinely nicer than hunting for a URL - and <code>blog-sync --pull</code> copies it back into the markdown as a hidden comment under the title:</p><p>Ghost owns the banner, the repo keeps a record of it, and a normal sync never sends banners <em>to</em> Ghost, so it can't overwrite one I set by hand. <code>--pull</code> only ever edits local files, which is why it isn't in the pipeline: a build shouldn't commit to <code>main</code>, and the workspace gets wiped afterwards anyway. I run it by hand before editing a post, and commit the result.</p><h2 id="scheduling-the-part-that-makes-it-feel-automatic">Scheduling: the part that makes it feel automatic</h2><p>Creating drafts is useful. Scheduling them is what turned it from "saves me copying" into "I merge a post and forget about it". <code>blog-sync --schedule --apply</code> works like this:</p><ol><li>Ask Ghost for every scheduled post <strong>carrying this series' tag</strong> and take the latest date.</li><li>The first slot is the day after that, or tomorrow if nothing is queued.</li><li>Walk the series in number order. A draft gets the next slot - 09:00 London time by default, one post every other day - and the slot advances. Anything already published or scheduled is skipped, and anything not yet on Ghost is reported rather than guessed at.</li></ol><p>Because step 1 reads the existing queue, the command is idempotent in exactly the way the sync is: with nothing in draft it changes nothing, and a post I add later joins the back of the queue rather than jumping ahead of ones already waiting. Times are converted from London time to UTC for Ghost, so summer time looks after itself.</p><p>The trade-off is that scheduling is <em>blind to intent</em>. If I put a scheduled post back to draft in Ghost, the next build sees a draft and schedules it again. To hold a post back, the rule is simply: don't merge it. That's a deliberate simplification - git is the single place where "this is ready" gets decided.</p><p>More than one project publishes to the same Ghost site, and the queue is found by tag, so each project keeps its own cadence. Another project's scheduled posts are ignored, which means two series can go out on the same day. I chose that over a single shared queue, where one project's backlog of ten drafts would push every other project's next post weeks out.</p><h2 id="the-pipeline-stage">The pipeline stage</h2><p>The Jenkins side is one stage, after deploy:</p><pre><code class="language-groovy">stage('Sync blog') {
    when { branch 'main' }
    steps {
        catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE') {
            withCredentials([
                string(credentialsId: 'ghost-url', variable: 'GHOST_URL'),
                string(credentialsId: 'ghost-admin-key', variable: 'GHOST_ADMIN_KEY'),
            ]) {
                sh '''
                    run_blog() {
                        uvx --from git+https://github.com/atownsend247/ghost-blog-sync.git@v0.2.0 blog-sync "$@"
                    }
                    run_blog --apply
                    run_blog --schedule --apply
                '''
            }
        }
    }
}
</code></pre><p>Every line of that is one of the four requirements:</p><ul><li><code>when { branch 'main' }</code> - feature branches never touch the blog.</li><li><code>catchError(... UNSTABLE)</code> - a Ghost outage, an expired key or a typo in a post turns the build yellow rather than red, and the deploy that already ran is unaffected. The stage also comes <em>after</em> deploy for the same reason.</li><li><code>run_blog --apply</code> before <code>run_blog --schedule --apply</code> - order matters, since scheduling skips posts that aren't on Ghost yet, and Jenkins' default <code>sh -e</code> stops before the second command if the first fails.</li><li><code>@v0.2.0</code> - the tool is pinned to a release tag, so a change to blog-sync can never break a project's build until I bump that project's tag. I'd avoid <code>@main</code> here.</li><li>No <code>changeset</code> condition - because unchanged posts are skipped, running it every build is cheap, and it also notices edits made in Ghost's editor.</li></ul><p><code>uvx</code> fetches and runs the tool straight from git, so there's nothing to install in the project: no <code>requirements.txt</code> entry, no virtualenv, no vendored script. The agent just needs <code>uv</code> and <code>git</code>. The Admin API credentials are two Jenkins secret-text credentials at global scope, so every project's job can use the same pair, and they come from the environment only - the tool never reads or writes them anywhere else.</p><h2 id="from-one-projects-script-to-a-shared-package">From one project's script to a shared package</h2><p>The first version of this was <code>blog/tools/ghost_publish.py</code>, living inside finance-system and growing one flag at a time: first publishing, then banners, then the scheduler, then the pipeline stage. It worked, and it was the right place to start, because I didn't know what the tool needed to be until I'd used it on a real series.</p><p>The trigger for extracting it was the identity system getting its own blog. The alternatives were copying the script (and then fixing every bug twice), or making it a package. Doing it properly meant a few things the script had quietly assumed:</p><ul><li><strong>The tag was hard-coded</strong>, so it became a <code>tag</code> setting in <code>blog.toml</code>.</li><li><strong>Slugs came straight from file names</strong>, which is fine for one series and a silent overwrite for two: if both projects have a <code>01-introduction.md</code>, the second sync clobbers the first. Hence the optional <code>slug_prefix</code> - the identity system's posts use <code>identity-system-</code>. The catch is that changing a prefix on a series already on Ghost makes every post look new, so it has to be chosen before the first sync. That's why finance-system leaves it unset: its posts were already live.</li><li><strong>The scheduling queue</strong> stays per series, but is now found by tag rather than by the script's own state, so it keeps working when several projects share a blog.</li></ul><p>Moving finance-system over was designed to be invisible. The file names, slugs and hash are unchanged, so the first run after the switch should report every post as <code>[unchanged]</code> and write nothing - and that's the parity check I ran locally, as a dry run against the live blog, before touching the Jenkinsfile. If anything had come back as an update, that would have been a difference to understand rather than a thing to ship. Only then did I swap the pipeline's commands, delete the copied script, and update the docs that told me to run <code>hatch run blog:publish</code>.</p><h2 id="what-it-still-doesnt-do">What it still doesn't do</h2><p>A few honest gaps, because they shape how I use it:</p><ul><li><strong>Projects can collide on a day.</strong> Each series has its own cadence, so two projects can publish on the same morning. That's deliberate, but it means the blog as a whole has no "one post a day" guarantee.</li><li><strong>It's one-way, mostly.</strong> Content flows from the repo to Ghost; only banners come back, and only when I ask. If I edit a post's body in Ghost's editor, the next sync will put the markdown version back - which is the point of markdown being the source of truth, but worth remembering.</li><li><strong>A rendering change touches every post.</strong> Because the hash covers rendered HTML, a release that renders markdown differently would update every post once on the next run. It's harmless, but it's the reason releases are pinned and noted.</li></ul><h2 id="what-this-adds-up-to">What this adds up to</h2><p>None of the pieces is clever. A filename convention, a hash stored on the post, a schedule that reads the queue before it writes, and a pipeline stage that can't fail the build. But together they change the shape of writing: finishing a post is now <code>git merge</code>, and the thing I used to do by hand - a dozen clicks, a date picker, and a link check - happens on its own, a couple of days later, at 09:00. That's the bar for tooling like this: not that it does something impressive, but that I stop thinking about it.</p><hr/>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: The first prototype: a CLI script that links a bank - Part 3]]></title><description><![CDATA[~10 min read

By this point I had sandbox credentials, a registered redirect URI, and a scope string I'd thought through (see the previous post). What I didn't have was any actual code, and I've learned not to trust an integration design until I've built the ugliest possible version of it and watched it work. So the first real artifact in this project wasn't an API, or a database, or a frontend - it was a single ~180-line script, truelayer_sync.py, that did exactly two things: link <bank> and fe]]></description><link>https://brightbot.co.uk/first-prototype-cli-script/</link><guid isPermaLink="false">Ghost__Post__6ad488c11df6faba8655698a</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Wed, 21 Oct 2026 08:00:00 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1619410283995-43d9134e7656?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDd8fEZpbmFuY2UlMjBjb2RlfGVufDB8fHx8MTc5MjMxNjYxNnww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1619410283995-43d9134e7656?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDd8fEZpbmFuY2UlMjBjb2RlfGVufDB8fHx8MTc5MjMxNjYxNnww&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: The first prototype: a CLI script that links a bank - Part 3"/><p><em>~10 min read</em></p><p>By this point I had sandbox credentials, a registered redirect URI, and a scope string I'd thought through (see the <a href="https://ghost.atathome.me/developer-access-and-app-setup/">previous post</a>). What I didn't have was any actual code, and I've learned not to trust an integration design until I've built the ugliest possible version of it and watched it work. So the first real artifact in this project wasn't an API, or a database, or a frontend - it was a single ~180-line script, <code>truelayer_sync.py</code>, that did exactly two things: <code>link &lt;bank&gt;</code> and <code>fetch</code>. No web server, no persistence layer beyond a JSON file, no error handling beyond what <code>sys.exit</code> gives you for free. The point wasn't elegance, it was proving the OAuth mechanics actually worked the way the docs said they would.</p><p><em>A note on names, for anyone following along in the git history: the script's own docstring calls it <code>truelayer_sync.py</code>, but the first commit that contains it filed it as <code>true_layer/check_banks_truelayer.py</code> - it started life as the TrueLayer half of the provider comparison in the previous posts, and grew <code>link</code> and <code>fetch</code> commands from there. It was renamed into the package as <code>src/finance_system/truelayer.py</code> in the initial backend commit, which is where the backend skeleton first appears.</em></p><h2 id="the-redirect-problem-solved-the-cheap-way">The redirect problem, solved the cheap way</h2><p>Authorization code flow needs a redirect URI that can receive the authorization code after the user approves access at their bank. In a real web app that's a route on your server. In a CLI script running on my laptop, there is no server - so I made one, just for the duration of the flow:</p><pre><code class="language-python">def wait_for_code():
    """Run a tiny local server that catches the redirect and returns the auth code."""
    result = {}

    class Handler(BaseHTTPRequestHandler):
        def do_GET(self):
            query = parse_qs(urlparse(self.path).query)
            result["code"] = query.get("code", [None])[0]
            result["error"] = query.get("error", [None])[0]
            self.send_response(200)
            self.end_headers()
            self.wfile.write(b"Done - you can close this tab.")

        def log_message(self, *args):
            pass

    HTTPServer(("localhost", 3000), Handler).handle_request()
    if result.get("error"):
        sys.exit(f"Bank linking failed: {result['error']}")
    return result["code"]
</code></pre><p><code>HTTPServer(...).handle_request()</code> - not <code>serve_forever()</code> - is the detail that makes this work as a <em>script</em> rather than a service: it starts a server, blocks until exactly one request comes in, handles it, and returns. Combined with the redirect URI I'd registered (<code>http://localhost:3000/callback</code>), the flow became: open a browser tab to TrueLayer's hosted consent page, block on <code>wait_for_code()</code>, and the moment the browser gets redirected back with a <code>?code=...</code> query param, the script wakes up with it in hand. No polling, no webhook, no server that needs to keep running after the script exits.</p><pre><code class="language-python">def link(label):
    auth_url = f"{AUTH_HOST}/?" + urlencode({
        "response_type": "code",
        "client_id": CLIENT_ID,
        "redirect_uri": REDIRECT_URI,
        "scope": SCOPES,
        "providers": PROVIDERS,
    })
    print("Opening browser to link your bank...")
    webbrowser.open(auth_url)

    code = wait_for_code()
    tokens = token_request({
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": REDIRECT_URI,
    })

    all_tokens = load_tokens()
    all_tokens[label] = {"refresh_token": tokens["refresh_token"]}
    save_tokens(all_tokens)
    print(f"Linked '{label}'.")
</code></pre><p><code>label</code> here is just whatever name I pass on the command line - <code>monzo</code>, <code>nationwide-cc</code>, whatever I want to call it locally. TrueLayer doesn't know or care what I call it; it's purely a key in my own <code>tokens.json</code> so I can tell my accounts apart later. Note what gets stored: not the access token (useless after about an hour) but the <strong>refresh token</strong>, which is what <code>offline_access</code> scope buys you, and what lets <code>fetch</code> run unattended without a browser in sight.</p><h2 id="storage-thats-really-just-a-dict-and-a-json-file">Storage that's really just a dict and a JSON file</h2><p><code>load_tokens</code> and <code>save_tokens</code> are about as unglamorous as code gets, and that was entirely the point at this stage:</p><pre><code class="language-python">TOKENS_FILE = Path("tokens.json")  # sensitive - never commit this file

def load_tokens():
    return json.loads(TOKENS_FILE.read_text()) if TOKENS_FILE.exists() else {}

def save_tokens(tokens):
    TOKENS_FILE.write_text(json.dumps(tokens, indent=2))
</code></pre><p>No database, no schema, no migrations - a dict keyed by label, dumped as JSON, read back in on the next run. I could open <code>tokens.json</code> in a text editor at any point and see exactly what state the script thought it was in, which turned out to be a genuinely useful debugging property in its own right: when the second run's refresh failed (more on that below), the first thing I did was just look at the file, and the stale refresh token was immediately obvious sitting there in plain text. A "real" database at this stage would have added ceremony without adding anything I actually needed yet - table definitions, a connection to manage, a query to write just to answer "what got saved." That trade only flips once you need things a flat file genuinely can't do well, like concurrent access or querying by a field other than the key - which is exactly what justified SQLite a few commits later, not before.</p><h2 id="fetching-the-boring-but-important-part">Fetching, the boring but important part</h2><p><code>fetch()</code> is where the actual value lives, and it's almost entirely plumbing: for every bank I'd linked, swap the stored refresh token for a fresh access token, list its accounts and cards, then pull transactions for each one.</p><pre><code class="language-python">def fetch(days=90):
    all_tokens = load_tokens()
    if not all_tokens:
        sys.exit("No banks linked yet - run: python truelayer_sync.py link &lt;name&gt;")

    date_range = {
        "from": (date.today() - timedelta(days=days)).isoformat(),
        "to": date.today().isoformat(),
    }
    output = []

    for label, stored in all_tokens.items():
        # Access tokens last about an hour, so swap the refresh token for a fresh one.
        tokens = token_request({
            "grant_type": "refresh_token",
            "refresh_token": stored["refresh_token"],
        })
        all_tokens[label]["refresh_token"] = tokens["refresh_token"]  # it rotates
        access = tokens["access_token"]

        sources = [("accounts", a["account_id"], a["display_name"]) for a in get(access, "/accounts")]
        sources += [("cards", c["account_id"], c["display_name"]) for c in get(access, "/cards")]

        for kind, account_id, name in sources:
            txns = get(access, f"/{kind}/{account_id}/transactions", date_range)
            ...
</code></pre><p>A few things in here turned out to matter a lot more later than they looked like they would at the time:</p><p><strong>Refresh tokens rotate.</strong> <code>all_tokens[label]["refresh_token"] = tokens["refresh_token"]</code> isn't defensive copying, it's load-bearing. TrueLayer issues a new refresh token every time you use one, and if you don't save the new one, the next refresh fails with the old one already invalidated. I found this the hard way on the second run of the script, when <code>fetch</code> worked once and then errored on every subsequent call until I noticed the token file wasn't being rewritten after a successful refresh.</p><p><strong>One <code>get()</code> helper handles a provider-specific quirk.</strong> Not every bank supports every endpoint - my Monzo connection has no <code>/cards</code>, so TrueLayer returns a <code>501 Not Implemented</code> for that call rather than an empty list. Treating that as "no cards for this bank" instead of an error, right in the shared helper, meant every call site downstream didn't need to know or care which banks have cards:</p><pre><code class="language-python">def get(access_token, path, params=None):
    resp = requests.get(
        f"{API_HOST}/data/v1{path}",
        headers={"Authorization": f"Bearer {access_token}"},
        params=params,
    )
    if resp.status_code == 501:  # endpoint not supported by this bank (e.g. no cards)
        return []
    resp.raise_for_status()
    return resp.json()["results"]
</code></pre><p><strong><code>kind</code> (<code>"accounts"</code> or <code>"cards"</code>) travels with each source all the way through the loop</strong>, because the transactions endpoint path differs - <code>/accounts/{id}/transactions</code> vs <code>/cards/{id}/transactions</code>. It's a small thing, but structuring <code>sources</code> as a flat list of <code>(kind, id, name)</code> tuples up front, rather than handling accounts and cards as two separate code paths, is a pattern that survived essentially unchanged all the way to the current codebase.</p><p>The rest is shaping TrueLayer's transaction object into something flatter and easier to work with downstream - <code>bank</code>, <code>account</code>, <code>id</code>, <code>date</code>, <code>description</code>, <code>merchant</code>, <code>amount</code>, <code>currency</code>, <code>bank_category</code> - and dumping the whole list to <code>transactions.json</code> at the end.</p><h2 id="what-this-version-got-right">What this version got right</h2><p>For a script I expected to throw away, a surprising amount of it didn't get thrown away. The <code>link</code> / <code>fetch</code> split - one interactive step that needs a browser, one unattended step that doesn't - is still exactly the shape of the real system today, just with <code>link</code>'s browser-opening replaced by a proper web redirect and <code>fetch</code> running on a nightly timer instead of by hand. The refresh-token rotation handling, the 501-as-empty-list treatment, the <code>(kind, account_id, name)</code> tuple shape: all still there, close to verbatim, several rewrites later.</p><h2 id="why-a-cli-first-and-not-a-minimal-web-app">Why a CLI first, and not a minimal web app</h2><p>It would have been entirely possible to skip straight to a FastAPI app with a <code>/link</code> and <code>/callback</code> route instead of a local HTTP server that lives for one request. I deliberately didn't, and it's worth explaining why rather than treating it as an obvious choice, because it wasn't obvious to me until partway through.</p><p>A web app, even a minimal one, means a process that stays running, a port that has to be free, and - if I'm testing the <em>deployed</em> shape of things - a place to actually put it. None of that helps answer the one question this stage of the project needed answered: does the OAuth exchange work the way the docs describe, against a real (or sandbox) TrueLayer environment, with my actual credentials? A CLI script that runs, does one thing, and exits is the fastest possible loop for answering that - I could change one line, re-run <code>python truelayer_sync.py link monzo</code>, and know within seconds whether that change helped, with no server to restart, no port conflicts from a previous run I forgot to kill, nothing else in the way. Collapsing "validate the integration" and "build the real service" into one step would have meant every OAuth debugging cycle also paying the cost of a web server's startup and routing, for no benefit at this stage. Keeping them separate meant the slow, careful part (getting a web service's shape right) only had to happen once, after the fast, disposable part (does this API actually work the way I think) had already answered the questions that mattered.</p><h2 id="what-it-obviously-couldnt-do">What it obviously couldn't do</h2><p>It also made very clear, very quickly, what it <em>couldn't</em> do, which is really the point of building the throwaway version first:</p><ul><li><strong>It only worked on my laptop.</strong> <code>webbrowser.open()</code> and a <code>localhost:3000</code> callback server assume there's a browser and a human sitting right there. No deploying this anywhere.</li><li><strong>No de-duplication.</strong> Every <code>fetch</code> overwrote <code>transactions.json</code> wholesale. Fine for a script I ran by hand a few times; not fine for something meant to run nightly and accumulate history.</li><li><strong><code>tokens.json</code> sitting on disk in plaintext</strong> was acceptable for an evening's experiment and not acceptable for anything I'd trust with real account access longer-term.</li><li><strong>No real error handling.</strong> A <code>sys.exit()</code> on missing tokens is fine for a CLI; it's not something you can build a service around.</li></ul><p>None of that mattered yet. The only question this version of the code needed to answer was "does the OAuth flow work, end to end, against my real banks" - and by the time I had a <code>transactions.json</code> file sitting on disk with real Monzo transactions in it, formatted the way I wanted, the answer was yes. Everything after this post is about turning that yes into something that could run unattended, store data properly, and be looked at from more than a terminal.</p><hr><p>Previous: <a href="https://ghost.atathome.me/developer-access-and-app-setup/">← Developer access and app setup</a> · Next: <a href="https://ghost.atathome.me/from-script-to-service/">From script to service →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: Developer access and app setup - Part 2]]></title><description><![CDATA[~10 min read

With TrueLayer picked as the data provider (see the previous post), the next step was the unglamorous part every API integration starts with: get an account, register an application, get credentials, and figure out exactly what permissions to ask for. This post is that setup, written down properly so I don't have to reconstruct it from memory the next time I need to do it again - for a second project, or when the production credentials need rotating.


Signing up and creating an ap]]></description><link>https://brightbot.co.uk/developer-access-and-app-setup/</link><guid isPermaLink="false">Ghost__Post__6ad488c01df6faba86556985</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sun, 18 Oct 2026 09:43:17 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1724304406928-c43b01912fa1?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDEwfHxGaW5hbmNlJTIwY2xhY3VsYXRvcnxlbnwwfHx8fDE3OTIzMTY1MTB8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1724304406928-c43b01912fa1?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDEwfHxGaW5hbmNlJTIwY2xhY3VsYXRvcnxlbnwwfHx8fDE3OTIzMTY1MTB8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: Developer access and app setup - Part 2"/><p><em>~10 min read</em></p><p>With TrueLayer picked as the data provider (see <a href="https://ghost.atathome.me/choosing-a-data-provider/">the previous post</a>), the next step was the unglamorous part every API integration starts with: get an account, register an application, get credentials, and figure out exactly what permissions to ask for. This post is that setup, written down properly so I don't have to reconstruct it from memory the next time I need to do it again - for a second project, or when the production credentials need rotating.</p><h2 id="signing-up-and-creating-an-application">Signing up and creating an application</h2><p>TrueLayer's developer Console (console.truelayer.com) is a normal self-serve signup - email, password, no sales call required, which matters for a side project where I want to be writing code the same evening I decide to start. Once in, the first real decision is creating an <strong>application</strong>, and the thing that's easy to miss on a first pass: <strong>sandbox and production are separate applications with separate credentials</strong>, not a toggle on one app.</p><p>I created the sandbox application first. There was no reason to touch production credentials before the sandbox flow worked end to end - and every OAuth integration has a token-exchange bug waiting to be found, so better to find it against a Mock Bank than a real one.</p><p>Each application, sandbox or production, gives you exactly two things you need: a <strong>Client ID</strong> and a <strong>Client Secret</strong>. These go straight into the environment, never into version control:</p><pre><code>TL_CLIENT_ID=...
TL_CLIENT_SECRET=...
TL_IS_SANDBOX=True
</code></pre><p>That <code>TL_IS_SANDBOX</code> flag is doing more work than it looks like. It's read once at startup and decides which host everything downstream talks to:</p><pre><code class="language-python">AUTH_HOST = "https://auth.truelayer-sandbox.com" if settings.tl_is_sandbox else "https://auth.truelayer.com"
API_HOST = "https://api.truelayer-sandbox.com" if settings.tl_is_sandbox else "https://api.truelayer.com"
</code></pre><p>Get sandbox credentials pointed at the production host, or vice versa, and every request fails authentication - not with a helpful "wrong environment" message, just a generic auth failure. The fix is boring but worth stating plainly: when you flip <code>TL_IS_SANDBOX</code>, swap the credential pair to match. I keep sandbox and production credentials in separate <code>.env</code> files rather than commenting lines in and out of one, specifically so I can't forget the second half of that swap.</p><h2 id="keeping-credentials-out-of-version-control">Keeping credentials out of version control</h2><p>This is obvious enough that it barely needs stating, except that "obvious" and "actually done consistently" aren't the same thing, so it's worth being explicit about the mechanics rather than just the principle. Both <code>.env</code> files - sandbox and production - went into <code>.gitignore</code> from the very first commit that introduced them, and a <code>.env.example</code> with the same variable names but empty/placeholder values went into the repo instead:</p><pre><code>TL_CLIENT_ID=
TL_CLIENT_SECRET=
TL_IS_SANDBOX=True
</code></pre><p>That split matters for two reasons beyond "don't leak secrets." First, it means anyone (including future me, on a new machine) can see exactly what environment variables the app expects without grepping through source for every <code>os.environ[...]</code> call. Second, it makes the <em>absence</em> of a value loud - <code>pydantic-settings</code> validates required fields at startup, so a missing <code>TL_CLIENT_ID</code> fails immediately and clearly on boot rather than quietly failing the first time something tries to make an API call. Given the alternative - a bare <code>os.environ["TL_CLIENT_ID"]</code> scattered somewhere deep in a request handler, failing only when that code path first runs - validating configuration at startup, before the app accepts any traffic at all, is worth the small extra ceremony of a settings class.</p><h2 id="registering-the-redirect-uri">Registering the redirect URI</h2><p>OAuth authorization code flow needs somewhere to send the user back to once they've approved (or declined) access at their bank. That's the redirect URI, and TrueLayer needs it registered in advance, in the Console, under <strong>Allowed Redirect URIs</strong> - it won't redirect anywhere that isn't on that list, which is a sensible anti-hijacking measure but means you register it <em>before</em> you can test anything, not as you go.</p><p>For local development that's:</p><pre><code>http://localhost:8000/api/providers/truelayer/callback
</code></pre><p>matching wherever the backend actually listens. The Console lets you register more than one URI, which turned out to matter later - once I deployed this somewhere real, I added the production URL (<code>https://yourdomain/api/providers/truelayer/callback</code>) as a second entry rather than swapping the local one out. Both work simultaneously, so local development against the deployed app's credentials never breaks just because I'm testing from my laptop.</p><p>This is also the point where the split from earlier pays off again: sandbox and production are different applications, so they each need this registered independently. Forgetting to register the redirect URI on the production app until you're mid-deploy is a very findable mistake - it fails in a way that's easy to diagnose (TrueLayer just won't redirect back) - but it's one less thing to hit if you remember it's a per-application setting up front.</p><h2 id="deciding-on-scopes">Deciding on scopes</h2><p>The scope string is the other thing that has to be right before anything else works, because unlike almost everything else in this setup, <strong>you can't add scopes to an existing consent after the fact</strong> - if a user's already linked their bank and you decide you need another scope later, they have to go through the consent flow again.</p><p>I settled on:</p><pre><code class="language-python">SCOPES = "info accounts balance cards transactions offline_access"
</code></pre><p>Working through why each one's there:</p><ul><li><strong><code>info</code></strong> - basic account holder information. Not strictly needed for a transactions-only tool, but cheap to ask for up front rather than discover a gap later.</li><li><strong><code>accounts</code></strong> - lists the bank/current accounts under a connection. Required baseline.</li><li><strong><code>cards</code></strong> - same, but for credit cards. Two of my five linked banks (Nationwide, M&amp;S) are cards, not current accounts, so this isn't optional for me.</li><li><strong><code>balance</code></strong> - I didn't use this at first. I added it to the scope string well before I actually built anything that reads a balance, purely because re-consenting later is annoying. It sat unused for a while; when I did eventually want to show account balances on the dashboard, the scope was already there and every existing connection already had it granted. Asking for a scope you might need later, rather than the exact minimum today, is a reasonable trade for a single-user tool where the "cost" of over-asking is just a slightly longer consent screen you're showing yourself.</li><li><strong><code>transactions</code></strong> - the actual point of the project.</li><li><strong><code>offline_access</code></strong> - gets you a refresh token alongside the access token. Access tokens are short-lived (about an hour); without this scope I'd be asking to re-authenticate with the bank constantly instead of refreshing silently in the background.</li></ul><h2 id="the-mock-bank">The Mock Bank</h2><p>With credentials and scopes in place, the sandbox environment's Mock Bank is where the OAuth flow actually gets exercised for the first time. Starting the auth flow against the sandbox host presents a fake bank login screen - no real credentials, no real 2FA, just a "pretend to be a bank" UI that TrueLayer provides specifically for this. Approving it redirects back with a real authorization code, exchangeable for a real (sandbox) access and refresh token pair, against a fake account with fabricated transaction history.</p><p>This is worth dwelling on because it's the payoff from the provider choice in the last post: I could run the entire link-a-bank-and-pull-transactions flow, top to bottom, as many times as I wanted, before ever pointing this at a real Nationwide or Monzo login. Every bug in the token exchange, every "wait, which field is the account ID in the response," got found against data that didn't matter.</p><h2 id="what-the-token-lifetimes-actually-mean-in-practice">What the token lifetimes actually mean in practice</h2><p>It's worth being concrete about <code>offline_access</code>, because "you get a refresh token" undersells what it actually buys. TrueLayer's access tokens last about an hour. Without a refresh token, that means every single sync - even an unattended, scheduled one - would need a human to re-approve access at the bank's login page roughly once an hour, which makes "nightly automated sync" simply impossible. The refresh token, by contrast, is long-lived (bounded mostly by how long the underlying bank consent stays valid, typically around ninety days under UK Open Banking rules before the user needs to reconfirm), and can be exchanged for a fresh access token as many times as needed without any further human involvement.</p><p>That distinction is the entire reason <code>offline_access</code> had to be decided correctly at this stage rather than added later: everything about running this unattended, on a timer, without a browser open, depends on having a refresh token from the very first successful consent. Get the scope string wrong here and the symptom doesn't show up during initial testing - it shows up an hour into the first unattended run, when the access token expires and there's nothing to refresh it with.</p><h2 id="sandbox-vs-production-one-more-time">Sandbox vs production, one more time</h2><p>The theme of this whole post, if there is one, is: <strong>treat sandbox and production as two genuinely separate integrations that happen to share code</strong>, not one integration with a flag. Separate Console applications, separate credentials, separate redirect URI registrations, both requiring the scope string to be right before any real consent happens. It's more setup than "here's an API key, go," but none of it is <em>hard</em> - it's just easy to half-do and then lose an evening to a confusing auth failure that turns out to be sandbox credentials pointed at the production host.</p><p>With that in place - a Console account, sandbox credentials working end to end against the Mock Bank, and a scope string that wouldn't need revisiting - there was finally something to build against. Next post: the first actual code, a single CLI script that could link one bank and pull its transactions to a JSON file.</p><hr><p><em>This post has no code of its own - it is console setup. The steps were later written up in <code>docs/providers.md</code>, and the <code>.env</code> layout is in <code>.env.example</code>.</em></p><p>Previous: <a href="https://ghost.atathome.me/choosing-a-data-provider/">← Choosing a data provider</a> · Next: <a href="https://ghost.atathome.me/first-prototype-cli-script/">The first prototype →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Personal finance aggregator: Choosing a data provider: TrueLayer vs Enable Banking - Part 1]]></title><description><![CDATA[~10 min read

I wanted one place to see everything I was spending, across six accounts at five banks that I actually use day-to-day: a Nationwide current account, a Nationwide credit card, Monzo, Tesco Bank, Virgin Money, and an M&S Bank credit card. None of these banks talk to each other, none of them export in a format the others understand, and I was tired of opening five apps to answer "how much did I actually spend this month." So: a personal finance aggregator. Pull everything into one SQL]]></description><link>https://brightbot.co.uk/choosing-a-data-provider/</link><guid isPermaLink="false">Ghost__Post__6ad488be1df6faba8655697e</guid><category><![CDATA[Building Finance System]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sun, 18 Oct 2026 09:42:23 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1631511258193-252ab3da6b8b?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fEZpbmFuY2UlMjBjbGFjdWxhdG9yfGVufDB8fHx8MTc5MjMxNjUxMHww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1631511258193-252ab3da6b8b?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fEZpbmFuY2UlMjBjbGFjdWxhdG9yfGVufDB8fHx8MTc5MjMxNjUxMHww&ixlib=rb-4.1.0&q=80&w=2000" alt="Personal finance aggregator: Choosing a data provider: TrueLayer vs Enable Banking - Part 1"/><p><em>~10 min read</em></p><p>I wanted one place to see everything I was spending, across six accounts at five banks that I actually use day-to-day: a Nationwide current account, a Nationwide credit card, Monzo, Tesco Bank, Virgin Money, and an M&amp;S Bank credit card. None of these banks talk to each other, none of them export in a format the others understand, and I was tired of opening five apps to answer "how much did I actually spend this month." So: a personal finance aggregator. Pull everything into one SQLite database, categorise it, look at it in one place.</p><p>The interesting design decision wasn't the database schema or the frontend framework. It was much earlier than that: how do you actually <em>get</em> transaction data out of a UK bank programmatically? You don't get to talk to Nationwide's or Monzo's APIs directly as a hobbyist - you go through an Open Banking aggregator, a company that's done the compliance work to sit between you and every bank's own (wildly inconsistent) API, and exposes one normalised API on top. In the UK that space has a few players - TrueLayer, Plaid, Yapily, Enable Banking, Tink - and picking one is closer to picking a foundation than picking a library, because your whole data model downstream inherits their quirks.</p><p>I evaluated two: TrueLayer and Enable Banking. Here's how, and why TrueLayer won.</p><h2 id="what-i-actually-needed">What I actually needed</h2><p>Before comparing anything, I wrote down the non-negotiables:</p><ul><li><strong>Coverage</strong> of my five specific banks/cards, not just "UK coverage" in the abstract - some aggregators are strong on the big five (Barclays, HSBC, Lloyds, NatWest, Santander) and weaker on challenger banks like Monzo or smaller building societies like Nationwide.</li><li><strong>A sandbox I could develop against</strong> without touching my real accounts on every test run. Open Banking consent flows involve redirecting to your real bank and authenticating there - fine once, painful to repeat fifty times while debugging a token refresh bug.</li><li><strong>A manageable auth model.</strong> I'm one person building this in spare evenings, not a fintech with a security team. Whatever the integration looked like needed to be something I could reason about end to end.</li><li><strong>Reasonable free-tier or sandbox access.</strong> This is a personal project, not a startup with a credit card on file for API calls.</li></ul><h2 id="providers-i-ruled-out-without-a-deep-evaluation">Providers I ruled out without a deep evaluation</h2><p>Worth being honest about the providers that didn't make it to a real comparison at all, and why, because "I didn't evaluate X" is a decision too, just a cheaper one.</p><p><strong>Plaid</strong> is the name most people reach for first, and for good reason - it's probably the best-documented aggregator API that exists. But Plaid's UK/EU Open Banking coverage has historically been a secondary market for them behind US bank connectivity, and a few minutes of searching turned up enough uncertainty about Nationwide and Monzo support specifically that I didn't want to sink an evening finding out the hard way. If this were a US project, Plaid would have been the first and probably only candidate evaluated.</p><p><strong>Yapily</strong> and <strong>Tink</strong> both looked plausible on paper - UK-focused, proper Open Banking coverage - and I'd put either one ahead of Enable Banking if I were doing this again with more time to spend on the comparison. I stopped at two candidates mostly for the mundane reason that evaluating an aggregator means actually registering, reading auth docs, and writing a throwaway script for each one, and two afternoons of that felt like the right amount for a side project. This is worth naming plainly rather than implying TrueLayer beat five contenders in some rigorous bake-off - it beat one real contender, on top of a short list of others I judged unlikely to change the outcome and didn't spend time confirming.</p><h2 id="enable-banking-interesting-but-a-heavier-lift">Enable Banking: interesting, but a heavier lift</h2><p>Enable Banking's Data API is JWT-based. You register an application in their control panel, and instead of getting a client ID and secret, you get an <strong>application ID and a downloaded private key file</strong>. Every API call means signing your own JWT:</p><pre><code class="language-python">def make_token():
    with open(KEY_PATH, "rb") as f:
        private_key = f.read()
    now = int(time.time())
    return jwt.encode(
        {
            "iss": "enablebanking.com",
            "aud": "api.enablebanking.com",
            "iat": now,
            "exp": now + 3600,  # valid for 1 hour
        },
        private_key,
        algorithm="RS256",
        headers={"kid": APP_ID},
    )
</code></pre><p>That's not <em>hard</em>, exactly - <code>pyjwt</code> and <code>cryptography</code> do the actual work - but it's a different category of thing to get right than "store a client secret." Now I'm also responsible for keeping a private key file out of version control (on top of the usual <code>.env</code>), rotating it if it leaks, and understanding RS256 well enough to debug it when a token gets rejected. For a side project, that's overhead I'd rather not carry.</p><p>I did get far enough to list available banks:</p><pre><code class="language-python">resp = requests.get(
    "https://api.enablebanking.com/aspsps",
    params={"country": "GB"},
    headers={"Authorization": f"Bearer {make_token()}"},
)
banks = resp.json()["aspsps"]
for bank in banks:
    if any(name in bank["name"].lower() for name in MY_BANKS):
        print(bank["name"], "-", bank.get("psu_types"))
</code></pre><p>Coverage looked fine on paper - all five of my banks showed up. But two things gave me pause. First, <code>psu_types</code> (personal vs business customer) varied per bank in ways I didn't fully understand without reading deeper into their docs - it wasn't obvious upfront whether a given bank supported the consumer flow I needed. Second, and more importantly: <strong>I couldn't find a sandbox with a mock bank</strong>. Enable Banking's docs pointed toward testing against real ASPSPs (the actual banks) in most cases. That meant every test run of my linking flow would mean a real trip through my actual bank's login page. Workable, but it slows down iteration a lot when you're still shaping the basic flow.</p><h2 id="truelayer-a-normal-oauth2-flow-and-a-real-sandbox">TrueLayer: a normal OAuth2 flow, and a real sandbox</h2><p>TrueLayer's Data API, by contrast, is standard OAuth2 authorization code flow - the same shape as "Sign in with Google." You get a client ID and client secret from their Console, same as any OAuth app registration you've done before:</p><pre><code class="language-python">AUTH_HOST = "https://auth.truelayer-sandbox.com" if SANDBOX else "https://auth.truelayer.com"
API_HOST = "https://api.truelayer-sandbox.com" if SANDBOX else "https://api.truelayer.com"
PROVIDERS = "uk-cs-mock" if SANDBOX else "uk-ob-all uk-oauth-all"

CLIENT_ID = os.environ["TL_CLIENT_ID"]
CLIENT_SECRET = os.environ["TL_CLIENT_SECRET"]
SCOPES = "info accounts balance cards transactions offline_access"
</code></pre><p>Two things stand out in that snippet, and both mattered for the decision.</p><p>The first is <code>AUTH_HOST</code>/<code>API_HOST</code> switching on a <code>SANDBOX</code> flag pointing at entirely separate hostnames (<code>auth.truelayer-sandbox.com</code> vs <code>auth.truelayer.com</code>). TrueLayer ships a genuine sandbox environment with a <strong>Mock Bank</strong> - <code>uk-cs-mock</code> as the provider ID - that you authenticate against with fake credentials, returning realistic-looking (fabricated) accounts and transactions. That meant I could build and rebuild the entire OAuth dance, the token exchange, the transaction pull, however many times I wanted, without ever touching a real bank login page until the integration actually worked.</p><p>The second is that <code>SCOPES</code> string. TrueLayer scopes data access the way you'd expect from any OAuth provider: <code>accounts</code>, <code>balance</code>, <code>cards</code>, <code>transactions</code>, plus <code>offline_access</code> for a refresh token so I'm not asking the user to re-authenticate every hour. <code>info</code> gets you basic account holder info. It reads like every other OAuth integration I've done, which is exactly what I wanted from something I'll be maintaining alone.</p><h2 id="checking-real-coverage">Checking real coverage</h2><p>Before committing, I wrote the equivalent bank-listing check against TrueLayer's public providers endpoint (no auth required for this one - it's just metadata):</p><pre><code class="language-python">resp = requests.get(f"{AUTH_HOST}/api/providers")
providers = resp.json()
for p in providers:
    if any(name in p["display_name"].lower() for name in MY_BANKS):
        print(p["provider_id"], p["display_name"], p["country"])
</code></pre><p>All five showed up under sensible provider IDs (<code>ob-nationwide</code>, <code>ob-monzo</code>, <code>ob-tesco-bank</code>, and so on - I'm working from memory of the exact IDs here, but the pattern held). Between that and the sandbox, TrueLayer covered everything I needed to actually start building, and let me build the linking flow and the transaction pull entirely against the Mock Bank first, with zero risk to my real accounts while I was still getting the OAuth mechanics right.</p><h2 id="the-consent-experience-itself">The consent experience itself</h2><p>One more thing that only became obvious once I actually ran both flows, not just read the docs: what the user - me - actually sees during consent matters more than I expected going in. TrueLayer's is a <strong>hosted consent page</strong>: you redirect to a TrueLayer domain, pick your bank from a list (or, if you already know which one, pass a <code>provider_id</code> to skip straight to it), and TrueLayer handles the visual back-and-forth with the bank's own login before redirecting you home. It looks polished, and critically, it looks the <em>same</em> regardless of which bank you picked - TrueLayer owns that whole surface.</p><p>Enable Banking's flow, from what I could piece together without fully building it, redirects more directly toward each ASPSP's own authentication surface, which in practice means the experience varies bank to bank in ways that are harder to predict or test for up front. Neither approach is wrong - PSD2 mandates the bank ultimately authenticates you regardless of who's brokering the flow - but "one consistent hosted screen I can screenshot and reason about" was a real point in TrueLayer's favour for something I was going to be linking and re-linking a handful of times while debugging.</p><h2 id="the-decision">The decision</h2><p>I picked TrueLayer for three reasons, in order of how much they actually mattered once I started building:</p><ol><li><strong>The sandbox.</strong> Being able to iterate on the OAuth flow against a mock bank, dozens of times, without touching real credentials, was worth more than I expected going in. Bugs in a token-refresh loop are much less stressful to debug when the "bank" is fake.</li><li><strong>A conventional auth model.</strong> Client ID, client secret, authorization code, refresh token. No private key file to protect, no JWT signing code of my own to get right. One less category of thing that could go subtly wrong.</li><li><strong>Coverage of the banks I actually use.</strong> Both providers had this on paper, so it came down to the other two factors - but it's worth flagging that this check happens <em>first</em>, always. Neither of the other two points matters if the bank you need isn't there.</li></ol><p>What I didn't weigh heavily, and would if I were doing this commercially: cost at scale, rate limits in production, and the breadth of European bank coverage. TrueLayer's free/sandbox tier and reasonable production pricing were enough for a single-user tool with a handful of linked accounts; that calculus would look different building something for other people to use.</p><p>The <code>enable_banking/</code> and <code>true_layer/</code> evaluation scripts are still sitting in the repo's history, artifacts of an afternoon spent figuring this out before writing a single line of the actual application. The TrueLayer one didn't stay a throwaway: it's the file that grew <code>link</code> and <code>fetch</code> commands and became the prototype in post 3. Next post: what it actually took to get a working TrueLayer Console app and credentials in hand, sandbox and production both.</p><hr><p>Next: <a href="https://ghost.atathome.me/developer-access-and-app-setup/">Developer access and app setup →</a></p></hr>]]></content:encoded></item><item><title><![CDATA[Verifying Your GitHub Commits with GPG or SSH]]></title><description><![CDATA[If you’ve been following along with the previous posts on managing multiple Git identities and multiple SSH keys, this next step adds a nice layer of polish — verified commits.

You’ve probably noticed some commits on GitHub have a little “Verified” badge next to them.
That badge tells others (and your future self) that GitHub has confirmed the commit really came from you — not someone impersonating your name and email.

Let’s walk through how to set up commit signing for your personal and work ]]></description><link>https://brightbot.co.uk/verifying-your-github-commits-with-gpg-or-ssh/</link><guid isPermaLink="false">Ghost__Post__68e4237264bc86d5eba401d5</guid><category><![CDATA[Infrastructure]]></category><category><![CDATA[Ansible]]></category><category><![CDATA[AWS]]></category><category><![CDATA[Home Lab]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Mon, 06 Oct 2025 20:28:52 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1728496120908-4fa5eb92ebee?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fHNpZ25lZHxlbnwwfHx8fDE3NTk3ODI1MTd8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1728496120908-4fa5eb92ebee?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fHNpZ25lZHxlbnwwfHx8fDE3NTk3ODI1MTd8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Verifying Your GitHub Commits with GPG or SSH"/><p>If you’ve been following along with the previous posts on managing <a href="https://ghost.atathome.me/managing-multiple-git-authors-by-directory/" rel="noreferrer">multiple Git identities</a> and <a href="https://ghost.atathome.me/managing-multiple-git-ssh-keys-by-directory/" rel="noreferrer">multiple SSH keys</a>, this next step adds a nice layer of polish — <strong>verified commits</strong>.</p><p>You’ve probably noticed some commits on GitHub have a little <strong>“Verified”</strong> badge next to them.<br>That badge tells others (and your future self) that GitHub has confirmed the commit really came from you — not someone impersonating your name and email.</br></p><p>Let’s walk through how to set up <strong>commit signing</strong> for your personal and work Git accounts.</p><hr><h2 id="%F0%9F%A7%A9-why-sign-commits">🧩 Why Sign Commits?</h2><p>Git already tracks who made each commit, but those details (name and email) are easy to fake — they’re just text in your config.</p><p>Signing your commits adds <strong>cryptographic proof</strong> that they actually came from you.</p><p>Benefits:</p><ul><li>✅ Verified commits on GitHub</li><li>🧠 Stronger identity assurance for open-source work</li><li>🔒 Prevents impersonation or accidental misattribution</li></ul><hr><h2 id="%F0%9F%94%90-two-ways-to-sign-commits">🔐 Two Ways to Sign Commits</h2><p>GitHub supports <strong>two signing methods</strong>:</p><ol><li><strong>GPG (GNU Privacy Guard)</strong> – traditional, widely supported</li><li><strong>SSH signing</strong> – newer and simpler (especially if you already use SSH keys)</li></ol><p>We’ll go through both, starting with SSH since it’s the easiest to set up.</p><hr><h2 id="%E2%9A%99%EF%B8%8F-option-1-%E2%80%93-signing-commits-with-ssh">⚙️ Option 1 – Signing Commits with SSH</h2><p>If you already have SSH keys for GitHub (from <a href="https://ghost.atathome.me/managing-multiple-git-ssh-keys-by-directory/" rel="noreferrer">Part 2</a>), you can use them to sign commits.</p><h3 id="1-check-your-git-version">1. Check your Git version</h3><p>SSH commit signing requires Git <strong>2.34+</strong>:</p><pre><code class="language-bash">git --version</code></pre><p>If it’s older, update it before continuing.</p><h3 id="2-tell-git-to-use-ssh-signing">2. Tell Git to use SSH signing</h3><p>Pick which key you want to use (personal or work) and set it as the signing key:</p><pre><code class="language-bash">git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519_personal.pub
git config --global commit.gpgsign true
</code></pre><p>If you use separate identities, you can set the signing key per directory using the same <code>includeIf</code> setup from earlier:</p><pre><code class="language-bash">[includeIf "gitdir:~/work/"]
    path = ~/.gitconfig-work</code></pre><p>And inside <code>~/.gitconfig-work</code>:</p><pre><code class="language-bash">[gpg]
    format = ssh
[user]
    signingkey = ~/.ssh/id_ed25519_work.pub</code></pre><h3 id="3-add-the-public-key-to-github">3. Add the public key to GitHub</h3><p>Copy your SSH public key:</p><pre><code class="language-bash">cat ~/.ssh/id_ed25519_personal.pub</code></pre><p>Go to <strong>GitHub → Settings → SSH and GPG keys → New SSH key</strong>,<br>then choose <strong>"Signing Key"</strong> as the type.</br></p><p>Once saved, any commit signed with that SSH key will show up as <strong>Verified</strong> on GitHub.</p><hr><h2 id="%F0%9F%94%91-option-2-%E2%80%93-signing-commits-with-gpg">🔑 Option 2 – Signing Commits with GPG</h2><p>If you prefer GPG, or already use it for encryption, you can generate and add a GPG key instead.</p><h3 id="1-generate-a-gpg-key">1. Generate a GPG key</h3><pre><code class="language-bash">gpg --full-generate-key</code></pre><p>Choose:</p><ul><li>Key type: <code>RSA and RSA</code></li><li>Key size: <code>4096</code></li><li>Expiration: up to you</li><li>Real name &amp; email: must match your Git config</li></ul><p>Then list your keys:</p><pre><code class="language-bash">gpg --list-secret-keys --keyid-format=long
</code></pre><h3 id="2-set-your-signing-key-in-git">2. Set your signing key in Git</h3><p>Take the long key ID (the part after <code>sec rsa4096/</code>) and configure Git:</p><pre><code class="language-bash">git config --global user.signingkey YOURKEYID
git config --global commit.gpgsign true</code></pre><h3 id="3-add-your-public-key-to-github">3. Add your public key to GitHub</h3><p>Export your public key:</p><pre><code class="language-bash">gpg --armor --export YOURKEYID
</code></pre><p>Copy the output and add it at<br><strong>GitHub → Settings → SSH and GPG keys → New GPG key</strong></br></p><p>That’s it — your GPG-signed commits will now show as verified too.</p><hr><h2 id="%F0%9F%A7%A0-testing-it">🧠 Testing It</h2><p>Make a test commit:</p><pre><code class="language-bash">git commit -S -m "test signed commit"
</code></pre><p>Push it to GitHub, then open the commit in your repo — you should see:</p><blockquote>✅ Verified</blockquote><p>For example, when enabled on GitHub it should look like this, see previous <code>Unverified</code> and then subsequent <code>Verified</code> commit.</p><figure class="kg-card kg-image-card"><img src="https://content.brightbot.co.uk/2025/10/Screenshot-2025-10-06-at-21.27.29.png" class="kg-image" alt="Verifying Your GitHub Commits with GPG or SSH" loading="lazy" width="3294" height="568"/></figure><p>If you don’t, check that:</p><ul><li>The key email matches your GitHub account email</li><li>The right key was added as a signing key</li><li>You’re not committing as a different user/SSH alias</li></ul><hr><h2 id="%F0%9F%A7%A9-bonus-tip-%E2%80%93-visual-verification">🧩 Bonus Tip – Visual Verification</h2><p>You can confirm locally that commits are signed and valid:</p><pre><code class="language-bash">git log --show-signature
</code></pre><p>This will show which key signed each commit.</p><hr><h2 id="%E2%9C%85-summary">✅ Summary</h2><p>You’ve now got:</p><ul><li><a href="https://ghost.atathome.me/managing-multiple-git-authors-by-directory/" rel="noreferrer">Part 1</a>: 🔄 Automatic author switching per directory</li><li><a href="https://ghost.atathome.me/managing-multiple-git-ssh-keys-by-directory/" rel="noreferrer">Part 2</a>: 🔑 SSH key separation for multiple Git accounts</li><li>Part 3 (This post): 🪪 Verified commits on GitHub</li></ul><p>Together, these make your Git setup more professional, secure, and organised — whether you’re working across open-source, side projects, or enterprise repos.</p></hr></hr></hr></hr></hr></hr></hr>]]></content:encoded></item><item><title><![CDATA[Managing Multiple Git SSH Keys by Directory]]></title><description><![CDATA[In the last post, we configured Git to automatically use different user names and emails depending on the project directory.
That solved one half of the problem.

But if you use multiple Git accounts — say, one for work, one for personal projects — you’ll also need to make sure Git connects using the right SSH key for each.

Let’s fix that next.


The Problem

By default, Git uses your system-wide SSH key (typically ~/.ssh/id_rsa or ~/.ssh/id_ed25519).
If both your personal and work GitHub accou]]></description><link>https://brightbot.co.uk/managing-multiple-git-ssh-keys-by-directory/</link><guid isPermaLink="false">Ghost__Post__68e41c4864bc86d5eba401af</guid><category><![CDATA[Infrastructure]]></category><category><![CDATA[Ansible]]></category><category><![CDATA[AWS]]></category><category><![CDATA[Home Lab]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Mon, 06 Oct 2025 20:07:48 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1643804926339-e94f0a655185?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fGtleXN8ZW58MHx8fHwxNzU5NzgwNTk3fDA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1643804926339-e94f0a655185?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDJ8fGtleXN8ZW58MHx8fHwxNzU5NzgwNTk3fDA&ixlib=rb-4.1.0&q=80&w=2000" alt="Managing Multiple Git SSH Keys by Directory"/><p><a href="https://ghost.atathome.me/managing-multiple-git-authors-by-directory/" rel="noreferrer">In the last post</a>, we configured Git to automatically use different <strong>user names and emails</strong> depending on the project directory.<br>That solved one half of the problem.</br></p><p>But if you use <strong>multiple Git accounts</strong> — say, one for work, one for personal projects — you’ll also need to make sure Git connects using the <strong>right SSH key</strong> for each.</p><p>Let’s fix that next.</p><hr><h2 id="the-problem">The Problem</h2><p>By default, Git uses your system-wide SSH key (typically <code>~/.ssh/id_rsa</code> or <code>~/.ssh/id_ed25519</code>).<br>If both your personal and work GitHub accounts use SSH, you can easily run into:</br></p><pre><code class="language-bash">ERROR: Permission denied (publickey)</code></pre><p>or worse — commits showing up under the wrong GitHub account.</p><p>The trick is to have <strong>separate SSH keys</strong> and tell your SSH client when to use which one.</p><hr><h2 id="%F0%9F%A7%B0-step-1-%E2%80%93-generate-your-keys">🧰 Step 1 – Generate Your Keys</h2><p>If you don’t already have separate keys, create them now.</p><pre><code class="language-bash"># Personal key
ssh-keygen -t ed25519 -f ~/.ssh/id_rsa_personal -C "personal@example.com"

# Work key
ssh-keygen -t ed25519 -f ~/.ssh/id_rsa_work -C "work@example.com"</code></pre><p>You’ll end up with two key pairs:</p><ul><li><code>id_ed25519_personal</code> / <code>id_ed25519_personal.pub</code></li><li><code>id_ed25519_work</code> / <code>id_ed25519_work.pub</code></li></ul><hr><h2 id="%F0%9F%A7%A9-step-2-%E2%80%93-add-keys-to-your-git-hosts">🧩 Step 2 – Add Keys to Your Git Hosts</h2><p>Add each <strong>public key</strong> (<code>.pub</code> file) to the correct account:</p><ul><li><strong>Personal GitHub</strong> → <em>Settings → SSH and GPG keys → New SSH key</em></li><li><strong>Work GitHub / GitLab</strong> → <em>Same path, different account</em></li></ul><p>Give them clear names like “Laptop Personal” and “Laptop Work.”</p><hr><h2 id="%E2%9A%99%EF%B8%8F-step-3-%E2%80%93-create-a-custom-ssh-config">⚙️ Step 3 – Create a Custom SSH Config</h2><p>Open (or create) <code>~/.ssh/config</code> and define custom host aliases for each account:</p><pre><code class="language-bash"># Personal GitHub
Host github-personal
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_personal
    IdentitiesOnly yes

# Work GitHub
Host github-work
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_work
    IdentitiesOnly yes

# Another Work Bitbucket
Host bitbucket
    HostName bitbucket.org
    User git
    IdentityFile ~/.ssh/id_rsa_work_bitbucket
    IdentitiesOnly yes
</code></pre><p>Now, instead of using <code>git@github.com</code>, you’ll use either:</p><ul><li><code>git@github-personal</code></li><li><code>git@github-work</code></li></ul><p>Each alias tells SSH which key to use. This will work for any provider, not just GitHub such as GitLab or Bitbucket etc.</p><hr><h2 id="%F0%9F%A7%B1-step-4-%E2%80%93-clone-repositories-with-the-right-alias">🧱 Step 4 – Clone Repositories with the Right Alias</h2><p>When cloning, use the correct alias:</p><pre><code class="language-bash"># Personal project
git clone git@github-personal:username/personal-repo.git

# Work project
git clone git@github-work:company/work-repo.git</code></pre><p>Git doesn’t care about the alias — it’s just an SSH shortcut that ensures the correct key gets used.</p><p>If you’ve already cloned a repo, you can edit the <code>.git/config</code> file inside it:</p><pre><code class="language-bash">[remote "origin"]
    url = git@github-work:company/work-repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*</code></pre><hr><h2 id="%F0%9F%A7%A0-step-5-%E2%80%93-combine-with-conditional-git-configs">🧠 Step 5 – Combine with Conditional Git Configs</h2><p>If you followed the previous post, you can now combine the two setups:</p><ul><li>Use <code>includeIf</code> in <code>~/.gitconfig</code> to pick the <strong>right author details</strong>.</li><li>Use SSH aliases in <code>~/.ssh/config</code> to pick the <strong>right authentication key</strong>.</li></ul><p>That means everything just works when you’re in the right directory — no more switching accounts manually.</p><hr><h2 id="%F0%9F%A7%A9-example-directory-setup">🧩 Example Directory Setup</h2><pre><code class="language-bash">~/projects/personal/     → uses github-personal + personal identity  
~/work/                  → uses github-work + work identity  </code></pre><p>Each repo inside those folders automatically gets the right author <em>and</em> the right SSH key.</p><hr><h2 id="%E2%9C%85-summary">✅ Summary</h2><p>With a few lines of config, you’ve now built a clean, automatic Git environment that handles multiple accounts seamlessly.</p><p><strong>Benefits:</strong></p><ul><li>Separate identities and SSH keys per project type</li><li>No more “wrong account” commits or permission errors</li><li>Clean, organized Git and SSH setups that just work</li></ul><p>This approach is especially useful if you:</p><ul><li>Contribute to open-source projects with your personal account</li><li>Work for multiple clients</li><li>Keep your personal and professional Git presence strictly separated</li></ul><p>In Part 3 we go a step further and <a href="https://ghost.atathome.me/verifying-your-github-commits-with-gpg-or-ssh/" rel="noreferrer">verifying our commits providing confidence they are from trusted authors</a></p></hr></hr></hr></hr></hr></hr></hr></hr>]]></content:encoded></item><item><title><![CDATA[Managing Multiple Git Authors by Directory]]></title><description><![CDATA[If you contribute to both personal and work repositories, you’ve probably run into this:

You commit to a personal project — and realise your work email is all over it.

Or worse, you commit to a company repo using your personal identity.

Git only tracks one author configuration per system by default, but with a little setup, you can make Git automatically choose the right name and email based on the directory you’re working in.

Let’s walk through how to do it cleanly.


🧩 The Problem

By def]]></description><link>https://brightbot.co.uk/managing-multiple-git-authors-by-directory/</link><guid isPermaLink="false">Ghost__Post__68e41a4764bc86d5eba40175</guid><category><![CDATA[Infrastructure]]></category><category><![CDATA[Ansible]]></category><category><![CDATA[AWS]]></category><category><![CDATA[Home Lab]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Mon, 06 Oct 2025 19:44:53 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1555099962-4199c345e5dd?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDN8fHNvdXJjZSUyMGNvZGV8ZW58MHx8fHwxNzU5Nzc5ODQ3fDA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1555099962-4199c345e5dd?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDN8fHNvdXJjZSUyMGNvZGV8ZW58MHx8fHwxNzU5Nzc5ODQ3fDA&ixlib=rb-4.1.0&q=80&w=2000" alt="Managing Multiple Git Authors by Directory"/><p>If you contribute to both personal and work repositories, you’ve probably run into this:</p><p>You commit to a personal project — and realise your <strong>work email</strong> is all over it.</p><p>Or worse, you commit to a company repo using your personal identity.</p><p>Git only tracks one author configuration per system by default, but with a little setup, you can make Git automatically choose the right name and email <strong>based on the directory you’re working in</strong>.</p><p>Let’s walk through how to do it cleanly.</p><hr><h2 id="%F0%9F%A7%A9-the-problem">🧩 The Problem</h2><p>By default, Git uses the global configuration you set up when you first installed it:</p><pre><code class="language-bash">git config --global user.name "John Smith"
git config --global user.email "john@work.com"</code></pre><p>That means <strong>every commit</strong> — no matter which project — will use that identity.</p><p>If you use Git for both work and personal projects, this gets messy fast.</p><hr><h2 id="%F0%9F%9B%A0%EF%B8%8F-the-solution-per-directory-config">🛠️ The Solution: Per-Directory Config</h2><p>Git allows <strong>conditional includes</strong>, meaning you can load different configuration files depending on the path of your repository.</p><p>You can define separate config files for each identity and tell Git which one to use automatically based on directory.</p><hr><h2 id="%E2%9A%99%EF%B8%8F-step-1-%E2%80%93-set-your-global-config">⚙️ Step 1 – Set Your Global Config</h2><p>Keep your global Git config simple — it acts as the default.</p><pre><code class="language-bash">git config --global user.name "Personal Name"
git config --global user.email "personal@example.com"
</code></pre><p>Then open your global config file for editing:</p><pre><code class="language-bash">nano ~/.gitconfig
</code></pre><p>You’ll see something like:</p><pre><code class="language-bash">[user]
    name = Personal Name
    email = personal@example.com</code></pre><hr><h2 id="%E2%9A%99%EF%B8%8F-step-2-%E2%80%93-add-conditional-includes">⚙️ Step 2 – Add Conditional Includes</h2><p>Now, let’s add rules so Git automatically uses your <strong>work identity</strong> in a specific folder, and your <strong>personal identity</strong> elsewhere.</p><p>Append this to your <code>~/.gitconfig</code>:</p><pre><code class="language-bash">[includeIf "gitdir:~/work/"]
    path = ~/.gitconfig-work

[includeIf "gitdir:~/projects/personal/"]
    path = ~/.gitconfig-personal
</code></pre><p>Each <code>includeIf</code> rule checks the path of the repository.<br>If the repo lives inside <code>~/work/</code>, Git will include your <code>~/.gitconfig-work</code> settings.</br></p><blockquote>💡 The path <strong>must end with a slash (<code>/</code>)</strong> to match everything inside that directory.</blockquote><hr><h2 id="step-3-%E2%80%93-create-the-additional-config-files">Step 3 – Create the Additional Config Files</h2><p>Now create the two files:</p><p><strong><code>~/.gitconfig-work</code></strong></p><pre><code class="language-bash">[user]
    name = Work Name
    email = work@example.com</code></pre><p><strong><code>~/.gitconfig-personal</code></strong></p><pre><code class="language-bash">[user]
    name = Personal Name
    email = personal@example.com</code></pre><p>You can add as many of these as you need — for freelance clients, open-source accounts, or separate organisations.</p><hr><h2 id="%F0%9F%A7%AA-step-4-%E2%80%93-test-it">🧪 Step 4 – Test It</h2><p>Navigate into one of your repos and check which author Git is using:</p><pre><code class="language-bash">cd ~/work/project1

git config user.name
-&gt; Work Name

git config user.email
-&gt; work@example.com

cd ~/projects/personal/myproject2

git config user.name
-&gt; Personal Name

git config user.email
-&gt; personal@example.com</code></pre><p>You should see the correct identity based on the folder you’re in.</p><hr><h2 id="%F0%9F%A7%B0-bonus-tip-%E2%80%93-verify-before-you-commit">🧰 Bonus Tip – Verify Before You Commit</h2><p>If you want a quick reminder before committing, you can add an alias to show the current identity:</p><pre><code class="language-bash">git config --global alias.whoami '!git config user.name &amp;&amp; git config user.email'</code></pre><p>Now run:</p><pre><code class="language-bash">cd ~/work/anotherproject

git whoami
Work Name</code></pre><p>to double-check which author Git will use in the current repo.</p><hr><h2 id="%F0%9F%9B%A0%EF%B8%8F-fixing-any-previous-commits">🛠️ Fixing any previous commits</h2><p/><p>If you have accidentally committed with the wrong git author, you can always go back and alter the commit history, however note this can be a destructive process so use with caution! Where GIT_HASH is the commit just before the bad commit author you can substitute that and run the following:</p><pre><code class="language-bash">git rebase -r GIT_HASH \
    --exec 'git commit --amend --no-edit --reset-author'</code></pre><p>This will rebase ALL commits from that point resetting them against the currently configured author. </p><p>⚠️ <strong>Warning:</strong> This rewrites history — only do this on branches you control (not shared ones).</p><hr><h2 id="%E2%9C%85-summary">✅ Summary</h2><p>With conditional includes, Git becomes smart enough to switch identities automatically based on directory.</p><p><strong>Benefits:</strong></p><ul><li>No need to constantly reconfigure or remember which profile you’re using.</li><li>Prevents accidentally committing to personal projects with your work email.</li><li>Keeps your global configuration clean and simple.</li></ul><p>It’s a small setup that saves a lot of cleanup later — especially if you juggle multiple Git identities daily.</p><p>In Part 2 we go into the next step of using <a href="https://ghost.atathome.me/managing-multiple-git-ssh-keys-by-directory/" rel="noreferrer">separate SSH keys for multiple Git Accounts</a></p></hr></hr></hr></hr></hr></hr></hr></hr></hr>]]></content:encoded></item><item><title><![CDATA[Building a Laser Trip Sensor with a Photoelectric Sensor and ESPHome]]></title><description><![CDATA[Presence detection is a cornerstone of home automation. Whether you want lights that automatically switch on when someone walks into a room, or smarter security alerts, presence sensors give your automations real-world context.

While PIR (motion) sensors are common, another interesting option is the photoelectric sensor. These sensors detect when an object breaks a light beam, making them great for detecting someone passing through a doorway, entering a hallway, or triggering an event when some]]></description><link>https://brightbot.co.uk/building-a-laser-trip-sensor-with-a-photoelectric-sensor-and-esphome/</link><guid isPermaLink="false">Ghost__Post__68ddababcb5315e3604fce97</guid><category><![CDATA[Home Automation]]></category><category><![CDATA[ESPHome]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sun, 05 Oct 2025 12:09:25 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1574232889174-1a6051231cf6?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDR8fGxhemVyfGVufDB8fHx8MTc1OTY2NjE1MHww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1574232889174-1a6051231cf6?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDR8fGxhemVyfGVufDB8fHx8MTc1OTY2NjE1MHww&ixlib=rb-4.1.0&q=80&w=2000" alt="Building a Laser Trip Sensor with a Photoelectric Sensor and ESPHome"/><p>Presence detection is a cornerstone of home automation. Whether you want lights that automatically switch on when someone walks into a room, or smarter security alerts, presence sensors give your automations real-world context.</p><p>While PIR (motion) sensors are common, another interesting option is the <strong>photoelectric sensor</strong>. These sensors detect when an object breaks a light beam, making them great for detecting someone passing through a doorway, entering a hallway, or triggering an event when something moves past.</p><p>In this post, I’ll walk through building a simple <strong>ESPHome-based presence sensor</strong> using a photoelectric sensor, an ESP microcontroller, and Home Assistant integration.</p><hr><h2 id="why-photoelectric-sensors">Why Photoelectric Sensors?</h2><p>Most people default to PIR sensors, but photoelectric sensors offer some nice benefits:</p><ul><li><strong>Directional detection</strong> – can be placed across a doorway or passage.</li><li><strong>More reliable indoors</strong> – less prone to false triggers from heat changes.</li><li><strong>Fast response</strong> – detects instantly when the beam is broken.</li><li><strong>Versatile</strong> – can detect objects, not just people.</li></ul><p>This makes them especially useful in <strong>hallways, staircases, garages, or even for counting entries/exits</strong>.</p><hr><h2 id="hardware-needed">Hardware Needed</h2><ul><li><strong>ESP8266 or ESP32</strong> board (NodeMCU, ESP32-DevKit, etc.).</li><li><strong>Photoelectric sensor</strong> (common 5V or 12V models, like E18-D80NK).</li><li><strong>Relay or MOSFET (optional)</strong> if the sensor requires different power than the ESP board.</li><li><strong>Wiring &amp; enclosure</strong> depending on where it’s installed.</li></ul><p>Most photoelectric sensors provide a digital output (HIGH/LOW) when the beam is broken, which makes them easy to integrate with ESPHome.</p><hr><h2 id="wiring-overview">Wiring Overview</h2><ul><li><strong>VCC</strong> of the sensor → 5V (or 12V depending on model).</li><li><strong>GND</strong> → Common ground with ESP board.</li><li><strong>OUT</strong> → Connect to an ESP GPIO pin (with level shifting if needed).</li></ul><hr><h2 id="esphome-configuration">ESPHome Configuration</h2><p>Here’s a simple YAML config to turn the sensor into a binary sensor in Home Assistant:</p><pre><code class="language-yaml">esphome:
  name: photo-sensor
  platform: ESP8266
  board: nodemcuv2

wifi:
  ssid: "YOUR_WIFI"
  password: "YOUR_PASSWORD"

api:
logger:
ota:

binary_sensor:
  - platform: gpio
    pin: D5
    name: "Presence Sensor"
    device_class: motion
    filters:
      - delayed_off: 500ms
</code></pre><p>✅ This setup creates a binary sensor entity in Home Assistant called <strong>Presence Sensor</strong>.<br>✅ <code>delayed_off</code> prevents flickering if the beam is quickly interrupted multiple times.</br></p><hr><h2 id="example-automations">Example Automations</h2><p>Once in Home Assistant, you can start building automations like:</p><ul><li><strong>Hallway lights</strong>: Turn on when someone walks through.</li><li><strong>Garage alert</strong>: Send a notification when the beam is broken after hours.</li><li><strong>Entry counting</strong>: Use two sensors side-by-side to count in/out movement.</li></ul><p>Example automation for lights:</p><pre><code class="language-yaml">alias: Hallway Lights On
trigger:
  - platform: state
    entity_id: binary_sensor.presence_sensor
    to: "on"
action:
  - service: light.turn_on
    target:
      entity_id: light.hallway
</code></pre><hr><h2 id="benefits-of-a-photoelectric-presence-sensor">Benefits of a Photoelectric Presence Sensor</h2><ul><li><strong>Accurate</strong> – triggers only when the beam is broken.</li><li><strong>Flexible</strong> – works for both people and objects.</li><li><strong>DIY-friendly</strong> – simple binary sensor integration with ESPHome.</li><li><strong>Expandable</strong> – add multiple sensors to track direction or build counters.</li></ul><hr><h2 id="conclusion">Conclusion</h2><p>A <strong>photoelectric sensor</strong> paired with <strong>ESPHome</strong> gives you a fast, reliable way to detect presence and movement in your smart home. It’s a great alternative to PIR sensors, especially in narrow or controlled spaces like doorways, staircases, or garages.</p><p>Once integrated with Home Assistant, the possibilities are endless — from simple light automation to more advanced occupancy tracking.</p></hr></hr></hr></hr></hr></hr></hr>]]></content:encoded></item><item><title><![CDATA[Building a 4-Zone Irrigation Controller with ESPHome - Part 1]]></title><description><![CDATA[Automating irrigation is one of those home automation projects that’s both practical and fun.

Instead of manually turning sprinklers or valves on and off, you can control watering schedules through your smart home — or even trigger watering based on weather or soil moisture sensors.

In this series, I’ll walk through building a 4-zone irrigation controller using ESPHome, some off-the-shelf components, and Home Assistant integration.


Series Overview

As I publish parts of this series I will up]]></description><link>https://brightbot.co.uk/building-a-4-zone-irrigation-controller-with-esphome-part-1/</link><guid isPermaLink="false">Ghost__Post__68dda75ccb5315e3604fce86</guid><category><![CDATA[Home Automation]]></category><category><![CDATA[ESPHome]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sat, 04 Oct 2025 20:44:38 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1495647688236-ed6ef40cb28b?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDl8fGlycmlnYXRpb258ZW58MHx8fHwxNzU5NjA5NDIzfDA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1495647688236-ed6ef40cb28b?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDl8fGlycmlnYXRpb258ZW58MHx8fHwxNzU5NjA5NDIzfDA&ixlib=rb-4.1.0&q=80&w=2000" alt="Building a 4-Zone Irrigation Controller with ESPHome - Part 1"/><p>Automating irrigation is one of those home automation projects that’s both <strong>practical</strong> and <strong>fun</strong>. </p><p>Instead of manually turning sprinklers or valves on and off, you can control watering schedules through your smart home — or even trigger watering based on weather or soil moisture sensors.</p><p>In this series, I’ll walk through building a <strong>4-zone irrigation controller</strong> using <strong>ESPHome</strong>, some off-the-shelf components, and Home Assistant integration.</p><hr><h2 id="series-overview">Series Overview</h2><p>As I publish parts of this series I will update the links between each part for easier navigation.</p><p><strong>Part 1 – Planning the Build &amp; Hardware Setup</strong><br>→ Components, software, wiring concept, safety.</br></p><p><strong>Part 2 – Prototype, Flashing ESPHome &amp; Writing the YAML</strong><br>→ ESPHome config, relay control, and testing each zone.</br></p><p><strong>Part 3 – Creating a custom PCB</strong><br>→ Walking through PCB design and ordering process</br></p><p><strong>Part 4 – Integrating with Home Assistant</strong><br>→ Adding all entities, automations, scheduling, and dashboard.</br></p><p><strong>Part 5 – Adding Sensors &amp; Smart Features</strong><br>→ Soil moisture, rain delay, weather data, and refinement.</br></p><p><strong>Part 6 – Final thoughts and future improvements</strong><br>→ Closing thoughts what I like, what I dislike and would do better next time.</br></p><hr><h3 id="why-build-a-custom-controller">Why Build a Custom Controller?</h3><p>Off-the-shelf irrigation systems work fine for simple setups — but they’re often limited, closed, and inflexible. By building your own controller with <strong>ESPHome</strong> and <strong>Home Assistant</strong>, you get:</p><ul><li><strong>Full control and customisation</strong> – tailor schedules, sensor logic, and automations exactly how you want.</li><li><strong>Local operation</strong> – no reliance on vendor cloud services or app subscriptions.</li><li><strong>Easy integration</strong> – connect with weather data, soil sensors, and other smart home devices.</li><li><strong>Expandability</strong> – add more zones, relays, or features later without replacing the hardware.</li><li><strong>Lower cost</strong> – use inexpensive components you can maintain or upgrade yourself.</li></ul><p>In short, a DIY controller gives you flexibility and transparency that commercial units rarely offer — and it’s far more satisfying to build something that perfectly fits <em>your</em> garden and your system.</p><hr><h2 id="why-esphome">Why ESPHome?</h2><p><strong>ESPHome</strong> is a framework for programming ESP8266/ESP32 microcontrollers with simple YAML configuration. Instead of writing C++ code, you declare sensors, switches, and automations in YAML, then flash them to your device. Benefits include:</p><ul><li><strong>Tight Home Assistant integration</strong> (auto discovery).</li><li><strong>Easy configuration and updates</strong> via Wi-Fi.</li><li><strong>Support for a huge range of sensors and relays.</strong></li><li><strong>Community-friendly</strong> with lots of real-world examples.</li></ul><p>Perfect for a project like irrigation control.</p><hr><h2 id="hardware-needed">Hardware Needed</h2><p>For a 4-zone controller, you’ll need at a minimum the following:</p><h3 id="electrical-components">Electrical Components</h3>
<!--kg-card-begin: html-->
<table>
<thead>
<tr>
<th>Component</th>
<th>Example</th>
<th>Purpose</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Microcontroller</strong></td>
<td>ESP8266 (NodeMCU) or ESP32</td>
<td>Brain of the system</td>
</tr>
<tr>
<td><strong>Relay module (4-channel)</strong></td>
<td>5 V or 12 V logic</td>
<td>Controls solenoid valves</td>
</tr>
<tr>
<td><strong>Solenoid valves</strong></td>
<td>12 VAC garden valves</td>
<td>Open/close water flow</td>
</tr>
<tr>
<td><strong>Power supply</strong></td>
<td>12 VAC transformer (for valves) + 5 V DC (for ESP)</td>
<td>Powers everything</td>
</tr>
<tr>
<td><strong>Jumper wires &amp; terminals</strong></td>
<td>Dupont / screw connectors</td>
<td>Clean wiring</td>
</tr>
<tr>
<td><strong>Enclosure</strong></td>
<td>Weather-resistant box</td>
<td>Keeps electronics dry</td>
</tr>
<tr>
<td><em>(optional)</em> <strong>Manual override switch or button</strong></td>
<td>—</td>
<td>Run a zone manually</td>
</tr>
</tbody>
</table>
<!--kg-card-end: html-->
<h3 id="waterhose-components">Water/Hose Components</h3>
<!--kg-card-begin: html-->
<table class="tg"><thead>
  <tr>
    <th class="tg-0lax">Component</th>
    <th class="tg-0lax">Example</th>
    <th class="tg-0lax">Purpose</th>
  </tr></thead>
<tbody>
  <tr>
    <td class="tg-0lax">Hose Manifold</td>
    <td class="tg-0lax"/>
    <td class="tg-0lax">Used to split the cold water supply to each zone</td>
  </tr>
  <tr>
    <td class="tg-0lax">Hose to G-thread adapters</td>
    <td class="tg-0lax">G3/4 to Hose</td>
    <td class="tg-0lax">Used to connect various hose pipes to solenoid valves, depending on the valve depends on which connectors/adapters are required.</td>
  </tr>
  <tr>
    <td class="tg-0lax">G-thread to irrigation adapters</td>
    <td class="tg-0lax"/>
    <td class="tg-0lax">Dependant on the irrigation system you use, you may need a specific adapter to go from the solenoid to pipe</td>
  </tr>
  <tr>
    <td class="tg-0lax">Irrigation kit/drip feeders</td>
    <td class="tg-0lax">Claber Dripper Irrigation Set for Ten Plants</td>
    <td class="tg-0lax">Provides the irrigation part of the solution with suitable pipe and drip feeders, this solution can be adapted to use any brand of irrigation kits</td>
  </tr>
  <tr>
    <td class="tg-0lax">Standard hose pipe</td>
    <td class="tg-0lax"/>
    <td class="tg-0lax">Misc. lengths of hose pipe to connect everything up</td>
  </tr>
</tbody></table>
<!--kg-card-end: html-->
<hr><h3 id="%E2%9A%A0%EF%B8%8F-safety-first">⚠️ Safety First</h3><p>Even though this project mostly uses low voltage, it still involves water! <strong>Electrical safety still matters</strong>:</p><ul><li>Double-check power ratings of relays and valves.</li><li>Keep low-voltage and mains-voltage circuits physically separate.</li><li>If you’re not confident with wiring, get help from someone experienced.</li><li>Always test with the water supply <strong>off</strong> the first time you power it up.</li><li>Always test the water fittings without the controller being connected to mains power!</li></ul><p>A small amount of planning here avoids fried boards (or flooded flowerbeds) later.</p><hr><h2 id="wiring-overview">Wiring Overview</h2><ul><li>The core idea is simple:</li><li>Each relay controls one irrigation <strong>zone</strong> (valve).</li><li>When the relay energizes, it completes the 24 VAC circuit to that valve.</li><li>The ESP sends a HIGH or LOW signal to trigger the relay.</li></ul><figure class="kg-card kg-code-card"><pre><code class="language-text">[ESP32] ---&gt; [Relay1] ---&gt; Zone 1 Valve  
        ---&gt; [Relay2] ---&gt; Zone 2 Valve  
        ---&gt; [Relay3] ---&gt; Zone 3 Valve  
        ---&gt; [Relay4] ---&gt; Zone 4 Valve
</code></pre><figcaption><p><span style="white-space: pre-wrap;">Diagram (simplified)</span></p></figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-text">ESP8266 GPIO → Relay Input → Relay Output → Solenoid Valve → 24 VAC Transformer</code></pre><figcaption><p><span style="white-space: pre-wrap;">Basic flow for controlling a zone</span></p></figcaption></figure><p>Label each zone clearly (Zone 1 – Front Garden, Zone 2 – Lawn, etc.). It makes automation easier down the road.</p><hr><h3 id="planning-the-zones">Planning the Zones</h3><p>Think through how you want to divide watering areas:</p><ul><li><strong>Zone 1</strong> – Front garden</li><li><strong>Zone 2</strong> – Back lawn</li><li><strong>Zone 3</strong> – Vegetable bed</li><li><strong>Zone 4</strong> – Pots / greenhouse</li></ul><p>The beauty of this project is you can add/remove zones as required at anytime, you can even expand this further to include even more zones should it be required.</p><p>Even if you wanted another controller in another part of the garden, its easy and cheap to replicate, compared to commercial offerings.</p><p>I started with one zone and build out the system at a later date to accommodate four zones.</p><p>If you plan ahead, you can also size your transformer and relay contacts properly for the total potential current draw.</p><hr><h3 id="next-up">Next Up</h3><p>In <strong>Part 2</strong>, we’ll:</p><ul><li>Build a prototype solution using one zone</li><li>Flash ESPHome onto the board</li><li>Write a simple YAML config for up to four relays</li><li>Expose each zone as a switch in Home Assistant</li></ul><p>By the end of Part 2, you’ll be able to toggle each valve manually from your Home Assistant dashboard.</p><p/><h2 id=""/></hr></hr></hr></hr></hr></hr></hr></hr>]]></content:encoded></item><item><title><![CDATA[Tracking Daily Power Usage and Cost with Shelly and Home Assistant - Part 2]]></title><description><![CDATA[One of the most rewarding parts of home automation is getting insights into how your home uses energy — and how much it’s costing you. If you’ve ever wondered what your washing machine, PC, or server rack really costs to run, you can easily find out using Shelly smart devices and Home Assistant.

In this post, we’ll look at how to set up Shelly devices to monitor power usage, track daily totals with Home Assistant’s Utility Meter, and calculate energy costs automatically.


Tutorial parts breakd]]></description><link>https://brightbot.co.uk/tracking-daily-power-usage-and-cost-with-shelly-and-home-assistant-part-2/</link><guid isPermaLink="false">Ghost__Post__68e1607b64bc86d5eba400ca</guid><category><![CDATA[Home Automation]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sat, 04 Oct 2025 18:20:35 GMT</pubDate><media:content url="https://content.brightbot.co.uk/2025/10/Shellyrelays.png" medium="image"/><content:encoded><![CDATA[<img src="https://content.brightbot.co.uk/2025/10/Shellyrelays.png" alt="Tracking Daily Power Usage and Cost with Shelly and Home Assistant - Part 2"/><p>One of the most rewarding parts of home automation is getting insights into how your home uses energy — and how much it’s costing you. If you’ve ever wondered what your washing machine, PC, or server rack really costs to run, you can easily find out using <strong>Shelly smart devices</strong> and <strong>Home Assistant</strong>.</p><p>In this post, we’ll look at how to set up Shelly devices to monitor power usage, track daily totals with Home Assistant’s <strong>Utility Meter</strong>, and calculate <strong>energy costs</strong> automatically.</p><hr><h2 id="tutorial-parts-breakdown">Tutorial parts breakdown</h2><ul><li><a href="https://ghost.atathome.me/tracking-daily-power-usage-with-shelly-and-home-assistant-part-1/" rel="noreferrer">Part 1</a> - (This post) Covering basic shelly setup along with configuring Home assistant utility meters to track periodic consumption daily/weekly etc.</li><li><a href="https://ghost.atathome.me/tracking-daily-power-usage-and-cost-with-shelly-and-home-assistant-part-2/" rel="noreferrer">Part 2</a> - (This Post) Covering device cost tracking, building upon Part 1 and extending this to track daily, weekly costs</li></ul><hr><h2 id="why-shelly">Why Shelly?</h2><p>Shelly devices are compact, Wi-Fi–enabled smart switches and relays made by <a href="https://shelly.cloud/" rel="noreferrer"><strong>Allterco Robotics</strong></a>. What makes them great for energy tracking is that many models (like the <strong>Shelly 2PM</strong>, , <strong>Shelly 1PM Mini Gen3</strong>, <strong>Shelly Plug S</strong>, or <strong>Shelly EM</strong>) include built-in <strong>power monitoring</strong>.</p><p>They’re:</p><ul><li><strong>Local-first</strong> (no cloud required).</li><li><strong>Affordable</strong> and easy to retrofit.</li><li><strong>Highly compatible</strong> with Home Assistant.</li><li><strong>Reliable</strong> for continuous energy measurement.</li></ul><p>If you’re already running Home Assistant, Shelly is one of the most seamless ways to get per-device power metrics.</p><hr><h2 id="a-quick-note-on-electrical-safety-%E2%9A%A0%EF%B8%8F">A Quick Note on Electrical Safety ⚠️</h2><p>Before diving into wiring any Shelly devices, it’s really important to emphasise <strong>electrical safety</strong>.</p><p>If you’re installing in-line devices like a Shelly 1PM or 2.5 — anything that involves mains voltage wiring — <strong>make sure you fully understand what you’re doing</strong>.</p><ul><li>Always <strong>turn off power</strong> at the breaker before working.</li><li>Use proper tools and insulation.</li><li>If you’re not confident with electrical work, it’s best to get help from a <strong>qualified electrician</strong>.</li><li>Ensure you have reviewed the manufacturer guidelines and specifications, Shelly are very good at this and link all of the documentation alongside their models. <strong>Not all</strong> relays are suitable for certain load types i.e inductive vs resistive loads!</li></ul><p>Smart home projects are great fun and rewarding to learn from, but safety should always come first — no automation is worth a shock or a fire hazard.</p><hr><h2 id="hardware-setup-adding-shelly-to-home-assistant">Hardware Setup &amp; Adding Shelly to Home Assistant</h2><p>We covered this in the previous post which went step by step through getting up to this point. Along with setting up the utility meters.</p><hr><h2 id="adding-cost-tracking-%F0%9F%92%B0">Adding Cost Tracking 💰</h2><p>To track cost, you can create <strong>template sensors</strong> that multiply energy usage by your electricity rate. These are in the <code>sensors.yaml</code> file in the home directory of your Home Assistant installation, this may not exist so you might have to create it.</p><p>I have the benefit of having my In Home Display (IHD) feed data into Home assistant via MQTT which provides my import rate per kWh of electric, however if you know this value you can setup a helper which stores the current price per kWh which I will use in the example below.</p><p>For example, if your electricity costs £0.30 per kWh, </p><figure class="kg-card kg-code-card"><pre><code class="language-yaml"># Platform: template
- platform: template
  sensors:

    # microwave usage cost tracking today
    microwave_switch_electric_cost_today:
      friendly_name: "Microwave Switch Cost Today"
      unique_id: microwave_switch_electric_cost_today
      unit_of_measurement: "GBP"
      icon_template: mdi:currency-gbp
      value_template: &gt;

        {% set todayPower = states('sensor.sensor.microwave_switch_power_today') %}

        {% if todayPower == 'unknown' or todayPower == 'unavailable' %}
          {% set todayPower = 0 | float %}
        {% endif %}


        {{ '%0.2f' % ((todayPower | float) * 0.30 | float) }}

    # microwave usage cost tracking week
    microwave_switch_electric_cost_week:
      friendly_name: "Microwave Switch Cost Week"
      unique_id: microwave_switch_electric_cost_week
      unit_of_measurement: "GBP"
      icon_template: mdi:currency-gbp
      value_template: &gt;

        {% set todayPower = states('sensor.sensor.microwave_switch_power_today') %}

        {% if todayPower == 'unknown' or todayPower == 'unavailable' %}
          {% set todayPower = 0 | float %}
        {% endif %}


        {{ '%0.2f' % ((todayPower | float) * 0.30 | float) }}</code></pre><figcaption><p><span style="white-space: pre-wrap;">Snipper from Home assistant home directory </span><code spellcheck="false" style="white-space: pre-wrap;"><span>sensors.yaml</span></code></p></figcaption></figure><p>When you have saved this file, head to <strong>Developer tools</strong> -&gt; <strong>Check configuration</strong>, assuming this gives you the green light of <code>Configuration will not prevent Home Assistant from starting!</code> you can simply click the <code>Template entities</code> button to load/reload them into Home Assistant.</p><p>This will give you two new entities:</p><ul><li><code>sensor.microwave_switch_electric_cost_today</code></li><li><code>sensor.microwave_switch_electric_cost_week</code></li></ul><p>As your utility meters update, these cost sensors will automatically calculate your spending based on current usage.</p><p>For more information on Template Sensors you can find the official documentation for them here: <a href="https://www.home-assistant.io/integrations/template/#sensor">https://www.home-assistant.io/integrations/template/#sensor</a></p><hr><h2 id="visualising-energy-and-cost">Visualising Energy and Cost</h2><p>Once your sensors are in place, you can add a card to your Home Assistant dashboard:</p><figure class="kg-card kg-code-card"><pre><code class="language-yaml">type: vertical-stack
cards:
  - type: statistics-graph
    title: Daily Energy Usage
    entities:
      - sensor.microwave_switch_power_today
    chart_type: bar
    days_to_show: 7
    stat_types:
      - sum
  - type: entities
    title: Today's Cost
    entities:
      - entity: sensor.microwave_switch_electric_cost_today
        name: Microwave Cost Today
</code></pre><figcaption><p><span style="white-space: pre-wrap;">Home assistant dashboard card showing statistics for energy usage and cost of that entity today</span></p></figcaption></figure><p>You’ll get a graph showing usage over the last week and a live readout of today’s running cost.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://content.brightbot.co.uk/2025/10/image-5.png" class="kg-image" alt="Tracking Daily Power Usage and Cost with Shelly and Home Assistant - Part 2" loading="lazy" width="956" height="384"><figcaption><span style="white-space: pre-wrap;">Example dashboard card showing power usage and cost today</span></figcaption></img></figure><hr><h2 id="going-further">Going Further</h2><ul><li>Use <strong>Shelly EM or 3EM</strong> to track total household energy usage.</li><li>Add <strong>automations</strong> to alert you if an appliance exceeds a certain daily cost.</li><li>Combine with <strong>InfluxDB + Grafana</strong> for long-term cost trends and forecasts.</li><li>Adjust your rate dynamically if your energy provider uses time-of-day pricing.</li></ul><hr><h2 id="conclusion">Conclusion</h2><p>With just a few Shelly devices and some Home Assistant YAML, you can turn your smart plugs into a detailed, cost-aware energy dashboard.</p><p>You’ll not only see <em>how much power</em> your devices use, but also <em>how much it costs</em> — giving you real insight into your home’s efficiency and helping you make smarter energy decisions.</p><p>Just remember: when dealing with mains wiring, <strong>take electrical safety seriously</strong> — measure twice, wire once, and if in doubt, call an electrician.</p><p>It’s one of those simple automations that pays for itself — literally.</p></hr></hr></hr></hr></hr></hr></hr></hr>]]></content:encoded></item><item><title><![CDATA[Tracking Daily Power Usage with Shelly and Home Assistant - Part 1]]></title><description><![CDATA[One of the best parts of home automation is getting real data about how your home works — not just controlling things, but understanding them. If you’ve ever wondered how much energy your appliances are actually using, or wanted to see your daily consumption trends, you can do that easily with Shelly smart devices and Home Assistant.

In this post, I’ll walk through how to integrate Shelly devices with Home Assistant and use them to track and visualise your daily power usage.


Tutorial parts br]]></description><link>https://brightbot.co.uk/tracking-daily-power-usage-with-shelly-and-home-assistant-part-1/</link><guid isPermaLink="false">Ghost__Post__68e1291d64bc86d5eba40097</guid><category><![CDATA[Home Automation]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Sat, 04 Oct 2025 14:28:21 GMT</pubDate><media:content url="https://content.brightbot.co.uk/2025/10/Shellyrelays.png" medium="image"/><content:encoded><![CDATA[<img src="https://content.brightbot.co.uk/2025/10/Shellyrelays.png" alt="Tracking Daily Power Usage with Shelly and Home Assistant - Part 1"/><p>One of the best parts of home automation is getting real data about how your home works — not just controlling things, but <em>understanding</em> them. If you’ve ever wondered how much energy your appliances are actually using, or wanted to see your daily consumption trends, you can do that easily with <strong>Shelly smart devices</strong> and <strong>Home Assistant</strong>.</p><p>In this post, I’ll walk through how to integrate Shelly devices with Home Assistant and use them to track and visualise your daily power usage.</p><hr><h2 id="tutorial-parts-breakdown">Tutorial parts breakdown</h2><ul><li><a href="https://ghost.atathome.me/tracking-daily-power-usage-with-shelly-and-home-assistant-part-1/" rel="noreferrer">Part 1</a> - (This post) Covering basic shelly setup along with configuring Home assistant utility meters to track periodic consumption daily/weekly etc.</li><li><a href="https://ghost.atathome.me/tracking-daily-power-usage-and-cost-with-shelly-and-home-assistant-part-2/" rel="noreferrer">Part 2</a> - Covering device cost tracking, building upon Part 1 and extending this to track daily, weekly costs</li></ul><hr><h2 id="why-shelly">Why Shelly?</h2><p>Shelly devices are compact, Wi-Fi–enabled smart switches and relays made by <a href="https://shelly.cloud/" rel="noreferrer"><strong>Allterco Robotics</strong></a>. What makes them great for energy tracking is that many models (like the <strong>Shelly 2PM</strong>, , <strong>Shelly 1PM Mini Gen3</strong>, <strong>Shelly Plug S</strong>, or <strong>Shelly EM</strong>) include built-in <strong>power monitoring</strong>.</p><p>They’re:</p><ul><li><strong>Local-first</strong> (no cloud required).</li><li><strong>Affordable</strong> and easy to retrofit.</li><li><strong>Highly compatible</strong> with Home Assistant.</li><li><strong>Reliable</strong> for continuous energy measurement.</li></ul><p>If you’re already running Home Assistant, Shelly is one of the most seamless ways to get per-device power metrics.</p><hr><h2 id="a-quick-note-on-electrical-safety-%E2%9A%A0%EF%B8%8F">A Quick Note on Electrical Safety ⚠️</h2><p>Before diving into wiring any Shelly devices, it’s really important to emphasise <strong>electrical safety</strong>.</p><p>If you’re installing in-line devices like a Shelly 1PM or 2.5 — anything that involves mains voltage wiring — <strong>make sure you fully understand what you’re doing</strong>.</p><ul><li>Always <strong>turn off power</strong> at the breaker before working.</li><li>Use proper tools and insulation.</li><li>If you’re not confident with electrical work, it’s best to get help from a <strong>qualified electrician</strong>.</li><li>Ensure you have reviewed the manufacturer guidelines and specifications, Shelly are very good at this and link all of the documentation alongside their models. <strong>Not all</strong> relays are suitable for certain load types i.e inductive vs resistive loads!</li></ul><p>Smart home projects are great fun and rewarding to learn from, but safety should always come first — no automation is worth a shock or a fire hazard.</p><hr><h2 id="hardware-setup">Hardware Setup</h2><p>For this example, you can use any of the following Shelly devices:</p><ul><li>🧱 <strong>Shelly 1PM / 2.5</strong> – inline relays with power monitoring for lights or sockets.</li><li>🔌 <strong>Shelly Plug S / Plug UK</strong> – smart plugs for standalone devices.</li><li>⚡ <strong>Shelly EM / 3EM</strong> – clamp meters for whole-circuit or multi-phase monitoring.</li></ul><p>Connect them to your Wi-Fi and assign static IPs if possible — it helps with reliability.</p><hr><h2 id="adding-shelly-to-home-assistant">Adding Shelly to Home Assistant</h2><p>You have two main options for integration:</p><h3 id="1-native-shelly-integration-recommended">1. <strong>Native Shelly Integration (Recommended)</strong></h3><p>Home Assistant natively supports Shelly devices using the <strong>CoAP</strong> or <strong>MQTT</strong> protocol.</p><ol><li>In Home Assistant, go to <strong>Settings → Devices &amp; Services → Add Integration</strong>.</li><li>Search for <strong>Shelly</strong>.</li><li>It should auto-discover devices on your network.</li><li>Click <strong>Configure</strong> to add them.</li></ol><p>Once connected, you’ll see new entities like:</p><ul><li><code>sensor.shelly_plug_power</code> (instantaneous power, W)</li><li><code>sensor.shelly_plug_energy</code> (total energy, Wh or kWh)<ul><li>This is total energy over all-time rather than today/yesterday like other devices such as Sonoff / Tasmota, so Shelly requires a bit more setup to get Periodic data (Daily, Weekly etc)</li></ul></li><li><code>switch.shelly_plug_relay</code> (on/off control)</li></ul><h3 id="2-mqtt-integration-optional">2. <strong>MQTT Integration</strong> (Optional)</h3><p>If you already use MQTT, you can flash Shelly devices to use it directly. Home Assistant will automatically create entities for MQTT topics like <code>shellies/shellyplug/emeter/0/power</code>.</p><hr><h2 id="tracking-daily-power-usage">Tracking Daily Power Usage</h2><p>Now that your Shelly devices are feeding data into Home Assistant, let’s turn that into meaningful daily stats.</p><p>You can use Home Assistant’s built-in <a href="https://www.home-assistant.io/integrations/utility_meter/" rel="noreferrer"><strong>Utility Meter</strong></a> integration to automatically track daily, weekly, or monthly energy totals.</p><h3 id="example-configuration">Example Configuration</h3><p>In your <code>configuration.yaml</code>:</p><figure class="kg-card kg-code-card"><pre><code class="language-yaml">...
utility_meter:
  microwave_switch_power_today:
    source: sensor.microwave_switch_power
    cycle: daily
  microwave_switch_power_weekly:
    source: sensor.microwave_switch_power
    cycle: monthly
...</code></pre><figcaption><p><span style="white-space: pre-wrap;">Example utility meters in Home Assistant configuration.yaml</span></p></figcaption></figure><p>This creates two new entities:</p><ul><li><code>sensor.microwave_switch_power_today</code></li><li><code>sensor.microwave_switch_power_weekly</code></li></ul><p>Each resets automatically at the start of a new day or month.</p><hr><h2 id="visualizing-in-the-dashboard">Visualizing in the Dashboard</h2><p>Once you’ve got your utility meter entities, you can create a <strong>Lovelace dashboard</strong> card:</p><figure class="kg-card kg-code-card"><pre><code class="language-yaml">type: statistics-graph
title: Daily Energy Usage
entities:
  - sensor.microwave_switch_power_today
  - sensor.tv_daily
chart_type: bar
days_to_show: 7
stat_types:
  - sum</code></pre><figcaption><p><span style="white-space: pre-wrap;">Home assistant dashboard card showing statistics for energy meters</span></p></figcaption></figure><p>Now you’ll have a bar chart showing daily consumption per device — great for spotting trends and understanding where your power goes.</p><hr><h2 id="bonus-alerts-automation">Bonus: Alerts &amp; Automation</h2><p>You can also use automations to warn you about unusual power usage or when an appliance finishes running. For example:</p><p><strong>Notify when washing machine is done:</strong></p><figure class="kg-card kg-code-card"><pre><code class="language-yaml">alias: Microwave Finished
trigger:
  - platform: numeric_state
    entity_id: sensor.microwave_switch_power
    below: 2
    for:
      minutes: 3
action:
  - service: notify.mobile_app_your_phone
    data:
      message: "Microwave cycle completed!"</code></pre><figcaption><p><span style="white-space: pre-wrap;">Home assistant automation detecting when a device has finished its cycle</span></p></figcaption></figure><p>A simple and unnecessary but very satisfying automation.</p><hr><h2 id="conclusion">Conclusion</h2><p>Shelly devices + Home Assistant = a powerful combo for understanding your home’s energy use.</p><p>With just a few sensors and a couple of YAML lines, you can build detailed daily usage charts, track trends over time, and even trigger automations based on real power data.</p><p>Whether you’re trying to save energy, monitor appliance efficiency, or just geek out on data, this setup is one of the most practical additions to any home lab.</p></hr></hr></hr></hr></hr></hr></hr></hr></hr>]]></content:encoded></item><item><title><![CDATA[Building a Home Lab Dashboard with Homer]]></title><description><![CDATA[If you’ve been running a home lab for a while, you’ve probably collected a fair number of services — things like Home Assistant, Pi-hole, Proxmox, Uptime Kuma, Grafana, media servers, and more. The problem is, remembering all those URLs and ports gets messy fast.

That’s where Homer comes in: a simple, customizable static dashboard you can host anywhere to keep your home lab neat and organized.


What is Homer?

Homer is a lightweight homepage for your self-hosted services. It’s just a single-pa]]></description><link>https://brightbot.co.uk/building-a-home-lab-dashboard-with-homer/</link><guid isPermaLink="false">Ghost__Post__68e038bb64bc86d5eba40059</guid><category><![CDATA[Home Lab]]></category><category><![CDATA[Infrastructure]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Fri, 03 Oct 2025 21:14:20 GMT</pubDate><media:content url="https://content.brightbot.co.uk/2025/10/Screenshot-2025-10-03-at-22.14.04.png" medium="image"/><content:encoded><![CDATA[<img src="https://content.brightbot.co.uk/2025/10/Screenshot-2025-10-03-at-22.14.04.png" alt="Building a Home Lab Dashboard with Homer"/><p>If you’ve been running a home lab for a while, you’ve probably collected a fair number of services — things like Home Assistant, Pi-hole, Proxmox, Uptime Kuma, Grafana, media servers, and more. The problem is, remembering all those URLs and ports gets messy fast.</p><p>That’s where <a href="https://github.com/bastienwirtz/homer" rel="noopener"><strong>Homer</strong></a> comes in: a simple, customizable <strong>static dashboard</strong> you can host anywhere to keep your home lab neat and organized.</p><hr><h2 id="what-is-homer">What is Homer?</h2><p>Homer is a <strong>lightweight homepage</strong> for your self-hosted services. It’s just a single-page web app written in Vue.js that you can run with Docker, Nginx, or even a static file host.</p><p>Key features:</p><ul><li><strong>Config-driven</strong>: Simple YAML config file for customisation.</li><li><strong>Beautiful UI</strong>: Clean, tile-based interface with icons and colours.</li><li><strong>Group support</strong>: Organise services into categories (e.g., Media, Monitoring, Infrastructure).</li><li><strong>Custom links and widgets</strong>: Add search bars, markdown notes, or quick links.</li><li><strong>Portable</strong>: No database — just config and assets.</li></ul><p>It’s like having your own start page for everything in your lab.</p><hr><h2 id="why-use-homer-in-a-home-lab">Why Use Homer in a Home Lab?</h2><ul><li><strong>Central access point</strong> for all your services.</li><li><strong>Easy to remember</strong> one URL (like <code>http://homer.local</code>) instead of 20 different ports.</li><li><strong>Customizable look and feel</strong> with icons and branding.</li><li><strong>Lightweight</strong> — runs anywhere without heavy dependencies.</li></ul><hr><h2 id="installing-homer">Installing Homer</h2><h3 id="using-docker">Using Docker</h3><p>The easiest way to get Homer running is with Docker:</p><pre><code class="language-bash">docker run -d \
  -p 8080:8080 \
  -v /path/to/config:/www/assets \
  b4bz/homer:latest</code></pre><ul><li>Mount a volume for your config at <code>/www/assets</code>.</li><li>Access Homer at <code>http://your-server:8080</code>.</li></ul><h3 id="using-proxmox-lxc">Using Proxmox LXC</h3><p>Homer is even easier to setup in Proxmox using a LXC Container, there is a community script available and its instructions can be found here:<br><a href="https://community-scripts.github.io/ProxmoxVE/scripts?id=homer">https://community-scripts.github.io/ProxmoxVE/scripts?id=homer</a></br></p><p>Always good to review scripts before blindly running them on your hardware but its as simple as running the following script and following the steps in the console</p><pre><code class="language-bash">bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/ct/homer.sh)"</code></pre><hr><h2 id="configuring-homer">Configuring Homer</h2><p>Homer is configured via a single YAML file: <code>config.yml</code>.</p><p>Here’s an example:</p><figure class="kg-card kg-code-card"><pre><code class="language-yaml">title: "Home Lab Dashboard"
subtitle: "All my services in one place"
logo: "assets/logo.png"

links:
  - name: "GitHub"
    url: "https://github.com"

services:
  - name: "Media"
    icon: "fas fa-film"
    items:
      - name: "Plex"
        logo: "assets/icons/plex.png"
        url: "http://192.168.1.10:32400"
      - name: "Jellyfin"
        logo: "assets/icons/jellyfin.png"
        url: "http://192.168.1.11:8096"

  - name: "Monitoring"
    icon: "fas fa-chart-line"
    items:
      - name: "Grafana"
        logo: "assets/icons/grafana.png"
        url: "http://192.168.1.12:3000"
      - name: "Uptime Kuma"
        logo: "assets/icons/uptime-kuma.png"
        url: "http://192.168.1.13:3001"
</code></pre><figcaption><p dir="ltr"><span style="white-space: pre-wrap;">homer config.yml example</span></p></figcaption></figure><p>You can even do things such as integrating with specific applications such as Proxmox  to get disk usage etc, this is done with smart cards.</p><p>See my image below or handily get it to ping resources to check they are online/offline, this can be achieved with the following snippet as an example.</p><pre><code class="language-yaml">- name: "Plex"
  logo: "https://i.redd.it/5x93lknmuaw81.jpg"
  subtitle: "https://plex.your-domain.com"
  url: "https://plex.your-domain.com/"
  type: Ping
  successCodes: [200, 401]
  method: "get"
  target: "_blank"</code></pre><p>For a full list of available Smart cards these are included in the Homer documentation here including a few I have mentioned above:</p><ul><li><a href="https://github.com/bastienwirtz/homer/blob/main/docs/customservices.md">https://github.com/bastienwirtz/homer/blob/main/docs/customservices.md</a></li><li><a href="https://github.com/bastienwirtz/homer/blob/main/docs/customservices.md#proxmox">https://github.com/bastienwirtz/homer/blob/main/docs/customservices.md#proxmox</a></li><li><a href="https://github.com/bastienwirtz/homer/blob/main/docs/customservices.md#ping">https://github.com/bastienwirtz/homer/blob/main/docs/customservices.md#ping</a></li></ul><hr><h2 id="customising-the-dashboard">Customising the Dashboard</h2><p>Some nice touches you can add:</p><ul><li><strong>Icons and logos</strong>: Drop PNG/SVGs into the assets folder.</li><li><strong>Themes</strong>: Light, dark, and custom themes supported.</li><li><strong>Widgets</strong>: Add search bars (Google, DuckDuckGo, internal docs) or markdown notes.</li><li><strong>External links</strong>: Quick access to GitHub, documentation, or cloud dashboards.</li></ul><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://content.brightbot.co.uk/2025/10/image-4.png" class="kg-image" alt="Building a Home Lab Dashboard with Homer" loading="lazy" width="3404" height="1508"><figcaption><span style="white-space: pre-wrap;">Example customised dashboard</span></figcaption></img></figure><hr><h2 id="tips-for-home-lab-use">Tips for Home Lab Use</h2><ul><li>Host Homer on a reverse proxy (like HAproxy or Nginx or Traefik) at <code>http://homer.your-domain</code>.</li><li>Use HTTPS with Let’s Encrypt if exposing outside your LAN.</li><li>Combine with authentication (Authelia, OAuth, etc.) for secure access or keep it hidden and internal use only.</li><li>Keep a <strong>backup of your config.yml</strong> — that’s your whole dashboard.</li></ul><hr><h2 id="conclusion">Conclusion</h2><p><strong>Homer</strong> is a simple, elegant way to bring order to your home lab chaos. With one URL, you get a beautiful dashboard that keeps all your services accessible and organised. It’s lightweight, easy to configure, and endlessly customisable.</p><p>If your browser bookmarks are overflowing or you’ve ever forgotten which port a service runs on, Homer is the perfect solution.</p><hr><h2 id="references">References</h2><ul><li><a href="https://github.com/louislam/uptime-kuma">https://github.com/louislam/uptime-kuma</a></li></ul><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/louislam/uptime-kuma"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - louislam/uptime-kuma: A fancy self-hosted monitoring tool</div><div class="kg-bookmark-description">A fancy self-hosted monitoring tool. Contribute to louislam/uptime-kuma development by creating an account on GitHub.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://static.ghost.org/v5.0.0/images/link-icon.svg" alt="Building a Home Lab Dashboard with Homer"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">louislam</span></img></div></div><div class="kg-bookmark-thumbnail"><img src="https://repository-images.githubusercontent.com/382496361/f21b61f5-693a-4925-9f1f-fea237ade223" alt="Building a Home Lab Dashboard with Homer" onerror="this.style.display = 'none'"/></div></a></figure><ul><li><a href="https://community-scripts.github.io/ProxmoxVE/scripts?id=uptimekuma">https://community-scripts.github.io/ProxmoxVE/scripts?id=uptimekuma</a></li></ul><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://community-scripts.github.io/ProxmoxVE/scripts?id=uptimekuma"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Proxmox VE Helper-Scripts</div><div class="kg-bookmark-description">The official website for the Proxmox VE Helper-Scripts (Community) repository. Featuring over 300+ scripts to help you manage your Proxmox Virtual Environment.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://static.ghost.org/v5.0.0/images/link-icon.svg" alt="Building a Home Lab Dashboard with Homer"><span class="kg-bookmark-author">Proxmox VE Helper-Scripts</span><span class="kg-bookmark-publisher">Bram Suurd</span></img></div></div><div class="kg-bookmark-thumbnail"><img src="https://community-scripts.github.io/ProxmoxVE/defaultimg.png" alt="Building a Home Lab Dashboard with Homer" onerror="this.style.display = 'none'"/></div></a></figure></hr></hr></hr></hr></hr></hr></hr></hr>]]></content:encoded></item><item><title><![CDATA[Monitoring Services with Uptime Kuma]]></title><description><![CDATA[If you run self-hosted apps, home lab services, or production infrastructure, you know the feeling: is it just me, or is the service down? Instead of waiting for someone to complain (or discovering it yourself when you try to use it), it’s better to have a monitoring tool that tells you when things break — and ideally before your users notice.

That’s where Uptime Kuma comes in.


What is Uptime Kuma?

Uptime Kuma is a self-hosted, open-source status monitoring tool. Think of it as a free, self-]]></description><link>https://brightbot.co.uk/monitoring-services-with-uptime-kuma/</link><guid isPermaLink="false">Ghost__Post__68e034f264bc86d5eba4003b</guid><category><![CDATA[Home Lab]]></category><category><![CDATA[Infrastructure]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Fri, 03 Oct 2025 20:52:56 GMT</pubDate><media:content url="https://content.brightbot.co.uk/2025/10/Screenshot-2025-10-03-at-21.52.33.png" medium="image"/><content:encoded><![CDATA[<img src="https://content.brightbot.co.uk/2025/10/Screenshot-2025-10-03-at-21.52.33.png" alt="Monitoring Services with Uptime Kuma"/><p>If you run self-hosted apps, home lab services, or production infrastructure, you know the feeling: <em>is it just me, or is the service down?</em> Instead of waiting for someone to complain (or discovering it yourself when you try to use it), it’s better to have a monitoring tool that tells you when things break — and ideally before your users notice.</p><p>That’s where <a href="https://github.com/louislam/uptime-kuma" rel="noreferrer"><strong>Uptime Kuma</strong></a> comes in.</p><hr><h2 id="what-is-uptime-kuma">What is Uptime Kuma?</h2><p>Uptime Kuma is a self-hosted, open-source <strong>status monitoring tool</strong>. Think of it as a free, self-managed alternative to services like UptimeRobot or StatusCake. It lets you monitor websites, APIs, and network services, then alerts you when they go down.</p><p>Key features:</p><ul><li><strong>Multiple monitor types</strong>: HTTP(s), TCP, ICMP (ping), DNS, Push, and more.</li><li><strong>Customisable alerts</strong>: Email, Telegram, Discord, Slack, Gotify, Pushover, etc.</li><li><strong>Beautiful dashboard</strong>: A clean web interface with status history and charts.</li><li><strong>Public status pages</strong>: Share uptime with your team or community.</li><li><strong>Self-hosted</strong>: You control the data and deployment.</li></ul><hr><h2 id="why-use-uptime-kuma">Why Use Uptime Kuma?</h2><ul><li><strong>Keep an eye on home lab services</strong> (Pi-hole, Home Assistant, media servers).</li><li><strong>Monitor production apps</strong> and APIs with confidence.</li><li><strong>Get alerts quickly</strong> instead of discovering downtime by accident.</li><li><strong>Track historical uptime</strong> for troubleshooting or reporting.</li><li><strong>Run it anywhere</strong> — from a Raspberry Pi to a cloud VPS.</li></ul><hr><h2 id="installing-uptime-kuma">Installing Uptime Kuma</h2><h3 id="using-docker">Using docker</h3><p>The easiest way to get started is with Docker:</p><pre><code class="language-bash">docker run -d \
  --restart=always \
  -p 3001:3001 \
  -v uptime-kuma:/app/data \
  louislam/uptime-kuma</code></pre><p>This runs Uptime Kuma on port <code>3001</code> and persists data in a Docker volume.</p><p>Then, open <code>http://your-server:3001</code> in a browser, create an admin account, and you’re ready to go.</p><h3 id="using-proxmox-lxc">Using Proxmox LXC</h3><p>Kuma is even easier to setup in Proxmox using a LXC Container, there is a community script available and its instructions can be found here:<br><a href="https://community-scripts.github.io/ProxmoxVE/scripts?id=uptimekuma">https://community-scripts.github.io/ProxmoxVE/scripts?id=uptimekuma</a></br></p><p>Always good to review scripts before blindly running them on your hardware but its as simple as running the following script and following the steps in the console</p><pre><code class="language-bash">bash -c "$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/ct/uptimekuma.sh)"</code></pre><hr><h2 id="adding-a-monitor">Adding a Monitor</h2><figure class="kg-card kg-image-card kg-width-wide kg-card-hascaption"><img src="https://content.brightbot.co.uk/2025/10/image-1.png" class="kg-image" alt="Monitoring Services with Uptime Kuma" loading="lazy" width="3404" height="1826"><figcaption><span style="white-space: pre-wrap;">Showing the create/edit monitor form</span></figcaption></img></figure><ol><li>Log in to the dashboard.</li><li>Click <strong>Add New Monitor</strong>.</li><li>Choose a monitor type (e.g., HTTP(s), Ping, TCP).</li><li>Enter the target URL or IP.</li><li>Configure interval, timeout, and retries.</li><li>Save — and your monitor starts running.</li></ol><p>You’ll see real-time status updates, response times, and uptime percentages.</p><figure class="kg-card kg-image-card kg-width-wide kg-card-hascaption"><img src="https://content.brightbot.co.uk/2025/10/image.png" class="kg-image" alt="Monitoring Services with Uptime Kuma" loading="lazy" width="3404" height="1826"><figcaption><span style="white-space: pre-wrap;">Showing the monitor once it has been setup</span></figcaption></img></figure><p>You can take this further by assigning meaningful Tags to categorise monitors such as in my example if it is a public facing endpoint or an internal endpoint.</p><hr><h2 id="setting-up-alerts">Setting Up Alerts</h2><p>Uptime Kuma supports a wide range of notifications. For example, to set up <strong>Telegram alerts</strong>:</p><ol><li>Go to <strong>Settings → Notification</strong>.</li><li>Add a new notification of type <strong>Telegram Bot</strong>.</li><li>Provide your bot token and chat ID.</li><li>Link it to one or more monitors.</li></ol><p>Now, you’ll get a Telegram message whenever a service goes down or comes back up.</p><hr><h2 id="public-status-page">Public Status Page</h2><p>One of Uptime Kuma’s nicest features is the ability to generate a <strong>public status page</strong>. This is great if you’re running services for others (or just want a clean way to check everything at a glance).</p><p>You can create multiple pages — for example:</p><ul><li><strong>Internal status page</strong> for your home lab.</li><li><strong>External status page</strong> for services your users access.</li></ul><p>Each page shows uptime graphs, response times, and the current state of your monitors.</p><figure class="kg-card kg-image-card kg-width-wide kg-card-hascaption"><img src="https://content.brightbot.co.uk/2025/10/Screenshot-2025-10-03-at-21.47.29.png" class="kg-image" alt="Monitoring Services with Uptime Kuma" loading="lazy" width="3404" height="1826"><figcaption><span style="white-space: pre-wrap;">An example status page once configured</span></figcaption></img></figure><hr><h2 id="conclusion">Conclusion</h2><p><strong>Uptime Kuma</strong> is an excellent, self-hosted alternative for service monitoring. It’s lightweight, feature-rich, and easy to deploy. Whether you’re running a home lab, side projects, or production systems, Kuma gives you peace of mind by watching your services and notifying you when something breaks.</p><p>If you’ve been relying on hope (or user complaints) to know when things go down, give Kuma a try — your future self will thank you.</p><hr><h2 id="references">References</h2><ul><li><a href="https://github.com/louislam/uptime-kuma">https://github.com/louislam/uptime-kuma</a></li></ul><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/louislam/uptime-kuma"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - louislam/uptime-kuma: A fancy self-hosted monitoring tool</div><div class="kg-bookmark-description">A fancy self-hosted monitoring tool. Contribute to louislam/uptime-kuma development by creating an account on GitHub.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://static.ghost.org/v5.0.0/images/link-icon.svg" alt="Monitoring Services with Uptime Kuma"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">louislam</span></img></div></div><div class="kg-bookmark-thumbnail"><img src="https://repository-images.githubusercontent.com/382496361/f21b61f5-693a-4925-9f1f-fea237ade223" alt="Monitoring Services with Uptime Kuma" onerror="this.style.display = 'none'"/></div></a></figure><ul><li><a href="https://community-scripts.github.io/ProxmoxVE/scripts?id=uptimekuma">https://community-scripts.github.io/ProxmoxVE/scripts?id=uptimekuma</a></li></ul><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://community-scripts.github.io/ProxmoxVE/scripts?id=uptimekuma"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Proxmox VE Helper-Scripts</div><div class="kg-bookmark-description">The official website for the Proxmox VE Helper-Scripts (Community) repository. Featuring over 300+ scripts to help you manage your Proxmox Virtual Environment.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://static.ghost.org/v5.0.0/images/link-icon.svg" alt="Monitoring Services with Uptime Kuma"><span class="kg-bookmark-author">Proxmox VE Helper-Scripts</span><span class="kg-bookmark-publisher">Bram Suurd</span></img></div></div><div class="kg-bookmark-thumbnail"><img src="https://community-scripts.github.io/ProxmoxVE/defaultimg.png" alt="Monitoring Services with Uptime Kuma" onerror="this.style.display = 'none'"/></div></a></figure></hr></hr></hr></hr></hr></hr></hr></hr>]]></content:encoded></item><item><title><![CDATA[Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 2]]></title><description><![CDATA[If you haven't read Part 1 of this series it can be found here Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 1

Amazon CloudFront is a powerful CDN for speeding up content delivery. By default, when you create a distribution, AWS gives you a long, autogenerated domain like:

d1234abcdef.cloudfront.net

That works fine, but it’s not user-friendly. For production, you’ll usually want to use your own domain — for example, content.yoursite.com — so your assets are delivered u]]></description><link>https://brightbot.co.uk/setting-up-ghost-with-s3-storage-using-ghost-storage-adapter-s3-part-2/</link><guid isPermaLink="false">Ghost__Post__68deff7f64bc86d5eba3ffc3</guid><category><![CDATA[AWS]]></category><category><![CDATA[Infrastructure]]></category><category><![CDATA[Home Lab]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Thu, 02 Oct 2025 23:01:18 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1662947368791-8630979e964b?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDl8fGFtYXpvbiUyMHdlYnxlbnwwfHx8fDE3NTk0NDYyODd8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1662947368791-8630979e964b?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDl8fGFtYXpvbiUyMHdlYnxlbnwwfHx8fDE3NTk0NDYyODd8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 2"/><p>If you haven't read Part 1 of this series it can be found here <a href="https://brightbot.co.uk/setting-up-ghost-with-s3-storage-using-ghost-storage-adapter-s3/" rel="noreferrer">Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 1</a></p><p>Amazon CloudFront is a powerful CDN for speeding up content delivery. By default, when you create a distribution, AWS gives you a long, autogenerated domain like:</p><pre><code class="language-bash">d1234abcdef.cloudfront.net</code></pre><p>That works fine, but it’s not user-friendly. For production, you’ll usually want to use your own domain — for example, <strong>content.yoursite.com</strong> — so your assets are delivered under your brand.</p><p>In this post, I’ll walk through setting up a CloudFront distribution with a <strong>custom domain alias (CNAME)</strong>.</p><hr><h2 id="prerequisites">Prerequisites</h2><ul><li>An AWS account with CloudFront enabled. (This is covered in Part 1)</li><li>A domain you own (registered with Route 53 or another DNS provider).</li><li>An SSL/TLS certificate in AWS Certificate Manager (ACM) for your domain.</li></ul><hr><p>Just like the Previous post, example AWS CloudFormation templates are available on my GitHub and can be found here and navigate to the <code>ghost-storage-adapter-s3</code> directory or using the individual links linked below. Or you can follow the steps to create it manually.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/atownsend247/brightbot-source-files/tree/main"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - atownsend247/brightbot-source-files: Provides git access to scripts and templates for associated BrightBot blog posts</div><div class="kg-bookmark-description">Provides git access to scripts and templates for associated BrightBot blog posts - atownsend247/brightbot-source-files</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://static.ghost.org/v5.0.0/images/link-icon.svg" alt="Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 2"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">atownsend247</span></img></div></div><div class="kg-bookmark-thumbnail"><img src="https://opengraph.githubassets.com/48597fed9a6461baf4b9cab167d58f0c122a8fbb8b77948e99a9043df6cd8a57/atownsend247/brightbot-source-files" alt="Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 2" onerror="this.style.display = 'none'"/></div></a></figure><ul><li><a href="https://github.com/atownsend247/brightbot-source-files/blob/main/ghost-storage-adapter-s3/cloudformation-template-acm.yaml">cloudformation-template-acm.yaml</a> Stack to create the AWS Amazon Certificate Manager (ACM) Certificate in the us-east-1 region.</li><li><a href="https://github.com/atownsend247/brightbot-source-files/blob/main/ghost-storage-adapter-s3/cloudformation-template-with-acm-alias.yaml">cloudformation-template-with-acm-alias.yaml</a> An update template from Part 1, that includes a custom CloudFront alias and certificate configuration.</li></ul><h2 id="step-1-request-an-ssltls-certificate">Step 1: Request an SSL/TLS Certificate</h2><p>To use a custom domain with CloudFront, you need an SSL certificate.</p><ol><li>Request a public certificate for your custom domain (e.g., <code>content.yoursite.com</code>).</li><li>Validate the certificate using DNS or email (DNS is recommended).</li></ol><p>Go to <strong>AWS Certificate Manager</strong> in the <strong>us-east-1 (N. Virginia)</strong> region.</p><blockquote>Important: CloudFront only uses certificates in <strong>us-east-1</strong>, even if your distribution is elsewhere.</blockquote><p>Once validated, your certificate will show as <strong>Issued</strong>.</p><hr><h2 id="step-2-create-or-edit-a-cloudfront-distribution">Step 2: Create or Edit a CloudFront Distribution</h2><ol><li>Go to <strong>CloudFront &gt; Distributions</strong> and click <strong>Create Distribution</strong> (or edit an existing one).</li><li>Under <strong>Settings → Alternate Domain Names (CNAMEs)</strong>, enter your custom domain:</li></ol><pre><code class="language-bash">content.yoursite.com
</code></pre><ol start="3"><li>Under <strong>Custom SSL Certificate</strong>, select the certificate you created in ACM.</li><li>Configure the rest of your distribution (origin, caching, behaviors) as usual.</li><li>Save and deploy the distribution.</li></ol><hr><h2 id="step-3-update-your-dns">Step 3: Update Your DNS</h2><p>Now you need to point your custom domain to the CloudFront distribution.</p><ol><li>Go to your DNS provider (Route 53 or elsewhere).</li><li>Create a <strong>CNAME record</strong> for your custom domain:</li></ol><pre><code class="language-bash">content.yoursite.com → d1234abcdef.cloudfront.net</code></pre><ol start="3"><li>Save the record.</li></ol><p>DNS changes may take some time to propagate.</p><hr><h2 id="step-4-test-the-setup">Step 4: Test the Setup</h2><p>Once DNS propagation is complete:</p><ul><li>Visit <code>https://content.yoursite.com</code> in your browser.</li><li>You should see content served from CloudFront.</li><li>Check the SSL certificate — it should show your custom domain.</li></ul><hr><h2 id="step-5-update-configuration-of-ghost-to-use-the-adapter">Step 5: Update configuration of Ghost to Use the Adapter</h2><p>In your Ghost config file (<code>config.production.json</code>), update the storage block <strong>assetHost</strong> property:</p><pre><code class="language-json">{
  ...,
  "storage": {
    "active": "s3",
    "s3": {
      ...
      "assetHost": "https://content.yoursite.com",
      ...
    }
  }
}</code></pre><p>Save the config file and restart your Ghost instance to apply changes:</p><pre><code class="language-bash">ghost restart</code></pre><p>From now on, uploaded images and media will go directly to your S3 bucket instead of local disk.</p><hr><h2 id="tips-best-practices">Tips &amp; Best Practices</h2><ul><li><strong>Use Route 53 with Alias Records</strong>: If your custom domain is a root domain (<code>example.com</code> instead of <code>cdn.example.com</code>), use an Alias record in Route 53 instead of CNAME.</li><li><strong>Leverage a CDN subdomain</strong>: Keeping CDN assets on <code>cdn.yoursite.com</code> helps separate them from your main domain.</li><li><strong>Enable logging</strong>: CloudFront can log requests to S3 for debugging and analytics.</li><li><strong>Cache policies</strong>: Fine-tune cache behavior to balance performance and freshness.</li></ul><hr><h2 id="conclusion">Conclusion</h2><p>Setting up a CloudFront distribution with a <strong>custom domain alias</strong> gives you:</p><ul><li>A cleaner, branded URL for your assets.</li><li>SSL/TLS encryption with your own domain certificate.</li><li>The speed and scalability of AWS CloudFront.</li></ul><p>Once configured, your site looks more professional and benefits from faster, more secure content delivery.</p><p>This tutorial has talked you through fully configuring Ghost to use an external storage adapter utilising Amazon S3, Amazon CloudFront, Amazon ACM Certificate.</p><hr><h2 id="other-posts-in-this-series">Other posts in this series</h2><ul><li><a href="https://brightbot.co.uk/setting-up-ghost-with-s3-storage-using-ghost-storage-adapter-s3/" rel="noreferrer">Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 1</a></li><li><a href="https://brightbot.co.uk/setting-up-ghost-with-s3-storage-using-ghost-storage-adapter-s3-part-2/" rel="noreferrer">Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 2</a></li></ul></hr></hr></hr></hr></hr></hr></hr></hr></hr>]]></content:encoded></item><item><title><![CDATA[Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 1]]></title><description><![CDATA[By default, Ghost stores uploaded images and media locally on the same server that runs Ghost. That works fine for small blogs, but if you want to run Ghost in a scalable environment (like Docker, Kubernetes, or multiple servers behind a load balancer), you’ll quickly run into problems.

To make Ghost more flexible, you can use Amazon S3 (or an S3-compatible service like MinIO, DigitalOcean Spaces, or Backblaze B2) for media storage. This decouples your storage from the Ghost instance, ensuring ]]></description><link>https://brightbot.co.uk/setting-up-ghost-with-s3-storage-using-ghost-storage-adapter-s3/</link><guid isPermaLink="false">Ghost__Post__68de512573be1314e6d24b0e</guid><category><![CDATA[AWS]]></category><category><![CDATA[Infrastructure]]></category><category><![CDATA[Home Lab]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Thu, 02 Oct 2025 14:32:08 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1662947368907-808ab49b9495?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDN8fGFtYXpvbiUyMHdlYiUyMHNlcnZpY2VzfGVufDB8fHx8MTc1OTQxODc2OHww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1662947368907-808ab49b9495?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDN8fGFtYXpvbiUyMHdlYiUyMHNlcnZpY2VzfGVufDB8fHx8MTc1OTQxODc2OHww&ixlib=rb-4.1.0&q=80&w=2000" alt="Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 1"/><p>By default, <a rel="noopener">Ghost</a> stores uploaded images and media locally on the same server that runs Ghost. That works fine for small blogs, but if you want to run Ghost in a <strong>scalable environment</strong> (like Docker, Kubernetes, or multiple servers behind a load balancer), you’ll quickly run into problems.</p><p>To make Ghost more flexible, you can use <strong>Amazon S3 (or an S3-compatible service like MinIO, DigitalOcean Spaces, or Backblaze B2)</strong> for media storage. This decouples your storage from the Ghost instance, ensuring uploads are consistent across deployments.</p><p>The main driver behind this, was to use <strong>Ghost</strong> as a completely headless CMS allowing for Gatsby to serve images easily and separately without exposing my Ghost instance to the public. This process allows you to upload images within Ghost and have them available within a Gatsby generated site.</p><p>In this post, I’ll walk through setting up Ghost with <a href="https://github.com/colinmeinke/ghost-storage-adapter-s3" rel="noopener"><code>ghost-storage-adapter-s3</code></a>. Using <strong>Amazon S3 and Amazon CloudFront</strong> to seamlessly serve images  for both Ghost as CMS and Gatsby as a static website.</p><hr><h2 id="why-use-s3-for-ghost-storage">Why Use S3 for Ghost Storage?</h2><ul><li><strong>Scalability</strong>: Media is available no matter how many Ghost instances you run.</li><li><strong>Durability</strong>: S3 handles replication and durability better than local disk.</li><li><strong>Flexibility</strong>: Works with AWS S3 or any S3-compatible service.</li><li><strong>Portability</strong>: Makes running Ghost in containers or serverless setups easier.</li></ul><hr><h2 id="why-use-cloudfront-for-asset-delivery">Why Use CloudFront for asset delivery?</h2><ul><li><strong>Fast</strong>: Caches your content across a global network of edge locations, so users get data from the nearest server instead of your origin. This reduces latency and speeds up page loads.</li><li><strong>Scalability</strong>: Your site can handle sudden traffic spikes without overwhelming your origin server. It distributes requests across multiple edge locations, keeping things stable even under heavy load.</li><li><strong>Security</strong>: integrates with <strong>AWS Shield</strong>, <strong>WAF</strong>, and SSL/TLS to protect against DDoS attacks, bots, and other threats — while ensuring encrypted connections for your users.</li><li><strong>Cost</strong>: By caching content at the edge, CloudFront reduces the amount of data pulled directly from your origin (like S3 or an EC2 instance). That means lower bandwidth costs and more efficient infrastructure usage.</li></ul><hr><h2 id="prerequisites">Prerequisites</h2><ul><li>A running Ghost instance (self-hosted).</li><li>Node.js environment (to install the adapter).</li><li>An Amazon S3 bucket. (Steps to create these will also be detailed below)</li><li>An Amazon CloudFront distribution. (Steps to create these will also be detailed below)</li><li>AWS IAM Access key + Secret key with appropriate permissions. (Steps to create these will also be detailed below)</li></ul><hr><h2 id="step-1-install-ghost-storage-adapter-s3">Step 1: Install <code>ghost-storage-adapter-s3</code></h2><p>Navigate to your Ghost installation directory and install the adapter:</p><pre><code class="language-bash">npm install ghost-storage-adapter-s3
mkdir -p ./content/adapters/storage
cp -r ./node_modules/ghost-storage-adapter-s3 ./content/adapters/storage/s3</code></pre><p>Ghost looks in <code>content/adapters/storage/</code> for storage adapters, so the directory structure is important</p><ul><li>Node.js environment (to install the adapter).</li><li>An S3 bucket (AWS or compatible).</li><li>S3 access key + secret key with appropriate permissions.</li></ul><hr><h2 id="step-2-configure-aws-resources">Step 2: Configure AWS resources</h2><p>There are two ways to proceed with AWS, I would strongly suggest using the CloudFormation template and sticking with Configuration as Source Code, but I have included the manual steps also if that is more preferable. At the end of this s you should have the values for</p><ul><li>AWS CLI Access Key - Used by Ghost to authenticate with AWS</li><li>AWS CLI Secret Access Key - Used in conjunction with the Access Key</li><li>AWS Region - The region in which your resources are deployed</li><li>AWS CloudFront distribution URL - Used as assetHost</li></ul><h3 id="using-a-cloudformation-template">Using a CloudFormation Template</h3><p>I have provided a GitHub repository for this article that offers a bare bones CloudFormation template which will provision the following AWS resources:</p><ul><li>24 Hour CloudFront Cache Policy</li><li>CloudFront Origin Access Control (OAC)</li><li>S3 Storage Bucket</li><li>S3 Storage Bucket Policy - Linking the Distribution/OAC with the bucket</li><li>IAM Ghost User - Used by Ghost to access the bucket securely</li><li>IAM Ghost User Policy</li><li>CloudFront Distribution</li></ul><p>The code can be reviewed here: <a href="https://github.com/atownsend247/brightbot-source-files/blob/main/ghost-storage-adapter-s3/cloudformation-template.yaml">https://github.com/atownsend247/brightbot-source-files/blob/main/ghost-storage-adapter-s3/cloudformation-template.yaml</a></p><p>You can use this to create a new CloudFormation stack from the AWS Console, then update the <code>Project</code> parameter to suit your requirement.</p><p>Finally once created complete, reference the Outputs tab of CloudFormation to get the CloudFront distribution URL to use as&nbsp;<em><strong>assetHost</strong> later on</em>.</p><p>Now the IAM user is created navigate to it in the AWS Console, click on <code>Security Credentials</code> -&gt; <code>Create access key</code>. Select <strong>Command Line Interface (CLI)</strong>, select the confirmation, give it a friendly name and either download the credentials.csv or copy the <strong>Access key</strong> value and <strong>Secret access key</strong> to somewhere safe as we need these later.</p><h3 id="manually-creating-resources">Manually creating resources</h3><p>You'll likely want to configure a separate S3 bucket for your blog, a specific IAM role, and, optionally, CloudFront, to serve from a CDN.</p><h3 id="s3">S3</h3><p><a href="https://github.com/colinmeinke/ghost-storage-adapter-s3#s3"/></p><p>Create a new bucket. The region isn't important at this stage. </p><p>As we are setting this up manually, you can let Amazon CloudFront setup the OAC (Origin Access Control) on your behalf.</p><h3 id="iam">IAM</h3><p><a href="https://github.com/colinmeinke/ghost-storage-adapter-s3#iam"/></p><p>You'll want to create a custom user role in IAM that just gives your Ghost installation the necessary permissions to manipulate objects in its S3 bucket.</p><p>Go to IAM in your AWS console and add a new user. Give it a username specific to your blog, and select&nbsp;<strong>Programmatic access</strong>&nbsp;as the Access type.</p><p>Next, on the permissions page, select&nbsp;<strong>Attach existing policies directly</strong>&nbsp;and click to&nbsp;<strong>Create policy</strong>. For the policy click on the JSON editor and add the following policy. You'll want to replace where it says&nbsp;<strong>your-bucket-name</strong>&nbsp;with the name of your blog's S3 bucket.</p><figure class="kg-card kg-code-card"><pre><code class="language-json">{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "s3:ListBucket",
            "Resource": "arn:aws:s3:::your-bucket-name"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:PutObjectVersionAcl",
                "s3:DeleteObject",
                "s3:PutObjectAcl"
            ],
            "Resource": "arn:aws:s3:::your-bucket-name/*"
        }
    ]
}
</code></pre><figcaption><p><span style="white-space: pre-wrap;">IAM User Policy</span></p></figcaption></figure><p>What this policy does is allow the user access to see the contents of the bucket (the first statement), and then manipulate the objects stored in the bucket (the second statement).</p><p>Finally, create the user and copy the&nbsp;<strong>Access key</strong>&nbsp;and&nbsp;<strong>Secret access key</strong>, these are what you'll use in your configuration.</p><p>At this point your done with the <strong>Ghost</strong> access to Amazon S3</p><h3 id="cloudfront">CloudFront</h3><p><a href="https://github.com/colinmeinke/ghost-storage-adapter-s3#cloudfront"/></p><p>CloudFront is a CDN that replicates objects in servers around the world so your blog's visitors will get your assets faster by using the server closest to them. It uses your S3 bucket as the "source of truth" that it populates its servers with.</p><p>Got to CloudFront in AWS and choose to&nbsp;<strong>Create a Distribution</strong>. On the next screen you'll want to leave everything the same, except change the following:</p><ul><li>Origin - Select Amazon S3<ul><li>Click the <strong>Browse S3</strong> button and find your newly created bucket</li><li>Ensure <strong>Allow private S3 bucket access to CloudFront -&nbsp;<em>Recommended</em><em> is selected as this will setup the secure/private permissions for you</em></strong></li></ul></li><li>Viewer Protocol Policy:&nbsp;<strong>Redirect HTTP to HTTPS</strong></li><li>Compress Objects Automatically:&nbsp;<strong>Yes</strong></li></ul><p>Then create the distribution.</p><p>Finally, in your configuration, use the subdomain for the CloudFront distribution as your setting for&nbsp;<strong><em>assetHost</em></strong>.</p><hr><h2 id="step-3-configure-ghost-to-use-the-adapter">Step 3: Configure Ghost to Use the Adapter</h2><p>In your Ghost config file (<code>config.production.json</code>), add the storage block:</p><pre><code class="language-json">{
  ...,
  "storage": {
    "active": "s3",
    "s3": {
      "accessKeyId": "YOUR_AWS_ACCESS_KEY",
      "secretAccessKey": "YOUR_AWS_SECRET_KEY",
      "region": "your-region",
      "bucket": "your-s3-bucket-name",
      "assetHost": "https://your-cloudfront-endpoint",
      "serverSideEncryption": "AES256",
      "forcePathStyle": true,
      "acl": "private"
    }
  }
}</code></pre><ul><li><code>accessKeyId</code> -&gt; Your AWS access key for the user with required permissions.</li><li><code>secretAccessKey</code> -&gt; Your AWS secret key for the user with required permissions.</li><li><code>region</code> → your S3 bucket’s AWS region.</li><li><code>bucket</code> → the name of your S3 bucket.</li><li><code>assetHost</code> → for serveing media via CloudFront.</li></ul><hr><h2 id="step-4-restart-ghost">Step 4: Restart Ghost</h2><p>Restart your Ghost instance to apply changes:</p><pre><code class="language-bash">ghost restart</code></pre><p>From now on, uploaded images and media will go directly to your S3 bucket instead of local disk.</p><hr><h2 id="step-5-verify-uploads">Step 5: Verify Uploads</h2><ol><li>Log in to your Ghost admin panel.</li><li>Upload an image to a post.</li><li>Check your S3 bucket (or CDN) to confirm the file is there.</li></ol><p>If you see the image in S3 and it loads in your post, you’re good to go.</p><hr><h2 id="conclusion">Conclusion</h2><p>With <strong><code>ghost-storage-adapter-s3</code></strong>, you can decouple Ghost’s media storage from your server, making your blog more resilient and easier to scale. Whether you’re running Ghost in Docker, on Kubernetes, or just want the reliability of cloud storage, this setup is a solid way to go.</p><p>If you also serve your media through a CDN (like CloudFront), you’ll get the added bonus of faster load times for readers all over the world.</p><p>Head over to Part 2 linked below, to expand this further and use a custom domain with AWS CloudFront.</p><hr><h2 id="other-posts-in-this-series">Other posts in this series</h2><ul><li><a href="https://brightbot.co.uk/setting-up-ghost-with-s3-storage-using-ghost-storage-adapter-s3/" rel="noreferrer">Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 1</a></li><li><a href="https://brightbot.co.uk/setting-up-ghost-with-s3-storage-using-ghost-storage-adapter-s3-part-2/" rel="noreferrer">Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 2</a></li></ul><hr><h2 id="references">References</h2><ul><li><a href="https://ghost.org/">https://ghost.org/</a></li></ul><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://ghost.org/"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Ghost: The best open source blog &amp; newsletter platform</div><div class="kg-bookmark-description">Beautiful, modern publishing with email newsletters and paid subscriptions built-in. Used by Platformer, 404Media, Lever News, Tangle, The Browser, and thousands more.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://static.ghost.org/v5.0.0/images/link-icon.svg" alt="Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 1"><span class="kg-bookmark-author">Ghost - The Professional Publishing Platform</span></img></div></div><div class="kg-bookmark-thumbnail"><img src="https://ghost.org/images/meta/ghost-6.png" alt="Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 1" onerror="this.style.display = 'none'"/></div></a></figure><ul><li><a href="https://github.com/colinmeinke/ghost-storage-adapter-s3">https://github.com/colinmeinke/ghost-storage-adapter-s3</a></li></ul><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/colinmeinke/ghost-storage-adapter-s3"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - colinmeinke/ghost-storage-adapter-s3: An AWS S3 storage adapter for Ghost</div><div class="kg-bookmark-description">An AWS S3 storage adapter for Ghost. Contribute to colinmeinke/ghost-storage-adapter-s3 development by creating an account on GitHub.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://static.ghost.org/v5.0.0/images/link-icon.svg" alt="Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 1"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">colinmeinke</span></img></div></div><div class="kg-bookmark-thumbnail"><img src="https://opengraph.githubassets.com/8c0b29dc0b94f6ddbd92e297cfa2f673a64135c86db85769b8238d7b6a5cb0d7/colinmeinke/ghost-storage-adapter-s3" alt="Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 1" onerror="this.style.display = 'none'"/></div></a></figure><ul><li><a href="https://github.com/atownsend247/brightbot-source-files/blob/main/ghost-storage-adapter-s3/cloudformation-template.yaml">https://github.com/atownsend247/brightbot-source-files/blob/main/ghost-storage-adapter-s3/cloudformation-template.yaml</a></li></ul><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/atownsend247/brightbot-source-files"><div class="kg-bookmark-content"><div class="kg-bookmark-title">GitHub - atownsend247/brightbot-source-files: Provides git access to scripts and templates for associated BrightBot blog posts</div><div class="kg-bookmark-description">Provides git access to scripts and templates for associated BrightBot blog posts - atownsend247/brightbot-source-files</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://static.ghost.org/v5.0.0/images/link-icon.svg" alt="Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 1"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">atownsend247</span></img></div></div><div class="kg-bookmark-thumbnail"><img src="https://opengraph.githubassets.com/c6e194a6b39459e58442e3c61eb59fb95a6375271b9f8a393342104eb3b26b88/atownsend247/brightbot-source-files" alt="Setting Up Ghost with S3 Storage Using ghost-storage-adapter-s3: Part 1" onerror="this.style.display = 'none'"/></div></a></figure></hr></hr></hr></hr></hr></hr></hr></hr></hr></hr></hr>]]></content:encoded></item><item><title><![CDATA[Linting Documentation with Vale: Consistent, Clear, and Error-Free Writing]]></title><description><![CDATA[If you’ve ever worked on a large documentation project, you know how quickly things can get messy. Different contributors bring different writing styles, terminology gets inconsistent, and small grammar mistakes sneak through. That’s where Vale comes in — a linter for prose that helps keep your docs clean, consistent, and professional.


What is Vale?

Vale is an open-source command-line tool for linting and style-checking text. Think of it like ESLint or Prettier, but for documentation and pros]]></description><link>https://brightbot.co.uk/linting-documentation-with-vale-consistent-clear-and-error-free-writing/</link><guid isPermaLink="false">Ghost__Post__68dd733bcb5315e3604fce56</guid><category><![CDATA[Home Lab]]></category><category><![CDATA[Infrastructure]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Wed, 01 Oct 2025 18:38:50 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1600267204091-5c1ab8b10c02?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fGRvY3VtZW50YXRpb258ZW58MHx8fHwxNzU5MzQzOTE5fDA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1600267204091-5c1ab8b10c02?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDF8fGRvY3VtZW50YXRpb258ZW58MHx8fHwxNzU5MzQzOTE5fDA&ixlib=rb-4.1.0&q=80&w=2000" alt="Linting Documentation with Vale: Consistent, Clear, and Error-Free Writing"/><p>If you’ve ever worked on a large documentation project, you know how quickly things can get messy. Different contributors bring different writing styles, terminology gets inconsistent, and small grammar mistakes sneak through. That’s where <strong>Vale</strong> comes in — a linter for prose that helps keep your docs clean, consistent, and professional.</p><hr><h2 id="what-is-vale">What is Vale?</h2><p><a rel="noopener"><strong>Vale</strong></a> is an open-source command-line tool for linting and style-checking text. Think of it like ESLint or Prettier, but for documentation and prose instead of code. It helps you:</p><ul><li><strong>Enforce a consistent style</strong> across docs.</li><li><strong>Catch grammar, spelling, and clarity issues</strong> early.</li><li><strong>Standardize terminology</strong> (e.g., always use “sign in” instead of “login”).</li><li><strong>Automate reviews</strong> so humans can focus on content, not nitpicks.</li></ul><p>Vale works with Markdown, reStructuredText, AsciiDoc, and more — making it a great fit for docs-as-code workflows.</p><hr><h2 id="why-use-vale">Why Use Vale?</h2><ul><li><strong>Consistency matters</strong>: Readers trust documentation that feels cohesive.</li><li><strong>Saves reviewer time</strong>: Automates style nitpicks so reviewers can focus on accuracy.</li><li><strong>Integrates with CI/CD</strong>: Catch doc issues before merging.</li><li><strong>Customisable</strong>: Define your own style rules or adopt existing ones (like Google or Microsoft style guides).</li></ul><hr><h2 id="installing-vale">Installing Vale</h2><p>Vale is distributed as a single binary — no big dependencies.</p><p>On macOS (via Homebrew):</p><pre><code class="language-bash">brew install vale</code></pre><p>On Linux (via binary release):</p><pre><code class="language-bash">curl -s https://api.github.com/repos/errata-ai/vale/releases/latest \
| grep "browser_download_url.*Linux_64-bit.tar.gz" \
| cut -d '"' -f 4 \
| wget -qi - &amp;&amp; tar -xzf Vale_*_Linux_64-bit.tar.gz</code></pre><p>On Windows: download from the <a href="https://github.com/errata-ai/vale/releases" rel="noopener">Vale releases page</a>.</p><hr><h2 id="setting-up-vale">Setting Up Vale</h2><p>In the root of your docs project, create a <code>.vale.ini</code> file:</p><pre><code class="language-ini">StylesPath = styles
MinAlertLevel = suggestion

Packages = Google, proselint, write-good

[*.md]
BasedOnStyles = Vale, Google, proselint, write-good</code></pre><p>This tells Vale to:</p><ul><li>Look for styles in the <code>styles/</code> directory.</li><li>Use Microsoft’s style guide.</li><li>Apply it to all <code>.md</code> files.</li></ul><hr><h2 id="running-vale">Running Vale</h2><p>Once configured, lint your docs with:</p><pre><code class="language-bash">vale path/to/docs/</code></pre><p>Example output:</p><pre><code class="language-bash">docs/getting-started.md
 25:5  error  'login' should be written as 'sign in'  Google.Terms
 44:10 warning  Avoid using 'simply'                  Google.Avoid</code></pre><p><br/></p><p>Here you can see Vale catching terminology and tone issues automatically.</p><hr><h2 id="customizing-rules">Customizing Rules</h2><p>Vale is powerful because you can define your own style rules. For example, let’s enforce “e-mail” vs “email.”</p><p>Create a file at <code>styles/Custom/Terms.yml</code>:</p><pre><code class="language-yaml">extends: existence
message: "Use 'email' instead of 'e-mail'."
level: error
ignorecase: true
tokens:
  - e-mail</code></pre><p>Now Vale will flag “e-mail” anywhere in your docs.</p><hr><h2 id="using-vale-in-cicd">Using Vale in CI/CD</h2><p>To ensure consistency across teams, add Vale to your build pipeline. For example, in GitHub Actions:</p><pre><code class="language-yaml">name: Lint Docs

on: [pull_request]

jobs:
  vale:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Install Vale
        run: |
          curl -fsSL https://install.goreleaser.com/github.com/errata-ai/vale.sh | sh
          sudo mv ./bin/vale /usr/local/bin/
      - name: Run Vale
        run: vale .</code></pre><p>This way, PRs can’t be merged until documentation passes <strong>linting</strong>.</p><hr><h1 id="starter-vale-style-guide">Starter Vale Style Guide</h1><p>This starter style guide enforces <strong>clear, consistent, and professional writing</strong>. It includes rules for terminology, tone, and formatting that you can extend as your docs mature.</p><p>👉 Folder structure example:</p><pre><code class="language-bash">docs/
styles/
  Starter/
    Terms.yml
    Tone.yml
    Spacing.yml
.vale.ini</code></pre><hr><p><code>.vale.ini</code></p><pre><code class="language-ini">StylesPath = styles
MinAlertLevel = suggestion

[*.md]
BasedOnStyles = Starter</code></pre><p>This tells Vale to look in the <code>styles/</code> folder and apply the <code>Starter</code> style to all Markdown files.</p><hr><h2 id="termsyml-%E2%80%93-consistent-terminology"><code>Terms.yml</code> – Consistent Terminology</h2><pre><code class="language-yaml">extends: substitution
message: "Use '%s' instead of '%s'."
level: error
ignorecase: true
swap:
  login: sign in
  log-in: sign in
  e-mail: email
  Github: GitHub
  Javascript: JavaScript</code></pre><p>✅ Enforces consistent word choices and fixes common brand/style mistakes.</p><hr><h2 id="toneyml-%E2%80%93-avoid-filler-words"><code>Tone.yml</code> – Avoid Filler Words</h2><pre><code class="language-yaml">extends: existence
message: "Avoid using '%s'."
level: warning
ignorecase: true
tokens:
  - simply
  - obviously
  - clearly
  - basically
  - just</code></pre><p>✅ Flags words that can sound condescending or unnecessary in documentation.</p><hr><h2 id="spacingyml-%E2%80%93-clean-formatting"><code>Spacing.yml</code> – Clean Formatting</h2><pre><code class="language-yaml">extends: existence
message: "Use a single space between sentences."
level: error
nonword: true
tokens:
  - '\s{2,}'</code></pre><p>✅ Ensures no double spaces sneak into your text.</p><hr><h2 id="how-to-use">How to Use</h2><ol><li>Save the above files into <code>styles/Starter/</code>.</li><li>Update <code>.vale.ini</code> to include <code>Starter</code>.</li><li>Run <code>vale docs/</code> and watch it flag issues.</li></ol><hr><h2 id="example-in-action">Example in Action</h2><p>Input:</p><p><code>To login, just click the button.  Github is</code> simply awesome!<br/></p><p>Output:</p><pre><code class="language-bash"> 1:4  error   Use 'sign in' instead of 'login'.       Starter.Terms
 1:11 warning Avoid using 'just'.                     Starter.Tone
 1:29 error   Use 'GitHub' instead of 'Github'.       Starter.Terms
 1:37 warning Avoid using 'simply'.                   Starter.Tone
 1:50 error   Use a single space between sentences.   Starter.Spacing</code></pre><h2 id="conclusion">Conclusion</h2><p><strong>Vale</strong> takes the guesswork out of documentation quality. By automating style and consistency checks, it frees up writers and reviewers to focus on content and accuracy. Whether you’re maintaining internal runbooks, public APIs, or open-source docs, Vale helps you deliver polished, professional writing every time.</p><p>This starter style guide gives you:</p><ul><li><strong>Terminology enforcement</strong> (consistent words, correct brands).</li><li><strong>Tone checks</strong> (avoid filler or condescending words).</li><li><strong>Formatting rules</strong> (like spacing).</li></ul><p>It’s lightweight but effective — and you can extend it with custom rules as your docs grow.</p><p>If you’re serious about treating docs like code, adding Vale to your toolchain is a no-brainer.</p></hr></hr></hr></hr></hr></hr></hr></hr></hr></hr></hr></hr></hr></hr>]]></content:encoded></item><item><title><![CDATA[Setting Up Network UPS Tools (NUT) for APC UPS Devices on Linux]]></title><description><![CDATA[When you’re running critical systems — whether it’s a home lab, a small business server, or production workloads — power outages can cause real headaches. That’s where an Uninterruptible Power Supply (UPS) comes in. But to make the most of it, your server needs to know when the UPS is running on battery, when it’s low, and when to shut down gracefully.

That’s exactly what Network UPS Tools (NUT) does. In this guide, we’ll walk through setting up NUT on Linux with an APC UPS.


What is NUT?

Net]]></description><link>https://brightbot.co.uk/setting-up-network-ups-tools-nut-for-apc-ups-devices-on-linux/</link><guid isPermaLink="false">Ghost__Post__68dcea1bcb5315e3604fce08</guid><category><![CDATA[Home Lab]]></category><category><![CDATA[Infrastructure]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Wed, 01 Oct 2025 08:56:05 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1738520420641-0d39da26723c?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDM2fHxwb3dlciUyMHN1cHBseXxlbnwwfHx8fDE3NTkzMDkwMTV8MA&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1738520420641-0d39da26723c?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDM2fHxwb3dlciUyMHN1cHBseXxlbnwwfHx8fDE3NTkzMDkwMTV8MA&ixlib=rb-4.1.0&q=80&w=2000" alt="Setting Up Network UPS Tools (NUT) for APC UPS Devices on Linux"/><p>When you’re running critical systems — whether it’s a home lab, a small business server, or production workloads — power outages can cause real headaches. That’s where an <strong>Uninterruptible Power Supply (UPS)</strong> comes in. But to make the most of it, your server needs to know when the UPS is running on battery, when it’s low, and when to shut down gracefully.</p><p>That’s exactly what <strong>Network UPS Tools (NUT)</strong> does. In this guide, we’ll walk through setting up <strong>NUT</strong> on Linux with an <strong>APC UPS</strong>.</p><hr><h2 id="what-is-nut">What is NUT?</h2><p><strong>Network UPS Tools (NUT)</strong> is an open-source suite that provides:</p><ul><li>Drivers for a wide range of UPS devices (including APC).</li><li>A monitoring daemon to track UPS status.</li><li>Shutdown coordination for multiple systems.</li><li>Remote monitoring over the network.</li></ul><p>It’s highly flexible, works across many UPS models, and is widely used in both enterprise and homelab environments.</p><hr><h2 id="prerequisites">Prerequisites</h2><ul><li>A Linux system (Debian/Ubuntu, RHEL, or similar).</li><li>An APC UPS connected via USB or serial cable.</li><li>Root or sudo access.</li></ul><p>For the purposes of this post, I will be connecting 2x APC UPS-B Back-UPS XS 1400U UPS's to a single Raspberry Pi5</p><hr><h2 id="step-1-install-nut">Step 1: Install NUT</h2><p>On Debian/Ubuntu:</p><pre><code class="language-bash">sudo apt update
sudo apt install nut nut-client nut-server</code></pre><hr><h2 id="step-2-identify-your-ups">Step 2: Identify Your UPS</h2><p>Plug in your APC UPS via USB, then run:</p><pre><code class="language-bash">lsusb
</code></pre><p>You should see something like:</p><pre><code class="language-bash">Bus 001 Device 005: ID 051d:0002 American Power Conversion Uninterruptible Power Supply
Bus 001 Device 004: ID 051d:0002 American Power Conversion Uninterruptible Power Supply</code></pre><p>This tells us the UPS is detected.</p><hr><h2 id="step-3-configure-nut-driver">Step 3: Configure NUT Driver</h2><p>Edit <code>/etc/nut/ups.conf</code>:</p><pre><code class="language-bash"># Generic APC UPS
[apc]
    driver = usbhid-ups
    port = auto
    desc = "APC UPS"

# Specific to my UPSs
[apcupsa]
driver = usbhid-ups
desc = "APC UPS-A Back-UPS XS 1400U 4B2028P50251"
port = auto
vendorid = 051d
productid = 0002
serial = serial1

[apcupsb]
driver = usbhid-ups
desc = "APC UPS-B Back-UPS XS 1400U 4B2028P50042"
port = auto
vendorid = 051d
productid = 0002
serial = serial2</code></pre><ul><li><code>apc</code> is the UPS name (you can choose your own).</li><li><code>usbhid-ups</code> is the driver used for most modern APC UPS devices.</li><li><code>port = auto</code> lets NUT detect the UPS automatically.</li></ul><p>Test the driver:</p><pre><code class="language-bash">sudo upsdrvctl start</code></pre><hr><h2 id="step-4-configure-ups-daemon">Step 4: Configure UPS Daemon</h2><p>Edit <code>/etc/nut/upsd.conf</code>:</p><pre><code class="language-bash">LISTEN 0.0.0.0 3493</code></pre><p>This tells NUT to listen for connections on localhost.</p><p>Then edit <code>/etc/nut/upsd.users</code>:</p><pre><code class="language-bash">[upsmon]
    password = strongpassword
    upsmon primary
    instcmds = ALL</code></pre><hr><h2 id="step-5-configure-nut-client">Step 5: Configure NUT Client</h2><p>Edit <code>/etc/nut/upsmon.conf</code>:</p><pre><code class="language-bash">MONITOR apcupsa@localhost 1 upsmon strongpassword primary
MONITOR apcupsb@localhost 1 upsmon strongpassword primary</code></pre><p>This means:</p><ul><li>Monitor the UPS named <code>apc</code> at <code>localhost</code>.</li><li>Use the <code>admin</code> user with the password.</li><li><code>master</code> indicates this system will manage shutdowns.</li></ul><hr><h2 id="step-6-set-nut-mode">Step 6: Set NUT Mode</h2><p>Edit <code>/etc/nut/nut.conf</code>:</p><pre><code class="language-bash">MODE=netserver</code></pre><p>(Use <code>netserver</code> or <code>netclient</code> if you want multiple systems connected to the UPS.)</p><hr><h2 id="step-7-start-and-enable-services">Step 7: Start and Enable Services</h2><pre><code class="language-bash">sudo systemctl enable nut-server
sudo systemctl enable nut-monitor
sudo systemctl start nut-server
sudo systemctl start nut-monitor</code></pre><hr><h2 id="step-8-verify">Step 8: Verify</h2><p>Check UPS status:</p><pre><code class="language-bash">upsc apc@localhost</code></pre><p>You should see output like:</p><pre><code class="language-bash">battery.charge: 100
battery.charge.low: 10
battery.charge.warning: 50
battery.date: 2001/09/25
battery.mfr.date: 2020/07/10
battery.runtime: 4088
battery.runtime.low: 120
battery.type: PbAc
battery.voltage: 27.3
battery.voltage.nominal: 24.0
device.mfr: American Power Conversion
device.model: Back-UPS XS 1400U
device.serial: myserial1
device.type: ups
driver.name: usbhid-ups
driver.parameter.pollfreq: 30
driver.parameter.pollinterval: 2
driver.parameter.port: auto
driver.parameter.productid: 0002
driver.parameter.serial: myserial1
driver.parameter.synchronous: auto
driver.parameter.vendorid: 051d
driver.version: 2.8.0
driver.version.data: APC HID 0.98
driver.version.internal: 0.47
driver.version.usb: libusb-1.0.26 (API: 0x1000109)
input.sensitivity: medium
input.transfer.high: 280
input.transfer.low: 155
input.transfer.reason: input voltage out of range
input.voltage: 240.0
input.voltage.nominal: 230
ups.beeper.status: enabled
ups.delay.shutdown: 20
ups.firmware: 926.T2 .I
ups.firmware.aux: T2
ups.load: 9
ups.mfr: American Power Conversion
ups.mfr.date: 2020/07/10
ups.model: Back-UPS XS 1400U
ups.productid: 0002
ups.realpower.nominal: 700
ups.serial: myserial1
ups.status: OL
ups.test.result: No test initiated
ups.timer.reboot: 0
ups.timer.shutdown: -1
ups.vendorid: 051d</code></pre><ul><li><code>OL</code> means “On Line” (power is good).</li><li>You’ll see <code>OB</code> (On Battery) if you unplug the UPS.</li></ul><hr><h2 id="step-9-optional-remote-monitoring">Step 9 (Optional): Remote Monitoring</h2><p>If you want multiple servers to shut down gracefully:</p><ol><li>Set <code>MODE=netserver</code> on the UPS host.</li><li>Configure <code>upsd.conf</code> to listen on the LAN IP.</li><li>On client machines, set <code>MODE=netclient</code> and point <code>upsmon.conf</code> at the UPS host.</li></ol><hr><h2 id="conclusion">Conclusion</h2><p>With NUT configured, your Linux system can <strong>monitor your APC UPS, log events, and safely shut down when power runs out</strong>. This setup ensures your data and systems stay protected during outages — and you get peace of mind knowing your UPS isn’t just sitting there, but actively integrated into your infrastructure.</p></hr></hr></hr></hr></hr></hr></hr></hr></hr></hr></hr></hr>]]></content:encoded></item><item><title><![CDATA[Ghost + Gatsby: A Modern Publishing Stack for Fast, Flexible Websites]]></title><description><![CDATA[If you want a publishing platform that’s both powerful and lightning fast, combining Ghost with Gatsby is a great way to go. Ghost handles content management and publishing, while Gatsby builds a highly optimized static site from that content. Together, they deliver the best of both worlds: an easy editor for authors and a blazing-fast frontend for readers.


What is Ghost?

Ghost is a modern, open-source CMS (Content Management System) built specifically for professional publishing. Unlike gene]]></description><link>https://brightbot.co.uk/ghost-gatsby-a-modern-publishing-stack-for-fast-flexible-websites/</link><guid isPermaLink="false">Ghost__Post__68da862bcb5315e3604fcde7</guid><category><![CDATA[Home Lab]]></category><category><![CDATA[Infrastructure]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Mon, 29 Sep 2025 13:29:30 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1583680599407-f73ab374fff4?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDh8fGdob3N0fGVufDB8fHx8MTc1OTE1MjU5OHww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1583680599407-f73ab374fff4?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDh8fGdob3N0fGVufDB8fHx8MTc1OTE1MjU5OHww&ixlib=rb-4.1.0&q=80&w=2000" alt="Ghost + Gatsby: A Modern Publishing Stack for Fast, Flexible Websites"/><p>If you want a publishing platform that’s both <strong>powerful</strong> and <strong>lightning fast</strong>, combining <strong>Ghost</strong> with <strong>Gatsby</strong> is a great way to go. Ghost handles content management and publishing, while Gatsby builds a highly optimized static site from that content. Together, they deliver the best of both worlds: an easy editor for authors and a blazing-fast frontend for readers.</p><hr><h2 id="what-is-ghost">What is Ghost?</h2><p><strong>Ghost</strong> is a modern, open-source CMS (Content Management System) built specifically for professional publishing. Unlike general-purpose CMS platforms, Ghost focuses on content creation, monetization, and simplicity.</p><p>Key features include:</p><ul><li><strong>Beautiful, distraction-free editor</strong> (Markdown-based with rich embeds)</li><li><strong>Membership and subscription support</strong></li><li><strong>Built-in SEO and AMP support</strong></li><li><strong>Powerful APIs</strong> for integration (REST and GraphQL)</li><li><strong>Headless CMS mode</strong></li></ul><p>Ghost can be used as a full CMS with its own frontend theme system, or as a <strong>headless CMS</strong> that provides content to another frontend like Gatsby.</p><hr><h2 id="what-is-gatsby">What is Gatsby?</h2><p><strong>Gatsby</strong> is a React-based static site generator. It takes your content (from sources like Ghost, WordPress, Markdown, or APIs) and compiles it into a static site. The result: <strong>super-fast load times, improved SEO, and high scalability</strong>.</p><p>Highlights include:</p><ul><li><strong>Static site generation</strong> with server-side rendering (SSR) and incremental builds</li><li><strong>Rich plugin ecosystem</strong> for data sources and features</li><li><strong>Performance optimization</strong> (image optimization, prefetching, code splitting)</li><li><strong>React-based frontend</strong> for dynamic interactivity</li><li><strong>Deployed anywhere</strong> (Netlify, Vercel, AWS, etc.)</li></ul><hr><h2 id="why-use-ghost-and-gatsby-together">Why Use Ghost and Gatsby Together?</h2><ul><li><strong>Ghost as the content hub</strong> – Editors and authors manage posts in Ghost’s admin panel.</li><li><strong>Gatsby as the frontend</strong> – Pulls content from Ghost’s API and builds a fast, secure, static site.</li><li><strong>Separation of concerns</strong> – Writers focus on content, developers focus on presentation.</li><li><strong>Performance and scalability</strong> – Gatsby sites are static, so they’re extremely fast and easy to host on CDNs.</li><li><strong>Security</strong> – With a static frontend, there’s no exposed CMS backend to attack.</li></ul><hr><h2 id="typical-architecture">Typical Architecture</h2><p>Here’s what a Ghost + Gatsby setup looks like:</p><pre><code class="language-text">   Authors &amp; Editors
          |
          v
   +---------------+
   |     Ghost     |  &lt;-- CMS (Content API)
   | (Headless)    |
   +---------------+
          |
          v
   +---------------+
   |    Gatsby     |  &lt;-- Static site generator (React)
   |   (Builds)    |
   +---------------+
          |
          v
   +---------------+
   |   Deployed    |  &lt;-- CDN / Hosting (Netlify, Vercel, etc.)
   |   Website     |
   +---------------+
          |
          v
       Readers</code></pre><ul><li>Ghost stores and manages your content.</li><li>Gatsby fetches content via the Ghost Content API (or GraphQL).</li><li>Gatsby builds static files (HTML, CSS, JS).</li><li>The site is deployed to a CDN for speed and global availability.</li></ul><hr><h2 id="example-setup">Example Setup</h2><h3 id="install-gatsby-ghost-source-plugin">Install Gatsby Ghost Source Plugin</h3><p>In <code>gatsby-config.js</code>:</p><pre><code class="language-js">module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-ghost`,
      options: {
        apiUrl: `https://your-ghost-site.com`,
        contentApiKey: `YOUR_CONTENT_API_KEY`,
      },
    },
  ],
};</code></pre><h3 id="query-ghost-content-with-graphql">Query Ghost Content with GraphQL</h3><p>Example query in Gatsby:</p><pre><code class="language-graphql">{
  allGhostPost {
    edges {
      node {
        title
        slug
        published_at(formatString: "MMMM DD, YYYY")
        html
      }
    }
  }
}</code></pre><p>This lets you pull posts from Ghost and render them in Gatsby pages.</p><hr><h2 id="benefits-of-this-setup">Benefits of This Setup</h2><ul><li><strong>Best authoring experience</strong> – Ghost provides a clean, intuitive editor.</li><li><strong>Blazing-fast sites</strong> – Gatsby generates static pages optimized for performance.</li><li><strong>Secure &amp; scalable</strong> – The frontend is static, hosted on a CDN.</li><li><strong>Developer-friendly</strong> – Modern React ecosystem for custom UIs.</li><li><strong>Future-proof</strong> – Decoupled CMS architecture for flexibility.</li></ul><hr><h2 id="conclusion">Conclusion</h2><p>Ghost + Gatsby is a modern publishing stack that balances <strong>content creation ease</strong> with <strong>frontend performance and scalability</strong>. Ghost takes care of authors, while Gatsby ensures readers get a super-fast experience.</p><p>If you’re building a blog, magazine, or content-driven business website, this combo is a powerful alternative to traditional CMS platforms.</p><p>In the next part of this series I will talk over fully expanding on Gatsby to generate a full static website, which funnily enough exactly how this site is created.</p></hr></hr></hr></hr></hr></hr></hr>]]></content:encoded></item><item><title><![CDATA[High Availability with HAProxy and Keepalived: A Practical Guide]]></title><description><![CDATA[When it comes to building resilient and scalable infrastructure, two tools often come up together: HAProxy and Keepalived. While HAProxy excels at load balancing and proxying, Keepalived ensures service continuity by managing failover and redundancy. Together, they form a rock-solid foundation for highly available systems.


What is HAProxy?

HAProxy (High Availability Proxy) is an open-source load balancer and reverse proxy widely used in production environments. It sits between clients and bac]]></description><link>https://brightbot.co.uk/high-availability-with-haproxy-and-keepalived/</link><guid isPermaLink="false">Ghost__Post__68da4e58cb5315e3604fcdc3</guid><category><![CDATA[Home Lab]]></category><category><![CDATA[Infrastructure]]></category><dc:creator><![CDATA[Andrew Townsend]]></dc:creator><pubDate>Mon, 29 Sep 2025 09:27:31 GMT</pubDate><media:content url="https://images.unsplash.com/photo-1587620962725-abab7fe55159?crop=entropy&amp;cs=tinysrgb&amp;fit=max&amp;fm=jpg&amp;ixid=M3wxMTc3M3wwfDF8c2VhcmNofDd8fHByb2dyYW1taW5nfGVufDB8fHx8MTc1OTEzMzM1OXww&amp;ixlib=rb-4.1.0&amp;q=80&amp;w=2000" medium="image"/><content:encoded><![CDATA[<img src="https://images.unsplash.com/photo-1587620962725-abab7fe55159?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wxMTc3M3wwfDF8c2VhcmNofDd8fHByb2dyYW1taW5nfGVufDB8fHx8MTc1OTEzMzM1OXww&ixlib=rb-4.1.0&q=80&w=2000" alt="High Availability with HAProxy and Keepalived: A Practical Guide"/><p>When it comes to building resilient and scalable infrastructure, two tools often come up together: <strong>HAProxy</strong> and <strong>Keepalived</strong>. While HAProxy excels at load balancing and proxying, Keepalived ensures service continuity by managing failover and redundancy. Together, they form a rock-solid foundation for highly available systems.</p><hr><h2 id="what-is-haproxy">What is HAProxy?</h2><p><strong>HAProxy (High Availability Proxy)</strong> is an open-source load balancer and reverse proxy widely used in production environments. It sits between clients and backend servers, distributing traffic efficiently and providing features such as:</p><ul><li><strong>Layer 4 and Layer 7 load balancing</strong> (TCP/HTTP/HTTPS)</li><li><strong>SSL termination</strong></li><li><strong>Health checks</strong> for backend servers</li><li><strong>Sticky sessions</strong></li><li><strong>Advanced routing and ACLs</strong></li><li><strong>Logging and metrics integration</strong></li></ul><p>Because of its performance and flexibility, HAProxy is used by some of the largest web platforms in the world.</p><hr><h2 id="what-is-keepalived">What is Keepalived?</h2><p><strong>Keepalived</strong> is an open-source tool that provides <strong>high availability</strong> and <strong>failover capabilities</strong> for Linux systems. It primarily uses <strong>VRRP (Virtual Router Redundancy Protocol)</strong> to create a floating IP address shared between servers. If the primary node goes down, Keepalived automatically promotes a standby node to take over the virtual IP.</p><p>Key features include:</p><ul><li><strong>VRRP-based failover</strong></li><li><strong>Health checks for services and nodes</strong></li><li><strong>Automatic failover with minimal downtime</strong></li><li><strong>Lightweight and easy to configure</strong></li></ul><hr><h2 id="why-use-haproxy-and-keepalived-together">Why Use HAProxy and Keepalived Together?</h2><p>Using HAProxy alone gives you load balancing across your backend servers. But what happens if the HAProxy server itself fails? That’s where Keepalived comes in.</p><p>With <strong>HAProxy + Keepalived</strong>, you get:</p><ol><li><strong>Load balancing and traffic management</strong> (via HAProxy).</li><li><strong>High availability of the load balancer itself</strong> (via Keepalived).</li><li><strong>A floating virtual IP</strong> that clients connect to, which always points to the active HAProxy node.</li><li><strong>Failover with minimal service disruption</strong> when a node fails.</li></ol><p>This setup prevents a single point of failure in your load balancing layer.</p><hr><h2 id="typical-architecture">Typical Architecture</h2><p>Here’s a simplified setup:</p><pre><code class="language-text">      +---------------------+
Client ---&gt; VIP:80/443 (Managed by Keepalived)
                 |
     -----------------------------
     |                           |
+------------+             +------------+
| HAProxy #1 |             | HAProxy #2 |
| (MASTER)   |             | (BACKUP)   |
| 10.1.0.10  |             | 10.2.0.10  |
+------------+             +------------+
     |                           |
     |       Load Balancing      |
     -----------------------------
     |       |       |       |
+---------+ +---------+ +---------+
| Backend | | Backend | | Backend |
| Server1 | | Server2 | | Server3 |
+---------+ +---------+ +---------+</code></pre><p/><ul><li>Clients connect to a <strong>virtual IP (VIP)</strong> managed by Keepalived.</li><li>HAProxy instances listen on this VIP and distribute traffic to backend servers.</li><li>If the master HAProxy node fails, Keepalived promotes the backup node and reassigns the VIP instantly.</li></ul><hr><h2 id="practical-guide">Practical guide</h2><p>This guide is written from the perspective of using a Debian 12 based OS running <code>haproxy/bookworm-backports-2.8,now 2.8.15-1~bpo12+1 amd64</code> and <code>keepalived/oldstable,now 1:2.2.7-1+b2 amd64</code> but should still be applicable for any other distribution using similar tooling.</p><h2 id="setting-up-keepalived">Setting up Keepalived</h2><h3 id="install">Install</h3><p>Ensure that Keepalived is installed on both the primary and backup servers. You can install it using your system's package manager:</p><p>For Debian/Ubuntu:</p><pre><code class="language-bash">sudo apt install keepalived -y</code></pre><h3 id="primary-server">Primary server</h3><p>Once installed edit the Keepalived configuration file on the primary server. The default configuration file is usually located at&nbsp;<code>/etc/keepalived/keepalived.conf</code>. Use your preferred text editor to open the file:</p><figure class="kg-card kg-code-card"><pre><code class="language-yaml"># /etc/keepalived/keepalived.conf
global_defs {
    enable_script_security
}

vrrp_script check-script {
   script "/usr/bin/pgrep haproxy"
   interval 2
   user root
}

vrrp_instance haproxy-vip-lc0-haproxy-01 {
    state MASTER
    priority 101
    interface ens18
    virtual_router_id 10

    advert_int 1

    unicast_src_ip 10.1.0.10 dev ens18
    unicast_peer {
        10.2.0.10
    }

    authentication {
        auth_type PASS
        auth_pass vagrant
    }

    virtual_ipaddress {
        10.0.0.100 dev ens18
    }
    track_script {
       check-script
    }
}</code></pre><figcaption><p><span style="white-space: pre-wrap;">Primary server: /etc/keepalived/keepalived.conf</span></p></figcaption></figure><p>Note for the primary server, the state should be <code>MASTER</code> and priority higher than the secondary server.</p><h3 id="secondary-servers">Secondary Server(s)</h3><figure class="kg-card kg-code-card"><pre><code class="language-yaml"># /etc/keepalived/keepalived.conf
global_defs {
    enable_script_security
}

vrrp_script check-script {
   script "/usr/bin/pgrep haproxy"
   interval 2
   user root
}

vrrp_instance haproxy-vip-lc0-haproxy-02 {
    state BACKUP
    priority 100
    interface ens18
    virtual_router_id 10

    advert_int 1

    unicast_src_ip 10.2.0.10 dev ens18
    unicast_peer {
        10.1.0.10
    }

    authentication {
        auth_type PASS
        auth_pass vagrant
    }

    virtual_ipaddress {
        10.0.0.100 dev ens18
    }
    track_script {
       check-script
    }
}</code></pre><figcaption><p><span style="white-space: pre-wrap;">Secondary server: /etc/keepalived/keepalived.conf</span></p></figcaption></figure><p>Note for the secondary server, the state should be <code>BACKUP</code> and priority lower than the primary server.</p><hr><h2 id="setting-up-haproxy">Setting up HAProxy</h2><p>Installing HAProxy requires a bit of apt repository configuration to get the desired HAProxy 2.8 the Debian site gives a handy helper page which gives instructions for selecting your target OS and version for specific HA Proxy versions, this can be found here: <a href="https://haproxy.debian.net/#distribution=Debian&amp;release=bookworm&amp;version=2.8">https://haproxy.debian.net/#distribution=Debian&amp;release=bookworm&amp;version=2.8</a></p><p>Once the steps are followed HAProxy 2.8 can be installed as follows</p><pre><code class="language-bash"># apt-get update
# apt-get install haproxy=2.8.\*</code></pre><p>Once installed you can go ahead and edit the HAProxy config file <code>/etc/haproxy/haproxy.cfg</code></p><figure class="kg-card kg-code-card"><pre><code class="language-yaml">global
	log /dev/log	local0
	log /dev/log	local1 notice
	chroot /var/lib/haproxy
	stats socket /run/haproxy/admin.sock mode 660 level admin
	stats timeout 30s
	user haproxy
	group haproxy
	daemon

	lua-load /etc/haproxy/cors.lua

	# Default SSL material locations
	ca-base /etc/ssl/certs
	crt-base /etc/ssl/private

	# See: https://ssl-config.mozilla.org/#server=haproxy&amp;server-version=2.0.3&amp;config=intermediate
        ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384
        ssl-default-bind-ciphersuites TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256
        ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets

defaults
	log	global
	mode	http
	option	httplog
	option	dontlognull
        timeout connect 5000
        timeout client  50000
        timeout server  50000
	errorfile 400 /etc/haproxy/errors/400.http
	errorfile 403 /etc/haproxy/errors/403.http
	errorfile 408 /etc/haproxy/errors/408.http
	errorfile 500 /etc/haproxy/errors/500.http
	errorfile 502 /etc/haproxy/errors/502.http
	errorfile 503 /etc/haproxy/errors/503.http
	errorfile 504 /etc/haproxy/errors/504.http

listen stats
        bind    10.1.0.10:9000
        mode    http
        
        stats   enable
        stats   hide-version
        stats   uri       /
        stats   refresh   30s

frontend web
    bind :80

    acl frontend-ghost hdr_sub(host) -i ghost.atathome.me

    use_backend backend-ghost if frontend-ghost

backend backend-ghost
    server lc0-ghost 10.0.0.1:80 check
    timeout server 30s
</code></pre><figcaption><p><span style="white-space: pre-wrap;">/etc/haproxy/haproxy.cfg</span></p></figcaption></figure><p>This is pretty much the out of the box config with an addition of a sample backend, this should be changed on both the primary and secondary server. Note the <code>listen stats</code> bind address should not be the VIP and be the management IP.</p><hr><h3 id="test-and-verify">Test and Verify</h3><p>After configuring Keepalived on both servers, test the configuration for syntax errors:</p><pre><code class="language-bash">sudo keepalived -t</code></pre><p>If there are no errors, start Keepalived on both servers:</p><pre><code class="language-bash">sudo systemctl start keepalived</code></pre><p>You can verify the high availability setup by checking the VIP address. On the primary server, the VIP should be active. On the backup server, it should be in a backup state. You can use the following command to check the status:</p><figure class="kg-card kg-code-card"><pre><code class="language-bash">~# ip a
1: lo: &lt;LOOPBACK,UP,LOWER_UP&gt; mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: ens18: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether bc:24:11:e1:08:40 brd ff:ff:ff:ff:ff:ff
    altname enp0s18
    inet 10.1.0.10/22 brd 10.1.0.255 scope global ens18
       valid_lft forever preferred_lft forever
    inet 10.0.0.100/32 scope global ens18
       valid_lft forever preferred_lft forever</code></pre><figcaption><p dir="ltr"><code spellcheck="false" style="white-space: pre-wrap;"><span>ip a</span></code><span style="white-space: pre-wrap;"> output logs</span></p></figcaption></figure><p>You should see the VIP address (<code>10.0.0.100</code>&nbsp;in this example) on the active server and not on the standby server.</p><p>Keepalived will automatically manage the failover process. If the primary server goes down or HAProxy becomes unresponsive, the VIP will migrate to the backup server.</p><p>If the primary server has not attached the VIP you can debug errors using journal</p><figure class="kg-card kg-code-card"><pre><code class="language-bash"># journalctl -xefu keepalived
Sep 29 10:35:37 lc0-haproxy-01 Keepalived_vrrp[55583]: Script `check-script` now returning 0
Sep 29 10:35:37 lc0-haproxy-01 Keepalived_vrrp[55583]: VRRP_Script(check-script) succeeded
Sep 29 10:35:37 lc0-haproxy-01 Keepalived_vrrp[55583]: (haproxy-vip-lc0-haproxy-01) Entering BACKUP STATE
Sep 29 10:35:37 lc0-haproxy-01 Keepalived_vrrp[55583]: (haproxy-vip-lc0-haproxy-01) received lower priority (100) advert from 10.2.0.10 - discarding
Sep 29 10:35:38 lc0-haproxy-01 Keepalived_vrrp[55583]: (haproxy-vip-lc0-haproxy-01) received lower priority (100) advert from 10.2.0.10 - discarding
Sep 29 10:35:39 lc0-haproxy-01 Keepalived_vrrp[55583]: (haproxy-vip-lc0-haproxy-01) received lower priority (100) advert from 10.2.0.10 - discarding
Sep 29 10:35:40 lc0-haproxy-01 Keepalived_vrrp[55583]: (haproxy-vip-lc0-haproxy-01) Entering MASTER STATE</code></pre><figcaption><p dir="ltr"><span style="white-space: pre-wrap;">Journal logs for keepalived</span></p></figcaption></figure><p>When successful you should see the message <code>Entering MASTER STATE</code></p><p/><hr><h2 id="benefits-of-this-setup">Benefits of This Setup</h2><ul><li><strong>Fault tolerance</strong> – no single point of failure at the load balancer layer.</li><li><strong>Scalability</strong> – distribute traffic across multiple backend servers.</li><li><strong>Minimal downtime</strong> – failover happens automatically and quickly.</li><li><strong>Flexibility</strong> – works with web apps, APIs, databases, and more.</li></ul><hr><h2 id="conclusion">Conclusion</h2><p>By combining <strong>HAProxy</strong> and <strong>Keepalived</strong>, you can build a highly available, fault-tolerant, and scalable load balancing infrastructure. HAProxy ensures smart traffic distribution, while Keepalived keeps the load balancer itself redundant and resilient.</p><p>Whether you’re running a high-traffic website, an API service, or a critical enterprise application, this duo is a tried-and-true solution for uptime and reliability.</p></hr></hr></hr></hr></hr></hr></hr></hr></hr>]]></content:encoded></item></channel></rss>