Commit Graph
34 Commits
Author SHA1 Message Date
Lucas RayanandClaude Opus 5 eec4a4e520 #21: complete the account area and audit every admin mutation
Sessions and password changes were the two things PLAN.md section 14.2
asks of the account area that were still missing, and the admin console
had no audit trail at all despite section 14.3 requiring one for every
mutation.

Session revocation is enforced on every request, not just recorded. A JWT
carries its own validity, so revoking a row without checking it would have
made "sign out this device" a button that did nothing until the token
expired eight hours later. Changing a password revokes every other session
for the same reason: a password change that leaves the attacker's session
alive has not locked anyone out.

Admin queries are scoped by role in the SQL rather than in the UI, as
section 14.3 requires: a DOMAIN_ADMIN calling the API directly sees only
its own domain, and a mailbox outside that scope answers 404 rather than
403 so the scope cannot be used to enumerate what exists elsewhere.

The two mutations that exist so far - enabling or disabling a mailbox, and
retrying or cancelling a queued delivery - write actor, IP and target to
audit_log, and there is an endpoint to read it back.

Covered by tests against a real database: a revoked token stops working
mid-session, a password change needs the current password and takes the
other sessions down with it, and the minimum length is enforced.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 10:27:14 -03:00
Lucas RayanandClaude Opus 5 93d21b4752 #21: push new mail to the browser over WebSocket
F4 lists real-time updates and the interface had none: an open inbox only
changed when the user reloaded it.

Events come from the transactional outbox rather than from an in-process
callback, which is what the outbox is for (PLAN.md section 9.4): the row
is written in the same transaction as the message, so an event can never
describe a delivery that rolled back, and a crash between commit and
publish loses nothing because the row is still there on restart. The relay
claims rows with SKIP LOCKED so a second instance can help without
publishing anything twice.

The hub fans events out per mailbox, keyed by the mailbox the session
resolved to, so one account's arrivals are never visible to another even
though they share the process. A subscriber that stops reading is dropped
rather than allowed to stall the relay; it reconciles on reconnect.

The client reconnects with capped exponential backoff and treats every
successful connect as a resync, refetching the folder. Without that, a
socket that dropped for a minute would leave the list quietly stale, which
is worse than having no real-time updates at all.

The upgrade goes through a Next rewrite, not the API route handler: a
route handler sees a finished request and cannot upgrade a connection.
Verified against the running stack - the handshake returns 101 through the
Next server, and a message delivered on port 25 arrives as a frame on an
already-open socket without the page asking for it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 10:26:54 -03:00
Lucas RayanandClaude Opus 5 3e60852551 #21: put real mail on the webmail screens
The mail list rendered two hardcoded messages and the reader showed their
canned HTML; compose ran a countdown and then navigated away without ever
submitting anything. Both now use the API, including search, the unread
badges in the sidebar (which were the literals "3" and "1", so an empty
inbox still advertised unread mail), and marking a message read on open.

The undo window now means what it says: the message is held in the browser
and only submitted when the countdown elapses, so cancelling it means
nothing was ever queued rather than trying to recall it afterwards.

Message bodies render in an iframe with an empty sandbox - no scripts, no
same-origin - and remote references are stripped until the reader asks for
images, so a tracking pixel cannot fire on open. The previous sandbox
allowed popups.

The admin page titles and the language switcher labels now come from the
bundles. The labels live there rather than in the source because PLAN.md
R9 keeps non-ASCII out of code, and each language should be named the way
that language names it.

ADR-001 assigned the mail API to the TypeScript storage service; the
reasoning for putting it in Go instead is recorded in PLAN.md, which
.gitignore deliberately keeps out of the repository, so that revision
lives only in the working copy.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 10:04:05 -03:00
Lucas RayanandClaude Opus 5 48fe3c68f3 #21: serve the webmail mail API from the protocols service
The mail screens had no backend at all: they rendered a hardcoded array,
and the storage service that ADR-001 assigned this to is still a health
stub. The API lands here instead, because the folder, UID, MODSEQ, flag
and blob logic already exists and is tested in this service for IMAP.
Reimplementing it in TypeScript would mean two implementations of the
same semantics and two chances to disagree about what a UID means.

Reads use a projected read model rather than hydrated aggregates, which
is the CQRS exception PLAN.md section 2 carves out for webmail queries.
Every query is scoped to the mailbox resolved from the verified session,
never to an identifier taken from the request, so one account cannot read
another's mail by guessing a UID - covered by a test that tries exactly
that and expects 404.

Sending reuses ProcessOutboundEmailUseCase, so mail written in the browser
gets the same treatment as mail submitted over 587: send limits, DKIM
signing, and the durable queue. The From address comes from the session
and never from the request body; letting the body choose it is how a
webmail becomes a relay for spoofed mail.

MIME is parsed server-side because this service already depends on a MIME
library. A message that will not parse still returns its raw text - an
unreadable message beats an inbox that refuses to open one.

Marking a message read updates the flag and the folder counter in one
transaction, and only on a real transition, so re-opening a message cannot
drive unread_count negative.

Verified against the running stack: a message delivered over port 25
appears in the list with its decoded subject and sender, opens, marks
itself read, is found by search, and a message composed in the webmail
reaches outbound_jobs with the session's address as the envelope sender.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 10:03:25 -03:00
Lucas RayanandClaude Opus 5 d33068a43c #21: fill in message metadata and stop losing mail to a missing folder
Two problems the mail screens exposed, both in the delivery path.

The subject, snippet, sender name and message-id columns have existed
since the first migration, but nothing ever wrote them: every row went in
with those fields NULL. A message list built on the database would have
shown blank subjects for every message. Delivery now parses them once per
message and stores them, decoding RFC 2047 encoded words so an accented
subject is readable rather than raw. Parsing failures are non-fatal: a
message with unreadable headers is still delivered, just with less
metadata, because refusing it would lose mail over a malformed Subject.

Worse, a message the spam filter routed to Junk failed delivery outright
when the mailbox had no Junk folder - the sender got 451 and retried
forever against a mailbox that would never grow one on its own. Delivery
now falls back to INBOX and says so in the log. Found by sending a real
message through port 25 against the running stack.

The SMTP handler also swallowed the cause of any unexpected failure: the
peer saw "temporary error" and the operator got nothing. It is logged now,
which is how the missing folder was diagnosed at all.

Also adds the JWT verifier the mail API needs. The tokens are minted by
the auth service and verified here under the same secret, so the test
fixtures are real tokens produced by that service: if the two
implementations drift, this fails before the webmail does. Challenge
tokens, wrong secrets, tampered payloads, expired tokens and the other
surface's audience are all rejected.

The dev seed gained the standard folder set, which is what a provisioned
mailbox has and what the fallback above should not have to compensate for.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 10:03:03 -03:00
Lucas RayanandClaude Opus 5 132cecd41c #21: guard the web surfaces and connect them to the auth service
Three separate gaps, all of which made the F4 interface non-functional or
unprotected:

The admin console rendered for anyone. There was no middleware and no
guard in the layout, so /admin/dashboard returned 200 unauthenticated -
only its data calls failed. middleware.ts now redirects both surfaces to
their login when the session cookie is missing, expired, carries the wrong
audience, or is a pre-MFA challenge token. It reads the claims without
verifying the signature on purpose: the signing key belongs to the auth
service and must not reach the browser bundle. That is sound because this
is not the boundary - every /api/v1 request is verified for real upstream.

Nothing served /api/v1/*. next.config.ts had no rewrites and there were no
route handlers, so every call the pages made 404'd against the Next
server, while AUTH_SERVICE_URL sat unused. A catch-all route now proxies
to the auth service, forwarding the client address and preserving multiple
Set-Cookie headers, which logout needs to clear both surfaces. Session
cookies also move to Path=/, since a cookie pinned to /user or /admin was
never sent with the /api/v1 requests that needed it.

i18n existed only as files. The three bundles had perfect key parity and
real translations, but no library, no imports and no switcher: the UI was
hardcoded English and i18n.test.ts compared keys while the feature was
absent. There is now a provider, a hook, a language switcher, and
server-side Accept-Language negotiation that honours q-values and matches
a bare "pt" to pt-BR. Logins, both layouts and the settings screen consume
it; the admin pages still have English titles.

The settings screen invented app passwords in the browser with Math.random
and never stored them. It now calls the API, which returns the password
once and keeps only its hash.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 09:33:49 -03:00
Lucas RayanandClaude Opus 5 833dc76c2e #21: make the auth service actually authenticate
The F4 auth service issued a valid session for any email and any password,
and accepted any non-empty string as a second factor. Reproduced against
the router before touching it: an invented password plus the code "000000"
returned a SUPER_ADMIN token that opened /api/v1/admin/dashboard.

Passwords. Hashing moves from PBKDF2 to Argon2id via hash-wasm, which is
what PLAN.md section 9 and the Go service already use - the previous
scheme meant a password set through the mail stack could never verify
here. Interoperability was checked in both directions before adopting the
library: a hash written by alexedwards/argon2id verifies in Node and one
written here verifies in Go. hash-wasm is pure WASM, so the multi-arch
Alpine images need no native build.

verifyPassword no longer falls back to comparing the password against the
stored hash. That fallback turned every stored hash into a working
credential: anyone with a database dump could authenticate by sending the
hash back. Anything that is not an argon2id PHC string is now refused.

Logins are decided against the database, with the failure counter and the
temporary lockout of PLAN.md section 5.2. An unknown address and a wrong
password give the same answer, and the unknown case still pays for a hash
so response time does not enumerate valid addresses.

Second factor. The TOTP secret is generated server-side, stored encrypted
and never accepted back from the client - the confirm step used to take
whichever secret the caller sent, so anyone could confirm with their own.
Recovery codes are Argon2id, single-use, and consumed under a guard so two
concurrent requests cannot spend the same one. App passwords are issued
and revoked through real endpoints instead of browser state.

Sessions gain a "purpose" claim. Without it the challenge token - handed
out after the password but before the second factor - satisfied every
check a real session did, which skipped MFA entirely.

The dev seed carried a hand-written password_hash whose digest was 24
bytes instead of 32, so it matched no password at all. Nothing noticed
while passwords went unverified; it is a real hash now.

Verified with 30 tests, 13 of them against a real Postgres: wrong password,
unknown account, pass-the-hash, wrong TOTP code, challenge token replay,
lockout, single-use recovery codes, and the surface isolation that F4's
acceptance criteria require.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 09:33:29 -03:00
Lucas Rayan 23da5f43e4 #20: fix non-ASCII lint violations in webmail and router source files 2026-08-02 08:39:52 -03:00
Lucas Rayan 6e01fc7ffb #20: implement F4 webmail, admin console, 2FA TOTP, surface isolation, and i18n 2026-08-02 08:39:00 -03:00
Lucas RayanandClaude Opus 5 a9960d1c7c #19: locate the repository root by a file that is actually committed
The E2E suite has never run in CI. repoRoot() walked up looking for
PLAN.md, but .gitignore excludes PLAN.md on purpose ("Internal planning
docs - never published with the code"), so it is absent from every fresh
checkout and the helper always failed. All twelve E2E tests died on it,
in this run and identically in #18 before any of these changes.

The marker is now the migrations directory, which is committed and is
what every caller of repoRoot is ultimately looking for.

Reproduced by exporting the tree with git archive - which yields exactly
what actions/checkout puts on the runner - and running the suite there:
it fails with the old helper and passes with the new one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 08:07:59 -03:00
Lucas RayanandClaude Opus 5 46d421c874 #19: add Trivy scanning and multi-architecture GHCR publishing
CI gains a security job (Trivy fs: vuln, secret and misconfig) and an
image job that builds each of the four services and scans the result. The
secret scanner earns its place here: a DKIM key or Cloudflare token
committed by accident is a full compromise of every domain served.

release.yml publishes on a merge into main and on v* tags. Four services
on two architectures is eight build jobs pushing by digest, then four
publish jobs joining each pair into one manifest list, tagged latest, sha
and semver. github.repository is lowercased first because GHCR rejects an
uppercase path and this repository is lucasrguerra/LambdaMail.

Both scanners failed on first run, so this commit also fixes what they
found rather than shipping a workflow that is red on arrival:

  - All four images ran as root (DS-0002), which section 17 risk R5
    explicitly argues against. They now run unprivileged; protocols keeps
    its eight ports below 1024 through cap_net_bind_service on the binary
    rather than through being root.

  - A HIGH advisory in postcss, reached only through Next. "npm audit fix
    --force" would have resolved it by downgrading Next from 15 to 9, so
    it is pinned with an override instead.

  - The Node images copied the build stage's node_modules wholesale,
    shipping typescript, eslint and vitest into production, and the base
    image's own bundled npm accounted for the rest of the CVEs. Runtime
    dependencies now come from npm ci --omit=dev and npm is removed from
    the final layer.

  - compose-up could never have passed: the proxy network is external
    because Coolify owns it on the deploy host, and nothing creates it in
    CI, so compose refused to start the stack at all.

Verified locally: actionlint clean, all ten action refs confirmed to
exist, Trivy fs and all four image scans exit 0, the full stack reaches
Healthy on every container, and the containers run as uid 10001/1000 with
all eight privileged ports bound and SMTP answering on 25. The arm64
build itself is unverified - this machine has no buildx - and will first
be exercised by release.yml.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 07:58:02 -03:00
Lucas RayanandClaude Opus 5 33d91fa247 #19: fix F1-F3 defects found auditing the phases against PLAN.md
Every fix here is a case where the code and the plan disagreed, and the
code was wrong.

Certificates (section 8.2, 8.4). The parser documented that it skipped
expired entries but never checked, so an expired certificate would be
served until every handshake failed. LastReload() only advanced when
acme.json changed - and it does not change for sixty days - which made
the timestamp risk R2 monitors indistinguishable from a watcher gone
blind. Expiry is now checked on every pass, LastReload records the check
and LastChange the swap, and the <7d/<24h alerts of section 8.4 exist.

ARC (section 5). buildArcSealer resolved the DKIM key at startup, before
runDnsReconciler had provisioned one. On a first boot ARC was disabled
until someone restarted the process, which the log even admitted while
offering no way for it to start. A LazySealer binds on first use instead.

Health (section 8.4). There was no degraded state at all. /health now
reports one - still 200, because restarting cannot fix a certificate
Traefik never issued.

Bounces. DSNs were sent From postmaster@lambdamail.local, a domain that
does not resolve, so the notification was itself undeliverable. They now
carry the configured mail host, a Message-ID, and Auto-Submitted so a
vacation responder cannot loop against them.

Fan-out atomicity (section 6.1). Persist ran one transaction per
recipient, so a failure halfway through an alias fan-out left earlier
recipients with a copy while the sender was told to retry - and the retry
delivered to them twice. PersistAll commits the whole delivery or none of
it. Verified against Postgres by reverting the repository to the old
behaviour and confirming the new test fails on it.

SMTP replies. The use case encoded replies in error text ("550 5.7.1 ...")
which the adapter re-parsed by prefix, so rewording a message could turn a
permanent refusal into a retry. SmtpRejection carries the decision and the
adapter renders it.

Repository tests. These only run with TEST_DATABASE_URL, which CI does
set - so the job was red: copy and expunge seeded a 68-character digest
into a CHAR(64) column, and three others used fixed digests that collide
with the UNIQUE index on any re-run. A shared testBlobDigest() helper
fixes both; the suite now passes twice in a row against one database.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 07:57:22 -03:00
Lucas Rayan d56f29d084 #18: implement SMTP Submission (587/465), SASL PLAIN/LOGIN auth and preflight diagnostics 2026-08-01 22:49:02 -03:00
Lucas Rayan bd0af98076 #17: implement DANE TLSA, MTA-STS policy resolution, ARC sealing and mail authentication 2026-08-01 22:48:38 -03:00
Lucas Rayan b96be4a2a5 #16: implement DKIM key provisioning, Ed25519 & RSA dual signatures and rotation 2026-08-01 22:48:15 -03:00
Lucas Rayan 6ef427dc09 #15: implement ACME certificate store, Traefik/Coolify cert watcher & secrets vault 2026-08-01 22:47:53 -03:00
Lucas Rayan 842a9058d8 #14: implement Phase 3 complete E2E integration test 2026-07-25 10:42:50 -03:00
Lucas Rayan af35211094 #13: implement Outbound Queue, Retry Backoff Engine & DSN Bounce Generator (RFC 3464) 2026-07-25 10:33:07 -03:00
Lucas Rayan 54d1ea5810 #12: implement Antispam & Antivirus scanning pipeline (Rspamd & ClamAV) 2026-07-25 10:25:52 -03:00
Lucas Rayan 314eb67dda #11: implement MTA-STS, TLS-RPT & Autoconfig HTTP services 2026-07-25 10:18:03 -03:00
Lucas Rayan 10836ea98f #10: implement Cloudflare DNS automation engine (13 records & system aliases) 2026-07-25 05:26:14 -03:00
Lucas Rayan 1938b3e75a #9: add complete F2 end-to-end integration test suite 2026-07-25 04:33:50 -03:00
Lucas Rayan 0e6fc27bc1 #8: implement ManageSieve protocol server (RFC 5804) 2026-07-25 04:20:21 -03:00
Lucas Rayan 5a7dcc002a #6: fix E2E search result length assertion for IMAP4rev1 search 2026-07-24 12:02:49 -03:00
Lucas Rayan 31a465e2e5 #6: fix pointer type matching in numSetIter for IMAP STORE/FETCH 2026-07-24 11:57:22 -03:00
Lucas Rayan 9ca97298bd #7: implement POP3 protocol server (RFC 1939, RFC 2449, STLS) 2026-07-24 11:51:27 -03:00
Lucas Rayan 6b1e4dc00a #6: implement IMAP IDLE (RFC 2177) and CONDSTORE (RFC 7162) 2026-07-24 11:43:37 -03:00
Lucas RayanandClaude Sonnet 5 0ec0698079 #5: F2 sub-project 2 - IMAP SEARCH, EXPUNGE, COPY, MOVE
Adds the second F2 sub-project on top of the merged IMAP core: full
SEARCH criteria matching (flags, dates, size, headers, body/text,
NOT/OR), EXPUNGE (soft-delete via expunged_at), COPY, and MOVE (RFC
6851, advertised via CapMove/CapUIDPlus). Verified end-to-end with a
real go-imap/v2 client against embedded Postgres.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 09:40:47 -03:00
Lucas Rayan 9fa19291d4 #4: implement F2 sub-project 1 - IMAP core (auth, LIST, SELECT, FETCH, STORE)
Adds a real :143 IMAP listener to the Go protocols service: a mailbox
owner authenticates over IMAP (Argon2id against mailboxes.password_hash,
enumeration-resistant per PLAN.md section 14.6), lists folders, selects
INBOX, fetches messages F1's SMTP path already persisted - including real
ENVELOPE/BODY[] built from the actual stored MIME bytes via go-imap/v2's
own ExtractEnvelope/ExtractBodySection helpers, not reconstructed from
denormalized columns - and sets/reads flags via STORE.

- ImapSessionUseCase orchestrates auth, folder listing/selection, message
  querying, and flag mutation against new Postgres repositories (auth,
  folders, message query, flags) and a local-disk blob reader.
- A github.com/emersion/go-imap/v2 (pinned v2.0.0-beta.8) Backend/Session
  implements 7 real methods (Login, List, Select, Unselect, Status, Fetch,
  Store) plus a correct no-op Poll; the other 10 of the interface's 18
  methods (Create/Delete/Rename/Subscribe/Unsubscribe/Append/Idle/Expunge/
  Search/Copy) are explicit stubs returning a clear "not yet implemented"
  IMAP error - SEARCH/EXPUNGE/COPY/MOVE, IDLE/CONDSTORE, mailbox
  management, and APPEND are separate follow-up sub-projects per the
  design doc's agreed ordering with the user.

Verified end-to-end with a real go-imap/v2 imapclient (embedded Postgres,
no Docker needed) driving Login -> Select -> Fetch -> Store -> List
against a message seeded through F1's real SMTP use case, proving true
SMTP-write/IMAP-read interop, not just isolated unit tests.

Built via 8 sequential tasks under subagent-driven development, each
independently reviewed, plus a final whole-branch review. Two real bugs
were found and fixed before merge, both exactly the kind unit tests with
fakes cannot catch:
- Store's UID-set resolution silently no-op'd on dynamic ranges like
  "UID STORE 1:*" (the common "mark all as read" operation) after an
  earlier draft bypassed the folder's real message list; restored to
  resolve against real messages via the same pattern Fetch already used
  correctly, with tests proving both dynamic ranges and non-UID STORE.
- go-imap/v2's server calls Session.Poll() implicitly before the status
  response of nearly every authenticated command (FETCH/STORE/SEARCH/
  APPEND/COPY), not just IDLE as assumed - a hard-stubbed Poll broke every
  real command through this path; fixed to a correct no-op.
- List had zero test coverage despite being committed scope; added unit
  tests for wildcard/delimiter matching plus a real E2E LIST assertion.

Known follow-up, not blocking: a pre-existing test-fixture hygiene gap
(hardcoded content_sha256 blob hashes with no cleanup, shared across
several Postgres integration test files including one new to this
branch) causes local-dev test collisions on repeated runs against a
persistent database - invisible to CI (fresh Postgres per run) but worth
a cleanup pass.
2026-07-23 20:34:48 -03:00
Lucas Rayan 2f7389841d #3: close 3 known F1 gaps - folder/mailbox counters, quota-at-RCPT, alias fan-out
Per feature/3-f0-f1-validation's own gap analysis (commit 097fa37):

- InboundMessageRepository.Persist now updates folders.unread_count,
  folders.total_count, and mailboxes.used_bytes in the same transaction
  as the message insert (PLAN.md section 6.1 "++counters" was a no-op
  before this).
- MailboxRecord carries QuotaBytes/UsedBytes; ResolveRecipient rejects
  RCPT with 452 4.2.2 when a target mailbox has already reached its
  quota (used_bytes >= quota_bytes), before DATA - never silently
  accepting mail into a full mailbox.
- MailboxRepository.ResolveDeliveryTargets tries a direct mailbox match
  first, then falls back to the aliases table (exact source_address
  match takes precedence over a domain catch-all). One RCPT TO can now
  fan out to multiple mailboxes; alias destinations that don't resolve
  to an internal active mailbox are silently skipped, since outbound/
  external forwarding doesn't exist yet. postmaster@/abuse@/dmarc@-style
  aliases now actually deliver.

The E2E test's counters_updated subtest flips from a documented KNOWN
GAP (t.Skipf) to a hard assertion now that it passes, and gains two new
subtests (quota_rejected_when_mailbox_full, alias_resolves_to_destination_mailbox)
covering the other two fixes end-to-end. New unit and Postgres
integration test coverage added for all three fixes at every layer.

Verified: full suite green on Windows (unit + E2E via embedded
Postgres, no Docker needed) and via WSL Docker against the real
docker-compose Postgres (all infrastructure/postgres and diskstorage
integration tests, not just E2E). lang-lint clean.
2026-07-23 11:36:03 -03:00
Lucas RayanandClaude Fable 5 097fa373e1 #3: add embedded-Postgres E2E test validating F1 inbound SMTP against PLAN acceptance criteria
Boots a real Postgres (no Docker), applies the real migration and seed,
starts the real go-smtp server wired as main.go does, and drives a live
SMTP session. Asserts: 550 for unknown RCPT, durable EML + row with
uid_next allocation, sha256 disk/db match, outbox event, blob dedup with
ref_count. Documents the counters gap (PLAN 6.1) as an explicit skip.

Phase: F1 validation
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 11:23:19 -03:00
Lucas Rayan e501cdc69e #2: implement F1 sub-project 1 - inbound SMTP listener with EML storage
Adds a real :25 SMTP listener to the Go protocols service, giving F1's
"Nucleo SMTP" milestone its first working sub-project: application,
infrastructure, and presentation layers on top of F0's domain-only
Clean Architecture.

- ProcessInboundEmailUseCase resolves recipients against Postgres and
  persists accepted mail (blob dedup by content hash, transactional
  UID allocation + outbox event, never sending 250 OK before durable
  commit per PLAN.md section 6.1).
- Postgres repositories via pgx/v5 (replacing lib/pq entirely).
- Local-disk blob storage with content-hash dedup, rename-before-commit
  ordering so a DB row can never reference a file that isn't actually
  on disk.
- A local-file TLS cert provider for STARTTLS, with an ephemeral
  self-signed fallback so a missing/misconfigured cert degrades
  gracefully instead of crash-looping the service (PLAN.md section 8.4).
- A github.com/emersion/go-smtp Backend/Session adapting real SMTP
  traffic to the use case: unknown recipients get 550 5.1.1 before
  DATA, duplicate RCPT TO for the same address is deduplicated, TLS is
  hardened to the project's required PFS-only cipher/curve policy.
- A dev-seed script and Makefile target for local testing.

Explicitly out of scope (separate follow-up sub-projects): alias
resolution, SPF/DKIM/DMARC/ARC verification, Rspamd/ClamAV, Submission
ports with SASL auth, DKIM signing, outbound delivery, and the real
Traefik acme.json cert watcher.

Verified live end-to-end via WSL Docker: the full compose stack (db,
redis, migrate, auth, storage, protocols, web) reaches healthy, and a
real swaks SMTP session is accepted and durably persisted with correct
sequential UIDs, while an unknown recipient is correctly rejected with
550 5.1.1 and zero rows persisted. Built via 10 sequential tasks under
subagent-driven development, each independently reviewed, plus a final
whole-branch review that caught and fixed a TLS-crash bug, a blob
commit-ordering bug, missing TLS hardening, and missing CI integration
coverage before merge.

Known follow-up, not blocking: email_messages' partition only covers
July 2026 and needs a partition-management job before 2026-08-01.
2026-07-23 08:41:31 -03:00
Lucas Rayan 7c91182111 #1: fix webmail healthcheck - Next standalone binds IPv4-only, wget resolved localhost to ::1
Verified live via WSL Docker (docker compose up --wait): every other F0
service came up healthy, but web stayed unhealthy. Root cause was two
compounding issues, both invisible to static review:

1. Docker auto-sets HOSTNAME to the container ID; Next's standalone
   server.js honors that env var and binds only to it instead of all
   interfaces. Fixed by explicitly setting ENV HOSTNAME=0.0.0.0 in the
   Dockerfile, after Docker's automatic assignment.
2. Even bound to 0.0.0.0 (IPv4), the healthcheck's `wget http://localhost`
   resolved localhost to ::1 (IPv6) first inside the container, where
   nothing was listening. Fixed by pointing the healthcheck at
   127.0.0.1 explicitly instead of localhost.

Full stack (db, redis, migrate, auth, storage, protocols, web) now
reaches healthy end-to-end under docker compose up --wait.
2026-07-23 06:51:28 -03:00
Lucas Rayan eb09fa0ced #1: implement F0 foundation - monorepo, migrations, Go domain layer, service skeletons, CI
Stands up the LambdaMail monorepo per PLAN.md's F0 milestone: local dev
scaffolding (.env.example, Makefile, .gitignore excluding PLAN.md/docs/
.superpowers/), the full initial Postgres schema as a golang-migrate
migration, the complete Go domain layer for services/protocols (value
objects, entities, domain events - zero external imports beyond
github.com/google/uuid) with unit tests, health-checked service skeletons
for auth/storage (TypeScript) and webmail (Next.js), a local
docker-compose.yaml wiring all services together, a language-enforcement
lint script, and a GitHub Actions CI workflow.

Built via 11 sequential tasks under subagent-driven development, each with
an independent implementer + reviewer cycle. Fixes applied during review:
DomainName.IsPunycode() added to satisfy the promised interface; ioredis
default-import typing under NodeNext; next.js bumped 15.0.3->15.5.21 to
resolve high/critical CVEs; lang-lint.mjs corrected to not flag its own
banned-terms list; web service healthcheck added so compose --wait
actually waits on it; webmail Dockerfile's missing public/ directory:
protocols go.mod version aligned with CI's Go 1.22 pin.

Known follow-ups for later phases (not blocking F0): go-arch-lint isn't
wired into CI yet; live docker compose up and migration apply have not
been exercised in this dev environment (no Docker/psql available here)
and will get their first real run in CI, which does have Docker.
2026-07-23 05:05:46 -03:00