Merge branch 'feat/hub2-protocol' into release/2.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+11
-1
@@ -21,6 +21,15 @@ Hub 2.0.0, Cross Code Hub, in steps (`docs/HUB-2.0-PLAN.md`).
|
||||
- `npm run check:hub2`: before deploying 2.0, lists customers with two open licences (the 2.0
|
||||
migration stops on them, naming them). Run it against production first.
|
||||
- `@crosscode/contracts` 1.0.0, committed as `backend/vendor/crosscode-contracts-1.0.0.tgz`.
|
||||
- **Protocol v2** (step 2) next to v1 (`utils/protocol.js`; `/api/public-key` lists `[1, 2]`):
|
||||
register and heartbeat say which `product` they are (it must match the licence, else
|
||||
`409 WRONG_PRODUCT`), register sends the install's public key, the heartbeat's stats are per
|
||||
product, and the replies add `linkedProducts`: the church's other installs in use that have a
|
||||
public key (product, id, address, key; nothing else). v2 bodies are checked against the
|
||||
contracts' schemas (`400 INVALID_REQUEST` says what's wrong); v1 requests and replies are exactly
|
||||
as before. Tests put every contract sample through the routes and check the replies against the
|
||||
contract.
|
||||
- Licence tokens carry `customerId` and `product` (Cross Events 2.1 ignores them).
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -28,7 +37,8 @@ Hub 2.0.0, Cross Code Hub, in steps (`docs/HUB-2.0-PLAN.md`).
|
||||
licence-token prefix stays: it's part of the protocol).
|
||||
- Installs register with protocol v1 only with a Cross Events licence (`409 WRONG_PRODUCT`
|
||||
otherwise); the other products register with protocol v2 (step 2). Only Cross Events licences
|
||||
can be invoiced until billing per customer (step 4).
|
||||
can be invoiced until billing per customer (step 4). Until releases per product (step 3), only
|
||||
Cross Events installs are told about releases or shown as behind.
|
||||
- Migration `20261104132032_products`.
|
||||
|
||||
## [1.7.0] - 2026-11-03
|
||||
|
||||
@@ -48,7 +48,8 @@ function summary(install, settings, now = new Date()) {
|
||||
url: install.url,
|
||||
customer: install.customer ? { id: install.customer.id, name: install.customer.name } : null,
|
||||
version: install.version,
|
||||
behind: !!(settings.latest_version && install.version && compareVersions(install.version, settings.latest_version) < 0),
|
||||
// Releases are Cross Events' until releases per product (Hub 2.0 step 3).
|
||||
behind: !!(install.product === 'events' && settings.latest_version && install.version && compareVersions(install.version, settings.latest_version) < 0),
|
||||
licence: install.licence ? { id: install.licence.id, status: install.licence.status, expiresAt: install.licence.expiresAt } : null,
|
||||
lastHeartbeatAt: install.lastHeartbeatAt,
|
||||
status: worst,
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
/**
|
||||
* The API installs call (docs/hub-protocol.md): public key, register, heartbeat, update request
|
||||
* (and withdrawing it).
|
||||
* (and withdrawing it), AI.
|
||||
* Install → Hub only; these are the only endpoints that aren't behind an admin login.
|
||||
*
|
||||
* Protocol v1 (Cross Events 2.1) and v2 (every product, @crosscode/contracts `hub`) are both
|
||||
* accepted (utils/protocol.js). v2 bodies are checked with the contract schemas, and v2 replies
|
||||
* add `linkedProducts`; v1 is handled and answered exactly as before.
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
@@ -18,10 +22,11 @@ const { releasesForInstall } = require('../utils/releases');
|
||||
const { noticesForInstall } = require('../utils/notices');
|
||||
const ai = require('../utils/ai');
|
||||
const { PRODUCT_NAMES } = require('../utils/products');
|
||||
const { hub } = require('@crosscode/contracts');
|
||||
const { PROTOCOL_VERSIONS, isV2, parseV2, linkedProductsFor } = require('../utils/protocol');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const PROTOCOL_VERSIONS = [1];
|
||||
const HEARTBEAT_MINUTES = 15;
|
||||
const registerLimiter = rateLimit({ windowMs: 60 * 60 * 1000, max: 20, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many attempts.', code: 'RATE_LIMITED' } });
|
||||
const heartbeatLimiter = rateLimit({ windowMs: 60 * 1000, max: 30, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many requests.', code: 'RATE_LIMITED' } });
|
||||
@@ -49,6 +54,15 @@ function cleanUrl(url) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases and the latest version are Cross Events' until releases per product (Hub 2.0 step 3):
|
||||
* other products are told nothing rather than Events versions.
|
||||
*/
|
||||
async function releaseInfo(install, version, settings) {
|
||||
if (install.product !== 'events') return { latestVersion: null, releases: [] };
|
||||
return { latestVersion: settings.latest_version || null, releases: await releasesForInstall(version) };
|
||||
}
|
||||
|
||||
async function tokenFor(install) {
|
||||
const licence = install.licenceId ? await prisma.licence.findUnique({ where: { id: install.licenceId }, include: { customer: { select: { name: true } } } }) : null;
|
||||
if (!licence) return null;
|
||||
@@ -77,14 +91,32 @@ async function signedInstall(req, res) {
|
||||
return install;
|
||||
}
|
||||
|
||||
/**
|
||||
* The request body: a v2 body checked against its contract schema (null once the 400 is sent),
|
||||
* a v1 body as it came.
|
||||
*/
|
||||
function bodyFor(req, res, schema) {
|
||||
if (!isV2(req.body)) return req.body || {};
|
||||
const parsed = parseV2(schema, req.body);
|
||||
if (!parsed.ok) { fail(res, parsed.status, parsed.code, parsed.message); return null; }
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
const wrongProduct = (res, got, want) =>
|
||||
fail(res, 409, 'WRONG_PRODUCT', `This is a ${PRODUCT_NAMES[got]} licence, not a ${PRODUCT_NAMES[want]} one. Check you copied the right key.`);
|
||||
|
||||
router.get('/public-key', (req, res) => {
|
||||
res.json({ protocolVersions: PROTOCOL_VERSIONS, keyId: 'k1', algorithm: 'Ed25519', publicKey: licenceToken.keyPair().publicKeyPem });
|
||||
});
|
||||
|
||||
router.post('/installs/register', registerLimiter, async (req, res) => {
|
||||
try {
|
||||
const body = req.body || {};
|
||||
if (!protocolOk(body)) return fail(res, 400, 'UNSUPPORTED_PROTOCOL', `Protocol ${body.protocolVersion} is not supported; this Hub speaks ${PROTOCOL_VERSIONS.join(', ')}.`);
|
||||
const raw = req.body || {};
|
||||
if (!protocolOk(raw)) return fail(res, 400, 'UNSUPPORTED_PROTOCOL', `Protocol ${raw.protocolVersion} is not supported; this Hub speaks ${PROTOCOL_VERSIONS.join(', ')}.`);
|
||||
const v2 = isV2(raw);
|
||||
// A key as typed (lower case, spaces) is tidied before the v2 schema checks its shape.
|
||||
const body = bodyFor({ body: v2 ? { ...raw, licenceKey: normaliseLicenceKey(raw.licenceKey) } : raw }, res, hub.registerRequestSchema);
|
||||
if (!body) return;
|
||||
const info = body.install || {};
|
||||
const url = cleanUrl(info.url);
|
||||
if (!url) return fail(res, 400, 'BAD_URL', 'The install needs its public web address (https://…).');
|
||||
@@ -92,11 +124,9 @@ router.post('/installs/register', registerLimiter, async (req, res) => {
|
||||
const licence = await prisma.licence.findUnique({ where: { key: normaliseLicenceKey(body.licenceKey) }, include: { install: true, customer: true } });
|
||||
if (!licence) return fail(res, 404, 'LICENCE_NOT_FOUND', 'That licence key was not found. Check it, or ask your provider for your key.');
|
||||
if (licence.status === 'revoked') return fail(res, 403, 'LICENCE_REVOKED', 'This licence has been revoked.');
|
||||
// Protocol v1 is Cross Events only; other products register with v2 (Hub 2.0 step 2).
|
||||
const product = 'events';
|
||||
if (licence.product !== product) {
|
||||
return fail(res, 409, 'WRONG_PRODUCT', `This is a ${PRODUCT_NAMES[licence.product]} licence key, not a ${PRODUCT_NAMES[product]} one. Check you copied the right key.`);
|
||||
}
|
||||
// v2 says which product is registering; v1 is always Cross Events.
|
||||
const product = v2 ? body.product : 'events';
|
||||
if (licence.product !== product) return wrongProduct(res, licence.product, product);
|
||||
if (licence.install && licence.install.url !== url) {
|
||||
return fail(res, 409, 'LICENCE_IN_USE', 'This licence is already used by another site. Ask your provider to release it if you have moved.');
|
||||
}
|
||||
@@ -112,6 +142,8 @@ router.post('/installs/register', registerLimiter, async (req, res) => {
|
||||
server: info.server ? { node: str(info.server.node, 40), postgres: str(info.server.postgres, 40), os: str(info.server.os, 80) } : undefined,
|
||||
timezone: str(info.timezone, 60),
|
||||
features: info.features && typeof info.features === 'object' ? info.features : undefined,
|
||||
// v2: shared with the church's other installs (linkedProducts). A v1 re-register keeps it.
|
||||
publicKey: v2 ? info.publicKey : undefined,
|
||||
releasedAt: null,
|
||||
};
|
||||
// Same licence, same site → re-register (new secret, same id).
|
||||
@@ -126,9 +158,9 @@ router.post('/installs/register', registerLimiter, async (req, res) => {
|
||||
installSecret: secret,
|
||||
licence: await tokenFor(install),
|
||||
heartbeatIntervalMinutes: HEARTBEAT_MINUTES,
|
||||
latestVersion: settings.latest_version || null,
|
||||
releases: await releasesForInstall(install.version),
|
||||
...(await releaseInfo(install, install.version, settings)),
|
||||
notices: await noticesForInstall(install.id),
|
||||
...(v2 ? { linkedProducts: await linkedProductsFor(install) } : {}),
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('[register]', e);
|
||||
@@ -140,7 +172,10 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => {
|
||||
try {
|
||||
const install = await signedInstall(req, res);
|
||||
if (!install) return;
|
||||
const body = req.body;
|
||||
const body = bodyFor(req, res, hub.heartbeatRequestSchema);
|
||||
if (!body) return;
|
||||
const v2 = isV2(body);
|
||||
if (v2 && body.product !== install.product) return wrongProduct(res, install.product, body.product);
|
||||
|
||||
const now = new Date();
|
||||
const version = str(body.version, 40);
|
||||
@@ -161,9 +196,9 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => {
|
||||
const settings = await getSettings();
|
||||
res.json({
|
||||
licence: await tokenFor(install),
|
||||
latestVersion: settings.latest_version || null,
|
||||
releases: await releasesForInstall(version || install.version),
|
||||
...(await releaseInfo(install, version || install.version, settings)),
|
||||
notices: await noticesForInstall(install.id, now),
|
||||
...(v2 ? { linkedProducts: await linkedProductsFor(install) } : {}),
|
||||
serverTime: now.toISOString(),
|
||||
});
|
||||
} catch (e) {
|
||||
@@ -178,10 +213,12 @@ router.post('/installs/update-request', updateRequestLimiter, async (req, res) =
|
||||
try {
|
||||
const install = await signedInstall(req, res);
|
||||
if (!install) return;
|
||||
const body = bodyFor(req, res, hub.updateRequestSchema);
|
||||
if (!body) return;
|
||||
|
||||
const settings = await getSettings();
|
||||
const latest = settings.latest_version || null;
|
||||
const current = str(req.body.version, 40) || install.version;
|
||||
const latest = (await releaseInfo(install, null, settings)).latestVersion;
|
||||
const current = str(body.version, 40) || install.version;
|
||||
if (!latest || compareVersions(current, latest) >= 0) {
|
||||
return fail(res, 409, 'UP_TO_DATE', 'This site already runs the latest version.');
|
||||
}
|
||||
@@ -232,6 +269,7 @@ router.post('/installs/update-request/cancel', updateRequestLimiter, async (req,
|
||||
try {
|
||||
const install = await signedInstall(req, res);
|
||||
if (!install) return;
|
||||
if (!bodyFor(req, res, hub.updateRequestCancelSchema)) return;
|
||||
|
||||
const now = new Date();
|
||||
const open = await prisma.installEvent.findMany({ where: { installId: install.id, type: 'update_requested', resolvedAt: null } });
|
||||
@@ -262,6 +300,7 @@ router.post('/installs/ai/status', aiLimiter, async (req, res) => {
|
||||
try {
|
||||
const install = await signedInstall(req, res);
|
||||
if (!install) return;
|
||||
if (!bodyFor(req, res, hub.aiStatusRequestSchema)) return;
|
||||
res.json(await ai.statusFor(install));
|
||||
} catch (e) {
|
||||
console.error('[ai/status]', e);
|
||||
@@ -275,7 +314,9 @@ router.post('/installs/ai/complete', aiLimiter, async (req, res) => {
|
||||
try {
|
||||
install = await signedInstall(req, res);
|
||||
if (!install) return;
|
||||
res.json(await ai.complete(install, req.body));
|
||||
const body = bodyFor(req, res, hub.aiCompleteRequestSchema);
|
||||
if (!body) return;
|
||||
res.json(await ai.complete(install, body));
|
||||
} catch (e) {
|
||||
if (e.status && e.code) return res.status(e.status).json({ code: e.code, message: e.message, ...(e.aiStatus ? { status: e.aiStatus } : {}) });
|
||||
console.error('[ai/complete]', e);
|
||||
|
||||
@@ -35,6 +35,10 @@ function buildPayload(licence, install, customerName, now = new Date()) {
|
||||
v: 1,
|
||||
licenceId: licence.id,
|
||||
installId: install.id,
|
||||
// Hub 2.0 (contracts licencePayloadSchema): optional fields, still v 1. An install refuses a
|
||||
// token for another product; Cross Events 2.1 ignores both.
|
||||
customerId: licence.customerId,
|
||||
product: licence.product || 'events',
|
||||
customer: customerName,
|
||||
plan: licence.plan,
|
||||
status: licence.status,
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Hub protocol versions (Hub 2.0). v1 is Cross Events 2.1 (docs/hub-protocol.md); v2 is every
|
||||
* Cross Code product, defined in @crosscode/contracts (`hub`). The Hub accepts both, so Events
|
||||
* installs keep reporting until they update; v1 requests and replies are exactly as before.
|
||||
*
|
||||
* v2 adds: `product` on register and heartbeat (stats per product), the install's public key,
|
||||
* and `linkedProducts` in the replies. v2 bodies are checked with the contracts' zod schemas:
|
||||
* unknown fields are dropped, anything missing or malformed is `400 INVALID_REQUEST`.
|
||||
*/
|
||||
|
||||
const { hub } = require('@crosscode/contracts');
|
||||
const prisma = require('../config/db');
|
||||
|
||||
const PROTOCOL_VERSIONS = [...hub.HUB_PROTOCOL_VERSIONS];
|
||||
const isV2 = body => body?.protocolVersion === 2;
|
||||
|
||||
/** "install.url: Invalid URL" for the first problem zod found. */
|
||||
function describeIssues(error) {
|
||||
const issue = error.issues[0];
|
||||
if (!issue) return 'The request is not valid.';
|
||||
const where = issue.path.length ? `${issue.path.join('.')}: ` : '';
|
||||
return `${where}${issue.message}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A v2 body checked against a contract schema: { ok: true, data } or { ok: false, status, code,
|
||||
* message }. v1 bodies aren't checked here (they keep the v1 handling).
|
||||
*/
|
||||
function parseV2(schema, body) {
|
||||
const result = schema.safeParse(body);
|
||||
if (result.success) return { ok: true, data: result.data };
|
||||
return { ok: false, status: 400, code: 'INVALID_REQUEST', message: describeIssues(result.error) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The church's other installs, for v2 replies: product, id, URL and public key, nothing else.
|
||||
* Only installs that are in use (not released, licence not revoked) and have sent a public key
|
||||
* (protocol v2) are listed, so a sibling can always verify what it's sent.
|
||||
*/
|
||||
async function linkedProductsFor(install, db = prisma) {
|
||||
const others = await db.install.findMany({
|
||||
where: {
|
||||
customerId: install.customerId,
|
||||
id: { not: install.id },
|
||||
releasedAt: null,
|
||||
publicKey: { not: null },
|
||||
licence: { is: { status: { not: 'revoked' } } },
|
||||
},
|
||||
select: { id: true, product: true, url: true, publicKey: true },
|
||||
orderBy: { registeredAt: 'asc' },
|
||||
});
|
||||
return others.map(o => ({ product: o.product, installId: o.id, url: o.url, publicKey: o.publicKey }));
|
||||
}
|
||||
|
||||
module.exports = { PROTOCOL_VERSIONS, isV2, parseV2, describeIssues, linkedProductsFor };
|
||||
@@ -0,0 +1,248 @@
|
||||
// Hub 2.0 step 2: protocol v2 next to v1. The contract samples (@crosscode/contracts/samples) go
|
||||
// through the real install API with signed requests, and every v2 reply is checked against the
|
||||
// contract's response schema. In-memory database.
|
||||
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const mockC1 = '0b8f3c2a-5d4e-4f6a-9b7c-1d2e3f4a5b6c';
|
||||
const mockC2 = '1c9a4d3b-6e5f-4a7b-8c8d-2e3f4a5b6c7d';
|
||||
const mockL_EVENTS = '2d0b5e4c-7f6a-4b8c-9d9e-3f4a5b6c7d8e';
|
||||
const mockL_WEBSITE = '3e1c6f5d-8a7b-4c9d-8eaf-4a5b6c7d8e9f';
|
||||
const mockL_OTHER = '4f2d7a6e-9b8c-4dae-9fb0-5b6c7d8e9fa0';
|
||||
const mockDb = (() => {
|
||||
const t = { licences: [], installs: [], events: [], heartbeats: [] };
|
||||
const id = p => `${p}_${crypto.randomUUID()}`;
|
||||
const customers = { [mockC1]: { id: mockC1, name: 'Hope Family Church' }, [mockC2]: { id: mockC2, name: 'Grace Church' } };
|
||||
const withLicence = l => l && { ...l, install: t.installs.find(i => i.licenceId === l.id) || null, customer: customers[l.customerId] };
|
||||
return {
|
||||
t,
|
||||
licence: {
|
||||
findUnique: jest.fn(async ({ where }) => withLicence(t.licences.find(l => (where.key ? l.key === where.key : l.id === where.id)))),
|
||||
},
|
||||
install: {
|
||||
findUnique: jest.fn(async ({ where }) => t.installs.find(i => i.id === where.id) || null),
|
||||
create: jest.fn(async ({ data }) => { const row = { id: crypto.randomUUID(), registeredAt: new Date(Date.now() + t.installs.length), releasedAt: null, ...data }; t.installs.push(row); return row; }),
|
||||
update: jest.fn(async ({ where, data }) => Object.assign(t.installs.find(i => i.id === where.id), Object.fromEntries(Object.entries(data).filter(([, v]) => v !== undefined)))),
|
||||
findMany: jest.fn(async ({ where, select }) => t.installs
|
||||
.filter(i => i.customerId === where.customerId && i.id !== where.id.not && i.releasedAt === null && i.publicKey != null)
|
||||
.filter(i => t.licences.find(l => l.id === i.licenceId)?.status !== 'revoked')
|
||||
.sort((a, b) => a.registeredAt - b.registeredAt)
|
||||
.map(i => Object.fromEntries(Object.keys(select).map(k => [k, i[k]])))),
|
||||
},
|
||||
installEvent: {
|
||||
create: jest.fn(async ({ data }) => { const row = { id: id('ev'), createdAt: new Date(), ...data }; t.events.push(row); return row; }),
|
||||
updateMany: jest.fn(async () => ({ count: 0 })),
|
||||
findFirst: jest.fn(async () => null),
|
||||
findMany: jest.fn(async () => []),
|
||||
},
|
||||
heartbeat: { create: jest.fn(async ({ data }) => { t.heartbeats.push(data); return data; }) },
|
||||
customer: { findUnique: jest.fn(async ({ where }) => customers[where.id]) },
|
||||
$transaction: jest.fn(async ops => Promise.all(ops)),
|
||||
};
|
||||
})();
|
||||
jest.mock('../src/config/db', () => mockDb);
|
||||
// Every test registers: the hourly register limit would cut in part-way through the file.
|
||||
jest.mock('express-rate-limit', () => () => (req, res, next) => next());
|
||||
jest.mock('../src/utils/settings', () => ({ getSettings: jest.fn(async () => ({ latest_version: '2.4.0' })) }));
|
||||
jest.mock('../src/utils/releases', () => ({
|
||||
releasesForInstall: jest.fn(async () => [{ version: '2.4.0', releasedAt: '2026-11-20T08:00:00.000Z', urgent: false, notes: '- Event feed' }]),
|
||||
}));
|
||||
jest.mock('../src/utils/notices', () => ({ noticesForInstall: jest.fn(async () => []) }));
|
||||
|
||||
process.env.HUB_ENCRYPTION_KEY = 'test-encryption-key-that-is-long-enough-123';
|
||||
const hubKey = crypto.generateKeyPairSync('ed25519');
|
||||
process.env.HUB_SIGNING_KEY = hubKey.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
|
||||
|
||||
const express = require('express');
|
||||
const { hub } = require('@crosscode/contracts');
|
||||
const licenceToken = require('../src/utils/licenceToken');
|
||||
const { signature } = require('../src/utils/signing');
|
||||
|
||||
const SAMPLES = path.join(path.dirname(require.resolve('@crosscode/contracts/package.json')), 'samples');
|
||||
const sample = name => JSON.parse(fs.readFileSync(path.join(SAMPLES, name), 'utf8'));
|
||||
const pem = () => crypto.generateKeyPairSync('ed25519').publicKey.export({ type: 'spki', format: 'pem' }).toString();
|
||||
|
||||
const KEYS = { events: 'CEH-7K2M-9QXA-P4RT-WD8C', website: 'CCW-AC3D-E4FG-H6JK-M7NP', events2: 'CEH-QRTU-VWXY-2346-79AC' };
|
||||
|
||||
let server;
|
||||
let base;
|
||||
beforeAll(async () => {
|
||||
const app = express();
|
||||
app.use(express.json({ verify: (req, res, buf) => { req.rawBody = buf.toString('utf8'); } }));
|
||||
app.use('/api', require('../src/routes/installApi'));
|
||||
await new Promise(resolve => { server = app.listen(0, '127.0.0.1', resolve); });
|
||||
base = `http://127.0.0.1:${server.address().port}/api`;
|
||||
});
|
||||
afterAll(() => new Promise(resolve => server.close(resolve)));
|
||||
|
||||
beforeEach(() => {
|
||||
const { t } = mockDb;
|
||||
t.installs.length = 0; t.events.length = 0; t.heartbeats.length = 0;
|
||||
t.licences.splice(0, t.licences.length,
|
||||
{ id: mockL_EVENTS, customerId: mockC1, product: 'events', key: KEYS.events, status: 'active', plan: 'Grow', expiresAt: null, graceDays: 14, aiMonthlyCapCents: 0 },
|
||||
{ id: mockL_WEBSITE, customerId: mockC1, product: 'website', key: KEYS.website, status: 'active', plan: 'Website', expiresAt: null, graceDays: 14, aiMonthlyCapCents: 0 },
|
||||
{ id: mockL_OTHER, customerId: mockC2, product: 'events', key: KEYS.events2, status: 'active', plan: 'Seed', expiresAt: null, graceDays: 14, aiMonthlyCapCents: 0 },
|
||||
);
|
||||
});
|
||||
|
||||
const post = (url, body, headers = {}) => fetch(`${base}${url}`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...headers }, body: typeof body === 'string' ? body : JSON.stringify(body) });
|
||||
|
||||
/** A signed request from an install (§3). */
|
||||
function signed(url, reg, body) {
|
||||
const raw = JSON.stringify(body);
|
||||
const timestamp = new Date().toISOString();
|
||||
return post(url, raw, { 'X-Hub-Install': reg.installId, 'X-Hub-Timestamp': timestamp, 'X-Hub-Signature': signature(reg.installSecret, timestamp, raw) });
|
||||
}
|
||||
|
||||
const eventsRegistration = () => sample('hub-register-request.json');
|
||||
const websiteRegistration = () => {
|
||||
const r = sample('hub-register-request.json');
|
||||
return { ...r, licenceKey: KEYS.website, product: 'website', install: { ...r.install, url: 'https://www.hopefamily.co.za', version: '1.0.0', features: {}, publicKey: pem() } };
|
||||
};
|
||||
|
||||
async function register(body) {
|
||||
const res = await post('/installs/register', body);
|
||||
return { status: res.status, json: await res.json() };
|
||||
}
|
||||
|
||||
describe('register', () => {
|
||||
test('the v2 sample registers, and the reply fits the contract', async () => {
|
||||
const { status, json } = await register(eventsRegistration());
|
||||
expect(status).toBe(201);
|
||||
expect(hub.registerResponseSchema.safeParse(json).error?.issues ?? []).toEqual([]);
|
||||
expect(json.linkedProducts).toEqual([]);
|
||||
expect(mockDb.t.installs[0]).toMatchObject({ product: 'events', protocolVersion: 2, publicKey: expect.stringContaining('BEGIN PUBLIC KEY') });
|
||||
});
|
||||
|
||||
test('the licence token carries the customer and product, and fits the contract', async () => {
|
||||
const { json } = await register(eventsRegistration());
|
||||
const payload = licenceToken.verify(json.licence, hubKey.publicKey);
|
||||
expect(hub.licencePayloadSchema.safeParse(payload).error?.issues ?? []).toEqual([]);
|
||||
expect(payload).toMatchObject({ customerId: mockC1, product: 'events', installId: json.installId });
|
||||
});
|
||||
|
||||
test('a second product lists the first in linkedProducts (and nothing more)', async () => {
|
||||
const events = await register(eventsRegistration());
|
||||
const { status, json } = await register(websiteRegistration());
|
||||
expect(status).toBe(201);
|
||||
expect(json.linkedProducts).toEqual([{ product: 'events', installId: events.json.installId, url: 'https://events.hopefamily.co.za', publicKey: eventsRegistration().install.publicKey }]);
|
||||
});
|
||||
|
||||
test('another church\'s installs are never listed', async () => {
|
||||
await register({ ...eventsRegistration(), licenceKey: KEYS.events2, install: { ...eventsRegistration().install, url: 'https://events.grace.test' } });
|
||||
const { json } = await register(eventsRegistration());
|
||||
expect(json.linkedProducts).toEqual([]);
|
||||
});
|
||||
|
||||
test('a product that doesn\'t match the licence is refused', async () => {
|
||||
const { status, json } = await register({ ...websiteRegistration(), product: 'events' });
|
||||
expect(status).toBe(409);
|
||||
expect(json.code).toBe('WRONG_PRODUCT');
|
||||
});
|
||||
|
||||
test('a key typed in lower case with spaces still registers', async () => {
|
||||
const { status } = await register({ ...eventsRegistration(), licenceKey: ' ceh-7k2m-9qxa-p4rt-wd8c ' });
|
||||
expect(status).toBe(201);
|
||||
});
|
||||
|
||||
test('a v2 body that breaks the contract is refused with what is wrong', async () => {
|
||||
const body = eventsRegistration();
|
||||
delete body.install.publicKey;
|
||||
const { status, json } = await register(body);
|
||||
expect(status).toBe(400);
|
||||
expect(json).toMatchObject({ code: 'INVALID_REQUEST', message: expect.stringContaining('install.publicKey') });
|
||||
});
|
||||
|
||||
test('v1 registers as before: Events, no linkedProducts, no public key', async () => {
|
||||
await register(websiteRegistration());
|
||||
const r = eventsRegistration();
|
||||
const { status, json } = await register({ protocolVersion: 1, licenceKey: r.licenceKey, install: { name: r.install.name, url: r.install.url, version: '2.1.1' } });
|
||||
expect(status).toBe(201);
|
||||
expect(json).not.toHaveProperty('linkedProducts');
|
||||
expect(mockDb.t.installs.find(i => i.product === 'events')).toMatchObject({ protocolVersion: 1, publicKey: undefined });
|
||||
});
|
||||
|
||||
test('protocol 3 is refused', async () => {
|
||||
const { status, json } = await register({ ...eventsRegistration(), protocolVersion: 3 });
|
||||
expect(status).toBe(400);
|
||||
expect(json.code).toBe('UNSUPPORTED_PROTOCOL');
|
||||
});
|
||||
});
|
||||
|
||||
describe('heartbeat', () => {
|
||||
test.each([
|
||||
['events', eventsRegistration, 'hub-heartbeat-events.json'],
|
||||
['website', websiteRegistration, 'hub-heartbeat-website.json'],
|
||||
])('the %s sample is recorded, and the reply fits the contract', async (product, registration, file) => {
|
||||
const { json: reg } = await register(registration());
|
||||
const res = await signed('/installs/heartbeat', reg, sample(file));
|
||||
const json = await res.json();
|
||||
expect(res.status).toBe(200);
|
||||
expect(hub.heartbeatResponseSchema.safeParse(json).error?.issues ?? []).toEqual([]);
|
||||
expect(mockDb.t.installs.find(i => i.id === reg.installId).stats).toEqual(sample(file).stats);
|
||||
});
|
||||
|
||||
test('linkedProducts in the heartbeat reply', async () => {
|
||||
const { json: events } = await register(eventsRegistration());
|
||||
const { json: website } = await register(websiteRegistration());
|
||||
const json = await (await signed('/installs/heartbeat', events, sample('hub-heartbeat-events.json'))).json();
|
||||
expect(json.linkedProducts.map(l => [l.product, l.installId])).toEqual([['website', website.installId]]);
|
||||
});
|
||||
|
||||
test('releases are Cross Events\' only until releases per product', async () => {
|
||||
const { json: website } = await register(websiteRegistration());
|
||||
expect(website).toMatchObject({ latestVersion: null, releases: [] });
|
||||
const { json: events } = await register(eventsRegistration());
|
||||
expect(events.latestVersion).toBe('2.4.0');
|
||||
});
|
||||
|
||||
test('a heartbeat for another product is refused', async () => {
|
||||
const { json: reg } = await register(eventsRegistration());
|
||||
const res = await signed('/installs/heartbeat', reg, sample('hub-heartbeat-website.json'));
|
||||
expect(res.status).toBe(409);
|
||||
expect((await res.json()).code).toBe('WRONG_PRODUCT');
|
||||
});
|
||||
|
||||
test('a v2 heartbeat that breaks the contract is refused', async () => {
|
||||
const { json: reg } = await register(eventsRegistration());
|
||||
const body = sample('hub-heartbeat-events.json');
|
||||
delete body.health;
|
||||
const res = await signed('/installs/heartbeat', reg, body);
|
||||
expect(res.status).toBe(400);
|
||||
expect((await res.json()).code).toBe('INVALID_REQUEST');
|
||||
});
|
||||
|
||||
test('a v1 heartbeat is answered as before (no linkedProducts)', async () => {
|
||||
const r = eventsRegistration();
|
||||
const { json: reg } = await register({ protocolVersion: 1, licenceKey: r.licenceKey, install: { name: r.install.name, url: r.install.url, version: '2.1.1' } });
|
||||
const res = await signed('/installs/heartbeat', reg, { protocolVersion: 1, version: '2.1.1', health: { db: true }, stats: { users: 3 } });
|
||||
const json = await res.json();
|
||||
expect(res.status).toBe(200);
|
||||
expect(Object.keys(json).sort()).toEqual(['latestVersion', 'licence', 'notices', 'releases', 'serverTime']);
|
||||
});
|
||||
|
||||
test('an unsigned heartbeat is refused', async () => {
|
||||
const { json: reg } = await register(eventsRegistration());
|
||||
const res = await post('/installs/heartbeat', sample('hub-heartbeat-events.json'), { 'X-Hub-Install': reg.installId, 'X-Hub-Timestamp': new Date().toISOString(), 'X-Hub-Signature': 'nope' });
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('update requests (v2)', () => {
|
||||
test('a v2 request without its version is refused', async () => {
|
||||
const { json: reg } = await register(eventsRegistration());
|
||||
const res = await signed('/installs/update-request', reg, { protocolVersion: 2 });
|
||||
expect(res.status).toBe(400);
|
||||
expect((await res.json()).code).toBe('INVALID_REQUEST');
|
||||
});
|
||||
|
||||
test('a v2 request is recorded', async () => {
|
||||
const { json: reg } = await register(eventsRegistration());
|
||||
const res = await signed('/installs/update-request', reg, { protocolVersion: 2, version: '2.3.0' });
|
||||
const json = await res.json();
|
||||
expect(res.status).toBe(201);
|
||||
expect(hub.updateRequestResponseSchema.safeParse(json).error?.issues ?? []).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user