API ReferenceREST /api/v1Sign in

Multi-Cloud Hosting Management Platform — Build Specification

Multi-Cloud Hosting Management Platform — Build Specification

Version: 2.0 (supersedes SRS 1.0) Type: Executable build spec for an AI coding agent Status: Normative. Every "MUST" is a test case.

0. How to use this document

This is not an SRS. An SRS describes what a system should do; this describes what to type. The source SRS 1.0 was a good scope document and a poor build document, because almost every technically interesting decision in it was deferred with the words may, should, possible, or recommended. An AI coding agent handed that document will invent those decisions inconsistently across sessions and produce a codebase that does not compose.

Rules for the implementing agent:

Nothing in §2 (Locked Decisions) is negotiable. Do not substitute libraries, rename tables, or "improve" the folder layout. Consistency across sessions is worth more than any local optimum. Build in the order given in §24. Each milestone has a Definition of Done that is a runnable command. Do not start milestone N+1 until milestone N's command passes. Where this document says MUST, write a test. Where it says SHOULD, use judgement. Where it says LATER, write nothing — not a stub, not an interface, not a TODO. Any provider-specific or panel-specific string outside packages/adapters-* is a bug. This is the single most important architectural constraint in the system. See §7. Every infrastructure mutation goes through a job with an idempotency key. No controller ever calls AWS, OVH, or HestiaCP synchronously. See §11. When this document and the original SRS disagree, this document wins. §1 explains why. 1. Analysis of SRS 1.0 — what was wrong, and what is now decided

The following is the diff in reasoning, not just in text. Read it; it explains the shape of everything below.

1.1 Contradictions in the source # Contradiction Resolution in this spec C1 §6 demands hard tenant isolation ("one customer must never access another's files") while §9 sells shared hosting, where all tenants share a kernel, a MySQL instance, and a PHP-FPM pool. Isolation is redefined as a tiered guarantee (§5.1). Shared tier gets OS-user + open_basedir + per-user FPM pools and is documented to the customer as shared. Isolated tier gets a dedicated VM. Selling "isolation" on a shared box is a liability, not a feature. C2 §67 targets 99.9% for the control plane and also says customer sites must survive control-plane failure. Under §18, provisioning, SSL renewal and backups all originate in the control plane — so control-plane downtime does degrade customer service. Split explicitly into data plane (servers keep serving; no dependency on control plane) and control plane (99.5% target, degrades gracefully). SSL renewal and backups are made server-resident cron with control-plane reconciliation (§13.4, §14.3), so a 6-hour control-plane outage cannot expire a certificate. C3 §34 suspends hosting for non-payment but §67 says the platform must not affect customer sites. Suspension is an intentional data-plane mutation, not an availability event. Called out as such; suspension is executed by a job that must be idempotent and reversible within the retention window (§20.4). C4 §44 Cost Optimization Engine recommends migrating customers from AWS to OVH to save money, while §14 says some customers are on AWS for compliance or contractual reasons. Naive cost optimisation would recommend illegal migrations. The placement engine gets hard constraints (never violated) separated from soft scores (optimised). Cost is only ever a soft score. See §9. C5 §75 says the customer must not know the provider; §20 requires customer-managed DNS and §37 gives customers backup and database access — all of which leak the server hostname and IP. Provider opacity is redefined as product opacity: the customer's plan never names a provider, and the platform must be able to migrate them without a product change. The customer still sees an IP and a panel hostname. Guarantee is now testable (§5.3). C6 §29–33 bill in NZD/AUD/USD, but §39 sums provider costs (billed in USD/EUR) into a single NZD figure with no stated FX policy. Margin numbers would be silently wrong. Money model is fully specified in §16.1: integer minor units, currency on every amount, explicit FX rate table with rate_date, and a rule that costs are converted at accrual date, not report date. C7 §13 forbids provisioning onto a server above threshold; §43 auto-balancing moves accounts to servers. Nothing defines what happens when every server in a pool is above threshold and autoscaling is off. Explicit terminal state: placement returns NO_CAPACITY, the order goes to awaiting_capacity, an alert fires, and the customer is not billed until active (§20.2, and §52 of the source is upgraded to a hard rule). 1.2 Gaps — required by the business, absent from the source

These are the things that will bite this project in month four. Each now has a section.

Email hosting. §9 lists "email accounts if supported" as a plan attribute and §21 requires MX/SPF/DKIM/DMARC records — but there is no mailbox management, no quota, no deliverability, no IP-reputation, no abuse handling. Shared hosting without a decided email answer is a trap. Decision: email is out of scope for v1 (§19.1). Plans sell DNS records pointing at an external provider. Revisit at Phase 3 with a dedicated mail-cluster design, never on the web nodes. Abuse, malware and the noisy-neighbour problem. The single largest operational cost in shared hosting is a compromised WordPress install sending spam or eating a whole CPU. The source has no scanning, no resource fencing, no abuse workflow. See §19.2 — this is a v1 requirement, not a nicety. Tax. NZ GST is 15% and invoices have legal content requirements; AU has GST + ABN validation; US sales tax on SaaS varies by state. §31 has a Tax field and no rules. See §16.5. PCI scope. §32 says "Stripe" but not how. If card data touches the app the business inherits PCI-DSS SAQ-D. Decision: Stripe Elements + PaymentIntents only, SAQ-A. No PAN ever reaches the platform (§16.6). Domain registrar. §20 tracks domain expiry dates and §61 sends "Domain Expiring" notices, but no registrar integration exists to read those dates or renew. v1 reads expiry via RDAP and never registers domains (§13.5). Data residency and the NZ Privacy Act 2020. §14 mentions compliance abstractly. IPPs 11/12 govern offshore disclosure. Concrete requirement in §22.4. Backup restore testing. §24–26 create and restore backups; nothing verifies a backup is restorable. An untested backup is not a backup. §14.5 makes monthly restore drills a scheduled job with a pass/fail record. Termination and data deletion. §35 deletes accounts; nothing covers the deletion of backups, PII, logs, or the customer's right to an export. §20.5. Reseller nesting. §7.5 introduces resellers whose customers are also tenants — a second tenancy dimension that changes every query in the system. Deferred to Phase 2, but the schema in §4 carries reseller_id from day one so it is not a rewrite. Rate limits and quota on the provider APIs. AWS and OVH both throttle. A provisioning burst will hit 429s. §7.4 mandates a per-provider-account token bucket. Clock, DNS TTL and migration cutover. §42 lists "switch DNS" as one box in a flow. In practice this is the only step that can lose customer data (writes to the old node after cutover). §18 specifies the TTL lowering schedule and the read-only freeze window. Observability of the platform itself. §27 monitors customer servers. Nothing monitors the queue depth, job failure rate, or webhook lag of the platform. §21.4. 1.3 Things the source over-specified and should not build in v1

Scope discipline matters more than feature count. Cut from v1, with reasons:

Auto-balancing (§43) — needs a year of production telemetry to tune. Building it early produces a system that shuffles customers for no reason. Cost Optimization Engine (§44) — a report, not an engine. v1 ships the report. Provider failover (§45) — cross-provider DR for shared hosting is a multi-quarter project and is not what a NZ$199/yr customer is buying. Phase 3. Six notification channels (§28) — v1 ships email + one webhook (Slack-compatible). SMS and WhatsApp add compliance and cost for marginal value. Both HestiaCP and Virtualmin (§5) — v1 ships HestiaCP only. The adapter interface (§8) is what proves the abstraction, not a second implementation nobody uses. 2. Locked decisions

Do not revisit these.

2.1 Stack Concern Decision Notes Runtime Node.js 22 LTS, TypeScript 5.6, strict: true noUncheckedIndexedAccess on API framework NestJS 10 Module-per-bounded-context Database PostgreSQL 16 One database, schema-per-concern not used; plain public ORM Prisma 5 Migrations are the only DDL path Queue BullMQ 5 on Redis 7 Separate Redis DB from cache Cache / locks Redis 7 (ioredis) Redlock for distributed locks Frontend Next.js 15 App Router, React 19 Two apps: admin, portal UI kit Tailwind 4 + shadcn/ui + TanStack Table/Query No other component library Auth Better-auth (sessions) + TOTP MFA Not NextAuth; needs org/tenant model API auth (machine) OAuth2 client-credentials + scoped PATs JWT RS256, 15-min access, refresh rotation Validation Zod at every boundary Shared schemas in packages/contracts Payments Stripe (PaymentIntents + Billing for cards), manual bank transfer Stripe is not the source of truth for subscriptions; see §16.2 Object storage S3 API (AWS S3 + OVH Object Storage, same client) @aws-sdk/client-s3 against both Secrets AWS Secrets Manager (prod), .env + SOPS (dev) §22.2 Server config mgmt Ansible, invoked from a worker via ansible-runner Not shell-over-SSH ad hoc Metrics ingest Prometheus node_exporter on each hosting node, scraped by the platform's Prometheus; platform reads via PromQL Not custom agents Platform observability OpenTelemetry → Grafana/Tempo/Loki §21.4 Tests Vitest (unit), Testcontainers (integration), Playwright (e2e) Monorepo pnpm workspaces + Turborepo 2.2 Repository layout hosting-platform/ ├── apps/ │ ├── api/ NestJS HTTP API (no queue processing) │ ├── worker/ BullMQ processors (no HTTP except /health) │ ├── scheduler/ Cron producers only; enqueues, never executes │ ├── admin/ Next.js admin portal │ └── portal/ Next.js customer portal ├── packages/ │ ├── contracts/ Zod schemas + generated OpenAPI + TS types │ ├── db/ Prisma schema, migrations, seed, repositories │ ├── domain/ Pure business logic. No I/O. Heavily unit-tested. │ │ ├── placement/ Provider/server selection engine (§9) │ │ ├── billing/ Proration, dunning, tax, FX (§16) │ │ ├── costing/ Allocation + margin math (§17) │ │ └── state/ State machines (§10) │ ├── adapters-cloud/ CloudProvider implementations (§7) │ │ ├── core/ Interface, errors, retry, rate limiting │ │ ├── aws/ │ │ └── ovh/ │ ├── adapters-panel/ HostingPanel implementations (§8) │ │ ├── core/ │ │ └── hestia/ │ ├── adapters-dns/ DNS providers (Cloudflare v1) │ ├── adapters-storage/ S3-compatible backup targets │ ├── adapters-payment/ Stripe + manual │ ├── jobs/ Job name constants, payload schemas, saga defs │ └── ui/ Shared React components + design tokens ├── infra/ │ ├── ansible/ Node build playbooks (§12.3) │ ├── terraform/ Platform's OWN infrastructure only │ └── docker/ └── docs/

Rule: packages/domain MUST NOT import from packages/db, any adapter, or any Node built-in that performs I/O. It takes plain data in and returns plain data out. This is what makes the placement engine and billing math testable without a database, and it is the difference between a project that can be safely modified in month nine and one that cannot.

2.3 Naming and conventions Tables: snake_case, plural. Columns: snake_case. Prisma models: PascalCase singular. Primary keys: id uuid PRIMARY KEY DEFAULT gen_random_uuid(). No auto-increment, ever — IDs appear in URLs and cross provider boundaries. Every business table has a human-facing short code as well: HST-000123, INV-2026-0042. Sequence-backed, never reused. Support staff read these aloud on the phone. Timestamps: timestamptz, always UTC. Column names created_at, updated_at, deleted_at. Business dates that are dates (invoice date, service period) are date in the customer's timezone, resolved at write time. Money: amount_minor bigint + currency char(3). Never a float. Never a bare amount. Lint rule enforced. Enums live in Postgres as native enums and are mirrored in packages/contracts. Soft delete only where legally needed (invoices, audit). Everything else hard-deletes with ON DELETE RESTRICT and an explicit archival path. API: REST, /api/v1, plural nouns, cursor pagination (?cursor=&limit=), application/problem+json for errors (RFC 9457). 3. Bounded contexts

Nine modules. Cross-module communication is via domain events on an outbox (§11.6), never by reaching into another module's tables.

Context Owns Key invariant Identity users, roles, permissions, sessions, MFA, API tokens Every request resolves to exactly one actor + one tenant_scope CRM customers, contacts, addresses, resellers A customer belongs to exactly one owner org (platform or reseller) Catalog hosting_plans, plan_limits, plan_prices, server_pools binding A plan's limits are immutable once a subscription references it; changes create a new plan version Subscriptions subscriptions, subscription_items, lifecycle A subscription is never active without a provisioned hosting_account Billing invoices, invoice_items, payments, credits, refunds, tax, fx An issued invoice is immutable; corrections are credit notes Infrastructure providers, provider_accounts, regions, server_types, servers, server_pools, capacity A server's recorded state is reconciled from the provider, never assumed Hosting hosting_accounts, websites, domains, dns_records, databases, ftp_users, ssl_certificates A hosting_account exists on exactly one server at a time Data Protection backup_policies, backups, restores, restore_drills Every hosting_account has ≥1 active policy with an off-server target Operations jobs, sagas, migrations, alerts, incidents, tickets, audit_log Every infrastructure mutation has an audit row and a job row 4. Data model

Complete enough to generate schema.prisma directly. Types are Postgres.

4.1 Identity sql users ( id uuid pk, email citext unique not null, name text not null, password_hash text, -- null for SSO-only mfa_secret_encrypted bytea, mfa_enabled boolean not null default false, mfa_recovery_codes_hashed text[], type user_type not null, -- 'staff' | 'customer' | 'reseller' customer_id uuid null refs customers, -- set iff type='customer' reseller_id uuid null refs resellers, -- set iff type='reseller' status user_status not null default 'active', -- active|disabled|locked last_login_at timestamptz, failed_login_count int not null default 0, locked_until timestamptz, created_at, updated_at, deleted_at ) -- CHECK: (type='customer') = (customer_id is not null) -- CHECK: (type='reseller') = (reseller_id is not null)

roles (id uuid pk, key text unique, name text, is_system boolean) permissions (id uuid pk, key text unique) -- 'server.create', 'invoice.refund', ... role_permissions (role_id, permission_id, pk(role_id,permission_id)) user_roles (user_id, role_id, scope_type, scope_id, pk(user_id,role_id,scope_type,scope_id)) -- scope_type: 'global' | 'reseller' | 'customer'

api_tokens ( id uuid pk, name text, token_hash text unique not null, prefix char(8) not null, user_id uuid refs users, scopes text[] not null, ip_allowlist inet[], last_used_at timestamptz, expires_at timestamptz, revoked_at timestamptz, created_at )

sessions (id uuid pk, user_id, token_hash, ip inet, user_agent text, expires_at, created_at, revoked_at) 4.2 CRM sql resellers (id uuid pk, code text unique, name text, status text, parent_margin_pct numeric(5,2), resource_limits jsonb, created_at, updated_at)

customers ( id uuid pk, code text unique not null, -- CUS-000123 reseller_id uuid null refs resellers, -- null = direct customer type customer_type not null, -- 'individual' | 'company' company_name text, legal_name text, first_name text, last_name text, email citext not null, phone text, country_code char(2) not null, timezone text not null default 'Pacific/Auckland', billing_currency char(3) not null, tax_number text, -- GST/ABN/VAT tax_number_validated_at timestamptz, tax_exempt boolean not null default false, status customer_status not null, -- prospect|active|suspended|overdue|terminated|archived status_changed_at timestamptz not null, data_residency_requirement text[], -- e.g. {'AU','NZ'} — HARD constraint, §9.2 provider_preference text null, -- 'aws'|'ovh'|null — HARD constraint isolation_tier isolation_tier not null default 'shared', -- §5.1 risk_score int not null default 0, notes text, created_at, updated_at, deleted_at ) -- INDEX (reseller_id, status), (email), (status) WHERE deleted_at IS NULL

customer_contacts (id, customer_id, type contact_type[], -- primary|billing|technical|abuse name, email citext, phone, is_primary boolean) customer_addresses (id, customer_id, type, line1, line2, city, region, postcode, country_code) 4.3 Catalog sql hosting_plans ( id uuid pk, code text not null, version int not null default 1, name text not null, description text, status plan_status not null, -- draft|active|retired isolation_tier isolation_tier not null, visibility text not null, -- 'public'|'private'|'reseller' reseller_id uuid null, created_at, updated_at, unique (code, version) )

plan_limits ( plan_id uuid pk refs hosting_plans, storage_mb int not null, bandwidth_gb_month int not null, -- 0 = unmetered (still soft-capped, §19.2) websites int not null, domains int not null, subdomains int not null, databases int not null, database_size_mb int not null, ftp_users int not null, cron_jobs int not null, php_workers int not null, -- maps to FPM pm.max_children cpu_quota_pct int not null, -- cgroup quota, 100 = 1 core memory_mb int not null, -- cgroup limit io_weight int not null default 100, inodes int not null, backup_retention_daily int not null, backup_retention_weekly int not null, backup_retention_monthly int not null, ssl_included boolean not null default true, support_tier text not null, -- 'standard'|'priority' overage_policy text not null -- 'block'|'bill'|'notify_only' §16.7 )

plan_prices ( id uuid pk, plan_id uuid refs hosting_plans, currency char(3) not null, period billing_period not null, -- monthly|quarterly|semiannual|annual amount_minor bigint not null, setup_fee_minor bigint not null default 0, tax_inclusive boolean not null, active_from date not null, active_to date null, unique (plan_id, currency, period, active_from) )

plan_pool_bindings (plan_id, server_pool_id, priority int, pk(plan_id, server_pool_id))

Plan versioning rule (MUST): changing any row in plan_limits for a plan that has ≥1 non-cancelled subscription creates version+1 and leaves existing subscriptions on the old version. This is the only safe way to change limits without silently breaking live accounts, and it makes "why did my quota change" answerable.

4.4 Infrastructure sql providers (id uuid pk, key text unique, -- 'aws' | 'ovh' name text, adapter_key text not null, status text)

provider_accounts ( id uuid pk, provider_id uuid refs providers, name text not null, environment text not null, -- 'production'|'staging' credential_ref text not null, -- secrets-manager path, NEVER the secret §22.2 credential_rotated_at timestamptz, default_region_id uuid, billing_currency char(3) not null, rate_limit_rps numeric not null default 5, status text not null, health_checked_at timestamptz, health_status text, created_at, updated_at )

provider_regions ( id uuid pk, provider_account_id uuid, code text not null, -- 'ap-southeast-2' | 'SYD' display_name text, country_code char(2) not null, latency_group text not null, -- 'ANZ'|'SEA'|'US'|'EU' — used by §9.3 is_enabled boolean not null default true, unique (provider_account_id, code) )

server_types ( id uuid pk, provider_id uuid, code text not null, -- 't3.medium' | 'vps-3' vcpu int, memory_mb int, storage_gb int, storage_type text, bandwidth_tb_month numeric, hourly_cost_minor bigint, monthly_cost_minor bigint, currency char(3), cost_refreshed_at timestamptz, is_enabled boolean, unique (provider_id, code) )

server_pools ( id uuid pk, key text unique, -- 'ovh-standard-au' name text, provider_account_id uuid, region_id uuid, isolation_tier isolation_tier not null, default_server_type_id uuid, panel_type text not null, -- 'hestia' autoscale_enabled boolean not null default false, min_servers int not null default 1, max_servers int not null default 10, placement_strategy text not null default 'balanced', -- 'balanced'|'binpack' §9.5 cpu_warn_pct int not null default 75, cpu_crit_pct int not null default 90, mem_warn_pct int not null default 75, mem_crit_pct int not null default 90, disk_warn_pct int not null default 75, disk_crit_pct int not null default 85, max_accounts_per_server int not null default 60, reserve_headroom_pct int not null default 15, -- §9.4 — never fill past this status text not null )

servers ( id uuid pk, code text unique, -- SRV-0007 pool_id uuid refs server_pools, provider_account_id uuid, region_id uuid, server_type_id uuid, provider_resource_id text, -- i-0abc.. | vps-xyz hostname text unique not null, display_name text, ipv4 inet, ipv6 inet, private_ipv4 inet, os text not null, panel_type text not null, panel_version text, panel_url text, panel_api_credential_ref text not null, ssh_port int not null default 22, ssh_key_ref text not null, cpu_cores int, memory_mb int, storage_gb int, status server_status not null, status_reason text, maintenance_until timestamptz, monthly_cost_minor bigint, cost_currency char(3), commissioned_at timestamptz, decommissioned_at timestamptz, last_seen_at timestamptz, last_reconciled_at timestamptz, created_at, updated_at ) -- INDEX (pool_id, status), (provider_account_id), (status)

server_metrics ( -- rolled up; raw lives in Prometheus, §15.1 server_id uuid, bucket_start timestamptz, bucket_size interval, cpu_pct numeric, mem_pct numeric, disk_pct numeric, disk_used_gb numeric, load1 numeric, iowait_pct numeric, net_in_mbps numeric, net_out_mbps numeric, account_count int, website_count int, pk (server_id, bucket_start, bucket_size) ) -- Hypertable-shaped; partition monthly. Retain 5m buckets 30d, 1h buckets 400d.

server_capacity ( -- materialised current view, refreshed by job §11.7 server_id uuid pk, cpu_pct numeric, mem_pct numeric, disk_pct numeric, allocated_storage_mb bigint, -- SUM of plan_limits.storage_mb on this server oversubscription_ratio numeric, -- allocated / physical §9.4 account_count int, capacity_state capacity_state not null, -- ok|warn|critical|full accepts_placement boolean not null, computed_at timestamptz not null ) 4.5 Hosting sql subscriptions ( id uuid pk, code text unique, -- SUB-000123 customer_id uuid, plan_id uuid, plan_version int, status subscription_status not null, -- pending_payment|provisioning|active|past_due|suspended|pending_cancellation|cancelled|failed currency char(3) not null, period billing_period not null, unit_amount_minor bigint not null, -- snapshot of price at signup discount_id uuid null, started_at timestamptz, current_period_start date, current_period_end date, next_invoice_date date, cancel_at date, cancelled_at timestamptz, suspended_at timestamptz, grace_ends_at timestamptz, terminate_at date, auto_renew boolean not null default true, created_at, updated_at )

hosting_accounts ( id uuid pk, code text unique, -- HST-000123 subscription_id uuid unique refs subscriptions, customer_id uuid, server_id uuid refs servers, panel_username text not null, -- unique per server panel_user_ref text, status hosting_account_status not null, -- provisioning|active|suspended|migrating|terminating|terminated|failed storage_used_mb bigint not null default 0, bandwidth_used_gb_period numeric not null default 0, inodes_used int not null default 0, usage_synced_at timestamptz, provisioned_at timestamptz, suspended_at timestamptz, terminated_at timestamptz, created_at, updated_at, unique (server_id, panel_username) )

websites ( id uuid pk, hosting_account_id uuid, primary_domain_id uuid, document_root text not null, app_type text not null, -- static|php|wordpress|laravel php_version text, ssl_certificate_id uuid, status text not null, http_status_code int, last_checked_at timestamptz, created_at, updated_at )

domains ( id uuid pk, name citext unique not null, punycode text not null, customer_id uuid, hosting_account_id uuid null, website_id uuid null, type text not null, -- 'primary'|'addon'|'subdomain'|'alias' dns_managed_by text not null, -- 'platform'|'external' dns_provider_key text, -- 'cloudflare' dns_zone_ref text, registrar text, registered_at date, expires_at date, expiry_checked_at timestamptz, nameservers text[], nameservers_verified_at timestamptz, status text not null, created_at, updated_at )

dns_records ( id uuid pk, domain_id uuid, provider_record_ref text, type text not null, name text not null, value text not null, ttl int not null default 300, priority int, proxied boolean, managed_by_platform boolean not null default true, created_at, updated_at )

databases ( id uuid pk, hosting_account_id uuid, server_id uuid, engine text not null, -- 'mysql'|'mariadb' name text not null, size_mb numeric not null default 0, status text not null, created_at, updated_at, unique (server_id, name) ) database_users (id, database_id, username, password_secret_ref text not null, privileges text[], host_pattern text, created_at) ftp_users (id, hosting_account_id, username, password_secret_ref, home_path, protocol text, status, created_at)

ssl_certificates ( id uuid pk, website_id uuid, domain_names text[] not null, issuer text not null default 'letsencrypt', type text not null, -- 'dv'|'custom' status ssl_status not null, -- pending|active|expiring|expired|failed|revoked issued_at timestamptz, expires_at timestamptz, last_renewal_attempt_at timestamptz, renewal_failure_count int not null default 0, last_error text, fingerprint_sha256 text, created_at, updated_at ) -- INDEX (expires_at) WHERE status IN ('active','expiring') 4.6 Data protection sql backup_policies ( id uuid pk, scope text not null, -- 'plan'|'account' plan_id uuid null, hosting_account_id uuid null, target_id uuid refs backup_targets, frequency_cron text not null, includes text[] not null, -- {'files','databases','config'} retain_daily int, retain_weekly int, retain_monthly int, encryption_key_ref text not null, is_enabled boolean not null default true )

backup_targets ( id uuid pk, key text unique, kind text not null, -- 's3'|'sftp' endpoint text, region text, bucket text, credential_ref text not null, provider_account_id uuid null, storage_cost_per_gb_month_minor bigint, currency char(3), is_default boolean )

backups ( id uuid pk, hosting_account_id uuid, policy_id uuid, target_id uuid, server_id uuid, -- source at time of backup kind text not null, -- 'full'|'files'|'database' status backup_status not null, -- scheduled|running|completed|failed|expired|deleted started_at, completed_at, size_bytes bigint, object_key text, checksum_sha256 text, encryption_key_ref text, is_verified boolean not null default false, expires_at timestamptz, error_code text, error_detail text, created_at ) -- INDEX (hosting_account_id, created_at DESC), (status), (expires_at)

restores ( id uuid pk, backup_id uuid, requested_by uuid refs users, target_hosting_account_id uuid, scope text not null, -- 'full'|'files'|'database' status text not null, approved_by uuid, approved_at timestamptz, started_at, completed_at, error_detail text, created_at )

restore_drills ( -- §14.5 id uuid pk, backup_id uuid, run_at timestamptz, passed boolean, checks jsonb, duration_seconds int, notes text ) 4.7 Billing sql invoices ( id uuid pk, number text unique, -- INV-2026-000042, gapless per §16.4 customer_id uuid, reseller_id uuid null, status invoice_status not null, -- draft|issued|partially_paid|paid|overdue|cancelled|refunded|uncollectible currency char(3) not null, subtotal_minor bigint not null, discount_minor bigint not null default 0, tax_minor bigint not null, total_minor bigint not null, amount_paid_minor bigint not null default 0, amount_due_minor bigint generated always as (total_minor - amount_paid_minor) stored, tax_rate_pct numeric(5,2), tax_label text, -- 'GST 15%' tax_country char(2), customer_tax_number text, issue_date date, due_date date, service_period_start date, service_period_end date, paid_at timestamptz, voided_at timestamptz, pdf_object_key text, notes text, created_at, updated_at ) -- Immutable once status <> 'draft'. Enforced by trigger. §16.4

invoice_items ( id uuid pk, invoice_id uuid, sort_order int, type text not null, -- hosting|domain|ssl|backup|overage|migration|setup|support|credit|adjustment subscription_id uuid null, description text not null, quantity numeric not null default 1, unit_amount_minor bigint not null, amount_minor bigint not null, tax_rate_pct numeric(5,2), tax_minor bigint not null, service_period_start date, service_period_end date, metadata jsonb )

payments ( id uuid pk, customer_id uuid, invoice_id uuid null, method text not null, -- 'stripe_card'|'bank_transfer'|'manual'|'credit' status text not null, -- pending|succeeded|failed|refunded|disputed amount_minor bigint not null, currency char(3), fee_minor bigint not null default 0, -- processor fee, feeds §17 provider_ref text, provider_payload jsonb, received_at timestamptz, reconciled_at timestamptz, created_by uuid, created_at )

credit_notes (id, customer_id, invoice_id, number text unique, amount_minor, currency, reason text, issued_at, created_by) customer_credits (id, customer_id, amount_minor, currency, balance_minor, source text, expires_at, created_at) refunds (id, payment_id, amount_minor, currency, reason, provider_ref, status, requested_by, approved_by, created_at)

discounts (id, code text unique, kind text, -- 'percent'|'fixed' value numeric, applies_to text, max_redemptions int, redeemed_count int, valid_from, valid_to, is_active)

tax_rates ( id uuid pk, country_code char(2), region_code text null, name text not null, -- 'GST' rate_pct numeric(5,2) not null, applies_to text[] not null, valid_from date not null, valid_to date null, reverse_charge_eligible boolean not null default false )

fx_rates (base char(3), quote char(3), rate numeric(18,8), rate_date date, source text, pk (base, quote, rate_date))

dunning_events (id, subscription_id, invoice_id, step int, action text, scheduled_for timestamptz, executed_at timestamptz, result text) 4.8 Cost & profitability sql provider_cost_records ( -- ingested from AWS CUR / OVH billing API, §17.1 id uuid pk, provider_account_id uuid, period_start date, period_end date, resource_ref text, -- instance id, bucket, etc. server_id uuid null, backup_target_id uuid null, category text not null, -- compute|storage|bandwidth|snapshot|other amount_minor bigint, currency char(3), amount_base_minor bigint, base_currency char(3), fx_rate numeric(18,8), ingested_at timestamptz, unique (provider_account_id, resource_ref, period_start, category) )

cost_allocations ( -- computed monthly, §17.2 id uuid pk, period date not null, -- first of month hosting_account_id uuid, customer_id uuid, server_id uuid, compute_minor bigint, storage_minor bigint, bandwidth_minor bigint, backup_minor bigint, payment_fee_minor bigint, support_minor bigint, total_minor bigint, currency char(3), allocation_basis jsonb, -- audit trail of the math computed_at timestamptz, unique (period, hosting_account_id) )

usage_records ( -- for overage billing + allocation id uuid pk, hosting_account_id uuid, metric text not null, -- 'storage_mb_avg'|'bandwidth_gb'|'cpu_seconds'|'backup_gb' period_start date, period_end date, quantity numeric, is_billed boolean not null default false, invoice_item_id uuid null, unique (hosting_account_id, metric, period_start) ) 4.9 Operations sql jobs ( id uuid pk, queue text not null, name text not null, idempotency_key text unique not null, -- §11.2 saga_id uuid null, step_index int null, payload jsonb not null, status job_status not null, -- queued|running|succeeded|failed|dead|cancelled|compensating|compensated attempts int not null default 0, max_attempts int not null default 5, scheduled_for timestamptz, started_at, finished_at, error_code text, error_detail text, error_is_retryable boolean, result jsonb, actor_id uuid null, correlation_id uuid not null, resource_type text, resource_id uuid, created_at, updated_at ) -- INDEX (status, scheduled_for), (resource_type, resource_id), (saga_id, step_index)

sagas (id uuid pk, name text, status text, current_step int, context jsonb, compensations jsonb, started_at, finished_at)

outbox (id bigserial pk, aggregate_type text, aggregate_id uuid, event_type text, payload jsonb, created_at, published_at timestamptz null) -- INDEX (published_at) WHERE published_at IS NULL

migrations_ops ( -- named to avoid clashing with schema migrations id uuid pk, code text unique, hosting_account_id uuid, source_server_id uuid, target_server_id uuid, reason text, strategy text, -- 'rsync_cutover' status migration_status not null, -- planned|precheck|syncing|verifying|awaiting_cutover|cutover|monitoring|completed|rolled_back|failed dry_run boolean not null default false, planned_cutover_at timestamptz, ttl_lowered_at timestamptz, freeze_started_at timestamptz, cutover_at timestamptz, rollback_deadline timestamptz, source_retained_until date, bytes_transferred bigint, checks jsonb, error_detail text, requested_by uuid, approved_by uuid, created_at, updated_at )

alerts ( id uuid pk, rule_key text not null, severity text not null, -- info|warning|critical resource_type text, resource_id uuid, customer_id uuid null, title text, detail text, fingerprint text not null, status text not null, -- firing|acknowledged|resolved|silenced first_seen_at, last_seen_at, resolved_at, acknowledged_by uuid, acknowledged_at, notification_sent_at timestamptz, unique (fingerprint) WHERE status = 'firing' -- dedupe, §15.3 )

audit_log ( id bigserial pk, occurred_at timestamptz not null, actor_type text not null, -- 'user'|'system'|'api_token'|'webhook' actor_id uuid null, actor_label text, action text not null, -- 'hosting_account.suspend' resource_type text not null, resource_id uuid, customer_id uuid null, before jsonb, after jsonb, diff jsonb, ip inet, user_agent text, correlation_id uuid, result text not null, -- 'success'|'failure' reason text ) -- Append-only. REVOKE UPDATE, DELETE from app role. Partitioned monthly. §22.6

support_tickets (id, code, customer_id, subject, category, priority, status, assigned_to, first_response_at, resolved_at, sla_due_at, created_at) ticket_messages (id, ticket_id, author_type, author_id, body, is_internal boolean, attachments jsonb, created_at)

notifications (id, template_key, channel, recipient, customer_id, subject, body_rendered, status, provider_ref, sent_at, opened_at, error, created_at)

idempotency_keys (key text pk, scope text, request_hash text, response_status int, response_body jsonb, created_at, expires_at) 5. Tenancy, isolation and the provider-opacity guarantee 5.1 Isolation tiers (replaces the source's unqualified isolation claim) Tier Implementation Sold as Blast radius shared One OS user per account; open_basedir; per-user PHP-FPM pool with its own uid; per-user cgroup v2 CPU/memory/IO limits; MySQL user scoped to own schemas; noexec,nosuid on /tmp per user "Shared hosting" Kernel + MySQL server shared. Documented. isolated Dedicated VM, single account, same panel "Managed VPS" Own kernel dedicated_db Isolated tier + managed database (RDS / OVH managed) "Enterprise" Own kernel + own DB

MUST: the customer-facing plan description for shared states that resources are shared. The word "isolated" MUST NOT appear in shared plan copy. This is both honest and legally safer.

5.2 Application-level tenancy

There are two tenancy dimensions: reseller_id and customer_id. Enforcement is in three layers, and all three MUST exist — defence in depth, because a single missed where clause in a shared-hosting billing system is a data breach.

Request scope. Auth middleware resolves an ActorContext { actorId, userType, customerId?, resellerId?, permissions: Set<string> } and puts it in an AsyncLocalStorage. There is no other way to learn who is calling. Repository guard. All reads go through repositories in packages/db. The base repository injects a tenant predicate for every model that declares tenantColumn. A repository method that needs to bypass it MUST be named *Unscoped and MUST be listed in an allowlist checked by a unit test. Postgres RLS. Enable row-level security on customers, subscriptions, hosting_accounts, websites, domains, databases, backups, invoices, payments, support_tickets. The API sets SET LOCAL app.customer_id per transaction. RLS is the backstop for a bug in layer 2, not the primary mechanism.

Test (MUST): a generated integration test enumerates every /api/v1 route, calls it as customer A with an ID belonging to customer B, and asserts 404 (not 403 — do not confirm existence).

5.3 Provider opacity — made testable

The source's "customer must not care about the provider" becomes three concrete rules:

P1. No API response served to a customer actor contains the strings from providers.key, provider_accounts.name, server_types.code, servers.provider_resource_id, or server_pools.key. Enforced by a response serialiser allowlist and asserted by a snapshot test over every portal endpoint. P2. hosting_accounts.server_id is never exposed to a customer actor. The portal shows an IP address and a panel URL (unavoidable) but never a server code or pool. P3. Migrating an account between providers MUST NOT change: plan id, price, invoice line description, subscription dates, or the customer's panel username. Asserted by the migration e2e test (§24, M9). 6. Roles and permissions

Permissions are flat strings, checked by a @RequirePermission('server.create') decorator. Roles are bundles. Scope (global / reseller:<id> / customer:<id>) narrows which rows the permission applies to.

Domains: customer, plan, subscription, invoice, payment, refund, credit, provider, server, pool, hosting_account, website, domain, dns, database, ssl, backup, restore, migration, alert, ticket, user, role, audit, secret, report, system Verbs: read, list, create, update, delete, suspend, resume, approve, execute, export

Seed roles:

Role Notable grants Notable denials super_admin * — hosting_admin all infra + hosting + backup + migration (migration.execute requires second approval, §18.6) secret.read, provider.update, role.*, payment.update support read on all customer/hosting/billing; ticket.*; hosting_account.resume; website.restart (service restart only) any delete, suspend, refund.*, server.* writes finance invoice.*, payment.*, refund.create, credit.*, report.*, customer.read every infrastructure permission, hosting_account.suspend (finance triggers dunning; dunning suspends) reseller_admin scoped to own reseller_id: customer/subscription/hosting read+create pricing of parent, other resellers, all infra customer scoped to own customer_id everything else

Rules (MUST):

Deny by default. An endpoint without a @RequirePermission decorator fails a lint test. secret.read does not exist as a grantable permission for humans. Credentials are never returned by any API to any actor (§22.2). Support "views" a credential only by triggering a rotate-and-deliver-to-customer flow. Privilege escalation guard: a user cannot grant a permission they do not hold. Every suspend, delete, refund, restore, migration.execute writes an audit_log row with reason — the reason is a required request field, not optional. 7. Cloud provider adapter

The whole architecture rests on this. If provider knowledge leaks out of packages/adapters-cloud, adding Hetzner later becomes a rewrite instead of a folder.

7.1 Interface ts // packages/adapters-cloud/core/src/provider.ts export interface CloudProvider { readonly key: string; // 'aws' | 'ovh' readonly capabilities: ProviderCapabilities;

// Catalog — cached, refreshed by a scheduled job listRegions(): Promise<Region[]>; listServerTypes(regionCode: string): Promise<ServerType[]>; getPricing(regionCode: string, typeCode: string): Promise<Price>;

// Lifecycle. All mutations take an idempotencyKey and are safe to replay. createServer(req: CreateServerRequest): Promise<ServerHandle>; getServer(ref: ProviderRef): Promise<ServerInfo | null>; deleteServer(ref: ProviderRef, opts: { idempotencyKey: string }): Promise<void>; rebootServer(ref: ProviderRef): Promise<void>; resizeServer(ref: ProviderRef, typeCode: string): Promise<ResizeResult>; waitUntilRunning(ref: ProviderRef, timeoutMs: number): Promise<ServerInfo>;

// Networking ensureFirewall(ref: ProviderRef, rules: FirewallRule[]): Promise<void>; attachStaticIp?(ref: ProviderRef): Promise<string>;

// Storage / snapshots createSnapshot?(ref: ProviderRef, label: string): Promise<SnapshotHandle>;

// Cost fetchCostRecords(from: Date, to: Date): Promise<CostRecord[]>;

// Health ping(): Promise<{ ok: boolean; latencyMs: number }>; }

export interface ProviderCapabilities { snapshots: boolean; resizeWithoutRebuild: boolean; privateNetworking: boolean; managedDatabase: boolean; objectStorage: boolean; staticIp: boolean; hourlyBilling: boolean; minBillingIncrementHours: number; // AWS 0 (per-second), OVH 720 (monthly) }

export interface CreateServerRequest { idempotencyKey: string; // MUST be passed to the provider where supported regionCode: string; typeCode: string; hostname: string; imageRef: string; // resolved from an image alias, §7.3 sshKeyRefs: string[]; cloudInit: string; // §12.2 tags: Record<string, string>; // MUST include platform, env, server_code }

Capability rule (MUST): the placement engine and provisioning saga branch on capabilities, never on provider.key. A switch (provider.key) anywhere outside adapters-cloud fails code review. Add an ESLint rule.

7.2 Error taxonomy

Every adapter maps provider errors into exactly one of these. Retry policy is decided from the class, never from an HTTP code, because AWS and OVH disagree about codes.

ts type ProviderErrorKind = | 'auth' // credentials bad/expired — do NOT retry, page an admin | 'rate_limited' // retry with backoff + jitter, honour Retry-After | 'quota_exceeded' // provider account limit — do NOT retry, alert, block pool | 'capacity' // region out of stock — retry in a DIFFERENT region/type | 'not_found' // resource gone — treat as terminal for delete (success) | 'conflict' // concurrent op — retry after short delay | 'invalid_request' // our bug — do NOT retry, dead-letter | 'timeout' // retry, but reconcile first (may have partially succeeded) | 'provider_down' // retry with long backoff, open the circuit breaker | 'unknown'; // retry twice then dead-letter

timeout is the dangerous one: a create that times out may still have created a server. MUST: before retrying any createServer, the saga calls findServerByTag(server_code) and adopts an existing resource rather than creating a second. Orphaned-resource detection is also a nightly reconciliation job (§11.7) — this is how a hosting business avoids paying for VMs it forgot about.

7.3 Image aliases

Never hardcode an AMI ID or OVH image name in business logic.

image alias: 'ubuntu-24.04-lts' aws → resolve via SSM public parameter /aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id ovh → 'Ubuntu 24.04'

Resolved images are cached in provider_images (alias, provider_account_id, region, resolved_ref, resolved_at) and refreshed weekly.

7.4 Rate limiting, retries, circuit breaking Per provider_account_id: Redis token bucket at rate_limit_rps, burst 2×. Retry: exponential backoff, base 1s, factor 2, max 60s, full jitter, max 5 attempts, only for retryable kinds. Circuit breaker per provider account: 5 consecutive provider_down/timeout opens it for 60s; half-open lets 1 request through. An open breaker sets provider_accounts.health_status='degraded' and makes the placement engine skip that account (§9.2 hard constraint 3) rather than failing orders. 7.5 AWS and OVH specifics (adapter-internal) Concern AWS OVH Compute EC2, gp3 root, ClientToken = idempotencyKey Public Cloud instances / VPS API, X-Ovh-* signed auth Idempotency Native (ClientToken) Not native. Adapter MUST implement it: write provider_operations(idempotency_key, provider_ref) before the call and look it up on replay. Firewall Security group per pool + per server OVH network firewall + host nftables (nftables is the source of truth, §12.4) Cost data Cost & Usage Report → S3 → parse daily /me/bill + /cloud/project/{id}/usage/current Billing granularity per-second monthly, prorated on some products — treat as monthly for allocation Metadata/tags native tags OVH instance has limited tagging; adapter mirrors tags into a local provider_resource_tags table Managed DB RDS (dedicated_db tier only) OVH Managed Databases (Phase 3)

The OVH idempotency gap is the single biggest correctness risk in the integration. Build provider_operations first, before either adapter's createServer.

8. Hosting panel adapter 8.1 Interface ts export interface HostingPanel { readonly key: string; // 'hestia' readonly capabilities: PanelCapabilities;

// Accounts createAccount(r: CreateAccountRequest): Promise<PanelAccount>; suspendAccount(username: string): Promise<void>; unsuspendAccount(username: string): Promise<void>; deleteAccount(username: string, opts: { backupFirst: boolean }): Promise<void>; setAccountLimits(username: string, limits: PanelLimits): Promise<void>; getAccountUsage(username: string): Promise<AccountUsage>; listAccounts(): Promise<PanelAccountSummary[]>; // for reconciliation

// Web addDomain(username: string, d: AddDomainRequest): Promise<void>; removeDomain(username: string, domain: string): Promise<void>; setPhpVersion(username: string, domain: string, version: string): Promise<void>;

// TLS issueLetsEncrypt(username: string, domain: string, aliases: string[]): Promise<CertInfo>; installCustomCert(username: string, domain: string, cert: Pem): Promise<CertInfo>; getCertInfo(username: string, domain: string): Promise<CertInfo | null>;

// Data createDatabase(username: string, r: CreateDbRequest): Promise<PanelDatabase>; dropDatabase(username: string, name: string): Promise<void>; createDbUser(username: string, r: CreateDbUserRequest): Promise<void>; rotateDbUserPassword(username: string, dbUser: string): Promise<{ password: string }>; createFtpUser(username: string, r: CreateFtpRequest): Promise<void>;

// Backup (panel-native; platform-level backup is §14) createBackup(username: string): Promise<PanelBackupHandle>; restoreBackup(username: string, ref: string, scope: RestoreScope): Promise<void>;

// Ops getServerStats(): Promise<PanelServerStats>; restartService(name: 'nginx'|'apache'|'php-fpm'|'mysql'): Promise<void>; } 8.2 HestiaCP binding notes Transport: HTTPS to :8083/api/ with user=admin&hash=<API key>, or v- CLI over SSH. Decision: use the HTTP API for all operations it supports; fall back to v-* commands over SSH only for setAccountLimits (cgroup/FPM tuning) and nftables changes. Both paths go through the adapter. Hestia returns numeric exit codes, not JSON errors. The adapter MUST map the documented E_* codes (e.g. E_EXISTS, E_NOTEXIST, E_LIMIT, E_PASSWORD, E_DISK) to PanelErrorKind mirroring §7.2. Unmapped codes → unknown. Hestia has no idempotency. Every mutating adapter method MUST be written as read-then-act: if (await exists(x)) return existing;. createAccount on an existing username returns the existing account if and only if it matches the expected plan fingerprint; otherwise it throws conflict. Panel API credentials are per-server, stored as servers.panel_api_credential_ref pointing at Secrets Manager. Rotated on a 90-day schedule by a job. Panel port 8083 is firewalled to the platform's egress NAT IPs plus an admin allowlist. Customers reach the panel through a platform reverse proxy at panel.<brand>.tld/<account-code> so the server hostname is not leaked (§5.3 P2). 8.3 Username generation

Deterministic, collision-safe, and stable across migrations (P3 in §5.3): u + base36(customer sequence) truncated to 8 chars, e.g. u0a3f9k. Uniqueness is per-server (unique (server_id, panel_username)) but the platform assigns globally unique names so a migration never has to rename. Never derive from the domain — domains change.

9. Placement engine

Pure function. Lives in packages/domain/placement. No I/O. This is the feature the source called the most important, and it is the one that was least specified.

9.1 Signature ts export function selectPlacement(input: PlacementInput): PlacementDecision;

interface PlacementInput { requirement: { planLimits: PlanLimits; isolationTier: IsolationTier; requiredCapabilities: (keyof ProviderCapabilities)[]; // e.g. managedDatabase customerCountry: string; dataResidency: string[] | null; // hard providerPreference: string | null; // hard latencyGroupPreference: string[]; // ordered soft, e.g. ['ANZ','SEA'] }; candidateServers: CandidateServer[]; // pre-filtered to bound pools pools: PoolConfig[]; providerAccountHealth: Record<string, 'healthy'|'degraded'|'down'>; weights: PlacementWeights; now: Date; }

type PlacementDecision = | { kind: 'existing_server'; serverId: string; score: number; trace: Trace } | { kind: 'new_server'; poolId: string; serverTypeId: string; regionId: string; estimatedMonthlyCostMinor: number; trace: Trace } | { kind: 'no_capacity'; reasons: RejectionReason[]; trace: Trace };

MUST: trace records, for every candidate, which hard constraint eliminated it or what each soft score component was. This is rendered verbatim in the admin UI. Support will ask "why did this customer land on server 7" every week; answer it in the product.

9.2 Hard constraints (evaluated first, in order; failing any eliminates a candidate) server.status == 'active' and not in maintenance. server.pool.isolation_tier == requirement.isolationTier. provider_account.health != 'down' and circuit breaker closed. If providerPreference set → server.provider.key == providerPreference. If dataResidency set → region.country_code ∈ dataResidency. All requiredCapabilities satisfied by the provider. Free disk after placement ≥ reserve_headroom_pct of physical: (allocated_storage_mb + planLimits.storage_mb) ≤ physical_mb × (1 − headroom) × oversubscription_limit. capacity_state != 'critical' and capacity_state != 'full'. account_count < max_accounts_per_server. Committed memory: Σ plan_limits.memory_mb (incl. new) ≤ physical_memory × mem_oversubscription (default 3.0 for shared, 1.0 for isolated). Not currently a migration source or target.

If no candidate survives and pool.autoscale_enabled → new_server. If autoscale disabled → no_capacity.

9.3 Soft scoring (0–100 each, weighted sum, highest wins) Component Default weight Definition cost 0.30 100 × (1 − normalise(marginalCostMinor)). Marginal cost of adding this account to an existing server ≈ server.monthly_cost / (account_count + 1) deltas; for new_server it is the full type cost. Always converted to base currency at the current fx_rates row. latency 0.25 100 if region's latency_group == first preference, 60 if second, 20 if third, 0 otherwise. utilisation_fit 0.20 Strategy-dependent. balanced: `100 − headroom_safety 0.15 100 × (1 − max(cpu_pct, mem_pct, disk_pct)/100) using the 7-day p95, not the instant value. p95, not average — averages hide the daily backup spike. age_stability 0.05 Prefer servers commissioned >14 days ago (fully burned-in, panel patched). consolidation 0.05 +100 if the customer already has accounts on this server (same-customer colocation simplifies support and migration).

Weights are stored in placement_weights and editable by super_admin, but the default set above ships as the seed.

Tie-break (deterministic, MUST): highest score → lowest server.code lexically. Never random. Deterministic placement makes the engine unit-testable and incident analysis possible.

9.4 Oversubscription policy

Shared hosting is economically viable only through oversubscription, and it is also how shared hosting businesses die. Explicit defaults:

disk: 1.0× (NEVER oversubscribe disk — it is the one resource that cannot be reclaimed under pressure and causes total node failure) memory: 3.0× (cgroup limits + swap; monitored via §15) cpu: 4.0× (cgroup quota is a ceiling, not a reservation)

reserve_headroom_pct (default 15%) is a floor on free disk that placement never eats into; it exists so that a single customer's runaway logs cannot fill the node.

9.5 Strategy

balanced is the default for shared pools: better tail latency and a smaller blast radius. binpack is available for pools where cost dominates and the workload is known idle. Do not make this dynamic in v1.

9.6 Test corpus (MUST exist before the engine is used)

A placement.fixtures.json with ≥30 scenarios, each an input and an expected decision, including: empty pool + autoscale off → no_capacity; residency AU excludes SG servers; provider preference overrides a cheaper alternative; disk-full server excluded even at low CPU; degraded provider account skipped; two identical servers → deterministic tie-break; enterprise tier with managedDatabase requirement excludes OVH pool.

10. State machines

Transitions not listed are illegal and MUST throw. Each machine is a table in packages/domain/state plus a generated diagram in docs/.

10.1 Subscription pending_payment ──payment_confirmed──▶ provisioning pending_payment ──expired/cancelled──▶ cancelled provisioning ──provisioned──▶ active provisioning ──failed──▶ failed (customer NOT billed; §20.2) failed ──retry──▶ provisioning failed ──abandon──▶ cancelled (auto-refund) active ──invoice_overdue──▶ past_due past_due ──payment_received──▶ active past_due ──grace_expired──▶ suspended suspended ──payment_received──▶ active (via reactivation job) suspended ──retention_expired──▶ pending_cancellation active ──customer_cancels──▶ pending_cancellation pending_cancellation ──period_end──▶ cancelled pending_cancellation ──customer_reactivates──▶ active cancelled ── (terminal; hosting_account terminated after §20.5 window) 10.2 Hosting account provisioning → active | failed active → suspended | migrating | terminating suspended → active | terminating migrating → active (on cutover success) | active (on rollback, back to source) terminating → terminated failed → provisioning (retry) | terminated

Invariant (MUST): subscription.status == 'active' ⟺ hosting_account.status ∈ {active, migrating}. A consistency check job asserts this every 15 minutes and alerts on drift.

10.3 Server requested → provisioning → installing → configuring → active any → failed (with reason) active → maintenance → active active → capacity_warning → active | full full → active (after accounts move off) active|full|maintenance → draining → decommissioning → decommissioned

draining is new versus the source and is essential: it means "no new placements, existing accounts being migrated off". Decommission MUST NOT be reachable from a state where hosting_accounts still reference the server — enforced by a FK check in the job.

10.4 Invoice

draft → issued → (partially_paid) → paid; issued → overdue → paid | uncollectible; draft → cancelled; issued → cancelled only via a credit note, never by mutation.

10.5 Migration

See §18; the enum is in migrations_ops.status.

11. Job and saga architecture 11.1 Rules MUST: no HTTP request performs an external mutation. Controllers validate, persist intent, enqueue, and return 202 with a job id and a polling URL. Queues (BullMQ), each with its own concurrency: provisioning (4), panel (8), dns (8), ssl (4), backup (6), restore (2), migration (2), billing (4), monitoring (16), notification (16), reconciliation (2), costing (2). Priorities: customer-visible provisioning > billing > backups > reconciliation. Job timeouts: default 5 min; backup 4 h; restore 4 h; migration step 2 h. A job exceeding its timeout is marked failed with error_is_retryable=true and its saga runs a reconcile step before retrying. 11.2 Idempotency

Every job payload carries idempotencyKey = sha256(jobName + businessKey), where businessKey is stable and semantic — e.g. hosting_account:HST-000123:provision:attempt-1. The jobs.idempotency_key unique index makes double-enqueue a no-op. Job handlers MUST additionally be written so that running twice with the same key produces the same end state (check-then-act against the panel/provider, never blind create).

11.3 Saga pattern

Multi-step infrastructure flows are sagas with per-step compensation. Steps are pure descriptors; the runner persists progress in sagas.context after each step so a worker crash resumes rather than restarts.

ts defineSaga('provision-hosting-account', { steps: [ step('select_placement', run: selectPlacement, compensate: noop), step('ensure_server', run: ensureServer, compensate: releaseIfCreatedByUs), step('create_panel_user', run: createPanelUser, compensate: deletePanelUser), step('apply_limits', run: applyLimits, compensate: noop), step('create_domain', run: addDomain, compensate: removeDomain), step('create_database', run: createDatabase, compensate: dropDatabase), step('configure_dns', run: upsertDnsRecords, compensate: revertDnsRecords), step('issue_ssl', run: issueLetsEncrypt, compensate: noop, optional: true), step('configure_backup', run: attachBackupPolicy, compensate: detachBackupPolicy), step('enable_monitoring', run: registerTargets, compensate: deregisterTargets), step('activate', run: markActive, compensate: markFailed), step('notify', run: sendWelcome, compensate: noop), ], onFailure: 'compensate_then_fail', });

optional: true (SSL) means failure logs a warning, raises an alert, and continues — a certificate that fails on DNS-not-yet-propagated must not roll back a whole account. A retry job picks it up (§13.4).

11.4 Failure handling (upgrades source §52)

On terminal failure: mark saga failed → run compensations in reverse → set subscription.status='failed' → void or credit any invoice raised for the failed period (MUST — never bill for hosting that does not exist) → alert hosting_admin with the trace → surface a "Retry" button that re-enqueues with attempt-N+1.

11.5 Dead letter

Jobs exhausting max_attempts move to status='dead' and a dlq:<queue> BullMQ queue, retained 30 days, retryable from the admin UI. Alert if DLQ depth > 0 for > 15 min.

11.6 Outbox

Domain events are written to outbox inside the same transaction as the state change, then published by a poller (every 1 s, FOR UPDATE SKIP LOCKED, batch 100). This is what prevents "hosting account activated but welcome email never sent" and its inverse. Consumers are idempotent by outbox.id.

11.7 Reconciliation jobs (scheduled)

Reality drifts from the database. These jobs are not optional garnish; they are how the system stays true.

Job Cadence Action reconcile-servers 15 min List provider resources by tag; flag DB servers missing at provider (orphan_db), and provider resources with no DB row (orphan_cloud — these are money on fire; alert critical) reconcile-panel-accounts hourly Diff listAccounts() against hosting_accounts; flag both directions sync-account-usage hourly getAccountUsage → hosting_accounts.storage_used_mb, inodes refresh-server-capacity 5 min Recompute server_capacity from Prometheus p95 + allocations refresh-provider-catalog daily Regions, types, prices ingest-provider-costs daily 04:00 §17.1 check-ssl-expiry hourly §13.4 check-domain-expiry daily RDAP lookup expire-backups daily Delete past-retention objects, mark expired restore-drill monthly §14.5 consistency-check 15 min §10.2 invariants + orphan rows rotate-panel-credentials daily scan, 90-day age §8.2 12. Server build pipeline 12.1 Saga provision-server: reserve_record → create_provider_server → wait_running → assign_dns_hostname → wait_ssh → run_ansible_base → run_ansible_panel → run_ansible_hardening → install_monitoring_agent → register_backup_agent → smoke_test → mark_active compensate: delete_provider_server (only if we created it), delete_record

smoke_test (MUST pass before active): panel API answers; a throwaway account can be created, given a domain, issued a self-signed vhost, and deleted; nginx/php-fpm/mysql all up; node_exporter scraping; backup agent can write and read a test object; nftables default-deny confirmed; df shows expected volume size.

12.2 cloud-init

Minimal on purpose — it only bootstraps enough for Ansible: create ops user, install the platform's SSH CA public key, set hostname, disable password auth, install python3. Everything else is Ansible, because cloud-init is not idempotent and cannot be re-run.

12.3 Ansible roles

base (packages, timezone UTC, unattended-security-upgrades, journald limits, swap, sysctl), storage (separate /home volume with quotas, noexec,nosuid,nodev on /tmp, /dev/shm), panel (HestiaCP pinned version, admin API key generated and written straight to Secrets Manager, panel bound to 8083 with allowlist), hardening (§12.4), monitoring (node_exporter, mysqld_exporter, nginx log shipping), backup_agent (restic + credentials from instance profile/OVH token), php (per-user FPM pool template, open_basedir, disable_functions, opcache), mysql (per-account users only, local_infile=0, slow log), waf (ModSecurity + CRS in DetectionOnly for 14 days then blocking).

MUST: Ansible is run with --check in CI against a container to prove idempotency; a second real run MUST report zero changed tasks.

12.4 Baseline hardening nftables default-deny inbound; allow 80, 443, 22 (platform NAT + admin allowlist), 8083 (same allowlist), 25 outbound blocked by default (spam containment — this single rule prevents the most common shared-hosting reputational disaster; per-account exceptions require an approval). SSH: CA-signed short-lived certificates (24 h) issued by the platform, not long-lived keys. No password auth, no root login, AllowUsers ops. fail2ban on ssh, panel, and web auth endpoints. Per-account cgroup v2 slices from plan_limits (cpu.max, memory.max, io.weight). open_basedir per FPM pool; disable_functions=exec,passthru,shell_exec,system,proc_open,popen. Automatic OS security updates; kernel livepatch where available; monthly reboot window per pool, staggered, announced. 13. Domains, DNS and SSL 13.1 Domain onboarding

Three paths, all supported: (a) customer delegates nameservers to Cloudflare zone the platform manages; (b) customer keeps external DNS and the platform emits a record checklist plus a verification poller; (c) subdomain of the platform's own domain for instant preview (hst-000123.preview.<brand>.tld) — MUST exist, because it lets a site be built and tested before DNS cutover, which is what makes migrations safe.

13.2 DNS adapter ts interface DnsProvider { ensureZone(domain: string): Promise<ZoneRef>; listRecords(zone: ZoneRef): Promise<DnsRecord[]>; upsertRecord(zone: ZoneRef, r: DnsRecordInput): Promise<DnsRecord>; deleteRecord(zone: ZoneRef, ref: string): Promise<void>; setZoneTtl(zone: ZoneRef, ttl: number): Promise<void>; }

Platform-managed records carry managed_by_platform=true; the reconciler never deletes a record it does not own. Every change writes an audit_log row with before/after (source SRS §21 requirement, now concrete).

13.3 Record templates on provisioning

A @ → server.ipv4 (TTL 300), A www, AAAA if available, CNAME for aliases, plus MUST for any domain the platform does not host mail for: MX untouched if present, and if absent a null MX (MX 0 .) plus TXT @ "v=spf1 -all" and _dmarc TXT "v=DMARC1; p=reject;". Publishing anti-spoofing records by default for non-mail domains is free and prevents the platform's IP space being used in forgery.

13.4 SSL — resilient by design (fixes C2) Issuance and renewal run on the node via the panel's ACME client (cron), not from the control plane. The control plane observes and repairs. check-ssl-expiry (hourly) reads actual certificate expiry via TLS handshake against the site — not the database, because the database can be wrong. Records into ssl_certificates. Status thresholds: active >21 d; expiring ≤21 d; escalate to a warning alert at ≤14 d, critical at ≤7 d, page at ≤3 d. On renewal_failure_count ≥ 2, enqueue ssl.force-renew with HTTP-01; if the domain is on platform-managed DNS, fall back to DNS-01 automatically (this is the only reliable path when a customer has a redirect or WAF in front). Rate-limit awareness: Let's Encrypt allows 5 duplicate certificates per week. The job MUST track attempts per domain in Redis and refuse a 6th, alerting instead of burning the quota. Wildcards require DNS-01 and are only offered when dns_managed_by='platform'. 13.5 Registrar

v1 does not register or renew domains. domains.expires_at is populated by an RDAP lookup (with WHOIS fallback), refreshed daily, and drives the "Domain Expiring" notification at 60/30/14/7 days. The UI states clearly that renewal is the customer's responsibility at their registrar. Registrar integration is Phase 3.

14. Backups 14.1 Design

Engine: restic to an S3-compatible target. Chosen over panel-native backups because it does deduplication, client-side encryption, and incremental snapshots, and because restic check gives a verifiable integrity signal.

One restic repository per hosting account (not per server). Per-account repos mean a migration moves the repo pointer, not the data, and a compromised node cannot read another account's backups. Encryption: per-account key, generated at provisioning, stored in Secrets Manager, referenced by backup_policies.encryption_key_ref. The key is never stored on the node — it is fetched into the agent's memory per run via a scoped, short-lived credential. Databases are dumped with mysqldump --single-transaction --quick into the snapshot; a logical dump is what makes a partial restore possible. 14.2 Off-server requirement

MUST: every backup_targets row used by a policy resolves to storage in a different failure domain from the source server — different provider account at minimum, and region.country_code must satisfy the customer's data_residency_requirement. A policy violating this fails validation at write time.

14.3 Scheduling (fixes C2)

Backups are cron on the node with a control-plane heartbeat. The node runs the schedule; the platform records the outcome via an agent callback and, if no callback arrives within frequency + 2 h, raises a backup_missing alert and enqueues a remote-triggered run. A control-plane outage therefore delays reporting, not backups.

14.4 Retention and cost

Retention comes from plan_limits. expire-backups applies restic forget --prune with the daily/weekly/monthly counts. backups.size_bytes feeds usage_records metric backup_gb which feeds §17 cost allocation — backup storage is a real per-customer cost and the source's profitability model silently omitted how it is measured.

14.5 Restore drills (new — MUST)

Monthly, the restore-drill job picks a sample (all accounts over 90 days, ≥5% of accounts, minimum 3) and, for each: provisions a scratch account on a designated drill server, restores the latest full backup, asserts (a) restic check passes, (b) document root file count within 5% of source, (c) database restores and SELECT count(*) on the largest table is non-zero, (d) the site returns HTTP 200 on the preview subdomain. Result written to restore_drills. A failed drill is a critical alert. An account whose last three drills failed MUST NOT be marked as having backup protection in the customer portal.

14.6 Customer-initiated restore

Portal → select snapshot → choose scope → confirm with typed account code → creates a restores row in pending. Full-account restores require staff approval; file-only and single-database restores are self-service. Every restore first takes a pre-restore safety snapshot, so an accidental restore is itself reversible. Retained 7 days.

15. Monitoring, alerting and health 15.1 Collection Node/infra: Prometheus scrapes node_exporter, mysqld_exporter, nginx-prometheus-exporter on each hosting node over the platform's private path (WireGuard mesh or provider private network; public scraping is not permitted). Synthetic web checks: Blackbox exporter from ≥2 regions, every 60 s per website: HTTP status, TLS validity and expiry, response time, redirect chain, content match on an optional string. Account usage: panel adapter, hourly. Platform self-monitoring: §21.4. 15.2 Alert rules (seed set, each with for: duration to stop flapping) Key Condition For Severity server.down up == 0 2 m critical server.cpu_high p95 cpu > pool crit 15 m warning server.mem_high mem > crit 10 m warning server.disk_high disk > crit 5 m critical server.disk_predict_full linear predict full < 12 h 30 m critical server.load_high load1/cores > 4 10 m warning service.down nginx/php-fpm/mysql down 2 m critical website.down non-2xx/3xx from ≥2 probes 3 m critical website.slow p95 TTFB > 3 s 15 m warning ssl.expiring < 7 d — critical ssl.renewal_failed failures ≥ 2 — warning backup.failed last run failed — warning backup.missing no success in 2× interval — critical restore_drill.failed drill failed — critical provider.api_failing breaker open 5 m critical provider.orphan_resource untracked resource found — critical queue.depth_high any queue > 500 10 m warning queue.dlq_nonempty dlq > 0 15 m critical job.failure_rate > 5% over 30 m 30 m warning capacity.pool_exhausted no placeable server in pool — critical abuse.outbound_spam mail queue spike / port-25 attempts 5 m critical billing.webhook_lag Stripe webhook age > 15 m — warning 15.3 Notification routing

Dedupe by alerts.fingerprint; group by resource; suppress child alerts when the parent (server.down) is firing. Channels v1: email + generic webhook (Slack-compatible payload). Escalation: critical unacknowledged for 15 min → repeat; 30 min → secondary contact. Quiet hours apply to warning only, never critical.

15.4 Public status

status.<brand>.tld renders per-pool aggregated health only. MUST NOT name individual customers, providers, or server hostnames.

16. Billing and money 16.1 Money model (fixes C6) All amounts: bigint minor units + explicit char(3) currency. No floats anywhere, including in JSON responses (send {"amountMinor": 19900, "currency": "NZD"}). Base currency: NZD. Every report that aggregates across currencies converts to base. fx_rates is populated daily from a single named source (ECB + a NZD cross, or a paid feed). Rule (MUST): a cost or revenue amount is converted at the FX rate of its accrual date and the converted value is persisted (amount_base_minor, fx_rate). Reports never re-convert historical rows at today's rate — otherwise last quarter's margin changes every time someone opens the dashboard, which destroys trust in the number. Rounding: half-up at the line-item level, then sum. Tax computed per line, then summed; the invoice total is the sum of line totals, never a recomputation from the subtotal. This is the only way line totals and the grand total agree. Currency is chosen per customer at creation (customers.billing_currency) and is immutable. Changing it requires closing the account and opening a new one. 16.2 Stripe is not the source of truth

Decision: the platform owns subscriptions, periods, proration and invoices. Stripe is used for PaymentIntent (card charges), SetupIntent (saving a card), and webhooks. Do not use Stripe Subscriptions. Reasons: multi-currency + NZ GST + reseller margins + mid-cycle plan changes tied to infrastructure provisioning cannot be expressed in Stripe's model, and a divergence between Stripe's idea of a subscription and the platform's is an unfixable class of bug.

Webhooks: verify signature, persist raw event to stripe_events before processing, process idempotently by event.id, tolerate out-of-order delivery, reconcile daily against the Stripe API for anything missed.

16.3 Proration and plan changes Upgrade (higher price): immediate. Credit the unused portion of the current plan (unit_amount × remaining_days / period_days, floor to minor unit), charge the new plan prorated for the remainder, invoice immediately, provision the limit change on payment. If the new plan's isolation_tier differs, the upgrade triggers a migration (§18) and the account stays on the old limits until cutover. Downgrade (lower price): takes effect at current_period_end. No refund; the difference is not credited. Reason: prevents plan-cycling abuse, and the infrastructure cost was already committed. Stated in the plan terms. Downgrade validation (MUST): refuse if current usage exceeds the target plan's limits (storage, website count, database count). Show exactly which limit and by how much. Silently accepting produces an account that is instantly over quota. Period boundaries use the customer's timezone; a monthly subscription started on the 31st bills on the last day of shorter months. 16.4 Invoices Numbering is gapless per calendar year per legal entity, allocated from a Postgres sequence inside the issuing transaction: INV-2026-000042. Draft invoices get no number. A cancelled issued invoice keeps its number and is offset by a credit note. Immutability enforced by trigger: any UPDATE on an invoice whose status <> 'draft' that touches an amount, tax, line item, or customer field raises an exception. Allowed updates post-issue: status, amount_paid_minor, paid_at, pdf_object_key. PDF generation is a job; the PDF is stored in object storage and served via a signed URL with a 15-minute expiry. Regenerating a PDF MUST produce byte-identical content for the same invoice (deterministic template, no "generated on" timestamp). Invoice contains: seller legal name + GST number, buyer name + address + tax number, invoice number, issue date, due date, service period per line, line descriptions that never name a provider or server (§5.3 P1), tax label and rate, totals, payment instructions. 16.5 Tax

tax_rates is looked up by the customer's country (and region where applicable) at invoice-issue time and the resolved rate is snapshotted onto the invoice. Seed:

Country Rule NZ GST 15% on all supplies to NZ customers. Invoice must show "Tax Invoice", the supplier's GST number, and the GST amount. AU GST 10% to AU customers. If the customer supplies a valid ABN and is registered, B2B digital services may be zero-rated — validate the ABN against the ABR and record tax_number_validated_at; if unvalidated, charge GST. Other 0% by default, tax_label='No GST'. Flag for review at NZ$60k/year revenue per jurisdiction.

MUST: tax logic lives in packages/domain/billing/tax.ts as a pure function with a fixture table, and thresholds are configuration, not code. This is a "get an accountant to confirm" area; the platform's job is to make the rule visible and changeable, not to be a tax authority. A note to that effect belongs in the admin UI.

16.6 PCI scope

Stripe Elements / Payment Element in the browser; the platform receives only a payment_method id. No PAN, CVV, or expiry ever reaches platform code, logs, or the database. This keeps the business on SAQ-A. A code-review rule and a log-scrubbing filter (regex for card-shaped numbers) enforce it. Bank transfers are reconciled manually or via a bank feed; a payments row with method='bank_transfer' requires a finance actor and a reference.

16.7 Overage

plan_limits.overage_policy:

block (default for entry plans): at 100% storage the account goes read-only for uploads (panel quota does this natively); customer is notified at 80%, 90%, 100%. bill: usage above the limit accrues to usage_records and is invoiced at the plan's overage rate on the next invoice. Requires a customer-visible rate and a monthly cap. notify_only: for enterprise accounts under contract.

Bandwidth is measured from nginx logs aggregated hourly per account. "Unmetered" plans still have a fair-use ceiling (§19.2) — unmetered means unbilled, not unlimited.

17. Cost and profitability

The source's dashboards (§39–41) are good products built on undefined arithmetic. Here is the arithmetic.

17.1 Cost ingestion

Daily job per provider account writes provider_cost_records:

AWS: Cost & Usage Report delivered to S3, parsed at line-item granularity, mapped to server_id via the server_code tag. Untagged spend goes to a shared_overhead bucket. OVH: /me/bill for issued bills plus current usage endpoints. OVH bills monthly, so daily records are the monthly cost divided by days in month, marked is_estimate=true until the bill arrives, then reconciled. Backup storage: measured from the S3 API (ListObjectsV2 sizes per prefix, so per-account) × backup_targets.storage_cost_per_gb_month_minor. This is measured, not estimated. Every record is converted to base currency at that day's rate and persisted (§16.1). 17.2 Allocation to accounts

Monthly job, cost_allocations. For a server S in month M:

serverCost(S,M) = Σ provider_cost_records where server_id = S accountDays(a,M) = days the account existed on S during M weight_storage(a) = plan_limits.storage_mb(a) × accountDays(a) weight_compute(a) = plan_limits.cpu_quota_pct(a) × accountDays(a)

computeShare(a) = serverComputeCost(S,M) × weight_compute(a) / Σ weight_compute storageShare(a) = serverStorageCost(S,M) × weight_storage(a) / Σ weight_storage bandwidthShare(a) = measured bandwidth_gb(a) × serverBandwidthCost / Σ measured backupCost(a) = measured backup bytes(a) × target rate [direct, not allocated] paymentFee(a) = Σ payments.fee_minor attributable to a's subscription in M supportCost(a) = ticket minutes(a) × configured hourly support rate / 60 (0 if time tracking is off — never guess) overhead(a) = shared_overhead(M) × (a's direct cost / Σ direct cost)

totalCost(a,M) = computeShare + storageShare + bandwidthShare + backupCost + paymentFee + supportCost + overhead

allocation_basis stores every input for that row. MUST: the sum of all cost_allocations.total_minor for a period equals the sum of provider_cost_records for that period ± 1 minor unit (rounding). A reconciliation assertion runs after the job and alerts on drift — an allocation model that does not add up is worse than none.

Empty capacity is deliberately not allocated to customers; it lands in shared_overhead and shows on the dashboard as "unallocated capacity cost", which is the number that tells the business it bought too many servers.

17.3 Reports Per-customer P&L: revenue recognised in the period (see below) − allocated cost. Revenue recognition (MUST): an annual invoice of NZ$199 is recognised at NZ$16.58/month over 12 months, not NZ$199 in month one. Deferred revenue is tracked in revenue_schedules (subscription_id, period, amount_minor). Without this, every monthly margin report is fiction. This is the single most common error in hosting-SaaS dashboards and the source SRS reproduced it in §39–41. Per-server P&L: Σ recognised revenue of accounts on the server − server cost. Includes an "accounts needed to break even" figure and a "months to payback" figure. Pool utilisation vs cost: cost per active account per pool, trended — this is the number that decides whether to buy bigger or more servers. Cost optimisation report (replaces source §44's "engine"): lists accounts whose allocated cost exceeds a configurable multiple of the cheapest compliant alternative, excluding any account with a hard placement constraint (residency, provider preference, isolation tier) — this is the fix for C4. Output is a ranked list with the estimated saving and the migration effort; a human decides. 18. Migration engine

The riskiest subsystem. The source treated "switch DNS" as one box; it is the step that can lose a customer's orders.

18.1 Strategy: rsync + cutover planned → precheck → syncing → verifying → awaiting_cutover → cutover → monitoring → completed any → rolled_back | failed 18.2 Steps precheck — target server passes placement hard constraints; disk headroom on target ≥ source usage × 1.3; PHP/MySQL versions compatible (or an explicit override with a recorded acknowledgement); source has a successful backup < 24 h old; domains.dns_managed_by known; current TTL recorded. lower_ttl — if platform-manages DNS, set all A/AAAA records for the account's domains to TTL 60. Then wait at least the old TTL before cutover (recorded in ttl_lowered_at; the earliest legal cutover is ttl_lowered_at + old_ttl + 5 min). If DNS is external, email the customer with the required TTL change and block the migration until a DNS query confirms TTL ≤ 300. create_target_account — panel account on the target with identical username, limits, PHP version, and domains. Site served on the preview subdomain (§13.1c). sync_1 (hot) — rsync -aHAX --delete while the source is live. Repeat until the delta is small. Databases are not synced in this phase. verify_hot — preview subdomain returns 200; file counts within tolerance. awaiting_cutover — requires approval (§18.6) and a scheduled window. cutover (the only downtime, target < 5 min): a. Put the source account into maintenance: nginx returns 503 for the account's domains and writes are blocked. This freeze is mandatory — without it, orders placed between the final dump and the DNS switch are lost, and the customer will not forgive it. b. Final rsync delta. c. mysqldump --single-transaction on source → import on target. Record row counts of the 10 largest tables on both sides and assert equality. d. Rewrite anything holding the old IP (WordPress siteurl/home only if changing hostname; normally unchanged). e. Issue/copy TLS on target and verify the chain. f. Flip DNS A/AAAA to the target IP. g. Keep the source serving a 307 redirect to the target IP for stragglers on cached DNS, for 48 h. h. Lift maintenance on target. monitoring — 24 h of elevated synthetic checks; error-rate comparison against the pre-migration baseline; automatic rollback offer if 5xx rate exceeds baseline + 2%. completed — restore original TTL; source_retained_until = cutover + 14 days; a scheduled job deletes the source account after that date, only if the target has had ≥3 successful backups. 18.3 Rollback

Valid until rollback_deadline (default cutover + 24 h). Rollback = re-freeze target, dump target DB → source, rsync target → source, flip DNS back, lift source. MUST: rollback replays data back to the source; a rollback that simply re-points DNS to a stale source silently discards every write since cutover. Test this in M9.

18.4 Cross-provider specifics

Same flow. Extra steps: firewall rules on the target must permit rsync from the source public IP for the sync window and be removed after; transfer cost is recorded against provider_cost_records category bandwidth; if regions differ, the pre-check warns about latency changes to the customer's own external services.

18.5 Bulk / drain

drain-server creates one migrations_ops per account with a concurrency cap of 2 and a per-account cutover window, so a server evacuation is a queue of individually reversible migrations rather than one large irreversible event.

18.6 Approvals

migration.execute requires a second staff approver (approved_by <> requested_by) for any migration touching a production account. Dry-run mode performs steps 1–5 and stops. Every migration writes a timeline to audit_log with per-step durations.

19. Abuse, fair use and email 19.1 Email — explicitly out of scope for v1

The platform does not host mailboxes. Plans state "email not included; DNS records for your email provider are supported". plan_limits has no mailbox fields. Rationale: IP reputation, deliverability, spam filtering, and storage growth make mail a separate product with its own infrastructure, and putting mail on the web nodes is what gets a provider's whole IP range blocklisted. Phase 3 revisits with a dedicated mail cluster.

Outbound application mail (a contact form) is supported via a platform SMTP relay with a per-account rate limit (default 200/day), authenticated submission only, and From domain verification. Port 25 outbound stays blocked on the nodes (§12.4).

19.2 Abuse and the noisy neighbour

This is the top operational cost of shared hosting and the source omitted it entirely.

Resource fencing: per-account cgroup CPU/memory/IO from plan_limits, per-user PHP-FPM pools with pm.max_children = php_workers. An account cannot consume the node. Malware scanning: ClamAV + a PHP-shell signature set, daily incremental scan of each account's document root. A detection creates an alerts row, quarantines the file to /quarantine/<account>/ (never deletes), and notifies the customer. Outbound spam containment: port 25 blocked; relay rate limits; alert on any account exceeding 3× its 7-day mail baseline. Application vulnerability nudging: detect WordPress/plugin versions from the filesystem, compare against a CVE feed, notify the customer with a severity. Do not auto-update customer code. Fair use on "unmetered": a soft ceiling (e.g. 1 TB/month, 20% sustained CPU over 24 h) that triggers a conversation, not a suspension, and is written in the plan terms. Abuse workflow: abuse@ contact per customer (§4.2), a ticket category, a documented 24 h response SLA, and a hosting_account.suspend path with reason abuse that is exempt from the billing dunning flow. 20. Order → active, dunning, suspension, termination 20.1 Order to active order created (subscription: pending_payment) → invoice issued (draft → issued) → payment succeeded [webhook or manual] → subscription: provisioning → saga 'provision-hosting-account' (§11.3) → subscription: active, hosting_account: active → welcome notification (panel URL, temp credentials via one-time link, next steps)

Credentials are delivered as a one-time-view link (single use, 24 h expiry, logged), never in the email body.

20.2 Capacity exhaustion (fixes C7)

If placement returns no_capacity and autoscale is off: subscription → awaiting_capacity (a substate of provisioning with its own timer), capacity.pool_exhausted critical alert, customer emailed with an honest ETA, and billing is not started — subscription.started_at and the first service period begin at activation, not at payment. If not resolved within 48 h, an automatic full refund is offered. Never bill for hosting that does not exist.

20.3 Dunning

Configurable per plan; defaults, driven by dunning_events:

Offset Action −30 d Renewal notice with amount and date −14 d Reminder −7 d Final reminder; card retried if saved Day 0 Invoice due; auto-charge attempt 1 +1, +3, +7 d Auto-charge retries (exponential; stop on hard decline) +3 d "Payment overdue" email; subscription → past_due +7 d Second notice + portal banner +14 d Final notice: "suspension in 3 days" +17 d Suspension (§20.4) +47 d Termination notice (14 days out) +61 d Termination (§20.5)

Hard declines (card cancelled/stolen) skip to the next human touchpoint rather than retrying. Every dunning email includes a one-click pay link.

20.4 Suspension

Idempotent and fully reversible. On suspend: panel account suspended (nginx serves a branded suspension page, HTTP 503 with Retry-After), FTP/SSH disabled, panel login disabled, cron disabled, databases left running but not reachable from the web, backups continue, files untouched. On payment: resume job reverses every step and asserts the site returns 200 within 5 minutes; failure raises a critical alert, because a customer who has paid and is still down is the worst possible state.

Suspension for abuse uses the same mechanism with a different reason and does not auto-resume on payment.

20.5 Termination and data deletion suspended (≥ retention window, default 45 d) → final notice (14 d before) → terminal backup taken and pinned for 90 d, off-server, encrypted → panel account deleted, DNS records removed, databases dropped, ssl revoked, monitoring targets removed → hosting_account: terminated → after 90 d: terminal backup deleted; backup repository destroyed → after 7 years: customer PII minimised (name, email, address redacted); invoices retained in redacted form for tax law

Requires: a hosting.terminate permission, a typed confirmation of the account code, and — for accounts with >NZ$1,000 lifetime revenue — a second approver. A customer-initiated data export (files + database dumps as a downloadable archive, 7-day signed URL) MUST be available from the portal at any time before deletion, and is offered automatically in the final notice.

21. Non-functional requirements and platform observability 21.1 Split planes (fixes C2) Plane Contents Availability target Failure behaviour Data plane Hosting nodes: nginx, PHP-FPM, MySQL, panel, node-local cron for SSL and backups 99.9% per node; pool-level SLA in plan terms Independent of the control plane. A total control-plane outage is invisible to visitors. Control plane API, workers, scheduler, portals, database 99.5% Degrades: no new provisioning, no dashboard, no billing runs. All catch up on recovery because every action is an idempotent job.

MUST: an automated test ("control-plane blackout drill", quarterly) stops the entire control plane for 30 minutes and asserts: all sample sites serve 200 throughout, SSL renewal that falls due during the window still happens on-node, backups still run, and on recovery no duplicate invoices, charges, or provisioning actions occur.

21.2 Performance budgets Operation Target Portal/admin API read, p95 < 300 ms Portal/admin API read, p99 < 800 ms Any write endpoint (enqueue + return), p95 < 500 ms Admin list views (10k rows, paginated) p95 < 700 ms Placement decision (pure function, 500 candidates) < 50 ms Provision hosting account (order → live), p50 / p95 < 3 min / < 8 min Provision new server (empty → active) < 15 min Invoice run for 5,000 subscriptions < 10 min Job pickup latency (queue → running), p95 < 5 s

MUST: no endpoint issues an unbounded query. Every list endpoint is cursor-paginated with a hard limit ≤ 100. N+1 detection runs in CI against the e2e suite.

21.3 Scale targets

v1 correctness at 200 customers / 1,000 sites / 25 servers. Architecture must reach 10,000 customers / 50,000 sites / 1,000 servers without changing the adapter or job model. Concretely, that means: no per-server polling loop in the API process (workers only), metrics in Prometheus not Postgres, server_metrics partitioned, and audit_log partitioned monthly with an archival job to object storage after 13 months.

21.4 Platform self-observability

OpenTelemetry traces on every request and job, with correlation_id propagated from HTTP → outbox → job → adapter → provider call, and stamped into audit_log. One trace ID should explain an entire provisioning. Golden signals dashboard: queue depth and age per queue, job success/failure rate by name, adapter call latency and error kind by provider, webhook lag, outbox backlog, DB connection saturation, saga compensation rate.

21.5 Disaster recovery for the control plane

RPO 5 min (Postgres PITR with WAL archiving to object storage in a second provider), RTO 4 h. Backups of the control-plane database restored and smoke-tested monthly. Provider credentials and backup encryption keys have a documented, tested recovery procedure held outside the platform — if Secrets Manager and the platform are lost together and the keys are irrecoverable, every customer backup becomes undecryptable ciphertext. This is the single worst failure mode in the design; treat the break-glass procedure as a first-class deliverable, not documentation.

22. Security 22.1 Baseline

HTTPS only (HSTS with preload); TOTP MFA mandatory for all staff and reseller users, optional but encouraged for customers; Argon2id password hashing; session timeout 8 h idle / 24 h absolute for staff; IP allowlist available per staff user and mandatory for super_admin; CSP without unsafe-inline; strict CORS; rate limits (auth 5/min/IP, API 100/min/token, provisioning 10/hour/customer).

22.2 Credentials — the hard rule

Provider API keys, panel API keys, SSH keys, database passwords, backup encryption keys: stored only in AWS Secrets Manager. The database stores a *_ref path, never a value, never a ciphertext blob the app can decrypt on its own.

MUST:

No API endpoint returns a secret value to any actor, including super_admin. Workers fetch secrets at use time with a 5-minute in-memory cache, never at boot into a long-lived variable. A log-scrubbing middleware redacts anything matching secret-shaped patterns and any key named password|secret|token|key|hash|credential at any nesting depth, applied to application logs, job payloads persisted to jobs.payload, HTTP error bodies, and audit before/after diffs. Rotation: provider keys 180 d, panel keys 90 d, SSH CA 365 d, backup keys never rotated without a re-encryption plan (rotation of a backup key must not orphan existing snapshots — implement as key-per-epoch with old keys retained). Customer-facing credentials (initial panel password, DB passwords) are generated, delivered once via a one-time link, and stored as a Secrets Manager ref that the platform can rotate but not display. A CI secret scanner (gitleaks) blocks merges. 22.3 SSH

Short-lived certificates from an internal CA, 24 h validity, issued per-job to the worker that needs them, principal-scoped to a single host. No shared keys, no key files on disk, no ssh from a developer laptop to a production node except through a bastion that records the session.

22.4 Privacy and residency customers.data_residency_requirement is a hard placement constraint (§9.2) and is additionally enforced for backups (§14.2) and for any log or metric export. NZ Privacy Act 2020 IPP 12: offshore disclosure requires comparable safeguards. The platform records, per customer, the countries their data resides in, and surfaces it in the portal. A change of residency country requires a migration, not a config flip. Data subject requests: export (§20.5) and deletion, both with an audited workflow and a 30-day SLA. PII in logs is redacted; support screens show masked emails/phones with an audited reveal action. 22.5 Application security

Parameterised queries only (Prisma); Zod validation at every boundary; output encoding by React; no dynamic shell string interpolation in the panel adapter — execFile with an argument array, never exec with a template string (this is the most likely RCE in the whole codebase, since panel commands take user-controlled domain and username strings); SSRF protection on any customer-supplied URL (blocklist RFC1918, link-local, metadata endpoints); file upload type and size validation; dependency scanning in CI.

22.6 Audit

audit_log is append-only at the database-role level (REVOKE UPDATE, DELETE). Every mutation records actor, action, resource, before/after diff, IP, correlation id, result, and — for destructive actions — a mandatory human-entered reason. Audit rows are written in the same transaction as the change. Retention 7 years, partitioned monthly, archived to object storage with a checksum manifest after 13 months.

23. API and frontend conventions 23.1 API /api/v1, REST, cursor pagination, RFC 9457 problem details, X-Correlation-Id echoed. Mutations that touch infrastructure return 202 Accepted with { jobId, statusUrl, resource }. Clients poll statusUrl or subscribe to SSE at /api/v1/jobs/:id/events. Idempotency-Key header supported (and required for order creation and payment endpoints), backed by idempotency_keys with a 24 h window. OpenAPI 3.1 generated from the Zod contracts; the generated client in packages/contracts is the only HTTP client the frontends use. Resources: customers, contacts, plans, subscriptions, invoices, payments, credits, refunds, providers, provider-accounts, regions, server-types, pools, servers, hosting-accounts, websites, domains, dns-records, databases, ftp-users, ssl, backup-policies, backups, restores, migrations, alerts, tickets, jobs, audit-logs, reports/*. Customer-scoped endpoints live under the same paths; scoping is by actor, not by URL prefix, so there is exactly one authorisation code path. 23.2 Frontend Server Components for reads; Server Actions only for trivial mutations, otherwise the generated client. TanStack Query for anything polling a job. Every destructive action: typed-confirmation dialog + a required reason field. Admin must render the placement trace (§9.1), the job/saga timeline, and the audit diff as first-class views. These three screens are what make the system operable, and they are usually the first thing cut and the first thing missed. Portal shows: plan, usage bars with limits, websites, domains with DNS status, SSL status, backup status including last successful restore drill, invoices, payment method, tickets. It shows no provider, pool, server code, or plan-internal identifiers. 24. Build order

Each milestone ends with a command that must pass. Do not proceed past a red milestone. Each milestone should be a separate PR.

M Scope Definition of Done M0 Monorepo, Docker Compose (Postgres, Redis, MinIO, mailhog), CI (lint, typecheck, test, migrate), OTel wiring, packages/contracts skeleton pnpm verify green in CI; docker compose up gives a working stack M1 Full Prisma schema (§4), migrations, seed (roles, permissions, tax rates, a plan, a pool, fx rates), repository base with tenant guard, RLS policies Migration up/down clean; tenant-guard unit tests pass; RLS integration test denies cross-tenant read M2 Identity: registration, login, MFA, sessions, API tokens, RBAC decorators, audit middleware, correlation ids e2e: every seeded role hits an allowed and a denied endpoint; the "no route without @RequirePermission" lint test passes M3 CRM + Catalog CRUD, plan versioning rule, admin shell UI Creating a subscription against a plan then editing plan limits produces version 2 and leaves the subscription on v1 M4 Job infrastructure: BullMQ setup, jobs table, idempotency, saga runner with compensation, outbox + publisher, DLQ, admin job viewer Chaos test: kill the worker mid-saga, restart, saga resumes and completes exactly once; duplicate enqueue is a no-op M5 adapters-cloud/core + provider_operations idempotency table + OVH adapter + AWS adapter, against recorded fixtures and one real sandbox account Contract test suite runs identically against both adapters; simulated timeout-then-retry adopts the existing resource rather than creating a second M6 Server provisioning: Ansible roles, cloud-init, provision-server saga, smoke test, reconciliation jobs A real server is created, hardened, panel-installed and reaches active unattended; a second Ansible run reports zero changes; deleting the DB row and re-running reconciliation detects the orphan M7 Panel adapter (Hestia) + placement engine + provision-hosting-account saga + capacity computation ≥30 placement fixtures pass; an order provisions a live, reachable site end to end; placement trace renders in admin M8 DNS (Cloudflare), SSL issuance and the expiry reconciler, website + database + FTP management, customer portal v1 A domain provisioned end to end serves valid HTTPS; killing the control plane does not prevent an on-node renewal M9 Backups, restores, restore drills, migration engine incl. rollback Migration e2e: write data, cutover, verify no writes lost during freeze; then roll back and verify data written after cutover survives the rollback M10 Billing: invoicing, tax, proration, Stripe, dunning, suspension, reactivation, termination Billing simulation over 400 simulated days with clock control: renewals, an upgrade, a downgrade, a failed card, suspension, reactivation, termination — assert every invoice, credit and state transition against a golden fixture M11 Monitoring, alerts, notifications, status page, abuse tooling (§19.2) Killing nginx on a node produces exactly one deduped critical alert and one notification within 3 minutes M12 Cost ingestion, allocation, revenue recognition, profitability dashboards Allocation reconciliation assertion passes on seeded data; monthly margin for an annual invoice is 1/12, not lumped M13 Hardening: load test to 10× v1 scale, control-plane blackout drill, pen-test checklist, runbooks, DR restore rehearsal Blackout drill passes (§21.1); p95 budgets in §21.2 met under load

Phase 2 (after M13): Virtualmin adapter, resellers, usage-based billing, advanced monitoring, auto-balancing recommendations, registrar integration. Phase 3: additional providers, managed WordPress, mail cluster, CDN/WAF products, cross-provider DR.

25. Test strategy Unit (packages/domain) — placement, billing, tax, proration, allocation, state machines. Target 95% branch coverage here specifically; this is where the money and the correctness live and it has no I/O, so there is no excuse. Contract tests for adapters — one suite executed against every implementation of CloudProvider and HostingPanel. A new provider is "done" when this suite is green. Recorded HTTP fixtures (Polly/nock) for CI, plus a nightly run against real sandbox accounts. Integration (Testcontainers) — repositories, RLS, jobs, sagas, outbox, migrations. Chaos — worker kill mid-saga; provider 429/500/timeout injection; duplicate webhook delivery; out-of-order webhooks; clock skew; database failover. e2e (Playwright) — the eight journeys: signup→live site; upgrade; downgrade attempt over quota; failed payment→suspend→pay→resume; backup→restore; migration→rollback; domain add with SSL; termination with export. Time-travel harness — a controllable clock so a 400-day billing simulation runs in seconds. Build this in M4; retrofitting it is painful. Security — automated: cross-tenant route sweep (§5.2), secret-leak scan of API responses and logs, dependency audit, ZAP baseline. 26. Open questions for the business

These need answers from the operator, not the developer. Each blocks a specific milestone.

Legal entity and GST registration — needed for invoice content and tax seed (M10). SLA offered to customers — uptime %, credits, support response times. Drives §15 thresholds and plan terms. Support cost tracking — will staff log ticket time? Without it, §17.2's supportCost is zero and per-customer margin is overstated. Decide before M12. Refund policy — for the failed-provisioning and capacity-exhaustion cases (§20.2). Backup retention beyond termination — 90 days is proposed; confirm against any contractual or legal requirement. Minimum node size and target accounts per node — sets the economics; §9.4 and §17.3 need real numbers to be useful. Which entity is the merchant of record for reseller customers — determines whether reseller billing is agency or resale, which changes the tax treatment entirely. Answer before Phase 2 starts, not during it.

Markdown source
Multi-Cloud Hosting Management Platform — Build Specification

Version: 2.0 (supersedes SRS 1.0) Type: Executable build spec for an AI coding agent Status: Normative. Every "MUST" is a test case.

0. How to use this document

This is not an SRS. An SRS describes what a system should do; this describes what to type. The source SRS 1.0 was a good scope document and a poor build document, because almost every technically interesting decision in it was deferred with the words may, should, possible, or recommended. An AI coding agent handed that document will invent those decisions inconsistently across sessions and produce a codebase that does not compose.

Rules for the implementing agent:

Nothing in §2 (Locked Decisions) is negotiable. Do not substitute libraries, rename tables, or "improve" the folder layout. Consistency across sessions is worth more than any local optimum.
Build in the order given in §24. Each milestone has a Definition of Done that is a runnable command. Do not start milestone N+1 until milestone N's command passes.
Where this document says MUST, write a test. Where it says SHOULD, use judgement. Where it says LATER, write nothing — not a stub, not an interface, not a TODO.
Any provider-specific or panel-specific string outside packages/adapters-* is a bug. This is the single most important architectural constraint in the system. See §7.
Every infrastructure mutation goes through a job with an idempotency key. No controller ever calls AWS, OVH, or HestiaCP synchronously. See §11.
When this document and the original SRS disagree, this document wins. §1 explains why.
1. Analysis of SRS 1.0 — what was wrong, and what is now decided

The following is the diff in reasoning, not just in text. Read it; it explains the shape of everything below.

1.1 Contradictions in the source
#	Contradiction	Resolution in this spec
C1	§6 demands hard tenant isolation ("one customer must never access another's files") while §9 sells shared hosting, where all tenants share a kernel, a MySQL instance, and a PHP-FPM pool.	Isolation is redefined as a tiered guarantee (§5.1). Shared tier gets OS-user + open_basedir + per-user FPM pools and is documented to the customer as shared. Isolated tier gets a dedicated VM. Selling "isolation" on a shared box is a liability, not a feature.
C2	§67 targets 99.9% for the control plane and also says customer sites must survive control-plane failure. Under §18, provisioning, SSL renewal and backups all originate in the control plane — so control-plane downtime does degrade customer service.	Split explicitly into data plane (servers keep serving; no dependency on control plane) and control plane (99.5% target, degrades gracefully). SSL renewal and backups are made server-resident cron with control-plane reconciliation (§13.4, §14.3), so a 6-hour control-plane outage cannot expire a certificate.
C3	§34 suspends hosting for non-payment but §67 says the platform must not affect customer sites.	Suspension is an intentional data-plane mutation, not an availability event. Called out as such; suspension is executed by a job that must be idempotent and reversible within the retention window (§20.4).
C4	§44 Cost Optimization Engine recommends migrating customers from AWS to OVH to save money, while §14 says some customers are on AWS for compliance or contractual reasons. Naive cost optimisation would recommend illegal migrations.	The placement engine gets hard constraints (never violated) separated from soft scores (optimised). Cost is only ever a soft score. See §9.
C5	§75 says the customer must not know the provider; §20 requires customer-managed DNS and §37 gives customers backup and database access — all of which leak the server hostname and IP.	Provider opacity is redefined as product opacity: the customer's plan never names a provider, and the platform must be able to migrate them without a product change. The customer still sees an IP and a panel hostname. Guarantee is now testable (§5.3).
C6	§29–33 bill in NZD/AUD/USD, but §39 sums provider costs (billed in USD/EUR) into a single NZD figure with no stated FX policy. Margin numbers would be silently wrong.	Money model is fully specified in §16.1: integer minor units, currency on every amount, explicit FX rate table with rate_date, and a rule that costs are converted at accrual date, not report date.
C7	§13 forbids provisioning onto a server above threshold; §43 auto-balancing moves accounts to servers. Nothing defines what happens when every server in a pool is above threshold and autoscaling is off.	Explicit terminal state: placement returns NO_CAPACITY, the order goes to awaiting_capacity, an alert fires, and the customer is not billed until active (§20.2, and §52 of the source is upgraded to a hard rule).
1.2 Gaps — required by the business, absent from the source

These are the things that will bite this project in month four. Each now has a section.

Email hosting. §9 lists "email accounts if supported" as a plan attribute and §21 requires MX/SPF/DKIM/DMARC records — but there is no mailbox management, no quota, no deliverability, no IP-reputation, no abuse handling. Shared hosting without a decided email answer is a trap. Decision: email is out of scope for v1 (§19.1). Plans sell DNS records pointing at an external provider. Revisit at Phase 3 with a dedicated mail-cluster design, never on the web nodes.
Abuse, malware and the noisy-neighbour problem. The single largest operational cost in shared hosting is a compromised WordPress install sending spam or eating a whole CPU. The source has no scanning, no resource fencing, no abuse workflow. See §19.2 — this is a v1 requirement, not a nicety.
Tax. NZ GST is 15% and invoices have legal content requirements; AU has GST + ABN validation; US sales tax on SaaS varies by state. §31 has a Tax field and no rules. See §16.5.
PCI scope. §32 says "Stripe" but not how. If card data touches the app the business inherits PCI-DSS SAQ-D. Decision: Stripe Elements + PaymentIntents only, SAQ-A. No PAN ever reaches the platform (§16.6).
Domain registrar. §20 tracks domain expiry dates and §61 sends "Domain Expiring" notices, but no registrar integration exists to read those dates or renew. v1 reads expiry via RDAP and never registers domains (§13.5).
Data residency and the NZ Privacy Act 2020. §14 mentions compliance abstractly. IPPs 11/12 govern offshore disclosure. Concrete requirement in §22.4.
Backup restore testing. §24–26 create and restore backups; nothing verifies a backup is restorable. An untested backup is not a backup. §14.5 makes monthly restore drills a scheduled job with a pass/fail record.
Termination and data deletion. §35 deletes accounts; nothing covers the deletion of backups, PII, logs, or the customer's right to an export. §20.5.
Reseller nesting. §7.5 introduces resellers whose customers are also tenants — a second tenancy dimension that changes every query in the system. Deferred to Phase 2, but the schema in §4 carries reseller_id from day one so it is not a rewrite.
Rate limits and quota on the provider APIs. AWS and OVH both throttle. A provisioning burst will hit 429s. §7.4 mandates a per-provider-account token bucket.
Clock, DNS TTL and migration cutover. §42 lists "switch DNS" as one box in a flow. In practice this is the only step that can lose customer data (writes to the old node after cutover). §18 specifies the TTL lowering schedule and the read-only freeze window.
Observability of the platform itself. §27 monitors customer servers. Nothing monitors the queue depth, job failure rate, or webhook lag of the platform. §21.4.
1.3 Things the source over-specified and should not build in v1

Scope discipline matters more than feature count. Cut from v1, with reasons:

Auto-balancing (§43) — needs a year of production telemetry to tune. Building it early produces a system that shuffles customers for no reason.
Cost Optimization Engine (§44) — a report, not an engine. v1 ships the report.
Provider failover (§45) — cross-provider DR for shared hosting is a multi-quarter project and is not what a NZ$199/yr customer is buying. Phase 3.
Six notification channels (§28) — v1 ships email + one webhook (Slack-compatible). SMS and WhatsApp add compliance and cost for marginal value.
Both HestiaCP and Virtualmin (§5) — v1 ships HestiaCP only. The adapter interface (§8) is what proves the abstraction, not a second implementation nobody uses.
2. Locked decisions

Do not revisit these.

2.1 Stack
Concern	Decision	Notes
Runtime	Node.js 22 LTS, TypeScript 5.6, strict: true	noUncheckedIndexedAccess on
API framework	NestJS 10	Module-per-bounded-context
Database	PostgreSQL 16	One database, schema-per-concern not used; plain public
ORM	Prisma 5	Migrations are the only DDL path
Queue	BullMQ 5 on Redis 7	Separate Redis DB from cache
Cache / locks	Redis 7 (ioredis)	Redlock for distributed locks
Frontend	Next.js 15 App Router, React 19	Two apps: admin, portal
UI kit	Tailwind 4 + shadcn/ui + TanStack Table/Query	No other component library
Auth	Better-auth (sessions) + TOTP MFA	Not NextAuth; needs org/tenant model
API auth (machine)	OAuth2 client-credentials + scoped PATs	JWT RS256, 15-min access, refresh rotation
Validation	Zod at every boundary	Shared schemas in packages/contracts
Payments	Stripe (PaymentIntents + Billing for cards), manual bank transfer	Stripe is not the source of truth for subscriptions; see §16.2
Object storage	S3 API (AWS S3 + OVH Object Storage, same client)	@aws-sdk/client-s3 against both
Secrets	AWS Secrets Manager (prod), .env + SOPS (dev)	§22.2
Server config mgmt	Ansible, invoked from a worker via ansible-runner	Not shell-over-SSH ad hoc
Metrics ingest	Prometheus node_exporter on each hosting node, scraped by the platform's Prometheus; platform reads via PromQL	Not custom agents
Platform observability	OpenTelemetry → Grafana/Tempo/Loki	§21.4
Tests	Vitest (unit), Testcontainers (integration), Playwright (e2e)	
Monorepo	pnpm workspaces + Turborepo	
2.2 Repository layout
hosting-platform/
├── apps/
│   ├── api/                    NestJS HTTP API (no queue processing)
│   ├── worker/                 BullMQ processors (no HTTP except /health)
│   ├── scheduler/              Cron producers only; enqueues, never executes
│   ├── admin/                  Next.js admin portal
│   └── portal/                 Next.js customer portal
├── packages/
│   ├── contracts/              Zod schemas + generated OpenAPI + TS types
│   ├── db/                     Prisma schema, migrations, seed, repositories
│   ├── domain/                 Pure business logic. No I/O. Heavily unit-tested.
│   │   ├── placement/          Provider/server selection engine (§9)
│   │   ├── billing/            Proration, dunning, tax, FX (§16)
│   │   ├── costing/            Allocation + margin math (§17)
│   │   └── state/              State machines (§10)
│   ├── adapters-cloud/         CloudProvider implementations (§7)
│   │   ├── core/               Interface, errors, retry, rate limiting
│   │   ├── aws/
│   │   └── ovh/
│   ├── adapters-panel/         HostingPanel implementations (§8)
│   │   ├── core/
│   │   └── hestia/
│   ├── adapters-dns/           DNS providers (Cloudflare v1)
│   ├── adapters-storage/       S3-compatible backup targets
│   ├── adapters-payment/       Stripe + manual
│   ├── jobs/                   Job name constants, payload schemas, saga defs
│   └── ui/                     Shared React components + design tokens
├── infra/
│   ├── ansible/                Node build playbooks (§12.3)
│   ├── terraform/              Platform's OWN infrastructure only
│   └── docker/
└── docs/

Rule: packages/domain MUST NOT import from packages/db, any adapter, or any Node built-in that performs I/O. It takes plain data in and returns plain data out. This is what makes the placement engine and billing math testable without a database, and it is the difference between a project that can be safely modified in month nine and one that cannot.

2.3 Naming and conventions
Tables: snake_case, plural. Columns: snake_case. Prisma models: PascalCase singular.
Primary keys: id uuid PRIMARY KEY DEFAULT gen_random_uuid(). No auto-increment, ever — IDs appear in URLs and cross provider boundaries.
Every business table has a human-facing short code as well: HST-000123, INV-2026-0042. Sequence-backed, never reused. Support staff read these aloud on the phone.
Timestamps: timestamptz, always UTC. Column names created_at, updated_at, deleted_at. Business dates that are dates (invoice date, service period) are date in the customer's timezone, resolved at write time.
Money: amount_minor bigint + currency char(3). Never a float. Never a bare amount. Lint rule enforced.
Enums live in Postgres as native enums and are mirrored in packages/contracts.
Soft delete only where legally needed (invoices, audit). Everything else hard-deletes with ON DELETE RESTRICT and an explicit archival path.
API: REST, /api/v1, plural nouns, cursor pagination (?cursor=&limit=), application/problem+json for errors (RFC 9457).
3. Bounded contexts

Nine modules. Cross-module communication is via domain events on an outbox (§11.6), never by reaching into another module's tables.

Context	Owns	Key invariant
Identity	users, roles, permissions, sessions, MFA, API tokens	Every request resolves to exactly one actor + one tenant_scope
CRM	customers, contacts, addresses, resellers	A customer belongs to exactly one owner org (platform or reseller)
Catalog	hosting_plans, plan_limits, plan_prices, server_pools binding	A plan's limits are immutable once a subscription references it; changes create a new plan version
Subscriptions	subscriptions, subscription_items, lifecycle	A subscription is never active without a provisioned hosting_account
Billing	invoices, invoice_items, payments, credits, refunds, tax, fx	An issued invoice is immutable; corrections are credit notes
Infrastructure	providers, provider_accounts, regions, server_types, servers, server_pools, capacity	A server's recorded state is reconciled from the provider, never assumed
Hosting	hosting_accounts, websites, domains, dns_records, databases, ftp_users, ssl_certificates	A hosting_account exists on exactly one server at a time
Data Protection	backup_policies, backups, restores, restore_drills	Every hosting_account has ≥1 active policy with an off-server target
Operations	jobs, sagas, migrations, alerts, incidents, tickets, audit_log	Every infrastructure mutation has an audit row and a job row
4. Data model

Complete enough to generate schema.prisma directly. Types are Postgres.

4.1 Identity
sql
users (
  id uuid pk, email citext unique not null, name text not null,
  password_hash text, -- null for SSO-only
  mfa_secret_encrypted bytea, mfa_enabled boolean not null default false,
  mfa_recovery_codes_hashed text[], 
  type user_type not null,            -- 'staff' | 'customer' | 'reseller'
  customer_id uuid null refs customers,   -- set iff type='customer'
  reseller_id uuid null refs resellers,   -- set iff type='reseller'
  status user_status not null default 'active', -- active|disabled|locked
  last_login_at timestamptz, failed_login_count int not null default 0,
  locked_until timestamptz,
  created_at, updated_at, deleted_at
)
-- CHECK: (type='customer') = (customer_id is not null)
-- CHECK: (type='reseller') = (reseller_id is not null)

roles (id uuid pk, key text unique, name text, is_system boolean)
permissions (id uuid pk, key text unique)   -- 'server.create', 'invoice.refund', ...
role_permissions (role_id, permission_id, pk(role_id,permission_id))
user_roles (user_id, role_id, scope_type, scope_id, pk(user_id,role_id,scope_type,scope_id))
-- scope_type: 'global' | 'reseller' | 'customer'

api_tokens (
  id uuid pk, name text, token_hash text unique not null, prefix char(8) not null,
  user_id uuid refs users, scopes text[] not null,
  ip_allowlist inet[], last_used_at timestamptz, expires_at timestamptz,
  revoked_at timestamptz, created_at
)

sessions (id uuid pk, user_id, token_hash, ip inet, user_agent text,
          expires_at, created_at, revoked_at)
4.2 CRM
sql
resellers (id uuid pk, code text unique, name text, status text,
           parent_margin_pct numeric(5,2), resource_limits jsonb,
           created_at, updated_at)

customers (
  id uuid pk, code text unique not null,        -- CUS-000123
  reseller_id uuid null refs resellers,          -- null = direct customer
  type customer_type not null,                   -- 'individual' | 'company'
  company_name text, legal_name text,
  first_name text, last_name text,
  email citext not null, phone text,
  country_code char(2) not null,
  timezone text not null default 'Pacific/Auckland',
  billing_currency char(3) not null,
  tax_number text,                               -- GST/ABN/VAT
  tax_number_validated_at timestamptz,
  tax_exempt boolean not null default false,
  status customer_status not null,               -- prospect|active|suspended|overdue|terminated|archived
  status_changed_at timestamptz not null,
  data_residency_requirement text[],             -- e.g. {'AU','NZ'} — HARD constraint, §9.2
  provider_preference text null,                 -- 'aws'|'ovh'|null  — HARD constraint
  isolation_tier isolation_tier not null default 'shared',  -- §5.1
  risk_score int not null default 0,
  notes text, created_at, updated_at, deleted_at
)
-- INDEX (reseller_id, status), (email), (status) WHERE deleted_at IS NULL

customer_contacts (id, customer_id, type contact_type[], -- primary|billing|technical|abuse
                   name, email citext, phone, is_primary boolean)
customer_addresses (id, customer_id, type, line1, line2, city, region,
                    postcode, country_code)
4.3 Catalog
sql
hosting_plans (
  id uuid pk, code text not null, version int not null default 1,
  name text not null, description text,
  status plan_status not null,                   -- draft|active|retired
  isolation_tier isolation_tier not null,
  visibility text not null,                      -- 'public'|'private'|'reseller'
  reseller_id uuid null,
  created_at, updated_at,
  unique (code, version)
)

plan_limits (
  plan_id uuid pk refs hosting_plans,
  storage_mb int not null,
  bandwidth_gb_month int not null,               -- 0 = unmetered (still soft-capped, §19.2)
  websites int not null, domains int not null, subdomains int not null,
  databases int not null, database_size_mb int not null,
  ftp_users int not null, cron_jobs int not null,
  php_workers int not null,                      -- maps to FPM pm.max_children
  cpu_quota_pct int not null,                    -- cgroup quota, 100 = 1 core
  memory_mb int not null,                        -- cgroup limit
  io_weight int not null default 100,
  inodes int not null,
  backup_retention_daily int not null,
  backup_retention_weekly int not null,
  backup_retention_monthly int not null,
  ssl_included boolean not null default true,
  support_tier text not null,                    -- 'standard'|'priority'
  overage_policy text not null                   -- 'block'|'bill'|'notify_only'  §16.7
)

plan_prices (
  id uuid pk, plan_id uuid refs hosting_plans,
  currency char(3) not null, period billing_period not null,  -- monthly|quarterly|semiannual|annual
  amount_minor bigint not null, setup_fee_minor bigint not null default 0,
  tax_inclusive boolean not null,
  active_from date not null, active_to date null,
  unique (plan_id, currency, period, active_from)
)

plan_pool_bindings (plan_id, server_pool_id, priority int, pk(plan_id, server_pool_id))

Plan versioning rule (MUST): changing any row in plan_limits for a plan that has ≥1 non-cancelled subscription creates version+1 and leaves existing subscriptions on the old version. This is the only safe way to change limits without silently breaking live accounts, and it makes "why did my quota change" answerable.

4.4 Infrastructure
sql
providers (id uuid pk, key text unique,          -- 'aws' | 'ovh'
           name text, adapter_key text not null, status text)

provider_accounts (
  id uuid pk, provider_id uuid refs providers,
  name text not null, environment text not null,     -- 'production'|'staging'
  credential_ref text not null,                      -- secrets-manager path, NEVER the secret §22.2
  credential_rotated_at timestamptz,
  default_region_id uuid, billing_currency char(3) not null,
  rate_limit_rps numeric not null default 5,
  status text not null, health_checked_at timestamptz, health_status text,
  created_at, updated_at
)

provider_regions (
  id uuid pk, provider_account_id uuid, code text not null,   -- 'ap-southeast-2' | 'SYD'
  display_name text, country_code char(2) not null,
  latency_group text not null,                  -- 'ANZ'|'SEA'|'US'|'EU' — used by §9.3
  is_enabled boolean not null default true,
  unique (provider_account_id, code)
)

server_types (
  id uuid pk, provider_id uuid, code text not null,   -- 't3.medium' | 'vps-3'
  vcpu int, memory_mb int, storage_gb int, storage_type text,
  bandwidth_tb_month numeric,
  hourly_cost_minor bigint, monthly_cost_minor bigint, currency char(3),
  cost_refreshed_at timestamptz,
  is_enabled boolean, unique (provider_id, code)
)

server_pools (
  id uuid pk, key text unique,                  -- 'ovh-standard-au'
  name text, provider_account_id uuid, region_id uuid,
  isolation_tier isolation_tier not null,
  default_server_type_id uuid,
  panel_type text not null,                      -- 'hestia'
  autoscale_enabled boolean not null default false,
  min_servers int not null default 1, max_servers int not null default 10,
  placement_strategy text not null default 'balanced',  -- 'balanced'|'binpack'  §9.5
  cpu_warn_pct int not null default 75, cpu_crit_pct int not null default 90,
  mem_warn_pct int not null default 75, mem_crit_pct int not null default 90,
  disk_warn_pct int not null default 75, disk_crit_pct int not null default 85,
  max_accounts_per_server int not null default 60,
  reserve_headroom_pct int not null default 15,  -- §9.4 — never fill past this
  status text not null
)

servers (
  id uuid pk, code text unique,                  -- SRV-0007
  pool_id uuid refs server_pools,
  provider_account_id uuid, region_id uuid, server_type_id uuid,
  provider_resource_id text,                     -- i-0abc.. | vps-xyz
  hostname text unique not null, display_name text,
  ipv4 inet, ipv6 inet, private_ipv4 inet,
  os text not null, panel_type text not null, panel_version text,
  panel_url text, panel_api_credential_ref text not null,
  ssh_port int not null default 22, ssh_key_ref text not null,
  cpu_cores int, memory_mb int, storage_gb int,
  status server_status not null,
  status_reason text, maintenance_until timestamptz,
  monthly_cost_minor bigint, cost_currency char(3),
  commissioned_at timestamptz, decommissioned_at timestamptz,
  last_seen_at timestamptz, last_reconciled_at timestamptz,
  created_at, updated_at
)
-- INDEX (pool_id, status), (provider_account_id), (status) 

server_metrics (            -- rolled up; raw lives in Prometheus, §15.1
  server_id uuid, bucket_start timestamptz, bucket_size interval,
  cpu_pct numeric, mem_pct numeric, disk_pct numeric,
  disk_used_gb numeric, load1 numeric, iowait_pct numeric,
  net_in_mbps numeric, net_out_mbps numeric,
  account_count int, website_count int,
  pk (server_id, bucket_start, bucket_size)
)
-- Hypertable-shaped; partition monthly. Retain 5m buckets 30d, 1h buckets 400d.

server_capacity (           -- materialised current view, refreshed by job §11.7
  server_id uuid pk,
  cpu_pct numeric, mem_pct numeric, disk_pct numeric,
  allocated_storage_mb bigint,        -- SUM of plan_limits.storage_mb on this server
  oversubscription_ratio numeric,     -- allocated / physical  §9.4
  account_count int, capacity_state capacity_state not null,  -- ok|warn|critical|full
  accepts_placement boolean not null,
  computed_at timestamptz not null
)
4.5 Hosting
sql
subscriptions (
  id uuid pk, code text unique,                  -- SUB-000123
  customer_id uuid, plan_id uuid, plan_version int,
  status subscription_status not null,
  -- pending_payment|provisioning|active|past_due|suspended|pending_cancellation|cancelled|failed
  currency char(3) not null, period billing_period not null,
  unit_amount_minor bigint not null,             -- snapshot of price at signup
  discount_id uuid null,
  started_at timestamptz, current_period_start date, current_period_end date,
  next_invoice_date date, cancel_at date, cancelled_at timestamptz,
  suspended_at timestamptz, grace_ends_at timestamptz, terminate_at date,
  auto_renew boolean not null default true,
  created_at, updated_at
)

hosting_accounts (
  id uuid pk, code text unique,                  -- HST-000123
  subscription_id uuid unique refs subscriptions,
  customer_id uuid, server_id uuid refs servers,
  panel_username text not null,                  -- unique per server
  panel_user_ref text,
  status hosting_account_status not null,
  -- provisioning|active|suspended|migrating|terminating|terminated|failed
  storage_used_mb bigint not null default 0,
  bandwidth_used_gb_period numeric not null default 0,
  inodes_used int not null default 0,
  usage_synced_at timestamptz,
  provisioned_at timestamptz, suspended_at timestamptz, terminated_at timestamptz,
  created_at, updated_at,
  unique (server_id, panel_username)
)

websites (
  id uuid pk, hosting_account_id uuid, primary_domain_id uuid,
  document_root text not null, app_type text not null,   -- static|php|wordpress|laravel
  php_version text, ssl_certificate_id uuid,
  status text not null, http_status_code int, last_checked_at timestamptz,
  created_at, updated_at
)

domains (
  id uuid pk, name citext unique not null, punycode text not null,
  customer_id uuid, hosting_account_id uuid null, website_id uuid null,
  type text not null,                            -- 'primary'|'addon'|'subdomain'|'alias'
  dns_managed_by text not null,                  -- 'platform'|'external'
  dns_provider_key text,                         -- 'cloudflare'
  dns_zone_ref text,
  registrar text, registered_at date, expires_at date, expiry_checked_at timestamptz,
  nameservers text[], nameservers_verified_at timestamptz,
  status text not null, created_at, updated_at
)

dns_records (
  id uuid pk, domain_id uuid, provider_record_ref text,
  type text not null, name text not null, value text not null,
  ttl int not null default 300, priority int, proxied boolean,
  managed_by_platform boolean not null default true,
  created_at, updated_at
)

databases (
  id uuid pk, hosting_account_id uuid, server_id uuid,
  engine text not null,                          -- 'mysql'|'mariadb'
  name text not null, size_mb numeric not null default 0,
  status text not null, created_at, updated_at,
  unique (server_id, name)
)
database_users (id, database_id, username, password_secret_ref text not null,
                privileges text[], host_pattern text, created_at)
ftp_users (id, hosting_account_id, username, password_secret_ref, home_path,
           protocol text, status, created_at)

ssl_certificates (
  id uuid pk, website_id uuid, domain_names text[] not null,
  issuer text not null default 'letsencrypt', type text not null, -- 'dv'|'custom'
  status ssl_status not null,                    -- pending|active|expiring|expired|failed|revoked
  issued_at timestamptz, expires_at timestamptz,
  last_renewal_attempt_at timestamptz, renewal_failure_count int not null default 0,
  last_error text, fingerprint_sha256 text,
  created_at, updated_at
)
-- INDEX (expires_at) WHERE status IN ('active','expiring')
4.6 Data protection
sql
backup_policies (
  id uuid pk, scope text not null,               -- 'plan'|'account'
  plan_id uuid null, hosting_account_id uuid null,
  target_id uuid refs backup_targets,
  frequency_cron text not null, includes text[] not null,  -- {'files','databases','config'}
  retain_daily int, retain_weekly int, retain_monthly int,
  encryption_key_ref text not null,
  is_enabled boolean not null default true
)

backup_targets (
  id uuid pk, key text unique, kind text not null,   -- 's3'|'sftp'
  endpoint text, region text, bucket text,
  credential_ref text not null, provider_account_id uuid null,
  storage_cost_per_gb_month_minor bigint, currency char(3),
  is_default boolean
)

backups (
  id uuid pk, hosting_account_id uuid, policy_id uuid, target_id uuid,
  server_id uuid,                                 -- source at time of backup
  kind text not null,                             -- 'full'|'files'|'database'
  status backup_status not null,                  -- scheduled|running|completed|failed|expired|deleted
  started_at, completed_at, size_bytes bigint,
  object_key text, checksum_sha256 text,
  encryption_key_ref text, is_verified boolean not null default false,
  expires_at timestamptz, error_code text, error_detail text,
  created_at
)
-- INDEX (hosting_account_id, created_at DESC), (status), (expires_at)

restores (
  id uuid pk, backup_id uuid, requested_by uuid refs users,
  target_hosting_account_id uuid, scope text not null,  -- 'full'|'files'|'database'
  status text not null, approved_by uuid, approved_at timestamptz,
  started_at, completed_at, error_detail text, created_at
)

restore_drills (          -- §14.5
  id uuid pk, backup_id uuid, run_at timestamptz, passed boolean,
  checks jsonb, duration_seconds int, notes text
)
4.7 Billing
sql
invoices (
  id uuid pk, number text unique,                -- INV-2026-000042, gapless per §16.4
  customer_id uuid, reseller_id uuid null,
  status invoice_status not null,                -- draft|issued|partially_paid|paid|overdue|cancelled|refunded|uncollectible
  currency char(3) not null,
  subtotal_minor bigint not null, discount_minor bigint not null default 0,
  tax_minor bigint not null, total_minor bigint not null,
  amount_paid_minor bigint not null default 0,
  amount_due_minor bigint generated always as (total_minor - amount_paid_minor) stored,
  tax_rate_pct numeric(5,2), tax_label text,     -- 'GST 15%'
  tax_country char(2), customer_tax_number text,
  issue_date date, due_date date, service_period_start date, service_period_end date,
  paid_at timestamptz, voided_at timestamptz,
  pdf_object_key text, notes text,
  created_at, updated_at
)
-- Immutable once status <> 'draft'. Enforced by trigger. §16.4

invoice_items (
  id uuid pk, invoice_id uuid, sort_order int,
  type text not null,                            -- hosting|domain|ssl|backup|overage|migration|setup|support|credit|adjustment
  subscription_id uuid null, description text not null,
  quantity numeric not null default 1,
  unit_amount_minor bigint not null, amount_minor bigint not null,
  tax_rate_pct numeric(5,2), tax_minor bigint not null,
  service_period_start date, service_period_end date, metadata jsonb
)

payments (
  id uuid pk, customer_id uuid, invoice_id uuid null,
  method text not null,                          -- 'stripe_card'|'bank_transfer'|'manual'|'credit'
  status text not null,                          -- pending|succeeded|failed|refunded|disputed
  amount_minor bigint not null, currency char(3),
  fee_minor bigint not null default 0,           -- processor fee, feeds §17
  provider_ref text, provider_payload jsonb,
  received_at timestamptz, reconciled_at timestamptz,
  created_by uuid, created_at
)

credit_notes (id, customer_id, invoice_id, number text unique, amount_minor,
              currency, reason text, issued_at, created_by)
customer_credits (id, customer_id, amount_minor, currency, balance_minor,
                  source text, expires_at, created_at)
refunds (id, payment_id, amount_minor, currency, reason, provider_ref,
         status, requested_by, approved_by, created_at)

discounts (id, code text unique, kind text,      -- 'percent'|'fixed'
           value numeric, applies_to text, max_redemptions int,
           redeemed_count int, valid_from, valid_to, is_active)

tax_rates (
  id uuid pk, country_code char(2), region_code text null,
  name text not null,                            -- 'GST'
  rate_pct numeric(5,2) not null, applies_to text[] not null,
  valid_from date not null, valid_to date null,
  reverse_charge_eligible boolean not null default false
)

fx_rates (base char(3), quote char(3), rate numeric(18,8), rate_date date,
          source text, pk (base, quote, rate_date))

dunning_events (id, subscription_id, invoice_id, step int, action text,
                scheduled_for timestamptz, executed_at timestamptz, result text)
4.8 Cost & profitability
sql
provider_cost_records (      -- ingested from AWS CUR / OVH billing API, §17.1
  id uuid pk, provider_account_id uuid, period_start date, period_end date,
  resource_ref text,                             -- instance id, bucket, etc.
  server_id uuid null, backup_target_id uuid null,
  category text not null,                        -- compute|storage|bandwidth|snapshot|other
  amount_minor bigint, currency char(3),
  amount_base_minor bigint, base_currency char(3), fx_rate numeric(18,8),
  ingested_at timestamptz,
  unique (provider_account_id, resource_ref, period_start, category)
)

cost_allocations (           -- computed monthly, §17.2
  id uuid pk, period date not null,              -- first of month
  hosting_account_id uuid, customer_id uuid, server_id uuid,
  compute_minor bigint, storage_minor bigint, bandwidth_minor bigint,
  backup_minor bigint, payment_fee_minor bigint, support_minor bigint,
  total_minor bigint, currency char(3),
  allocation_basis jsonb,                        -- audit trail of the math
  computed_at timestamptz,
  unique (period, hosting_account_id)
)

usage_records (              -- for overage billing + allocation
  id uuid pk, hosting_account_id uuid, metric text not null,
  -- 'storage_mb_avg'|'bandwidth_gb'|'cpu_seconds'|'backup_gb'
  period_start date, period_end date, quantity numeric,
  is_billed boolean not null default false, invoice_item_id uuid null,
  unique (hosting_account_id, metric, period_start)
)
4.9 Operations
sql
jobs (
  id uuid pk, queue text not null, name text not null,
  idempotency_key text unique not null,          -- §11.2
  saga_id uuid null, step_index int null,
  payload jsonb not null, status job_status not null,
  -- queued|running|succeeded|failed|dead|cancelled|compensating|compensated
  attempts int not null default 0, max_attempts int not null default 5,
  scheduled_for timestamptz, started_at, finished_at,
  error_code text, error_detail text, error_is_retryable boolean,
  result jsonb, actor_id uuid null, correlation_id uuid not null,
  resource_type text, resource_id uuid,
  created_at, updated_at
)
-- INDEX (status, scheduled_for), (resource_type, resource_id), (saga_id, step_index)

sagas (id uuid pk, name text, status text, current_step int,
       context jsonb, compensations jsonb, started_at, finished_at)

outbox (id bigserial pk, aggregate_type text, aggregate_id uuid,
        event_type text, payload jsonb, created_at,
        published_at timestamptz null)
-- INDEX (published_at) WHERE published_at IS NULL

migrations_ops (             -- named to avoid clashing with schema migrations
  id uuid pk, code text unique, hosting_account_id uuid,
  source_server_id uuid, target_server_id uuid,
  reason text, strategy text,                    -- 'rsync_cutover'
  status migration_status not null,
  -- planned|precheck|syncing|verifying|awaiting_cutover|cutover|monitoring|completed|rolled_back|failed
  dry_run boolean not null default false,
  planned_cutover_at timestamptz, ttl_lowered_at timestamptz,
  freeze_started_at timestamptz, cutover_at timestamptz,
  rollback_deadline timestamptz, source_retained_until date,
  bytes_transferred bigint, checks jsonb, error_detail text,
  requested_by uuid, approved_by uuid, created_at, updated_at
)

alerts (
  id uuid pk, rule_key text not null, severity text not null,  -- info|warning|critical
  resource_type text, resource_id uuid, customer_id uuid null,
  title text, detail text, fingerprint text not null,
  status text not null,                          -- firing|acknowledged|resolved|silenced
  first_seen_at, last_seen_at, resolved_at,
  acknowledged_by uuid, acknowledged_at,
  notification_sent_at timestamptz,
  unique (fingerprint) WHERE status = 'firing'   -- dedupe, §15.3
)

audit_log (
  id bigserial pk, occurred_at timestamptz not null,
  actor_type text not null,                      -- 'user'|'system'|'api_token'|'webhook'
  actor_id uuid null, actor_label text,
  action text not null,                          -- 'hosting_account.suspend'
  resource_type text not null, resource_id uuid,
  customer_id uuid null,
  before jsonb, after jsonb, diff jsonb,
  ip inet, user_agent text, correlation_id uuid,
  result text not null,                          -- 'success'|'failure'
  reason text
)
-- Append-only. REVOKE UPDATE, DELETE from app role. Partitioned monthly. §22.6

support_tickets (id, code, customer_id, subject, category, priority,
                 status, assigned_to, first_response_at, resolved_at,
                 sla_due_at, created_at)
ticket_messages (id, ticket_id, author_type, author_id, body,
                 is_internal boolean, attachments jsonb, created_at)

notifications (id, template_key, channel, recipient, customer_id,
               subject, body_rendered, status, provider_ref,
               sent_at, opened_at, error, created_at)

idempotency_keys (key text pk, scope text, request_hash text,
                  response_status int, response_body jsonb,
                  created_at, expires_at)
5. Tenancy, isolation and the provider-opacity guarantee
5.1 Isolation tiers (replaces the source's unqualified isolation claim)
Tier	Implementation	Sold as	Blast radius
shared	One OS user per account; open_basedir; per-user PHP-FPM pool with its own uid; per-user cgroup v2 CPU/memory/IO limits; MySQL user scoped to own schemas; noexec,nosuid on /tmp per user	"Shared hosting"	Kernel + MySQL server shared. Documented.
isolated	Dedicated VM, single account, same panel	"Managed VPS"	Own kernel
dedicated_db	Isolated tier + managed database (RDS / OVH managed)	"Enterprise"	Own kernel + own DB

MUST: the customer-facing plan description for shared states that resources are shared. The word "isolated" MUST NOT appear in shared plan copy. This is both honest and legally safer.

5.2 Application-level tenancy

There are two tenancy dimensions: reseller_id and customer_id. Enforcement is in three layers, and all three MUST exist — defence in depth, because a single missed where clause in a shared-hosting billing system is a data breach.

Request scope. Auth middleware resolves an ActorContext { actorId, userType, customerId?, resellerId?, permissions: Set<string> } and puts it in an AsyncLocalStorage. There is no other way to learn who is calling.
Repository guard. All reads go through repositories in packages/db. The base repository injects a tenant predicate for every model that declares tenantColumn. A repository method that needs to bypass it MUST be named *Unscoped and MUST be listed in an allowlist checked by a unit test.
Postgres RLS. Enable row-level security on customers, subscriptions, hosting_accounts, websites, domains, databases, backups, invoices, payments, support_tickets. The API sets SET LOCAL app.customer_id per transaction. RLS is the backstop for a bug in layer 2, not the primary mechanism.

Test (MUST): a generated integration test enumerates every /api/v1 route, calls it as customer A with an ID belonging to customer B, and asserts 404 (not 403 — do not confirm existence).

5.3 Provider opacity — made testable

The source's "customer must not care about the provider" becomes three concrete rules:

P1. No API response served to a customer actor contains the strings from providers.key, provider_accounts.name, server_types.code, servers.provider_resource_id, or server_pools.key. Enforced by a response serialiser allowlist and asserted by a snapshot test over every portal endpoint.
P2. hosting_accounts.server_id is never exposed to a customer actor. The portal shows an IP address and a panel URL (unavoidable) but never a server code or pool.
P3. Migrating an account between providers MUST NOT change: plan id, price, invoice line description, subscription dates, or the customer's panel username. Asserted by the migration e2e test (§24, M9).
6. Roles and permissions

Permissions are flat strings, checked by a @RequirePermission('server.create') decorator. Roles are bundles. Scope (global / reseller:<id> / customer:<id>) narrows which rows the permission applies to.

Domains:      customer, plan, subscription, invoice, payment, refund, credit,
              provider, server, pool, hosting_account, website, domain, dns,
              database, ssl, backup, restore, migration, alert, ticket, user,
              role, audit, secret, report, system
Verbs:        read, list, create, update, delete, suspend, resume, approve,
              execute, export

Seed roles:

Role	Notable grants	Notable denials
super_admin	*	—
hosting_admin	all infra + hosting + backup + migration (migration.execute requires second approval, §18.6)	secret.read, provider.update, role.*, payment.update
support	read on all customer/hosting/billing; ticket.*; hosting_account.resume; website.restart (service restart only)	any delete, suspend, refund.*, server.* writes
finance	invoice.*, payment.*, refund.create, credit.*, report.*, customer.read	every infrastructure permission, hosting_account.suspend (finance triggers dunning; dunning suspends)
reseller_admin	scoped to own reseller_id: customer/subscription/hosting read+create	pricing of parent, other resellers, all infra
customer	scoped to own customer_id	everything else

Rules (MUST):

Deny by default. An endpoint without a @RequirePermission decorator fails a lint test.
secret.read does not exist as a grantable permission for humans. Credentials are never returned by any API to any actor (§22.2). Support "views" a credential only by triggering a rotate-and-deliver-to-customer flow.
Privilege escalation guard: a user cannot grant a permission they do not hold.
Every suspend, delete, refund, restore, migration.execute writes an audit_log row with reason — the reason is a required request field, not optional.
7. Cloud provider adapter

The whole architecture rests on this. If provider knowledge leaks out of packages/adapters-cloud, adding Hetzner later becomes a rewrite instead of a folder.

7.1 Interface
ts
// packages/adapters-cloud/core/src/provider.ts
export interface CloudProvider {
  readonly key: string;                       // 'aws' | 'ovh'
  readonly capabilities: ProviderCapabilities;

  // Catalog — cached, refreshed by a scheduled job
  listRegions(): Promise<Region[]>;
  listServerTypes(regionCode: string): Promise<ServerType[]>;
  getPricing(regionCode: string, typeCode: string): Promise<Price>;

  // Lifecycle. All mutations take an idempotencyKey and are safe to replay.
  createServer(req: CreateServerRequest): Promise<ServerHandle>;
  getServer(ref: ProviderRef): Promise<ServerInfo | null>;
  deleteServer(ref: ProviderRef, opts: { idempotencyKey: string }): Promise<void>;
  rebootServer(ref: ProviderRef): Promise<void>;
  resizeServer(ref: ProviderRef, typeCode: string): Promise<ResizeResult>;
  waitUntilRunning(ref: ProviderRef, timeoutMs: number): Promise<ServerInfo>;

  // Networking
  ensureFirewall(ref: ProviderRef, rules: FirewallRule[]): Promise<void>;
  attachStaticIp?(ref: ProviderRef): Promise<string>;

  // Storage / snapshots
  createSnapshot?(ref: ProviderRef, label: string): Promise<SnapshotHandle>;

  // Cost
  fetchCostRecords(from: Date, to: Date): Promise<CostRecord[]>;

  // Health
  ping(): Promise<{ ok: boolean; latencyMs: number }>;
}

export interface ProviderCapabilities {
  snapshots: boolean;
  resizeWithoutRebuild: boolean;
  privateNetworking: boolean;
  managedDatabase: boolean;
  objectStorage: boolean;
  staticIp: boolean;
  hourlyBilling: boolean;
  minBillingIncrementHours: number;   // AWS 0 (per-second), OVH 720 (monthly)
}

export interface CreateServerRequest {
  idempotencyKey: string;             // MUST be passed to the provider where supported
  regionCode: string;
  typeCode: string;
  hostname: string;
  imageRef: string;                   // resolved from an image alias, §7.3
  sshKeyRefs: string[];
  cloudInit: string;                  // §12.2
  tags: Record<string, string>;       // MUST include platform, env, server_code
}

Capability rule (MUST): the placement engine and provisioning saga branch on capabilities, never on provider.key. A switch (provider.key) anywhere outside adapters-cloud fails code review. Add an ESLint rule.

7.2 Error taxonomy

Every adapter maps provider errors into exactly one of these. Retry policy is decided from the class, never from an HTTP code, because AWS and OVH disagree about codes.

ts
type ProviderErrorKind =
  | 'auth'            // credentials bad/expired — do NOT retry, page an admin
  | 'rate_limited'    // retry with backoff + jitter, honour Retry-After
  | 'quota_exceeded'  // provider account limit — do NOT retry, alert, block pool
  | 'capacity'        // region out of stock — retry in a DIFFERENT region/type
  | 'not_found'       // resource gone — treat as terminal for delete (success)
  | 'conflict'        // concurrent op — retry after short delay
  | 'invalid_request' // our bug — do NOT retry, dead-letter
  | 'timeout'         // retry, but reconcile first (may have partially succeeded)
  | 'provider_down'   // retry with long backoff, open the circuit breaker
  | 'unknown';        // retry twice then dead-letter

timeout is the dangerous one: a create that times out may still have created a server. MUST: before retrying any createServer, the saga calls findServerByTag(server_code) and adopts an existing resource rather than creating a second. Orphaned-resource detection is also a nightly reconciliation job (§11.7) — this is how a hosting business avoids paying for VMs it forgot about.

7.3 Image aliases

Never hardcode an AMI ID or OVH image name in business logic.

image alias:  'ubuntu-24.04-lts'
  aws  → resolve via SSM public parameter /aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id
  ovh  → 'Ubuntu 24.04'

Resolved images are cached in provider_images (alias, provider_account_id, region, resolved_ref, resolved_at) and refreshed weekly.

7.4 Rate limiting, retries, circuit breaking
Per provider_account_id: Redis token bucket at rate_limit_rps, burst 2×.
Retry: exponential backoff, base 1s, factor 2, max 60s, full jitter, max 5 attempts, only for retryable kinds.
Circuit breaker per provider account: 5 consecutive provider_down/timeout opens it for 60s; half-open lets 1 request through. An open breaker sets provider_accounts.health_status='degraded' and makes the placement engine skip that account (§9.2 hard constraint 3) rather than failing orders.
7.5 AWS and OVH specifics (adapter-internal)
Concern	AWS	OVH
Compute	EC2, gp3 root, ClientToken = idempotencyKey	Public Cloud instances / VPS API, X-Ovh-* signed auth
Idempotency	Native (ClientToken)	Not native. Adapter MUST implement it: write provider_operations(idempotency_key, provider_ref) before the call and look it up on replay.
Firewall	Security group per pool + per server	OVH network firewall + host nftables (nftables is the source of truth, §12.4)
Cost data	Cost & Usage Report → S3 → parse daily	/me/bill + /cloud/project/{id}/usage/current
Billing granularity	per-second	monthly, prorated on some products — treat as monthly for allocation
Metadata/tags	native tags	OVH instance has limited tagging; adapter mirrors tags into a local provider_resource_tags table
Managed DB	RDS (dedicated_db tier only)	OVH Managed Databases (Phase 3)

The OVH idempotency gap is the single biggest correctness risk in the integration. Build provider_operations first, before either adapter's createServer.

8. Hosting panel adapter
8.1 Interface
ts
export interface HostingPanel {
  readonly key: string;                      // 'hestia'
  readonly capabilities: PanelCapabilities;

  // Accounts
  createAccount(r: CreateAccountRequest): Promise<PanelAccount>;
  suspendAccount(username: string): Promise<void>;
  unsuspendAccount(username: string): Promise<void>;
  deleteAccount(username: string, opts: { backupFirst: boolean }): Promise<void>;
  setAccountLimits(username: string, limits: PanelLimits): Promise<void>;
  getAccountUsage(username: string): Promise<AccountUsage>;
  listAccounts(): Promise<PanelAccountSummary[]>;      // for reconciliation

  // Web
  addDomain(username: string, d: AddDomainRequest): Promise<void>;
  removeDomain(username: string, domain: string): Promise<void>;
  setPhpVersion(username: string, domain: string, version: string): Promise<void>;

  // TLS
  issueLetsEncrypt(username: string, domain: string, aliases: string[]): Promise<CertInfo>;
  installCustomCert(username: string, domain: string, cert: Pem): Promise<CertInfo>;
  getCertInfo(username: string, domain: string): Promise<CertInfo | null>;

  // Data
  createDatabase(username: string, r: CreateDbRequest): Promise<PanelDatabase>;
  dropDatabase(username: string, name: string): Promise<void>;
  createDbUser(username: string, r: CreateDbUserRequest): Promise<void>;
  rotateDbUserPassword(username: string, dbUser: string): Promise<{ password: string }>;
  createFtpUser(username: string, r: CreateFtpRequest): Promise<void>;

  // Backup (panel-native; platform-level backup is §14)
  createBackup(username: string): Promise<PanelBackupHandle>;
  restoreBackup(username: string, ref: string, scope: RestoreScope): Promise<void>;

  // Ops
  getServerStats(): Promise<PanelServerStats>;
  restartService(name: 'nginx'|'apache'|'php-fpm'|'mysql'): Promise<void>;
}
8.2 HestiaCP binding notes
Transport: HTTPS to :8083/api/ with user=admin&hash=<API key>, or v- CLI over SSH. Decision: use the HTTP API for all operations it supports; fall back to v-* commands over SSH only for setAccountLimits (cgroup/FPM tuning) and nftables changes. Both paths go through the adapter.
Hestia returns numeric exit codes, not JSON errors. The adapter MUST map the documented E_* codes (e.g. E_EXISTS, E_NOTEXIST, E_LIMIT, E_PASSWORD, E_DISK) to PanelErrorKind mirroring §7.2. Unmapped codes → unknown.
Hestia has no idempotency. Every mutating adapter method MUST be written as read-then-act: if (await exists(x)) return existing;. createAccount on an existing username returns the existing account if and only if it matches the expected plan fingerprint; otherwise it throws conflict.
Panel API credentials are per-server, stored as servers.panel_api_credential_ref pointing at Secrets Manager. Rotated on a 90-day schedule by a job.
Panel port 8083 is firewalled to the platform's egress NAT IPs plus an admin allowlist. Customers reach the panel through a platform reverse proxy at panel.<brand>.tld/<account-code> so the server hostname is not leaked (§5.3 P2).
8.3 Username generation

Deterministic, collision-safe, and stable across migrations (P3 in §5.3): u + base36(customer sequence) truncated to 8 chars, e.g. u0a3f9k. Uniqueness is per-server (unique (server_id, panel_username)) but the platform assigns globally unique names so a migration never has to rename. Never derive from the domain — domains change.

9. Placement engine

Pure function. Lives in packages/domain/placement. No I/O. This is the feature the source called the most important, and it is the one that was least specified.

9.1 Signature
ts
export function selectPlacement(input: PlacementInput): PlacementDecision;

interface PlacementInput {
  requirement: {
    planLimits: PlanLimits;
    isolationTier: IsolationTier;
    requiredCapabilities: (keyof ProviderCapabilities)[];  // e.g. managedDatabase
    customerCountry: string;
    dataResidency: string[] | null;      // hard
    providerPreference: string | null;   // hard
    latencyGroupPreference: string[];    // ordered soft, e.g. ['ANZ','SEA']
  };
  candidateServers: CandidateServer[];   // pre-filtered to bound pools
  pools: PoolConfig[];
  providerAccountHealth: Record<string, 'healthy'|'degraded'|'down'>;
  weights: PlacementWeights;
  now: Date;
}

type PlacementDecision =
  | { kind: 'existing_server'; serverId: string; score: number; trace: Trace }
  | { kind: 'new_server'; poolId: string; serverTypeId: string; regionId: string;
      estimatedMonthlyCostMinor: number; trace: Trace }
  | { kind: 'no_capacity'; reasons: RejectionReason[]; trace: Trace };

MUST: trace records, for every candidate, which hard constraint eliminated it or what each soft score component was. This is rendered verbatim in the admin UI. Support will ask "why did this customer land on server 7" every week; answer it in the product.

9.2 Hard constraints (evaluated first, in order; failing any eliminates a candidate)
server.status == 'active' and not in maintenance.
server.pool.isolation_tier == requirement.isolationTier.
provider_account.health != 'down' and circuit breaker closed.
If providerPreference set → server.provider.key == providerPreference.
If dataResidency set → region.country_code ∈ dataResidency.
All requiredCapabilities satisfied by the provider.
Free disk after placement ≥ reserve_headroom_pct of physical: (allocated_storage_mb + planLimits.storage_mb) ≤ physical_mb × (1 − headroom) × oversubscription_limit.
capacity_state != 'critical' and capacity_state != 'full'.
account_count < max_accounts_per_server.
Committed memory: Σ plan_limits.memory_mb (incl. new) ≤ physical_memory × mem_oversubscription (default 3.0 for shared, 1.0 for isolated).
Not currently a migration source or target.

If no candidate survives and pool.autoscale_enabled → new_server. If autoscale disabled → no_capacity.

9.3 Soft scoring (0–100 each, weighted sum, highest wins)
Component	Default weight	Definition
cost	0.30	100 × (1 − normalise(marginalCostMinor)). Marginal cost of adding this account to an existing server ≈ server.monthly_cost / (account_count + 1) deltas; for new_server it is the full type cost. Always converted to base currency at the current fx_rates row.
latency	0.25	100 if region's latency_group == first preference, 60 if second, 20 if third, 0 otherwise.
utilisation_fit	0.20	Strategy-dependent. balanced: `100 −
headroom_safety	0.15	100 × (1 − max(cpu_pct, mem_pct, disk_pct)/100) using the 7-day p95, not the instant value. p95, not average — averages hide the daily backup spike.
age_stability	0.05	Prefer servers commissioned >14 days ago (fully burned-in, panel patched).
consolidation	0.05	+100 if the customer already has accounts on this server (same-customer colocation simplifies support and migration).

Weights are stored in placement_weights and editable by super_admin, but the default set above ships as the seed.

Tie-break (deterministic, MUST): highest score → lowest server.code lexically. Never random. Deterministic placement makes the engine unit-testable and incident analysis possible.

9.4 Oversubscription policy

Shared hosting is economically viable only through oversubscription, and it is also how shared hosting businesses die. Explicit defaults:

disk:    1.0×  (NEVER oversubscribe disk — it is the one resource that
                cannot be reclaimed under pressure and causes total node failure)
memory:  3.0×  (cgroup limits + swap; monitored via §15)
cpu:     4.0×  (cgroup quota is a ceiling, not a reservation)

reserve_headroom_pct (default 15%) is a floor on free disk that placement never eats into; it exists so that a single customer's runaway logs cannot fill the node.

9.5 Strategy

balanced is the default for shared pools: better tail latency and a smaller blast radius. binpack is available for pools where cost dominates and the workload is known idle. Do not make this dynamic in v1.

9.6 Test corpus (MUST exist before the engine is used)

A placement.fixtures.json with ≥30 scenarios, each an input and an expected decision, including: empty pool + autoscale off → no_capacity; residency AU excludes SG servers; provider preference overrides a cheaper alternative; disk-full server excluded even at low CPU; degraded provider account skipped; two identical servers → deterministic tie-break; enterprise tier with managedDatabase requirement excludes OVH pool.

10. State machines

Transitions not listed are illegal and MUST throw. Each machine is a table in packages/domain/state plus a generated diagram in docs/.

10.1 Subscription
pending_payment ──payment_confirmed──▶ provisioning
pending_payment ──expired/cancelled──▶ cancelled
provisioning ──provisioned──▶ active
provisioning ──failed──▶ failed          (customer NOT billed; §20.2)
failed ──retry──▶ provisioning
failed ──abandon──▶ cancelled (auto-refund)
active ──invoice_overdue──▶ past_due
past_due ──payment_received──▶ active
past_due ──grace_expired──▶ suspended
suspended ──payment_received──▶ active   (via reactivation job)
suspended ──retention_expired──▶ pending_cancellation
active ──customer_cancels──▶ pending_cancellation
pending_cancellation ──period_end──▶ cancelled
pending_cancellation ──customer_reactivates──▶ active
cancelled ── (terminal; hosting_account terminated after §20.5 window)
10.2 Hosting account
provisioning → active | failed
active → suspended | migrating | terminating
suspended → active | terminating
migrating → active (on cutover success) | active (on rollback, back to source)
terminating → terminated
failed → provisioning (retry) | terminated

Invariant (MUST): subscription.status == 'active' ⟺ hosting_account.status ∈ {active, migrating}. A consistency check job asserts this every 15 minutes and alerts on drift.

10.3 Server
requested → provisioning → installing → configuring → active
any → failed (with reason)
active → maintenance → active
active → capacity_warning → active | full
full → active (after accounts move off)
active|full|maintenance → draining → decommissioning → decommissioned

draining is new versus the source and is essential: it means "no new placements, existing accounts being migrated off". Decommission MUST NOT be reachable from a state where hosting_accounts still reference the server — enforced by a FK check in the job.

10.4 Invoice

draft → issued → (partially_paid) → paid; issued → overdue → paid | uncollectible; draft → cancelled; issued → cancelled only via a credit note, never by mutation.

10.5 Migration

See §18; the enum is in migrations_ops.status.

11. Job and saga architecture
11.1 Rules
MUST: no HTTP request performs an external mutation. Controllers validate, persist intent, enqueue, and return 202 with a job id and a polling URL.
Queues (BullMQ), each with its own concurrency: provisioning (4), panel (8), dns (8), ssl (4), backup (6), restore (2), migration (2), billing (4), monitoring (16), notification (16), reconciliation (2), costing (2).
Priorities: customer-visible provisioning > billing > backups > reconciliation.
Job timeouts: default 5 min; backup 4 h; restore 4 h; migration step 2 h. A job exceeding its timeout is marked failed with error_is_retryable=true and its saga runs a reconcile step before retrying.
11.2 Idempotency

Every job payload carries idempotencyKey = sha256(jobName + businessKey), where businessKey is stable and semantic — e.g. hosting_account:HST-000123:provision:attempt-1. The jobs.idempotency_key unique index makes double-enqueue a no-op. Job handlers MUST additionally be written so that running twice with the same key produces the same end state (check-then-act against the panel/provider, never blind create).

11.3 Saga pattern

Multi-step infrastructure flows are sagas with per-step compensation. Steps are pure descriptors; the runner persists progress in sagas.context after each step so a worker crash resumes rather than restarts.

ts
defineSaga('provision-hosting-account', {
  steps: [
    step('select_placement',  run: selectPlacement,      compensate: noop),
    step('ensure_server',     run: ensureServer,         compensate: releaseIfCreatedByUs),
    step('create_panel_user', run: createPanelUser,      compensate: deletePanelUser),
    step('apply_limits',      run: applyLimits,          compensate: noop),
    step('create_domain',     run: addDomain,            compensate: removeDomain),
    step('create_database',   run: createDatabase,       compensate: dropDatabase),
    step('configure_dns',     run: upsertDnsRecords,     compensate: revertDnsRecords),
    step('issue_ssl',         run: issueLetsEncrypt,     compensate: noop, optional: true),
    step('configure_backup',  run: attachBackupPolicy,   compensate: detachBackupPolicy),
    step('enable_monitoring', run: registerTargets,      compensate: deregisterTargets),
    step('activate',          run: markActive,           compensate: markFailed),
    step('notify',            run: sendWelcome,          compensate: noop),
  ],
  onFailure: 'compensate_then_fail',
});

optional: true (SSL) means failure logs a warning, raises an alert, and continues — a certificate that fails on DNS-not-yet-propagated must not roll back a whole account. A retry job picks it up (§13.4).

11.4 Failure handling (upgrades source §52)

On terminal failure: mark saga failed → run compensations in reverse → set subscription.status='failed' → void or credit any invoice raised for the failed period (MUST — never bill for hosting that does not exist) → alert hosting_admin with the trace → surface a "Retry" button that re-enqueues with attempt-N+1.

11.5 Dead letter

Jobs exhausting max_attempts move to status='dead' and a dlq:<queue> BullMQ queue, retained 30 days, retryable from the admin UI. Alert if DLQ depth > 0 for > 15 min.

11.6 Outbox

Domain events are written to outbox inside the same transaction as the state change, then published by a poller (every 1 s, FOR UPDATE SKIP LOCKED, batch 100). This is what prevents "hosting account activated but welcome email never sent" and its inverse. Consumers are idempotent by outbox.id.

11.7 Reconciliation jobs (scheduled)

Reality drifts from the database. These jobs are not optional garnish; they are how the system stays true.

Job	Cadence	Action
reconcile-servers	15 min	List provider resources by tag; flag DB servers missing at provider (orphan_db), and provider resources with no DB row (orphan_cloud — these are money on fire; alert critical)
reconcile-panel-accounts	hourly	Diff listAccounts() against hosting_accounts; flag both directions
sync-account-usage	hourly	getAccountUsage → hosting_accounts.storage_used_mb, inodes
refresh-server-capacity	5 min	Recompute server_capacity from Prometheus p95 + allocations
refresh-provider-catalog	daily	Regions, types, prices
ingest-provider-costs	daily 04:00	§17.1
check-ssl-expiry	hourly	§13.4
check-domain-expiry	daily	RDAP lookup
expire-backups	daily	Delete past-retention objects, mark expired
restore-drill	monthly	§14.5
consistency-check	15 min	§10.2 invariants + orphan rows
rotate-panel-credentials	daily scan, 90-day age	§8.2
12. Server build pipeline
12.1 Saga
provision-server:
  reserve_record → create_provider_server → wait_running → assign_dns_hostname
  → wait_ssh → run_ansible_base → run_ansible_panel → run_ansible_hardening
  → install_monitoring_agent → register_backup_agent → smoke_test → mark_active
compensate: delete_provider_server (only if we created it), delete_record

smoke_test (MUST pass before active): panel API answers; a throwaway account can be created, given a domain, issued a self-signed vhost, and deleted; nginx/php-fpm/mysql all up; node_exporter scraping; backup agent can write and read a test object; nftables default-deny confirmed; df shows expected volume size.

12.2 cloud-init

Minimal on purpose — it only bootstraps enough for Ansible: create ops user, install the platform's SSH CA public key, set hostname, disable password auth, install python3. Everything else is Ansible, because cloud-init is not idempotent and cannot be re-run.

12.3 Ansible roles

base (packages, timezone UTC, unattended-security-upgrades, journald limits, swap, sysctl), storage (separate /home volume with quotas, noexec,nosuid,nodev on /tmp, /dev/shm), panel (HestiaCP pinned version, admin API key generated and written straight to Secrets Manager, panel bound to 8083 with allowlist), hardening (§12.4), monitoring (node_exporter, mysqld_exporter, nginx log shipping), backup_agent (restic + credentials from instance profile/OVH token), php (per-user FPM pool template, open_basedir, disable_functions, opcache), mysql (per-account users only, local_infile=0, slow log), waf (ModSecurity + CRS in DetectionOnly for 14 days then blocking).

MUST: Ansible is run with --check in CI against a container to prove idempotency; a second real run MUST report zero changed tasks.

12.4 Baseline hardening
nftables default-deny inbound; allow 80, 443, 22 (platform NAT + admin allowlist), 8083 (same allowlist), 25 outbound blocked by default (spam containment — this single rule prevents the most common shared-hosting reputational disaster; per-account exceptions require an approval).
SSH: CA-signed short-lived certificates (24 h) issued by the platform, not long-lived keys. No password auth, no root login, AllowUsers ops.
fail2ban on ssh, panel, and web auth endpoints.
Per-account cgroup v2 slices from plan_limits (cpu.max, memory.max, io.weight).
open_basedir per FPM pool; disable_functions=exec,passthru,shell_exec,system,proc_open,popen.
Automatic OS security updates; kernel livepatch where available; monthly reboot window per pool, staggered, announced.
13. Domains, DNS and SSL
13.1 Domain onboarding

Three paths, all supported: (a) customer delegates nameservers to Cloudflare zone the platform manages; (b) customer keeps external DNS and the platform emits a record checklist plus a verification poller; (c) subdomain of the platform's own domain for instant preview (hst-000123.preview.<brand>.tld) — MUST exist, because it lets a site be built and tested before DNS cutover, which is what makes migrations safe.

13.2 DNS adapter
ts
interface DnsProvider {
  ensureZone(domain: string): Promise<ZoneRef>;
  listRecords(zone: ZoneRef): Promise<DnsRecord[]>;
  upsertRecord(zone: ZoneRef, r: DnsRecordInput): Promise<DnsRecord>;
  deleteRecord(zone: ZoneRef, ref: string): Promise<void>;
  setZoneTtl(zone: ZoneRef, ttl: number): Promise<void>;
}

Platform-managed records carry managed_by_platform=true; the reconciler never deletes a record it does not own. Every change writes an audit_log row with before/after (source SRS §21 requirement, now concrete).

13.3 Record templates on provisioning

A @ → server.ipv4 (TTL 300), A www, AAAA if available, CNAME for aliases, plus MUST for any domain the platform does not host mail for: MX untouched if present, and if absent a null MX (MX 0 .) plus TXT @ "v=spf1 -all" and _dmarc TXT "v=DMARC1; p=reject;". Publishing anti-spoofing records by default for non-mail domains is free and prevents the platform's IP space being used in forgery.

13.4 SSL — resilient by design (fixes C2)
Issuance and renewal run on the node via the panel's ACME client (cron), not from the control plane. The control plane observes and repairs.
check-ssl-expiry (hourly) reads actual certificate expiry via TLS handshake against the site — not the database, because the database can be wrong. Records into ssl_certificates.
Status thresholds: active >21 d; expiring ≤21 d; escalate to a warning alert at ≤14 d, critical at ≤7 d, page at ≤3 d.
On renewal_failure_count ≥ 2, enqueue ssl.force-renew with HTTP-01; if the domain is on platform-managed DNS, fall back to DNS-01 automatically (this is the only reliable path when a customer has a redirect or WAF in front).
Rate-limit awareness: Let's Encrypt allows 5 duplicate certificates per week. The job MUST track attempts per domain in Redis and refuse a 6th, alerting instead of burning the quota.
Wildcards require DNS-01 and are only offered when dns_managed_by='platform'.
13.5 Registrar

v1 does not register or renew domains. domains.expires_at is populated by an RDAP lookup (with WHOIS fallback), refreshed daily, and drives the "Domain Expiring" notification at 60/30/14/7 days. The UI states clearly that renewal is the customer's responsibility at their registrar. Registrar integration is Phase 3.

14. Backups
14.1 Design

Engine: restic to an S3-compatible target. Chosen over panel-native backups because it does deduplication, client-side encryption, and incremental snapshots, and because restic check gives a verifiable integrity signal.

One restic repository per hosting account (not per server). Per-account repos mean a migration moves the repo pointer, not the data, and a compromised node cannot read another account's backups.
Encryption: per-account key, generated at provisioning, stored in Secrets Manager, referenced by backup_policies.encryption_key_ref. The key is never stored on the node — it is fetched into the agent's memory per run via a scoped, short-lived credential.
Databases are dumped with mysqldump --single-transaction --quick into the snapshot; a logical dump is what makes a partial restore possible.
14.2 Off-server requirement

MUST: every backup_targets row used by a policy resolves to storage in a different failure domain from the source server — different provider account at minimum, and region.country_code must satisfy the customer's data_residency_requirement. A policy violating this fails validation at write time.

14.3 Scheduling (fixes C2)

Backups are cron on the node with a control-plane heartbeat. The node runs the schedule; the platform records the outcome via an agent callback and, if no callback arrives within frequency + 2 h, raises a backup_missing alert and enqueues a remote-triggered run. A control-plane outage therefore delays reporting, not backups.

14.4 Retention and cost

Retention comes from plan_limits. expire-backups applies restic forget --prune with the daily/weekly/monthly counts. backups.size_bytes feeds usage_records metric backup_gb which feeds §17 cost allocation — backup storage is a real per-customer cost and the source's profitability model silently omitted how it is measured.

14.5 Restore drills (new — MUST)

Monthly, the restore-drill job picks a sample (all accounts over 90 days, ≥5% of accounts, minimum 3) and, for each: provisions a scratch account on a designated drill server, restores the latest full backup, asserts (a) restic check passes, (b) document root file count within 5% of source, (c) database restores and SELECT count(*) on the largest table is non-zero, (d) the site returns HTTP 200 on the preview subdomain. Result written to restore_drills. A failed drill is a critical alert. An account whose last three drills failed MUST NOT be marked as having backup protection in the customer portal.

14.6 Customer-initiated restore

Portal → select snapshot → choose scope → confirm with typed account code → creates a restores row in pending. Full-account restores require staff approval; file-only and single-database restores are self-service. Every restore first takes a pre-restore safety snapshot, so an accidental restore is itself reversible. Retained 7 days.

15. Monitoring, alerting and health
15.1 Collection
Node/infra: Prometheus scrapes node_exporter, mysqld_exporter, nginx-prometheus-exporter on each hosting node over the platform's private path (WireGuard mesh or provider private network; public scraping is not permitted).
Synthetic web checks: Blackbox exporter from ≥2 regions, every 60 s per website: HTTP status, TLS validity and expiry, response time, redirect chain, content match on an optional string.
Account usage: panel adapter, hourly.
Platform self-monitoring: §21.4.
15.2 Alert rules (seed set, each with for: duration to stop flapping)
Key	Condition	For	Severity
server.down	up == 0	2 m	critical
server.cpu_high	p95 cpu > pool crit	15 m	warning
server.mem_high	mem > crit	10 m	warning
server.disk_high	disk > crit	5 m	critical
server.disk_predict_full	linear predict full < 12 h	30 m	critical
server.load_high	load1/cores > 4	10 m	warning
service.down	nginx/php-fpm/mysql down	2 m	critical
website.down	non-2xx/3xx from ≥2 probes	3 m	critical
website.slow	p95 TTFB > 3 s	15 m	warning
ssl.expiring	< 7 d	—	critical
ssl.renewal_failed	failures ≥ 2	—	warning
backup.failed	last run failed	—	warning
backup.missing	no success in 2× interval	—	critical
restore_drill.failed	drill failed	—	critical
provider.api_failing	breaker open	5 m	critical
provider.orphan_resource	untracked resource found	—	critical
queue.depth_high	any queue > 500	10 m	warning
queue.dlq_nonempty	dlq > 0	15 m	critical
job.failure_rate	> 5% over 30 m	30 m	warning
capacity.pool_exhausted	no placeable server in pool	—	critical
abuse.outbound_spam	mail queue spike / port-25 attempts	5 m	critical
billing.webhook_lag	Stripe webhook age > 15 m	—	warning
15.3 Notification routing

Dedupe by alerts.fingerprint; group by resource; suppress child alerts when the parent (server.down) is firing. Channels v1: email + generic webhook (Slack-compatible payload). Escalation: critical unacknowledged for 15 min → repeat; 30 min → secondary contact. Quiet hours apply to warning only, never critical.

15.4 Public status

status.<brand>.tld renders per-pool aggregated health only. MUST NOT name individual customers, providers, or server hostnames.

16. Billing and money
16.1 Money model (fixes C6)
All amounts: bigint minor units + explicit char(3) currency. No floats anywhere, including in JSON responses (send {"amountMinor": 19900, "currency": "NZD"}).
Base currency: NZD. Every report that aggregates across currencies converts to base.
fx_rates is populated daily from a single named source (ECB + a NZD cross, or a paid feed). Rule (MUST): a cost or revenue amount is converted at the FX rate of its accrual date and the converted value is persisted (amount_base_minor, fx_rate). Reports never re-convert historical rows at today's rate — otherwise last quarter's margin changes every time someone opens the dashboard, which destroys trust in the number.
Rounding: half-up at the line-item level, then sum. Tax computed per line, then summed; the invoice total is the sum of line totals, never a recomputation from the subtotal. This is the only way line totals and the grand total agree.
Currency is chosen per customer at creation (customers.billing_currency) and is immutable. Changing it requires closing the account and opening a new one.
16.2 Stripe is not the source of truth

Decision: the platform owns subscriptions, periods, proration and invoices. Stripe is used for PaymentIntent (card charges), SetupIntent (saving a card), and webhooks. Do not use Stripe Subscriptions. Reasons: multi-currency + NZ GST + reseller margins + mid-cycle plan changes tied to infrastructure provisioning cannot be expressed in Stripe's model, and a divergence between Stripe's idea of a subscription and the platform's is an unfixable class of bug.

Webhooks: verify signature, persist raw event to stripe_events before processing, process idempotently by event.id, tolerate out-of-order delivery, reconcile daily against the Stripe API for anything missed.

16.3 Proration and plan changes
Upgrade (higher price): immediate. Credit the unused portion of the current plan (unit_amount × remaining_days / period_days, floor to minor unit), charge the new plan prorated for the remainder, invoice immediately, provision the limit change on payment. If the new plan's isolation_tier differs, the upgrade triggers a migration (§18) and the account stays on the old limits until cutover.
Downgrade (lower price): takes effect at current_period_end. No refund; the difference is not credited. Reason: prevents plan-cycling abuse, and the infrastructure cost was already committed. Stated in the plan terms.
Downgrade validation (MUST): refuse if current usage exceeds the target plan's limits (storage, website count, database count). Show exactly which limit and by how much. Silently accepting produces an account that is instantly over quota.
Period boundaries use the customer's timezone; a monthly subscription started on the 31st bills on the last day of shorter months.
16.4 Invoices
Numbering is gapless per calendar year per legal entity, allocated from a Postgres sequence inside the issuing transaction: INV-2026-000042. Draft invoices get no number. A cancelled issued invoice keeps its number and is offset by a credit note.
Immutability enforced by trigger: any UPDATE on an invoice whose status <> 'draft' that touches an amount, tax, line item, or customer field raises an exception. Allowed updates post-issue: status, amount_paid_minor, paid_at, pdf_object_key.
PDF generation is a job; the PDF is stored in object storage and served via a signed URL with a 15-minute expiry. Regenerating a PDF MUST produce byte-identical content for the same invoice (deterministic template, no "generated on" timestamp).
Invoice contains: seller legal name + GST number, buyer name + address + tax number, invoice number, issue date, due date, service period per line, line descriptions that never name a provider or server (§5.3 P1), tax label and rate, totals, payment instructions.
16.5 Tax

tax_rates is looked up by the customer's country (and region where applicable) at invoice-issue time and the resolved rate is snapshotted onto the invoice. Seed:

Country	Rule
NZ	GST 15% on all supplies to NZ customers. Invoice must show "Tax Invoice", the supplier's GST number, and the GST amount.
AU	GST 10% to AU customers. If the customer supplies a valid ABN and is registered, B2B digital services may be zero-rated — validate the ABN against the ABR and record tax_number_validated_at; if unvalidated, charge GST.
Other	0% by default, tax_label='No GST'. Flag for review at NZ$60k/year revenue per jurisdiction.

MUST: tax logic lives in packages/domain/billing/tax.ts as a pure function with a fixture table, and thresholds are configuration, not code. This is a "get an accountant to confirm" area; the platform's job is to make the rule visible and changeable, not to be a tax authority. A note to that effect belongs in the admin UI.

16.6 PCI scope

Stripe Elements / Payment Element in the browser; the platform receives only a payment_method id. No PAN, CVV, or expiry ever reaches platform code, logs, or the database. This keeps the business on SAQ-A. A code-review rule and a log-scrubbing filter (regex for card-shaped numbers) enforce it. Bank transfers are reconciled manually or via a bank feed; a payments row with method='bank_transfer' requires a finance actor and a reference.

16.7 Overage

plan_limits.overage_policy:

block (default for entry plans): at 100% storage the account goes read-only for uploads (panel quota does this natively); customer is notified at 80%, 90%, 100%.
bill: usage above the limit accrues to usage_records and is invoiced at the plan's overage rate on the next invoice. Requires a customer-visible rate and a monthly cap.
notify_only: for enterprise accounts under contract.

Bandwidth is measured from nginx logs aggregated hourly per account. "Unmetered" plans still have a fair-use ceiling (§19.2) — unmetered means unbilled, not unlimited.

17. Cost and profitability

The source's dashboards (§39–41) are good products built on undefined arithmetic. Here is the arithmetic.

17.1 Cost ingestion

Daily job per provider account writes provider_cost_records:

AWS: Cost & Usage Report delivered to S3, parsed at line-item granularity, mapped to server_id via the server_code tag. Untagged spend goes to a shared_overhead bucket.
OVH: /me/bill for issued bills plus current usage endpoints. OVH bills monthly, so daily records are the monthly cost divided by days in month, marked is_estimate=true until the bill arrives, then reconciled.
Backup storage: measured from the S3 API (ListObjectsV2 sizes per prefix, so per-account) × backup_targets.storage_cost_per_gb_month_minor. This is measured, not estimated.
Every record is converted to base currency at that day's rate and persisted (§16.1).
17.2 Allocation to accounts

Monthly job, cost_allocations. For a server S in month M:

serverCost(S,M)      = Σ provider_cost_records where server_id = S
accountDays(a,M)     = days the account existed on S during M
weight_storage(a)    = plan_limits.storage_mb(a) × accountDays(a)
weight_compute(a)    = plan_limits.cpu_quota_pct(a) × accountDays(a)

computeShare(a) = serverComputeCost(S,M) × weight_compute(a) / Σ weight_compute
storageShare(a) = serverStorageCost(S,M) × weight_storage(a) / Σ weight_storage
bandwidthShare(a) = measured bandwidth_gb(a) × serverBandwidthCost / Σ measured
backupCost(a)   = measured backup bytes(a) × target rate           [direct, not allocated]
paymentFee(a)   = Σ payments.fee_minor attributable to a's subscription in M
supportCost(a)  = ticket minutes(a) × configured hourly support rate / 60
                  (0 if time tracking is off — never guess)
overhead(a)     = shared_overhead(M) × (a's direct cost / Σ direct cost)

totalCost(a,M) = computeShare + storageShare + bandwidthShare + backupCost
                 + paymentFee + supportCost + overhead

allocation_basis stores every input for that row. MUST: the sum of all cost_allocations.total_minor for a period equals the sum of provider_cost_records for that period ± 1 minor unit (rounding). A reconciliation assertion runs after the job and alerts on drift — an allocation model that does not add up is worse than none.

Empty capacity is deliberately not allocated to customers; it lands in shared_overhead and shows on the dashboard as "unallocated capacity cost", which is the number that tells the business it bought too many servers.

17.3 Reports
Per-customer P&L: revenue recognised in the period (see below) − allocated cost.
Revenue recognition (MUST): an annual invoice of NZ$199 is recognised at NZ$16.58/month over 12 months, not NZ$199 in month one. Deferred revenue is tracked in revenue_schedules (subscription_id, period, amount_minor). Without this, every monthly margin report is fiction. This is the single most common error in hosting-SaaS dashboards and the source SRS reproduced it in §39–41.
Per-server P&L: Σ recognised revenue of accounts on the server − server cost. Includes an "accounts needed to break even" figure and a "months to payback" figure.
Pool utilisation vs cost: cost per active account per pool, trended — this is the number that decides whether to buy bigger or more servers.
Cost optimisation report (replaces source §44's "engine"): lists accounts whose allocated cost exceeds a configurable multiple of the cheapest compliant alternative, excluding any account with a hard placement constraint (residency, provider preference, isolation tier) — this is the fix for C4. Output is a ranked list with the estimated saving and the migration effort; a human decides.
18. Migration engine

The riskiest subsystem. The source treated "switch DNS" as one box; it is the step that can lose a customer's orders.

18.1 Strategy: rsync + cutover
planned → precheck → syncing → verifying → awaiting_cutover
        → cutover → monitoring → completed
any → rolled_back | failed
18.2 Steps
precheck — target server passes placement hard constraints; disk headroom on target ≥ source usage × 1.3; PHP/MySQL versions compatible (or an explicit override with a recorded acknowledgement); source has a successful backup < 24 h old; domains.dns_managed_by known; current TTL recorded.
lower_ttl — if platform-manages DNS, set all A/AAAA records for the account's domains to TTL 60. Then wait at least the old TTL before cutover (recorded in ttl_lowered_at; the earliest legal cutover is ttl_lowered_at + old_ttl + 5 min). If DNS is external, email the customer with the required TTL change and block the migration until a DNS query confirms TTL ≤ 300.
create_target_account — panel account on the target with identical username, limits, PHP version, and domains. Site served on the preview subdomain (§13.1c).
sync_1 (hot) — rsync -aHAX --delete while the source is live. Repeat until the delta is small. Databases are not synced in this phase.
verify_hot — preview subdomain returns 200; file counts within tolerance.
awaiting_cutover — requires approval (§18.6) and a scheduled window.
cutover (the only downtime, target < 5 min): a. Put the source account into maintenance: nginx returns 503 for the account's domains and writes are blocked. This freeze is mandatory — without it, orders placed between the final dump and the DNS switch are lost, and the customer will not forgive it. b. Final rsync delta. c. mysqldump --single-transaction on source → import on target. Record row counts of the 10 largest tables on both sides and assert equality. d. Rewrite anything holding the old IP (WordPress siteurl/home only if changing hostname; normally unchanged). e. Issue/copy TLS on target and verify the chain. f. Flip DNS A/AAAA to the target IP. g. Keep the source serving a 307 redirect to the target IP for stragglers on cached DNS, for 48 h. h. Lift maintenance on target.
monitoring — 24 h of elevated synthetic checks; error-rate comparison against the pre-migration baseline; automatic rollback offer if 5xx rate exceeds baseline + 2%.
completed — restore original TTL; source_retained_until = cutover + 14 days; a scheduled job deletes the source account after that date, only if the target has had ≥3 successful backups.
18.3 Rollback

Valid until rollback_deadline (default cutover + 24 h). Rollback = re-freeze target, dump target DB → source, rsync target → source, flip DNS back, lift source. MUST: rollback replays data back to the source; a rollback that simply re-points DNS to a stale source silently discards every write since cutover. Test this in M9.

18.4 Cross-provider specifics

Same flow. Extra steps: firewall rules on the target must permit rsync from the source public IP for the sync window and be removed after; transfer cost is recorded against provider_cost_records category bandwidth; if regions differ, the pre-check warns about latency changes to the customer's own external services.

18.5 Bulk / drain

drain-server creates one migrations_ops per account with a concurrency cap of 2 and a per-account cutover window, so a server evacuation is a queue of individually reversible migrations rather than one large irreversible event.

18.6 Approvals

migration.execute requires a second staff approver (approved_by <> requested_by) for any migration touching a production account. Dry-run mode performs steps 1–5 and stops. Every migration writes a timeline to audit_log with per-step durations.

19. Abuse, fair use and email
19.1 Email — explicitly out of scope for v1

The platform does not host mailboxes. Plans state "email not included; DNS records for your email provider are supported". plan_limits has no mailbox fields. Rationale: IP reputation, deliverability, spam filtering, and storage growth make mail a separate product with its own infrastructure, and putting mail on the web nodes is what gets a provider's whole IP range blocklisted. Phase 3 revisits with a dedicated mail cluster.

Outbound application mail (a contact form) is supported via a platform SMTP relay with a per-account rate limit (default 200/day), authenticated submission only, and From domain verification. Port 25 outbound stays blocked on the nodes (§12.4).

19.2 Abuse and the noisy neighbour

This is the top operational cost of shared hosting and the source omitted it entirely.

Resource fencing: per-account cgroup CPU/memory/IO from plan_limits, per-user PHP-FPM pools with pm.max_children = php_workers. An account cannot consume the node.
Malware scanning: ClamAV + a PHP-shell signature set, daily incremental scan of each account's document root. A detection creates an alerts row, quarantines the file to /quarantine/<account>/ (never deletes), and notifies the customer.
Outbound spam containment: port 25 blocked; relay rate limits; alert on any account exceeding 3× its 7-day mail baseline.
Application vulnerability nudging: detect WordPress/plugin versions from the filesystem, compare against a CVE feed, notify the customer with a severity. Do not auto-update customer code.
Fair use on "unmetered": a soft ceiling (e.g. 1 TB/month, 20% sustained CPU over 24 h) that triggers a conversation, not a suspension, and is written in the plan terms.
Abuse workflow: abuse@ contact per customer (§4.2), a ticket category, a documented 24 h response SLA, and a hosting_account.suspend path with reason abuse that is exempt from the billing dunning flow.
20. Order → active, dunning, suspension, termination
20.1 Order to active
order created (subscription: pending_payment)
  → invoice issued (draft → issued)
  → payment succeeded  [webhook or manual]
  → subscription: provisioning
  → saga 'provision-hosting-account' (§11.3)
  → subscription: active, hosting_account: active
  → welcome notification (panel URL, temp credentials via one-time link, next steps)

Credentials are delivered as a one-time-view link (single use, 24 h expiry, logged), never in the email body.

20.2 Capacity exhaustion (fixes C7)

If placement returns no_capacity and autoscale is off: subscription → awaiting_capacity (a substate of provisioning with its own timer), capacity.pool_exhausted critical alert, customer emailed with an honest ETA, and billing is not started — subscription.started_at and the first service period begin at activation, not at payment. If not resolved within 48 h, an automatic full refund is offered. Never bill for hosting that does not exist.

20.3 Dunning

Configurable per plan; defaults, driven by dunning_events:

Offset	Action
−30 d	Renewal notice with amount and date
−14 d	Reminder
−7 d	Final reminder; card retried if saved
Day 0	Invoice due; auto-charge attempt 1
+1, +3, +7 d	Auto-charge retries (exponential; stop on hard decline)
+3 d	"Payment overdue" email; subscription → past_due
+7 d	Second notice + portal banner
+14 d	Final notice: "suspension in 3 days"
+17 d	Suspension (§20.4)
+47 d	Termination notice (14 days out)
+61 d	Termination (§20.5)

Hard declines (card cancelled/stolen) skip to the next human touchpoint rather than retrying. Every dunning email includes a one-click pay link.

20.4 Suspension

Idempotent and fully reversible. On suspend: panel account suspended (nginx serves a branded suspension page, HTTP 503 with Retry-After), FTP/SSH disabled, panel login disabled, cron disabled, databases left running but not reachable from the web, backups continue, files untouched. On payment: resume job reverses every step and asserts the site returns 200 within 5 minutes; failure raises a critical alert, because a customer who has paid and is still down is the worst possible state.

Suspension for abuse uses the same mechanism with a different reason and does not auto-resume on payment.

20.5 Termination and data deletion
suspended (≥ retention window, default 45 d)
  → final notice (14 d before)
  → terminal backup taken and pinned for 90 d, off-server, encrypted
  → panel account deleted, DNS records removed, databases dropped,
    ssl revoked, monitoring targets removed
  → hosting_account: terminated
  → after 90 d: terminal backup deleted; backup repository destroyed
  → after 7 years: customer PII minimised (name, email, address redacted);
    invoices retained in redacted form for tax law

Requires: a hosting.terminate permission, a typed confirmation of the account code, and — for accounts with >NZ$1,000 lifetime revenue — a second approver. A customer-initiated data export (files + database dumps as a downloadable archive, 7-day signed URL) MUST be available from the portal at any time before deletion, and is offered automatically in the final notice.

21. Non-functional requirements and platform observability
21.1 Split planes (fixes C2)
Plane	Contents	Availability target	Failure behaviour
Data plane	Hosting nodes: nginx, PHP-FPM, MySQL, panel, node-local cron for SSL and backups	99.9% per node; pool-level SLA in plan terms	Independent of the control plane. A total control-plane outage is invisible to visitors.
Control plane	API, workers, scheduler, portals, database	99.5%	Degrades: no new provisioning, no dashboard, no billing runs. All catch up on recovery because every action is an idempotent job.

MUST: an automated test ("control-plane blackout drill", quarterly) stops the entire control plane for 30 minutes and asserts: all sample sites serve 200 throughout, SSL renewal that falls due during the window still happens on-node, backups still run, and on recovery no duplicate invoices, charges, or provisioning actions occur.

21.2 Performance budgets
Operation	Target
Portal/admin API read, p95	< 300 ms
Portal/admin API read, p99	< 800 ms
Any write endpoint (enqueue + return), p95	< 500 ms
Admin list views (10k rows, paginated) p95	< 700 ms
Placement decision (pure function, 500 candidates)	< 50 ms
Provision hosting account (order → live), p50 / p95	< 3 min / < 8 min
Provision new server (empty → active)	< 15 min
Invoice run for 5,000 subscriptions	< 10 min
Job pickup latency (queue → running), p95	< 5 s

MUST: no endpoint issues an unbounded query. Every list endpoint is cursor-paginated with a hard limit ≤ 100. N+1 detection runs in CI against the e2e suite.

21.3 Scale targets

v1 correctness at 200 customers / 1,000 sites / 25 servers. Architecture must reach 10,000 customers / 50,000 sites / 1,000 servers without changing the adapter or job model. Concretely, that means: no per-server polling loop in the API process (workers only), metrics in Prometheus not Postgres, server_metrics partitioned, and audit_log partitioned monthly with an archival job to object storage after 13 months.

21.4 Platform self-observability

OpenTelemetry traces on every request and job, with correlation_id propagated from HTTP → outbox → job → adapter → provider call, and stamped into audit_log. One trace ID should explain an entire provisioning. Golden signals dashboard: queue depth and age per queue, job success/failure rate by name, adapter call latency and error kind by provider, webhook lag, outbox backlog, DB connection saturation, saga compensation rate.

21.5 Disaster recovery for the control plane

RPO 5 min (Postgres PITR with WAL archiving to object storage in a second provider), RTO 4 h. Backups of the control-plane database restored and smoke-tested monthly. Provider credentials and backup encryption keys have a documented, tested recovery procedure held outside the platform — if Secrets Manager and the platform are lost together and the keys are irrecoverable, every customer backup becomes undecryptable ciphertext. This is the single worst failure mode in the design; treat the break-glass procedure as a first-class deliverable, not documentation.

22. Security
22.1 Baseline

HTTPS only (HSTS with preload); TOTP MFA mandatory for all staff and reseller users, optional but encouraged for customers; Argon2id password hashing; session timeout 8 h idle / 24 h absolute for staff; IP allowlist available per staff user and mandatory for super_admin; CSP without unsafe-inline; strict CORS; rate limits (auth 5/min/IP, API 100/min/token, provisioning 10/hour/customer).

22.2 Credentials — the hard rule

Provider API keys, panel API keys, SSH keys, database passwords, backup encryption keys: stored only in AWS Secrets Manager. The database stores a *_ref path, never a value, never a ciphertext blob the app can decrypt on its own.

MUST:

No API endpoint returns a secret value to any actor, including super_admin.
Workers fetch secrets at use time with a 5-minute in-memory cache, never at boot into a long-lived variable.
A log-scrubbing middleware redacts anything matching secret-shaped patterns and any key named password|secret|token|key|hash|credential at any nesting depth, applied to application logs, job payloads persisted to jobs.payload, HTTP error bodies, and audit before/after diffs.
Rotation: provider keys 180 d, panel keys 90 d, SSH CA 365 d, backup keys never rotated without a re-encryption plan (rotation of a backup key must not orphan existing snapshots — implement as key-per-epoch with old keys retained).
Customer-facing credentials (initial panel password, DB passwords) are generated, delivered once via a one-time link, and stored as a Secrets Manager ref that the platform can rotate but not display.
A CI secret scanner (gitleaks) blocks merges.
22.3 SSH

Short-lived certificates from an internal CA, 24 h validity, issued per-job to the worker that needs them, principal-scoped to a single host. No shared keys, no key files on disk, no ssh from a developer laptop to a production node except through a bastion that records the session.

22.4 Privacy and residency
customers.data_residency_requirement is a hard placement constraint (§9.2) and is additionally enforced for backups (§14.2) and for any log or metric export.
NZ Privacy Act 2020 IPP 12: offshore disclosure requires comparable safeguards. The platform records, per customer, the countries their data resides in, and surfaces it in the portal. A change of residency country requires a migration, not a config flip.
Data subject requests: export (§20.5) and deletion, both with an audited workflow and a 30-day SLA.
PII in logs is redacted; support screens show masked emails/phones with an audited reveal action.
22.5 Application security

Parameterised queries only (Prisma); Zod validation at every boundary; output encoding by React; no dynamic shell string interpolation in the panel adapter — execFile with an argument array, never exec with a template string (this is the most likely RCE in the whole codebase, since panel commands take user-controlled domain and username strings); SSRF protection on any customer-supplied URL (blocklist RFC1918, link-local, metadata endpoints); file upload type and size validation; dependency scanning in CI.

22.6 Audit

audit_log is append-only at the database-role level (REVOKE UPDATE, DELETE). Every mutation records actor, action, resource, before/after diff, IP, correlation id, result, and — for destructive actions — a mandatory human-entered reason. Audit rows are written in the same transaction as the change. Retention 7 years, partitioned monthly, archived to object storage with a checksum manifest after 13 months.

23. API and frontend conventions
23.1 API
/api/v1, REST, cursor pagination, RFC 9457 problem details, X-Correlation-Id echoed.
Mutations that touch infrastructure return 202 Accepted with { jobId, statusUrl, resource }. Clients poll statusUrl or subscribe to SSE at /api/v1/jobs/:id/events.
Idempotency-Key header supported (and required for order creation and payment endpoints), backed by idempotency_keys with a 24 h window.
OpenAPI 3.1 generated from the Zod contracts; the generated client in packages/contracts is the only HTTP client the frontends use.
Resources: customers, contacts, plans, subscriptions, invoices, payments, credits, refunds, providers, provider-accounts, regions, server-types, pools, servers, hosting-accounts, websites, domains, dns-records, databases, ftp-users, ssl, backup-policies, backups, restores, migrations, alerts, tickets, jobs, audit-logs, reports/*.
Customer-scoped endpoints live under the same paths; scoping is by actor, not by URL prefix, so there is exactly one authorisation code path.
23.2 Frontend
Server Components for reads; Server Actions only for trivial mutations, otherwise the generated client.
TanStack Query for anything polling a job.
Every destructive action: typed-confirmation dialog + a required reason field.
Admin must render the placement trace (§9.1), the job/saga timeline, and the audit diff as first-class views. These three screens are what make the system operable, and they are usually the first thing cut and the first thing missed.
Portal shows: plan, usage bars with limits, websites, domains with DNS status, SSL status, backup status including last successful restore drill, invoices, payment method, tickets. It shows no provider, pool, server code, or plan-internal identifiers.
24. Build order

Each milestone ends with a command that must pass. Do not proceed past a red milestone. Each milestone should be a separate PR.

M	Scope	Definition of Done
M0	Monorepo, Docker Compose (Postgres, Redis, MinIO, mailhog), CI (lint, typecheck, test, migrate), OTel wiring, packages/contracts skeleton	pnpm verify green in CI; docker compose up gives a working stack
M1	Full Prisma schema (§4), migrations, seed (roles, permissions, tax rates, a plan, a pool, fx rates), repository base with tenant guard, RLS policies	Migration up/down clean; tenant-guard unit tests pass; RLS integration test denies cross-tenant read
M2	Identity: registration, login, MFA, sessions, API tokens, RBAC decorators, audit middleware, correlation ids	e2e: every seeded role hits an allowed and a denied endpoint; the "no route without @RequirePermission" lint test passes
M3	CRM + Catalog CRUD, plan versioning rule, admin shell UI	Creating a subscription against a plan then editing plan limits produces version 2 and leaves the subscription on v1
M4	Job infrastructure: BullMQ setup, jobs table, idempotency, saga runner with compensation, outbox + publisher, DLQ, admin job viewer	Chaos test: kill the worker mid-saga, restart, saga resumes and completes exactly once; duplicate enqueue is a no-op
M5	adapters-cloud/core + provider_operations idempotency table + OVH adapter + AWS adapter, against recorded fixtures and one real sandbox account	Contract test suite runs identically against both adapters; simulated timeout-then-retry adopts the existing resource rather than creating a second
M6	Server provisioning: Ansible roles, cloud-init, provision-server saga, smoke test, reconciliation jobs	A real server is created, hardened, panel-installed and reaches active unattended; a second Ansible run reports zero changes; deleting the DB row and re-running reconciliation detects the orphan
M7	Panel adapter (Hestia) + placement engine + provision-hosting-account saga + capacity computation	≥30 placement fixtures pass; an order provisions a live, reachable site end to end; placement trace renders in admin
M8	DNS (Cloudflare), SSL issuance and the expiry reconciler, website + database + FTP management, customer portal v1	A domain provisioned end to end serves valid HTTPS; killing the control plane does not prevent an on-node renewal
M9	Backups, restores, restore drills, migration engine incl. rollback	Migration e2e: write data, cutover, verify no writes lost during freeze; then roll back and verify data written after cutover survives the rollback
M10	Billing: invoicing, tax, proration, Stripe, dunning, suspension, reactivation, termination	Billing simulation over 400 simulated days with clock control: renewals, an upgrade, a downgrade, a failed card, suspension, reactivation, termination — assert every invoice, credit and state transition against a golden fixture
M11	Monitoring, alerts, notifications, status page, abuse tooling (§19.2)	Killing nginx on a node produces exactly one deduped critical alert and one notification within 3 minutes
M12	Cost ingestion, allocation, revenue recognition, profitability dashboards	Allocation reconciliation assertion passes on seeded data; monthly margin for an annual invoice is 1/12, not lumped
M13	Hardening: load test to 10× v1 scale, control-plane blackout drill, pen-test checklist, runbooks, DR restore rehearsal	Blackout drill passes (§21.1); p95 budgets in §21.2 met under load

Phase 2 (after M13): Virtualmin adapter, resellers, usage-based billing, advanced monitoring, auto-balancing recommendations, registrar integration. Phase 3: additional providers, managed WordPress, mail cluster, CDN/WAF products, cross-provider DR.

25. Test strategy
Unit (packages/domain) — placement, billing, tax, proration, allocation, state machines. Target 95% branch coverage here specifically; this is where the money and the correctness live and it has no I/O, so there is no excuse.
Contract tests for adapters — one suite executed against every implementation of CloudProvider and HostingPanel. A new provider is "done" when this suite is green. Recorded HTTP fixtures (Polly/nock) for CI, plus a nightly run against real sandbox accounts.
Integration (Testcontainers) — repositories, RLS, jobs, sagas, outbox, migrations.
Chaos — worker kill mid-saga; provider 429/500/timeout injection; duplicate webhook delivery; out-of-order webhooks; clock skew; database failover.
e2e (Playwright) — the eight journeys: signup→live site; upgrade; downgrade attempt over quota; failed payment→suspend→pay→resume; backup→restore; migration→rollback; domain add with SSL; termination with export.
Time-travel harness — a controllable clock so a 400-day billing simulation runs in seconds. Build this in M4; retrofitting it is painful.
Security — automated: cross-tenant route sweep (§5.2), secret-leak scan of API responses and logs, dependency audit, ZAP baseline.
26. Open questions for the business

These need answers from the operator, not the developer. Each blocks a specific milestone.

Legal entity and GST registration — needed for invoice content and tax seed (M10).
SLA offered to customers — uptime %, credits, support response times. Drives §15 thresholds and plan terms.
Support cost tracking — will staff log ticket time? Without it, §17.2's supportCost is zero and per-customer margin is overstated. Decide before M12.
Refund policy — for the failed-provisioning and capacity-exhaustion cases (§20.2).
Backup retention beyond termination — 90 days is proposed; confirm against any contractual or legal requirement.
Minimum node size and target accounts per node — sets the economics; §9.4 and §17.3 need real numbers to be useful.
Which entity is the merchant of record for reseller customers — determines whether reseller billing is agency or resale, which changes the tax treatment entirely. Answer before Phase 2 starts, not during it.