diff --git a/CHANGELOG.md b/CHANGELOG.md index 2dd8bbf..5f585e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,40 @@ versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [2.21.0] - 2026-11-25 + +The Hub side of the Church Website 1.0.0 (crosscode-platform docs/WEBSITE-1.0-PLAN.md §11). +**Migration:** `Licence.extraStorageSteps` (a column, default 0). Vendors `@crosscode/contracts` +1.17.0 (was 1.16.0). No API is removed. + +### Added + +- **New install offers the Church Website.** Its release needs Accounts (`— requires accounts …` in + its notes), so a church without one gets Accounts installed first, as Cross Events 3 does. The + Website is on the church's own address: Accounts goes in front of it (`www.hope.co.za` → + `accounts.hope.co.za`, `hope.crosscode.co.za` → `accounts.hope.crosscode.co.za`), unless an + Accounts domain is given. Its releases (`website@` tags, `apps/website/WHATS-NEW.md`) and env + template (`apps/website/env.template.json` at the tag) were already read; there are none yet. +- **The FastPanel email for a Website on `www.`** also sets up its bare domain: an alias (so + Let's Encrypt covers it), a 301 to `https://www.…` to paste into the site's nginx, and DNS for + both. A Cross Code address has no `www.` and gets the usual steps. +- **Extra Website storage is bought in 5 GB steps** (Customers → the Website → Edit → Extra storage, + 0–99). The licence token sends the site its limit, 5 GB plus the steps (`limits.storageBytes`, + contracts 1.17.0), with the next heartbeat; the site stops uploads when it's full (plan decision + 12). The product card shows the storage it can hold. + +### Changed + +- **Extra Website storage is billed on the steps bought**, R20 a month each and never discounted, + no longer on what the site reports using (which can't go above the limit any more). +- A Website licence starts on the Website plan, and an App licence on its first tier, however it's + made: New install now does this too (it gave "standard" before), not only Generate. + +### Not yet + +- **Get more storage** (the Website asking the Hub, and the email to Joshua) comes with contracts + 1.18.0 and the Website itself. + ## [2.20.0] - 2026-11-23 No migration. `GET /api/admin/ports` and a server's `frp` state carry more fields; nothing is removed. diff --git a/backend/package-lock.json b/backend/package-lock.json index aac3022..2d98b81 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1,16 +1,16 @@ { "name": "events-hub-backend", - "version": "2.20.0", + "version": "2.21.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-backend", - "version": "2.20.0", + "version": "2.21.0", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^1.3.0", - "@crosscode/contracts": "file:vendor/crosscode-contracts-1.16.0.tgz", + "@crosscode/contracts": "file:vendor/crosscode-contracts-1.17.0.tgz", "@prisma/adapter-pg": "^7.10.1", "@prisma/client": "^7.10.1", "bcryptjs": "^2.4.3", @@ -609,9 +609,9 @@ "license": "MIT" }, "node_modules/@crosscode/contracts": { - "version": "1.16.0", - "resolved": "file:vendor/crosscode-contracts-1.16.0.tgz", - "integrity": "sha512-pqqrBS6stQquM+NUW22pb8Z6g4w7HG4fPZozZgp1FC79eT/0/V6VjrmFUcsIasF+RVgl6oug2Spxbq0cx6FUuw==", + "version": "1.17.0", + "resolved": "file:vendor/crosscode-contracts-1.17.0.tgz", + "integrity": "sha512-mT/A1/NEkw3h3vRHZ546x2KJvqVRBkv+x4c0/Cb+xTE/mZKUpXRwbDyBsDxKzs7orKdAcPZQxLg91gnAObx2PQ==", "license": "UNLICENSED", "dependencies": { "zod": "^4.6.7" diff --git a/backend/package.json b/backend/package.json index 0398d0e..741fa04 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-backend", - "version": "2.20.0", + "version": "2.21.0", "private": true, "description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats", "main": "src/index.js", @@ -20,7 +20,7 @@ }, "dependencies": { "@anthropic-ai/sdk": "^1.3.0", - "@crosscode/contracts": "file:vendor/crosscode-contracts-1.16.0.tgz", + "@crosscode/contracts": "file:vendor/crosscode-contracts-1.17.0.tgz", "@prisma/adapter-pg": "^7.10.1", "@prisma/client": "^7.10.1", "bcryptjs": "^2.4.3", diff --git a/backend/prisma/migrations/20261124120000_storage_steps/migration.sql b/backend/prisma/migrations/20261124120000_storage_steps/migration.sql new file mode 100644 index 0000000..467601d --- /dev/null +++ b/backend/prisma/migrations/20261124120000_storage_steps/migration.sql @@ -0,0 +1,4 @@ +-- Hub 2.21.0: a Church Website licence's extra storage steps (5 GB each), bought and billed. + +-- AlterTable +ALTER TABLE "Licence" ADD COLUMN "extraStorageSteps" INTEGER NOT NULL DEFAULT 0; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 16f7555..f468f1c 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -119,6 +119,9 @@ model Licence { billedUntil DateTime? @db.Date // A price per month instead of the tier's (e.g. the Network tier), in cents. customMonthlyCents Int? + // Hub 2.21.0, Church Website only: extra 5 GB storage steps bought (R20/month each). The + // licence token sends 5 GB + these as the site's storage limit; invoices bill them. + extraStorageSteps Int @default(0) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt // One licence = one install. diff --git a/backend/src/routes/admin.js b/backend/src/routes/admin.js index c618650..a54e1af 100644 --- a/backend/src/routes/admin.js +++ b/backend/src/routes/admin.js @@ -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' }); diff --git a/backend/src/utils/billing/compute.js b/backend/src/utils/billing/compute.js index 286e18f..c76906b 100644 --- a/backend/src/utils/billing/compute.js +++ b/backend/src/utils/billing/compute.js @@ -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({ diff --git a/backend/src/utils/billing/tiers.js b/backend/src/utils/billing/tiers.js index 40fa76c..17043f1 100644 --- a/backend/src/utils/billing/tiers.js +++ b/backend/src/utils/billing/tiers.js @@ -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, }; diff --git a/backend/src/utils/jobs.js b/backend/src/utils/jobs.js index cc5269a..a200fa8 100644 --- a/backend/src/utils/jobs.js +++ b/backend/src/utils/jobs.js @@ -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 || ''} (${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 || ''} (${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).` }; } diff --git a/backend/src/utils/licenceToken.js b/backend/src/utils/licenceToken.js index 1e50366..ded2c46 100644 --- a/backend/src/utils/licenceToken.js +++ b/backend/src/utils/licenceToken.js @@ -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) } : {}), + }, }; } diff --git a/backend/src/utils/licences.js b/backend/src/utils/licences.js index 6adab47..303931b 100644 --- a/backend/src/utils/licences.js +++ b/backend/src/utils/licences.js @@ -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 }); diff --git a/backend/tests/billing.test.js b/backend/tests/billing.test.js index 19257a5..3c2cc9e 100644 --- a/backend/tests/billing.test.js +++ b/backend/tests/billing.test.js @@ -3,7 +3,7 @@ jest.mock('../src/config/db', () => ({})); const fs = require('fs'); const path = require('path'); const { hub } = require('@crosscode/contracts'); -const { TIERS, WEBSITE_PLANS, APP_TIERS, tierForBand, appTierForBand, planPrice, extraStorageBlocks } = require('../src/utils/billing/tiers'); +const { TIERS, WEBSITE_PLANS, APP_TIERS, tierForBand, appTierForBand, planPrice, extraStorageBlocks, storageLimitBytes } = require('../src/utils/billing/tiers'); const { day, ymd, addMonths, addDays, today, saHour, periodLabel, money } = require('../src/utils/billing/dates'); const { draftCustomerInvoice, customerInvoiceLines, planChangesOf, cleanLines, totals, invoiceState, statement, recipientFor } = require('../src/utils/billing/compute'); @@ -78,6 +78,14 @@ describe('tiers', () => { expect(extraStorageBlocks({ usedBytes: 11 * GB })).toBe(2); expect(extraStorageBlocks(null)).toBe(0); }); + + test("2.21.0: a Website's storage limit is 5 GB plus the steps bought", () => { + expect(storageLimitBytes(0)).toBe(5 * GB); + expect(storageLimitBytes(2)).toBe(15 * GB); + expect(storageLimitBytes(undefined)).toBe(5 * GB); + expect(storageLimitBytes(-1)).toBe(5 * GB); + expect(storageLimitBytes(1000)).toBe(500 * GB); + }); }); describe('dates', () => { @@ -214,18 +222,23 @@ describe('drafting an invoice (several products, Hub 2.0)', () => { expect(invoice.lines.some(l => /Bundle|Accounts/.test(l.description))).toBe(false); }); - test('extra website storage: R20 per 5 GB a month, never discounted', () => { - const { invoice } = draft(customer({ founding: true }), [events(), website({ install: { product: 'website', stats: { storage: { usedBytes: 12 * GB, includedBytes: 5 * GB } } } })]); + test('extra website storage: R20 per 5 GB bought a month, never discounted', () => { + const { invoice } = draft(customer({ founding: true }), [events(), website({ extraStorageSteps: 2, install: { product: 'website', stats: { storage: { usedBytes: 7 * GB, includedBytes: 15 * GB } } } })]); expect(invoice.lines.at(-1)).toEqual({ description: 'Extra website storage: 2 × 5 GB, December 2026', quantity: 2, unitCents: 2000, amountCents: 4000 }); // The bundle comes off the products only: (360 + 64) × 15% = R63.60. expect(invoice.lines.find(l => /Bundle/.test(l.description)).amountCents).toBe(-6360); }); test('yearly: add-ons are 12 months\' price (decision 2), products 10', () => { - const { invoice } = draft(customer({ billingCycle: 'yearly', reviewDate: day('2027-12-01') }), [website({ install: { product: 'website', stats: { storage: { usedBytes: 8 * GB } } } })]); + const { invoice } = draft(customer({ billingCycle: 'yearly', reviewDate: day('2027-12-01') }), [website({ extraStorageSteps: 1 })]); expect(invoice.lines.map(l => [l.quantity, l.unitCents])).toEqual([[10, 9900], [12, 2000]]); }); + test('2.21.0: storage is billed on the steps bought, not on what the site reports using', () => { + const { invoice } = draft(customer(), [website({ install: { product: 'website', stats: { storage: { usedBytes: 12 * GB, includedBytes: 5 * GB } } } })]); + expect(invoice.lines.some(l => /storage/.test(l.description))).toBe(false); + }); + test('the App is reviewed on its active members', () => { const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [app({ billedUntil: day('2026-12-31'), install: { product: 'app', stats: { activeMembers90d: '301–750' } } })]); expect(invoice.planChange).toEqual([expect.objectContaining({ licenceId: 'l3', product: 'app', from: 'Mustard Seed', to: 'Congregation', toMonthlyCents: 39900, band: '301–750' })]); diff --git a/backend/tests/products.test.js b/backend/tests/products.test.js index 0682b53..f602074 100644 --- a/backend/tests/products.test.js +++ b/backend/tests/products.test.js @@ -88,6 +88,12 @@ describe('licences', () => { await expect(generateLicence(mockDb, { customerId: 'c2', product: 'events', data: {} })).resolves.toBeTruthy(); }); + test('2.21.0: a Website licence starts on the Website plan and an App one on the first tier, however it is made', async () => { + expect((await generateLicence(mockDb, { customerId: 'c1', product: 'website' })).licence.plan).toBe('Website'); + expect((await generateLicence(mockDb, { customerId: 'c1', product: 'app' })).licence.plan).toBe('Mustard Seed'); + expect((await generateLicence(mockDb, { customerId: 'c2', product: 'website', data: { plan: 'Custom' } })).licence.plan).toBe('Custom'); + }); + test('a revoked licence can be replaced', async () => { const { licence } = await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} }); licence.status = 'revoked'; diff --git a/backend/tests/servers.test.js b/backend/tests/servers.test.js index 48d44ed..04d00b8 100644 --- a/backend/tests/servers.test.js +++ b/backend/tests/servers.test.js @@ -8,7 +8,7 @@ jest.mock('../src/utils/mail', () => ({ sendMail: jest.fn(async m => { mockMails process.env.HUB_ENCRYPTION_KEY = 'test-encryption-key-test-encryption-key'; process.env.FRONTEND_URL = 'https://hub.test'; -const { agent } = require('@crosscode/contracts'); +const { agent, hub } = require('@crosscode/contracts'); const signing = require('@crosscode/contracts/signing'); const db = require('../src/config/db'); const servers = require('../src/utils/servers'); @@ -473,7 +473,7 @@ describe('Accounts from the Hub (2.3.0)', () => { await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW); await expect(jobs.newInstall({ product: 'accounts', customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'accounts.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'BUSY' }); await expect(jobs.newInstall({ product: 'accounts', customerId: 'cust-1', serverId: other.id, shortName: 'hope', domain: 'accounts.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'OTHER_SERVER' }); - await expect(jobs.newInstall({ product: 'website', customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'www.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_REQUEST' }); + await expect(jobs.newInstall({ product: 'app', customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'app.hope.co.za' }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_REQUEST' }); }); }); @@ -539,6 +539,63 @@ describe('Cross Events 3.0 brings its Accounts (2.5.0)', () => { }); }); +describe('the Church Website from the Hub (2.21.0)', () => { + const poll = (server) => jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.1.0', mode: 'church', runningJobId: null }, NOW); + beforeEach(async () => { + await db.release.create({ data: { id: 'rw1', product: 'website', version: '1.0.0', notes: '- First release', requires: [{ product: 'accounts', version: '1.7.0' }], releasedAt: NOW } }); + await db.release.create({ data: { id: 'ra7', product: 'accounts', version: '1.7.0', notes: '- Brand style', releasedAt: NOW } }); + }); + + test('a new church: Accounts first at accounts., then the Website on www., with a CCW- licence on the Website plan', async () => { + const { server } = await joinServer(); + await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' }); + const out = await jobs.newInstall({ product: 'website', customerId: 'cust-1', serverId: server.id, shortName: 'grace', domain: 'www.grace.co.za' }, admin, NOW); + expect(out.alsoInstalling).toEqual({ product: 'accounts', domain: 'accounts.grace.co.za', version: '1.7.0' }); + const [first] = (await poll(server)).jobs; + expect(first).toMatchObject({ type: 'install', args: { products: ['accounts'] } }); + await jobs.receiveReport(server, signedReport(first, 'succeeded', { result: { versions: { accounts: 'accounts@1.7.0' } } }), NOW); + const [second] = (await poll(server)).jobs; + expect(second).toMatchObject({ type: 'add-product', args: { church: 'grace', product: 'website', version: 'website@1.0.0', domain: 'www.grace.co.za' } }); + expect(agent.agentJobSchema.safeParse(second).success).toBe(true); + const key = signing.openConfig(second.config, keys.x.privateKeyPem).install.website.HUB_LICENCE_KEY; + expect(key).toMatch(/^CCW-/); + expect(await db.licence.findFirst({ where: { key } })).toMatchObject({ product: 'website', plan: 'Website' }); + }); + + test('on a Cross Code address, Accounts goes in front of it', async () => { + const { server } = await joinServer(); + await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' }); + const out = await jobs.newInstall({ product: 'website', customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'hope.crosscode.co.za' }, admin, NOW); + expect(out.alsoInstalling.domain).toBe('accounts.hope.crosscode.co.za'); + }); + + test("the FastPanel steps send the bare domain to www. with a 301; a Cross Code address has no such step", async () => { + const own = await jobs.fastPanelText({ id: 'd1', product: 'website', shortName: 'grace', domain: 'www.grace.co.za', webPort: 20010, apiPort: 20011, customer: { name: 'Grace' } }); + expect(own).toContain('Add grace.co.za as an alias'); + expect(own).toContain('return 301 https://www.grace.co.za$request_uri;'); + expect(own).toContain('DNS: www.grace.co.za and grace.co.za'); + expect(own).toContain('location ^~ /api/ {'); + const crosscode = await jobs.fastPanelText({ id: 'd2', product: 'website', shortName: 'hope', domain: 'hope.crosscode.co.za', webPort: 20012, apiPort: 20013, customer: { name: 'Hope' } }); + expect(crosscode).not.toContain('301'); + const events = await jobs.fastPanelText({ id: 'd3', product: 'events', shortName: 'hope', domain: 'www.hope.co.za', webPort: 20014, apiPort: 20015, customer: { name: 'Hope' } }); + expect(events).not.toContain('301'); + }); +}); + +describe("a Website licence carries its storage limit (2.21.0)", () => { + const GB = 1024 ** 3; + const licenceToken = require('../src/utils/licenceToken'); + const base = { id: '0b6f2c1e-8a3d-4f5b-9c7e-1d2e3f4a5b6c', customerId: '1c7a3d2f-9b4e-4a6c-8d8f-2e3f4a5b6c7d', plan: 'Website', status: 'active', expiresAt: null, graceDays: 14 }; + + test('5 GB plus the steps bought, valid for contracts 1.17.0; other products have none', () => { + const p = licenceToken.buildPayload({ ...base, product: 'website', extraStorageSteps: 2 }, { id: '2d8b4e3a-0c5f-4b7d-9e9a-3f4a5b6c7d8e' }, 'Grace', NOW); + expect(p.limits.storageBytes).toBe(15 * GB); + expect(hub.licencePayloadSchema.safeParse(p).success).toBe(true); + expect(licenceToken.buildPayload({ ...base, product: 'website' }, { id: '2d8b4e3a-0c5f-4b7d-9e9a-3f4a5b6c7d8e' }, 'Grace', NOW).limits.storageBytes).toBe(5 * GB); + expect(licenceToken.buildPayload({ ...base, product: 'events', plan: 'Seed', extraStorageSteps: 3 }, { id: '2d8b4e3a-0c5f-4b7d-9e9a-3f4a5b6c7d8e' }, 'Grace', NOW).limits).not.toHaveProperty('storageBytes'); + }); +}); + describe('settings for servers (found in the VM test)', () => { test('install defaults, the port range and the central IP are saved', async () => { diff --git a/backend/vendor/crosscode-contracts-1.16.0.tgz b/backend/vendor/crosscode-contracts-1.16.0.tgz deleted file mode 100644 index 193462d..0000000 Binary files a/backend/vendor/crosscode-contracts-1.16.0.tgz and /dev/null differ diff --git a/backend/vendor/crosscode-contracts-1.17.0.tgz b/backend/vendor/crosscode-contracts-1.17.0.tgz new file mode 100644 index 0000000..709170f Binary files /dev/null and b/backend/vendor/crosscode-contracts-1.17.0.tgz differ diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 1d94eca..aea5c5b 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "events-hub-frontend", - "version": "2.20.0", + "version": "2.21.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-frontend", - "version": "2.20.0", + "version": "2.21.0", "dependencies": { "lucide-react": "^0.536.0", "next": "^15.5.24", diff --git a/frontend/package.json b/frontend/package.json index 3732dd4..192c78f 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-frontend", - "version": "2.20.0", + "version": "2.21.0", "private": true, "scripts": { "dev": "next dev -p 3200", diff --git a/frontend/src/app/(hub)/servers/installs/page.tsx b/frontend/src/app/(hub)/servers/installs/page.tsx index 7eaac3a..ebb90e6 100644 --- a/frontend/src/app/(hub)/servers/installs/page.tsx +++ b/frontend/src/app/(hub)/servers/installs/page.tsx @@ -17,6 +17,12 @@ type Msg = { type: "ok" | "err"; text: string } | null; type Customer = { id: string; name: string; domain?: string | null }; type InstallRow = { id: string; name: string; url: string; customer: { id: string; name: string } | null; version: string | null }; +/** The Accounts domain the Hub makes when none is given (backend accountsDomainFor). */ +function accountsPlaceholder(product: string, domain: string) { + if (!domain) return "accounts.hope.co.za"; + return product === "website" ? `accounts.${domain.replace(/^www\./, "")}` : domain.replace(/^[^.]+./, "accounts."); +} + const emptyNew = { product: "events", customerId: "", serverId: "", shortName: "", domain: "", accountsDomain: "", timezone: "", adminName: "", adminEmail: "", version: "" }; const emptyLink = { installId: "", serverId: "", shortName: "", webPort: "", apiPort: "" }; const changedFrom = >(form: T, empty: T) => (Object.keys(empty) as (keyof T)[]).some(k => form[k] !== empty[k]); @@ -57,18 +63,21 @@ function NewInstallModal({ servers, onClose }: { servers: ServerSummary[]; onClo

{form.product === "accounts" ? "Install Accounts before the Website, the App or Cross Events 3.0. Use the church's short name to add it next to its Events on the same server." - : "A church that already has a product here keeps its short name: the new one is added next to it on the same server."} + : form.product === "website" + ? "On the church's own address: www.hope.co.za (its bare domain is sent to www.), or a Cross Code address like hope.crosscode.co.za. A church that already has a product here keeps its short name." + : "A church that already has a product here keeps its short name: the new one is added next to it on the same server."}

Folders, database and tunnels: a-z, 0-9 and -.

-
- {form.product === "events" && ( -

Cross Events 3 signs in through the church's Accounts: a church without it gets it installed first, here.

+
+ {(form.product === "events" || form.product === "website") && ( +

{form.product === "website" ? "The Website" : "Cross Events 3"} signs in through the church's Accounts: a church without it gets it installed first, here.

)}
@@ -177,6 +186,7 @@ export default function InstallsPage() { + diff --git a/frontend/src/components/customer/ProductCard.tsx b/frontend/src/components/customer/ProductCard.tsx index fd0c90a..9c7ce52 100644 --- a/frontend/src/components/customer/ProductCard.tsx +++ b/frontend/src/components/customer/ProductCard.tsx @@ -56,6 +56,7 @@ export function ProductCard({ licence, billing, plans, nextInvoiceDate, onDone } billed ? (billing?.billedFrom ? `charged from ${day(billing.billedFrom)}` : "not charged") : null, ]; facts.push(licence.expiresAt ? `expires ${fmtDate(licence.expiresAt, false)}` : "expires never", `grace ${licence.graceDays} days`); + if (licence.product === "website") facts.push(licence.extraStorageSteps ? `${5 + 5 * licence.extraStorageSteps} GB storage (${licence.extraStorageSteps} extra × 5 GB)` : "5 GB storage"); return (
@@ -100,7 +101,8 @@ export function ProductCard({ licence, billing, plans, nextInvoiceDate, onDone } /** One popup, one Save: the licence fields and the billing fields, each sent only if changed. */ function EditProduct({ licence, billing, onClose, onDone }: { licence: Licence; billing: BillingLicence | undefined; onClose: () => void; onDone: Done }) { - const lic0 = { plan: licence.plan, expiresAt: dateInput(licence.expiresAt), graceDays: String(licence.graceDays), notes: licence.notes || "" }; + const website = licence.product === "website"; + const lic0 = { plan: licence.plan, expiresAt: dateInput(licence.expiresAt), graceDays: String(licence.graceDays), notes: licence.notes || "", storage: String(licence.extraStorageSteps ?? 0) }; const bill0 = { billedFrom: billing?.billedFrom || "", custom: randInput(billing?.customMonthlyCents) }; const [lic, setLic] = useState(lic0); const [bill, setBill] = useState(bill0); @@ -119,7 +121,7 @@ function EditProduct({ licence, billing, onClose, onDone }: { licence: Licence; try { const said: string[] = []; if (licChanged) { - await api(`/api/admin/licences/${licence.id}`, { method: "PUT", body: { plan: lic.plan, expiresAt: endOfDay(lic.expiresAt), graceDays: lic.graceDays, notes: lic.notes } }); + await api(`/api/admin/licences/${licence.id}`, { method: "PUT", body: { plan: lic.plan, expiresAt: endOfDay(lic.expiresAt), graceDays: lic.graceDays, notes: lic.notes, ...(website ? { extraStorageSteps: Number(lic.storage) } : {}) } }); said.push(`Licence saved. ${HEARTBEAT}`); } if (billChanged && billing) { @@ -155,6 +157,13 @@ function EditProduct({ licence, billing, onClose, onDone }: { licence: Licence;
setLic({ ...lic, graceDays: e.target.value })} />

{licence.product === "accounts" ? "Free: comes with the church's other products." : "The tier is shown on the church's Licence page and priced on its invoices."}

+ {website && ( +
+ + setLic({ ...lic, storage: e.target.value })} /> +

The site can hold {5 + 5 * (Number(lic.storage) || 0)} GB; uploads stop when it's full. R20 a month per step, from the next invoice, never discounted. The site gets the new limit with its next heartbeat.

+
+ )}
setLic({ ...lic, notes: e.target.value })} placeholder="Anything worth remembering about this licence" />
diff --git a/frontend/src/lib/types.ts b/frontend/src/lib/types.ts index 6bda575..0c5a745 100644 --- a/frontend/src/lib/types.ts +++ b/frontend/src/lib/types.ts @@ -28,6 +28,8 @@ export type Licence = { expiresAt: string | null; graceDays: number; notes: string | null; + /** Hub 2.21.0, Church Website: extra 5 GB storage steps bought (the site's limit is 5 GB + these). */ + extraStorageSteps?: number; createdAt: string; install?: { id: string; name: string; url: string; lastHeartbeatAt: string | null } | null; };