#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:
1 parent
f219b28075
commit
eb09fa0ced
73 files changed
+6891
No files matched your search
@@ -0,0 +1,27 @@
|
||||
# --- Postgres ---
|
||||
POSTGRES_DB=lambdamail
|
||||
POSTGRES_USER=lambdamail
|
||||
POSTGRES_PASSWORD=change-me-in-local-dev
|
||||
|
||||
# --- Redis ---
|
||||
REDIS_PASSWORD=change-me-in-local-dev
|
||||
|
||||
# --- Shared secrets (local dev values — never reuse in production) ---
|
||||
JWT_SECRET=local-dev-jwt-secret-change-me
|
||||
LAMBDAMAIL_MASTER_KEY=local-dev-master-key-32-bytes-min
|
||||
|
||||
# --- Cloudflare (optional in F0 — DNS automation lands in F3) ---
|
||||
CLOUDFLARE_API_TOKEN=
|
||||
|
||||
# --- Host identity ---
|
||||
PRIMARY_MAIL_HOST=mail.localhost
|
||||
PUBLIC_IPV4=127.0.0.1
|
||||
PUBLIC_IPV6=
|
||||
|
||||
# --- TLS (F0 has no real certs — protocols stub reports degraded, never crashes) ---
|
||||
TLS_MODE=traefik
|
||||
COOLIFY_PROXY_DIR=./local/acme
|
||||
|
||||
# --- Webmail ---
|
||||
WEBMAIL_HOST=localhost:3000
|
||||
ADMIN_HOST=
|
||||
@@ -0,0 +1,73 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
lang-lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: node scripts/lang-lint.mjs
|
||||
|
||||
go-protocols:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: services/protocols
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with: { go-version: "1.22" }
|
||||
- run: go vet ./...
|
||||
- run: go test ./... -v
|
||||
|
||||
ts-auth:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: services/auth
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with: { node-version: "20" }
|
||||
- run: npm install
|
||||
- run: npm run lint
|
||||
- run: npm test
|
||||
|
||||
ts-storage:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: services/storage
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with: { node-version: "20" }
|
||||
- run: npm install
|
||||
- run: npm run lint
|
||||
- run: npm test
|
||||
|
||||
webmail-build:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: services/webmail
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with: { node-version: "20" }
|
||||
- run: npm install
|
||||
- run: npm run build
|
||||
|
||||
compose-up:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [go-protocols, ts-auth, ts-storage, webmail-build]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: cp .env.example .env
|
||||
- run: docker compose --env-file .env up --build --wait
|
||||
- run: docker compose ps
|
||||
- run: docker compose down -v
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
# Internal planning docs — never published with the code
|
||||
PLAN.md
|
||||
docs/
|
||||
.superpowers/
|
||||
|
||||
# Dependencies
|
||||
node_modules/
|
||||
vendor/
|
||||
|
||||
# Build output
|
||||
.next/
|
||||
dist/
|
||||
build/
|
||||
*.exe
|
||||
|
||||
# Env / secrets
|
||||
.env
|
||||
.env.local
|
||||
acme.json
|
||||
|
||||
# Go
|
||||
*.test
|
||||
*.out
|
||||
|
||||
# OS / editor
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
.vscode/
|
||||
.idea/
|
||||
@@ -0,0 +1,27 @@
|
||||
.PHONY: up down logs test lint migrate-up migrate-down
|
||||
|
||||
up:
|
||||
docker compose --env-file .env up --build
|
||||
|
||||
down:
|
||||
docker compose down -v
|
||||
|
||||
logs:
|
||||
docker compose logs -f
|
||||
|
||||
test:
|
||||
cd services/protocols && go test ./...
|
||||
cd services/auth && npm test
|
||||
cd services/storage && npm test
|
||||
|
||||
lint:
|
||||
cd services/protocols && go vet ./...
|
||||
node scripts/lang-lint.mjs
|
||||
|
||||
migrate-up:
|
||||
docker run --rm -v $(PWD)/migrations:/migrations --network host \
|
||||
migrate/migrate -path=/migrations -database "$$DATABASE_URL" up
|
||||
|
||||
migrate-down:
|
||||
docker run --rm -v $(PWD)/migrations:/migrations --network host \
|
||||
migrate/migrate -path=/migrations -database "$$DATABASE_URL" down 1
|
||||
@@ -0,0 +1,129 @@
|
||||
x-logging: &default-logging
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "3" }
|
||||
|
||||
services:
|
||||
db:
|
||||
image: postgres:16-alpine
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:?required}
|
||||
POSTGRES_USER: ${POSTGRES_USER:?required}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?required}
|
||||
ports: ["5432:5432"]
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
command: >
|
||||
redis-server --appendonly yes --requirepass ${REDIS_PASSWORD:?required}
|
||||
environment:
|
||||
REDIS_PASSWORD: ${REDIS_PASSWORD}
|
||||
volumes: [redis_data:/data]
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "redis-cli --no-auth-warning -a $${REDIS_PASSWORD} ping | grep -q PONG"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
|
||||
migrate:
|
||||
image: migrate/migrate:v4.17.1
|
||||
restart: "no"
|
||||
volumes: ["./migrations:/migrations"]
|
||||
depends_on:
|
||||
db: { condition: service_healthy }
|
||||
entrypoint:
|
||||
- migrate
|
||||
- -path=/migrations
|
||||
- -database
|
||||
- postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable
|
||||
- up
|
||||
|
||||
auth:
|
||||
build: { context: ./services/auth }
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
environment:
|
||||
PORT: 3001
|
||||
DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable
|
||||
REDIS_URL: redis://:${REDIS_PASSWORD}@redis:6379
|
||||
JWT_SECRET: ${JWT_SECRET:?required}
|
||||
LAMBDAMAIL_MASTER_KEY: ${LAMBDAMAIL_MASTER_KEY:?required}
|
||||
depends_on:
|
||||
db: { condition: service_healthy }
|
||||
redis: { condition: service_healthy }
|
||||
migrate: { condition: service_completed_successfully }
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "-e", "fetch('http://localhost:3001/health/ready').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 15s
|
||||
|
||||
storage:
|
||||
build: { context: ./services/storage }
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
environment:
|
||||
PORT: 3002
|
||||
DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable
|
||||
REDIS_URL: redis://:${REDIS_PASSWORD}@redis:6379
|
||||
depends_on:
|
||||
db: { condition: service_healthy }
|
||||
redis: { condition: service_healthy }
|
||||
migrate: { condition: service_completed_successfully }
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "-e", "fetch('http://localhost:3002/health/ready').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 15s
|
||||
|
||||
protocols:
|
||||
build: { context: ./services/protocols }
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
ports: ["8080:8080"]
|
||||
environment:
|
||||
DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable
|
||||
depends_on:
|
||||
db: { condition: service_healthy }
|
||||
migrate: { condition: service_completed_successfully }
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -qO- http://localhost:8080/health/ready || exit 1"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 15s
|
||||
|
||||
web:
|
||||
build: { context: ./services/webmail }
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
ports: ["3000:3000"]
|
||||
environment:
|
||||
PORT: 3000
|
||||
AUTH_SERVICE_URL: http://auth:3001
|
||||
STORAGE_SERVICE_URL: http://storage:3002
|
||||
depends_on:
|
||||
auth: { condition: service_healthy }
|
||||
storage: { condition: service_healthy }
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -qO- http://localhost:3000/health || exit 1"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 15s
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
@@ -0,0 +1,22 @@
|
||||
-- 0001_init_schema.down.sql
|
||||
DROP TABLE IF EXISTS audit_log;
|
||||
DROP TABLE IF EXISTS dmarc_reports;
|
||||
DROP TABLE IF EXISTS tls_policy_cache;
|
||||
DROP TABLE IF EXISTS sieve_scripts;
|
||||
DROP TABLE IF EXISTS domain_events_outbox;
|
||||
DROP TABLE IF EXISTS outbound_jobs;
|
||||
DROP TABLE IF EXISTS message_flags;
|
||||
DROP TABLE IF EXISTS email_messages_2026_07;
|
||||
DROP TABLE IF EXISTS email_messages;
|
||||
DROP TABLE IF EXISTS message_blobs;
|
||||
DROP TABLE IF EXISTS folders;
|
||||
DROP TABLE IF EXISTS aliases;
|
||||
DROP TABLE IF EXISTS app_passwords;
|
||||
DROP TABLE IF EXISTS web_sessions;
|
||||
DROP TABLE IF EXISTS trusted_devices;
|
||||
DROP TABLE IF EXISTS mfa_webauthn_credentials;
|
||||
DROP TABLE IF EXISTS mfa_recovery_codes;
|
||||
DROP TABLE IF EXISTS mfa_totp;
|
||||
DROP TABLE IF EXISTS mailboxes;
|
||||
DROP TABLE IF EXISTS dkim_keys;
|
||||
DROP TABLE IF EXISTS domains;
|
||||
@@ -0,0 +1,382 @@
|
||||
-- 0001_init_schema.up.sql
|
||||
-- Initial LambdaMail schema. Source of truth: PLAN.md section 9.
|
||||
|
||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||
CREATE EXTENSION IF NOT EXISTS citext; -- case-insensitive local-part comparison
|
||||
CREATE EXTENSION IF NOT EXISTS pg_trgm; -- similarity search
|
||||
|
||||
-- =====================================================================
|
||||
-- 1. DOMAINS
|
||||
-- =====================================================================
|
||||
CREATE TABLE domains (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name CITEXT NOT NULL UNIQUE,
|
||||
punycode_name VARCHAR(255) NOT NULL, -- IDNA for non-ASCII names
|
||||
cloudflare_zone_id VARCHAR(64),
|
||||
-- Token is ENCRYPTED (AES-256-GCM), not hashed: it must be reusable.
|
||||
cloudflare_token_enc BYTEA,
|
||||
cloudflare_token_nonce BYTEA,
|
||||
cloudflare_key_version INT DEFAULT 1, -- supports KEK rotation
|
||||
dns_status VARCHAR(16) NOT NULL DEFAULT 'PENDING'
|
||||
CHECK (dns_status IN ('PENDING','VERIFIED','PARTIAL','DRIFT','ERROR')),
|
||||
dns_last_checked_at TIMESTAMPTZ,
|
||||
dns_state_hash VARCHAR(64),
|
||||
dmarc_policy VARCHAR(16) NOT NULL DEFAULT 'quarantine'
|
||||
CHECK (dmarc_policy IN ('none','quarantine','reject')),
|
||||
mta_sts_mode VARCHAR(16) NOT NULL DEFAULT 'testing'
|
||||
CHECK (mta_sts_mode IN ('none','testing','enforce')),
|
||||
mta_sts_id VARCHAR(32),
|
||||
dane_enabled BOOLEAN NOT NULL DEFAULT false,
|
||||
max_message_bytes BIGINT NOT NULL DEFAULT 52428800, -- 50 MB
|
||||
-- Domain MFA policy (see PLAN.md section 14.5). Admins are always required.
|
||||
mfa_policy VARCHAR(16) NOT NULL DEFAULT 'required_admins'
|
||||
CHECK (mfa_policy IN ('optional','required_admins','required_all')),
|
||||
is_active BOOLEAN NOT NULL DEFAULT true,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- =====================================================================
|
||||
-- 2. DKIM KEYS (private key ENCRYPTED + lifecycle for rotation)
|
||||
-- =====================================================================
|
||||
CREATE TABLE dkim_keys (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
domain_id UUID NOT NULL REFERENCES domains(id) ON DELETE CASCADE,
|
||||
selector VARCHAR(63) NOT NULL,
|
||||
algorithm VARCHAR(16) NOT NULL CHECK (algorithm IN ('rsa2048','rsa4096','ed25519')),
|
||||
private_key_enc BYTEA NOT NULL,
|
||||
private_key_nonce BYTEA NOT NULL,
|
||||
key_version INT NOT NULL DEFAULT 1,
|
||||
public_key TEXT NOT NULL,
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'PENDING'
|
||||
CHECK (status IN ('PENDING','ACTIVE','RETIRING','REVOKED')),
|
||||
activated_at TIMESTAMPTZ,
|
||||
retire_after TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE (domain_id, selector)
|
||||
);
|
||||
-- Invariant: at most one ACTIVE key per (domain, algorithm).
|
||||
CREATE UNIQUE INDEX uq_dkim_active
|
||||
ON dkim_keys(domain_id, algorithm) WHERE status = 'ACTIVE';
|
||||
|
||||
-- =====================================================================
|
||||
-- 3. MAILBOXES
|
||||
-- =====================================================================
|
||||
CREATE TABLE mailboxes (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
domain_id UUID NOT NULL REFERENCES domains(id) ON DELETE CASCADE,
|
||||
local_part CITEXT NOT NULL,
|
||||
email_address CITEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL, -- Argon2id, PHC string format
|
||||
password_updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
quota_bytes BIGINT NOT NULL DEFAULT 1073741824,
|
||||
used_bytes BIGINT NOT NULL DEFAULT 0 CHECK (used_bytes >= 0),
|
||||
max_recipients_per_hour INT NOT NULL DEFAULT 200, -- contains a compromised account
|
||||
failed_login_count INT NOT NULL DEFAULT 0,
|
||||
locked_until TIMESTAMPTZ,
|
||||
-- Interface and notification language for this user (see PLAN.md section 21).
|
||||
locale VARCHAR(8) NOT NULL DEFAULT 'en'
|
||||
CHECK (locale IN ('en','pt-BR','es')),
|
||||
timezone VARCHAR(64) NOT NULL DEFAULT 'UTC', -- IANA tz
|
||||
role VARCHAR(16) NOT NULL DEFAULT 'USER'
|
||||
CHECK (role IN ('USER','DOMAIN_ADMIN','SUPER_ADMIN')),
|
||||
is_active BOOLEAN NOT NULL DEFAULT true,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE (domain_id, local_part)
|
||||
);
|
||||
|
||||
-- ---------------------------------------------------------------------
|
||||
-- 3b. SECOND FACTOR (TOTP RFC 6238 - Google Authenticator, Aegis, 1Password)
|
||||
-- ---------------------------------------------------------------------
|
||||
CREATE TABLE mfa_totp (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
mailbox_id UUID NOT NULL REFERENCES mailboxes(id) ON DELETE CASCADE,
|
||||
label VARCHAR(64) NOT NULL DEFAULT 'Authenticator',
|
||||
secret_enc BYTEA NOT NULL, -- base32 secret, encrypted (AES-256-GCM / KEK)
|
||||
secret_nonce BYTEA NOT NULL,
|
||||
key_version INT NOT NULL DEFAULT 1,
|
||||
algorithm VARCHAR(8) NOT NULL DEFAULT 'SHA1', -- SHA1: required by Google Authenticator
|
||||
digits SMALLINT NOT NULL DEFAULT 6,
|
||||
period_seconds SMALLINT NOT NULL DEFAULT 30,
|
||||
-- Two-step enrollment: becomes CONFIRMED only after the user proves one code.
|
||||
status VARCHAR(12) NOT NULL DEFAULT 'PENDING'
|
||||
CHECK (status IN ('PENDING','CONFIRMED','REVOKED')),
|
||||
-- Anti-replay (RFC 6238 section 5.2): a code can only be used once.
|
||||
last_used_step BIGINT,
|
||||
confirmed_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE UNIQUE INDEX uq_totp_confirmed ON mfa_totp(mailbox_id) WHERE status = 'CONFIRMED';
|
||||
|
||||
-- Recovery codes: single use, stored as hash (never recoverable).
|
||||
CREATE TABLE mfa_recovery_codes (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
mailbox_id UUID NOT NULL REFERENCES mailboxes(id) ON DELETE CASCADE,
|
||||
code_hash TEXT NOT NULL, -- Argon2id
|
||||
used_at TIMESTAMPTZ,
|
||||
used_ip INET,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX idx_recovery_unused ON mfa_recovery_codes(mailbox_id) WHERE used_at IS NULL;
|
||||
|
||||
-- WebAuthn / passkeys - Phase 6, table created now so MFA doesn't need a breaking migration later.
|
||||
CREATE TABLE mfa_webauthn_credentials (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
mailbox_id UUID NOT NULL REFERENCES mailboxes(id) ON DELETE CASCADE,
|
||||
credential_id BYTEA NOT NULL UNIQUE,
|
||||
public_key BYTEA NOT NULL,
|
||||
sign_count BIGINT NOT NULL DEFAULT 0,
|
||||
label VARCHAR(64),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Trusted devices: "don't ask for the code for 30 days" on this browser.
|
||||
CREATE TABLE trusted_devices (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
mailbox_id UUID NOT NULL REFERENCES mailboxes(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
user_agent TEXT,
|
||||
ip_address INET,
|
||||
surface VARCHAR(8) NOT NULL CHECK (surface IN ('user','admin')),
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
last_seen_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Webmail/admin sessions, individually revocable by the user.
|
||||
CREATE TABLE web_sessions (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
mailbox_id UUID NOT NULL REFERENCES mailboxes(id) ON DELETE CASCADE,
|
||||
surface VARCHAR(8) NOT NULL CHECK (surface IN ('user','admin')),
|
||||
refresh_token_hash TEXT NOT NULL UNIQUE,
|
||||
mfa_satisfied BOOLEAN NOT NULL DEFAULT false,
|
||||
mfa_satisfied_at TIMESTAMPTZ, -- step-up: admin re-requires after 15 min
|
||||
ip_address INET,
|
||||
user_agent TEXT,
|
||||
revoked_at TIMESTAMPTZ,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX idx_sessions_active ON web_sessions(mailbox_id) WHERE revoked_at IS NULL;
|
||||
|
||||
-- App passwords (IMAP/SMTP clients cannot do 2FA)
|
||||
CREATE TABLE app_passwords (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
mailbox_id UUID NOT NULL REFERENCES mailboxes(id) ON DELETE CASCADE,
|
||||
label VARCHAR(64) NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
scopes TEXT[] NOT NULL DEFAULT '{imap,pop3,smtp}',
|
||||
last_used_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- =====================================================================
|
||||
-- 4. ALIASES (catch-all and multiple destinations supported)
|
||||
-- =====================================================================
|
||||
CREATE TABLE aliases (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
domain_id UUID NOT NULL REFERENCES domains(id) ON DELETE CASCADE,
|
||||
source_address CITEXT NOT NULL, -- '*@domain' = catch-all
|
||||
destination_addresses TEXT[] NOT NULL CHECK (cardinality(destination_addresses) > 0),
|
||||
is_catch_all BOOLEAN NOT NULL DEFAULT false,
|
||||
is_active BOOLEAN NOT NULL DEFAULT true,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE (domain_id, source_address)
|
||||
);
|
||||
|
||||
-- =====================================================================
|
||||
-- 5. FOLDERS (mandatory IMAP state)
|
||||
-- =====================================================================
|
||||
CREATE TABLE folders (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
mailbox_id UUID NOT NULL REFERENCES mailboxes(id) ON DELETE CASCADE,
|
||||
name VARCHAR(255) NOT NULL, -- decoded modified UTF-7
|
||||
special_use VARCHAR(16) -- RFC 6154
|
||||
CHECK (special_use IN ('inbox','sent','drafts','trash','junk','archive')),
|
||||
parent_id UUID REFERENCES folders(id) ON DELETE CASCADE,
|
||||
uid_validity BIGINT NOT NULL DEFAULT (EXTRACT(EPOCH FROM NOW())::BIGINT),
|
||||
uid_next BIGINT NOT NULL DEFAULT 1, -- RFC 3501 section 2.3.1.1
|
||||
highest_modseq BIGINT NOT NULL DEFAULT 1, -- RFC 7162 CONDSTORE
|
||||
subscribed BOOLEAN NOT NULL DEFAULT true,
|
||||
unread_count INT NOT NULL DEFAULT 0,
|
||||
total_count INT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
-- TRAP: UNIQUE(mailbox_id, parent_id, name) does NOT prevent duplicates at the root -
|
||||
-- in SQL, NULL != NULL, so two root folders named "Work" would both pass.
|
||||
-- Two partial indexes cover both cases:
|
||||
CREATE UNIQUE INDEX uq_folder_child ON folders(mailbox_id, parent_id, name)
|
||||
WHERE parent_id IS NOT NULL;
|
||||
CREATE UNIQUE INDEX uq_folder_root ON folders(mailbox_id, name)
|
||||
WHERE parent_id IS NULL;
|
||||
|
||||
-- =====================================================================
|
||||
-- 6. BLOBS (deduplication: 1 email to 50 recipients = 1 file)
|
||||
-- =====================================================================
|
||||
CREATE TABLE message_blobs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
content_sha256 CHAR(64) NOT NULL UNIQUE,
|
||||
storage_driver VARCHAR(16) NOT NULL CHECK (storage_driver IN ('local','s3')),
|
||||
storage_path VARCHAR(1024) NOT NULL,
|
||||
size_bytes BIGINT NOT NULL,
|
||||
ref_count INT NOT NULL DEFAULT 0 CHECK (ref_count >= 0),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- =====================================================================
|
||||
-- 7. MESSAGES (partitioned by month - volume grows without bound)
|
||||
-- =====================================================================
|
||||
CREATE TABLE email_messages (
|
||||
id UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||
mailbox_id UUID NOT NULL,
|
||||
folder_id UUID NOT NULL,
|
||||
uid BIGINT NOT NULL, -- unique and increasing within the folder
|
||||
modseq BIGINT NOT NULL DEFAULT 1,
|
||||
blob_id UUID NOT NULL REFERENCES message_blobs(id),
|
||||
message_id_header VARCHAR(998),
|
||||
in_reply_to VARCHAR(998),
|
||||
thread_id UUID, -- conversation grouping
|
||||
sender_address CITEXT NOT NULL,
|
||||
from_display_name TEXT,
|
||||
recipient_addresses TEXT[] NOT NULL,
|
||||
subject TEXT,
|
||||
snippet TEXT,
|
||||
size_bytes BIGINT NOT NULL,
|
||||
has_attachments BOOLEAN NOT NULL DEFAULT false,
|
||||
-- Security verdicts
|
||||
spf_result VARCHAR(12) CHECK (spf_result IN ('pass','fail','softfail','neutral','none','temperror','permerror')),
|
||||
dkim_result VARCHAR(12) CHECK (dkim_result IN ('pass','fail','none','policy','temperror','permerror')),
|
||||
dmarc_result VARCHAR(12) CHECK (dmarc_result IN ('pass','fail','none')),
|
||||
arc_result VARCHAR(12),
|
||||
dane_status VARCHAR(12) CHECK (dane_status IN ('verified','skipped','failed','unsupported')),
|
||||
tls_version VARCHAR(8),
|
||||
spam_score NUMERIC(6,2) NOT NULL DEFAULT 0,
|
||||
spam_verdict VARCHAR(12) CHECK (spam_verdict IN ('ham','probable','spam','reject')),
|
||||
virus_name VARCHAR(128),
|
||||
received_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
expunged_at TIMESTAMPTZ, -- soft delete (IMAP \Deleted + EXPUNGE)
|
||||
search_vector TSVECTOR GENERATED ALWAYS AS (
|
||||
to_tsvector('simple',
|
||||
coalesce(subject,'') || ' ' ||
|
||||
coalesce(snippet,'') || ' ' ||
|
||||
coalesce(sender_address::text,''))
|
||||
) STORED,
|
||||
PRIMARY KEY (id, received_at)
|
||||
) PARTITION BY RANGE (received_at);
|
||||
|
||||
-- Partitions are created by a monthly job (pg_partman or a custom routine).
|
||||
-- Seed the current month so local dev / F0 has a writable partition out of the box.
|
||||
CREATE TABLE email_messages_2026_07 PARTITION OF email_messages
|
||||
FOR VALUES FROM ('2026-07-01') TO ('2026-08-01');
|
||||
|
||||
-- Uniqueness index (folder_id, uid): on a partitioned table, every UNIQUE index
|
||||
-- must include the partition key - so this alone does NOT guarantee the invariant
|
||||
-- (the same (folder_id, uid) could exist in different partitions). The real guarantee
|
||||
-- comes from the APPLICATION: UIDs are allocated exclusively via folders.uid_next under
|
||||
-- SELECT ... FOR UPDATE, in the same transaction as the INSERT. This index is defense
|
||||
-- in depth within each partition + speeds up FETCH by UID.
|
||||
CREATE UNIQUE INDEX uq_msg_folder_uid ON email_messages(folder_id, uid, received_at);
|
||||
CREATE INDEX idx_msg_list ON email_messages(mailbox_id, folder_id, received_at DESC)
|
||||
WHERE expunged_at IS NULL;
|
||||
CREATE INDEX idx_msg_modseq ON email_messages(folder_id, modseq); -- CONDSTORE sync
|
||||
CREATE INDEX idx_msg_search ON email_messages USING GIN(search_vector);
|
||||
CREATE INDEX idx_msg_thread ON email_messages(thread_id) WHERE thread_id IS NOT NULL;
|
||||
CREATE INDEX idx_msg_msgid ON email_messages(message_id_header);
|
||||
|
||||
-- =====================================================================
|
||||
-- 8. IMAP FLAGS (separate table: \Seen \Answered \Flagged \Draft + keywords)
|
||||
-- =====================================================================
|
||||
CREATE TABLE message_flags (
|
||||
message_id UUID NOT NULL,
|
||||
received_at TIMESTAMPTZ NOT NULL,
|
||||
flag VARCHAR(64) NOT NULL,
|
||||
PRIMARY KEY (message_id, received_at, flag),
|
||||
-- FK to a partitioned table is supported since PG 12; without it, orphan
|
||||
-- flags would accumulate forever after EXPUNGE.
|
||||
FOREIGN KEY (message_id, received_at)
|
||||
REFERENCES email_messages(id, received_at) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX idx_flags_lookup ON message_flags(flag, message_id);
|
||||
|
||||
-- =====================================================================
|
||||
-- 9. OUTBOUND QUEUE (source of truth in Postgres; Redis is only an index)
|
||||
-- =====================================================================
|
||||
CREATE TABLE outbound_jobs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
mailbox_id UUID REFERENCES mailboxes(id) ON DELETE SET NULL,
|
||||
blob_id UUID NOT NULL REFERENCES message_blobs(id),
|
||||
envelope_from CITEXT NOT NULL, -- '' = bounce (never re-bounce)
|
||||
envelope_to CITEXT NOT NULL,
|
||||
destination_domain CITEXT NOT NULL,
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'QUEUED'
|
||||
CHECK (status IN ('QUEUED','SENDING','DEFERRED','DELIVERED','BOUNCED','CANCELLED')),
|
||||
attempt INT NOT NULL DEFAULT 0,
|
||||
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
expires_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + INTERVAL '5 days',
|
||||
last_smtp_code VARCHAR(4),
|
||||
last_error TEXT,
|
||||
tls_policy_used VARCHAR(16), -- dane | mta-sts | opportunistic | none
|
||||
delay_dsn_sent BOOLEAN NOT NULL DEFAULT false,
|
||||
locked_by VARCHAR(64), -- worker id
|
||||
locked_until TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX idx_outbound_ready ON outbound_jobs(next_attempt_at)
|
||||
WHERE status IN ('QUEUED','DEFERRED');
|
||||
CREATE INDEX idx_outbound_domain ON outbound_jobs(destination_domain, status);
|
||||
|
||||
-- =====================================================================
|
||||
-- 10. TRANSACTIONAL OUTBOX (events are never published outside the transaction)
|
||||
-- =====================================================================
|
||||
CREATE TABLE domain_events_outbox (
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
event_type VARCHAR(64) NOT NULL,
|
||||
aggregate_id UUID NOT NULL,
|
||||
payload JSONB NOT NULL,
|
||||
published_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- =====================================================================
|
||||
-- 11. SIEVE, TLS POLICY CACHE, REPORTS AND AUDIT
|
||||
-- =====================================================================
|
||||
CREATE TABLE sieve_scripts (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
mailbox_id UUID NOT NULL REFERENCES mailboxes(id) ON DELETE CASCADE,
|
||||
name VARCHAR(128) NOT NULL,
|
||||
script TEXT NOT NULL,
|
||||
is_active BOOLEAN NOT NULL DEFAULT false,
|
||||
UNIQUE (mailbox_id, name)
|
||||
);
|
||||
CREATE UNIQUE INDEX uq_sieve_active ON sieve_scripts(mailbox_id) WHERE is_active;
|
||||
|
||||
CREATE TABLE tls_policy_cache (
|
||||
destination_domain CITEXT PRIMARY KEY,
|
||||
policy_type VARCHAR(16) NOT NULL, -- dane | mta-sts | none
|
||||
policy_body JSONB NOT NULL,
|
||||
mx_patterns TEXT[],
|
||||
fetched_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
expires_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE dmarc_reports (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
domain_id UUID NOT NULL REFERENCES domains(id) ON DELETE CASCADE,
|
||||
org_name VARCHAR(255),
|
||||
report_id VARCHAR(255),
|
||||
date_begin TIMESTAMPTZ, date_end TIMESTAMPTZ,
|
||||
raw_xml TEXT,
|
||||
summary JSONB, -- {pass, fail, sources:[{ip,count,spf,dkim}]}
|
||||
UNIQUE (domain_id, org_name, report_id)
|
||||
);
|
||||
|
||||
CREATE TABLE audit_log (
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
actor_id UUID, actor_ip INET,
|
||||
action VARCHAR(64) NOT NULL,
|
||||
target_type VARCHAR(64), target_id UUID,
|
||||
metadata JSONB,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX idx_audit_time ON audit_log(created_at DESC);
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env node
|
||||
// Fails the build if tracked source contains non-ASCII characters or common
|
||||
// Portuguese terms in identifiers/comments (PLAN.md section 21.1: "all code in
|
||||
// English, no exceptions - enforced by CI, not by human review").
|
||||
import { execSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
const BANNED_TERMS = [
|
||||
"usuario", "senha", "endereco", "mensagem", "dominio", "caixa",
|
||||
"remetente", "destinatario", "cadastro", "autenticacao",
|
||||
];
|
||||
|
||||
const SCANNED_PREFIXES = ["services/", "migrations/", "scripts/"];
|
||||
const SCANNED_EXTENSIONS = [".go", ".ts", ".tsx", ".sql", ".mjs", ".js"];
|
||||
|
||||
function trackedFiles() {
|
||||
return execSync("git ls-files", { encoding: "utf8" })
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.filter((f) => SCANNED_PREFIXES.some((p) => f.startsWith(p)))
|
||||
.filter((f) => SCANNED_EXTENSIONS.some((ext) => f.endsWith(ext))); // tests are scanned too - same rule applies
|
||||
}
|
||||
|
||||
let failures = [];
|
||||
|
||||
for (const file of trackedFiles()) {
|
||||
const isSelf = file === "scripts/lang-lint.mjs";
|
||||
const content = readFileSync(file, "utf8");
|
||||
const lines = content.split("\n");
|
||||
lines.forEach((line, i) => {
|
||||
if (/[^\x00-\x7F]/.test(line)) {
|
||||
failures.push(`${file}:${i + 1}: non-ASCII character`);
|
||||
}
|
||||
if (!isSelf) {
|
||||
const lower = line.toLowerCase();
|
||||
for (const term of BANNED_TERMS) {
|
||||
if (lower.includes(term)) {
|
||||
failures.push(`${file}:${i + 1}: banned Portuguese term "${term}"`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (failures.length > 0) {
|
||||
console.error(`lang-lint: ${failures.length} violation(s) found:\n`);
|
||||
for (const f of failures.slice(0, 50)) console.error(` ${f}`);
|
||||
if (failures.length > 50) console.error(` ... and ${failures.length - 50} more`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log("lang-lint: clean");
|
||||
@@ -0,0 +1,14 @@
|
||||
FROM node:20-alpine AS build
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json* ./
|
||||
RUN npm install
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-alpine
|
||||
WORKDIR /app
|
||||
COPY --from=build /app/node_modules ./node_modules
|
||||
COPY --from=build /app/dist ./dist
|
||||
COPY package.json ./
|
||||
EXPOSE 3001
|
||||
CMD ["node", "dist/server.js"]
|
||||
Generated
+1727
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "@lambdamail/auth",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"start": "node dist/server.js",
|
||||
"test": "vitest run",
|
||||
"lint": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"pg": "^8.12.0",
|
||||
"ioredis": "^5.4.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.14.0",
|
||||
"@types/pg": "^8.11.6",
|
||||
"typescript": "^5.5.4",
|
||||
"vitest": "^2.0.5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildHealthHandler } from "./health.js";
|
||||
import { createServer } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
|
||||
async function withServer(
|
||||
handler: ReturnType<typeof buildHealthHandler>,
|
||||
run: (baseUrl: string) => Promise<void>,
|
||||
) {
|
||||
const server = createServer(handler);
|
||||
await new Promise<void>((resolve) => server.listen(0, resolve));
|
||||
const { port } = server.address() as AddressInfo;
|
||||
try {
|
||||
await run(`http://127.0.0.1:${port}`);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
}
|
||||
|
||||
describe("buildHealthHandler", () => {
|
||||
it("returns 200 on /health/live regardless of dependency state", async () => {
|
||||
const handler = buildHealthHandler(
|
||||
async () => { throw new Error("db down"); },
|
||||
async () => { throw new Error("redis down"); },
|
||||
);
|
||||
await withServer(handler, async (base) => {
|
||||
const res = await fetch(`${base}/health/live`);
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
it("returns 200 on /health/ready when both dependencies respond", async () => {
|
||||
const handler = buildHealthHandler(async () => {}, async () => {});
|
||||
await withServer(handler, async (base) => {
|
||||
const res = await fetch(`${base}/health/ready`);
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
it("returns 503 on /health/ready when a dependency fails", async () => {
|
||||
const handler = buildHealthHandler(
|
||||
async () => { throw new Error("db down"); },
|
||||
async () => {},
|
||||
);
|
||||
await withServer(handler, async (base) => {
|
||||
const res = await fetch(`${base}/health/ready`);
|
||||
expect(res.status).toBe(503);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
|
||||
type PingFn = () => Promise<void>;
|
||||
|
||||
/**
|
||||
* Builds the /health/live and /health/ready handler shared by the auth and
|
||||
* storage services (PLAN.md section 11.5 and the compose healthcheck in section 13).
|
||||
*/
|
||||
export function buildHealthHandler(pingDb: PingFn, pingRedis: PingFn) {
|
||||
return async (req: IncomingMessage, res: ServerResponse) => {
|
||||
if (req.url === "/health/live") {
|
||||
res.writeHead(200).end();
|
||||
return;
|
||||
}
|
||||
if (req.url === "/health/ready") {
|
||||
try {
|
||||
await Promise.all([pingDb(), pingRedis()]);
|
||||
res.writeHead(200).end();
|
||||
} catch {
|
||||
res.writeHead(503).end();
|
||||
}
|
||||
return;
|
||||
}
|
||||
res.writeHead(404).end();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { createServer } from "node:http";
|
||||
import { Client } from "pg";
|
||||
import { Redis } from "ioredis";
|
||||
import { buildHealthHandler } from "./health.js";
|
||||
|
||||
const port = Number(process.env.PORT ?? 3001);
|
||||
|
||||
const handler = buildHealthHandler(
|
||||
async () => {
|
||||
const client = new Client({ connectionString: process.env.DATABASE_URL });
|
||||
await client.connect();
|
||||
await client.query("SELECT 1");
|
||||
await client.end();
|
||||
},
|
||||
async () => {
|
||||
const redis = new Redis(process.env.REDIS_URL ?? "");
|
||||
await redis.ping();
|
||||
redis.disconnect();
|
||||
},
|
||||
);
|
||||
|
||||
createServer(handler).listen(port, () => {
|
||||
// F0 scaffold: only health endpoints are wired. Auth use cases land in F1+.
|
||||
console.log(`auth service listening on ${port}`);
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: { environment: "node" },
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
version: 3
|
||||
workdir: .
|
||||
vendors: { golang: { in: golang } }
|
||||
excludeFiles:
|
||||
- "**/*_test.go"
|
||||
components:
|
||||
domain:
|
||||
in: internal/domain/**
|
||||
health:
|
||||
in: internal/health/**
|
||||
cmd:
|
||||
in: cmd/**
|
||||
deps:
|
||||
domain:
|
||||
canUse: [] # zero-dependency layer 1 (PLAN.md section 3)
|
||||
health:
|
||||
canUse: []
|
||||
cmd:
|
||||
canUse: [domain, health]
|
||||
@@ -0,0 +1,12 @@
|
||||
FROM golang:1.22-alpine AS build
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 go build -o /out/lambdamail-protocols ./cmd/lambdamail-protocols
|
||||
|
||||
FROM alpine:3.20
|
||||
RUN apk add --no-cache ca-certificates
|
||||
COPY --from=build /out/lambdamail-protocols /app/lambdamail-protocols
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["/app/lambdamail-protocols"]
|
||||
@@ -0,0 +1,30 @@
|
||||
// Command lambdamail-protocols is the entry point for the protocols service.
|
||||
// F0 boots only the health endpoint; SMTP/IMAP/POP3/ManageSieve listeners land in F1/F2.
|
||||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
_ "github.com/lib/pq"
|
||||
"lambdamail/protocols/internal/health"
|
||||
)
|
||||
|
||||
func main() {
|
||||
dbURL := os.Getenv("DATABASE_URL")
|
||||
db, err := sql.Open("postgres", dbURL)
|
||||
if err != nil {
|
||||
log.Fatalf("open database: %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
handler := health.Handler(func() error { return db.Ping() })
|
||||
|
||||
addr := ":8080"
|
||||
log.Printf("lambdamail-protocols listening on %s (health only - F0 scaffold)", addr)
|
||||
if err := http.ListenAndServe(addr, handler); err != nil {
|
||||
log.Fatalf("serve: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
module lambdamail/protocols
|
||||
|
||||
go 1.22
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/lib/pq v1.10.9
|
||||
)
|
||||
@@ -0,0 +1,4 @@
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// Package event contains the domain events listed in PLAN.md section 3.
|
||||
// They are persisted through the transactional outbox (section 9.4), never
|
||||
// published directly on a bus from inside a write transaction.
|
||||
package event
|
||||
|
||||
import "github.com/google/uuid"
|
||||
|
||||
// DomainEvent is implemented by every domain event.
|
||||
type DomainEvent interface {
|
||||
Type() string
|
||||
AggregateID() uuid.UUID
|
||||
}
|
||||
|
||||
type EmailReceived struct{ MessageAggregateID uuid.UUID }
|
||||
|
||||
func (e EmailReceived) Type() string { return "EmailReceived" }
|
||||
func (e EmailReceived) AggregateID() uuid.UUID { return e.MessageAggregateID }
|
||||
|
||||
type EmailAccepted struct{ MessageAggregateID uuid.UUID }
|
||||
|
||||
func (e EmailAccepted) Type() string { return "EmailAccepted" }
|
||||
func (e EmailAccepted) AggregateID() uuid.UUID { return e.MessageAggregateID }
|
||||
|
||||
type EmailDelivered struct{ JobAggregateID uuid.UUID }
|
||||
|
||||
func (e EmailDelivered) Type() string { return "EmailDelivered" }
|
||||
func (e EmailDelivered) AggregateID() uuid.UUID { return e.JobAggregateID }
|
||||
|
||||
type EmailDeferred struct{ JobAggregateID uuid.UUID }
|
||||
|
||||
func (e EmailDeferred) Type() string { return "EmailDeferred" }
|
||||
func (e EmailDeferred) AggregateID() uuid.UUID { return e.JobAggregateID }
|
||||
|
||||
type EmailBounced struct{ JobAggregateID uuid.UUID }
|
||||
|
||||
func (e EmailBounced) Type() string { return "EmailBounced" }
|
||||
func (e EmailBounced) AggregateID() uuid.UUID { return e.JobAggregateID }
|
||||
|
||||
type MailboxQuotaWarning struct{ MailboxAggregateID uuid.UUID }
|
||||
|
||||
func (e MailboxQuotaWarning) Type() string { return "MailboxQuotaWarning" }
|
||||
func (e MailboxQuotaWarning) AggregateID() uuid.UUID { return e.MailboxAggregateID }
|
||||
|
||||
type MailboxQuotaExceeded struct{ MailboxAggregateID uuid.UUID }
|
||||
|
||||
func (e MailboxQuotaExceeded) Type() string { return "MailboxQuotaExceeded" }
|
||||
func (e MailboxQuotaExceeded) AggregateID() uuid.UUID { return e.MailboxAggregateID }
|
||||
|
||||
type SpamDetected struct{ MessageAggregateID uuid.UUID }
|
||||
|
||||
func (e SpamDetected) Type() string { return "SpamDetected" }
|
||||
func (e SpamDetected) AggregateID() uuid.UUID { return e.MessageAggregateID }
|
||||
|
||||
type VirusDetected struct{ MessageAggregateID uuid.UUID }
|
||||
|
||||
func (e VirusDetected) Type() string { return "VirusDetected" }
|
||||
func (e VirusDetected) AggregateID() uuid.UUID { return e.MessageAggregateID }
|
||||
|
||||
type DkimRotationStarted struct{ DomainAggregateID uuid.UUID }
|
||||
|
||||
func (e DkimRotationStarted) Type() string { return "DkimRotationStarted" }
|
||||
func (e DkimRotationStarted) AggregateID() uuid.UUID { return e.DomainAggregateID }
|
||||
|
||||
type DkimRotationCompleted struct{ DomainAggregateID uuid.UUID }
|
||||
|
||||
func (e DkimRotationCompleted) Type() string { return "DkimRotationCompleted" }
|
||||
func (e DkimRotationCompleted) AggregateID() uuid.UUID { return e.DomainAggregateID }
|
||||
|
||||
type DnsRecordDrifted struct{ DomainAggregateID uuid.UUID }
|
||||
|
||||
func (e DnsRecordDrifted) Type() string { return "DnsRecordDrifted" }
|
||||
func (e DnsRecordDrifted) AggregateID() uuid.UUID { return e.DomainAggregateID }
|
||||
|
||||
type CertificateRotated struct{ HostAggregateID uuid.UUID }
|
||||
|
||||
func (e CertificateRotated) Type() string { return "CertificateRotated" }
|
||||
func (e CertificateRotated) AggregateID() uuid.UUID { return e.HostAggregateID }
|
||||
|
||||
type AuthenticationFailed struct{ MailboxAggregateID uuid.UUID }
|
||||
|
||||
func (e AuthenticationFailed) Type() string { return "AuthenticationFailed" }
|
||||
func (e AuthenticationFailed) AggregateID() uuid.UUID { return e.MailboxAggregateID }
|
||||
|
||||
type RateLimitTriggered struct{ SubjectAggregateID uuid.UUID }
|
||||
|
||||
func (e RateLimitTriggered) Type() string { return "RateLimitTriggered" }
|
||||
func (e RateLimitTriggered) AggregateID() uuid.UUID { return e.SubjectAggregateID }
|
||||
@@ -0,0 +1,22 @@
|
||||
package event
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestEmailReceived_ImplementsDomainEvent(t *testing.T) {
|
||||
id := uuid.New()
|
||||
e := EmailReceived{MessageAggregateID: id}
|
||||
if e.Type() != "EmailReceived" {
|
||||
t.Errorf("Type() = %q, want %q", e.Type(), "EmailReceived")
|
||||
}
|
||||
if e.AggregateID() != id {
|
||||
t.Errorf("AggregateID() = %v, want %v", e.AggregateID(), id)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmailBounced_ImplementsDomainEvent(t *testing.T) {
|
||||
var _ DomainEvent = EmailBounced{}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package valueobject
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// DeliveryStatusCode is an RFC 3463 enhanced mail status code (class.subject.detail).
|
||||
type DeliveryStatusCode struct {
|
||||
class, subject, detail int
|
||||
}
|
||||
|
||||
var ErrDeliveryStatusInvalidClass = errors.New("delivery status code: class must be 2 (success), 4 (transient) or 5 (permanent)")
|
||||
|
||||
func NewDeliveryStatusCode(class, subject, detail int) (DeliveryStatusCode, error) {
|
||||
if class != 2 && class != 4 && class != 5 {
|
||||
return DeliveryStatusCode{}, ErrDeliveryStatusInvalidClass
|
||||
}
|
||||
return DeliveryStatusCode{class: class, subject: subject, detail: detail}, nil
|
||||
}
|
||||
|
||||
func (c DeliveryStatusCode) String() string {
|
||||
return fmt.Sprintf("%d.%d.%d", c.class, c.subject, c.detail)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package valueobject
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNewDeliveryStatusCode_AcceptsSuccess(t *testing.T) {
|
||||
c, err := NewDeliveryStatusCode(2, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if c.String() != "2.0.0" {
|
||||
t.Errorf("String() = %q, want %q", c.String(), "2.0.0")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDeliveryStatusCode_AcceptsPermanentFailure(t *testing.T) {
|
||||
c, err := NewDeliveryStatusCode(5, 1, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if c.String() != "5.1.1" {
|
||||
t.Errorf("String() = %q, want %q", c.String(), "5.1.1")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDeliveryStatusCode_RejectsInvalidClass(t *testing.T) {
|
||||
if _, err := NewDeliveryStatusCode(3, 0, 0); err == nil {
|
||||
t.Fatal("expected error: RFC 3463 only defines classes 2, 4 and 5, got nil")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package valueobject
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// DomainName is an RFC 1035 fully-qualified domain name, normalized to lowercase.
|
||||
type DomainName struct {
|
||||
value string
|
||||
}
|
||||
|
||||
var (
|
||||
ErrDomainNameEmpty = errors.New("domain name: must not be empty")
|
||||
ErrDomainNameNotFQDN = errors.New("domain name: must contain at least one dot (not a FQDN)")
|
||||
ErrDomainNameInvalidLabel = errors.New("domain name: label must not start or end with a hyphen")
|
||||
)
|
||||
|
||||
// NewDomainName validates and normalizes raw into a DomainName.
|
||||
func NewDomainName(raw string) (DomainName, error) {
|
||||
if raw == "" {
|
||||
return DomainName{}, ErrDomainNameEmpty
|
||||
}
|
||||
lower := strings.ToLower(raw)
|
||||
labels := strings.Split(lower, ".")
|
||||
if len(labels) < 2 {
|
||||
return DomainName{}, ErrDomainNameNotFQDN
|
||||
}
|
||||
for _, label := range labels {
|
||||
if label == "" || strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") {
|
||||
return DomainName{}, ErrDomainNameInvalidLabel
|
||||
}
|
||||
}
|
||||
return DomainName{value: lower}, nil
|
||||
}
|
||||
|
||||
func (d DomainName) String() string { return d.value }
|
||||
|
||||
// IsPunycode reports whether the domain name is IDNA/punycode-encoded.
|
||||
// It returns true if any label of the domain starts with the ASCII Compatible Encoding prefix "xn--".
|
||||
func (d DomainName) IsPunycode() bool {
|
||||
labels := strings.Split(d.value, ".")
|
||||
for _, label := range labels {
|
||||
if strings.HasPrefix(label, "xn--") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package valueobject
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNewDomainName_AcceptsValidFQDN(t *testing.T) {
|
||||
d, err := NewDomainName("Example.COM")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if d.String() != "example.com" {
|
||||
t.Errorf("String() = %q, want lowercased %q", d.String(), "example.com")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDomainName_RejectsEmpty(t *testing.T) {
|
||||
if _, err := NewDomainName(""); err == nil {
|
||||
t.Fatal("expected error for empty domain name, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDomainName_RejectsLabelWithoutDot(t *testing.T) {
|
||||
if _, err := NewDomainName("localhost"); err == nil {
|
||||
t.Fatal("expected error for single-label name (not a FQDN), got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDomainName_RejectsTrailingHyphenLabel(t *testing.T) {
|
||||
if _, err := NewDomainName("bad-.example.com"); err == nil {
|
||||
t.Fatal("expected error for label ending in hyphen, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDomainName_IsPunycode_WithPunycodeLabel(t *testing.T) {
|
||||
d, err := NewDomainName("xn--exmple-cua.com")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !d.IsPunycode() {
|
||||
t.Error("IsPunycode() = false, want true for punycode domain")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDomainName_IsPunycode_WithoutPunycodeLabel(t *testing.T) {
|
||||
d, err := NewDomainName("example.com")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if d.IsPunycode() {
|
||||
t.Error("IsPunycode() = true, want false for plain ASCII domain")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Package valueobject contains the domain's immutable, self-validating value objects.
|
||||
// Zero external imports: this is layer 1 of Clean Architecture (see PLAN.md section 3).
|
||||
package valueobject
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// EmailAddress is an RFC 5322 mailbox address, normalized with a lowercased domain.
|
||||
type EmailAddress struct {
|
||||
localPart string
|
||||
domain string
|
||||
}
|
||||
|
||||
var (
|
||||
ErrEmailMissingAtSign = errors.New("email address: missing '@' separator")
|
||||
ErrEmailEmptyLocalPart = errors.New("email address: local part must not be empty")
|
||||
ErrEmailEmptyDomain = errors.New("email address: domain must not be empty")
|
||||
ErrEmailLocalPartTooLong = errors.New("email address: local part exceeds 64 octets (RFC 5321 4.5.3.1.1)")
|
||||
)
|
||||
|
||||
// NewEmailAddress validates and normalizes raw into an EmailAddress.
|
||||
func NewEmailAddress(raw string) (EmailAddress, error) {
|
||||
at := strings.LastIndex(raw, "@")
|
||||
if at < 0 {
|
||||
return EmailAddress{}, ErrEmailMissingAtSign
|
||||
}
|
||||
local, domain := raw[:at], raw[at+1:]
|
||||
if local == "" {
|
||||
return EmailAddress{}, ErrEmailEmptyLocalPart
|
||||
}
|
||||
if len(local) > 64 {
|
||||
return EmailAddress{}, ErrEmailLocalPartTooLong
|
||||
}
|
||||
if domain == "" {
|
||||
return EmailAddress{}, ErrEmailEmptyDomain
|
||||
}
|
||||
return EmailAddress{localPart: local, domain: strings.ToLower(domain)}, nil
|
||||
}
|
||||
|
||||
func (e EmailAddress) LocalPart() string { return e.localPart }
|
||||
func (e EmailAddress) Domain() string { return e.domain }
|
||||
func (e EmailAddress) String() string { return e.localPart + "@" + e.domain }
|
||||
@@ -0,0 +1,47 @@
|
||||
package valueobject
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNewEmailAddress_AcceptsValidAddress(t *testing.T) {
|
||||
addr, err := NewEmailAddress("User.Name+tag@Example.com")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if addr.LocalPart() != "User.Name+tag" {
|
||||
t.Errorf("local part = %q, want %q", addr.LocalPart(), "User.Name+tag")
|
||||
}
|
||||
if addr.Domain() != "example.com" {
|
||||
t.Errorf("domain = %q, want lowercased %q", addr.Domain(), "example.com")
|
||||
}
|
||||
if addr.String() != "User.Name+tag@example.com" {
|
||||
t.Errorf("String() = %q, want %q", addr.String(), "User.Name+tag@example.com")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewEmailAddress_RejectsMissingAtSign(t *testing.T) {
|
||||
if _, err := NewEmailAddress("not-an-email"); err == nil {
|
||||
t.Fatal("expected error for address without '@', got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewEmailAddress_RejectsEmptyLocalPart(t *testing.T) {
|
||||
if _, err := NewEmailAddress("@example.com"); err == nil {
|
||||
t.Fatal("expected error for empty local part, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewEmailAddress_RejectsEmptyDomain(t *testing.T) {
|
||||
if _, err := NewEmailAddress("user@"); err == nil {
|
||||
t.Fatal("expected error for empty domain, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewEmailAddress_RejectsOverlongLocalPart(t *testing.T) {
|
||||
longLocal := ""
|
||||
for i := 0; i < 65; i++ {
|
||||
longLocal += "a"
|
||||
}
|
||||
if _, err := NewEmailAddress(longLocal + "@example.com"); err == nil {
|
||||
t.Fatal("expected error for local part over 64 octets (RFC 5321 4.5.3.1.1), got nil")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package valueobject
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// MessageID is an RFC 5322 Message-ID, always wrapped in angle brackets.
|
||||
type MessageID struct {
|
||||
raw string
|
||||
}
|
||||
|
||||
var (
|
||||
ErrMessageIDEmpty = errors.New("message id: must not be empty")
|
||||
ErrMessageIDNotBracketed = errors.New("message id: must be wrapped in angle brackets")
|
||||
)
|
||||
|
||||
func NewMessageID(raw string) (MessageID, error) {
|
||||
if raw == "" {
|
||||
return MessageID{}, ErrMessageIDEmpty
|
||||
}
|
||||
if !strings.HasPrefix(raw, "<") || !strings.HasSuffix(raw, ">") {
|
||||
return MessageID{}, ErrMessageIDNotBracketed
|
||||
}
|
||||
return MessageID{raw: raw}, nil
|
||||
}
|
||||
|
||||
func (m MessageID) String() string { return m.raw }
|
||||
@@ -0,0 +1,25 @@
|
||||
package valueobject
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNewMessageID_AcceptsAngleBracketForm(t *testing.T) {
|
||||
id, err := NewMessageID("<abc123@mail.example.com>")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if id.String() != "<abc123@mail.example.com>" {
|
||||
t.Errorf("String() = %q, want input preserved", id.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewMessageID_RejectsEmpty(t *testing.T) {
|
||||
if _, err := NewMessageID(""); err == nil {
|
||||
t.Fatal("expected error for empty Message-ID, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewMessageID_RejectsMissingAngleBrackets(t *testing.T) {
|
||||
if _, err := NewMessageID("abc123@mail.example.com"); err == nil {
|
||||
t.Fatal("expected error for Message-ID without angle brackets, got nil")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package valueobject
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// PasswordHash wraps an Argon2id PHC-format hash string (see PLAN.md section 9, mailboxes.password_hash).
|
||||
type PasswordHash struct {
|
||||
phc string
|
||||
}
|
||||
|
||||
var (
|
||||
ErrPasswordHashEmpty = errors.New("password hash: must not be empty")
|
||||
ErrPasswordHashWrongScheme = errors.New("password hash: only argon2id PHC strings are accepted")
|
||||
)
|
||||
|
||||
// NewPasswordHash validates that phc is a well-formed argon2id PHC string.
|
||||
func NewPasswordHash(phc string) (PasswordHash, error) {
|
||||
if phc == "" {
|
||||
return PasswordHash{}, ErrPasswordHashEmpty
|
||||
}
|
||||
if !strings.HasPrefix(phc, "$argon2id$") {
|
||||
return PasswordHash{}, ErrPasswordHashWrongScheme
|
||||
}
|
||||
return PasswordHash{phc: phc}, nil
|
||||
}
|
||||
|
||||
func (p PasswordHash) String() string { return p.phc }
|
||||
@@ -0,0 +1,26 @@
|
||||
package valueobject
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNewPasswordHash_AcceptsArgon2idPHCString(t *testing.T) {
|
||||
phc := "$argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHQ$RdescudvJCsgt3ub+b+dWRWJTmaaJObG"
|
||||
h, err := NewPasswordHash(phc)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if h.String() != phc {
|
||||
t.Errorf("String() = %q, want %q", h.String(), phc)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewPasswordHash_RejectsNonArgon2idScheme(t *testing.T) {
|
||||
if _, err := NewPasswordHash("$bcrypt$10$abcdefg"); err == nil {
|
||||
t.Fatal("expected error for non-argon2id scheme, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewPasswordHash_RejectsEmpty(t *testing.T) {
|
||||
if _, err := NewPasswordHash(""); err == nil {
|
||||
t.Fatal("expected error for empty hash, got nil")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package valueobject
|
||||
|
||||
// ProtocolSecurityLevel is the effective TLS requirement for a listener (see PLAN.md section 4).
|
||||
type ProtocolSecurityLevel int
|
||||
|
||||
const (
|
||||
SecurityOpportunistic ProtocolSecurityLevel = iota // STARTTLS offered, plaintext fallback allowed (port 25 only)
|
||||
SecurityRequired // STARTTLS mandatory before AUTH (587/143/110/4190)
|
||||
SecurityImplicit // TLS from the first byte (465/993/995)
|
||||
)
|
||||
|
||||
func (l ProtocolSecurityLevel) String() string {
|
||||
switch l {
|
||||
case SecurityRequired:
|
||||
return "required"
|
||||
case SecurityImplicit:
|
||||
return "implicit"
|
||||
default:
|
||||
return "opportunistic"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package valueobject
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestProtocolSecurityLevel_StringRoundTrip(t *testing.T) {
|
||||
cases := []struct {
|
||||
level ProtocolSecurityLevel
|
||||
want string
|
||||
}{
|
||||
{SecurityOpportunistic, "opportunistic"},
|
||||
{SecurityRequired, "required"},
|
||||
{SecurityImplicit, "implicit"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := c.level.String(); got != c.want {
|
||||
t.Errorf("String() = %q, want %q", got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package valueobject
|
||||
|
||||
import "errors"
|
||||
|
||||
// QuotaLimit is a strictly positive byte quota (see PLAN.md section 3, Mailbox invariant).
|
||||
type QuotaLimit struct {
|
||||
bytes int64
|
||||
}
|
||||
|
||||
var ErrQuotaLimitNotPositive = errors.New("quota limit: must be a positive number of bytes")
|
||||
|
||||
func NewQuotaLimit(bytes int64) (QuotaLimit, error) {
|
||||
if bytes <= 0 {
|
||||
return QuotaLimit{}, ErrQuotaLimitNotPositive
|
||||
}
|
||||
return QuotaLimit{bytes: bytes}, nil
|
||||
}
|
||||
|
||||
func (q QuotaLimit) Bytes() int64 { return q.bytes }
|
||||
|
||||
// Exceeds reports whether usedBytes violates the "used_bytes <= quota_bytes" invariant.
|
||||
func (q QuotaLimit) Exceeds(usedBytes int64) bool { return usedBytes > q.bytes }
|
||||
@@ -0,0 +1,35 @@
|
||||
package valueobject
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNewQuotaLimit_AcceptsPositiveBytes(t *testing.T) {
|
||||
q, err := NewQuotaLimit(1073741824)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if q.Bytes() != 1073741824 {
|
||||
t.Errorf("Bytes() = %d, want %d", q.Bytes(), 1073741824)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewQuotaLimit_RejectsZero(t *testing.T) {
|
||||
if _, err := NewQuotaLimit(0); err == nil {
|
||||
t.Fatal("expected error for zero quota, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewQuotaLimit_RejectsNegative(t *testing.T) {
|
||||
if _, err := NewQuotaLimit(-1); err == nil {
|
||||
t.Fatal("expected error for negative quota, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaLimit_Exceeds(t *testing.T) {
|
||||
q, _ := NewQuotaLimit(1000)
|
||||
if !q.Exceeds(1001) {
|
||||
t.Error("Exceeds(1001) = false, want true for a 1000-byte quota")
|
||||
}
|
||||
if q.Exceeds(1000) {
|
||||
t.Error("Exceeds(1000) = true, want false: used_bytes <= quota_bytes is the invariant (PLAN.md section 3)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package valueobject
|
||||
|
||||
// SpamVerdict classifies a message by Rspamd score (thresholds from PLAN.md section 10.1).
|
||||
type SpamVerdict int
|
||||
|
||||
const (
|
||||
SpamHam SpamVerdict = iota
|
||||
SpamProbable
|
||||
SpamReject
|
||||
)
|
||||
|
||||
// SpamVerdictFromScore maps a Rspamd score to a verdict per the thresholds table in section 10.1.
|
||||
func SpamVerdictFromScore(score float64) SpamVerdict {
|
||||
switch {
|
||||
case score >= 9:
|
||||
return SpamReject
|
||||
case score >= 4:
|
||||
return SpamProbable
|
||||
default:
|
||||
return SpamHam
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package valueobject
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestSpamVerdictFromScore_MatchesThresholds(t *testing.T) {
|
||||
// Thresholds from PLAN.md section 10.1.
|
||||
cases := []struct {
|
||||
score float64
|
||||
want SpamVerdict
|
||||
}{
|
||||
{0, SpamHam},
|
||||
{3.9, SpamHam},
|
||||
{4, SpamProbable},
|
||||
{8.9, SpamProbable},
|
||||
{9, SpamReject}, // section 10.1: 9-15 greylists/defers, modeled here as reject-eligible
|
||||
{15.1, SpamReject},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := SpamVerdictFromScore(c.score); got != c.want {
|
||||
t.Errorf("SpamVerdictFromScore(%v) = %v, want %v", c.score, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package valueobject
|
||||
|
||||
import "errors"
|
||||
|
||||
// TLSARecord models a DANE TLSA RR (RFC 6698/7671). Usage 2 (PKIX-CA) is rejected
|
||||
// by explicit ADR - see PLAN.md section 5.1: Let's Encrypt rotates intermediates
|
||||
// without notice, making it unpredictable. Only usage 3 (DANE-EE) is supported.
|
||||
type TLSARecord struct {
|
||||
usage uint8
|
||||
selector uint8
|
||||
matchingType uint8
|
||||
data string
|
||||
}
|
||||
|
||||
var (
|
||||
ErrTLSAUsageUnsupported = errors.New("tlsa record: only usage 3 (DANE-EE) is supported")
|
||||
ErrTLSADataWrongLength = errors.New("tlsa record: matching type 1 (SHA-256) requires a 64-hex-char digest")
|
||||
)
|
||||
|
||||
func NewTLSARecord(usage, selector, matchingType uint8, data string) (TLSARecord, error) {
|
||||
if usage != 3 {
|
||||
return TLSARecord{}, ErrTLSAUsageUnsupported
|
||||
}
|
||||
if matchingType == 1 && len(data) != 64 {
|
||||
return TLSARecord{}, ErrTLSADataWrongLength
|
||||
}
|
||||
return TLSARecord{usage: usage, selector: selector, matchingType: matchingType, data: data}, nil
|
||||
}
|
||||
|
||||
func (r TLSARecord) Usage() uint8 { return r.usage }
|
||||
func (r TLSARecord) Selector() uint8 { return r.selector }
|
||||
func (r TLSARecord) MatchingType() uint8 { return r.matchingType }
|
||||
func (r TLSARecord) Data() string { return r.data }
|
||||
@@ -0,0 +1,29 @@
|
||||
package valueobject
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNewTLSARecord_AcceptsUsage3Selector1MatchingType1(t *testing.T) {
|
||||
hash := "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
|
||||
r, err := NewTLSARecord(3, 1, 1, hash)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if r.Usage() != 3 || r.Selector() != 1 || r.MatchingType() != 1 {
|
||||
t.Errorf("fields not preserved: got usage=%d selector=%d matchingType=%d", r.Usage(), r.Selector(), r.MatchingType())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewTLSARecord_RejectsUsage2(t *testing.T) {
|
||||
// DANE_TLSA_USAGE=2 was explicitly rejected by ADR (PLAN.md section 5.1):
|
||||
// Let's Encrypt rotates intermediates without notice, making usage 2 unpredictable.
|
||||
hash := "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
|
||||
if _, err := NewTLSARecord(2, 1, 1, hash); err == nil {
|
||||
t.Fatal("expected error for usage=2 (PKIX-CA), got nil - rejected by ADR in PLAN.md section 5.1")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewTLSARecord_RejectsWrongLengthHash(t *testing.T) {
|
||||
if _, err := NewTLSARecord(3, 1, 1, "tooshort"); err == nil {
|
||||
t.Fatal("expected error for a SHA-256 hash that isn't 64 hex chars, got nil")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Package health exposes liveness/readiness endpoints (PLAN.md section 11.5).
|
||||
package health
|
||||
|
||||
import "net/http"
|
||||
|
||||
// PingerFunc reports whether a dependency (e.g. Postgres) is reachable.
|
||||
type PingerFunc func() error
|
||||
|
||||
// Handler serves /health/live (process up) and /health/ready (dependencies reachable).
|
||||
func Handler(ping PingerFunc) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/health/live", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
mux.HandleFunc("/health/ready", func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := ping(); err != nil {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
return mux
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package health
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHandler_Live_AlwaysReturns200(t *testing.T) {
|
||||
h := Handler(func() error { return errors.New("db down") })
|
||||
req := httptest.NewRequest(http.MethodGet, "/health/live", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("GET /health/live status = %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandler_Ready_Returns200WhenPingSucceeds(t *testing.T) {
|
||||
h := Handler(func() error { return nil })
|
||||
req := httptest.NewRequest(http.MethodGet, "/health/ready", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("GET /health/ready status = %d, want %d", rec.Code, http.StatusOK)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandler_Ready_Returns503WhenPingFails(t *testing.T) {
|
||||
h := Handler(func() error { return errors.New("db down") })
|
||||
req := httptest.NewRequest(http.MethodGet, "/health/ready", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusServiceUnavailable {
|
||||
t.Errorf("GET /health/ready status = %d, want %d", rec.Code, http.StatusServiceUnavailable)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
FROM node:20-alpine AS build
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json* ./
|
||||
RUN npm install
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-alpine
|
||||
WORKDIR /app
|
||||
COPY --from=build /app/node_modules ./node_modules
|
||||
COPY --from=build /app/dist ./dist
|
||||
COPY package.json ./
|
||||
EXPOSE 3002
|
||||
CMD ["node", "dist/server.js"]
|
||||
Generated
+1727
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "@lambdamail/storage",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"start": "node dist/server.js",
|
||||
"test": "vitest run",
|
||||
"lint": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"pg": "^8.12.0",
|
||||
"ioredis": "^5.4.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.14.0",
|
||||
"@types/pg": "^8.11.6",
|
||||
"typescript": "^5.5.4",
|
||||
"vitest": "^2.0.5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildHealthHandler } from "./health.js";
|
||||
import { createServer } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
|
||||
async function withServer(
|
||||
handler: ReturnType<typeof buildHealthHandler>,
|
||||
run: (baseUrl: string) => Promise<void>,
|
||||
) {
|
||||
const server = createServer(handler);
|
||||
await new Promise<void>((resolve) => server.listen(0, resolve));
|
||||
const { port } = server.address() as AddressInfo;
|
||||
try {
|
||||
await run(`http://127.0.0.1:${port}`);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
}
|
||||
|
||||
describe("buildHealthHandler", () => {
|
||||
it("returns 200 on /health/live regardless of dependency state", async () => {
|
||||
const handler = buildHealthHandler(
|
||||
async () => { throw new Error("db down"); },
|
||||
async () => { throw new Error("redis down"); },
|
||||
);
|
||||
await withServer(handler, async (base) => {
|
||||
const res = await fetch(`${base}/health/live`);
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
it("returns 200 on /health/ready when both dependencies respond", async () => {
|
||||
const handler = buildHealthHandler(async () => {}, async () => {});
|
||||
await withServer(handler, async (base) => {
|
||||
const res = await fetch(`${base}/health/ready`);
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
it("returns 503 on /health/ready when a dependency fails", async () => {
|
||||
const handler = buildHealthHandler(
|
||||
async () => { throw new Error("db down"); },
|
||||
async () => {},
|
||||
);
|
||||
await withServer(handler, async (base) => {
|
||||
const res = await fetch(`${base}/health/ready`);
|
||||
expect(res.status).toBe(503);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
|
||||
type PingFn = () => Promise<void>;
|
||||
|
||||
/**
|
||||
* Builds the /health/live and /health/ready handler shared by the auth and
|
||||
* storage services (PLAN.md section 11.5 and the compose healthcheck in section 13).
|
||||
*/
|
||||
export function buildHealthHandler(pingDb: PingFn, pingRedis: PingFn) {
|
||||
return async (req: IncomingMessage, res: ServerResponse) => {
|
||||
if (req.url === "/health/live") {
|
||||
res.writeHead(200).end();
|
||||
return;
|
||||
}
|
||||
if (req.url === "/health/ready") {
|
||||
try {
|
||||
await Promise.all([pingDb(), pingRedis()]);
|
||||
res.writeHead(200).end();
|
||||
} catch {
|
||||
res.writeHead(503).end();
|
||||
}
|
||||
return;
|
||||
}
|
||||
res.writeHead(404).end();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { createServer } from "node:http";
|
||||
import { Client } from "pg";
|
||||
import { Redis } from "ioredis";
|
||||
import { buildHealthHandler } from "./health.js";
|
||||
|
||||
const port = Number(process.env.PORT ?? 3002);
|
||||
|
||||
const handler = buildHealthHandler(
|
||||
async () => {
|
||||
const client = new Client({ connectionString: process.env.DATABASE_URL });
|
||||
await client.connect();
|
||||
await client.query("SELECT 1");
|
||||
await client.end();
|
||||
},
|
||||
async () => {
|
||||
const redis = new Redis(process.env.REDIS_URL ?? "");
|
||||
await redis.ping();
|
||||
redis.disconnect();
|
||||
},
|
||||
);
|
||||
|
||||
createServer(handler).listen(port, () => {
|
||||
// F0 scaffold: only health endpoints are wired. Storage use cases land in F1+.
|
||||
console.log(`storage service listening on ${port}`);
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: { environment: "node" },
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
FROM node:20-alpine AS build
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json* ./
|
||||
RUN npm install
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM node:20-alpine
|
||||
WORKDIR /app
|
||||
COPY --from=build /app/.next/standalone ./
|
||||
COPY --from=build /app/.next/static ./.next/static
|
||||
COPY --from=build /app/public ./public
|
||||
EXPOSE 3000
|
||||
CMD ["node", "server.js"]
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
/// <reference path="./.next/types/routes.d.ts" />
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
output: "standalone",
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
Generated
+1085
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "@lambdamail/webmail",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start -p 3000"
|
||||
},
|
||||
"dependencies": {
|
||||
"next": "15.5.21",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.5.4",
|
||||
"@types/node": "^20.14.0",
|
||||
"@types/react": "^18.3.3"
|
||||
},
|
||||
"overrides": {
|
||||
"sharp": "^0.35.0"
|
||||
}
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,3 @@
|
||||
export function GET() {
|
||||
return new Response(null, { status: 200 });
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export default function HomePage() {
|
||||
return (
|
||||
<main>
|
||||
<h1>LambdaMail</h1>
|
||||
<p>Webmail and admin console land in F4. This is the F0 boot scaffold.</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"jsx": "preserve",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"allowJs": true,
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true
|
||||
},
|
||||
"include": [
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
"next-env.d.ts",
|
||||
".next/types/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user