#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.
This commit is contained in:
Lucas Rayan committed 2026-07-23 05:05:46 -03:00
1 parent f219b28075
commit eb09fa0ced
73 files changed
+6891

No files matched your search

@@ -0,0 +1,32 @@
package entity
import "github.com/google/uuid"
// DkimStatus is the lifecycle state of a DkimKeyPair (PLAN.md section 9, dkim_keys.status).
type DkimStatus int
const (
DkimStatusPending DkimStatus = iota
DkimStatusActive
DkimStatusRetiring
DkimStatusRevoked
)
// DkimKeyPair is a DKIM signing key with a selector (PLAN.md section 3).
// Invariant enforced at the aggregate boundary (Domain), not here: only one
// ACTIVE key per (domain, algorithm) - see the unique partial index in migrations/0001.
type DkimKeyPair struct {
domainID uuid.UUID
selector string
status DkimStatus
}
func NewDkimKeyPair(domainID uuid.UUID, selector string) *DkimKeyPair {
return &DkimKeyPair{domainID: domainID, selector: selector, status: DkimStatusPending}
}
func (k *DkimKeyPair) Selector() string { return k.selector }
func (k *DkimKeyPair) Status() DkimStatus { return k.status }
func (k *DkimKeyPair) Activate() { k.status = DkimStatusActive }
func (k *DkimKeyPair) Retire() { k.status = DkimStatusRetiring }
func (k *DkimKeyPair) Revoke() { k.status = DkimStatusRevoked }
@@ -0,0 +1,22 @@
package entity
import (
"testing"
"github.com/google/uuid"
)
func TestNewDkimKeyPair_StartsPending(t *testing.T) {
k := NewDkimKeyPair(uuid.New(), "sel1")
if k.Status() != DkimStatusPending {
t.Errorf("Status() = %v, want DkimStatusPending", k.Status())
}
}
func TestDkimKeyPair_Activate_SetsActive(t *testing.T) {
k := NewDkimKeyPair(uuid.New(), "sel1")
k.Activate()
if k.Status() != DkimStatusActive {
t.Errorf("Status() = %v, want DkimStatusActive", k.Status())
}
}
@@ -0,0 +1,44 @@
// Package entity contains the domain's aggregate roots and entities (Clean Architecture layer 1).
package entity
import (
"errors"
"lambdamail/protocols/internal/domain/valueobject"
)
// Domain is the aggregate root for a hosted mail domain (PLAN.md section 3).
type Domain struct {
name valueobject.DomainName
active bool
activeMailboxCount int
}
var ErrDomainHasActiveMailboxes = errors.New("domain: cannot deactivate while it has active mailboxes")
func NewDomain(name valueobject.DomainName) *Domain {
return &Domain{name: name, active: true}
}
func (d *Domain) Name() valueobject.DomainName { return d.name }
func (d *Domain) IsActive() bool { return d.active }
func (d *Domain) ActiveMailboxCount() int { return d.activeMailboxCount }
// RegisterMailboxCreated tracks a newly created active mailbox under this domain.
func (d *Domain) RegisterMailboxCreated() { d.activeMailboxCount++ }
// RegisterMailboxRemoved tracks a mailbox no longer counted as active under this domain.
func (d *Domain) RegisterMailboxRemoved() {
if d.activeMailboxCount > 0 {
d.activeMailboxCount--
}
}
// Deactivate enforces the invariant "cannot deactivate with active mailboxes" (PLAN.md section 3).
func (d *Domain) Deactivate() error {
if d.activeMailboxCount > 0 {
return ErrDomainHasActiveMailboxes
}
d.active = false
return nil
}
@@ -0,0 +1,38 @@
package entity
import (
"testing"
"lambdamail/protocols/internal/domain/valueobject"
)
func TestNewDomain_StartsActiveWithNoMailboxes(t *testing.T) {
name, _ := valueobject.NewDomainName("example.com")
d := NewDomain(name)
if !d.IsActive() {
t.Error("IsActive() = false, want true for a newly created domain")
}
if d.ActiveMailboxCount() != 0 {
t.Errorf("ActiveMailboxCount() = %d, want 0", d.ActiveMailboxCount())
}
}
func TestDomain_Deactivate_SucceedsWithNoActiveMailboxes(t *testing.T) {
name, _ := valueobject.NewDomainName("example.com")
d := NewDomain(name)
if err := d.Deactivate(); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if d.IsActive() {
t.Error("IsActive() = true after Deactivate(), want false")
}
}
func TestDomain_Deactivate_FailsWithActiveMailboxes(t *testing.T) {
name, _ := valueobject.NewDomainName("example.com")
d := NewDomain(name)
d.RegisterMailboxCreated()
if err := d.Deactivate(); err == nil {
t.Fatal("expected error: a domain with active mailboxes must not be deactivatable (PLAN.md section 3)")
}
}
@@ -0,0 +1,24 @@
package entity
import "github.com/google/uuid"
// Folder is an IMAP folder entity. uidNext is strictly monotonic (RFC 3501 section 2.3.1.1),
// enforced per PLAN.md section 3.
type Folder struct {
mailboxID uuid.UUID
name string
uidNext int64
}
func NewFolder(mailboxID uuid.UUID, name string) *Folder {
return &Folder{mailboxID: mailboxID, name: name, uidNext: 1}
}
func (f *Folder) Name() string { return f.name }
// NextUID allocates and returns the next UID, then advances the counter.
func (f *Folder) NextUID() int64 {
uid := f.uidNext
f.uidNext++
return uid
}
@@ -0,0 +1,20 @@
package entity
import (
"testing"
"github.com/google/uuid"
)
func TestFolder_NextUID_StartsAtOneAndIsMonotonic(t *testing.T) {
f := NewFolder(uuid.New(), "INBOX")
first := f.NextUID()
second := f.NextUID()
third := f.NextUID()
if first != 1 {
t.Errorf("first NextUID() = %d, want 1 (RFC 3501 section 2.3.1.1 uid_next starts at 1)", first)
}
if second <= first || third <= second {
t.Errorf("NextUID() sequence not strictly increasing: %d, %d, %d", first, second, third)
}
}
@@ -0,0 +1,36 @@
package entity
import (
"errors"
"github.com/google/uuid"
"lambdamail/protocols/internal/domain/valueobject"
)
// Mailbox is a mail account entity (PLAN.md section 3).
type Mailbox struct {
domainID uuid.UUID
address valueobject.EmailAddress
hash valueobject.PasswordHash
quota valueobject.QuotaLimit
usedBytes int64
}
var ErrMailboxQuotaExceeded = errors.New("mailbox: recording this usage would exceed the quota")
func NewMailbox(domainID uuid.UUID, address valueobject.EmailAddress, hash valueobject.PasswordHash, quota valueobject.QuotaLimit) *Mailbox {
return &Mailbox{domainID: domainID, address: address, hash: hash, quota: quota}
}
func (m *Mailbox) Address() valueobject.EmailAddress { return m.address }
func (m *Mailbox) UsedBytes() int64 { return m.usedBytes }
func (m *Mailbox) Quota() valueobject.QuotaLimit { return m.quota }
// RecordUsage sets used_bytes, enforcing "used_bytes <= quota_bytes" (PLAN.md section 3).
func (m *Mailbox) RecordUsage(bytes int64) error {
if m.quota.Exceeds(bytes) {
return ErrMailboxQuotaExceeded
}
m.usedBytes = bytes
return nil
}
@@ -0,0 +1,40 @@
package entity
import (
"testing"
"github.com/google/uuid"
"lambdamail/protocols/internal/domain/valueobject"
)
func newTestMailbox(t *testing.T) *Mailbox {
t.Helper()
addr, _ := valueobject.NewEmailAddress("user@example.com")
hash, _ := valueobject.NewPasswordHash("$argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHQ$RdescudvJCsgt3ub+b+dWRWJTmaaJObG")
quota, _ := valueobject.NewQuotaLimit(1000)
return NewMailbox(uuid.New(), addr, hash, quota)
}
func TestNewMailbox_StartsWithZeroUsage(t *testing.T) {
m := newTestMailbox(t)
if m.UsedBytes() != 0 {
t.Errorf("UsedBytes() = %d, want 0", m.UsedBytes())
}
}
func TestMailbox_RecordUsage_AllowsUpToQuota(t *testing.T) {
m := newTestMailbox(t)
if err := m.RecordUsage(1000); err != nil {
t.Fatalf("unexpected error recording usage exactly at quota: %v", err)
}
if m.UsedBytes() != 1000 {
t.Errorf("UsedBytes() = %d, want 1000", m.UsedBytes())
}
}
func TestMailbox_RecordUsage_RejectsOverQuota(t *testing.T) {
m := newTestMailbox(t)
if err := m.RecordUsage(1001); err == nil {
t.Fatal("expected error: used_bytes must never exceed quota_bytes (PLAN.md section 3), got nil")
}
}
@@ -0,0 +1,51 @@
package entity
import (
"errors"
"time"
)
// OutboundJob is a delivery unit with retry state (PLAN.md section 3 and 6.3).
type OutboundJob struct {
attempt int
maxAttempts int
}
var ErrOutboundJobMaxAttemptsExceeded = errors.New("outbound job: attempt count would exceed max_attempts")
func NewOutboundJob(maxAttempts int) *OutboundJob {
return &OutboundJob{maxAttempts: maxAttempts}
}
func (j *OutboundJob) Attempt() int { return j.attempt }
// RecordAttempt enforces "attempt <= max_attempts" (PLAN.md section 3).
func (j *OutboundJob) RecordAttempt() error {
if j.attempt >= j.maxAttempts {
return ErrOutboundJobMaxAttemptsExceeded
}
j.attempt++
return nil
}
// retrySchedule mirrors the accumulated-wait table in PLAN.md section 6.3.
var retrySchedule = []time.Duration{
0,
5 * time.Minute,
15 * time.Minute,
1 * time.Hour,
2 * time.Hour,
4 * time.Hour,
8 * time.Hour,
12 * time.Hour,
}
// NextBackoff returns the wait before the next attempt, per the schedule in section 6.3.
// Attempts beyond the table repeat the last (12h) step, matching the "9+: every 12h" rule.
func (j *OutboundJob) NextBackoff() time.Duration {
idx := j.attempt
if idx >= len(retrySchedule) {
idx = len(retrySchedule) - 1
}
return retrySchedule[idx]
}
@@ -0,0 +1,40 @@
package entity
import "testing"
func TestOutboundJob_RecordAttempt_AllowsUpToMax(t *testing.T) {
j := NewOutboundJob(3)
for i := 0; i < 3; i++ {
if err := j.RecordAttempt(); err != nil {
t.Fatalf("attempt %d: unexpected error: %v", i+1, err)
}
}
if j.Attempt() != 3 {
t.Errorf("Attempt() = %d, want 3", j.Attempt())
}
}
func TestOutboundJob_RecordAttempt_RejectsBeyondMax(t *testing.T) {
j := NewOutboundJob(1)
if err := j.RecordAttempt(); err != nil {
t.Fatalf("unexpected error on first attempt: %v", err)
}
if err := j.RecordAttempt(); err == nil {
t.Fatal("expected error: attempt must never exceed max_attempts (PLAN.md section 3), got nil")
}
}
func TestOutboundJob_NextBackoff_IsMonotonicPerRetryTable(t *testing.T) {
// Backoff schedule from PLAN.md section 6.3: attempts 1-4 map to
// immediate, +5m, +15m, +1h.
j := NewOutboundJob(8)
var prev int64 = -1
for i := 0; i < 4; i++ {
j.RecordAttempt()
d := j.NextBackoff()
if int64(d) < prev {
t.Errorf("attempt %d: backoff %v is not >= previous backoff", i+1, d)
}
prev = int64(d)
}
}
@@ -0,0 +1,25 @@
package entity
// TLSPolicy is the effective transport security policy for an outbound destination
// (PLAN.md section 3: DANE has precedence over MTA-STS, RFC 8461 section 2).
type TLSPolicy struct {
daneAvailable bool
mtaSTSAvailable bool
}
func NewTLSPolicy(daneAvailable, mtaSTSAvailable bool) TLSPolicy {
return TLSPolicy{daneAvailable: daneAvailable, mtaSTSAvailable: mtaSTSAvailable}
}
// Effective returns "dane", "mta-sts" or "opportunistic" following the precedence
// rule in PLAN.md section 5 / RFC 8461 section 2.
func (p TLSPolicy) Effective() string {
switch {
case p.daneAvailable:
return "dane"
case p.mtaSTSAvailable:
return "mta-sts"
default:
return "opportunistic"
}
}
@@ -0,0 +1,25 @@
package entity
import "testing"
func TestTLSPolicy_Effective_DANETakesPrecedenceOverMTASTS(t *testing.T) {
// RFC 8461 section 2, restated in PLAN.md section 5: DANE wins when both are present.
p := NewTLSPolicy(true, true)
if p.Effective() != "dane" {
t.Errorf("Effective() = %q, want %q when both DANE and MTA-STS are available", p.Effective(), "dane")
}
}
func TestTLSPolicy_Effective_FallsBackToMTASTSWithoutDANE(t *testing.T) {
p := NewTLSPolicy(false, true)
if p.Effective() != "mta-sts" {
t.Errorf("Effective() = %q, want %q", p.Effective(), "mta-sts")
}
}
func TestTLSPolicy_Effective_FallsBackToOpportunisticWithNeither(t *testing.T) {
p := NewTLSPolicy(false, false)
if p.Effective() != "opportunistic" {
t.Errorf("Effective() = %q, want %q", p.Effective(), "opportunistic")
}
}