Events 2.4.0 backend: protocol v2, Linked products, the event feed
- Hub client: register and heartbeat on protocol v2 with the site's Ed25519 key (sent on the heartbeat until the Hub has it); falls back to v1 for a day if the Hub refuses v2, so the licence always refreshes. - crosscode.link/1 Connect / Disconnect, both directions, trusted through the Hub's cached linkedProducts (ProductLink, LinkNonce). - GET /api/feed/v1/events from FeedEntry (go-live, closing and selling out are changes; deactivated events go in deleted), event.changed to connected products, and showing their events (ImportedEvent). - /api/v2/linked-products, /api/v2/linked-events; /events/:id/full gains crosscodeEvent and priceRangeCents for the JSON-LD. - Contracts: FEED_PATHS, typesVersions for @crosscode/contracts/signing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,186 @@
|
||||
/**
|
||||
* Connect and Disconnect (`crosscode.link/1`, docs/EVENTS-2.4-PLAN.md §2).
|
||||
*
|
||||
* Trust comes from the Hub's list on both sides: a message is accepted only from an install in
|
||||
* this site's own cached `linkedProducts` (same church), signed with the key the Hub listed for
|
||||
* it. The Hub isn't called while connecting. Both sides then hold the same secret, which signs the
|
||||
* calls between them (the `event.changed` webhook).
|
||||
*/
|
||||
import {
|
||||
LINK_PATHS,
|
||||
LINK_SCHEMA,
|
||||
linkConnectedSchema,
|
||||
linkConnectSchema,
|
||||
linkDisconnectSchema,
|
||||
type LinkConnect,
|
||||
type LinkConnected,
|
||||
type LinkDisconnect,
|
||||
type hub,
|
||||
} from '@crosscode/contracts';
|
||||
import { newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
|
||||
import { hubInstallId, siteUrl } from '../feed/context';
|
||||
import { callSibling, LinkCallError, siblingUrl } from './http';
|
||||
import { keyPair, listedProduct } from './store';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
const { encrypt } = require('../utils/encryption') as { encrypt(v: string): string };
|
||||
const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(entry: object): Promise<void> };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
export class LinkError extends Error {
|
||||
constructor(message: string, public code: string, public status = 400) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
const NONCE_KEEP_MS = 60 * 60 * 1000;
|
||||
|
||||
type Self = { installId: string; url: string; privateKeyPem: string };
|
||||
|
||||
async function self(): Promise<Self> {
|
||||
const installId = await hubInstallId();
|
||||
if (!installId) throw new LinkError('This site isn\'t connected to the Hub, so it can\'t link to other products yet.', 'LINKS_UNAVAILABLE', 503);
|
||||
const url = await siteUrl();
|
||||
if (!/^https?:\/\//.test(url)) throw new LinkError('Set the site\'s web address first (Site settings → Organisation).', 'LINKS_UNAVAILABLE', 503);
|
||||
const { privateKeyPem } = await keyPair();
|
||||
return { installId, url, privateKeyPem };
|
||||
}
|
||||
|
||||
const party = (s: Self) => ({ product: 'events' as const, installId: s.installId, url: s.url });
|
||||
|
||||
/** Records a nonce; false when it was seen before (a replay). Old nonces are cleaned up. */
|
||||
async function firstUse(nonce: string, now: Date): Promise<boolean> {
|
||||
await prisma.linkNonce.deleteMany({ where: { seenAt: { lt: new Date(now.getTime() - NONCE_KEEP_MS) } } }).catch(() => {});
|
||||
try {
|
||||
await prisma.linkNonce.create({ data: { nonce, seenAt: now } });
|
||||
return true;
|
||||
} catch (e) {
|
||||
if ((e as { code?: string })?.code === 'P2002') return false;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async function audit(action: string, link: { installId: string; product: string }, actor: { id: string; role: string } | null, ip: string | null, metadata: object = {}) {
|
||||
await logAdminAction({
|
||||
actorId: actor?.id ?? null,
|
||||
actorRole: actor?.role ?? 'linked_product',
|
||||
action,
|
||||
targetType: 'product_link',
|
||||
targetId: link.installId,
|
||||
metadata: { product: link.product, ...metadata },
|
||||
ip,
|
||||
});
|
||||
}
|
||||
|
||||
async function saveLink(sibling: hub.LinkedProduct, secret: string, connectedById: string | null, now: Date) {
|
||||
const data = { product: sibling.product, url: sibling.url, publicKey: sibling.publicKey, secret: encrypt(secret), connectedAt: now, connectedById, lastSyncError: null };
|
||||
return prisma.productLink.upsert({ where: { installId: sibling.installId }, create: { installId: sibling.installId, ...data }, update: data });
|
||||
}
|
||||
|
||||
// ─── This site connects (an admin clicked Connect) ─────────────────────────────
|
||||
|
||||
export async function connectTo(installId: string, actor: { id: string; role: string }, ip: string | null, now = new Date()) {
|
||||
const sibling = await listedProduct(installId);
|
||||
if (!sibling) throw new LinkError('That product isn\'t in the list the Hub gave this site. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
|
||||
const me = await self();
|
||||
const secret = newLinkSecret();
|
||||
const message = signLink<Omit<LinkConnect, 'signature'>>({
|
||||
schema: LINK_SCHEMA,
|
||||
type: 'link.connect',
|
||||
from: party(me),
|
||||
to: { installId: sibling.installId },
|
||||
secret,
|
||||
issuedAt: now.toISOString(),
|
||||
nonce: newLinkNonce(),
|
||||
}, me.privateKeyPem);
|
||||
|
||||
let reply: unknown;
|
||||
try {
|
||||
reply = await callSibling(await siblingUrl(sibling.url, LINK_PATHS.connect), { method: 'POST', body: JSON.stringify(message) });
|
||||
} catch (e) {
|
||||
if (e instanceof LinkCallError) throw new LinkError(`${sibling.url} refused to connect: ${e.message}`, e.code, 502);
|
||||
throw e;
|
||||
}
|
||||
const parsed = linkConnectedSchema.safeParse(reply);
|
||||
if (!parsed.success) throw new LinkError(`${sibling.url} answered in a way this site doesn't understand.`, 'BAD_REPLY', 502);
|
||||
const r: LinkConnected = parsed.data;
|
||||
const check = verifyLink(r as unknown as Record<string, unknown>, sibling.publicKey, { now: new Date() });
|
||||
if (!check.ok || r.inReplyTo !== message.nonce || r.from.installId !== sibling.installId || r.to.installId !== me.installId) {
|
||||
throw new LinkError(`${sibling.url}'s answer isn't signed with the key the Hub listed for it.`, 'BAD_SIGNATURE', 502);
|
||||
}
|
||||
const link = await saveLink(sibling, secret, actor.id, now);
|
||||
await audit('product_link_connected', link, actor, ip, { by: 'this_site' });
|
||||
return link;
|
||||
}
|
||||
|
||||
// ─── A sibling connects to this site ───────────────────────────────────────────
|
||||
|
||||
/** Answers `POST /api/links/v1/connect`. Throws LinkError (with the code the sibling is told). */
|
||||
export async function acceptConnect(body: unknown, ip: string | null, now = new Date()): Promise<LinkConnected> {
|
||||
const parsed = linkConnectSchema.safeParse(body);
|
||||
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 connect message.', 'INVALID_REQUEST', 400);
|
||||
const m = parsed.data;
|
||||
const me = await self();
|
||||
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
|
||||
const sibling = await listedProduct(m.from.installId);
|
||||
if (!sibling || sibling.product !== m.from.product) {
|
||||
throw new LinkError('This site doesn\'t know that install yet: the Hub lists the church\'s products in its next heartbeat (up to 15 minutes).', 'NOT_LINKED', 403);
|
||||
}
|
||||
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { now });
|
||||
if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401);
|
||||
if (!(await firstUse(m.nonce, now))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
|
||||
|
||||
const link = await saveLink(sibling, m.secret, null, now);
|
||||
await audit('product_link_connected', link, null, ip, { by: 'sibling' });
|
||||
return signLink<Omit<LinkConnected, 'signature'>>({
|
||||
schema: LINK_SCHEMA,
|
||||
type: 'link.connected',
|
||||
from: party(me),
|
||||
to: { installId: sibling.installId },
|
||||
inReplyTo: m.nonce,
|
||||
issuedAt: new Date().toISOString(),
|
||||
nonce: newLinkNonce(),
|
||||
}, me.privateKeyPem);
|
||||
}
|
||||
|
||||
// ─── Disconnect ───────────────────────────────────────────────────────────────
|
||||
|
||||
/** This site ends a link. The local link goes even if the sibling can't be reached. */
|
||||
export async function disconnectFrom(installId: string, actor: { id: string; role: string }, ip: string | null, now = new Date()): Promise<{ siblingTold: boolean; message: string | null }> {
|
||||
const link = await prisma.productLink.findUnique({ where: { installId } });
|
||||
if (!link) throw new LinkError('That product isn\'t connected.', 'NOT_LINKED', 404);
|
||||
let siblingTold = false;
|
||||
let problem: string | null = null;
|
||||
try {
|
||||
const me = await self();
|
||||
const message = signLink<Omit<LinkDisconnect, 'signature'>>({
|
||||
schema: LINK_SCHEMA, type: 'link.disconnect', from: party(me), to: { installId }, issuedAt: now.toISOString(), nonce: newLinkNonce(),
|
||||
}, me.privateKeyPem);
|
||||
await callSibling(await siblingUrl(link.url, LINK_PATHS.disconnect), { method: 'POST', body: JSON.stringify(message) });
|
||||
siblingTold = true;
|
||||
} catch (e) {
|
||||
problem = (e as Error).message;
|
||||
}
|
||||
// Its imported events go with it (ImportedEvent cascades).
|
||||
await prisma.productLink.delete({ where: { installId } });
|
||||
await audit('product_link_disconnected', link, actor, ip, { by: 'this_site', siblingTold });
|
||||
return { siblingTold, message: problem };
|
||||
}
|
||||
|
||||
/** Answers `POST /api/links/v1/disconnect`, checked against the key saved when the link was made. */
|
||||
export async function acceptDisconnect(body: unknown, ip: string | null, now = new Date()): Promise<void> {
|
||||
const parsed = linkDisconnectSchema.safeParse(body);
|
||||
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 disconnect message.', 'INVALID_REQUEST', 400);
|
||||
const m = parsed.data;
|
||||
const me = await self();
|
||||
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
|
||||
const link = await prisma.productLink.findUnique({ where: { installId: m.from.installId } });
|
||||
// Already gone: nothing to do, and nothing to tell (the sibling just wants it ended).
|
||||
if (!link) return;
|
||||
const check = verifyLink(m as unknown as Record<string, unknown>, link.publicKey, { now });
|
||||
if (!check.ok) throw new LinkError('The signature doesn\'t match this link.', check.code, 401);
|
||||
if (!(await firstUse(m.nonce, now))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
|
||||
await prisma.productLink.delete({ where: { installId: link.installId } });
|
||||
await audit('product_link_disconnected', link, null, ip, { by: 'sibling' });
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* Calls to a linked product: only to a public https address the Hub listed (the same rule as
|
||||
* outbound webhooks, utils/webhooks.js: private addresses refused unless WEBHOOKS_ALLOW_PRIVATE
|
||||
* is set for local testing), redirects not followed, a timeout, and a size limit on the answer.
|
||||
*/
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const { assertPublicHost } = require('../utils/webhooks') as { assertPublicHost(hostname: string): Promise<void> };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
export const TIMEOUT_MS = 15000;
|
||||
const MAX_BYTES = 5 * 1024 * 1024;
|
||||
|
||||
export class LinkCallError extends Error {
|
||||
constructor(message: string, public code: string, public status = 502, public data: unknown = null) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
const allowHttp = () => String(process.env.WEBHOOKS_ALLOW_PRIVATE || '').toLowerCase() === 'true';
|
||||
|
||||
/** The address of `path` on a sibling, after checking where it points. */
|
||||
export async function siblingUrl(base: string, path: string, query: Record<string, string> = {}): Promise<URL> {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(path, base.endsWith('/') ? base : `${base}/`);
|
||||
} catch {
|
||||
throw new LinkCallError(`${base} isn't a web address`, 'BAD_ADDRESS', 400);
|
||||
}
|
||||
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && allowHttp())) throw new LinkCallError(`${base} doesn't use https`, 'BAD_ADDRESS', 400);
|
||||
for (const [k, v] of Object.entries(query)) url.searchParams.set(k, v);
|
||||
try {
|
||||
await assertPublicHost(url.hostname);
|
||||
} catch (e) {
|
||||
throw new LinkCallError((e as Error).message, 'PRIVATE_ADDRESS', 400);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
async function readLimited(res: Response): Promise<string> {
|
||||
const length = Number(res.headers.get('content-length') || 0);
|
||||
if (length > MAX_BYTES) throw new LinkCallError('The answer is too large', 'TOO_LARGE');
|
||||
const text = await res.text();
|
||||
if (text.length > MAX_BYTES) throw new LinkCallError('The answer is too large', 'TOO_LARGE');
|
||||
return text;
|
||||
}
|
||||
|
||||
/** A JSON request to a sibling. Throws LinkCallError with the sibling's own message and code on a 4xx/5xx. */
|
||||
export async function callSibling(url: URL, init: { method: 'GET' | 'POST'; body?: string; headers?: Record<string, string> }): Promise<unknown> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(url, {
|
||||
method: init.method,
|
||||
headers: { Accept: 'application/json', ...(init.body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...init.headers },
|
||||
body: init.body,
|
||||
redirect: 'manual',
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||
});
|
||||
} catch (e) {
|
||||
throw new LinkCallError(`${url.host} could not be reached: ${(e as Error)?.message || e}`, 'UNREACHABLE');
|
||||
}
|
||||
if (res.status >= 300 && res.status < 400) throw new LinkCallError(`${url.host} answered with a redirect`, 'REDIRECTED');
|
||||
const text = await readLimited(res);
|
||||
let data: unknown = null;
|
||||
try {
|
||||
data = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
if (res.ok) throw new LinkCallError(`${url.host} didn't answer with JSON`, 'NOT_JSON');
|
||||
}
|
||||
if (!res.ok) {
|
||||
const d = (data && typeof data === 'object' ? data : {}) as { message?: string; code?: string; error?: { message?: string; code?: string } };
|
||||
throw new LinkCallError(d.message || d.error?.message || `${url.host} answered ${res.status}`, d.code || d.error?.code || `HTTP_${res.status}`, res.status >= 500 ? 502 : res.status, data);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* The endpoints the church's other products call (docs/EVENTS-2.4-PLAN.md §2–4). Contracts
|
||||
* between products, so outside /api/v2, with errors as `{ message, code }`:
|
||||
*
|
||||
* GET /api/feed/v1/events?updatedSince= crosscode.event-feed/1 (public; "Publish my events")
|
||||
* POST /api/feed/v1/changed event.changed from a linked product (LINK_HEADERS)
|
||||
* POST /api/links/v1/connect crosscode.link/1 link.connect → link.connected
|
||||
* POST /api/links/v1/disconnect crosscode.link/1 link.disconnect → link.disconnected
|
||||
*
|
||||
* Mounted before the app's JSON parser: the webhook is verified on its raw bytes.
|
||||
*/
|
||||
import express, { type Request, type Response, type Router } from 'express';
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import { eventChangedSchema, FEED_PATHS, LINK_PATHS, LINK_SCHEMA } from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, verify } from '@crosscode/contracts/signing';
|
||||
import { hubInstallId, publishOn } from '../feed/context';
|
||||
import { feedResponse, lastRefresh, refreshOnce } from '../feed/entries';
|
||||
import { acceptConnect, acceptDisconnect, LinkError } from './connect';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
const { decrypt } = require('../utils/encryption') as { decrypt(v: string): string };
|
||||
const { getClientIp } = require('../utils/requestUtils') as { getClientIp(req: Request): string | null };
|
||||
const { enqueueTask } = require('../jobs') as { enqueueTask(name: string, data: object): Promise<unknown> };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
/** The feed is rebuilt before answering when the last refresh is older than this. */
|
||||
const FRESH_MS = 60 * 1000;
|
||||
|
||||
const fail = (res: Response, status: number, code: string, message: string) => res.status(status).json({ message, code });
|
||||
|
||||
function sendError(res: Response, e: unknown) {
|
||||
if (e instanceof LinkError) return fail(res, e.status, e.code, e.message);
|
||||
console.error('[links]', e);
|
||||
return fail(res, 500, 'SERVER_ERROR', 'Something went wrong.');
|
||||
}
|
||||
|
||||
const limiter = (max: number) => rateLimit({ windowMs: 5 * 60 * 1000, max, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many requests, please try again later.', code: 'RATE_LIMITED' } });
|
||||
|
||||
export function crossProductRouter(): Router {
|
||||
const router = express.Router();
|
||||
const json = express.json({ limit: '16kb' });
|
||||
|
||||
router.get(FEED_PATHS.events.replace(/^\/api/, ''), limiter(300), async (req, res) => {
|
||||
try {
|
||||
if (!(await publishOn())) return fail(res, 404, 'FEED_OFF', 'This site doesn\'t publish its events (Settings → Linked products).');
|
||||
if (!(await hubInstallId())) return fail(res, 503, 'FEED_UNAVAILABLE', 'This site isn\'t connected to the Hub yet, so it has no feed.');
|
||||
const raw = typeof req.query.updatedSince === 'string' ? req.query.updatedSince : null;
|
||||
const since = raw ? new Date(raw) : null;
|
||||
if (raw && (!since || !Number.isFinite(since.getTime()))) return fail(res, 400, 'INVALID_REQUEST', 'updatedSince must be an ISO 8601 date and time.');
|
||||
if (Date.now() - lastRefresh() > FRESH_MS) await refreshOnce();
|
||||
res.set('Cache-Control', 'no-store');
|
||||
return res.json(await feedResponse(since));
|
||||
} catch (e) {
|
||||
return sendError(res, e);
|
||||
}
|
||||
});
|
||||
|
||||
router.post(FEED_PATHS.changed.replace(/^\/api/, ''), limiter(300), express.raw({ type: () => true, limit: '16kb' }), async (req, res) => {
|
||||
try {
|
||||
const sender = String(req.get(LINK_HEADERS.sender) || '');
|
||||
const link = sender ? await prisma.productLink.findUnique({ where: { installId: sender } }) : null;
|
||||
if (!link) return fail(res, 404, 'NOT_LINKED', 'This site has no link with that install.');
|
||||
const rawBody: Buffer = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
|
||||
const check = verify({ secret: decrypt(link.secret), timestamp: req.get(LINK_HEADERS.timestamp), signature: req.get(LINK_HEADERS.signature), rawBody });
|
||||
if (!check.ok) return fail(res, 401, check.code, 'The signature doesn\'t match this link.');
|
||||
let body: unknown;
|
||||
try { body = JSON.parse(rawBody.toString('utf8')); } catch { body = null; }
|
||||
if (!eventChangedSchema.safeParse(body).success) return fail(res, 400, 'INVALID_REQUEST', 'That isn\'t an event.changed message.');
|
||||
if (link.showEvents) await enqueueTask('feed-sync-link', { installId: link.installId });
|
||||
return res.status(202).json({ accepted: true, fetching: link.showEvents });
|
||||
} catch (e) {
|
||||
return sendError(res, e);
|
||||
}
|
||||
});
|
||||
|
||||
router.post(LINK_PATHS.connect.replace(/^\/api/, ''), limiter(30), json, async (req, res) => {
|
||||
try {
|
||||
return res.json(await acceptConnect(req.body, getClientIp(req)));
|
||||
} catch (e) {
|
||||
return sendError(res, e);
|
||||
}
|
||||
});
|
||||
|
||||
router.post(LINK_PATHS.disconnect.replace(/^\/api/, ''), limiter(30), json, async (req, res) => {
|
||||
try {
|
||||
await acceptDisconnect(req.body, getClientIp(req));
|
||||
return res.json({ schema: LINK_SCHEMA, type: 'link.disconnected' });
|
||||
} catch (e) {
|
||||
return sendError(res, e);
|
||||
}
|
||||
});
|
||||
|
||||
// A body that isn't JSON (express.json's own error) answers in the same shape.
|
||||
router.use((err: { type?: string; status?: number }, _req: Request, res: Response, next: (e?: unknown) => void) => {
|
||||
if (err?.type === 'entity.parse.failed' || err?.type === 'entity.too.large') return fail(res, err.status || 400, 'INVALID_REQUEST', 'The body must be JSON (16 kB at most).');
|
||||
return next(err);
|
||||
});
|
||||
return router;
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* This site's Ed25519 key pair and the church's other products as the Hub last listed them
|
||||
* (docs/EVENTS-2.4-PLAN.md §1–2). Kept in AppSetting, out of the generic settings endpoints
|
||||
* (hub/client.js HUB_KEYS):
|
||||
* hub_private_key (encrypted PKCS#8 PEM), hub_public_key (SPKI PEM), hub_public_key_status
|
||||
* (the Hub's last publicKeyStatus), hub_linked_products (JSON, from the last heartbeat).
|
||||
* The key pair is made once and never changed: the Hub keeps the first key it saw, and every
|
||||
* linked product checks this site's messages against it.
|
||||
*/
|
||||
import { hub } from '@crosscode/contracts';
|
||||
import { ed25519PublicToPem, generateEd25519 } from '@crosscode/contracts/signing';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
const { encrypt, decrypt } = require('../utils/encryption') as { encrypt(v: string): string; decrypt(v: string): string };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
type LinkedProduct = hub.LinkedProduct;
|
||||
|
||||
export const KEY_SETTINGS = ['hub_private_key', 'hub_public_key', 'hub_public_key_status', 'hub_linked_products'] as const;
|
||||
|
||||
async function read(key: string): Promise<string | null> {
|
||||
const row = await prisma.appSetting.findUnique({ where: { key } });
|
||||
return row?.value ?? null;
|
||||
}
|
||||
|
||||
async function write(key: string, value: string | null): Promise<void> {
|
||||
if (value === null) await prisma.appSetting.deleteMany({ where: { key } });
|
||||
else await prisma.appSetting.upsert({ where: { key }, update: { value }, create: { key, value } });
|
||||
}
|
||||
|
||||
let made: Promise<{ publicKeyPem: string; privateKeyPem: string }> | null = null;
|
||||
|
||||
/** This site's key pair, made the first time it's needed. */
|
||||
export function keyPair(): Promise<{ publicKeyPem: string; privateKeyPem: string }> {
|
||||
if (!made) {
|
||||
made = (async () => {
|
||||
const [priv, pub] = await Promise.all([read('hub_private_key'), read('hub_public_key')]);
|
||||
if (priv && pub) return { privateKeyPem: decrypt(priv), publicKeyPem: pub };
|
||||
const pair = generateEd25519();
|
||||
const publicKeyPem = ed25519PublicToPem(pair.publicKey);
|
||||
await write('hub_private_key', encrypt(pair.privateKeyPem));
|
||||
await write('hub_public_key', publicKeyPem);
|
||||
return { privateKeyPem: pair.privateKeyPem, publicKeyPem };
|
||||
})().catch((e) => {
|
||||
made = null;
|
||||
throw e;
|
||||
});
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
/** For tests. */
|
||||
export function forgetKeyPair(): void {
|
||||
made = null;
|
||||
}
|
||||
|
||||
/** `saved` / `matches` / `mismatch` from the Hub, or null (not sent yet, or a Hub before 2.2.0). */
|
||||
export async function publicKeyStatus(): Promise<string | null> {
|
||||
return read('hub_public_key_status');
|
||||
}
|
||||
|
||||
export async function setPublicKeyStatus(status: string | null): Promise<void> {
|
||||
await write('hub_public_key_status', status);
|
||||
}
|
||||
|
||||
/** The church's other installs as the Hub last listed them (an empty list if it never did). */
|
||||
export async function linkedProducts(): Promise<LinkedProduct[]> {
|
||||
const raw = await read('hub_linked_products');
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const list = JSON.parse(raw);
|
||||
return Array.isArray(list) ? list.filter((l) => hub.linkedProductSchema.safeParse(l).success) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves the list from a v2 heartbeat or register reply. Entries that don't fit the contract are left out. */
|
||||
export async function saveLinkedProducts(list: unknown): Promise<LinkedProduct[]> {
|
||||
if (!Array.isArray(list)) return linkedProducts();
|
||||
const clean = list.map((l) => hub.linkedProductSchema.safeParse(l)).filter((r) => r.success).map((r) => r.data as LinkedProduct).slice(0, 10);
|
||||
await write('hub_linked_products', JSON.stringify(clean));
|
||||
return clean;
|
||||
}
|
||||
|
||||
export async function listedProduct(installId: string): Promise<LinkedProduct | null> {
|
||||
return (await linkedProducts()).find((l) => l.installId === installId) ?? null;
|
||||
}
|
||||
Reference in New Issue
Block a user