Files
crosscode-platform/apps/website/backend/tests/links.test.ts
T
joshuaandClaude Opus 5.5 f6a536ad64 Accounts 1.7.1, Website 1.0.2, Events 3.7.1: link right after an install; Preview behind the proxy
Found installing the Website for cross-demo2.

- All three: a connect involving an install that isn't in the cached copy
  of the Hub's list yet asks the Hub for a fresh list (one heartbeat, at
  most once a minute) instead of refusing. A new Website's admin couldn't
  sign in for up to 30 minutes.
- Accounts: a heartbeat on every start.
- Website: /admin links to Accounts on the spot (at most every 15 s), one
  connect to Accounts at a time, and the problem page says "not linked
  yet" (ACCOUNTS_NOT_LINKED). Preview redirected to the server's own
  http://localhost:<web port>: the preview routes now answer with a
  relative Location.
- Events: a new Website can connect for the event feed straight away.
- docs: VERSIONS, changelogs, WHATS-NEW.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 16:14:20 +02:00

199 lines
12 KiB
TypeScript

import { after, describe, it } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import express from 'express';
import request from 'supertest';
import { churchExportSchema, hub, INTERNAL_ID_KEYS, LINK_SCHEMA, linkConnectSchema, type LinkConnected } from '@crosscode/contracts';
import { ed25519PublicToPem, generateEd25519, newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
import { buildExport } from '../src/export/churchExport.js';
import { stats } from '../src/hub/client.js';
import { connectAccountsIfListed } from '../src/links/connect.js';
import { keyPair, saveLinkedProducts } from '../src/links/store.js';
import { ACCOUNTS_INSTALL_ID, harness, INSTALL_ID, SITE } from './support/harness.js';
const accountsKeys = generateEd25519();
const accountsPublic = ed25519PublicToPem(accountsKeys.publicKey);
/** The church's Accounts, accepting a connect as apps/accounts/backend/src/links/connect.ts does. */
async function fakeAccounts(websitePublicKey: () => Promise<string>, opts: { badSignature?: boolean } = {}) {
const app = express();
const seen: unknown[] = [];
app.post('/api/links/v1/connect', express.json(), async (req, res) => {
const m = linkConnectSchema.parse(req.body);
seen.push(m);
if (!verifyLink(m as unknown as Record<string, unknown>, await websitePublicKey()).ok) return res.status(401).json({ code: 'BAD_SIGNATURE', message: 'no' });
const reply = signLink<Omit<LinkConnected, 'signature'>>({
schema: LINK_SCHEMA, type: 'link.connected', from: { product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: `http://127.0.0.1:${port}` },
to: { installId: m.from.installId }, inReplyTo: m.nonce, issuedAt: new Date().toISOString(), nonce: newLinkNonce(),
}, opts.badSignature ? generateEd25519().privateKeyPem : accountsKeys.privateKeyPem);
return res.json(reply);
});
const server = http.createServer(app);
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
const port = (server.address() as AddressInfo).port;
return { url: `http://127.0.0.1:${port}`, seen, close: () => new Promise((r) => server.close(r)) };
}
const closers: (() => Promise<unknown>)[] = [];
after(async () => { for (const c of closers) await c(); });
describe('linking to the church\'s Accounts', () => {
it('connects by itself once the Hub lists an Accounts, with a secret both sides keep', async () => {
const h = await harness({ linked: false, env: { LINKS_ALLOW_PRIVATE: 'true' } });
const accounts = await fakeAccounts(async () => (await keyPair(h.ctx)).publicKeyPem);
closers.push(accounts.close);
assert.equal(await connectAccountsIfListed(h.ctx), 'skipped', 'nothing listed yet');
await saveLinkedProducts(h.ctx, [{ product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: accounts.url, publicKey: accountsPublic }]);
assert.equal(await connectAccountsIfListed(h.ctx), 'connected');
const link = await h.db.productLink.findUnique({ where: { installId: ACCOUNTS_INSTALL_ID } });
assert.equal(link!.product, 'accounts');
const sent = accounts.seen[0] as { secret: string; from: { product: string; installId: string } };
assert.equal(sent.from.product, 'website');
assert.equal(sent.from.installId, INSTALL_ID);
assert.equal(h.ctx.secrets.decrypt(String(link!.secret)), sent.secret);
assert.notEqual(link!.secret, sent.secret, 'stored encrypted');
assert.equal(await connectAccountsIfListed(h.ctx), 'skipped', 'already linked');
assert.equal(accounts.seen.length, 1);
});
it('doesn\'t keep a link whose answer isn\'t signed with the key the Hub listed', async () => {
const h = await harness({ linked: false, env: { LINKS_ALLOW_PRIVATE: 'true' } });
const accounts = await fakeAccounts(async () => (await keyPair(h.ctx)).publicKeyPem, { badSignature: true });
closers.push(accounts.close);
await saveLinkedProducts(h.ctx, [{ product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: accounts.url, publicKey: accountsPublic }]);
assert.equal(await connectAccountsIfListed(h.ctx), 'failed');
assert.equal(await h.db.productLink.count(), 0);
});
it('accepts a connect from a listed sibling signed with its key, once', async () => {
const h = await harness({ linked: false });
await saveLinkedProducts(h.ctx, [{ product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: 'https://accounts.hope.test', publicKey: accountsPublic }]);
const message = () => signLink({
schema: LINK_SCHEMA, type: 'link.connect', from: { product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: 'https://accounts.hope.test' },
to: { installId: INSTALL_ID }, secret: newLinkSecret(), issuedAt: new Date().toISOString(), nonce: newLinkNonce(),
}, accountsKeys.privateKeyPem);
const m = message();
const res = await request(h.app).post('/api/links/v1/connect').send(m);
assert.equal(res.status, 200);
assert.equal(res.body.type, 'link.connected');
assert.ok(verifyLink(res.body, (await keyPair(h.ctx)).publicKeyPem).ok);
assert.equal(await h.db.productLink.count(), 1);
assert.equal((await request(h.app).post('/api/links/v1/connect').send(m)).body.code, 'REPLAYED');
const forged = { ...message(), signature: message().signature };
assert.equal((await request(h.app).post('/api/links/v1/connect').send(forged)).status, 401);
});
});
/** A Hub answering heartbeats with `list` as the church's products (only what the Website reads). */
async function fakeHub(list: () => unknown[]) {
const calls: string[] = [];
const server = http.createServer((req, res) => {
calls.push(String(req.url));
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ ok: true, licence: '', linkedProducts: list() }));
});
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
closers.push(() => new Promise((r) => server.close(r)));
return { url, calls };
}
describe('1.0.2: linking right after an install', () => {
it('links to Accounts when someone opens /admin, asking the Hub for a fresh list first', async () => {
let accountsUrl = '';
const hubServer = await fakeHub(() => [{ product: 'accounts', installId: ACCOUNTS_INSTALL_ID, url: accountsUrl, publicKey: accountsPublic }]);
const h = await harness({ linked: false, env: { LINKS_ALLOW_PRIVATE: 'true', HUB_URL: hubServer.url } });
await h.ctx.settings.set('hub_install_secret', 'secret');
const accounts = await fakeAccounts(async () => (await keyPair(h.ctx)).publicKeyPem);
closers.push(accounts.close);
accountsUrl = accounts.url;
// The Website's cached list has no Accounts yet (it registered before the Hub knew of one).
const res = await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin');
assert.equal(res.status, 303);
assert.match(res.headers.location!, /^https:\/\/accounts\.hope\.test\//, 'off to Accounts, not the problem page');
assert.deepEqual(hubServer.calls, ['/api/installs/heartbeat']);
assert.equal(accounts.seen.length, 1, 'one connect, not one from the heartbeat and another from the sign-in');
assert.equal(await h.db.productLink.count({ where: { product: 'accounts' } }), 1);
});
it('tries again at most every 15 seconds while it can\'t link', async () => {
let clock = new Date('2026-11-26T15:00:00Z');
const hubServer = await fakeHub(() => []);
const h = await harness({ linked: false, env: { HUB_URL: hubServer.url } });
h.ctx.now = () => clock;
await h.ctx.settings.set('hub_install_secret', 'secret');
const problem = `${SITE}/auth/problem?code=ACCOUNTS_NOT_LINKED&returnTo=%2Fadmin`;
assert.equal((await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin')).headers.location, problem);
assert.equal((await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin')).headers.location, problem);
assert.equal(hubServer.calls.length, 1);
clock = new Date(clock.getTime() + 61_000);
await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin');
assert.equal(hubServer.calls.length, 2);
});
it('accepts a connect from a product installed after its last heartbeat (Events, for the event feed)', async () => {
const EVENTS_INSTALL_ID = '4d2e8f3a-9b1c-4d0e-8f7a-6b5c4d3e2f1a';
const eventsKeys = generateEd25519();
const events = { product: 'events', installId: EVENTS_INSTALL_ID, url: 'https://events.hope.test', publicKey: ed25519PublicToPem(eventsKeys.publicKey) };
const hubServer = await fakeHub(() => [events]);
const h = await harness({ env: { HUB_URL: hubServer.url } });
await h.ctx.settings.set('hub_install_secret', 'secret');
const m = signLink({
schema: LINK_SCHEMA, type: 'link.connect', from: { product: 'events', installId: EVENTS_INSTALL_ID, url: events.url },
to: { installId: INSTALL_ID }, secret: newLinkSecret(), issuedAt: new Date().toISOString(), nonce: newLinkNonce(),
}, eventsKeys.privateKeyPem);
const res = await request(h.app).post('/api/links/v1/connect').send(m);
assert.equal(res.status, 200, JSON.stringify(res.body));
assert.equal(hubServer.calls.length, 1);
assert.equal(await h.db.productLink.count({ where: { product: 'events' } }), 1);
});
});
describe('the heartbeat and the export', () => {
it('reports aggregate counts the Hub accepts', async () => {
const h = await harness();
await h.db.mediaAsset.create({ data: { filename: 'hero.jpg', mime: 'image/jpeg', bytes: 1200 } });
await h.db.page.create({ data: { kind: 'home', slug: 'home', title: 'Home' } });
const s = await stats(h.ctx);
assert.ok(hub.websiteStatsSchema.safeParse(s).success);
assert.equal(s.storage.usedBytes, 1200);
assert.deepEqual(s.pages, { published: 0, drafts: 1 });
});
it('exports the content in crosscode.church-export/1, without internal ids', async () => {
const h = await harness();
await h.db.siteDesign.create({ data: { id: 1, template: 'clean', variants: {}, home: [], style: { spacing: 'airy' } } });
const home = await h.db.page.create({ data: { kind: 'home', slug: 'home', title: 'Home' } });
await h.db.section.create({ data: { pageId: home.id, type: 'hero', variant: 'text', data: { headline: 'Welcome home' } } });
const img = await h.db.mediaAsset.create({ data: { filename: '2026/hero.jpg', mime: 'image/jpeg', bytes: 1200, alt: 'The hall' } });
await h.db.simpleEvent.create({ data: { slug: 'picnic', title: 'Picnic', startsAt: new Date('2026-12-05T08:00:00Z'), imageId: img.id, publishedAt: new Date() } });
await h.db.message.create({ data: { slug: 'hope', title: 'Hope', date: new Date('2026-11-22T08:00:00Z'), source: 'youtube_feed', mediaUrl: 'https://www.youtube.com/watch?v=abc' } });
await h.db.websiteUser.create({ data: { id: '11111111-1111-4111-8111-111111111111', name: 'Sam', email: 'pastor@hope.test', role: 'owner' } });
await h.db.siteVersion.create({ data: { number: 1, snapshot: {}, publishedBy: '11111111-1111-4111-8111-111111111111', note: 'First' } });
const data = await buildExport(h.ctx);
assert.ok(churchExportSchema.safeParse(data).success);
const w = data.website!;
assert.equal(w.template, 'clean');
assert.equal(w.pages[0]!.path, '/');
assert.deepEqual(w.pages[0]!.sections[0], { type: 'hero', variant: 'text', hidden: false, content: { headline: 'Welcome home' } });
assert.equal(w.events[0]!.image, 'uploads/2026/hero.jpg');
assert.equal(w.messages[0]!.source, 'youtube-feed');
assert.deepEqual(w.versions[0], { number: 1, publishedAt: w.versions[0]!.publishedAt, by: 'Sam', note: 'First' });
assert.equal(data.people[0]!.role, 'website owner');
const keys: string[] = [];
const walk = (x: unknown) => {
if (Array.isArray(x)) x.forEach(walk);
else if (x && typeof x === 'object') for (const [k, v] of Object.entries(x)) { keys.push(k); walk(v); }
};
walk({ ...data, website: { ...w, pages: w.pages.map((p) => ({ ...p, sections: p.sections.map((s) => ({ ...s, content: {} })) })) } });
assert.deepEqual(keys.filter((k) => INTERNAL_ID_KEYS.test(k)), []);
});
});