Hub 2.21.0: install the Church Website; Website storage bought in steps

- New install offers the Church Website: Accounts first when the church has
  none, at accounts.<its address> (www. dropped); the FastPanel email sends a
  www. site's bare domain to www. with a 301.
- Licence.extraStorageSteps (migration): the token sends a Website its limit
  (5 GB + steps, limits.storageBytes, contracts 1.17.0); invoices bill the
  steps bought instead of the storage reported. Edit popup field 0-99.
- A Website/App licence starts on its plan however it's made (New install too).
- Vendored @crosscode/contracts 1.17.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 00:03:21 +02:00
co-authored by Claude Opus 5.5
parent 6f8242064f
commit c6f734ab20
21 changed files with 235 additions and 36 deletions
+9
View File
@@ -9,6 +9,7 @@ const { generateLicence, checkReopen } = require('../utils/licences');
const { PRODUCTS, isProduct, PRODUCT_NAMES } = require('../utils/products');
const compute = require('../utils/billing/compute');
const { ymd, today } = require('../utils/billing/dates');
const { MAX_STORAGE_STEPS } = require('../utils/billing/tiers');
const { linkedProductsFor } = require('../utils/protocol');
const { audit } = require('../utils/audit');
const { getSettings, setSettings } = require('../utils/settings');
@@ -245,6 +246,14 @@ router.put('/licences/:id', wrap(async (req, res) => {
const existing = await prisma.licence.findUnique({ where: { id: req.params.id } });
if (!existing) throw bad('Licence not found', 404);
const data = licenceData(req.body, { partial: true });
// Hub 2.21.0: a Website's extra storage steps (5 GB each), sent to the site as its storage limit
// with the next heartbeat and billed from the next invoice.
if (req.body?.extraStorageSteps !== undefined) {
if (existing.product !== 'website') throw bad('Only a Church Website licence has extra storage.');
const n = Number(req.body.extraStorageSteps);
if (!Number.isInteger(n) || n < 0 || n > MAX_STORAGE_STEPS) throw bad(`Extra storage: 0–${MAX_STORAGE_STEPS} steps of 5 GB.`);
data.extraStorageSteps = n;
}
await checkReopen(prisma, existing, data.status);
const licence = await prisma.licence.update({ where: { id: existing.id }, data }).catch(e => {
if (e.code === 'P2002') throw Object.assign(bad(`This customer already has an open ${PRODUCT_NAMES[existing.product]} licence.`, 409), { code: 'PRODUCT_LICENCE_EXISTS' });
+4 -3
View File
@@ -20,7 +20,7 @@
*/
const {
tierNamed, reviewTier, planPrice, extraStorageBlocks, STORAGE, ADDRESS, BUNDLE_PERCENT, YEARLY_MONTHS, FOUNDING_PERCENT,
tierNamed, reviewTier, planPrice, STORAGE, ADDRESS, BUNDLE_PERCENT, YEARLY_MONTHS, FOUNDING_PERCENT,
} = require('./tiers');
const { ymd, day, addDays, addMonths, periodLabel, shortDate } = require('./dates');
const { PRODUCTS, PRODUCT_NAMES, BILLABLE } = require('../products');
@@ -213,9 +213,10 @@ function customerInvoiceLines({ customer, licences, period, reviewed }) {
add(`${label}, ${shortDate(licence.billedFrom)} – ${shortDate(end)} (${days} day${days === 1 ? '' : 's'}, from its start)`, 1, Math.round(perDay(price.monthlyCents) * days));
}
// Add-ons for the whole period only (measured now), never discounted.
// Add-ons for the whole period only, never discounted. Hub 2.21.0: the storage steps bought
// (the limit in the site's licence), no longer what the site reports using.
if (product === 'website' && ymd(licence.billedFrom) <= ymd(start)) {
const blocks = extraStorageBlocks(licence.install?.stats?.storage);
const blocks = Math.max(0, Number(licence.extraStorageSteps) || 0);
if (blocks) {
const m = monthsIn(cycle);
addOns.push({
+17 -2
View File
@@ -113,7 +113,22 @@ function planPrice(plan, customMonthlyCents = null, product = 'events') {
return { monthlyCents: tier.monthly * 100, foundingCents: tier.founding * 100, custom: false };
}
/** How many extra 5 GB blocks a website uses (from its heartbeat's `storage`). */
/** Most extra storage steps one Website licence can have (500 GB in all). */
const MAX_STORAGE_STEPS = 99;
/**
* A Website's storage limit (Hub 2.21.0, WEBSITE-1.0-PLAN decision 12): the 5 GB included plus
* the extra steps bought. Sent in the licence token; uploads stop when it's full.
*/
function storageLimitBytes(steps) {
const n = Number.isInteger(steps) && steps > 0 ? Math.min(steps, MAX_STORAGE_STEPS) : 0;
return STORAGE.includedBytes + n * STORAGE.stepBytes;
}
/**
* How many extra 5 GB blocks a website uses (from its heartbeat's `storage`). Hub 2.21.0 bills the
* steps bought (`Licence.extraStorageSteps`), not this; it's shown next to them.
*/
function extraStorageBlocks(storage) {
const used = Number(storage?.usedBytes);
if (!Number.isFinite(used) || used <= 0) return 0;
@@ -122,6 +137,6 @@ function extraStorageBlocks(storage) {
}
module.exports = {
TIERS, WEBSITE_PLANS, APP_TIERS, PLANS, STORAGE, ADDRESS, BUNDLE_PERCENT, YEARLY_MONTHS, FOUNDING_PERCENT,
TIERS, WEBSITE_PLANS, APP_TIERS, PLANS, STORAGE, MAX_STORAGE_STEPS, storageLimitBytes, ADDRESS, BUNDLE_PERCENT, YEARLY_MONTHS, FOUNDING_PERCENT,
tierNamed, tierForBand, appTierForBand, reviewTier, planPrice, extraStorageBlocks,
};
+32 -7
View File
@@ -535,6 +535,22 @@ const fastPanelNginx = d => [
`location = /api { proxy_pass http://127.0.0.1:${d.apiPort}; }`,
].join('\n');
/**
* Hub 2.21.0 (WEBSITE-1.0-PLAN §11): a Website on `www.` (an own domain) also answers on the bare
* domain, which sends visitors to `www.` with a 301. A Cross Code address (hope.crosscode.co.za)
* has no `www.`, so nothing else.
*/
const bareDomainOf = d => (d.product === 'website' && d.domain.startsWith('www.') ? d.domain.slice(4) : null);
function websiteSteps(d) {
const bare = bareDomainOf(d);
if (!bare) return [];
return [{
text: `Add ${bare} as an alias of the site (so Let's Encrypt covers it too), and send it to https://${d.domain} with a 301: add this to the site's nginx configuration, above the locations.`,
code: [`if ($host = ${bare}) {`, ` return 301 https://${d.domain}$request_uri;`, '}'].join('\n'),
}];
}
/** The FastPanel steps (§11): what Joshua sets up by hand; nothing is done automatically. */
async function fastPanelSteps(d) {
const dnsOk = await dnsPointsAtCentral(d.domain);
@@ -545,9 +561,10 @@ async function fastPanelSteps(d) {
link: `${hubUrl()}/servers/installs/${d.id}`,
steps: [
{ text: `Add the site ${d.domain} as a proxy to http://127.0.0.1:${d.webPort} (the frontend). Pass the Host header and X-Forwarded-For / X-Forwarded-Proto: https, and allow uploads up to 25 MB.` },
...websiteSteps(d),
{ text: 'Send /api to the backend: add this to the site\'s nginx configuration. Keep the ^~: without it FastPanel\'s static-file rule sends every /api path with a file extension (an uploaded logo, a PDF) to the frontend.', code: fastPanelNginx(d) },
{ text: 'Turn on Let\'s Encrypt for the site.' },
{ text: `DNS: ${d.domain} → ${ip || '<central server IP>'} (${dnsOk === true ? 'checked: points there' : dnsOk === false ? 'not yet' : 'not checked: set the central server IP in Settings'}).` },
{ text: `DNS: ${[d.domain, bareDomainOf(d)].filter(Boolean).join(' and ')} → ${ip || '<central server IP>'} (${dnsOk === true ? 'checked: points there' : dnsOk === false ? 'not yet' : 'not checked: set the central server IP in Settings'}).` },
{ text: 'Click "Proxy done" in the Hub. It checks the site, its /api and a file under /api, then makes it live.' },
],
};
@@ -626,8 +643,11 @@ async function preflight(server, product, version, now) {
if (invalid.length) throw fail(409, 'CONFIG_INVALID', `${server.name}'s configuration: ${invalid.join(' ')} (Servers → ${server.name} → Configuration).`);
}
/** Products the Hub can install so far (Accounts from Hub 2.3.0, docs/ACCOUNTS-1.0-PLAN.md §9). */
const INSTALLABLE = new Set(['events', 'accounts']);
/**
* Products the Hub can install so far (Accounts from Hub 2.3.0, docs/ACCOUNTS-1.0-PLAN.md §9; the
* Church Website from 2.21.0, WEBSITE-1.0-PLAN §11).
*/
const INSTALLABLE = new Set(['events', 'accounts', 'website']);
/**
* New install (§7): licence, ports, the install job. A church already on that server (the same
@@ -900,8 +920,13 @@ async function writeFrp(serverId, { content, restart = true, totp }, admin, now
return makeJob(prisma, { serverId: s.id, type: 'frp-write', args: { path: last.path, content: text, restart: !!restart }, createdById: admin?.id || null, notBefore: now });
}
/** `events.hope.co.za` → `accounts.hope.co.za`: the first label swapped (ROADMAP-v3 decision 6). */
function accountsDomainFor(domain) {
/**
* `events.hope.co.za` → `accounts.hope.co.za`: the first label swapped (ROADMAP-v3 decision 6).
* Hub 2.21.0: a Website is on the church's own address, so Accounts goes in front of it:
* `www.hope.co.za` → `accounts.hope.co.za`, `hope.crosscode.co.za` → `accounts.hope.crosscode.co.za`.
*/
function accountsDomainFor(domain, product = 'events') {
if (product === 'website') return `accounts.${domain.replace(/^www\./, '')}`;
const parts = domain.split('.');
return parts.length > 2 ? ['accounts', ...parts.slice(1)].join('.') : `accounts.${domain}`;
}
@@ -926,7 +951,7 @@ async function requiredFirst({ release, product, siblings, input, domain, server
if (compareVersions(accountsRelease.version, need.version) < 0) {
throw fail(409, 'REQUIREMENT_NOT_MET', `${PRODUCT_NAMES[product]} ${release.version} needs Accounts ${need.version}; the newest Accounts release is ${accountsRelease.version}.`);
}
const accountsDomain = String(input.accountsDomain || accountsDomainFor(domain)).trim().toLowerCase();
const accountsDomain = String(input.accountsDomain || accountsDomainFor(domain, product)).trim().toLowerCase();
if (!DOMAIN.test(accountsDomain) || accountsDomain === domain) throw fail(400, 'BAD_REQUEST', 'Give Accounts its own domain, like accounts.hope.co.za.');
await preflight(server, 'accounts', accountsRelease.version, now);
return { release: accountsRelease, domain: accountsDomain };
@@ -1125,7 +1150,7 @@ async function accountsPlan(d, release, accountsRelease) {
if (acc.status !== 'live') throw fail(409, 'NOT_LIVE', `${d.shortName}: its Accounts isn't live (${acc.status}).`);
return { version: `accounts@${accountsRelease.version}`, install: null, note: `${d.shortName}: Accounts is updated from ${running || 'an unknown version'} to ${accountsRelease.version} first (${PRODUCT_NAMES[d.product]} ${release.version} needs ${need.version}).` };
}
const domain = accountsDomainFor(d.domain);
const domain = accountsDomainFor(d.domain, d.product);
if (!DOMAIN.test(domain)) throw fail(400, 'BAD_REQUEST', `${d.shortName}: no Accounts domain could be made from ${d.domain}; install Accounts first (New install).`);
return { version: `accounts@${accountsRelease.version}`, install: { domain, release: accountsRelease }, note: `${d.shortName}: Accounts ${accountsRelease.version} is installed first at ${domain} (${PRODUCT_NAMES[d.product]} ${release.version} needs it).` };
}
+6 -1
View File
@@ -7,6 +7,7 @@
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const { storageLimitBytes } = require('./billing/tiers');
const PREFIX = 'hel1';
const VALID_DAYS = 30;
@@ -46,7 +47,11 @@ function buildPayload(licence, install, customerName, now = new Date()) {
graceDays: licence.graceDays,
issuedAt: now.toISOString(),
validUntil: new Date(now.getTime() + VALID_DAYS * DAY).toISOString(),
limits: { aiMonthlyCapCents: licence.aiMonthlyCapCents || 0 },
limits: {
aiMonthlyCapCents: licence.aiMonthlyCapCents || 0,
// Hub 2.21.0 (contracts 1.17.0): a Website's storage limit, 5 GB plus the steps bought.
...(licence.product === 'website' ? { storageBytes: storageLimitBytes(licence.extraStorageSteps) } : {}),
},
};
}
+6
View File
@@ -54,6 +54,9 @@ async function ensureAccountsLicence(db, customerId) {
}
}
/** The plan a new licence starts on, for products with one (others: the default). */
const FIRST_PLAN = { website: 'Website', app: 'Mustard Seed' };
/**
* Generate a licence for a customer, plus its Accounts licence when this is a product other than
* Accounts and it has none yet. Returns { licence, accounts } (accounts: the licence if created now).
@@ -61,6 +64,9 @@ async function ensureAccountsLicence(db, customerId) {
async function generateLicence(db, { customerId, product = 'events', data = {}, now = new Date() }) {
// Hub 2.0, decision 3: a product added to a customer that's already billed gets its free month,
// then joins the customer's invoices (the days before its first full period prorated).
// Hub 2.21.0: a Website licence is on its one plan, an App licence on the first tier, however it's
// made (Generate or New install); the App's review moves it.
if (data.plan === undefined && FIRST_PLAN[product]) data = { ...data, plan: FIRST_PLAN[product] };
const customer = BILLABLE.includes(product) && data.billedFrom === undefined ? await db.customer?.findUnique({ where: { id: customerId } }) : null;
if (customer && customer.billingCycle && customer.billingCycle !== 'none') data = { ...data, billedFrom: addMonths(today(now), 1) };
const licence = await createLicence(db, { customerId, product, data });