Under the bonnet

How it works

For LSE IT, a department's information-governance contact, or anyone deciding whether to trust it: how the system is put together, how departments are kept apart, what happens to a document and a notification, how it is secured, what it does with personal data, and how it was built and tested. The design documents in docs/ have the full detail.

Architecture

One repository, TypeScript throughout, four applications and a set of shared packages. The overview diagram shows how they run: the API and the worker share Postgres; Caddy serves the two front ends; email and push go out through providers behind interfaces with test fakes.

PartBuilt withRole
APIFastify 5, Zod, Drizzle ORM, Node 22138 routes declared once in a shared manifest with request and response schemas, OpenAPI generated from it; plus the two signed Mailgun webhooks
Workerpg-boss, poppler, sharpDocument processing, notification fan-out and delivery, digests, reminders, email-in, exports, metrics, the ops digest
DatabasePostgres 16Data, row-level security, full-text search, the job queue and the live-event bus
Admin portalReact 19, Vite, TanStack Router and Query, Tailwind, RadixA static single-page app
Phone appExpo (React Native), expo-router, TanStack Query, MMKV, SecureStoreiOS, Android and the web from one codebase; white-label builds from configuration
Shared packagesshared, db, storage, email, push, jobs, ui-tokensThe route manifest and schemas, the audience rule, the Markdown sanitiser with its maths and media extensions, text reflow for the reader, the typed API client, the database schema and migrations, encrypted storage, providers, colour and type tokens
Command linetooling/cliPlatform administration (for the platform owner)

There is deliberately no Redis, no search engine and no message broker. Postgres does all three jobs at department scale (tens of departments, tens of thousands of users), which keeps the launch configuration inside 1.2 GB of memory on a shared 2 GB server.

Departments and the audience rule

An institution (LSE) owns email domains; a tenant is a department within it; a user is one person, keyed by email address, with one membership per department carrying a role, a programme, a year of study and how it was verified (roster, admin or self-declared). Every row a department owns carries its tenant_id.

Departments are kept apart twice. The API resolves the department from the URL (/v1/t/philosophy/…), checks the caller's membership, and opens a transaction that sets the department and user as Postgres session variables. Row-level security policies on every department table compare against them, so a query that forgot its WHERE tenant_id would still see nothing of another department. At integration a cross-tenant audit called each of the 108 department routes as members and owners of the other department, and with the other department's ids in every parameter; it found one route that echoed a foreign id (no data was exposed or changed), which was fixed. The audit runs in every test run.

The audience rule

Publications, posts and events all carry an audience, and one rule decides who it reaches:

{ all: true }                                  everyone in the department
{ space: "<group id>" }                       active members of one group
{ programmes?: [...], years?: [...],           AND across the keys present,
  levels?: ["ug" | "pgt" | "pgr"],             OR within a key
  roles?: ["student" | "staff"] }

So { programmes: [BSc PPE, BSc PLSM], years: [2] } reaches second-years on either programme. The rule is implemented once in SQL (audience_matches, used by the feed, the library, events, search and the notification fan-out) and once in TypeScript for the apps, and both are tested against the same fixture of cases. Programme and year channels are views of the same posts filtered by audience, which is why a post to two programmes appears in both channels and a student on a third programme sees it in neither. Admins see everything in the portal, for moderation; in the app they see what is addressed to them.

The publishing pipeline

  1. Upload. The file (50 MB at most) is checked by its content, not its name, against an allow-list of types; images are re-encoded, which strips their metadata; an identical file uploaded twice in a department is stored once. Bytes are written only through the encrypted storage layer.
  2. Process (a worker job). pdftotext extracts the text page by page for search; pdfinfo reads the document title; the first page is rendered as a preview image; Word files become sanitised HTML so they read as formatted text. With LibreOffice switched on (not on the 2 GB server), Office files are converted to PDF in an isolated process with a time limit.
  3. Publish, now or at a scheduled time (a job runs every minute). The search index is weighted: title first, then summary, body and the document's text.
  4. Notify: one fan-out job for the audience (see below), and a live event so open apps add the item at once.
  5. Serve. Files are fetched through short-lived signed links bound to the user (an HMAC over the file, user and expiry), with ranges and ETags so the app can cache them; an invalid or expired link answers "not found".
  6. Replace a file and the previous metadata and files are kept as a version; the item shows "Updated". Expire moves an item to the archive, where it stays searchable.

Email-in: the email provider (Mailgun on the live server, which receives the departments' addresses at pigeonhole.jmckalex.org) posts each inbound message to a signed webhook. The address identifies the department; the sender must pass SPF or DKIM aligned with the From address and be staff of the department or on its allow-list, otherwise the message is recorded as rejected and nobody is told (so forged mail gets no reply). The raw message is stored encrypted; the HTML body becomes sanitised Markdown; the department's rules choose category and audience and whether to publish; otherwise admins get a draft with a signed one-click Publish link valid for seven days. Slots are iCalendar recurrence rules; a daily job emails a slot's owner two days before an occurrence that has nothing scheduled.

Notifications

A module that has something to say (a publication, a reply, a reminder) calls one function with an audience or a list of users and a category. The worker resolves the audience to people, writes one inbox row each, then, per person, consults their preferences and quiet hours and decides: push now, push later (held until quiet hours end), email, digest only, or nothing. Pushes go to Expo's service in batches of 100, which forwards them to Apple and Google; a later job reads the receipts and drops dead device tokens. The weekly digest is built on Monday mornings from unread notifications and new publications. Reminders are scheduled jobs created when someone RSVPs, and re-check the event before firing. Every notification carries a link to its item, which the app opens.

CategoryPush by defaultIn the digest
New publicationFor categories the department marks "notify"Yes
Pinned noticeYesYes
Reply or mentionYesNo
New post in a group I joinedYesYes
New post to my programme or yearNoYes
Event reminderYes–
New event in my audienceNoYes
Answer to my questionYes–

Quiet hours default to 22:00–08:00 in the department's time zone; departments set the defaults and each person can change their own.

Live updates

While the app or portal is open it holds one server-sent-events connection per department (GET /v1/t/:tenant/stream). Modules raise domain events after their transaction commits (post.created, reaction.changed, publication.published, notification.created, event.changed, and report.created for admins) on a bus that uses Postgres NOTIFY, so an event raised in the worker reaches a phone connected to the API, and any number of API processes would see it. The stream applies the audience rule, blocks and group membership per connection before sending anything, so a student never receives an event about something they could not open. Payloads are the same summaries the list routes return, so clients patch their caches without another request. Votes on anonymous polls are deliberately not broadcast: counts ticking up in a small group would reveal who had just voted. Connections reconnect with Last-Event-ID and are sent what they missed; when the stream is unavailable the apps fall back to pull-to-refresh. A new or changed event on the stream also refreshes Home's "Coming up" list, and anything stale is fetched again when the app comes back to the foreground.

Maths, media players and the reader

Maths. One module of delimiter rules (packages/shared/src/math-syntax.ts) is used by every parser that looks for maths: event titles, the portal's and the server's Markdown (marked) and the app's (markdown-it). Inline maths is $…$ or \(…\), displayed maths $$…$$ or \[…\]; a $ followed by a space, or a closing $ followed by a digit, is not maths, so prices stay text; nothing matches across a blank line. Formulas are drawn as SVG by MathJax (mathjax-full 3.2.2) and passed through the same sanitiser as the rest of the text. The portal puts the SVG in the page; the app draws it with expo-image from a base64 data URI, needing no native module, so maths reached phones as an over-the-air update. React Native places an image inside a line of text by its default font's metrics, not the text's, so on iOS each formula is moved by an amount measured on the simulator, which puts digits in a formula and in the surrounding text on the same baseline to within a pixel. The app grew by 1.84 MB of Hermes bytecode (812 KB compressed).

Media players. packages/shared/src/media.ts decides whether a line is only a link to YouTube, Vimeo or an audio or video file, and both Markdown pipelines use it, so the portal and the app agree. The portal shows an iframe from www.youtube-nocookie.com or player.vimeo.com (the sanitiser allows frames from those two hosts and no others), or an HTML5 audio or video element, with the link underneath; the sites' content security policy allows those two frame sources and https: media. The app draws each player in a WebView, inside a small page whose address is the app's own web origin, because YouTube refuses to play its embed page loaded on its own. Emails, push notifications and text snippets show the labelled link instead.

The reader. The text extracted from a PDF comes out of pdftotext one line at a time. packages/shared/src/reflow.ts joins the lines of each paragraph, rejoins words hyphenated at a line end, and keeps the breaks at blank lines, list items (including Word's "o" sub-bullets) and headings; highlights from a search are computed on the reflowed text. It was tested on the department's own assessment documents. Full screen is a separate header-less screen pushed over the reader, because hiding a modal's header in place remounts it and loses its state.

Security and encryption

  • Sign-in: link tokens (32 random bytes) and 6-digit codes are stored hashed, last 15 minutes and work once; five wrong codes end a request, ten wrong codes in a day stop codes for that address, and at most ten sign-in emails an hour go to one address. Each university chooses whether its sign-in emails carry the link as well as the code; LSE's carry the code only. Access tokens last 15 minutes; refresh tokens rotate on every use and reusing an old one ends the whole session (token-theft detection). Signing out, "sign out everywhere" and an admin's revoke take effect on the next request, not after 15 minutes. The portal holds its refresh token in an httpOnly cookie.
  • Authorisation: every route declares its minimum role (public, user, member, staff, admin, owner, superadmin), enforced by one hook; role matrices test every route for every role, including pending, suspended and lapsed members.
  • Input: every request is validated against the shared schema; errors use one envelope and never contain stack traces or SQL. User Markdown goes through one sanitiser and raw HTML from users is never rendered. Rate limits on sign-in, uploads, posting and search.
  • Files: content-type checks, size limits, image re-encoding, isolated document conversion with a time limit, and optional virus scanning.
  • Encryption at rest, two layers: every stored file is AES-256-GCM encrypted under its department's own key, itself wrapped by a master key held only in the server's environment, so files are encrypted on disk, in backups and on object storage; and the database and uploads sit on a LUKS2-encrypted block volume whose passphrase never touches the server's disk (on the live server since 5 November; the stack stays down after a reboot until the volume is unlocked by hand). Backups are encrypted by restic. Anonymous question authors are sealed with a separate key.
  • Transport and headers: TLS everywhere, HSTS, a content security policy for both front ends, framing denied, CORS limited to the two front ends.
  • The server: SSH keys only, firewall, fail2ban, automatic security updates, containers as a non-root user with all capabilities dropped, the database on an internal network with no route out and no published port, and development sign-in refused in production by the API, the compose files and the deploy script.
  • Audit: every administrative, moderation and sensitive sign-in action is logged with actor, target and time, and kept for 24 months.

Encryption at rest protects data that is not in use. A running server must read its own database, so an attacker with root on the live host can read what the application reads. The defences against that are the hardening above, holding little data, and hashing every secret token.

The Phase 3 security review (agent P3, merged on 4 November) walked every area above and reported 33 findings: no High left open (one high-impact email-in spoofing issue was confirmed and fixed), 13 Medium all fixed with regression tests, 18 Low (10 fixed, 3 in part, 5 reported), 2 informational. Among the fixes: a double-submit CSRF token on the portal's cookie routes; the client address taken only from trusted proxies; caps on wrong codes and sign-in emails per address; audit entries for superadmin support access; admin-initiated export and deletion on a member's behalf; the 12-month anonymisation and retention jobs; limits on image and PDF decoding; refusing Office "zip bombs"; and logs without query strings. The report is docs/SECURITY-REVIEW.md. The reported items still open include running LibreOffice without network access (it is off on the live server), an image vulnerability scan in CI, and asking LSE IT whether its mail relay lets a user send as another address.

Privacy and moderation

Under UK GDPR each department (through the LSE) is the controller for its students' data and the platform is a processor; before launch the department records the processing, adapts the privacy notice (Settings → Privacy notice; shown in the app) and asks the LSE Data Protection Officer whether a Data Protection Impact Assessment is needed. The design keeps that conversation short:

  • no special-category data, no profiling, no tracking or analytics SDKs in the app, no advertising, no private messaging;
  • students see each other only by real name and programme; the student directory and push notifications are opt-in;
  • reading is recorded only to keep unread state and aggregate counts; staff never see who has read what, and the median time to first view is withheld below three readers;
  • anonymous questions cannot be attributed by admins; only the owner can reveal an author, and every reveal is audited;
  • export and deletion are self-service in Settings.
DataKept
Email, name, programme, yearWhile a member; anonymised 12 months after the last membership ends, or at once on request
Avatar, bio, interests, directory choiceDeleted with the account
Posts, reactions, votes, group membershipsWhile the department exists; shown as "Former member" after deletion
Publication readsUnread state and totals only; purged 24 months after the publication expires
Notifications and deliveries90 days
Sessions, devices, push tokensUntil sign-out or 90 days unused, then 7 more days
Data exports24 hours
Audit log24 months
Backups30 daily and 12 monthly, encrypted (on the droplet until a Spaces bucket exists)

Two nightly jobs apply this table: retention.sweep removes ended sessions and expired exports, and account.anonymise_inactive anonymises an account 12 months after its last membership ended and it was last used (no warning email is sent first). An admin can export or delete a member's account on their request through the API, the export going to the member's own address; the portal has no buttons for this yet. Raw inbound emails, roster imports and searches that found nothing have no retention period yet; the owner is to set them.

Moderation

Community guidelines are shown before a student's first post and linked from every report. Any post, user, group or event can be reported; reports go to every admin by email and in the portal, with a 24-hour expectation that the department documents. A post with three open reports from different people is hidden at once, pending review. Moderators can dismiss, hide, remove, warn (from templates), suspend for 1, 7 or 30 days, or ban from a group; each action is logged with actor, target, reason and time, and the reporter is told the outcome in general terms. Blocking is symmetric and private; muting is private. Edits are allowed for 24 hours and marked "edited"; an author's deletion removes a post for everyone but keeps it in the moderation log for 30 days. Suspended and lapsed members cannot post, react or start groups. Together with in-app account deletion, these meet the App Store's and Google Play's rules for apps with user-generated content.

Accessibility

The target is WCAG 2.2 AA in both themes. Every control is labelled; touch targets are at least 44 points; text follows Dynamic Type; reduced motion turns animation off; colours come from one set of tokens whose contrast is checked by tests. The portal scores 100 in Lighthouse's accessibility audit in both themes. The reader offers the extracted text as an accessible alternative where a department's PDF has none.

The Phase 3 accessibility pass (agent P2, merged on 4 November) ran axe-core over every portal screen and every app screen in both themes, against the mock and the real API, with no serious or critical findings left; Lighthouse scored 100 for accessibility on the sign-in page and 39 portal pages in both themes, and CI now fails a portal page below 95. It fixed 34 defects (7 in the portal, 27 in the app), among them buttons announcing state with the wrong attribute, accessible names that left out visible text, form-field outlines below 3:1 contrast, decorative glyphs read aloud, the in-app banner covering the header, and screen transitions that ignored Reduce Motion. On the iOS simulator at the largest accessibility text size it checked 13 screens and fixed 10 layout defects; display text is capped so that titles stay on screen. VoiceOver and TalkBack have not yet been tried by a person on a device, and should be before release.

How it was built

Pigeonhole was built by Claude Code agents working in parallel from a written design, each in its own git worktree and branch, owning a fixed set of paths, and finishing with a written hand-off. The design was arranged so that agents never needed to talk to each other while they worked:

  • Phase 0: one agent wrote the contract: the database schema and migrations with row-level security, the route manifest with every request and response schema, a mock server that answers every route with realistic data generated from the seed, the app and portal shells, and the seed itself. The contract was then frozen; later changes had to be additive and written up in docs/contract-changes/.
  • Phase 1: eight agents built against it at the same time. The front ends worked against the mock server, so they never waited for the back end.
  • Phase 2: one agent merged the eight branches in order, fixed what the agents had assumed differently, switched the front ends to the real API and ran everything end to end.
  • Phase 3: specialist agents, briefed by the integration agent from what it found. A second integration agent (Z2) merged them on 4 November in a planned order, and the system was deployed the same day. Later briefs added maths (P7, merged on 5 November) and a visual editor for the portal (P8, in progress).
AgentScopeResult
S0Scaffold and contract: schema, migrations, row-level security, 136-route manifest, mock server, app shells, seed (2 departments, 79 users, 26 publications, 120 posts, 5 groups, 15 events)Done
A1Sign-in, sessions, memberships, rosters, invitations, member administration (43 routes)Done
A2Uploads, document processing, publications, slots, email-in, search (29 routes)Done
A3Groups, posts, polls, moderation, the live stream and event bus (30 routes)Done
A4Events, notifications, people, questions and FAQs, analytics (30 routes)Done
A5The admin portal, every section, the setup wizard; 14 end-to-end flowsDone
A6App shell, sign-in, library, reader, search, inbox, people, Ask, settingsDone
A7App community and events; 17 end-to-end flowsDone
A8Docker images, shared-host deployment, backups and restore drill, CLI, CIDone
Z1Integration: merges, cross-cutting fixes, end-to-end against the real API, the cross-tenant auditDone
P1White-label builds, release configuration, icons, store listing and privacy answersDone merged 4 Nov
P2Accessibility and QA passDone merged 4 Nov
P3Security reviewDone merged 4 Nov
P4Performance and load test at 1,000 members, 500 publications, 10,000 postsNot run
P5Setup-wizard polish and department guidesNot run
P6Mailgun as an email provider (the one used on the live server)Done merged 4 Nov
Z2Phase 3 integration: P6, P3, P1 and P2 merged in that order, then D1; fixes at integration; the production images checked on a local copy of the shared-host stackDone
P7TeX maths in event titles and Markdown bodies, drawn as MathJax SVG in the portal and the appDone merged 5 Nov
P8A visual (Tiptap) editor for Markdown bodies in the portalIn progress on agent/P8
D1These pages and their screenshotsDone
D2These pages brought up to date after the deploymentDone

Tests

On the code of main, a fresh run of pnpm test on 5 November 2026 passed 1,846 tests, with one skipped: the LibreOffice conversion test, which runs in CI where LibreOffice is installed. API tests run against a real Postgres, not mocks. (At the end of Phase 2 the count was 1,491; at the end of the Phase 3 merges, 1,748.)

PackageTests on main
api842 + 1 skipped
shared (contract, audience rule, maths, media, reflow, client, mock server)582
mobile138
ui-tokens88
admin74
worker33
push22
email20
cli18
db15
storage12
jobs2
Total1,846

End to end, against the real API, worker and Postgres: the integration agent's five flows pass (publish a PDF and see it arrive live on a phone, then search inside it; a group meeting with reminders fired by the worker; a report hidden at the threshold and moderated; a roster re-import lapsing a student; a joint-degree student posting to two departments' programmes), as do the portal's 37 flows (including the accessibility tour), the app's 38 on its web build (all passing after the reader change on 5 November) and the community app's 17. Maestro drove the iOS simulator on 5 November to check the inline maths and the reader; the written Maestro flows have not yet been run as a suite.

Continuous integration. Since 5 November the code is in a private GitHub repository, and every push runs lint, typecheck and the tests on a clean Postgres (with the worker's real tools, LibreOffice included), the infrastructure checks, the portal's smoke flows and the app's web build under Playwright with axe, and a Lighthouse accessibility audit of every portal section in both themes. The infrastructure drill (provision, deploy, back up, wipe, restore and compare) runs on the first of every month and on infrastructure changes. Both passed in full on GitHub on 5 November 2026, after four fixes for differences between a fresh runner and the owner's Mac.

These pages

Written and captured by agent D1 on 4 November 2026 from a private copy of the stack (its own Postgres, seeded; the API, worker and portal on private ports; the app in Expo Go on a clone of the iPhone 16 Pro simulator, driven by deep links; the portal and the web build in headless Chromium). Brought up to date by agent D2 on 5 November 2026, which took the changed screens again in the same way. The capture scripts are in docs/site-capture/.