// Hub 2.0 step 1: products, licence keys per product, one open licence per product per customer // (with the partial unique index simulated), the free Accounts licence, and protocol v1 // registering Events licences only. In-memory database. const mockLicences = []; const mockInstalls = []; const isOpen = l => l.status !== 'revoked'; const mockDb = { licence: { findFirst: jest.fn(async ({ where }) => mockLicences.find(l => l.customerId === where.customerId && l.product === where.product && (!where.status?.not || l.status !== where.status.not)) || null), findUnique: jest.fn(async ({ where, include }) => { const l = mockLicences.find(x => (where.key ? x.key === where.key : x.id === where.id)); if (!l) return null; return include ? { ...l, install: mockInstalls.find(i => i.licenceId === l.id) || null, customer: { id: l.customerId, name: 'Hope Church' } } : l; }), create: jest.fn(async ({ data }) => { // The unique key and the partial unique index on (customerId, product) WHERE status <> 'revoked'. if (mockLicences.some(l => l.key === data.key)) throw Object.assign(new Error('Unique constraint failed'), { code: 'P2002' }); const status = data.status || 'active'; if (status !== 'revoked' && mockLicences.some(l => isOpen(l) && l.customerId === data.customerId && l.product === data.product)) { throw Object.assign(new Error('Unique constraint failed'), { code: 'P2002' }); } const row = { id: `lic_${mockLicences.length + 1}`, status, plan: 'standard', createdAt: new Date(), ...data }; mockLicences.push(row); return row; }), }, install: { create: jest.fn(async ({ data }) => { const row = { id: `inst_${mockInstalls.length + 1}`, ...data }; mockInstalls.push(row); return row; }), update: jest.fn(), }, installEvent: { create: jest.fn(async () => ({})) }, }; jest.mock('../src/config/db', () => mockDb); jest.mock('../src/utils/settings', () => ({ getSettings: jest.fn(async () => ({ latest_version: '2.1.1' })) })); jest.mock('../src/utils/releases', () => ({ releasesForInstall: jest.fn(async () => []), latestVersions: jest.fn(async () => ({ events: '2.1.1' })) })); jest.mock('../src/utils/notices', () => ({ noticesForInstall: jest.fn(async () => []) })); jest.mock('../src/utils/licenceToken', () => ({ sign: jest.fn(() => 'hel1.token.sig'), buildPayload: jest.fn(() => ({})) })); process.env.HUB_ENCRYPTION_KEY = 'test-encryption-key-that-is-long-enough-123'; const express = require('express'); const { licenceKey } = require('../src/utils/crypto'); const { PRODUCTS, KEY_PREFIXES, productOfKey } = require('../src/utils/products'); const { generateLicence, createLicence, checkReopen } = require('../src/utils/licences'); const { productSchema } = require('@crosscode/contracts'); beforeEach(() => { mockLicences.length = 0; mockInstalls.length = 0; }); describe('products', () => { test('the Hub has the same products as the contracts', () => { expect([...PRODUCTS].sort()).toEqual([...productSchema.options].sort()); }); test.each(PRODUCTS)('%s keys have their own prefix and are recognised', product => { const key = licenceKey(product); expect(key).toMatch(new RegExp(`^${KEY_PREFIXES[product]}(-[ACDEFGHJKMNPQRTUVWXY234679]{4}){4}$`)); expect(productOfKey(key)).toBe(product); }); test('Events keys keep CEH-, and the default is Events', () => { expect(licenceKey()).toMatch(/^CEH-/); expect(() => licenceKey('nope')).toThrow(); }); }); describe('licences', () => { test('the first product licence comes with a free Accounts licence', async () => { const { licence, accounts } = await generateLicence(mockDb, { customerId: 'c1', product: 'website', data: { status: 'active' } }); expect(licence).toMatchObject({ product: 'website', key: expect.stringMatching(/^CCW-/) }); expect(accounts).toMatchObject({ product: 'accounts', plan: 'included', key: expect.stringMatching(/^CCA-/) }); }); test('a later product licence does not make a second Accounts licence', async () => { await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} }); const { accounts } = await generateLicence(mockDb, { customerId: 'c1', product: 'app', data: {} }); expect(accounts).toBeNull(); expect(mockLicences.filter(l => l.product === 'accounts')).toHaveLength(1); }); test('a second open licence for the same product is refused', async () => { await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} }); await expect(generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} })).rejects.toMatchObject({ status: 409, code: 'PRODUCT_LICENCE_EXISTS' }); }); test('another customer can have the same product', async () => { await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} }); await expect(generateLicence(mockDb, { customerId: 'c2', product: 'events', data: {} })).resolves.toBeTruthy(); }); test('a revoked licence can be replaced', async () => { const { licence } = await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} }); licence.status = 'revoked'; await expect(generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} })).resolves.toBeTruthy(); }); test('a race is caught by the unique index', async () => { // Both requests pass the check before either inserts: the second insert hits the index. mockDb.licence.findFirst.mockResolvedValueOnce(null); await createLicence(mockDb, { customerId: 'c1', product: 'app', data: {} }); mockDb.licence.findFirst.mockResolvedValueOnce(null); await expect(createLicence(mockDb, { customerId: 'c1', product: 'app', data: {} })).rejects.toMatchObject({ code: 'PRODUCT_LICENCE_EXISTS' }); }); test('un-revoking is refused when the product has another open licence', async () => { const { licence: old } = await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} }); old.status = 'revoked'; await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} }); await expect(checkReopen(mockDb, old, 'active')).rejects.toMatchObject({ code: 'PRODUCT_LICENCE_EXISTS' }); await expect(checkReopen(mockDb, old, 'revoked')).resolves.toBeUndefined(); }); test('a product added to a customer that is billed already starts after its free month', async () => { mockDb.customer = { findUnique: jest.fn(async () => ({ id: 'c1', billingCycle: 'monthly' })) }; try { const { licence, accounts } = await generateLicence(mockDb, { customerId: 'c1', product: 'app', data: {}, now: new Date('2026-11-04T10:00:00Z') }); expect(licence.billedFrom.toISOString().slice(0, 10)).toBe('2026-12-04'); // Accounts is free: never charged. expect(accounts.billedFrom).toBeUndefined(); } finally { delete mockDb.customer; } }); test('a customer not billed yet: the product waits until billing is set up', async () => { mockDb.customer = { findUnique: jest.fn(async () => ({ id: 'c1', billingCycle: 'none' })) }; try { const { licence } = await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} }); expect(licence.billedFrom).toBeUndefined(); } finally { delete mockDb.customer; } }); test('unknown products are refused', async () => { await expect(createLicence(mockDb, { customerId: 'c1', product: 'shop' })).rejects.toMatchObject({ status: 400 }); }); }); describe('register (protocol v1)', () => { let server; let base; beforeAll(async () => { const app = express(); app.use(express.json()); 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))); const register = key => fetch(`${base}/installs/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ protocolVersion: 1, licenceKey: key, install: { name: 'Hope Church', url: 'https://events.hope.test', version: '2.1.1' } }), }); test('an Events licence registers, and the install is an Events install', async () => { const { licence } = await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} }); const res = await register(licence.key); expect(res.status).toBe(201); expect(mockInstalls[0]).toMatchObject({ product: 'events', licenceId: licence.id }); }); test('another product\'s licence is refused with WRONG_PRODUCT', async () => { const { licence } = await generateLicence(mockDb, { customerId: 'c1', product: 'website', data: {} }); const res = await register(licence.key); expect(res.status).toBe(409); expect(await res.json()).toMatchObject({ code: 'WRONG_PRODUCT' }); expect(mockInstalls).toHaveLength(0); }); });