feat(website): the event feed both ways, and Linked products
Publish my events: the Website's simple events as crosscode.event/1 (GET /api/feed/v1/events, updatedSince, removals in deleted for 90 days) and a signed event.changed to linked siblings. Show events from: each sibling's feed every 15 minutes and at once on its signed event.changed; read-only copies of only that sibling's events, one bad event skipped, the last good copy kept. Admin: Linked products. church.changed from Accounts refreshes the profile at once. Plan: the video hero, more blocks and more pages move to website@1.1.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -11,6 +11,7 @@ import { audit } from '../lib/audit.js';
|
||||
import { youtubeId, spotifyEmbed } from '../site/content.js';
|
||||
import { mediaUrl } from '../site/snapshot.js';
|
||||
import { getSource, setSource, syncYoutube, uniqueSlug } from '../site/youtube.js';
|
||||
import { markRemoved, notifyLinks } from '../feed/feed.js';
|
||||
|
||||
type Who = { id: string; role: string };
|
||||
|
||||
@@ -136,7 +137,10 @@ export async function saveEvent(ctx: Ctx, id: string | null, body: unknown, by:
|
||||
const data = { title: e.title, startsAt: new Date(e.startsAt), endsAt: e.endsAt ? new Date(e.endsAt) : null, allDay: e.allDay, location: e.location, description: e.description, imageId: e.imageId, link: e.link, timezone: ctx.config.timezone, updatedBy: by.id };
|
||||
if (id) {
|
||||
if (!(await ctx.db.simpleEvent.findUnique({ where: { id } }))) throw new ApiError(404, 'NOT_FOUND', 'That event doesn\'t exist.');
|
||||
return ctx.db.simpleEvent.update({ where: { id }, data });
|
||||
const saved = await ctx.db.simpleEvent.update({ where: { id }, data });
|
||||
// A live event changed: the church's other sites fetch it now.
|
||||
if (saved.publishedAt) void notifyLinks(ctx, [id]).catch(() => {});
|
||||
return saved;
|
||||
}
|
||||
return ctx.db.simpleEvent.create({ data: { ...data, slug: await uniqueSlug(ctx, e.title, 'simpleEvent') } });
|
||||
}
|
||||
@@ -149,6 +153,9 @@ export async function setEventState(ctx: Ctx, id: string, change: { published?:
|
||||
...(change.cancelled !== undefined ? { cancelled: change.cancelled } : {}),
|
||||
updatedBy: by.id,
|
||||
} });
|
||||
// In or out of the feed (ROADMAP-v3 §4: an unpublished event goes in `deleted`), and siblings told.
|
||||
if (change.published !== undefined) await markRemoved(ctx, id, !change.published);
|
||||
if (row.publishedAt || change.published) void notifyLinks(ctx, [id]).catch(() => {});
|
||||
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'event_changed', targetType: 'simple_event', targetId: id, metadata: { title: row.title, ...change } });
|
||||
}
|
||||
|
||||
@@ -156,5 +163,9 @@ export async function deleteEvent(ctx: Ctx, id: string, by: Who) {
|
||||
const row = await ctx.db.simpleEvent.findUnique({ where: { id } });
|
||||
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That event doesn\'t exist.');
|
||||
await ctx.db.simpleEvent.delete({ where: { id } });
|
||||
if (row.publishedAt) {
|
||||
await markRemoved(ctx, id, true);
|
||||
void notifyLinks(ctx, [id]).catch(() => {});
|
||||
}
|
||||
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'event_deleted', targetType: 'simple_event', targetId: id, metadata: { title: row.title } });
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ import * as content from './content.js';
|
||||
import * as people from './people.js';
|
||||
import * as happenings from './happenings.js';
|
||||
import { syncYoutube } from '../site/youtube.js';
|
||||
import { publishOn, syncLink } from '../feed/feed.js';
|
||||
import { connectTo, disconnectFrom } from '../links/connect.js';
|
||||
import { linkedProducts } from '../links/store.js';
|
||||
import { MAX_UPLOAD_BYTES, storage, upload } from './media.js';
|
||||
import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js';
|
||||
|
||||
@@ -118,6 +121,53 @@ export function adminRouter(ctx: Ctx) {
|
||||
}));
|
||||
r.delete('/events/:id', editor, handle(async (req) => { await happenings.deleteEvent(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
|
||||
|
||||
// ─── Linked products and the event feed (§8, §9) ───
|
||||
r.get('/links', handle(async () => {
|
||||
const [listed, links, publishing] = await Promise.all([linkedProducts(ctx), ctx.db.productLink.findMany(), publishOn(ctx)]);
|
||||
const counts = new Map<string, number>();
|
||||
for (const l of links) counts.set(l.installId, await ctx.db.importedEvent.count({ where: { linkId: l.installId } }));
|
||||
const ids = new Set([...listed.map((l) => l.installId), ...links.map((l) => l.installId)]);
|
||||
return {
|
||||
publishMyEvents: publishing,
|
||||
products: [...ids].map((id) => {
|
||||
const l = listed.find((x) => x.installId === id);
|
||||
const link = links.find((x) => x.installId === id);
|
||||
return {
|
||||
installId: id, product: link?.product ?? l!.product, url: link?.url ?? l!.url, connected: !!link, listed: !!l,
|
||||
showEvents: link?.showEvents ?? null, events: counts.get(id) ?? 0,
|
||||
lastSyncAt: link?.lastSyncAt?.toISOString() ?? null, lastSyncError: link?.lastSyncError ?? null,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}));
|
||||
const linkAdmin = requireRole(ctx, 'admin');
|
||||
r.post('/links/:id/connect', linkAdmin, handle(async (req) => {
|
||||
const link = await connectTo(ctx, param(req, 'id'), who(req), req);
|
||||
if (link.product !== 'accounts') await syncLink(ctx, link);
|
||||
return { ok: true };
|
||||
}));
|
||||
r.delete('/links/:id', linkAdmin, handle(async (req) => {
|
||||
const link = await ctx.db.productLink.findUnique({ where: { installId: param(req, 'id') } });
|
||||
if (link?.product === 'accounts') throw new ApiError(400, 'ACCOUNTS', 'The Website signs in through Accounts, so that link stays.');
|
||||
return disconnectFrom(ctx, param(req, 'id'), who(req), req);
|
||||
}));
|
||||
r.put('/links/:id', editor, json, handle(async (req) => {
|
||||
const id = param(req, 'id');
|
||||
const link = await ctx.db.productLink.findUnique({ where: { installId: id } });
|
||||
if (!link) throw new ApiError(404, 'NOT_LINKED', "That product isn't connected.");
|
||||
const updated = await ctx.db.productLink.update({ where: { installId: id }, data: { showEvents: !!req.body?.showEvents } });
|
||||
return syncLink(ctx, updated);
|
||||
}));
|
||||
r.post('/links/:id/sync', editor, handle(async (req) => {
|
||||
const link = await ctx.db.productLink.findUnique({ where: { installId: param(req, 'id') } });
|
||||
if (!link) throw new ApiError(404, 'NOT_LINKED', "That product isn't connected.");
|
||||
return syncLink(ctx, link);
|
||||
}));
|
||||
r.put('/feed', editor, json, handle(async (req) => {
|
||||
await ctx.settings.set('feed_publish', req.body?.publish === false ? 'false' : 'true');
|
||||
return { publishMyEvents: await publishOn(ctx) };
|
||||
}));
|
||||
|
||||
// ─── People: who can use the admin, as what (Owner and Admin) ───
|
||||
const admin = requireRole(ctx, 'admin');
|
||||
r.get('/people', admin, handle(() => people.listPeople(ctx)));
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* The event feed (WEBSITE-1.0-PLAN §8, ROADMAP-v3 §4), both ways, as Cross Events 2.4:
|
||||
*
|
||||
* - **Publish my events** (AppSetting `feed_publish`, on by default): the Website's published simple
|
||||
* events as `crosscode.event/1` at `GET /api/feed/v1/events?updatedSince=`, with removed ones in
|
||||
* `deleted` for 90 days. Only events it made itself, never ones it imported (no loops).
|
||||
* - **Show events from** each linked sibling (`ProductLink.showEvents`): fetched every 15 minutes and
|
||||
* at once on its signed `event.changed`; read-only copies, the last good copy kept when a fetch
|
||||
* fails, one bad event skipped without holding up the rest, and only events that really come
|
||||
* from that sibling.
|
||||
* - Linked siblings are told (`event.changed`) when one of the Website's events changes.
|
||||
*/
|
||||
import { EVENT_FEED_SCHEMA, EVENT_SCHEMA, eventSchema, FEED_PATHS, parseEventFeed, type CrosscodeEvent, type EventChanged, type EventFeed } from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { callSibling, siblingUrl } from '../links/http.js';
|
||||
import { imageOf } from '../site/snapshot.js';
|
||||
|
||||
const DAY = 864e5;
|
||||
export const ENDED_KEEP_DAYS = 30;
|
||||
export const REMOVED_KEEP_DAYS = 90;
|
||||
/** Fetch from a little before the last good fetch, so an event saved during it isn't missed. */
|
||||
const OVERLAP_MS = 5 * 60 * 1000;
|
||||
|
||||
export const publishOn = (ctx: Ctx) => ctx.settings.bool('feed_publish', true);
|
||||
|
||||
type SimpleRow = {
|
||||
id: string; slug: string; title: string; startsAt: Date; endsAt: Date | null; allDay: boolean; timezone: string; location: string | null;
|
||||
description: string | null; imageId: string | null; link: string | null; cancelled: boolean; updatedAt: Date;
|
||||
};
|
||||
|
||||
/** One of the Website's simple events as `crosscode.event/1`. */
|
||||
export function toCrosscodeEvent(ctx: Ctx, e: SimpleRow, installId: string, imageUrl: string | null): CrosscodeEvent {
|
||||
const url = `${ctx.config.publicUrl}/events/${e.slug}`;
|
||||
const ends = e.endsAt ?? new Date(e.startsAt.getTime() + (e.allDay ? DAY - 60e3 : 2 * 3600e3));
|
||||
return {
|
||||
schema: EVENT_SCHEMA,
|
||||
id: e.id,
|
||||
origin: { product: 'website', installId, url },
|
||||
status: e.cancelled ? 'cancelled' : 'published',
|
||||
updatedAt: e.updatedAt.toISOString(),
|
||||
title: e.title.slice(0, 200),
|
||||
summary: e.description ? e.description.replace(/\s+/g, ' ').slice(0, 300) : null,
|
||||
description: e.description,
|
||||
imageUrl,
|
||||
timezone: e.timezone,
|
||||
startsAt: e.startsAt.toISOString(),
|
||||
endsAt: ends.toISOString(),
|
||||
allDay: e.allDay,
|
||||
sessions: [],
|
||||
location: e.location ? { name: e.location.slice(0, 200), address: null, onlineUrl: null } : null,
|
||||
campus: null,
|
||||
series: null,
|
||||
tags: [],
|
||||
// Only Cross Events takes registrations: a link, or nothing (roadmap decision 4).
|
||||
registration: e.link ? { mode: 'external', url: e.link, status: 'open', opensAt: null, closesAt: null, priceFrom: null } : { mode: 'none', url: null, status: 'open', opensAt: null, closesAt: null, priceFrom: null },
|
||||
} as CrosscodeEvent;
|
||||
}
|
||||
|
||||
/** `GET /api/feed/v1/events`: what changed since `since` (everything when null). */
|
||||
export async function buildFeed(ctx: Ctx, since: Date | null): Promise<EventFeed> {
|
||||
const now = ctx.now();
|
||||
const installId = (await ctx.settings.get('hub_install_id'))!;
|
||||
const [rows, media, removals] = await Promise.all([
|
||||
ctx.db.simpleEvent.findMany({ where: { publishedAt: { not: null }, startsAt: { gte: new Date(now.getTime() - (ENDED_KEEP_DAYS + 30) * DAY) } }, orderBy: { startsAt: 'asc' } }),
|
||||
ctx.db.mediaAsset.findMany(),
|
||||
ctx.db.feedRemoval.findMany({ where: { removedAt: { gte: new Date(now.getTime() - REMOVED_KEEP_DAYS * DAY), ...(since ? { gt: since } : {}) } } }),
|
||||
]);
|
||||
const byId = new Map(media.map((m) => [m.id, m]));
|
||||
const events: CrosscodeEvent[] = [];
|
||||
for (const row of rows) {
|
||||
const ends = row.endsAt ?? row.startsAt;
|
||||
if (ends.getTime() < now.getTime() - ENDED_KEEP_DAYS * DAY) continue;
|
||||
if (since && row.updatedAt <= since) continue;
|
||||
const m = row.imageId ? byId.get(row.imageId) : null;
|
||||
const e = toCrosscodeEvent(ctx, row, installId, m ? `${ctx.config.publicUrl}${imageOf(m).url}` : null);
|
||||
// Never publish something the contract refuses.
|
||||
if (eventSchema.safeParse(e).success) events.push(e);
|
||||
}
|
||||
return { schema: EVENT_FEED_SCHEMA, generatedAt: now.toISOString(), events, deleted: removals.map((r) => ({ id: r.eventId, deletedAt: r.removedAt.toISOString() })) };
|
||||
}
|
||||
|
||||
/** A simple event left the feed: siblings drop their copy. Back on it (published again): no longer removed. */
|
||||
export async function markRemoved(ctx: Ctx, eventId: string, removed: boolean) {
|
||||
if (removed) await ctx.db.feedRemoval.upsert({ where: { eventId }, create: { eventId, removedAt: ctx.now() }, update: { removedAt: ctx.now() } });
|
||||
else await ctx.db.feedRemoval.deleteMany({ where: { eventId } });
|
||||
}
|
||||
|
||||
/** Tells every linked sibling (not Accounts) that these events changed. One try; their poll catches up. */
|
||||
export async function notifyLinks(ctx: Ctx, eventIds: string[]): Promise<{ told: number; failed: number }> {
|
||||
if (!eventIds.length || !(await publishOn(ctx))) return { told: 0, failed: 0 };
|
||||
const senderId = await ctx.settings.get('hub_install_id');
|
||||
if (!senderId) return { told: 0, failed: 0 };
|
||||
const links = await ctx.db.productLink.findMany({ where: { product: { not: 'accounts' } } });
|
||||
const body: EventChanged = { schema: EVENT_FEED_SCHEMA, type: 'event.changed', occurredAt: ctx.now().toISOString(), eventIds: eventIds.slice(0, 100) };
|
||||
const raw = JSON.stringify(body);
|
||||
let told = 0;
|
||||
let failed = 0;
|
||||
await Promise.all(links.map(async (link) => {
|
||||
try {
|
||||
const headers = signedHeaders(LINK_HEADERS, { senderId, secret: ctx.secrets.decrypt(link.secret), rawBody: raw });
|
||||
await callSibling(await siblingUrl(ctx, link.url, FEED_PATHS.changed), { method: 'POST', body: raw, headers });
|
||||
told++;
|
||||
} catch (e) {
|
||||
failed++;
|
||||
console.warn(`[feed] event.changed to ${link.url} failed (its poll will catch up):`, (e as Error).message);
|
||||
}
|
||||
}));
|
||||
return { told, failed };
|
||||
}
|
||||
|
||||
type LinkRow = { installId: string; product: string; url: string; showEvents: boolean; lastGoodAt: Date | null };
|
||||
|
||||
export type SyncResult = { installId: string; ok: boolean; imported?: number; deleted?: number; rejected?: number; error?: string };
|
||||
|
||||
/** Fetches one sibling's feed into read-only copies. */
|
||||
export async function syncLink(ctx: Ctx, link: LinkRow): Promise<SyncResult> {
|
||||
if (link.product === 'accounts') return { installId: link.installId, ok: true, imported: 0 };
|
||||
if (!link.showEvents) {
|
||||
const gone = (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId } })).count;
|
||||
return { installId: link.installId, ok: true, imported: 0, deleted: gone };
|
||||
}
|
||||
const now = ctx.now();
|
||||
const since = link.lastGoodAt ? new Date(link.lastGoodAt.getTime() - OVERLAP_MS) : null;
|
||||
try {
|
||||
const url = await siblingUrl(ctx, link.url, FEED_PATHS.events);
|
||||
if (since) url.searchParams.set('updatedSince', since.toISOString());
|
||||
const parsed = parseEventFeed(await callSibling(url, { method: 'GET' }));
|
||||
if (!parsed.ok) throw new Error(`The feed isn't a crosscode.event-feed/1 (${parsed.error.issues.slice(0, 2).map((i) => `${i.path.join('.')} ${i.message}`).join('; ')})`);
|
||||
const { feed, rejected } = parsed;
|
||||
for (const r of rejected) console.warn(`[feed] skipped an event from ${link.url} (${r.id ?? `#${r.index}`})`);
|
||||
// Only events that really come from this sibling: one product can't speak for another.
|
||||
const theirs = feed.events.filter((e) => e.origin.installId === link.installId && e.origin.product === link.product);
|
||||
for (const e of theirs) {
|
||||
const data = { linkId: link.installId, startsAt: new Date(e.startsAt), endsAt: new Date(e.endsAt), data: e as never, syncedAt: now };
|
||||
const existing = await ctx.db.importedEvent.findFirst({ where: { originProduct: e.origin.product, originId: e.id } });
|
||||
if (existing) await ctx.db.importedEvent.update({ where: { id: existing.id }, data });
|
||||
else await ctx.db.importedEvent.create({ data: { ...data, originProduct: e.origin.product, originId: e.id } });
|
||||
}
|
||||
let deleted = 0;
|
||||
for (const d of feed.deleted) deleted += (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId, originId: d.id } })).count;
|
||||
// A full fetch is the whole list: anything not in it is gone.
|
||||
if (!since) deleted += (await ctx.db.importedEvent.deleteMany({ where: { linkId: link.installId, originId: { notIn: theirs.map((e) => e.id) } } })).count;
|
||||
await ctx.db.productLink.update({
|
||||
where: { installId: link.installId },
|
||||
data: { lastSyncAt: now, lastGoodAt: new Date(feed.generatedAt), lastSyncError: rejected.length ? `${rejected.length} event(s) skipped: they don't fit crosscode.event/1` : null },
|
||||
});
|
||||
return { installId: link.installId, ok: true, imported: theirs.length, deleted, rejected: rejected.length };
|
||||
} catch (e) {
|
||||
const error = String((e as Error)?.message || e).slice(0, 500);
|
||||
await ctx.db.productLink.update({ where: { installId: link.installId }, data: { lastSyncAt: now, lastSyncError: error } }).catch(() => {});
|
||||
return { installId: link.installId, ok: false, error };
|
||||
}
|
||||
}
|
||||
|
||||
/** Every linked sibling, one after another; one failing never stops the rest. */
|
||||
export async function syncAll(ctx: Ctx) {
|
||||
const links = await ctx.db.productLink.findMany({ where: { product: { not: 'accounts' } } });
|
||||
let failed = 0;
|
||||
for (const link of links) if (!(await syncLink(ctx, link)).ok) failed++;
|
||||
return { links: links.length, failed };
|
||||
}
|
||||
|
||||
/** Every 15 minutes (ROADMAP-v3 §4: "consumers also poll every 15 minutes as a fallback"). */
|
||||
export function startFeedSync(ctx: Ctx): () => void {
|
||||
if (!ctx.config.jobsEnabled) return () => {};
|
||||
const run = () => syncAll(ctx).catch((e) => console.warn('[feed]', (e as Error).message));
|
||||
const first = setTimeout(run, 20_000);
|
||||
const timer = setInterval(run, 15 * 60 * 1000);
|
||||
first.unref?.();
|
||||
timer.unref?.();
|
||||
return () => { clearTimeout(first); clearInterval(timer); };
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import { createCtx } from './context.js';
|
||||
import { connectFromEnv, heartbeat, startHeartbeats } from './hub/client.js';
|
||||
import { loadConfig } from './lib/config.js';
|
||||
import { startYoutubeSync } from './site/youtube.js';
|
||||
import { startFeedSync } from './feed/feed.js';
|
||||
|
||||
async function main() {
|
||||
const config = loadConfig();
|
||||
@@ -23,6 +24,7 @@ async function main() {
|
||||
const server = app.listen(config.port, () => console.log(`[website] Listening on ${config.port} (${config.publicUrl}).`));
|
||||
const stopHeartbeats = startHeartbeats(ctx);
|
||||
const stopYoutube = startYoutubeSync(ctx);
|
||||
const stopFeed = startFeedSync(ctx);
|
||||
|
||||
connectFromEnv(ctx).then((r) => {
|
||||
if (r.connected || r.reason === 'already') heartbeat(ctx).catch(() => {});
|
||||
@@ -31,6 +33,7 @@ async function main() {
|
||||
const stop = async () => {
|
||||
stopHeartbeats();
|
||||
stopYoutube();
|
||||
stopFeed();
|
||||
server.close();
|
||||
await db.$disconnect();
|
||||
process.exit(0);
|
||||
|
||||
@@ -1,20 +1,30 @@
|
||||
/**
|
||||
* The link endpoints siblings call (`crosscode.link/1`): Accounts (or Events) connecting to and
|
||||
* disconnecting from this site. Errors use the link protocol's `{ code, message }`.
|
||||
* What the church's other products call (`crosscode.link/1` and friends), as Cross Events'
|
||||
* cross-product routes. Errors use the link protocol's `{ code, message }`.
|
||||
*
|
||||
* POST /links/v1/connect, /disconnect a sibling connects or disconnects
|
||||
* GET /feed/v1/events?updatedSince= the Website's events (crosscode.event-feed/1), public
|
||||
* POST /feed/v1/changed a sibling's events changed: fetch them now (signed)
|
||||
* POST /church/v1/changed Accounts: the church profile changed (signed)
|
||||
*/
|
||||
import express from 'express';
|
||||
import { LINK_PATHS } from '@crosscode/contracts';
|
||||
import { CHURCH_PATHS, churchChangedSchema, eventChangedSchema, FEED_PATHS, LINK_PATHS } from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, verify } from '@crosscode/contracts/signing';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { churchChanged } from '../church/profile.js';
|
||||
import { buildFeed, publishOn, syncLink } from '../feed/feed.js';
|
||||
import { acceptConnect, acceptDisconnect, LinkError } from './connect.js';
|
||||
|
||||
export function linksRouter(ctx: Ctx) {
|
||||
const r = express.Router();
|
||||
const json = express.json({ limit: '32kb' });
|
||||
const say = (res: express.Response, status: number, code: string, message: string) => res.status(status).json({ code, message });
|
||||
const fail = (res: express.Response, e: unknown) => {
|
||||
if (e instanceof LinkError) return res.status(e.status).json({ code: e.code, message: e.message });
|
||||
if (e instanceof LinkError) return say(res, e.status, e.code, e.message);
|
||||
console.error('[links]', e);
|
||||
return res.status(500).json({ code: 'INTERNAL', message: 'Something went wrong.' });
|
||||
return say(res, 500, 'INTERNAL', 'Something went wrong.');
|
||||
};
|
||||
|
||||
r.post(LINK_PATHS.connect.replace(/^\/api/, ''), json, async (req, res) => {
|
||||
try {
|
||||
res.json(await acceptConnect(ctx, req.body, req));
|
||||
@@ -30,5 +40,69 @@ export function linksRouter(ctx: Ctx) {
|
||||
fail(res, e);
|
||||
}
|
||||
});
|
||||
|
||||
r.get(FEED_PATHS.events.replace(/^\/api/, ''), async (req, res) => {
|
||||
try {
|
||||
if (!(await publishOn(ctx))) return say(res, 404, 'FEED_OFF', 'This site doesn\'t publish its events.');
|
||||
if (!(await ctx.settings.get('hub_install_id'))) return say(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 say(res, 400, 'INVALID_REQUEST', 'updatedSince must be an ISO 8601 date and time.');
|
||||
res.set('Cache-Control', 'no-store');
|
||||
return res.json(await buildFeed(ctx, since));
|
||||
} catch (e) {
|
||||
return fail(res, e);
|
||||
}
|
||||
});
|
||||
|
||||
/** A signed message from a linked sibling: its link, or the reason it's refused. */
|
||||
async function signedBy(req: express.Request, res: express.Response, accountsOnly = false) {
|
||||
const sender = String(req.get(LINK_HEADERS.sender) || '');
|
||||
const link = sender ? await ctx.db.productLink.findUnique({ where: { installId: sender } }) : null;
|
||||
if (!link || (accountsOnly && link.product !== 'accounts')) {
|
||||
say(res, 404, 'NOT_LINKED', 'This site has no link with that install.');
|
||||
return null;
|
||||
}
|
||||
const rawBody: Buffer = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
|
||||
const check = verify({ secret: ctx.secrets.decrypt(link.secret), timestamp: req.get(LINK_HEADERS.timestamp), signature: req.get(LINK_HEADERS.signature), rawBody, now: ctx.now() });
|
||||
if (!check.ok) {
|
||||
say(res, 401, check.code, 'The signature doesn\'t match this link.');
|
||||
return null;
|
||||
}
|
||||
let body: unknown;
|
||||
try {
|
||||
body = JSON.parse(rawBody.toString('utf8'));
|
||||
} catch {
|
||||
body = null;
|
||||
}
|
||||
return { link, body };
|
||||
}
|
||||
|
||||
const raw = express.raw({ type: () => true, limit: '16kb' });
|
||||
|
||||
r.post(FEED_PATHS.changed.replace(/^\/api/, ''), raw, async (req, res) => {
|
||||
try {
|
||||
const got = await signedBy(req, res);
|
||||
if (!got) return undefined;
|
||||
if (!eventChangedSchema.safeParse(got.body).success) return say(res, 400, 'INVALID_REQUEST', 'That isn\'t an event.changed message.');
|
||||
// Fetched after answering: the sibling doesn't wait for it.
|
||||
if (got.link.showEvents) setImmediate(() => { syncLink(ctx, got.link).catch(() => {}); });
|
||||
return res.status(202).json({ accepted: true, fetching: got.link.showEvents });
|
||||
} catch (e) {
|
||||
return fail(res, e);
|
||||
}
|
||||
});
|
||||
|
||||
r.post(CHURCH_PATHS.changed.replace(/^\/api/, ''), raw, async (req, res) => {
|
||||
try {
|
||||
const got = await signedBy(req, res, true);
|
||||
if (!got) return undefined;
|
||||
if (!churchChangedSchema.safeParse(got.body).success) return say(res, 400, 'INVALID_REQUEST', 'That isn\'t a church.changed message.');
|
||||
churchChanged(ctx);
|
||||
return res.status(202).json({ accepted: true });
|
||||
} catch (e) {
|
||||
return fail(res, e);
|
||||
}
|
||||
});
|
||||
return r;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user