Platform billing (Stage 3)
Stripe-managed subscriptions for customer hubs. Stripe is the source of truth; platform D1 mirrors subscription state via webhooks.
Related: roadmap §3 · platform provision · Account plans & Stripe products (Multi Home SKUs, env vars, verification)
Account plans & Stripe products
Household home allowance (Free = 1 home, Lovely Home+ = 1 with full features, Multi Home = 3 or 10) is defined in code (platformAccountHomeLimits.js) and surfaced on My Homes, Add Home, and pricing. Hub signup still bills through STRIPE_PRICE_ID / STRIPE_PRICE_ID_YEARLY (Lovely Home+) and STRIPE_PRICE_ID_FREE per site_billing row.
Account-level subscription Products (Lovely Home+, Multi Home 3/10) and their Pages env vars are documented step-by-step in Account plans & Stripe products — create those Prices in Stripe test and live, map ids when Terraform exposes STRIPE_ACCOUNT_PRICE_*, and use ACCOUNT_HOME_PLAN_OVERRIDE on platform Pages for QA.
Architecture
| Component | Location |
|---|---|
| Checkout + billing API | Platform Pages Functions — /api/platform/billing/* |
| Stripe webhooks | /api/stripe/webhook (no Cloudflare Access) |
| Billing mirror | D1 lovely-home-platform-billing → binding PLATFORM_BILLING_DB |
| Provision / deprovision | trialing webhook → hub-provision queue → Platform site provision; subscription.deleted / canceled → hub-provision queue (teardown) → registry drop |
One-time setup (test mode)
Stripe Dashboard (test mode) — create Product + recurring Price (GBP). Note
price_….Terraform — optional vars on
module.platform_admin(viaterraform/environments/hub.tfvars):stripe_secret_key=sk_test_…stripe_webhook_secret=whsec_…(from Stripe CLI or Dashboard endpoint)stripe_price_id= monthlyprice_…(e.g. £9.99/month)stripe_price_id_yearly= yearlyprice_…(e.g. £99/year)- Optional live twins (
stripe_secret_key_live,stripe_webhook_secret_live,stripe_price_id_live,stripe_price_id_yearly_live) — store them before public launch. Mode is switched from platform admin, not Terraform.
Important: Platform Pages env is managed by Terraform. Setting Stripe vars only in the Cloudflare dashboard is not enough — the next
terraform apply(including Platform site provision on any hub) rewrites env vars and removes dashboard-only secrets. Always keep Stripe values inhub.tfvars(local apply) and in GitHub Actions secrets (CI provision).For CI, add repo secrets
STRIPE_SECRET_KEY,STRIPE_WEBHOOK_SECRET,STRIPE_PRICE_ID,STRIPE_PRICE_ID_YEARLY(test) and the matchingSTRIPE_*_LIVEsecrets. Add repo variableSTRIPE_MODE(test|live). Verify after apply:bashbash scripts/verify-platform-stripe-env.shterraform apply— creates D1 database and bindsPLATFORM_BILLING_DBonhome-dashboard-platform.Apply migration:
bashnode scripts/apply-platform-billing-migration.mjsWebhook endpoint (production platform hostname):
https://platform.lovely-home.co.uk/api/stripe/webhookEvents:
checkout.session.completed,customer.subscription.*,invoice.paid,invoice.payment_failed,customer.subscription.trial_will_end.Cloudflare Access: Stripe cannot log in via OTP. Add a Bypass Access application for
platform.lovely-home.co.uk/api/stripe/webhook(Terraform:platform_stripe_webhookinterraform/modules/platform_admin/access.tf), or manually in Zero Trust → Access → Add application → path/api/stripe/webhook→ Bypass → Everyone. Without this, deliveries fail (302/500) and billing rows are never written.If you created the Access app manually first, import it before
terraform apply:bashexport CLOUDFLARE_API_TOKEN="..." bash scripts/import-platform-stripe-webhook-access.sh -var-file=environments/hub.tfvars cd terraform && terraform apply -var-file=environments/hub.tfvars
Local development
Forward Stripe webhooks to the platform dev stack:
# Terminal 1
npm run dev:platform
# Terminal 2 — after `stripe login`
stripe listen --forward-to http://127.0.0.1:8791/stripe/webhookSet secrets in .dev.vars on the platform Pages project or export for local testing:
STRIPE_SECRET_KEYSTRIPE_WEBHOOK_SECRET(fromstripe listen)STRIPE_PRICE_ID— monthly subscription priceSTRIPE_PRICE_ID_YEARLY— yearly subscription price (optional but recommended for public signup)
Public signup Checkout always sends managed_payments[enabled]=false and automatic_tax[enabled]=false so Lovely Home bills directly (not Stripe Managed Payments / merchant-of-record VAT). Use new Products whose tax code is not labelled “Eligible for Managed Payments”. Once a product has been used with Managed Payments, Stripe will not let you change its tax code — create a replacement product and point the price env vars at the new price_… ids.
Local currency on Checkout (Adaptive Pricing)
You keep one GBP Price per plan (STRIPE_PRICE_ID, yearly, live twins). International customers can see and pay in their local currency on the Stripe-hosted Checkout page via Adaptive Pricing.
- Stripe Dashboard (test and live) — Settings → Payments (or search “Adaptive Pricing”) and turn Adaptive Pricing on for Checkout.
- Deploy platform Pages — Checkout sessions send
adaptive_pricing[enabled]=trueby default (checkoutSessionLocalizationParamsinplatformBilling.js). SetSTRIPE_CHECKOUT_ADAPTIVE_PRICING=falseon the platform project to turn it off. - Test — In test mode, start a Plus signup Checkout from a non-UK browser/VPN or use Stripe’s preview tools; the total should show in local currency with an FX disclosure. Your payout/settlement stays tied to the Price currency (GBP); Stripe handles presentment FX.
- Marketing site — lovely-home.co.uk/pricing calls
GET /api/public/signup/pricing?lang=…and converts the GBP Stripe Prices into a presentment currency fromCF-IPCountry(fallback: UI language → EUR/CZK/PLN/…). Rates come from the ECB (Frankfurter). Checkout Adaptive Pricing remains the charge-time source of truth and may differ slightly from the marketing estimate.
Coupons (referral / intro) still apply; verify a discounted Checkout in test mode for your main markets.
Tax: Adaptive Pricing is separate from VAT/sales tax. If you sell to EU/US consumers at scale, review Collect taxes for recurring payments before enabling automatic_tax.
Test and live: repeat product creation in both Stripe modes. Update STRIPE_PRICE_ID / STRIPE_PRICE_ID_YEARLY (test) and STRIPE_PRICE_ID_LIVE / STRIPE_PRICE_ID_YEARLY_LIVE (live), then apply Terraform / redeploy platform Pages. Cancel old test subscriptions on the legacy MP product; live only needs new prices before you take real signups on the old product.
Local dev API (scripts/platform-admin-dev-api.mjs) does not yet mirror billing routes — use deployed preview or wrangler pages dev for full billing tests.
Operator API (Access-protected)
Create Checkout session (Lovely Home+, card at signup)
Lovely Home+ Checkout collects a card and starts an active subscription — there is no trial period. Use the Free plan for a no-card tryout.
POST /api/platform/billing/checkout
Content-Type: application/json
{
"siteId": "smith",
"customerEmail": "owner@example.com"
}Response: { "ok": true, "sessionId": "cs_…", "url": "https://checkout.stripe.com/…" }
List billing records
GET /api/platform/billingSite billing status
GET /api/platform/billing/sites/smithTest cards
Use Stripe test cards — e.g. 4242 4242 4242 4242, any future expiry, any CVC.
Advance trial billing without waiting 7 days: Stripe test clocks — see Testing referrals with Bob and Robert below.
Referral scheme
Single-use opaque links (LH-XXXX-XXXX) generated from account.html after OTP sign-in.
| Plan | Referee (new signup) | Referrer (when referee pays) |
|---|---|---|
| Monthly | £5 off each of the first two paid months | £10 Stripe account credit |
| Yearly | £15 off the first year | £15 Stripe account credit |
Referrer eligibility: you can generate referral links only after your own first paid invoice (referrer_eligible_at on site_billing).
Timing: referee discounts apply on Stripe invoices (coupon on the subscription). Referrer credit is added on the referee's first paid invoice (invoice.paid), not at checkout. A referral link created before the referrer paid is rejected at signup once eligibility is enforced.
Each generated link is single-use. Referrers can keep multiple unused links active (for inviting several people).
Testing referrals with Bob and Robert
Typical sandbox setup:
| Role | Customer | What to test |
|---|---|---|
| Referrer | Bob B | Becomes eligible to refer after his first paid invoice |
| Referee | Robert R | Signed up with Bob's link; £5 off applies on Robert's first paid invoice after trial; Bob gets £10 credit when Robert's first invoice is paid |
Fast path (existing subscriptions, no test clock):
- Stripe Dashboard → Customers → Bob B → open his subscription.
- Actions → Update subscription → End trial now (or set trial end to now).
- Pay the £9.99 invoice with test card
4242 4242 4242 4242. - Confirm webhook
invoice.paidwithamount_paid: 999— platform sets Bob'sreferrer_eligible_atand (if Robert already paid) may credit Bob. - Repeat End trial now for Robert R's subscription. His first paid invoice should show the referral coupon (£5 off → £4.99 on month one).
- On Robert's
invoice.paid, check Bob's Stripe customer Balance (+£10).
Test clock path (new signups):
- Dashboard → Developers → Test clocks → Create test clock (frozen at today).
- New customers/subscriptions must be created on that clock (API:
test_clockon Customer create). Existing Bob/Robert subs created without a clock cannot be moved — use End trial now for those. - Advance the clock 8 days (past the 7-day trial) → Stripe generates invoices → pay with the default test payment method.
- Advance again for the next billing cycle to see the second month's £5-off invoice for monthly referees.
Apply migration 0011_referrer_eligible.sql after deploy:
node scripts/apply-platform-billing-migration.mjsStripe coupons (create in Dashboard, test + live)
Monthly referee coupon
- Amount off: £5.00 GBP
- Duration: Repeating, 2 months
Yearly referee coupon
- Amount off: £15.00 GBP
- Duration: Once
Copy each coupon id (…) into platform Pages env (via Terraform hub.tfvars):
STRIPE_REFERRAL_COUPON_MONTHLY/STRIPE_REFERRAL_COUPON_MONTHLY_LIVESTRIPE_REFERRAL_COUPON_YEARLY/STRIPE_REFERRAL_COUPON_YEARLY_LIVE
Apply migration 0009_referral_codes.sql:
node scripts/apply-platform-billing-migration.mjsPublic API:
GET /api/public/signup/referral/{code}— preview benefit copy for signup pagePOST /api/public/signup— optionalreferralCode(from?ref=on signup.html)POST /api/public/account/referral-code— generate a new single-use link (requires account session)
Referrer rewards use Stripe customer balance credits on the referee's first paid invoice; referee discounts use Checkout discounts on the subscription (applied to post-trial invoices).
When a reward is credited, the referrer receives email from Lovely Home (support@lovely-home.co.uk via Resend) with the amount and a link to account.html.
Where referral credit appears in Stripe
| View | What you see |
|---|---|
| Stripe Dashboard (your platform account) → Customers → Bob B | Credit balance (e.g. £10.00) and Balance transactions (negative amount = credit added) |
| Customer Portal (what Bob sees on “Manage billing”) | Applied balance on the next upcoming invoice — often shows £0.00 due until credit is used up |
| Developers → Events | invoice.paid on the referee’s subscription triggers the platform webhook that adds credit |
The credit is not a separate line on your Stripe Home dashboard — open the referrer’s customer record to see it.
Introductory offer (new households)
Automatic discount for first-time customers at public signup on lovely-home.co.uk. An email is eligible only if it has never appeared on a site_billing row (including canceled hubs). Referral links take precedence — intro offers never stack with referrals. Operator billing checkout from the platform admin is never discounted.
| Plan | Intro benefit (after trial) |
|---|---|
| Monthly | 25% off each of the first two paid months |
| Yearly | 30% off the first year |
At list price (£9.99/month, £99/year), that is roughly £2.50/month × 2 or ~£30 off the first year — sweeter than the flat referral referee discounts.
Trial length stays 7 days. Discounts apply on Stripe invoices after the trial (coupon on the subscription), same timing as referrals.
Operator toggle
Stored in D1 platform_settings.intro_offer_enabled (default off). Toggle from Platform admin → Introductory offer (POST /api/platform/intro-offer with { "enabled": true }). Requires intro Stripe coupons to be configured before enabling.
While the offer is on, the home page shows a terracotta offer bar at the very top (an Offer tag, the promo line from the pricing API, and a Claim offer button to /signup). It replaces the old live-demo bar, which was removed in #1053; the demo login is shown on the demo sign-in page instead.
Apply migration 0010_intro_offer_setting.sql:
node scripts/apply-platform-billing-migration.mjsStripe coupons (create in Dashboard, test + live)
Monthly intro coupon
- Percent off: 25%
- Duration: Repeating, 2 months
Yearly intro coupon
- Percent off: 30%
- Duration: Once
Create separate coupon ids from referral referee coupons so launch offers can differ.
Copy each coupon id into platform Pages env (via Terraform hub.tfvars locally, or GitHub Actions secrets for CI-generated tfvars):
STRIPE_INTRO_COUPON_MONTHLY/STRIPE_INTRO_COUPON_MONTHLY_LIVESTRIPE_INTRO_COUPON_YEARLY/STRIPE_INTRO_COUPON_YEARLY_LIVE
For CI terraform (generate-hub-tfvars.mjs), also set matching GitHub repository secrets so hub provision does not drop coupon env vars on the platform Pages project:
node scripts/sync-stripe-coupon-github-secrets.mjsReads terraform/environments/hub.tfvars (or pass a path) and runs gh secret set for each coupon id present. Requires gh auth login.
Public API:
GET /api/public/signup/pricing— includesintroOffer.activeand benefit copy when enabledPOST /api/public/signup— applies intro coupon at checkout when eligible (server-side; not client-controlled)
Marketing pricing copy (display only)
Operators can edit what lovely-home.co.uk shows for list prices, trial wording, intro-offer lines, and referral benefits from Platform admin → Marketing pricing copy. Overrides are stored in D1 (platform_settings.marketing_pricing_display) and merged into GET /api/public/signup/pricing (and referral preview APIs).
Does not change Stripe: checkout still uses Terraform/env price IDs and coupon IDs. If marketing copy says “£8.99/month” but Stripe charges £9.99, the customer sees the real amount on the Stripe page. Change Stripe products/prices in the Dashboard, then update Terraform price env vars when the billed amount should change.
Apply migration 0013_marketing_pricing_display.sql:
node scripts/apply-platform-billing-migration.mjsOperator API: GET / POST /api/platform/marketing-pricing (POST { "reset": true } clears overrides).
Help & FAQ: owner help source (src/help/ownerSections.js) uses placeholders such as {introMonthlyBenefit} and {referralMonthlyReferee}. The marketing Help page and embedded FAQ lists load GET /api/public/signup/pricing and substitute live copy at runtime. After editing owner help, run npm run build:website-help so website/help-data.js stays in sync.
Slice 2 — provision on paid signup (shipped)
When Stripe sends checkout.session.completed or customer.subscription.created with status active (legacy rows may still show trialing):
- Platform D1 billing row is upserted (as before).
- If the site is in
platform-manifest.jsonbut has no Terraform contract yet, the platform dispatchesplatform-site-provision.ymlviaPLATFORM_GITHUB_TOKEN. site_billing.provision_dispatched_atis set on success so duplicate webhooks do not re-run provision.- If GitHub dispatch fails, the webhook returns 503 (Stripe retries) and
provision_last_erroris recorded.
Skipped automatically for production, demo, sites that already have a D1 contract in the manifest, or when provision was already dispatched.
Apply migration after deploy:
node scripts/apply-platform-billing-migration.mjsOperator test: add a registry-only site (e.g. practice) with no Terraform contract, run Checkout for that siteId, confirm GitHub Actions Platform site provision starts.
Slice 2b — deprovision on cancel (shipped)
When Stripe sends customer.subscription.deleted or customer.subscription.updated with status canceled (includes unpaid):
Platform D1 billing row is updated to
canceled.If the site was live (provisioned or had
trialing/active/past_duebilling), the platform dispatchesplatform-site-billing-deprovision.ymlviaPLATFORM_GITHUB_TOKEN. A staleplatform-manifest.json(the post-provision follow-up PR has not deployed yet) does not block that dispatch.The workflow: archive hub JSON to platform R2 (while the hub is still live) → refresh
origin/main(wait untilattach_hub_api_binding: trueso the provision follow-up is not still in flight) → open a registry removal PR (auto-merge when CI passes) → merge triggersplatform-site-deprovision.ymlfor Terraform destroy + Worker delete + manifest rebuild. A stale checkout ofmainfrom job start conflicts with the “mark provisioned” PR on the same yaml/toml blocks.site_billing.deprovision_dispatched_atis set on success;deprovision_last_erroron dispatch failure (webhook returns 503 for Stripe retry).One teardown per cancellation (#1104). Stripe sends several events for one cancellation (
customer.subscription.deleted, then.updatedwith statuscanceled). Two rules keep these to one teardown:- An atomic claim. The teardown is claimed with a single compare-and-set on
deprovision_dispatched_at, so when two webhooks arrive together, only the one whose update changes the row enqueues. - No repeat while one is running. Once a teardown is dispatched, later events don't queue another one. That holds while the site is still in the manifest, because it stays there until the first teardown finishes.
A new teardown is allowed only if:
- the last dispatch recorded an error,
- billing is live again, or a provision was dispatched after the teardown, or
- the teardown is over 2 hours old and the hub is still registered (
DEPROVISION_STALE_MS).
- An atomic claim. The teardown is claimed with a single compare-and-set on
invoice.payment_failedsetspast_dueonly — hub stays live while Stripe retries billing.
Apply migrations after deploy:
node scripts/apply-platform-billing-migration.mjsOperator test: cancel a test subscription in Stripe Dashboard (or end a test clock) → confirm Platform site billing deprovision runs for that siteId.
Re-trial and subscription resume
The same site_id can go through multiple billing cycles (throwaway test hubs, cancel → sign up again).
| Stripe event | Platform behaviour |
|---|---|
| New trial / checkout after prior deprovision | Clears stale deprovision_dispatched_at / provision_dispatched_at (and signup_email_sent_at) when status becomes trialing or active again after the earlier cycle ended: resumed from canceled, or a teardown was dispatched. Re-provision runs if the manifest has no Terraform contract. A different subscription id on its own doesn't count (#1116). While a hub is still being built, a second subscription used to re-provision it and re-send the sign-up email. |
Cancel while hub is live (trialing / active / past_due) | Dispatches billing deprovision even if an earlier cycle already set deprovision_dispatched_at. |
Cancel at period end (still trialing until period ends) | No deprovision until status becomes canceled. |
Resume before period end (cancel_at_period_end cleared) | subscription.updated → status stays trialing / active; no deprovision. |
Duplicate subscription.deleted webhooks | Second event skipped via already_dispatched once D1 status is canceled. |
Archive JSON in R2 is kept across cycles for restore (platform-site-archive.md). After reprovision CI succeeds, scripts/restore-hub-site-from-archive.mjs loads the billing archive_r2_key from platform R2 and calls POST /api/platform/site-restore on the hub Worker (same shared secret as pre-deprovision export).
Customer retention and reinstate (close hub)
When a household closes a hub (Close hub on Billing for a Free home or a home on a Multi Home plan, Stripe cancel, or subscription deleted):
Homes on a Multi Home plan (#1448). A home added from Add another home shares the account's Stripe customer and has no subscription of its own (stripe_subscription_id is NULL); the account plan pays for it. hubBilledByAccountPlan (platformBilling.js) spots these, Billing offers Close hub on them, and closeAccountPlanHub closes one without any Stripe call: the account plan's price doesn't depend on how many of its homes are live. The home is marked canceled, its name held, its teardown queued, and the owner gets "Your Lovely Home hub … is closing" (the plan and other homes stay as they are). Cancelling the plan itself is below. The account plan columns (account_subscription_plan, account_stripe_subscription_id, account_stripe_customer_id) sit on every one of the owner's rows. syncAccountSubscriptionToOwnerRows only updates rows that already exist, so upsertSiteBilling copies those columns from the owner's other rows when it inserts a new one (#1460). Before that, a home added on Multi Home had no plan on its row, looked like a Plus hub with nothing to cancel, and Close hub returned 409.
Cancelling or shrinking an account plan (#1450, #1451, #1452). Multi Home and account Lovely Home+ are one Stripe subscription, so they are changed from the Account plan card on Billing, not per hub, and not in the Stripe portal (its configuration has cancel and plan switches turned off; it keeps the card and invoices, #1453). The flow (platformAccountPlanEnding.js):
- Cancel plan →
POST /api/public/account/plan-cancel{ sessionToken, keepSiteIds }. Stripe is toldcancel_at_period_end; the row inaccount_plan_changes(migration 0029) recordsends_at(the period end),next_planfreeandreasoncancel. Switch to a smaller paid plan →…/plan-switch{ accountPlan, keepSiteIds }: same, withreasondowngrade; Stripe is not changed until the date. Upgrades keep using checkout. - The owner picks which homes carry on (the next plan's allowance: 1, 3 or 10). The rest get
closes_at_plan_end = 1onsite_billing. Before the date they can Keep my plan (…/plan-keep, undoes it, refused once Stripe itself ended the plan) or pick different homes (…/plan-homes). The eligibility call returnsaccountPlanChange(endsAt,nextPlan,reason,pastDueAt,keepSiteIds,closeSiteIds) and each hub carriesclosesAtPlanEnd, which is what Billing renders. - The date comes. Either Stripe's
customer.subscription.deletedarrives (cancel) or the daily run findsends_atin the past:finalizeAccountPlanChangecloses the flagged homes throughfinishOwnerHubClose(teardown queued, name held, no per-hub email), then for a cancel puts the remaining rows onplan_tier = 'free'and clears the account subscription columns, or for a switch moves the Stripe subscription to the new price (proration_behavior: none, the new price starts with the next invoice) and syncs the rows. One "Your … plan has ended" / "Your plan is now …" email. - Stripe ends the plan on its own (card failed for weeks, or an operator cancelled in the Dashboard): the plan is cleared at once (the hubs read Free from the next plan-status call) and homes beyond the Free allowance get a 14-day grace (
reasonstripe): closed by the daily run unless the owner upgrades again. A live account plan (thecustomer.subscription.*webhook with status active/trialing, orsyncOwnerAccountPlanFromStripe) callsclearEndedAccountPlanGrace, which deletes the change row and clearscloses_at_plan_end(#1462). It only touchesreasonstripe; a cancel or switch the owner scheduled stays. - Daily run. The hub-jobs Worker's 09:00 cron also calls
POST /api/public/account-plan-run(sameX-Activation-Run-Secretas activation emails;handleAccountPlanRun→runAccountPlanEndings): finalises due changes and sends the reminder a week before (not for grace cases). Each email is sent once:sendAccountPlanEmailOnceclaims the matching*_email_sent_atcolumn first. - Card failed on the account subscription.
invoice.payment_failedwith nosite_idand an account subscription id markspast_due_atand sends "Payment failed for your … plan" once;invoice.paidon that subscription clears it. Billing shows the notice while it is set. - No grandfathering (#1451). After the plan has ended the rows say
plan_tier = 'free'and carry no account subscription, soinferAccountSubscriptionPlanhas nothing to infer from; it still counts live Plus homes only for accounts that never had an account subscription (legacy per-hub Plus).
| Stage | What happens |
|---|---|
| Live site | Stays up until the end of the current billing period when one applies; Free close may tear down after archive succeeds. |
| Teardown | Billing deprovision archives guide JSON to platform R2, then registry removal + Terraform destroy (see platform-provision.md). |
| Retention | Platform archive + hub name hold for the same owner email for about 12 months — customer copy: “All hubs can rejoin within 12 months and carry on where you left off.” |
| Reinstate | Owner uses Account → Billing or My Homes (POST /api/public/account/reinstate-hub) or public signup with the same name while the hold applies; provision CI runs restore-hub-site-from-archive.mjs when archive_r2_key is set. |
| Full backup | Owner should download an encrypted full backup from the hub before close — platform archive is guide JSON only (no photos/PDFs). |
After the reclaim window, operators may purge D1 billing rows so the slug can go to a new household (scripts/purge-platform-site-for-reuse.mjs — only after deprovision completes).
Close account (#1528)
The account holder closes the whole account from Account → Team → Close account. A pop-up says what happens now and after 7 days, with Keep my account as the main button; Close my account stays off until the holder types their email.
- Close →
POST /api/public/account/close{ sessionToken, confirmEmail }(handleAccountClose,platformAccountClosure.js). Insertsaccount_closures(migration 0033:account_email,requested_at,deletes_at,reminder_email_sent_at) first, so Stripe's webhooks for what it cancels next see the account closing. ThencloseAccountHomes: every live home's own subscription (Free £0 or Lovely Home+) is deleted in Stripe now, the home goes throughfinishOwnerHubClose(canceled, name held, teardown queued) with no per-home email, andcanceled_email_sent_atis claimed so the webhook doesn't send one either. The account plan subscription is deleted too and the rows end on Free. One "Your account is closing" email lists the homes and the date. deletes_at= 7 days later, moved to 08:00 UTC of the next day the 09:00 run sees, so the date shown is the day it really happens.- While closing the public router refuses every account change except
account/reopenwith409 ACCOUNT_CLOSING; team members can't sign in to the account (resolveSessionAccount), and a public sign-up with the holder's email is refused. Every account page shows a banner with the date and Reopen account (account.closesAtin the session payload).handleAccountSubscriptionEndedends the plan without grace or "plan ended" email. - Reopen →
POST /api/public/account/reopendeletes the row. Homes stay closed; Billing offers Reinstate as usual (archive and name hold are still there). A paid plan has to be picked again. - Daily run (
account-plan-run→runAccountClosures): finishes any home a close couldn't (Stripe or queue error), sends the reminder the run beforedeletes_at, and ondeletes_atcallspurgeClosedAccount. That refuses while a home is live or still in the site registry (teardown not finished) and when theHUB_ARCHIVESR2 binding is missing; otherwise it deletes{site}/…from the archive bucket and the account's D1 rows (site_billing, name holds, attribution, activation, suspensions, build attempts, account_homes, referral codes it issued, saved setups, plan changes, team, name, sessions, sign-in codes, the closure), then sends "Your account has been deleted". Refusals show in the run's JSON (accountClosures.results) and are retried next day. - Kept: the Stripe customer and its invoices (the billing records the privacy page keeps for 6 years). The holder's place on other people's teams is theirs to remove.
- Infra: the platform Pages project binds the archive bucket as
HUB_ARCHIVES, production only (#1530). The Cloudflare provider'sr2_bucketsfailed with 8000022 "Invalid R2 bucket name ()", soterraform_data.hub_archives_bindinginterraform/modules/platform_admin/pages.tfrunsscripts/attach-platform-archives-binding.mjs, which PATCHes the binding through the Pages API and checks it stuck; the project ignoresr2_bucketsdrift. If closed accounts stay in the daily run's results withARCHIVES_NOT_BOUND, check the binding is on the project's production settings.
Slice 3 — public signup (in progress)
Marketing site (lovely-home.co.uk)
| Page | Purpose |
|---|---|
/pricing.html | Transparent pricing — monthly amount loaded from Stripe via public API |
/signup.html | Hub name + owner email → Stripe Checkout |
/signup-success.html | Post-checkout “we’re provisioning your hub” |
Home page and signup link to Pricing and Start free trial.
Public API (platform Pages, no Access)
Managed by Terraform on module.platform_admin (via terraform/environments/hub.tfvars):
| Terraform variable | Pages env var | Purpose |
|---|---|---|
marketing_site_origin | MARKETING_SITE_ORIGIN | CORS + Checkout return URLs (default https://lovely-home.co.uk) |
public_signup_enabled | PUBLIC_SIGNUP_ENABLED | Set true to enable /api/public/signup (requires Stripe + platform_github_token) |
turnstile_site_key | TURNSTILE_SITE_KEY | Optional Cloudflare Turnstile widget key. Setting both keys turns on the bot check |
turnstile_secret_key | TURNSTILE_SECRET_KEY | Turnstile server secret used to verify the token |
Also requires the Stripe vars from One-time setup. Do not set these only in the Cloudflare dashboard — the next terraform apply overwrites Pages env.
Cloudflare Access: Browser calls from lovely-home.co.uk hit platform.lovely-home.co.uk/api/public/*. Terraform creates a Zero Trust bypass application for that path (same pattern as /api/stripe/webhook). Without public_signup_enabled = true + terraform apply, slug checks fail with a CORS error after an Access login redirect.
When public_signup_enabled = true, Terraform also creates a Zero Trust bypass for /api/public/* (same pattern as the Stripe webhook). Without it, browser requests from lovely-home.co.uk hit the Access login redirect and fail CORS during slug checks.
Pre-launch marketing site gate: Set marketing_site_access_protected = true in hub tfvars to require OTP on lovely-home.co.uk (terraform/modules/marketing_site). Operators always stay on that list. Extra preview emails are guests managed from Marketing site access on the platform dashboard — they do not get platform Access. Set false at public launch.
| Endpoint | Method | Purpose |
|---|---|---|
/api/public/signup/status | GET | Whether signup is enabled |
/api/public/signup/pricing | GET | Trial length + monthly/yearly prices from Stripe |
/api/public/signup/slug/{siteId} | GET | Slug availability check |
/api/public/signup | POST | Slug reservation + Stripe Checkout { siteId, customerEmail, billingInterval?, turnstileToken? } (month or year) |
/api/public/hub-status/{siteId} | GET | Provisioning status for the success page — probes {siteId}.lovely-hub.com and returns { state, ready, hubUrl, plan } (plan is free, plus, multi_3, multi_10, or null until billing is live) |
/api/public/contact/status | GET | Whether the Support contact form can send mail (enabled) plus optional Turnstile site key |
/api/public/contact | POST | Support contact form { name, email, subject, message, hub?, turnstileToken? } — emails support@lovely-home.co.uk via Resend |
Nothing is provisioned until Stripe confirms payment. Signup only reserves the slug and opens Checkout; the registry PR is dispatched from the webhook:
POST /api/public/signup— Turnstile check (if configured) → per-IP rate limit → slug availability (including live reservations) → Stripe Checkout session → reserve the slug for the life of the session. No GitHub dispatch, no Cloudflare resources.- Stripe
checkout.session.completed/customer.subscription.createdwith atrialingsubscription → dispatch platform-site-manage to open the registry PR (registry_dispatched_atis claimed with an atomic D1 update before GitHub is called, socheckout.session.completedandcustomer.subscription.createdcannot open two PRs) → release the slug reservation now that the registry owns the name. - Registry PR merges → platform-site-provision builds the hub.
Abandoned checkouts therefore cost nothing and free their slug when the reservation expires. registry_last_error records a failed dispatch so a Stripe webhook retry (or a manual replay) can pick it back up.
Signup abuse controls, all backed by the platform billing D1 database:
| Control | Behaviour |
|---|---|
| Rate limit | Fixed window per client IP; the IP is stored only as a SHA-256 hash. Over the limit returns 429 with error: rate_limited |
| Daily alert | New public sign-ups (Free subscription or Plus Checkout started) per UTC day, including reinstates (same owner reclaiming a torn-down name). Default alert at 10 (no hard stop). When the count reaches the threshold, platform operators (or PUBLIC_SIGNUP_ALERT_EMAILS when set) get one Resend email per UTC day (requires RESEND_API_KEY). Edit thresholds in Platform admin → Platform settings → Sign-up limits (GET/POST /api/platform/signup-daily-settings). Stored in D1 platform_settings (signup_daily_alert_at, signup_daily_hard_cap). |
| Per sign-up notify | Each successful public sign-up sends one operator email when a notify inbox is configured (D1 signup_notify_email via Platform admin → Sign-up limits, or PLATFORM_SIGNUP_NOTIFY_EMAIL / Terraform platform_signup_notify_email as fallback). Includes hub hostname, plan, UTC time, reinstate flag, and owner email. Separate from the daily threshold alert. |
| Daily hard cap | Optional. Default 0 (unlimited). When set above zero, sign-ups over the cap return 503 with error: SIGNUP_DAILY_CAP. Lifecycle e2e-… slugs bypass limits. |
| Slug reservation | An in-flight Checkout holds the slug, so two buyers cannot race for one hostname |
| Turnstile | Active only when both Turnstile keys are set; signup/status advertises the site key so the widget renders itself |
| Edge rate limits | Terraform http_ratelimit rules on the marketing zone for platform /api/public/signup, slug checks, account OTP, and contact — see signup-abuse-protection.md |
Provisioning takes up to 10 minutes end to end (often faster when queues are clear), so signup-success.html polls hub-status and only shows the Open button and hub QR code once the hub SPA is actually serving (HTML contains hub-shell). Cloudflare Access often starts redirecting to login a few minutes before Pages has deployed the app — that still counts as provisioning. registry_last_error (invalid hostname, GitHub dispatch, or a failed platform-site-manage create) and provision_last_error (GitHub dispatch or a failed platform-site-provision run) both surface as state: "failed" so the success page can stop the spinner. After 30 minutes without a live hub the page asks for support instead of showing a QR.
The page's first step names the owner's plan from hub-status.plan (#963): Lovely Home Free, Lovely Home+, or Multi Home (3 or 10 homes, from the owner's account plan across all their homes). It says just "Signup is confirmed." until billing is live, for example while the Stripe webhook is still arriving. Add-home signups (from=add-home) say the hub is being added to the account. The steps are written by signup-success.js and translated through window.LovelyHomeTranslatePageBody, so new step text needs entries in every website/pageLocales/*.js.
Customer emails
The webhook also sends mail through Resend when RESEND_API_KEY is set on platform Pages (Terraform: resend_api_key). Without the key, billing still works; the customer only gets Stripe’s own receipts.
| Stripe event | |
|---|---|
checkout.session.completed (and customer.subscription.created if checkout did not already send) | Hub setup in progress ("usually about 3 minutes, we will email you when it is live"), first-step checklist, hub URL, success-page link, Help |
| hub answers for the first time (hub-status poll or 15-minute sweep, #1506) | Your hub is live: Open link, setup checklist, how the Cloudflare sign-in code arrives (hub_live_email_sent_at) |
| build gave up after every attempt (#1508) | We could not build your hub today: we have been alerted, finished by hand, email follows, nothing charged (build_failed_email_sent_at); the sign-up notify inbox gets "Hub build stopped" |
customer.subscription.trial_will_end | Trial ending; first charge date |
invoice.payment_failed | Card failed; hub stays up while Stripe retries |
customer.subscription.deleted / canceled | Hub is ending; download a backup while it is up |
Each kind is recorded on site_billing (signup_email_sent_at, …) so webhook retries do not send twice. The two build emails need migration 0032_hub_build_status.sql; how builds are tracked is in platform-provision.md → Build tracking and feedback. Reinstates (same owner reclaiming a hub after teardown) send the welcome-back signup mail again; signup_email_sent_at is cleared when billing cycle flags reset after deprovision. From-address defaults to Lovely Home <support@lovely-home.co.uk> (customer_email_from / CUSTOMER_EMAIL_FROM). Verify that domain in Resend before going live.
Owners manage billing themselves at lovely-home.co.uk/account.html: email OTP (Resend), then a Stripe Customer Portal session (POST /v1/billing_portal/sessions). Marketing account sessions last 30 minutes from sign-in (expiresAt on verify and POST /api/public/account/session); signed-in account pages show a centred warning toast two minutes before logout, with Stay signed in (extends via POST /api/public/account/session) or dismiss until the next warning window (#LH-43–49). Activate the portal in Stripe Dashboard → Settings → Billing → Customer portal (allow card update, invoices, and cancel). After a subscription is cancelled, Stripe’s portal only shows invoices and the saved card — there is no live plan to cancel or change. The account page states Cancelled. Apply the OTP tables after deploy:
node scripts/apply-platform-billing-migration.mjsSet GitHub secret RESEND_API_KEY (and the same value in hub.tfvars) so the next terraform apply does not wipe it.
Account team (#1474)
An account can have up to 10 more people as Admin, Maintainer or Read only (Account → Team). Migration 0030_account_members.sql adds the account_members table and account_sessions.account_email (which account a sign-in acts on; null = the person's own). Apply it before the deploy that uses it.
- Sign-in: a team member asks for a code with their own email. They land on their own account if they hold homes, otherwise the first account they were added to; someone on several accounts switches from the toolbar (
POST /api/public/account/switch). - Role checks: the public router checks the role before any account route runs (
accountRouteRoleinfunctions/api/platform/platformAccountTeam.js). Billing, add/close/reinstate home, referral and Team changes need Admin; cancelling the whole plan needs the account holder; stays, cleaners and saved setups need Maintainer. Anything else on the account is readable by everyone on it. A refused call is403 ACCOUNT_ROLE. - API:
POST /api/public/account/team(list) andPOST /api/public/account/team/manage{ action: add | role | remove, email, role }. Adding sends the person an invite email; the response listshomesPending(homes that didn't take the change yet; they pull it within the hour). - Account name (#1481):
POST /api/public/account/team/name{ name }(Admin; up to 60 characters, empty clears it) stores it inaccount_profiles(migration0031_account_profiles.sql). The team list returnsaccountName, the session and switch responses returnaccount.nameandaccounts[].name, and the invite email names the account by it. With no name the holder's email is used, and the invite never repeats it. - Billing: Stripe customer and receipts stay with the account holder. Team members don't count towards any plan limit.
- How it reaches hubs is in Cloudflare Access → Account team.
Going live
Keep both Stripe key sets on platform Pages. D1 platform_settings.stripe_mode is the source of truth (test until you switch).
- Create the live Product and Prices in the Stripe Dashboard (live mode). Register the same webhook URL (
https://platform.lovely-home.co.uk/api/stripe/webhook) in live mode and copy itswhsec_…. - Put live values in
hub.tfvarsand GitHub secretsSTRIPE_SECRET_KEY_LIVE,STRIPE_WEBHOOK_SECRET_LIVE,STRIPE_PRICE_ID_LIVE,STRIPE_PRICE_ID_YEARLY_LIVE. Apply Terraform so Pages receives them. Test keys stay in the existingSTRIPE_*vars. - Apply billing migrations so
0007_platform_settings.sqlexists:bashnode scripts/apply-platform-billing-migration.mjs - Grant
PLATFORM_GITHUB_TOKENpermission to write Actions variables (fine-grained: Variables read/write). The go-live button sets repo variableSTRIPE_MODE. - On platform admin, use Go live… and type
GO LIVE. If D1 still has open test subscriptions, tick the acknowledgement. Reverse with Switch to test mode… andUSE TEST. - Run the on-demand lifecycle test while still in test mode before going live — see e2e/README.md.
Checkout, webhooks, public pricing, and the customer portal all read the active mode. terraform apply does not flip the switch.
Lifecycle regression
npm run test:lifecycle and workflow Hub lifecycle (Stripe test) (workflow_dispatch only) sign up a throwaway e2e-… hub with the test card, wait for hub-shell, cancel the trial immediately, and assert teardown. They refuse to run when STRIPE_MODE is live or the secret is not sk_test_.
Deploy marketing pages after merge:
bash scripts/deploy-lovely-home-website.shPlatform admin deploys from GitHub on main; run terraform apply to push env vars, or bash scripts/deploy-platform-admin.sh for Functions-only updates.